diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 8f71f43f..00000000 --- a/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - diff --git a/README.md b/README.md deleted file mode 100644 index a473e94b..00000000 --- a/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# Diffusion API Examples - -This project contains example code that demonstrates the use of -the Diffusion APIs. - -Please refer to the online documentation for further details. - -[Diffusion Documentation](http://docs.pushtechnology.com/docs/latest/manual/html) - -[Diffusion Cloud Documentation](http://docs.pushtechnology.com/cloud/latest/manual/html/cloud/intro/cloud_getting_started.html) \ No newline at end of file diff --git a/android/README.md b/android/README.md deleted file mode 100644 index 61a37891..00000000 --- a/android/README.md +++ /dev/null @@ -1,20 +0,0 @@ -# Android examples for the Diffusion APIs - -This directory contains examples showing the use of the Android API -for Diffusion and Diffusion Cloud. - -The Java API examples are also relevant to Android. The Diffusion Java and -Android APIs are the same, except for a very few changes to -accommodate Android. For example, the Android time series -range query API does not use the `java.time` classes. - - -## Client library - - -You can download the Android client library from the following location: - -* [http://download.pushtechnology.com/cloud/latest/sdks.html](http://download.pushtechnology.com/cloud/latest/sdks.html#android) - -The client library is also available in the `clients` directory of the Diffusion installation. - diff --git a/android/pubsub/README.md b/android/pubsub/README.md index 7eed6638..c0a8c6fb 100644 --- a/android/pubsub/README.md +++ b/android/pubsub/README.md @@ -4,26 +4,26 @@ This is an Android application that demonstrates how to create, update, and subscribe to a Diffusion topic. - ## Building the example - You can build the example from the command line using gradle, but we recommend importing the example into Android Studio as a project. The following has been tested with Android -Studio 3.2.1. +Studio 2024.1.1 Patch 1. 1. Copy the `diffusion-android.jar` to the `app/libs` directory. -2. Start Android Studio. Use the -`File/New/Import Project...` menu option, and select the `examples\android\pubsub` directory. +2. Start Android Studio. Use the `File/New/Import Project...` menu option, +and select the `examples\android\pubsub` directory. 3. Use the `Build/Make Project` menu option. -## Running the example +## Running the example 1. Start the Diffusion server. -2. Use Android Studio (`Run/Run "app"`) to deploy the example to the Android emulator. Create a new virtual device if one doesn't already exist, using API level 19 or higher. +2. Create and/or start a virtual device, using API level 19 or higher. + +3. Use Android Studio (`Run/Run "app"`) to deploy the example to the Android emulator. -3. The example doesn't use Android UI features. To see the output, use Android Studio to examine the log. +4. Updates to the 'counter' topic will be displayed on the virtual device UI. diff --git a/android/pubsub/app/build.gradle b/android/pubsub/app/build.gradle index 0026990d..45daebd1 100644 --- a/android/pubsub/app/build.gradle +++ b/android/pubsub/app/build.gradle @@ -1,12 +1,12 @@ apply plugin: 'com.android.application' android { - compileSdkVersion 27 + compileSdkVersion 34 defaultConfig { multiDexEnabled true applicationId "com.pushtechnology.examples" minSdkVersion 19 - targetSdkVersion 27 + targetSdkVersion 34 versionCode 1 versionName "1.0" } diff --git a/android/pubsub/app/src/main/AndroidManifest.xml b/android/pubsub/app/src/main/AndroidManifest.xml index 939515da..56c589af 100644 --- a/android/pubsub/app/src/main/AndroidManifest.xml +++ b/android/pubsub/app/src/main/AndroidManifest.xml @@ -1,6 +1,5 @@ - + @@ -9,7 +8,9 @@ android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true"> - + diff --git a/android/pubsub/app/src/main/ic_launcher-playstore.png b/android/pubsub/app/src/main/ic_launcher-playstore.png new file mode 100644 index 00000000..6a87324d Binary files /dev/null and b/android/pubsub/app/src/main/ic_launcher-playstore.png differ diff --git a/android/pubsub/app/src/main/java/com/pushtechnology/diffusion/examples/PubSubExample.java b/android/pubsub/app/src/main/java/com/pushtechnology/diffusion/examples/PubSubExample.java index 2261c82e..48083362 100644 --- a/android/pubsub/app/src/main/java/com/pushtechnology/diffusion/examples/PubSubExample.java +++ b/android/pubsub/app/src/main/java/com/pushtechnology/diffusion/examples/PubSubExample.java @@ -85,7 +85,8 @@ private void startSession() { if (ex != null) { Log.e("diffusion", "Failed to connect to Diffusion server, is it running? Will retry.", ex); executor.schedule(this::startSession, 10, TimeUnit.SECONDS); - } else { + } + else { example(session); } }); @@ -120,7 +121,7 @@ private void example(Session session) { final AtomicLong i = new AtomicLong(0); // Schedule a recurring task that increments the counter and updates the topic. - executor.scheduleAtFixedRate( + executor.scheduleWithFixedDelay( () -> topics.set("counter", Long.class, i.getAndIncrement()), 1, 1, TimeUnit.SECONDS); @@ -141,7 +142,7 @@ public void onValue( runOnUiThread(new Runnable() { @Override public void run() { - TextView valueView = (TextView)findViewById(R.id.value); + final TextView valueView = (TextView)findViewById(R.id.value); valueView.setText(String.format(Locale.getDefault(), "Subscribed to 'counter' topic: %d", newValue)); } diff --git a/android/pubsub/app/src/main/res/drawable/logo.png b/android/pubsub/app/src/main/res/drawable/logo.png new file mode 100644 index 00000000..2afb2506 Binary files /dev/null and b/android/pubsub/app/src/main/res/drawable/logo.png differ diff --git a/android/pubsub/app/src/main/res/layout/activity_example.xml b/android/pubsub/app/src/main/res/layout/activity_example.xml index acf30f58..f57058c5 100644 --- a/android/pubsub/app/src/main/res/layout/activity_example.xml +++ b/android/pubsub/app/src/main/res/layout/activity_example.xml @@ -5,8 +5,20 @@ + + diff --git a/android/pubsub/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/android/pubsub/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 00000000..036d09bc --- /dev/null +++ b/android/pubsub/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/android/pubsub/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/android/pubsub/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 00000000..036d09bc --- /dev/null +++ b/android/pubsub/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/android/pubsub/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/pubsub/app/src/main/res/mipmap-hdpi/ic_launcher.png deleted file mode 100644 index b304a24d..00000000 Binary files a/android/pubsub/app/src/main/res/mipmap-hdpi/ic_launcher.png and /dev/null differ diff --git a/android/pubsub/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/android/pubsub/app/src/main/res/mipmap-hdpi/ic_launcher.webp new file mode 100644 index 00000000..cbd0f038 Binary files /dev/null and b/android/pubsub/app/src/main/res/mipmap-hdpi/ic_launcher.webp differ diff --git a/android/pubsub/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp b/android/pubsub/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp new file mode 100644 index 00000000..18b1e0be Binary files /dev/null and b/android/pubsub/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp differ diff --git a/android/pubsub/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/android/pubsub/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp new file mode 100644 index 00000000..bd443637 Binary files /dev/null and b/android/pubsub/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp differ diff --git a/android/pubsub/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/pubsub/app/src/main/res/mipmap-mdpi/ic_launcher.png deleted file mode 100644 index e26c8eca..00000000 Binary files a/android/pubsub/app/src/main/res/mipmap-mdpi/ic_launcher.png and /dev/null differ diff --git a/android/pubsub/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/android/pubsub/app/src/main/res/mipmap-mdpi/ic_launcher.webp new file mode 100644 index 00000000..c00da8a1 Binary files /dev/null and b/android/pubsub/app/src/main/res/mipmap-mdpi/ic_launcher.webp differ diff --git a/android/pubsub/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp b/android/pubsub/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp new file mode 100644 index 00000000..b315427b Binary files /dev/null and b/android/pubsub/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp differ diff --git a/android/pubsub/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/android/pubsub/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp new file mode 100644 index 00000000..7f08c2ff Binary files /dev/null and b/android/pubsub/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp differ diff --git a/android/pubsub/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/pubsub/app/src/main/res/mipmap-xhdpi/ic_launcher.png deleted file mode 100644 index 582b4d93..00000000 Binary files a/android/pubsub/app/src/main/res/mipmap-xhdpi/ic_launcher.png and /dev/null differ diff --git a/android/pubsub/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/android/pubsub/app/src/main/res/mipmap-xhdpi/ic_launcher.webp new file mode 100644 index 00000000..ec062c9c Binary files /dev/null and b/android/pubsub/app/src/main/res/mipmap-xhdpi/ic_launcher.webp differ diff --git a/android/pubsub/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp b/android/pubsub/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp new file mode 100644 index 00000000..570de4de Binary files /dev/null and b/android/pubsub/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp differ diff --git a/android/pubsub/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/android/pubsub/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp new file mode 100644 index 00000000..8f20cd13 Binary files /dev/null and b/android/pubsub/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp differ diff --git a/android/pubsub/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/pubsub/app/src/main/res/mipmap-xxhdpi/ic_launcher.png deleted file mode 100644 index 298e79c4..00000000 Binary files a/android/pubsub/app/src/main/res/mipmap-xxhdpi/ic_launcher.png and /dev/null differ diff --git a/android/pubsub/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/android/pubsub/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp new file mode 100644 index 00000000..07758d4c Binary files /dev/null and b/android/pubsub/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp differ diff --git a/android/pubsub/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp b/android/pubsub/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp new file mode 100644 index 00000000..f973fea0 Binary files /dev/null and b/android/pubsub/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp differ diff --git a/android/pubsub/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/android/pubsub/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp new file mode 100644 index 00000000..6276e969 Binary files /dev/null and b/android/pubsub/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp differ diff --git a/android/pubsub/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/pubsub/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png deleted file mode 100644 index 88af15de..00000000 Binary files a/android/pubsub/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png and /dev/null differ diff --git a/android/pubsub/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/android/pubsub/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp new file mode 100644 index 00000000..84390bbc Binary files /dev/null and b/android/pubsub/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp differ diff --git a/android/pubsub/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp b/android/pubsub/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp new file mode 100644 index 00000000..3b60f7a5 Binary files /dev/null and b/android/pubsub/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp differ diff --git a/android/pubsub/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/android/pubsub/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp new file mode 100644 index 00000000..60e3c696 Binary files /dev/null and b/android/pubsub/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp differ diff --git a/android/pubsub/app/src/main/res/values/ic_launcher_background.xml b/android/pubsub/app/src/main/res/values/ic_launcher_background.xml new file mode 100644 index 00000000..66fba34f --- /dev/null +++ b/android/pubsub/app/src/main/res/values/ic_launcher_background.xml @@ -0,0 +1,4 @@ + + + #1A0F4B + \ No newline at end of file diff --git a/android/pubsub/app/src/main/res/values/strings.xml b/android/pubsub/app/src/main/res/values/strings.xml index e1e8d954..0c8feb1d 100644 --- a/android/pubsub/app/src/main/res/values/strings.xml +++ b/android/pubsub/app/src/main/res/values/strings.xml @@ -1,3 +1,4 @@ PubSub + Diffusion logo diff --git a/android/pubsub/build.gradle b/android/pubsub/build.gradle index 50de12f1..639f7247 100644 --- a/android/pubsub/build.gradle +++ b/android/pubsub/build.gradle @@ -7,7 +7,7 @@ buildscript { jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:4.0.0' + classpath 'com.android.tools.build:gradle:8.5.2' // NOTE: Do not place your application dependencies here; they belong diff --git a/android/pubsub/gradle.properties b/android/pubsub/gradle.properties index 82618cec..bb065144 100644 --- a/android/pubsub/gradle.properties +++ b/android/pubsub/gradle.properties @@ -6,7 +6,7 @@ # http://www.gradle.org/docs/current/userguide/build_environment.html # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. -org.gradle.jvmargs=-Xmx1536m +org.gradle.jvmargs=-XX:+AlwaysPreTouch -Xms512m -Xmx512m --add-opens java.base/java.io=ALL-UNNAMED # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects diff --git a/android/pubsub/gradle/wrapper/gradle-wrapper.properties b/android/pubsub/gradle/wrapper/gradle-wrapper.properties index 9cbb443d..12a77462 100644 --- a/android/pubsub/gradle/wrapper/gradle-wrapper.properties +++ b/android/pubsub/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-all.zip diff --git a/android/pubsub/gradlew b/android/pubsub/gradlew old mode 100644 new mode 100755 diff --git a/apple/Connecting/AuthenticatedConnectionExample.m b/apple/Connecting/AuthenticatedConnectionExample.m index 69f36cd3..65c4bc60 100644 --- a/apple/Connecting/AuthenticatedConnectionExample.m +++ b/apple/Connecting/AuthenticatedConnectionExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2015 - 2022 Push Technology Ltd. +// Copyright (C) 2015 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Connecting/ConnectionExample.m b/apple/Connecting/ConnectionExample.m index 00edcf1c..0e333ad0 100644 --- a/apple/Connecting/ConnectionExample.m +++ b/apple/Connecting/ConnectionExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2015 - 2022 Push Technology Ltd. +// Copyright (C) 2015 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Connecting/CustomReconnectionStrategyExample.m b/apple/Connecting/CustomReconnectionStrategyExample.m index ee38e239..eb1043e8 100644 --- a/apple/Connecting/CustomReconnectionStrategyExample.m +++ b/apple/Connecting/CustomReconnectionStrategyExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2016 - 2022 Push Technology Ltd. +// Copyright (C) 2016 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Connecting/InitialSessionEstablishmentRetryStrategy.m b/apple/Connecting/InitialSessionEstablishmentRetryStrategy.m index 1189eade..816737a3 100644 --- a/apple/Connecting/InitialSessionEstablishmentRetryStrategy.m +++ b/apple/Connecting/InitialSessionEstablishmentRetryStrategy.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2022 Push Technology Ltd. +// Copyright (C) 2022 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Features/ClientControl/CloseSessionExample.m b/apple/Features/ClientControl/CloseSessionExample.m index fb502db8..384da93b 100644 --- a/apple/Features/ClientControl/CloseSessionExample.m +++ b/apple/Features/ClientControl/CloseSessionExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2020, 2021 Push Technology Ltd. +// Copyright (C) 2020 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Features/ClientControl/CloseSessionFilterExample.m b/apple/Features/ClientControl/CloseSessionFilterExample.m index d2400c03..80410a90 100644 --- a/apple/Features/ClientControl/CloseSessionFilterExample.m +++ b/apple/Features/ClientControl/CloseSessionFilterExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2020, 2021 Push Technology Ltd. +// Copyright (C) 2020 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Features/ClientControl/GetSessionPropertiesExample.m b/apple/Features/ClientControl/GetSessionPropertiesExample.m index 2e179845..72b02400 100644 --- a/apple/Features/ClientControl/GetSessionPropertiesExample.m +++ b/apple/Features/ClientControl/GetSessionPropertiesExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2020, 2021 Push Technology Ltd. +// Copyright (C) 2020 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Features/ClientControl/SessionPropertiesListenerExample.m b/apple/Features/ClientControl/SessionPropertiesListenerExample.m index 7f7b4bb5..ce5e07d9 100644 --- a/apple/Features/ClientControl/SessionPropertiesListenerExample.m +++ b/apple/Features/ClientControl/SessionPropertiesListenerExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2020, 2021 Push Technology Ltd. +// Copyright (C) 2020 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Features/ClientControl/SetQueueConflationExample.m b/apple/Features/ClientControl/SetQueueConflationExample.m index 3f28383d..40716f9e 100644 --- a/apple/Features/ClientControl/SetQueueConflationExample.m +++ b/apple/Features/ClientControl/SetQueueConflationExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2020, 2021 Push Technology Ltd. +// Copyright (C) 2020 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Features/ClientControl/SetQueueConflationFilterExample.m b/apple/Features/ClientControl/SetQueueConflationFilterExample.m index 4cb1c3aa..4f174b99 100644 --- a/apple/Features/ClientControl/SetQueueConflationFilterExample.m +++ b/apple/Features/ClientControl/SetQueueConflationFilterExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2020, 2021 Push Technology Ltd. +// Copyright (C) 2020 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Features/ClientControl/SetQueueEventHandlerExample.m b/apple/Features/ClientControl/SetQueueEventHandlerExample.m index 35680fb8..e98d1597 100644 --- a/apple/Features/ClientControl/SetQueueEventHandlerExample.m +++ b/apple/Features/ClientControl/SetQueueEventHandlerExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2021 Push Technology Ltd. +// Copyright (C) 2021 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Features/ClientControl/SetSessionPropertiesExample.m b/apple/Features/ClientControl/SetSessionPropertiesExample.m index bdb53710..08e46a4a 100644 --- a/apple/Features/ClientControl/SetSessionPropertiesExample.m +++ b/apple/Features/ClientControl/SetSessionPropertiesExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2020, 2021 Push Technology Ltd. +// Copyright (C) 2020 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Features/ClientControl/SetSessionPropertiesFilterExample.m b/apple/Features/ClientControl/SetSessionPropertiesFilterExample.m index cd219ef6..e45aa9b0 100644 --- a/apple/Features/ClientControl/SetSessionPropertiesFilterExample.m +++ b/apple/Features/ClientControl/SetSessionPropertiesFilterExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2020, 2021 Push Technology Ltd. +// Copyright (C) 2020 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Features/Metrics/SessionMetricCollectorExample.m b/apple/Features/Metrics/SessionMetricCollectorExample.m index e31676d6..84aa45a1 100644 --- a/apple/Features/Metrics/SessionMetricCollectorExample.m +++ b/apple/Features/Metrics/SessionMetricCollectorExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2021 Push Technology Ltd. +// Copyright (C) 2021 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Features/Metrics/TopicMetricCollectorExample.m b/apple/Features/Metrics/TopicMetricCollectorExample.m index 297cc6c7..165c3dd9 100644 --- a/apple/Features/Metrics/TopicMetricCollectorExample.m +++ b/apple/Features/Metrics/TopicMetricCollectorExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2021 - 2022 Push Technology Ltd. +// Copyright (C) 2021 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Features/RemoteServers/CheckRemoteServerExample.m b/apple/Features/RemoteServers/CheckRemoteServerExample.m index 1ece148a..447a4a17 100644 --- a/apple/Features/RemoteServers/CheckRemoteServerExample.m +++ b/apple/Features/RemoteServers/CheckRemoteServerExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2021 Push Technology Ltd. +// Copyright (C) 2021 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -54,11 +54,11 @@ -(void)startWithURL:(NSURL*)url { NSString *const serverName = @"New remote server"; - PTDiffusionRemoteServer *const remoteServer = + PTDiffusionSecondaryInitiatorRemoteServer *const remoteServer = [[[[PTDiffusionRemoteServerBuilder new] principal:remoteServerPrincipal] credentials:remoteServerCredentials] - createWithName:serverName andURL:@"ws://new.server.url.com"]; + createSecondaryInitiatorWithName:serverName andURL:@"ws://new.server.url.com"]; // creating a remote server with default Connection Options [session.remoteServers createRemoteServer:remoteServer diff --git a/apple/Features/RemoteServers/CreateRemoteServerExample.m b/apple/Features/RemoteServers/CreateRemoteServerExample.m index 7d32023d..49f6028f 100644 --- a/apple/Features/RemoteServers/CreateRemoteServerExample.m +++ b/apple/Features/RemoteServers/CreateRemoteServerExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2021 Push Technology Ltd. +// Copyright (C) 2021 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -53,11 +53,11 @@ -(void)startWithURL:(NSURL*)url { PTDiffusionCredentials *remoteServerCredentials = PTDiffusionCredentials.noCredentials; // use the builder to create the remote server object - PTDiffusionRemoteServer *const remoteServer = + PTDiffusionSecondaryInitiatorRemoteServer *const remoteServer = [[[[PTDiffusionRemoteServerBuilder new] principal:remoteServerPrincipal] credentials:remoteServerCredentials] - createWithName:@"New remote server" andURL:@"ws://new.server.url.com"]; + createSecondaryInitiatorWithName:@"New remote server" andURL:@"ws://new.server.url.com"]; // creating a remote server with default Connection Options [session.remoteServers createRemoteServer:remoteServer @@ -91,12 +91,12 @@ -(void)startWithURL:(NSURL*)url { PTDiffusionRemoteServerConnectionOption.connectionTimeout: @"15000" }; - PTDiffusionRemoteServer *const remoteServer_2 = + PTDiffusionSecondaryInitiatorRemoteServer *const remoteServer_2 = [[[[[PTDiffusionRemoteServerBuilder new] principal:remoteServerPrincipal] credentials:remoteServerCredentials] connectionOptions:connectionOptions] - createWithName:@"New remote server 2" andURL:@"ws://another.server.url.com"]; + createSecondaryInitiatorWithName:@"New remote server 2" andURL:@"ws://another.server.url.com"]; [session.remoteServers createRemoteServer:remoteServer_2 completionHandler:^(PTDiffusionCreateRemoteServerResult * _Nullable result, diff --git a/apple/Features/RemoteServers/ListRemoteServersExample.m b/apple/Features/RemoteServers/ListRemoteServersExample.m index 5e011b2b..c23fe2fb 100644 --- a/apple/Features/RemoteServers/ListRemoteServersExample.m +++ b/apple/Features/RemoteServers/ListRemoteServersExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2021 Push Technology Ltd. +// Copyright (C) 2021 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -53,11 +53,11 @@ -(void)startWithURL:(NSURL*)url { PTDiffusionCredentials *remoteServerCredentials = PTDiffusionCredentials.noCredentials; // creating a remote server with default Connection Options - PTDiffusionRemoteServer *const remoteServer = + PTDiffusionSecondaryInitiatorRemoteServer *const remoteServer = [[[[PTDiffusionRemoteServerBuilder new] principal:remoteServerPrincipal] credentials:remoteServerCredentials] - createWithName:@"New remote server" andURL:@"ws://new.server.url.com"]; + createSecondaryInitiatorWithName:@"New remote server" andURL:@"ws://new.server.url.com"]; [session.remoteServers createRemoteServer:remoteServer completionHandler:^(PTDiffusionCreateRemoteServerResult * _Nullable result, @@ -90,12 +90,12 @@ -(void)startWithURL:(NSURL*)url { PTDiffusionRemoteServerConnectionOption.connectionTimeout: @"15000" }; - PTDiffusionRemoteServer *const remoteServer_2 = + PTDiffusionSecondaryInitiatorRemoteServer *const remoteServer_2 = [[[[[PTDiffusionRemoteServerBuilder new] principal:remoteServerPrincipal] credentials:remoteServerCredentials] connectionOptions:connectionOptions] - createWithName:@"New remote server 2" andURL:@"ws://another.server.url.com"]; + createSecondaryInitiatorWithName:@"New remote server 2" andURL:@"ws://another.server.url.com"]; [session.remoteServers createRemoteServer:remoteServer_2 completionHandler:^(PTDiffusionCreateRemoteServerResult * _Nullable result, @@ -116,7 +116,26 @@ -(void)startWithURL:(NSURL*)url { NSLog(@"Available Remote Servers"); for(PTDiffusionRemoteServer *remoteServer in result) { - NSLog(@" %@: %@ (%@)", remoteServer.name, remoteServer.url, remoteServer.principal); + switch (remoteServer.type) { + case PTDiffusionRemoteServerType_PrimaryInitiator: + { + PTDiffusionPrimaryInitiatorRemoteServer *primaryInitiator = (PTDiffusionPrimaryInitiatorRemoteServer *) remoteServer; + NSLog(@" %@: %@ (%@)", primaryInitiator.name, primaryInitiator.urls, primaryInitiator.connector); + break; + } + case PTDiffusionRemoteServerType_SecondaryInitiator: + { + PTDiffusionSecondaryInitiatorRemoteServer *secondaryInitiator = (PTDiffusionSecondaryInitiatorRemoteServer *) remoteServer; + NSLog(@" %@: %@ (%@)", secondaryInitiator.name, secondaryInitiator.url, secondaryInitiator.principal); + break; + } + case PTDiffusionRemoteServerType_SecondaryAcceptor: + { + PTDiffusionSecondaryAcceptorRemoteServer *secondaryAcceptor = (PTDiffusionSecondaryAcceptorRemoteServer *) remoteServer; + NSLog(@" %@: %@ (%@)", secondaryAcceptor.name, secondaryAcceptor.primaryHostName, secondaryAcceptor.principal); + break; + } + } } }]; diff --git a/apple/Features/RemoteServers/RemoveRemoteServerExample.m b/apple/Features/RemoteServers/RemoveRemoteServerExample.m index ef04944d..cf7af40d 100644 --- a/apple/Features/RemoteServers/RemoveRemoteServerExample.m +++ b/apple/Features/RemoteServers/RemoveRemoteServerExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2021 Push Technology Ltd. +// Copyright (C) 2021 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -54,11 +54,11 @@ -(void)startWithURL:(NSURL*)url { NSString *const serverName = @"New remote server"; - PTDiffusionRemoteServer *const remoteServer = + PTDiffusionSecondaryInitiatorRemoteServer *const remoteServer = [[[[PTDiffusionRemoteServerBuilder new] principal:remoteServerPrincipal] credentials:remoteServerCredentials] - createWithName:serverName andURL:@"ws://new.server.url.com"]; + createSecondaryInitiatorWithName:serverName andURL:@"ws://new.server.url.com"]; // creating a remote server with default Connection Options [session.remoteServers createRemoteServer:remoteServer diff --git a/apple/Features/SessionTrees/SessionTreesExample.m b/apple/Features/SessionTrees/SessionTreesExample.m index 36b934d5..f5f3c001 100644 --- a/apple/Features/SessionTrees/SessionTreesExample.m +++ b/apple/Features/SessionTrees/SessionTreesExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2021 Push Technology Ltd. +// Copyright (C) 2021 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Features/TimeSeries/TimeSeriesAppendExample.m b/apple/Features/TimeSeries/TimeSeriesAppendExample.m index f85a3c3e..ba4e75ef 100644 --- a/apple/Features/TimeSeries/TimeSeriesAppendExample.m +++ b/apple/Features/TimeSeries/TimeSeriesAppendExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2020 Push Technology Ltd. +// Copyright (C) 2020 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -55,7 +55,7 @@ -(void)startWithURL:(NSURL*)url { // append value to the topic (Publisher) [self appendValue:@"hello world!" toTimeSeriesTopic:topicPath usingSession:session]; [self appendValue:@"Diffusion" toTimeSeriesTopic:topicPath usingSession:session]; - [self appendValue:@"Push Technology" toTimeSeriesTopic:topicPath usingSession:session]; + [self appendValue:@"DiffusionData" toTimeSeriesTopic:topicPath usingSession:session]; }]; } diff --git a/apple/Features/TimeSeries/TimeSeriesCreateTopicExample.m b/apple/Features/TimeSeries/TimeSeriesCreateTopicExample.m index d2c65b98..0d2847f0 100644 --- a/apple/Features/TimeSeries/TimeSeriesCreateTopicExample.m +++ b/apple/Features/TimeSeries/TimeSeriesCreateTopicExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2020 Push Technology Ltd. +// Copyright (C) 2020 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Features/TimeSeries/TimeSeriesEditExample.m b/apple/Features/TimeSeries/TimeSeriesEditExample.m index 3831188e..989b0db6 100644 --- a/apple/Features/TimeSeries/TimeSeriesEditExample.m +++ b/apple/Features/TimeSeries/TimeSeriesEditExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2020 Push Technology Ltd. +// Copyright (C) 2020 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -55,7 +55,7 @@ -(void)startWithURL:(NSURL*)url { // append value to the topic (Publisher) [self appendValue:@"hello world!" toTimeSeriesTopic:topicPath usingSession:session]; [self appendValue:@"Diffusion" toTimeSeriesTopic:topicPath usingSession:session]; - [self appendValue:@"Push Technology" toTimeSeriesTopic:topicPath usingSession:session]; + [self appendValue:@"DiffusionData" toTimeSeriesTopic:topicPath usingSession:session]; // edit first value in the topic (Publisher) [self editTimeSeriesEvent:0U diff --git a/apple/Features/TimeSeries/TimeSeriesRangeQueryExample.m b/apple/Features/TimeSeries/TimeSeriesRangeQueryExample.m index 54c17fe9..414db516 100644 --- a/apple/Features/TimeSeries/TimeSeriesRangeQueryExample.m +++ b/apple/Features/TimeSeries/TimeSeriesRangeQueryExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2020 Push Technology Ltd. +// Copyright (C) 2020 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -55,7 +55,7 @@ -(void)startWithURL:(NSURL*)url { // append value to the topic (Publisher) [self appendValue:@"hello world!" toTimeSeriesTopic:topicPath usingSession:session]; [self appendValue:@"Diffusion" toTimeSeriesTopic:topicPath usingSession:session]; - [self appendValue:@"Push Technology" toTimeSeriesTopic:topicPath usingSession:session]; + [self appendValue:@"DiffusionData" toTimeSeriesTopic:topicPath usingSession:session]; // range query to see the topic values after append [self rangeQueryValuesOfTopic:topicPath usingSession:session]; diff --git a/apple/Features/TimeSeries/TimeSeriesTimestampAppendExample.m b/apple/Features/TimeSeries/TimeSeriesTimestampAppendExample.m index 679bf95b..94b820c9 100644 --- a/apple/Features/TimeSeries/TimeSeriesTimestampAppendExample.m +++ b/apple/Features/TimeSeries/TimeSeriesTimestampAppendExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2020 Push Technology Ltd. +// Copyright (C) 2020 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -64,7 +64,7 @@ -(void)startWithURL:(NSURL*)url { [self appendValue:@"Diffusion" withDate:date2 toTimeSeriesTopic:topicPath usingSession:session]; NSDate *date3 = [dateFormatter dateFromString:@"2042-09-17 23:53:46 +0000"]; - [self appendValue:@"Push Technology" withDate:date3 toTimeSeriesTopic:topicPath usingSession:session]; + [self appendValue:@"DiffusionData" withDate:date3 toTimeSeriesTopic:topicPath usingSession:session]; }]; } diff --git a/apple/Features/TopicUpdate/UpdateStreamBuilderExample.m b/apple/Features/TopicUpdate/UpdateStreamBuilderExample.m index d50f85e1..fe7c99aa 100644 --- a/apple/Features/TopicUpdate/UpdateStreamBuilderExample.m +++ b/apple/Features/TopicUpdate/UpdateStreamBuilderExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2022 Push Technology Ltd. +// Copyright (C) 2022 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Features/TopicUpdate/UpdateStreamRecoveryExample.m b/apple/Features/TopicUpdate/UpdateStreamRecoveryExample.m new file mode 100644 index 00000000..33d7796c --- /dev/null +++ b/apple/Features/TopicUpdate/UpdateStreamRecoveryExample.m @@ -0,0 +1,93 @@ +// Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples +// +// Copyright (C) 2023 DiffusionData Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "UpdateStreamRecoveryExample.h" + +@import Diffusion; + + +@implementation UpdateStreamRecoveryExample{ + PTDiffusionSession* _session; +} + +-(void)startWithURL:(NSURL*)url { + + PTDiffusionCredentials *const credentials = + [[PTDiffusionCredentials alloc] initWithPassword:@"password"]; + + PTDiffusionSessionConfiguration *const sessionConfiguration = + [[PTDiffusionSessionConfiguration alloc] initWithPrincipal:@"admin" + credentials:credentials]; + + NSLog(@"Connecting..."); + + [PTDiffusionSession openWithURL:url + configuration:sessionConfiguration + completionHandler:^(PTDiffusionSession *const session, NSError *const error) + { + if (!session) { + NSLog(@"Failed to open session: %@", error); + return; + } + + // At this point we now have a connected session. + NSLog(@"Connected."); + + // Set ivar to maintain a strong reference to the session. + self->_session = session; + + // create an update stream builder + PTDiffusionUpdateStreamBuilder *const builder = [session.topicUpdate newUpdateStreamBuilder]; + + // create the Topic Specification and set the Update Stream Builder to it + PTDiffusionTopicSpecification * const specification = [[PTDiffusionTopicSpecification alloc] initWithType:PTDiffusionTopicType_JSON]; + [builder topicSpecification:specification]; + + // define a RetryStrategy in case the update stream needs to recover from a transient error + // 250ms interval between attempts, for a total of 10 attempts + PTDiffusionRetryStrategy *const retryStrategy = [[PTDiffusionRetryStrategy alloc] initWithInterval:250 andAttempts:10]; + + // create a Recoverable Update Stream + PTDiffusionRecoverableUpdateStream* const updateStream = + [builder recoverableJsonUpdateStreamWithPath:@"a/b/c" retryStrategy:retryStrategy]; + + // define a completion handler for processing the asynchronous response + __weak PTDiffusionRecoverableUpdateStream* const weakUpdateStream = updateStream; + + PTDiffusionUpdateStreamHandlerBlock completionHandler = ^ + (PTDiffusionTopicCreationResult * _Nullable result, NSError * _Nullable error) + { + PTDiffusionRecoverableUpdateStream* const strongUpdateStream = weakUpdateStream; + if (error != nil) { + if ([PTDiffusionRecoverableUpdateStream isErrorRecoverable:error]) { + NSLog(@"Transient error detected, attempting to recover"); + [strongUpdateStream recover:nil]; + } + else { + NSLog(@"Unrecoverable error detected: %@", error); + } + } + else { + NSLog(@"Topic has been updated!"); + } + }; + + // use the update stream to create and set the topic value + PTDiffusionJSON *value = [[PTDiffusionJSON alloc] initWithJSONString:@"{\"hello\": \"world\"}" error:nil]; + [updateStream setValue:value completionHandler:completionHandler error:nil]; + }]; +} + +@end diff --git a/apple/Features/TopicViews/TopicViewsCreateExample.m b/apple/Features/TopicViews/TopicViewsCreateExample.m index b08d74ca..4884118f 100644 --- a/apple/Features/TopicViews/TopicViewsCreateExample.m +++ b/apple/Features/TopicViews/TopicViewsCreateExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2020 Push Technology Ltd. +// Copyright (C) 2020 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Features/TopicViews/TopicViewsGetExample.m b/apple/Features/TopicViews/TopicViewsGetExample.m index 0ba37e2f..f4f1e334 100644 --- a/apple/Features/TopicViews/TopicViewsGetExample.m +++ b/apple/Features/TopicViews/TopicViewsGetExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2021 Push Technology Ltd. +// Copyright (C) 2021 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Features/TopicViews/TopicViewsListExample.m b/apple/Features/TopicViews/TopicViewsListExample.m index 147c10e6..14acd0a3 100644 --- a/apple/Features/TopicViews/TopicViewsListExample.m +++ b/apple/Features/TopicViews/TopicViewsListExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2020 Push Technology Ltd. +// Copyright (C) 2020 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Features/TopicViews/TopicViewsRemoveExample.m b/apple/Features/TopicViews/TopicViewsRemoveExample.m index 06aa99af..cc7f2f8c 100644 --- a/apple/Features/TopicViews/TopicViewsRemoveExample.m +++ b/apple/Features/TopicViews/TopicViewsRemoveExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2020 Push Technology Ltd. +// Copyright (C) 2020 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/FetchExample.m b/apple/FetchExample.m index f5e53a91..51a47703 100644 --- a/apple/FetchExample.m +++ b/apple/FetchExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2015, 2018 Push Technology Ltd. +// Copyright (C) 2015 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/MessagingRequestResponseExample.m b/apple/MessagingRequestResponseExample.m index 31ea5420..33a3a33a 100644 --- a/apple/MessagingRequestResponseExample.m +++ b/apple/MessagingRequestResponseExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2020 Push Technology Ltd. +// Copyright (C) 2020 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/MissingTopicHandlerExample.m b/apple/MissingTopicHandlerExample.m index 3da18bd1..07b474a2 100644 --- a/apple/MissingTopicHandlerExample.m +++ b/apple/MissingTopicHandlerExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2016, 2021 Push Technology Ltd. +// Copyright (C) 2016 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/PingExample.m b/apple/PingExample.m index f15dd807..69a1a79f 100644 --- a/apple/PingExample.m +++ b/apple/PingExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2015, 2020 Push Technology Ltd. +// Copyright (C) 2015 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Publish/AddTopicExample.m b/apple/Publish/AddTopicExample.m index 4a8f684c..cc92f63f 100644 --- a/apple/Publish/AddTopicExample.m +++ b/apple/Publish/AddTopicExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2016 - 2022 Push Technology Ltd. +// Copyright (C) 2016 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Publish/CreatingRecordV2SchemaExample.m b/apple/Publish/CreatingRecordV2SchemaExample.m index a52aa80d..9dac7e4e 100644 --- a/apple/Publish/CreatingRecordV2SchemaExample.m +++ b/apple/Publish/CreatingRecordV2SchemaExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2017 - 2022 Push Technology Ltd. +// Copyright (C) 2017 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Publish/JSONUpdateExample.m b/apple/Publish/JSONUpdateExample.m index 15723b77..794f41d8 100644 --- a/apple/Publish/JSONUpdateExample.m +++ b/apple/Publish/JSONUpdateExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2016 - 2022 Push Technology Ltd. +// Copyright (C) 2016 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Publish/RemoveTopicExample.m b/apple/Publish/RemoveTopicExample.m index 323fbfa7..f1dca520 100644 --- a/apple/Publish/RemoveTopicExample.m +++ b/apple/Publish/RemoveTopicExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2016 - 2022 Push Technology Ltd. +// Copyright (C) 2016 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Subscribe/ConsumingRecordV2TopicsExample.swift b/apple/Subscribe/ConsumingRecordV2TopicsExample.swift index ab4ed6f1..8ad8f704 100644 --- a/apple/Subscribe/ConsumingRecordV2TopicsExample.swift +++ b/apple/Subscribe/ConsumingRecordV2TopicsExample.swift @@ -91,7 +91,7 @@ public class ClientConsumingRecordV2Topics { let topics = session.topics let topicSelector = "?" + rootTopic + "//" do { - try topics.add(valueStream, withSelectorExpression: topicSelector, error:()) + try topics.add(valueStream, withSelectorExpression: topicSelector) } catch { print("Error while adding stream with selector expression") diff --git a/apple/Subscribe/CounterSubscribeExample.m b/apple/Subscribe/CounterSubscribeExample.m index 7bcd95f0..f03883e1 100644 --- a/apple/Subscribe/CounterSubscribeExample.m +++ b/apple/Subscribe/CounterSubscribeExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2015 - 2022 Push Technology Ltd. +// Copyright (C) 2015 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Subscribe/JSONSubscribeExample.m b/apple/Subscribe/JSONSubscribeExample.m index f255021f..cbffe5f7 100644 --- a/apple/Subscribe/JSONSubscribeExample.m +++ b/apple/Subscribe/JSONSubscribeExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2016 - 2022 Push Technology Ltd. +// Copyright (C) 2016 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Subscribe/SubscribeUnsubscribeExample.m b/apple/Subscribe/SubscribeUnsubscribeExample.m index 48ff03fa..e8f47d22 100644 --- a/apple/Subscribe/SubscribeUnsubscribeExample.m +++ b/apple/Subscribe/SubscribeUnsubscribeExample.m @@ -1,6 +1,6 @@ // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2015 - 2022 Push Technology Ltd. +// Copyright (C) 2015 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Utils/QueueEventListener.h b/apple/Utils/QueueEventListener.h index 74662250..4da25389 100644 --- a/apple/Utils/QueueEventListener.h +++ b/apple/Utils/QueueEventListener.h @@ -1,7 +1,7 @@ // // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2021 Push Technology Ltd. +// Copyright (C) 2021 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/apple/Utils/QueueEventListener.m b/apple/Utils/QueueEventListener.m index 76d44eb5..7b0c7059 100644 --- a/apple/Utils/QueueEventListener.m +++ b/apple/Utils/QueueEventListener.m @@ -1,7 +1,7 @@ // // Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // -// Copyright (C) 2021 Push Technology Ltd. +// Copyright (C) 2021 - 2023 DiffusionData Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/c/CMakeLists.txt b/c/CMakeLists.txt new file mode 100644 index 00000000..8cf6e101 --- /dev/null +++ b/c/CMakeLists.txt @@ -0,0 +1,68 @@ +cmake_minimum_required(VERSION 3.16) + +project(diffusion_sdk_c_examples) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_BUILD_TYPE "Release") +set(CMAKE_OSX_ARCHITECTURES "${ARCHITECTURE}") + +cmake_path(SET DEPENDENCIES_FOLDER ${CMAKE_CURRENT_SOURCE_DIR}/dependencies) +cmake_path(SET CMAKE_SCRIPTS_FOLDER ${CMAKE_CURRENT_SOURCE_DIR}/cmake) +cmake_path(SET EXAMPLES_SOURCE_FOLDER ${CMAKE_CURRENT_SOURCE_DIR}/examples) +cmake_path(SET RESOURCES_SOURCE_FOLDER ${CMAKE_CURRENT_SOURCE_DIR}/resources) +cmake_path(SET UTILS_SOURCE_FOLDER ${EXAMPLES_SOURCE_FOLDER}/utils) + +cmake_path(SET CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${TARGET}/lib/${ARCHITECTURE}) +cmake_path(SET CMAKE_LIBRARY_OUTPUT_DIRECTORY ${TARGET}/bin/${ARCHITECTURE}) +cmake_path(SET CMAKE_RUNTIME_OUTPUT_DIRECTORY ${TARGET}/bin/${ARCHITECTURE}) + + +# ============================================================================= +# Debug + +add_compile_options(-fsanitize=undefined -fsanitize=address) +add_link_options(-fsanitize=undefined -fsanitize=address) + + +# ============================================================================= +# Dependencies + +list(APPEND CMAKE_MODULE_PATH "${CMAKE_SCRIPTS_FOLDER}") +set(INCLUDE_DIRECTORIES "") +set(ADDITIONAL_LD_FLAGS "") + +# PThread +set(THREADS_PREFER_PTHREAD_FLAG ON) +find_package(Threads) + +# APR +cmake_path(SET APR_ROOT_PATH ${DEPENDENCIES_FOLDER}/${OPERATING_SYSTEM}/apr) +include(${CMAKE_SCRIPTS_FOLDER}/APR.cmake) + +# Diffusion - C SDK +cmake_path(SET DIFFUSION_ROOT_FOLDER ${TARGET}/client) +include(${CMAKE_SCRIPTS_FOLDER}/Diffusion.cmake) + +# PCRE +include(${CMAKE_SCRIPTS_FOLDER}/PCRE.cmake) + +# ZLib +include(${CMAKE_SCRIPTS_FOLDER}/ZLib.cmake) + +# Operating System dependencies +include(${CMAKE_SCRIPTS_FOLDER}/OperatingSystem.cmake) + + +# ============================================================================= +# Examples Support +set(INCLUDE_DIRECTORIES ${INCLUDE_DIRECTORIES} ${UTILS_SOURCE_FOLDER}) + + +# ============================================================================= +# Examples +include(${EXAMPLES_SOURCE_FOLDER}/examples.cmake) + + + + diff --git a/c/Makefile b/c/Makefile deleted file mode 100644 index fde19270..00000000 --- a/c/Makefile +++ /dev/null @@ -1,288 +0,0 @@ -# The following two variables must be set. -# -# Directory containing the C client include files. -# DIFFUSION_C_CLIENT_INCDIR = -# -# Directory containing libdiffusion.a -# DIFFUSION_C_CLIENT_LIBDIR = -# -# Directory containing the various external Diffusion dependencies -# DIFFUSION_C_CLIENT_DEPENDENCIES_DIR = -# -# Directory that will contain the executables and generated objects -# TARGET_FOLDER = - -ifndef DIFFUSION_C_CLIENT_INCDIR -$(error DIFFUSION_C_CLIENT_INCDIR is not set) -endif - -ifndef DIFFUSION_C_CLIENT_LIBDIR -$(error DIFFUSION_C_CLIENT_LIBDIR is not set) -endif - -ifndef TARGET_FOLDER -$(error TARGET_FOLDER is not set) -endif - -# Extra definitions from current directory, if they exist. --include makefile.defs - -CFLAGS += $(INCLUDES) \ - -g -std=c99 -D_POSIX_C_SOURCE=200112L -D_XOPEN_SOURCE=700 \ - -Wall -Werror -Wno-error=deprecated-declarations \ - -I$(DIFFUSION_C_CLIENT_INCDIR) - -LDFLAGS += -lpthread -lpcre -lcurl -lz \ - $(DIFFUSION_C_CLIENT_LIBDIR)/$(ARCH)/libdiffusion.a \ - $(LIBS) - -# Detect the platform the Diffusion Client will be running on -PLATFORM = $(shell uname -s | tr '[A-Z]' '[a-z]' | sed -e 's/darwin/osx/') - -ifeq ($(PLATFORM),osx) - CC = clang -else - # If not MacOS, add '-lrt' to the linker flags - CC = gcc - LDFLAGS += -lrt -endif - -ARFLAGS += -SOURCES = connect-async.c \ - connect.c \ - reconnect.c \ - session-factory.c \ - features/authentication_control/auth-service.c \ - features/client-control-change-roles-with-filter.c \ - features/client-control-change-roles-with-session.c \ - features/client-control-close-with-filter.c \ - features/client-control-close-with-session.c \ - features/client_control/get-session-properties.c \ - features/client_control/session-properties-listener.c \ - features/messaging/send-request-to-filter.c \ - features/messaging/send-request-to-path.c \ - features/messaging/send-request-to-session.c \ - features/metrics/session-metric-collector.c \ - features/metrics/topic-metric-collector.c \ - features/remote_servers/remote-servers.c \ - features/security/change-principal.c \ - features/session_trees/session-trees.c \ - features/subscription_control/subscription-control.c \ - features/system_authentication_control/system-auth-control.c \ - features/time_series/time-series-timestamp-append.c \ - features/time_series/time-series-range-query.c \ - features/time_series/time-series-append.c \ - features/time_series/time-series-edit.c \ - features/topic_control/missing-topic-notification.c \ - features/topic_control/add-topics.c \ - features/topic_update/update-record.c \ - features/topic_update/topic-update.c \ - features/topic_update/topic-update-stream.c \ - features/topic_update/topic-update-with-constraint.c \ - features/topic_update/topic-update-add-and-set.c \ - features/topic_views/topic-views.c \ - features/topic_views/topic-views-get.c \ - features/topic_views/topic-views-remove.c \ - features/topic_views/topic-views-list.c \ - features/topics/subscribe.c \ - features/topics/subscribe-multiple.c \ - features/topics/recordv2-topics.c \ - features/topics/string-topics.c \ - features/topics/double-topics.c \ - features/topics/fetch-request.c \ - features/topics/int64-topics.c \ - features/topics/binary-topics.c - -OBJ_DIR = $(TARGET_FOLDER)/objs/$(ARCH) -BIN_DIR = $(TARGET_FOLDER)/bin/$(ARCH) -OBJECTS = $(SOURCES:.c=.o) - -TARGETS = connect-async \ - connect \ - reconnect \ - session-factory \ - authentication_control \ - client-control-change-roles-with-filter \ - client-control-change-roles-with-session \ - client-control-close-with-filter \ - client-control-close-with-session \ - client-control-get-session-properties \ - client-control-session-properties-listener \ - messaging-send-request-to-filter \ - messaging-send-request-to-path \ - messaging-send-request-to-session \ - metrics-session-metric-collector \ - metrics-topic-metric-collector \ - remote-servers \ - session-trees \ - security-change-principal \ - subscription-control \ - system-authentication-control \ - time-series-timestamp-append \ - time-series-range-query \ - time-series-append \ - time-series-edit \ - topic-control-missing-topic-notification \ - topic-control-add-topics \ - topic-update-record \ - topic-update \ - topic-update-stream \ - topic-update-with-constraint \ - topic-update-add-and-set \ - topic-views \ - topic-views-get \ - topic-views-remove \ - topic-views-list \ - topics-subscribe \ - topics-subscribe-multiple \ - topics-recordv2 \ - topics-string \ - topics-double \ - topics-fetch \ - topics-int64 \ - topics-binary - -.PHONY: all - -all: prepare $(TARGETS) - -prepare: - mkdir -p $(OBJ_DIR) $(BIN_DIR) - -$(OBJ_DIR)/%.o: %.c - $(CC) $(CFLAGS) -c -o $@ $< - -connect-async: $(OBJ_DIR)/connect-async.o - $(CC) $< $(LDFLAGS) -o $(BIN_DIR)/$@ - -connect: $(OBJ_DIR)/connect.o - $(CC) $< $(LDFLAGS) -o $(BIN_DIR)/$@ - -reconnect: $(OBJ_DIR)/reconnect.o - $(CC) $< $(LDFLAGS) -o $(BIN_DIR)/$@ - -session-factory: $(OBJ_DIR)/session-factory.o - $(CC) $< $(LDFLAGS) -o $(BIN_DIR)/$@ - -authentication_control: features/authentication_control/auth-service.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -client-control-change-roles-with-filter: features/client_control/change-roles-with-filter.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -client-control-change-roles-with-session: features/client_control/change-roles-with-session.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -client-control-close-with-filter: features/client_control/close-with-filter.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -client-control-close-with-session: features/client_control/close-with-session.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -client-control-get-session-properties: features/client_control/get-session-properties.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -client-control-session-properties-listener: features/client_control/session-properties-listener.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -messaging-send-request-to-filter: features/messaging/send-request-to-filter.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -messaging-send-request-to-path: features/messaging/send-request-to-path.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -messaging-send-request-to-session: features/messaging/send-request-to-session.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -metrics-session-metric-collector: features/metrics/session-metric-collector.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -metrics-topic-metric-collector: features/metrics/topic-metric-collector.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -remote-servers: features/remote_servers/remote-servers.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -session-trees: features/session_trees/session-trees.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -security-change-principal: features/security/change-principal.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -subscription-control: features/subscription_control/subscription-control.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -system-authentication-control: features/system_authentication_control/system-auth-control.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -time-series-timestamp-append: features/time_series/time-series-timestamp-append.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -time-series-range-query: features/time_series/time-series-range-query.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -time-series-append: features/time_series/time-series-append.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -time-series-edit: features/time_series/time-series-edit.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -topic-control-missing-topic-notification: features/topic_control/missing-topic-notification.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -topic-control-add-topics: features/topic_control/add-topics.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -topic-update-record: features/topic_update/update-record.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -topic-update: features/topic_update/topic-update.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -topic-update-stream: features/topic_update/topic-update-stream.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -topic-update-with-constraint: features/topic_update/topic-update-with-constraint.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -topic-update-add-and-set: features/topic_update/topic-update-add-and-set.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -topic-views: features/topic_views/topic-views.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -topic-views-get: features/topic_views/topic-views-get.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -topic-views-remove: features/topic_views/topic-views-remove.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -topic-views-list: features/topic_views/topic-views-list.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -topics-subscribe: features/topics/subscribe.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -topics-subscribe-multiple: features/topics/subscribe-multiple.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -topics-recordv2: features/topics/recordv2-topics.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -topics-string: features/topics/string-topics.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -topics-double: features/topics/double-topics.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -topics-fetch: features/topics/fetch-request.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -topics-int64: features/topics/int64-topics.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -topics-binary: features/topics/binary-topics.c - $(CC) $^ $(CFLAGS) $(LDFLAGS) -lm -o $(BIN_DIR)/$@ - -clean: - rm -rf $(TARGETS) $(OBJECTS) $(TARGET_FOLDER) core a.out diff --git a/c/README.md b/c/README.md index d185c384..1c153581 100644 --- a/c/README.md +++ b/c/README.md @@ -1,42 +1,34 @@ -# C Examples for the Diffusion APIs -This directory contains examples showing the use of the C API for Diffusion and Diffusion Cloud. + -To use these examples, download the C client library for your operating system from the links below. -The C API is available for the following operating systems: +

-* 64-bit Linux as a statically or dynamically linked library -* 32-bit and 64-bit Windows as a statically linked library -* 64-bit OS X as a statically linked library +

-## Client libraries +## Diffusion SDK Examples - C -You can download the C client libraries from the following locations: -* Download from [our website](http://download.pushtechnology.com/cloud/latest/sdks.html#c) +### Pre-requirements -* The client libraries are also available in the `clients` directory of the Diffusion server installation. +- [CMake](https://cmake.org/) (version 3.16+) +- ZLib library +- PCRE library -## Dependencies +### Folder Structure -The C client requires the following dependencies: +1. Create a folder named `target` at the same level as this README.md +2. Create a folder named `client` in `target` containing the `include` and `lib` folders of the Diffusion C SDK you wish to use. -* [Perl Compatible Regular Expressions (PCRE)](http://pcre.org) library, version 8.3 -* [OpenSSL](https://www.openssl.org) library, version 1.0.2a -For Linux or OS X, you can download them through your operating system's package manager. -For Windows™, Push Technology provides custom builds of these libraries built with the same compiler and on the same architecture as the C client libraries. +### Build process +Run the following command at this folder level: -## Running the examples +```bash +cmake --fresh . +cmake --build . +``` -1. Install the required dependencies on your development system. -2. Get the C client library zip for your platform and extract it. -3. Uncomment the variables at the top of the `Makefile` in the examples directory. Set these variables to the location of the extracted Diffusion C client library: - - DIFFUSION_C_CLIENT_INCDIR = /include - DIFFUSION_C_CLIENT_LIBDIR = /lib - -4. Run the `make` command in the examples directory. \ No newline at end of file +This will created an executable in `target/bin` for each example. diff --git a/c/build.ps1 b/c/build.ps1 new file mode 100644 index 00000000..52f92b1f --- /dev/null +++ b/c/build.ps1 @@ -0,0 +1,17 @@ + +$SourceDir = $PSScriptRoot +$TargetDir = "$SourceDir\target" + +function build($architecture) { + + $cmakeDir = "$TargetDir\cmake-$architecture" + + Write-Output "[$architecture] Configuring" + & cmake "-S $SourceDir" "-A Win32" "-B $cmakeDir" "-D ARCHITECTURE=$architecture" "-D TARGET=$TargetDir" "-D OPERATING_SYSTEM=windows" + + Write-Output "[$architecture] Building" + & cmake --build "$cmakeDir" --config "Release" +} + +build "x86" +build "x64" diff --git a/c/build.sh b/c/build.sh new file mode 100644 index 00000000..5d075ccb --- /dev/null +++ b/c/build.sh @@ -0,0 +1,89 @@ +#!/bin/bash + +ROOT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) +SOURCE_DIR="$ROOT_DIR" +TARGET_DIR="$ROOT_DIR/target" + + +if [ ! -d $TARGET_DIR ]; then + echo "Creating folder $TARGET_DIR" + mkdir -p $TARGET_DIR +fi + + +function build_linux() { + build_for_unix "x86_64" "linux" false +} + + +function build_macos() { + build_for_unix "x86_64" "macos" true + build_for_unix "arm64" "macos" true +} + + +function build_for_unix() { + local architecture=$1 + local operating_system=$2 + local is_macos=$3 + local cmake_dir="$TARGET_DIR/cmake-$operating_system-$architecture" + echo "About to run cmake for $operating_system / $architecture" + echo "Build directory: $cmake_dir" + + # Define reusable build steps + build_commands() { + set -e + echo "Running cmake for $operating_system / $architecture" + echo "Build directory: $cmake_dir" + echo "---" + set -x + + if $is_macos ; then + if [[ "$architecture" == "x86_64" ]]; then + homebrew_root_path="/usr/local" + + + elif [[ "$architecture" == "arm64" ]]; then + homebrew_root_path="/opt/homebrew" + fi + + eval "${homebrew_root_path}/bin/brew shellenv" + else + homebrew_root_path="" + fi + + cmake --fresh \ + -S"$SOURCE_DIR" \ + -B"$cmake_dir" \ + -DTARGET="$TARGET_DIR" \ + -DOPERATING_SYSTEM="$operating_system" \ + -DARCHITECTURE="$architecture" \ + -DARCHFLAGS="-arch ${architecture}" \ + -DCMAKE_OSX_ARCHITECTURES="${architecture}" \ + -DHOMEBREW_ROOT_PATH="${homebrew_root_path}" + + cmake --build "$cmake_dir" + set +x + } + + if $is_macos; then + export SOURCE_DIR TARGET_DIR cmake_dir operating_system architecture is_macos + + # Pass function definition and invoke it inside the new shell + set -x + arch "-$architecture" /bin/zsh --login -c "$(declare -f build_commands); source ~/.zshrc && source ~/.profile && source ~/.zprofile && set -a; SOURCE_DIR=${SOURCE_DIR}; is_macos=${is_macos}; TARGET_DIR=${TARGET_DIR}; cmake_dir=${cmake_dir}; operating_system=${operating_system}; architecture=${architecture}; build_commands" || exit 1 + set +x + else + build_commands + fi + +} + + +case "$OSTYPE" in + solaris*) build_linux ;; + darwin*) build_macos ;; + linux*) build_linux ;; + bsd*) build_linux ;; + *) echo "unknown: $OSTYPE"; exit 1 ;; +esac diff --git a/c/cmake/APR.cmake b/c/cmake/APR.cmake new file mode 100644 index 00000000..c81374a6 --- /dev/null +++ b/c/cmake/APR.cmake @@ -0,0 +1,51 @@ +add_library(apr STATIC IMPORTED) +add_library(apr-util STATIC IMPORTED) + +if(WIN32) + cmake_path(SET APR_PATH ${APR_ROOT_PATH}/${ARCHITECTURE}) + cmake_path(SET APR_LIB_PATH ${APR_PATH}/lib/apr.lib) + cmake_path(SET APR_UTIL_LIB_PATH ${APR_PATH}/lib/aprutil.lib) + cmake_path(SET APR_INCLUDE_PATH ${APR_PATH}/include) + + set_target_properties(apr PROPERTIES + IMPORTED_IMPLIB ${APR_LIB_PATH} + IMPORTED_LOCATION ${APR_LIB_PATH} + INTERFACE_INCLUDE_DIRECTORIES ${APR_INCLUDE_PATH} + ) + + set_target_properties(apr-util PROPERTIES + IMPORTED_IMPLIB ${APR_UTIL_LIB_PATH} + IMPORTED_LOCATION ${APR_UTIL_LIB_PATH} + INTERFACE_INCLUDE_DIRECTORIES ${APR_INCLUDE_PATH} + ) + +elseif(UNIX) + cmake_path(SET APR_LIB_PATH ${APR_ROOT_PATH}/lib/${ARCHITECTURE}/libapr.a) + cmake_path(SET APR_UTIL_LIB_PATH ${APR_ROOT_PATH}/lib/${ARCHITECTURE}/libaprutil.a) + cmake_path(SET APR_INCLUDE_PATH ${APR_ROOT_PATH}/include) + + set_target_properties(apr PROPERTIES + IMPORTED_IMPLIB ${APR_LIB_PATH} + IMPORTED_LOCATION ${APR_LIB_PATH} + INTERFACE_INCLUDE_DIRECTORIES ${APR_INCLUDE_PATH} + ) + + set_target_properties(apr-util PROPERTIES + IMPORTED_IMPLIB ${APR_UTIL_LIB_PATH} + IMPORTED_LOCATION ${APR_UTIL_LIB_PATH} + INTERFACE_INCLUDE_DIRECTORIES ${APR_INCLUDE_PATH} + ) +endif() + +get_target_property(apr_INCLUDE_DIRECTORIES apr INTERFACE_INCLUDE_DIRECTORIES) + +set(INCLUDE_DIRECTORIES ${INCLUDE_DIRECTORIES} ${apr_INCLUDE_DIRECTORIES}) + +set(DEPENDENCIES ${DEPENDENCIES} apr apr-util) + +# list(APPEND WINDOWS_PATH ${APR_LIB_PATH} ${APR_UTIL_LIB_PATH}) + +message(STATUS "") +message(STATUS "APR has been imported from ${APR_ROOT_PATH}") +message(STATUS " - ${apr_INCLUDE_DIRECTORIES}") +message(STATUS "") diff --git a/c/cmake/CMocka.cmake b/c/cmake/CMocka.cmake new file mode 100644 index 00000000..ee84986d --- /dev/null +++ b/c/cmake/CMocka.cmake @@ -0,0 +1,50 @@ +add_library(cmocka-static STATIC IMPORTED) + +if(WIN32) + if(CMAKE_SIZEOF_VOID_P MATCHES 8) + set(ARCHITECTURE "x64") + elseif(CMAKE_SIZEOF_VOID_P MATCHES 4) + set(ARCHITECTURE "x86") + endif() + + cmake_path(SET CMOCKA_PATH ${CMOCKA_ROOT_PATH}/${ARCHITECTURE}) + cmake_path(SET CMOCKA_LIB_PATH ${CMOCKA_PATH}/lib/cmocka.lib) + cmake_path(SET CMOCKA_BIN_PATH ${CMOCKA_PATH}/bin) + cmake_path(SET CMOCKA_DLL_PATH ${CMOCKA_BIN_PATH}/cmocka.dll) + cmake_path(SET CMOCKA_INCLUDE_PATH ${CMOCKA_PATH}/include) + + set_target_properties(cmocka-static PROPERTIES + IMPORTED_IMPLIB ${CMOCKA_LIB_PATH} + IMPORTED_LOCATION ${CMOCKA_LIB_PATH} + INTERFACE_INCLUDE_DIRECTORIES ${CMOCKA_INCLUDE_PATH} + ) + + # Cmocka is a dynamic library: the .lib looks internally for the .dll + # Link the executable to the folder that contains the DLL for cmocka + set(TEST_WORKING_DIRECTORY ${CMOCKA_BIN_PATH}) + +elseif(UNIX) + cmake_path(SET CMOCKA_LIB_PATH ${CMOCKA_ROOT_PATH}/lib/${ARCHITECTURE}/libcmocka.a) + cmake_path(SET CMOCKA_INCLUDE_PATH ${CMOCKA_ROOT_PATH}/include) + + set_target_properties(cmocka-static PROPERTIES + IMPORTED_IMPLIB ${CMOCKA_LIB_PATH} + IMPORTED_LOCATION ${CMOCKA_LIB_PATH} + INTERFACE_INCLUDE_DIRECTORIES ${CMOCKA_INCLUDE_PATH} + ) + + set(TEST_WORKING_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) +endif() + +get_target_property(cmocka_INCLUDE_DIRECTORIES cmocka-static INTERFACE_INCLUDE_DIRECTORIES) + +set(INCLUDE_DIRECTORIES ${INCLUDE_DIRECTORIES} ${cmocka_INCLUDE_DIRECTORIES}) + +set(DEPENDENCIES ${DEPENDENCIES} cmocka-static) + +list(APPEND WINDOWS_PATH ${CMOCKA_DLL_PATH}) + +message(STATUS "") +message(STATUS "CMocka has been imported from ${CMOCKA_ROOT_PATH}") +message(STATUS " - ${cmocka_INCLUDE_DIRECTORIES}") +message(STATUS "") diff --git a/c/cmake/Diffusion.cmake b/c/cmake/Diffusion.cmake new file mode 100644 index 00000000..992164f3 --- /dev/null +++ b/c/cmake/Diffusion.cmake @@ -0,0 +1,43 @@ +add_library(diffusion SHARED IMPORTED) + +cmake_path(SET DIFFUSION_INCLUDE_PATH ${DIFFUSION_ROOT_FOLDER}/include) + +if(WIN32) + # Windows (32-bit or 64-bit) + if(CMAKE_SIZEOF_VOID_P MATCHES 8) + set(ARCHITECTURE "x64") + elseif(CMAKE_SIZEOF_VOID_P MATCHES 4) + set(ARCHITECTURE "x86") + endif() + + cmake_path(SET DIFFUSION_LIB_PATH ${DIFFUSION_ROOT_FOLDER}/lib/${ARCHITECTURE}/uci.lib) + + set_target_properties(diffusion PROPERTIES + IMPORTED_IMPLIB ${DIFFUSION_LIB_PATH} + IMPORTED_LOCATION ${DIFFUSION_LIB_PATH} + INTERFACE_INCLUDE_DIRECTORIES ${DIFFUSION_INCLUDE_PATH} + ) + +elseif(UNIX) + # Unix (MacOS or Linux) + cmake_path(SET DIFFUSION_LIB_PATH ${DIFFUSION_ROOT_FOLDER}/lib/${ARCHITECTURE}/libdiffusion.a) + + set_target_properties(diffusion PROPERTIES + IMPORTED_LOCATION ${DIFFUSION_LIB_PATH} + INTERFACE_INCLUDE_DIRECTORIES ${DIFFUSION_INCLUDE_PATH} + ) +endif() + +get_target_property(diffusion_INCLUDE_DIRECTORIES diffusion INTERFACE_INCLUDE_DIRECTORIES) + +set(INCLUDE_DIRECTORIES ${INCLUDE_DIRECTORIES} ${diffusion_INCLUDE_DIRECTORIES}) + +set(DEPENDENCIES ${DEPENDENCIES} diffusion) + +# list(APPEND WINDOWS_PATH ${DIFFUSION_LIB_PATH}) + +message(STATUS "") +message(STATUS "Diffusion has been imported from ${DIFFUSION_ROOT_FOLDER}") +message(STATUS " - ${diffusion_INCLUDE_DIRECTORIES}") +message(STATUS "") + diff --git a/c/cmake/OperatingSystem.cmake b/c/cmake/OperatingSystem.cmake new file mode 100644 index 00000000..1d761a86 --- /dev/null +++ b/c/cmake/OperatingSystem.cmake @@ -0,0 +1,5 @@ +if(WIN32) + set(DEPENDENCIES ${DEPENDENCIES} wsock32 ws2_32 Rpcrt4.lib) +else() + set(ADDITIONAL_LD_FLAGS ${ADDITIONAL_LD_FLAGS} "-ldl") +endif() diff --git a/c/cmake/PCRE.cmake b/c/cmake/PCRE.cmake new file mode 100644 index 00000000..e5b9dec6 --- /dev/null +++ b/c/cmake/PCRE.cmake @@ -0,0 +1,110 @@ +if(WIN32) + # Windows (32-bit or 64-bit) + add_library(pcre SHARED IMPORTED) + add_library(pcre_posix SHARED IMPORTED) + + if(CMAKE_SIZEOF_VOID_P MATCHES 8) + set(ARCHITECTURE "x64") + elseif(CMAKE_SIZEOF_VOID_P MATCHES 4) + set(ARCHITECTURE "x86") + endif() + + cmake_path(SET PCRE_ROOT_PATH ${DIFFUSION_ROOT_FOLDER}/dependencies/pcre/${ARCHITECTURE}) + cmake_path(SET PCRE_LIB_PATH ${PCRE_ROOT_PATH}/lib/pcre3.lib) + cmake_path(SET PCRE_POSIX_LIB_PATH ${PCRE_ROOT_PATH}/lib/pcreposix3.lib) + cmake_path(SET PCRE_INCLUDE_PATH ${PCRE_ROOT_PATH}/include) + cmake_path(SET PCRE_BIN_PATH ${PCRE_ROOT_PATH}/bin) + cmake_path(SET PCRE_DLL_PATH ${PCRE_BIN_PATH}/pcre3.dll) + cmake_path(SET PCRE_POSIX_DLL_PATH ${PCRE_BIN_PATH}/pcreposix3.dll) + + set_target_properties(pcre PROPERTIES + IMPORTED_IMPLIB ${PCRE_LIB_PATH} + IMPORTED_LOCATION ${PCRE_LIB_PATH} + INTERFACE_INCLUDE_DIRECTORIES ${PCRE_INCLUDE_PATH} + ) + + set_target_properties(pcre_posix PROPERTIES + IMPORTED_IMPLIB ${PCRE_POSIX_LIB_PATH} + IMPORTED_LOCATION ${PCRE_POSIX_LIB_PATH} + INTERFACE_INCLUDE_DIRECTORIES ${PCRE_INCLUDE_PATH} + ) + + get_target_property(pcre_INTERFACE_INCLUDE_DIRECTORIES pcre INTERFACE_INCLUDE_DIRECTORIES) + get_target_property(pcre_posix_INTERFACE_INCLUDE_DIRECTORIES pcre_posix INTERFACE_INCLUDE_DIRECTORIES) + + set(INCLUDE_DIRECTORIES ${INCLUDE_DIRECTORIES} ${pcre_INTERFACE_INCLUDE_DIRECTORIES}) + set(INCLUDE_DIRECTORIES ${INCLUDE_DIRECTORIES} ${pcre_posix_INTERFACE_INCLUDE_DIRECTORIES}) + + set(DEPENDENCIES ${DEPENDENCIES} pcre pcre_posix) + + list(APPEND WINDOWS_PATH ${PCRE_DLL_PATH} ${PCRE_POSIX_DLL_PATH}) + + message(STATUS "") + message(STATUS "PCRE has been imported from ${PCRE_ROOT_PATH}") + message(STATUS " - ${pcre_INTERFACE_INCLUDE_DIRECTORIES}") + message(STATUS " - ${pcre_posix_INTERFACE_INCLUDE_DIRECTORIES}") + message(STATUS "") + +elseif(UNIX) + # Unix (MacOS or Linux) + + if (CMAKE_HOST_SYSTEM_NAME MATCHES "Darwin") + # MacOS + message(STATUS "HOMEBREW_ROOT_PATH is ${HOMEBREW_ROOT_PATH}") + + execute_process( + COMMAND ${HOMEBREW_ROOT_PATH}/bin/brew --prefix pcre + RESULT_VARIABLE BREW_PCRE + OUTPUT_VARIABLE BREW_PCRE_PREFIX + OUTPUT_STRIP_TRAILING_WHITESPACE + ) + + if (BREW_PCRE EQUAL 0 AND EXISTS "${BREW_PCRE_PREFIX}") + message(STATUS "Found PCRE installed by Homebrew at ${BREW_PCRE_PREFIX}") + + add_library(pcre SHARED IMPORTED) + add_library(pcre_posix SHARED IMPORTED) + + cmake_path(SET PCRE_LIB_PATH ${BREW_PCRE_PREFIX}/lib/libpcre.a) + cmake_path(SET PCRE_POSIX_LIB_PATH ${BREW_PCRE_PREFIX}/lib/libpcreposix.a) + cmake_path(SET PCRE_INCLUDE_PATH ${BREW_PCRE_PREFIX}/include) + + set_target_properties(pcre PROPERTIES + IMPORTED_IMPLIB ${PCRE_LIB_PATH} + IMPORTED_LOCATION ${PCRE_LIB_PATH} + INTERFACE_INCLUDE_DIRECTORIES ${PCRE_INCLUDE_PATH} + ) + + set_target_properties(pcre_posix PROPERTIES + IMPORTED_IMPLIB ${PCRE_POSIX_LIB_PATH} + IMPORTED_LOCATION ${PCRE_POSIX_LIB_PATH} + INTERFACE_INCLUDE_DIRECTORIES ${PCRE_INCLUDE_PATH} + ) + + get_target_property(pcre_INTERFACE_INCLUDE_DIRECTORIES pcre INTERFACE_INCLUDE_DIRECTORIES) + get_target_property(pcre_posix_INTERFACE_INCLUDE_DIRECTORIES pcre_posix INTERFACE_INCLUDE_DIRECTORIES) + + set(INCLUDE_DIRECTORIES ${INCLUDE_DIRECTORIES} ${pcre_INTERFACE_INCLUDE_DIRECTORIES}) + set(INCLUDE_DIRECTORIES ${INCLUDE_DIRECTORIES} ${pcre_posix_INTERFACE_INCLUDE_DIRECTORIES}) + + set(DEPENDENCIES ${DEPENDENCIES} pcre pcre_posix) + + message(STATUS "") + message(STATUS "PCRE has been imported from ${BREW_PCRE_PREFIX} for architecture ${ARCHITECTURE}") + message(STATUS " - ${pcre_INTERFACE_INCLUDE_DIRECTORIES}") + message(STATUS " - ${pcre_posix_INTERFACE_INCLUDE_DIRECTORIES}") + message(STATUS "") + + else() + message(STATUS "Unable to find PCRE in this machine for architecture ${ARCHITECTURE}") + + endif() + + else() + # Linux + set(ADDITIONAL_LD_FLAGS ${ADDITIONAL_LD_FLAGS} "-lpcre") + + endif() + +endif() + diff --git a/c/cmake/ZLib.cmake b/c/cmake/ZLib.cmake new file mode 100644 index 00000000..f7708d52 --- /dev/null +++ b/c/cmake/ZLib.cmake @@ -0,0 +1,88 @@ +if(WIN32) + # Windows (32-bit or 64-bit) + add_library(zlib SHARED IMPORTED) + + if(CMAKE_SIZEOF_VOID_P MATCHES 8) + set(ARCHITECTURE "x64") + elseif(CMAKE_SIZEOF_VOID_P MATCHES 4) + set(ARCHITECTURE "x86") + endif() + + cmake_path(SET ZLIB_ROOT_PATH ${DIFFUSION_ROOT_FOLDER}/dependencies/zlib/${ARCHITECTURE}) + cmake_path(SET ZLIB_LIB_PATH ${ZLIB_ROOT_PATH}/lib/zlib.lib) + cmake_path(SET ZLIB_INCLUDE_PATH ${ZLIB_ROOT_PATH}/include) + + set_target_properties(zlib PROPERTIES + IMPORTED_IMPLIB ${ZLIB_LIB_PATH} + IMPORTED_LOCATION ${ZLIB_LIB_PATH} + INTERFACE_INCLUDE_DIRECTORIES ${ZLIB_INCLUDE_PATH} + ) + + get_target_property(zlib_INCLUDE_DIRECTORIES zlib INTERFACE_INCLUDE_DIRECTORIES) + + set(INCLUDE_DIRECTORIES ${INCLUDE_DIRECTORIES} ${zlib_INCLUDE_DIRECTORIES}) + + set(DEPENDENCIES ${DEPENDENCIES} zlib) + + # list(APPEND WINDOWS_PATH ${ZLIB_LIB_PATH}) + + include_directories(${zlib_INCLUDE_DIRECTORIES}) + + message(STATUS "") + message(STATUS "ZLIB has been imported from ${ZLIB_ROOT_PATH}") + message(STATUS " - ${zlib_INCLUDE_DIRECTORIES}") + message(STATUS "") + +elseif(UNIX) + # Unix (MacOS or Linux) + + if (CMAKE_HOST_SYSTEM_NAME MATCHES "Darwin") + # MacOS + message(STATUS "HOMEBREW_ROOT_PATH is ${HOMEBREW_ROOT_PATH}") + + execute_process( + COMMAND ${HOMEBREW_ROOT_PATH}/bin/brew --prefix zlib + RESULT_VARIABLE BREW_ZLIB + OUTPUT_VARIABLE BREW_ZLIB_PREFIX + OUTPUT_STRIP_TRAILING_WHITESPACE + ) + + if (BREW_ZLIB EQUAL 0 AND EXISTS "${BREW_ZLIB_PREFIX}") + message(STATUS "Found ZLIB installed by Homebrew at ${BREW_ZLIB_PREFIX}") + + add_library(zlib SHARED IMPORTED) + + cmake_path(SET ZLIB_LIB_PATH ${BREW_ZLIB_PREFIX}/lib/libz.a) + cmake_path(SET ZLIB_INCLUDE_PATH ${BREW_ZLIB_PREFIX}/include) + + set_target_properties(zlib PROPERTIES + IMPORTED_IMPLIB ${ZLIB_LIB_PATH} + IMPORTED_LOCATION ${ZLIB_LIB_PATH} + INTERFACE_INCLUDE_DIRECTORIES ${ZLIB_INCLUDE_PATH} + ) + + get_target_property(zlib_INTERFACE_INCLUDE_DIRECTORIES zlib INTERFACE_INCLUDE_DIRECTORIES) + + set(INCLUDE_DIRECTORIES ${INCLUDE_DIRECTORIES} ${zlib_INTERFACE_INCLUDE_DIRECTORIES}) + + set(DEPENDENCIES ${DEPENDENCIES} zlib) + + message(STATUS "") + message(STATUS "ZLIB has been imported from ${BREW_ZLIB_PREFIX} for architecture ${ARCHITECTURE}") + message(STATUS " - ${zlib_INTERFACE_INCLUDE_DIRECTORIES}") + message(STATUS "") + + else() + message(STATUS "Unable to find ZLIB in this machine for architecture ${ARCHITECTURE}") + + endif() + + else() + # Linux + set(ADDITIONAL_LD_FLAGS ${ADDITIONAL_LD_FLAGS} "-lz") + + endif() + + +endif() + diff --git a/c/connect-async.c b/c/connect-async.c deleted file mode 100644 index 23760788..00000000 --- a/c/connect-async.c +++ /dev/null @@ -1,157 +0,0 @@ -/** - * Copyright © 2014 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 5.0 - */ - -/* - * This examples shows how to make an asynchronous connection to Diffusion. - */ -#include -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "client"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - END_OF_ARG_OPTS -}; - -SESSION_T *g_session = NULL; - -/* - * This callback is used when the session state changes, e.g. when a session - * moves from a "connecting" to a "connected" state, or from "connected" to - * "closed". - */ -static void on_session_state_changed( - SESSION_T *session, - const SESSION_STATE_T old_state, - const SESSION_STATE_T new_state) -{ - printf("Session state changed from %s (%d) to %s (%d)\n", - session_state_as_string(old_state), old_state, - session_state_as_string(new_state), new_state); -} - -/* - * This is the callback that is invoked if the client can successfully - * connect to Diffusion, and a session instance is ready for use. - */ -static int on_connected(SESSION_T *session) -{ - char *sid = session_id_to_string(session->id); - printf("on_connected(), state=%d, session id=%s\n", - session_state_get(session), - sid); - free(sid); - - g_session = session; - return HANDLER_SUCCESS; -} - -/* - * This is the callback that is invoked if there is an error connection - * to the Diffusion instance. - */ -static int on_error(SESSION_T *session, DIFFUSION_ERROR_T *error) -{ - g_session = session; - - char *sid = session_id_to_string(session->id); - printf("on_error(), session_id=%s, error=%s\n", - sid, - error->message); - free(sid); - return HANDLER_SUCCESS; -} - -/* - * Entry point for the example. - */ -int main(int argc, char **argv) -{ - /* - * Standard command-line parsing. - */ - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - CREDENTIALS_T *credentials = NULL; - const char *password = hash_get(options, "credentials"); - if(password != NULL) { - credentials = credentials_create_password(password); - } - - DIFFUSION_ERROR_T error = { 0 }; - SESSION_LISTENER_T session_listener = { 0 }; - session_listener.on_state_changed = &on_session_state_changed; - - /* - * Asynchronous connections have callbacks for notifying that - * a connection has been made, or that an error occurred. - */ - SESSION_CREATE_CALLBACK_T *callbacks = calloc(1, sizeof(SESSION_CREATE_CALLBACK_T)); - callbacks->on_connected = &on_connected; - callbacks->on_error = &on_error; - - RECONNECTION_STRATEGY_T reconnection_strategy = { - .retry_count = 3, - .retry_delay = 1000 - }; - - /* - * Although we're connecting asynchronously, we are using a - * mutex and a condition variable to signal when a - * session_create_async callback has been invoked, and we can - * then close & free the session. - */ - session_create_async(url, principal, credentials, &session_listener, &reconnection_strategy, callbacks, &error); - - // sleep for 10 seconds - sleep(10); - - /* - * Close/free session (if we have one) and release resources - * and memory. - */ - if(g_session != NULL) { - session_close(g_session, NULL); - session_free(g_session); - } - credentials_free(credentials); - hash_free(options, NULL, free); - free(callbacks); - - return EXIT_SUCCESS; -} diff --git a/c/connect-with-user-context.c b/c/connect-with-user-context.c deleted file mode 100644 index 49bae63d..00000000 --- a/c/connect-with-user-context.c +++ /dev/null @@ -1,161 +0,0 @@ -/** - * Copyright © 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.9 - */ - -/* - * This example shows how to make a synchronous connection to Diffusion, passing a user_context to it. - */ -#include -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "client"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - {'d', "delay", "Delay between reconnection attempts, in ms", ARG_OPTIONAL, ARG_HAS_VALUE, "2000" }, - {'r', "retries", "Reconnection retry attempts", ARG_OPTIONAL, ARG_HAS_VALUE, "5" }, - {'t', "timeout", "Reconnection timeout for a disconnected session", ARG_OPTIONAL, ARG_HAS_VALUE, NULL }, - {'s', "sleep", "Time to sleep before disconnecting (in seconds).", ARG_OPTIONAL, ARG_HAS_VALUE, "5" }, - END_OF_ARG_OPTS -}; - -/* - * This callback is used when the session state changes, e.g. when a session - * moves from a "connecting" to a "connected" state, or from "connected" to - * "closed". - */ -static void on_session_state_changed( - SESSION_T *session, - const SESSION_STATE_T old_state, - const SESSION_STATE_T new_state) -{ - printf("Session state changed from %s (%d) to %s (%d)\n", - session_state_as_string(old_state), old_state, - session_state_as_string(new_state), new_state); - - printf("The user context for the session is: %s\n", session->user_context); -} - -/* - * Entry point for the example. - */ -int main(int argc, char **argv) -{ - /* - * Standard command-line parsing. - */ - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - CREDENTIALS_T *credentials = NULL; - const char *password = hash_get(options, "credentials"); - if(password != NULL) { - credentials = credentials_create_password(password); - } - - long retry_delay = atol(hash_get(options, "delay")); - long retry_count = atol(hash_get(options, "retries")); - long reconnect_timeout; - if(hash_get(options, "timeout") != NULL) { - reconnect_timeout = atol(hash_get(options, "timeout")); - } - else { - reconnect_timeout = -1; - } - - const unsigned int sleep_time = atol(hash_get(options, "sleep")); - - SESSION_T *session; - DIFFUSION_ERROR_T error = { 0 }; - - SESSION_LISTENER_T session_listener = { 0 }; - session_listener.on_state_changed = &on_session_state_changed; - - /* - * Specify how we might want to failover or retry, and - * how long to keep the session alive on the server before - * it's discarded. - */ - RECONNECTION_STRATEGY_T *reconnection_strategy = - make_reconnection_strategy_repeating_attempt(retry_count, retry_delay); - - if(reconnect_timeout > 0) { - reconnection_strategy_set_timeout(reconnection_strategy, reconnect_timeout); - } - - /* - * Set the user context for the session. - * This can be of any type. - */ - char *user_context = "This is the user context for the session to be created."; - - /* - * Create a session, synchronously. - */ - session = session_create_with_user_context( - url, - principal, - credentials, - &session_listener, - reconnection_strategy, - user_context, - &error); - if(session != NULL) { - char *sid_str = session_id_to_string(session->id); - printf("Session created (state=%d, id=%s)\n", session_state_get(session), sid_str); - free(sid_str); - } - else { - printf("Failed to create session: %s\n", error.message); - free(error.message); - } - - /* - * Sleep for a while. - */ - sleep(sleep_time); - - /* - * Close the session, and release resources and memory. - */ - session_close(session, NULL); - session_free(session); - - credentials_free(credentials); - hash_free(options, NULL, free); - free_reconnection_strategy(reconnection_strategy); - - return EXIT_SUCCESS; -} diff --git a/c/connect.c b/c/connect.c deleted file mode 100644 index 234c92b0..00000000 --- a/c/connect.c +++ /dev/null @@ -1,155 +0,0 @@ -/** - * Copyright © 2014 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 5.0 - */ - -/* - * This example shows how to make a synchronous connection to Diffusion. - */ -#include -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "client"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - {'d', "delay", "Delay between reconnection attempts, in ms", ARG_OPTIONAL, ARG_HAS_VALUE, "2000" }, - {'r', "retries", "Reconnection retry attempts", ARG_OPTIONAL, ARG_HAS_VALUE, "5" }, - {'t', "timeout", "Reconnection timeout for a disconnected session", ARG_OPTIONAL, ARG_HAS_VALUE, NULL }, - {'s', "sleep", "Time to sleep before disconnecting (in seconds).", ARG_OPTIONAL, ARG_HAS_VALUE, "5" }, - END_OF_ARG_OPTS -}; - - -/* - * This callback is used when the session state changes, e.g. when a session - * moves from a "connecting" to a "connected" state, or from "connected" to - * "closed". - */ -static void on_session_state_changed( - SESSION_T *session, - const SESSION_STATE_T old_state, - const SESSION_STATE_T new_state) -{ - printf("Session state changed from %s (%d) to %s (%d)\n", - session_state_as_string(old_state), old_state, - session_state_as_string(new_state), new_state); -} - - -/* - * Entry point for the example. - */ -int main(int argc, char **argv) -{ - /* - * Standard command-line parsing. - */ - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - CREDENTIALS_T *credentials = NULL; - const char *password = hash_get(options, "credentials"); - if(password != NULL) { - credentials = credentials_create_password(password); - } - - long retry_delay = atol(hash_get(options, "delay")); - long retry_count = atol(hash_get(options, "retries")); - long reconnect_timeout; - if(hash_get(options, "timeout") != NULL) { - reconnect_timeout = atol(hash_get(options, "timeout")); - } - else { - reconnect_timeout = -1; - } - - const unsigned int sleep_time = atol(hash_get(options, "sleep")); - - SESSION_T *session; - DIFFUSION_ERROR_T error = { 0 }; - - SESSION_LISTENER_T session_listener = { 0 }; - session_listener.on_state_changed = &on_session_state_changed; - - /* - * Specify how we might want to failover or retry, and - * how long to keep the session alive on the server before - * it's discarded. - */ - RECONNECTION_STRATEGY_T *reconnection_strategy = - make_reconnection_strategy_repeating_attempt(retry_count, retry_delay); - - if(reconnect_timeout > 0) { - reconnection_strategy_set_timeout(reconnection_strategy, reconnect_timeout); - } - - /* - * Create a session, synchronously. - */ - session = session_create( - url, - principal, - credentials, - &session_listener, - reconnection_strategy, - &error); - if(session != NULL) { - char *sid_str = session_id_to_string(session->id); - printf("Session created (state=%d, id=%s)\n", session_state_get(session), sid_str); - free(sid_str); - } - else { - printf("Failed to create session: %s\n", error.message); - free(error.message); - } - - /* - * Sleep for a while. - */ - sleep(sleep_time); - - /* - * Close the session, and release resources and memory. - */ - session_close(session, NULL); - session_free(session); - - credentials_free(credentials); - hash_free(options, NULL, free); - free_reconnection_strategy(reconnection_strategy); - - return EXIT_SUCCESS; -} diff --git a/c/dependencies/linux/apr/include/apr.h b/c/dependencies/linux/apr/include/apr.h new file mode 100644 index 00000000..3f08694d --- /dev/null +++ b/c/dependencies/linux/apr/include/apr.h @@ -0,0 +1,656 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef APR_H +#define APR_H + +/* GENERATED FILE WARNING! DO NOT EDIT apr.h + * + * You must modify apr.h.in instead. + * + * And please, make an effort to stub apr.hw and apr.hnw in the process. + */ + +/** + * @file apr.h + * @brief APR Platform Definitions + * @remark This is a generated header generated from include/apr.h.in by + * ./configure, or copied from include/apr.hw or include/apr.hnw + * for Win32 or Netware by those build environments, respectively. + */ + +/** + * @defgroup APR Apache Portability Runtime library + * @{ + */ +/** + * @defgroup apr_platform Platform Definitions + * @{ + * @warning + * The actual values of macros and typedefs on this page
+ * are platform specific and should NOT be relied upon!
+ */ + +/* So that we can use inline on some critical functions, and use + * GNUC attributes (such as to get -Wall warnings for printf-like + * functions). Only do this in gcc 2.7 or later ... it may work + * on earlier stuff, but why chance it. + * + * We've since discovered that the gcc shipped with NeXT systems + * as "cc" is completely broken. It claims to be __GNUC__ and so + * on, but it doesn't implement half of the things that __GNUC__ + * means. In particular it's missing inline and the __attribute__ + * stuff. So we hack around it. PR#1613. -djg + */ +#if !defined(__GNUC__) || __GNUC__ < 2 || \ + (__GNUC__ == 2 && __GNUC_MINOR__ < 7) ||\ + defined(NEXT) +#ifndef __attribute__ +#define __attribute__(__x) +#endif +#define APR_INLINE +#define APR_HAS_INLINE 0 +#else +#define APR_INLINE __inline__ +#define APR_HAS_INLINE 1 +#endif + +#define APR_HAVE_ARPA_INET_H 1 +#define APR_HAVE_CONIO_H 0 +#define APR_HAVE_CRYPT_H 1 +#define APR_HAVE_CTYPE_H 1 +#define APR_HAVE_DIRENT_H 1 +#define APR_HAVE_ERRNO_H 1 +#define APR_HAVE_FCNTL_H 1 +#define APR_HAVE_IO_H 0 +#define APR_HAVE_LIMITS_H 1 +#define APR_HAVE_NETDB_H 1 +#define APR_HAVE_NETINET_IN_H 1 +#define APR_HAVE_NETINET_SCTP_H 1 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 1 +#define APR_HAVE_PROCESS_H 0 +#define APR_HAVE_PTHREAD_H 1 +#define APR_HAVE_SEMAPHORE_H 1 +#define APR_HAVE_SIGNAL_H 1 +#define APR_HAVE_STDARG_H 1 +#define APR_HAVE_STDINT_H 1 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 1 +#define APR_HAVE_INTTYPES_H 1 +#define APR_HAVE_SYS_IOCTL_H 1 +#define APR_HAVE_SYS_SENDFILE_H 1 +#define APR_HAVE_SYS_SIGNAL_H 1 +#define APR_HAVE_SYS_SOCKET_H 1 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#define APR_HAVE_SYS_TIME_H 1 +#define APR_HAVE_SYS_TYPES_H 1 +#define APR_HAVE_SYS_UIO_H 1 +#define APR_HAVE_SYS_UN_H 1 +#define APR_HAVE_SYS_WAIT_H 1 +#define APR_HAVE_TIME_H 1 +#define APR_HAVE_UNISTD_H 1 +#define APR_HAVE_WINDOWS_H 0 +#define APR_HAVE_WINSOCK2_H 0 + +/** @} */ +/** @} */ + +/* We don't include our conditional headers within the doxyblocks + * or the extern "C" namespace + */ + +#if APR_HAVE_WINDOWS_H && defined(WIN32) +/* If windows.h was already included, our preferences don't matter. + * If not, include a restricted set of windows headers to our tastes. + */ +#ifndef _WINDOWS_ + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif + +#ifndef _WIN32_WINNT +/* Restrict the server to a subset of Windows XP header files by default + */ +#define _WIN32_WINNT 0x0501 +#endif + +#ifndef NOUSER +#define NOUSER +#endif +#ifndef NOMCX +#define NOMCX +#endif +#ifndef NOIME +#define NOIME +#endif + +#include +/* + * Add a _very_few_ declarations missing from the restricted set of headers + * (If this list becomes extensive, re-enable the required headers above!) + * winsock headers were excluded by WIN32_LEAN_AND_MEAN, so include them now + */ +#define SW_HIDE 0 +#ifndef _WIN32_WCE +#include +#include +#include +#else +#include +#endif + +#endif /* ndef _WINDOWS_ */ +#endif /* APR_HAVE_WINDOWS_H */ + +#if APR_HAVE_SYS_TYPES_H +#include +#endif + +#if APR_HAVE_SYS_SOCKET_H +#include +#endif + +#if APR_HAVE_STDINT_H +#ifdef __cplusplus +/* C99 7.18.4 requires that stdint.h only exposes INT64_C + * and UINT64_C for C++ implementations if this is defined: */ +#ifndef __STDC_CONSTANT_MACROS +#define __STDC_CONSTANT_MACROS +#endif +/* C++ needs this too for PRI*NN formats: */ +#ifndef __STDC_FORMAT_MACROS +#define __STDC_FORMAT_MACROS +#endif +#endif /* __cplusplus */ +#include +#endif + +#if APR_HAVE_INTTYPES_H +#include +#endif + +#if APR_HAVE_SYS_WAIT_H +#include +#endif + +#ifdef OS2 +#define INCL_DOS +#define INCL_DOSERRORS +#include +#endif + +/* header files for PATH_MAX, _POSIX_PATH_MAX */ +#if APR_HAVE_LIMITS_H +#include +#else +#if APR_HAVE_SYS_SYSLIMITS_H +#include +#endif +#endif + +/* __APPLE__ is now the official pre-defined macro for macOS */ +#ifdef __APPLE__ +#undef DARWIN +#undef DARWIN_10 +#define DARWIN +#define DARWIN_10 +#endif /* __APPLE__ */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @addtogroup apr_platform + * @ingroup APR + * @{ + */ + +#define APR_HAVE_SHMEM_MMAP_TMP 1 +#define APR_HAVE_SHMEM_MMAP_SHM 1 +#define APR_HAVE_SHMEM_MMAP_ZERO 1 +#define APR_HAVE_SHMEM_SHMGET_ANON 1 +#define APR_HAVE_SHMEM_SHMGET 1 +#define APR_HAVE_SHMEM_MMAP_ANON 1 +#define APR_HAVE_SHMEM_BEOS 0 + +#define APR_USE_SHMEM_MMAP_TMP 0 +#define APR_USE_SHMEM_MMAP_SHM 0 +#define APR_USE_SHMEM_MMAP_ZERO 0 +#define APR_USE_SHMEM_SHMGET_ANON 0 +#define APR_USE_SHMEM_SHMGET 1 +#define APR_USE_SHMEM_MMAP_ANON 1 +#define APR_USE_SHMEM_BEOS 0 + +#define APR_USE_FLOCK_SERIALIZE 0 +#define APR_USE_SYSVSEM_SERIALIZE 0 +#define APR_USE_POSIXSEM_SERIALIZE 0 +#define APR_USE_FCNTL_SERIALIZE 0 +#define APR_USE_PROC_PTHREAD_SERIALIZE 1 +#define APR_USE_PTHREAD_SERIALIZE 1 + +#define APR_HAS_FLOCK_SERIALIZE 1 +#define APR_HAS_SYSVSEM_SERIALIZE 1 +#define APR_HAS_POSIXSEM_SERIALIZE 1 +#define APR_HAS_FCNTL_SERIALIZE 1 +#define APR_HAS_PROC_PTHREAD_SERIALIZE 1 + +#define APR_PROCESS_LOCK_IS_GLOBAL 0 + +#define APR_HAVE_CORKABLE_TCP 1 +#define APR_HAVE_GETRLIMIT 1 +#define APR_HAVE_IN_ADDR 1 +#define APR_HAVE_INET_ADDR 1 +#define APR_HAVE_INET_NETWORK 1 +#define APR_HAVE_IPV6 1 +#define APR_HAVE_SOCKADDR_UN 1 +#define APR_HAVE_MEMMOVE 1 +#define APR_HAVE_SETRLIMIT 1 +#define APR_HAVE_SIGACTION 1 +#define APR_HAVE_SIGSUSPEND 1 +#define APR_HAVE_SIGWAIT 1 +#define APR_HAVE_SA_STORAGE 1 +#define APR_HAVE_STRCASECMP 1 +#define APR_HAVE_STRDUP 1 +#define APR_HAVE_STRICMP 0 +#define APR_HAVE_STRNCASECMP 1 +#define APR_HAVE_STRNICMP 0 +#define APR_HAVE_STRSTR 1 +#define APR_HAVE_MEMCHR 1 +#define APR_HAVE_STRUCT_RLIMIT 1 +#define APR_HAVE_UNION_SEMUN 0 +#define APR_HAVE_SCTP 1 +#define APR_HAVE_IOVEC 1 + +/* APR Feature Macros */ +#define APR_HAS_SHARED_MEMORY 1 +#define APR_HAS_THREADS 1 +#define APR_HAS_SENDFILE 1 +#define APR_HAS_MMAP 1 +#define APR_HAS_FORK 1 +#define APR_HAS_RANDOM 1 +#define APR_HAS_OTHER_CHILD 1 +#define APR_HAS_DSO 1 +#define APR_HAS_SO_ACCEPTFILTER 0 +#define APR_HAS_UNICODE_FS 0 +#define APR_HAS_PROC_INVOKED 0 +#define APR_HAS_USER 1 +#define APR_HAS_LARGE_FILES 0 +#define APR_HAS_XTHREAD_FILES 0 +#define APR_HAS_OS_UUID 1 +#define APR_HAS_TIMEDLOCKS 1 + +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 0 + +/* APR sets APR_FILES_AS_SOCKETS to 1 on systems where it is possible + * to poll on files/pipes. + */ +#define APR_FILES_AS_SOCKETS 1 + +/* This macro indicates whether or not EBCDIC is the native character set. + */ +#define APR_CHARSET_EBCDIC 0 + +/* If we have a TCP implementation that can be "corked", what flag + * do we use? + */ +#define APR_TCP_NOPUSH_FLAG TCP_CORK + +/* Is the TCP_NODELAY socket option inherited from listening sockets? +*/ +#define APR_TCP_NODELAY_INHERITED 1 + +/* Is the O_NONBLOCK flag inherited from listening sockets? +*/ +#define APR_O_NONBLOCK_INHERITED 0 + +/* Typedefs that APR needs. */ + +typedef unsigned char apr_byte_t; + +typedef short apr_int16_t; +typedef unsigned short apr_uint16_t; + +typedef int apr_int32_t; +typedef unsigned int apr_uint32_t; + +#define APR_SIZEOF_VOIDP 8 + +/* + * Darwin 10's default compiler (gcc42) builds for both 64 and + * 32 bit architectures unless specifically told not to. + * In those cases, we need to override types depending on how + * we're being built at compile time. + * NOTE: This is an ugly work-around for Darwin's + * concept of universal binaries, a single package + * (executable, lib, etc...) which contains both 32 + * and 64 bit versions. The issue is that if APR is + * built universally, if something else is compiled + * against it, some bit sizes will depend on whether + * it is 32 or 64 bit. This is determined by the __LP64__ + * flag. Since we need to support both, we have to + * handle OS X unqiuely. + */ +#ifdef DARWIN_10 +#undef APR_SIZEOF_VOIDP +#undef APR_INT64_C +#undef APR_UINT64_C +#ifdef __LP64__ + typedef long apr_int64_t; + typedef unsigned long apr_uint64_t; + #define APR_SIZEOF_VOIDP 8 + #define APR_INT64_C(v) (v ## L) + #define APR_UINT64_C(v) (v ## UL) +#else + typedef long long apr_int64_t; + typedef unsigned long long apr_uint64_t; + #define APR_SIZEOF_VOIDP 4 + #define APR_INT64_C(v) (v ## LL) + #define APR_UINT64_C(v) (v ## ULL) +#endif +#else + typedef int64_t apr_int64_t; + typedef uint64_t apr_uint64_t; + + /* Mechanisms to properly type numeric literals */ + #define APR_INT64_C(val) INT64_C(val) + #define APR_UINT64_C(val) UINT64_C(val) +#endif + +typedef size_t apr_size_t; +typedef ssize_t apr_ssize_t; +typedef off_t apr_off_t; +typedef socklen_t apr_socklen_t; +typedef ino_t apr_ino_t; + +#if APR_SIZEOF_VOIDP == 8 +typedef apr_uint64_t apr_uintptr_t; +#else +typedef apr_uint32_t apr_uintptr_t; +#endif + +/* Are we big endian? */ +#define APR_IS_BIGENDIAN 0 + +#ifdef INT16_MIN +#define APR_INT16_MIN INT16_MIN +#else +#define APR_INT16_MIN (-0x7fff - 1) +#endif + +#ifdef INT16_MAX +#define APR_INT16_MAX INT16_MAX +#else +#define APR_INT16_MAX (0x7fff) +#endif + +#ifdef UINT16_MAX +#define APR_UINT16_MAX UINT16_MAX +#else +#define APR_UINT16_MAX (0xffff) +#endif + +#ifdef INT32_MIN +#define APR_INT32_MIN INT32_MIN +#else +#define APR_INT32_MIN (-0x7fffffff - 1) +#endif + +#ifdef INT32_MAX +#define APR_INT32_MAX INT32_MAX +#else +#define APR_INT32_MAX 0x7fffffff +#endif + +#ifdef UINT32_MAX +#define APR_UINT32_MAX UINT32_MAX +#else +#define APR_UINT32_MAX (0xffffffffU) +#endif + +#ifdef INT64_MIN +#define APR_INT64_MIN INT64_MIN +#else +#define APR_INT64_MIN (APR_INT64_C(-0x7fffffffffffffff) - 1) +#endif + +#ifdef INT64_MAX +#define APR_INT64_MAX INT64_MAX +#else +#define APR_INT64_MAX APR_INT64_C(0x7fffffffffffffff) +#endif + +#ifdef UINT64_MAX +#define APR_UINT64_MAX UINT64_MAX +#else +#define APR_UINT64_MAX APR_UINT64_C(0xffffffffffffffff) +#endif + +#define APR_SIZE_MAX (~((apr_size_t)0)) + + +/* Definitions that APR programs need to work properly. */ + +/** + * APR public API wrap for C++ compilers. + */ +#ifdef __cplusplus +#define APR_BEGIN_DECLS extern "C" { +#define APR_END_DECLS } +#else +#define APR_BEGIN_DECLS +#define APR_END_DECLS +#endif + +/** + * Thread callbacks from APR functions must be declared with APR_THREAD_FUNC, + * so that they follow the platform's calling convention. + *

+ *
+ * void* APR_THREAD_FUNC my_thread_entry_fn(apr_thread_t *thd, void *data);
+ *
+ * 
+ */ +#define APR_THREAD_FUNC + +#if defined(DOXYGEN) || !defined(WIN32) + +/** + * The public APR functions are declared with APR_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APR_DECLARE_NONSTD(). + * + * @remark Both the declaration and implementations must use the same macro. + * + *
+ * APR_DECLARE(rettype) apr_func(args)
+ * 
+ * @see APR_DECLARE_NONSTD @see APR_DECLARE_DATA + * @remark Note that when APR compiles the library itself, it passes the + * symbol -DAPR_DECLARE_EXPORT to the compiler on some platforms (e.g. Win32) + * to export public symbols from the dynamic library build.\n + * The user must define the APR_DECLARE_STATIC when compiling to target + * the static APR library on some platforms (e.g. Win32.) The public symbols + * are neither exported nor imported when APR_DECLARE_STATIC is defined.\n + * By default, compiling an application and including the APR public + * headers, without defining APR_DECLARE_STATIC, will prepare the code to be + * linked to the dynamic library. + */ +#define APR_DECLARE(type) type + +/** + * The public APR functions using variable arguments are declared with + * APR_DECLARE_NONSTD(), as they must follow the C language calling convention. + * @see APR_DECLARE @see APR_DECLARE_DATA + * @remark Both the declaration and implementations must use the same macro. + *
+ *
+ * APR_DECLARE_NONSTD(rettype) apr_func(args, ...);
+ *
+ * 
+ */ +#define APR_DECLARE_NONSTD(type) type + +/** + * The public APR variables are declared with AP_MODULE_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * @see APR_DECLARE @see APR_DECLARE_NONSTD + * @remark Note that the declaration and implementations use different forms, + * but both must include the macro. + * + *
+ *
+ * extern APR_DECLARE_DATA type apr_variable;\n
+ * APR_DECLARE_DATA type apr_variable = value;
+ *
+ * 
+ */ +#define APR_DECLARE_DATA + +#elif defined(APR_DECLARE_STATIC) +#define APR_DECLARE(type) type __stdcall +#define APR_DECLARE_NONSTD(type) type __cdecl +#define APR_DECLARE_DATA +#elif defined(APR_DECLARE_EXPORT) +#define APR_DECLARE(type) __declspec(dllexport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllexport) +#else +#define APR_DECLARE(type) __declspec(dllimport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllimport) +#endif + +/* Define APR_SSIZE_T_FMT. + * If ssize_t is an integer we define it to be "d", + * if ssize_t is a long int we define it to be "ld", + * if ssize_t is neither we declare an error here. + * I looked for a better way to define this here, but couldn't find one, so + * to find the logic for this definition search for "ssize_t_fmt" in + * configure.in. + */ + +#define APR_SSIZE_T_FMT "ld" + +/* And APR_SIZE_T_FMT */ +#define APR_SIZE_T_FMT "lu" + +/* And APR_OFF_T_FMT */ +#define APR_OFF_T_FMT "ld" + +/* And APR_PID_T_FMT */ +#define APR_PID_T_FMT "d" + +/* And APR_INT64_T_FMT */ +#define APR_INT64_T_FMT PRId64 + +/* And APR_UINT64_T_FMT */ +#define APR_UINT64_T_FMT PRIu64 + +/* And APR_UINT64_T_HEX_FMT */ +#define APR_UINT64_T_HEX_FMT PRIx64 + +/* + * Ensure we work with universal binaries on Darwin + */ +#ifdef DARWIN_10 + +#undef APR_HAS_LARGE_FILES +#undef APR_SIZEOF_VOIDP +#undef APR_INT64_T_FMT +#undef APR_UINT64_T_FMT +#undef APR_UINT64_T_HEX_FMT + +#ifdef __LP64__ + #define APR_HAS_LARGE_FILES 0 + #define APR_SIZEOF_VOIDP 8 + #define APR_INT64_T_FMT "ld" + #define APR_UINT64_T_FMT "lu" + #define APR_UINT64_T_HEX_FMT "lx" +#else + #define APR_HAS_LARGE_FILES 1 + #define APR_SIZEOF_VOIDP 4 + #define APR_INT64_T_FMT "lld" + #define APR_UINT64_T_FMT "llu" + #define APR_UINT64_T_HEX_FMT "llx" +#endif + +#undef APR_IS_BIGENDIAN +#ifdef __BIG_ENDIAN__ + #define APR_IS_BIGENDIAN 1 +#else + #define APR_IS_BIGENDIAN 0 +#endif + +#undef APR_OFF_T_FMT +#define APR_OFF_T_FMT "lld" + +#endif /* DARWIN_10 */ + +/* Does the proc mutex lock threads too */ +#define APR_PROC_MUTEX_IS_GLOBAL 0 + +/* Local machine definition for console and log output. */ +#define APR_EOL_STR "\n" + +#if APR_HAVE_SYS_WAIT_H +#ifdef WEXITSTATUS +#define apr_wait_t int +#else +#define apr_wait_t union wait +#define WEXITSTATUS(status) (int)((status).w_retcode) +#define WTERMSIG(status) (int)((status).w_termsig) +#endif /* !WEXITSTATUS */ +#elif defined(__MINGW32__) +typedef int apr_wait_t; +#endif /* HAVE_SYS_WAIT_H */ + +#if defined(PATH_MAX) +#define APR_PATH_MAX PATH_MAX +#elif defined(_POSIX_PATH_MAX) +#define APR_PATH_MAX _POSIX_PATH_MAX +#else +#error no decision has been made on APR_PATH_MAX for your platform +#endif + +#define APR_DSOPATH "LD_LIBRARY_PATH" + +/** @} */ + +/* Definitions that only Win32 programs need to compile properly. */ + +/* XXX These simply don't belong here, perhaps in apr_portable.h + * based on some APR_HAVE_PID/GID/UID? + */ +#ifdef __MINGW32__ +#ifndef __GNUC__ +typedef int pid_t; +#endif +typedef int uid_t; +typedef int gid_t; +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* APR_H */ diff --git a/c/dependencies/linux/apr/include/apr_allocator.h b/c/dependencies/linux/apr/include/apr_allocator.h new file mode 100644 index 00000000..be05d0e4 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_allocator.h @@ -0,0 +1,179 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ALLOCATOR_H +#define APR_ALLOCATOR_H + +/** + * @file apr_allocator.h + * @brief APR Internal Memory Allocation + */ + +#include "apr.h" +#include "apr_errno.h" +#define APR_WANT_MEMFUNC /**< For no good reason? */ +#include "apr_want.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_allocator Internal Memory Allocation + * @ingroup APR + * @{ + */ + +/** the allocator structure */ +typedef struct apr_allocator_t apr_allocator_t; +/** the structure which holds information about the allocation */ +typedef struct apr_memnode_t apr_memnode_t; + +/** basic memory node structure + * @note The next, ref and first_avail fields are available for use by the + * caller of apr_allocator_alloc(), the remaining fields are read-only. + * The next field has to be used with caution and sensibly set when the + * memnode is passed back to apr_allocator_free(). See apr_allocator_free() + * for details. + * The ref and first_avail fields will be properly restored by + * apr_allocator_free(). + */ +struct apr_memnode_t { + apr_memnode_t *next; /**< next memnode */ + apr_memnode_t **ref; /**< reference to self */ + apr_uint32_t index; /**< size */ + apr_uint32_t free_index; /**< how much free */ + char *first_avail; /**< pointer to first free memory */ + char *endp; /**< pointer to end of free memory */ +}; + +/** The base size of a memory node - aligned. */ +#define APR_MEMNODE_T_SIZE APR_ALIGN_DEFAULT(sizeof(apr_memnode_t)) + +/** Symbolic constants */ +#define APR_ALLOCATOR_MAX_FREE_UNLIMITED 0 + +/** + * Create a new allocator + * @param allocator The allocator we have just created. + * + */ +APR_DECLARE(apr_status_t) apr_allocator_create(apr_allocator_t **allocator) + __attribute__((nonnull(1))); + +/** + * Destroy an allocator + * @param allocator The allocator to be destroyed + * @remark Any memnodes not given back to the allocator prior to destroying + * will _not_ be free()d. + */ +APR_DECLARE(void) apr_allocator_destroy(apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +/** + * Allocate a block of mem from the allocator + * @param allocator The allocator to allocate from + * @param size The size of the mem to allocate (excluding the + * memnode structure) + */ +APR_DECLARE(apr_memnode_t *) apr_allocator_alloc(apr_allocator_t *allocator, + apr_size_t size) + __attribute__((nonnull(1))); + +/** + * Free a list of blocks of mem, giving them back to the allocator. + * The list is typically terminated by a memnode with its next field + * set to NULL. + * @param allocator The allocator to give the mem back to + * @param memnode The memory node to return + */ +APR_DECLARE(void) apr_allocator_free(apr_allocator_t *allocator, + apr_memnode_t *memnode) + __attribute__((nonnull(1,2))); + +/** + * Get the true size that would be allocated for the given size (including + * the header and alignment). + * @param allocator The allocator from which to the memory would be allocated + * @param size The size to align + * @return The aligned size (or zero on apr_size_t overflow) + */ +APR_DECLARE(apr_size_t) apr_allocator_align(apr_allocator_t *allocator, + apr_size_t size); + +#include "apr_pools.h" + +/** + * Set the owner of the allocator + * @param allocator The allocator to set the owner for + * @param pool The pool that is to own the allocator + * @remark Typically pool is the highest level pool using the allocator + */ +/* + * XXX: see if we can come up with something a bit better. Currently + * you can make a pool an owner, but if the pool doesn't use the allocator + * the allocator will never be destroyed. + */ +APR_DECLARE(void) apr_allocator_owner_set(apr_allocator_t *allocator, + apr_pool_t *pool) + __attribute__((nonnull(1))); + +/** + * Get the current owner of the allocator + * @param allocator The allocator to get the owner from + */ +APR_DECLARE(apr_pool_t *) apr_allocator_owner_get(apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +/** + * Set the current threshold at which the allocator should start + * giving blocks back to the system. + * @param allocator The allocator to set the threshold on + * @param size The threshold. 0 == unlimited. + */ +APR_DECLARE(void) apr_allocator_max_free_set(apr_allocator_t *allocator, + apr_size_t size) + __attribute__((nonnull(1))); + +#include "apr_thread_mutex.h" + +#if APR_HAS_THREADS +/** + * Set a mutex for the allocator to use + * @param allocator The allocator to set the mutex for + * @param mutex The mutex + */ +APR_DECLARE(void) apr_allocator_mutex_set(apr_allocator_t *allocator, + apr_thread_mutex_t *mutex) + __attribute__((nonnull(1))); + +/** + * Get the mutex currently set for the allocator + * @param allocator The allocator + */ +APR_DECLARE(apr_thread_mutex_t *) apr_allocator_mutex_get( + apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ALLOCATOR_H */ diff --git a/c/dependencies/linux/apr/include/apr_anylock.h b/c/dependencies/linux/apr/include/apr_anylock.h new file mode 100644 index 00000000..51e97ff3 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_anylock.h @@ -0,0 +1,128 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_anylock.h + * @brief APR-Util transparent any lock flavor wrapper + */ +#ifndef APR_ANYLOCK_H +#define APR_ANYLOCK_H + +#include "apr_proc_mutex.h" +#include "apr_thread_mutex.h" +#include "apr_thread_rwlock.h" + +/** Structure that may contain any APR lock type */ +typedef struct apr_anylock_t { + /** Indicates what type of lock is in lock */ + enum tm_lock { + apr_anylock_none, /**< None */ + apr_anylock_procmutex, /**< Process-based */ + apr_anylock_threadmutex, /**< Thread-based */ + apr_anylock_readlock, /**< Read lock */ + apr_anylock_writelock /**< Write lock */ + } type; + /** Union of all possible APR locks */ + union apr_anylock_u_t { + apr_proc_mutex_t *pm; /**< Process mutex */ +#if APR_HAS_THREADS + apr_thread_mutex_t *tm; /**< Thread mutex */ + apr_thread_rwlock_t *rw; /**< Read-write lock */ +#endif + } lock; +} apr_anylock_t; + +#if APR_HAS_THREADS + +/** Lock an apr_anylock_t structure */ +#define APR_ANYLOCK_LOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_threadmutex) \ + ? apr_thread_mutex_lock((lck)->lock.tm) \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_lock((lck)->lock.pm) \ + : (((lck)->type == apr_anylock_readlock) \ + ? apr_thread_rwlock_rdlock((lck)->lock.rw) \ + : (((lck)->type == apr_anylock_writelock) \ + ? apr_thread_rwlock_wrlock((lck)->lock.rw) \ + : APR_EINVAL))))) + +#else /* APR_HAS_THREADS */ + +#define APR_ANYLOCK_LOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_lock((lck)->lock.pm) \ + : APR_EINVAL)) + +#endif /* APR_HAS_THREADS */ + +#if APR_HAS_THREADS + +/** Try to lock an apr_anylock_t structure */ +#define APR_ANYLOCK_TRYLOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_threadmutex) \ + ? apr_thread_mutex_trylock((lck)->lock.tm) \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_trylock((lck)->lock.pm) \ + : (((lck)->type == apr_anylock_readlock) \ + ? apr_thread_rwlock_tryrdlock((lck)->lock.rw) \ + : (((lck)->type == apr_anylock_writelock) \ + ? apr_thread_rwlock_trywrlock((lck)->lock.rw) \ + : APR_EINVAL))))) + +#else /* APR_HAS_THREADS */ + +#define APR_ANYLOCK_TRYLOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_trylock((lck)->lock.pm) \ + : APR_EINVAL)) + +#endif /* APR_HAS_THREADS */ + +#if APR_HAS_THREADS + +/** Unlock an apr_anylock_t structure */ +#define APR_ANYLOCK_UNLOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_threadmutex) \ + ? apr_thread_mutex_unlock((lck)->lock.tm) \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_unlock((lck)->lock.pm) \ + : ((((lck)->type == apr_anylock_readlock) || \ + ((lck)->type == apr_anylock_writelock)) \ + ? apr_thread_rwlock_unlock((lck)->lock.rw) \ + : APR_EINVAL)))) + +#else /* APR_HAS_THREADS */ + +#define APR_ANYLOCK_UNLOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_unlock((lck)->lock.pm) \ + : APR_EINVAL)) + +#endif /* APR_HAS_THREADS */ + +#endif /* !APR_ANYLOCK_H */ diff --git a/c/dependencies/linux/apr/include/apr_atomic.h b/c/dependencies/linux/apr/include/apr_atomic.h new file mode 100644 index 00000000..3d203edc --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_atomic.h @@ -0,0 +1,207 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ATOMIC_H +#define APR_ATOMIC_H + +/** + * @file apr_atomic.h + * @brief APR Atomic Operations + */ + +#include "apr.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_atomic Atomic Operations + * @ingroup APR + * @{ + */ + +/** + * this function is required on some platforms to initialize the + * atomic operation's internal structures + * @param p pool + * @return APR_SUCCESS on successful completion + * @remark Programs do NOT need to call this directly. APR will call this + * automatically from apr_initialize(). + * @internal + */ +APR_DECLARE(apr_status_t) apr_atomic_init(apr_pool_t *p); + +/* + * Atomic operations on 32-bit values + * Note: Each of these functions internally implements a memory barrier + * on platforms that require it + */ + +/** + * atomically read an apr_uint32_t from memory + * @param mem the pointer + */ +APR_DECLARE(apr_uint32_t) apr_atomic_read32(volatile apr_uint32_t *mem); + +/** + * atomically set an apr_uint32_t in memory + * @param mem pointer to the object + * @param val value that the object will assume + */ +APR_DECLARE(void) apr_atomic_set32(volatile apr_uint32_t *mem, apr_uint32_t val); + +/** + * atomically add 'val' to an apr_uint32_t + * @param mem pointer to the object + * @param val amount to add + * @return old value pointed to by mem + */ +APR_DECLARE(apr_uint32_t) apr_atomic_add32(volatile apr_uint32_t *mem, apr_uint32_t val); + +/** + * atomically subtract 'val' from an apr_uint32_t + * @param mem pointer to the object + * @param val amount to subtract + */ +APR_DECLARE(void) apr_atomic_sub32(volatile apr_uint32_t *mem, apr_uint32_t val); + +/** + * atomically increment an apr_uint32_t by 1 + * @param mem pointer to the object + * @return old value pointed to by mem + */ +APR_DECLARE(apr_uint32_t) apr_atomic_inc32(volatile apr_uint32_t *mem); + +/** + * atomically decrement an apr_uint32_t by 1 + * @param mem pointer to the atomic value + * @return zero if the value becomes zero on decrement, otherwise non-zero + */ +APR_DECLARE(int) apr_atomic_dec32(volatile apr_uint32_t *mem); + +/** + * compare an apr_uint32_t's value with 'cmp'. + * If they are the same swap the value with 'with' + * @param mem pointer to the value + * @param with what to swap it with + * @param cmp the value to compare it to + * @return the old value of *mem + */ +APR_DECLARE(apr_uint32_t) apr_atomic_cas32(volatile apr_uint32_t *mem, apr_uint32_t with, + apr_uint32_t cmp); + +/** + * exchange an apr_uint32_t's value with 'val'. + * @param mem pointer to the value + * @param val what to swap it with + * @return the old value of *mem + */ +APR_DECLARE(apr_uint32_t) apr_atomic_xchg32(volatile apr_uint32_t *mem, apr_uint32_t val); + +/* + * Atomic operations on 64-bit values + * Note: Each of these functions internally implements a memory barrier + * on platforms that require it + */ + +/** + * atomically read an apr_uint64_t from memory + * @param mem the pointer + */ +APR_DECLARE(apr_uint64_t) apr_atomic_read64(volatile apr_uint64_t *mem); + +/** + * atomically set an apr_uint64_t in memory + * @param mem pointer to the object + * @param val value that the object will assume + */ +APR_DECLARE(void) apr_atomic_set64(volatile apr_uint64_t *mem, apr_uint64_t val); + +/** + * atomically add 'val' to an apr_uint64_t + * @param mem pointer to the object + * @param val amount to add + * @return old value pointed to by mem + */ +APR_DECLARE(apr_uint64_t) apr_atomic_add64(volatile apr_uint64_t *mem, apr_uint64_t val); + +/** + * atomically subtract 'val' from an apr_uint64_t + * @param mem pointer to the object + * @param val amount to subtract + */ +APR_DECLARE(void) apr_atomic_sub64(volatile apr_uint64_t *mem, apr_uint64_t val); + +/** + * atomically increment an apr_uint64_t by 1 + * @param mem pointer to the object + * @return old value pointed to by mem + */ +APR_DECLARE(apr_uint64_t) apr_atomic_inc64(volatile apr_uint64_t *mem); + +/** + * atomically decrement an apr_uint64_t by 1 + * @param mem pointer to the atomic value + * @return zero if the value becomes zero on decrement, otherwise non-zero + */ +APR_DECLARE(int) apr_atomic_dec64(volatile apr_uint64_t *mem); + +/** + * compare an apr_uint64_t's value with 'cmp'. + * If they are the same swap the value with 'with' + * @param mem pointer to the value + * @param with what to swap it with + * @param cmp the value to compare it to + * @return the old value of *mem + */ +APR_DECLARE(apr_uint64_t) apr_atomic_cas64(volatile apr_uint64_t *mem, apr_uint64_t with, + apr_uint64_t cmp); + +/** + * exchange an apr_uint64_t's value with 'val'. + * @param mem pointer to the value + * @param val what to swap it with + * @return the old value of *mem + */ +APR_DECLARE(apr_uint64_t) apr_atomic_xchg64(volatile apr_uint64_t *mem, apr_uint64_t val); + +/** + * compare the pointer's value with cmp. + * If they are the same swap the value with 'with' + * @param mem pointer to the pointer + * @param with what to swap it with + * @param cmp the value to compare it to + * @return the old value of the pointer + */ +APR_DECLARE(void*) apr_atomic_casptr(volatile void **mem, void *with, const void *cmp); + +/** + * exchange a pair of pointer values + * @param mem pointer to the pointer + * @param with what to swap it with + * @return the old value of the pointer + */ +APR_DECLARE(void*) apr_atomic_xchgptr(volatile void **mem, void *with); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ATOMIC_H */ diff --git a/c/dependencies/linux/apr/include/apr_base64.h b/c/dependencies/linux/apr/include/apr_base64.h new file mode 100644 index 00000000..17de1c58 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_base64.h @@ -0,0 +1,113 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * The apr_vsnprintf/apr_snprintf functions are based on, and used with the + * permission of, the SIO stdio-replacement strx_* functions by Panos + * Tsirigotis for xinetd. + */ + +/** + * @file apr_base64.h + * @brief APR-UTIL Base64 Encoding + */ +#ifndef APR_BASE64_H +#define APR_BASE64_H + +#include "apu.h" +#include "apr_general.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Base64 Base64 Encoding + * @ingroup APR_Util + * @{ + */ + +/* Simple BASE64 encode/decode functions. + * + * As we might encode binary strings, hence we require the length of + * the incoming plain source. And return the length of what we decoded. + * + * The decoding function takes any non valid char (i.e. whitespace, \0 + * or anything non A-Z,0-9 etc as terminal. + * + * plain strings/binary sequences are not assumed '\0' terminated. Encoded + * strings are neither. But probably should. + * + */ + +/** + * Given the length of an un-encoded string, get the length of the + * encoded string. + * @param len the length of an unencoded string. + * @return the length of the string after it is encoded, including the + * trailing \0 + */ +APU_DECLARE(int) apr_base64_encode_len(int len); + +/** + * Encode a text string using base64encoding. + * @param coded_dst The destination string for the encoded string. + * @param plain_src The original string in plain text + * @param len_plain_src The length of the plain text string + * @return the length of the encoded string + */ +APU_DECLARE(int) apr_base64_encode(char * coded_dst, const char *plain_src, + int len_plain_src); + +/** + * Encode an EBCDIC string using base64encoding. + * @param coded_dst The destination string for the encoded string. + * @param plain_src The original string in plain text + * @param len_plain_src The length of the plain text string + * @return the length of the encoded string + */ +APU_DECLARE(int) apr_base64_encode_binary(char * coded_dst, + const unsigned char *plain_src, + int len_plain_src); + +/** + * Determine the maximum buffer length required to decode the plain text + * string given the encoded string. + * @param coded_src The encoded string + * @return the maximum required buffer length for the plain text string + */ +APU_DECLARE(int) apr_base64_decode_len(const char * coded_src); + +/** + * Decode a string to plain text + * @param plain_dst The destination string for the plain text + * @param coded_src The encoded string + * @return the length of the plain text string + */ +APU_DECLARE(int) apr_base64_decode(char * plain_dst, const char *coded_src); + +/** + * Decode an EBCDIC string to plain text + * @param plain_dst The destination string for the plain text + * @param coded_src The encoded string + * @return the length of the plain text string + */ +APU_DECLARE(int) apr_base64_decode_binary(unsigned char * plain_dst, + const char *coded_src); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_BASE64_H */ diff --git a/c/dependencies/linux/apr/include/apr_buckets.h b/c/dependencies/linux/apr/include/apr_buckets.h new file mode 100644 index 00000000..ce64b78d --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_buckets.h @@ -0,0 +1,1598 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file apr_buckets.h + * @brief APR-UTIL Buckets/Bucket Brigades + */ + +#ifndef APR_BUCKETS_H +#define APR_BUCKETS_H + +#if defined(APR_BUCKET_DEBUG) && !defined(APR_RING_DEBUG) +#define APR_RING_DEBUG +#endif + +#include "apu.h" +#include "apr_network_io.h" +#include "apr_file_io.h" +#include "apr_general.h" +#include "apr_mmap.h" +#include "apr_errno.h" +#include "apr_ring.h" +#include "apr.h" +#if APR_HAVE_SYS_UIO_H +#include /* for struct iovec */ +#endif +#if APR_HAVE_STDARG_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Bucket_Brigades Bucket Brigades + * @ingroup APR_Util + * @{ + */ + +/** default bucket buffer size - 8KB minus room for memory allocator headers */ +#define APR_BUCKET_BUFF_SIZE 8000 + +/** Determines how a bucket or brigade should be read */ +typedef enum { + APR_BLOCK_READ, /**< block until data becomes available */ + APR_NONBLOCK_READ /**< return immediately if no data is available */ +} apr_read_type_e; + +/** + * The one-sentence buzzword-laden overview: Bucket brigades represent + * a complex data stream that can be passed through a layered IO + * system without unnecessary copying. A longer overview follows... + * + * A bucket brigade is a doubly linked list (ring) of buckets, so we + * aren't limited to inserting at the front and removing at the end. + * Buckets are only passed around as members of a brigade, although + * singleton buckets can occur for short periods of time. + * + * Buckets are data stores of various types. They can refer to data in + * memory, or part of a file or mmap area, or the output of a process, + * etc. Buckets also have some type-dependent accessor functions: + * read, split, copy, setaside, and destroy. + * + * read returns the address and size of the data in the bucket. If the + * data isn't in memory then it is read in and the bucket changes type + * so that it can refer to the new location of the data. If all the + * data doesn't fit in the bucket then a new bucket is inserted into + * the brigade to hold the rest of it. + * + * split divides the data in a bucket into two regions. After a split + * the original bucket refers to the first part of the data and a new + * bucket inserted into the brigade after the original bucket refers + * to the second part of the data. Reference counts are maintained as + * necessary. + * + * setaside ensures that the data in the bucket has a long enough + * lifetime. Sometimes it is convenient to create a bucket referring + * to data on the stack in the expectation that it will be consumed + * (output to the network) before the stack is unwound. If that + * expectation turns out not to be valid, the setaside function is + * called to move the data somewhere safer. + * + * copy makes a duplicate of the bucket structure as long as it's + * possible to have multiple references to a single copy of the + * data itself. Not all bucket types can be copied. + * + * destroy maintains the reference counts on the resources used by a + * bucket and frees them if necessary. + * + * Note: all of the above functions have wrapper macros (apr_bucket_read(), + * apr_bucket_destroy(), etc), and those macros should be used rather + * than using the function pointers directly. + * + * To write a bucket brigade, they are first made into an iovec, so that we + * don't write too little data at one time. Currently we ignore compacting the + * buckets into as few buckets as possible, but if we really want good + * performance, then we need to compact the buckets before we convert to an + * iovec, or possibly while we are converting to an iovec. + */ + +/* + * Forward declaration of the main types. + */ + +/** @see apr_bucket_brigade */ +typedef struct apr_bucket_brigade apr_bucket_brigade; +/** @see apr_bucket */ +typedef struct apr_bucket apr_bucket; +/** @see apr_bucket_alloc_t */ +typedef struct apr_bucket_alloc_t apr_bucket_alloc_t; + +/** @see apr_bucket_type_t */ +typedef struct apr_bucket_type_t apr_bucket_type_t; + +/** + * Basic bucket type + */ +struct apr_bucket_type_t { + /** + * The name of the bucket type + */ + const char *name; + /** + * The number of functions this bucket understands. Can not be less than + * five. + */ + int num_func; + /** + * Whether the bucket contains metadata (ie, information that + * describes the regular contents of the brigade). The metadata + * is not returned by apr_bucket_read() and is not indicated by + * the ->length of the apr_bucket itself. In other words, an + * empty bucket is safe to arbitrarily remove if and only if it + * contains no metadata. In this sense, "data" is just raw bytes + * that are the "content" of the brigade and "metadata" describes + * that data but is not a proper part of it. + */ + enum { + /** This bucket type represents actual data to send to the client. */ + APR_BUCKET_DATA = 0, + /** This bucket type represents metadata. */ + APR_BUCKET_METADATA = 1 + } is_metadata; + /** + * Free the private data and any resources used by the bucket (if they + * aren't shared with another bucket). This function is required to be + * implemented for all bucket types, though it might be a no-op on some + * of them (namely ones that never allocate any private data structures). + * @param data The private data pointer from the bucket to be destroyed + */ + void (*destroy)(void *data); + + /** + * Read the data from the bucket. This is required to be implemented + * for all bucket types. + * @param b The bucket to read from + * @param str A place to store the data read. Allocation should only be + * done if absolutely necessary. + * @param len The amount of data read. + * @param block Should this read function block if there is more data that + * cannot be read immediately. + */ + apr_status_t (*read)(apr_bucket *b, const char **str, apr_size_t *len, + apr_read_type_e block); + + /** + * Make it possible to set aside the data for at least as long as the + * given pool. Buckets containing data that could potentially die before + * this pool (e.g. the data resides on the stack, in a child pool of + * the given pool, or in a disjoint pool) must somehow copy, shift, or + * transform the data to have the proper lifetime. + * @param e The bucket to convert + * @remark Some bucket types contain data that will always outlive the + * bucket itself. For example no data (EOS and FLUSH), or the data + * resides in global, constant memory (IMMORTAL), or the data is on + * the heap (HEAP). For these buckets, apr_bucket_setaside_noop can + * be used. + */ + apr_status_t (*setaside)(apr_bucket *e, apr_pool_t *pool); + + /** + * Split one bucket in two at the specified position by duplicating + * the bucket structure (not the data) and modifying any necessary + * start/end/offset information. If it's not possible to do this + * for the bucket type (perhaps the length of the data is indeterminate, + * as with pipe and socket buckets), then APR_ENOTIMPL is returned. + * @param e The bucket to split + * @param point The offset of the first byte in the new bucket + */ + apr_status_t (*split)(apr_bucket *e, apr_size_t point); + + /** + * Copy the bucket structure (not the data), assuming that this is + * possible for the bucket type. If it's not, APR_ENOTIMPL is returned. + * @param e The bucket to copy + * @param c Returns a pointer to the new bucket + */ + apr_status_t (*copy)(apr_bucket *e, apr_bucket **c); + +}; + +/** + * apr_bucket structures are allocated on the malloc() heap and + * their lifetime is controlled by the parent apr_bucket_brigade + * structure. Buckets can move from one brigade to another e.g. by + * calling APR_BRIGADE_CONCAT(). In general the data in a bucket has + * the same lifetime as the bucket and is freed when the bucket is + * destroyed; if the data is shared by more than one bucket (e.g. + * after a split) the data is freed when the last bucket goes away. + */ +struct apr_bucket { + /** Links to the rest of the brigade */ + APR_RING_ENTRY(apr_bucket) link; + /** The type of bucket. */ + const apr_bucket_type_t *type; + /** The length of the data in the bucket. This could have been implemented + * with a function, but this is an optimization, because the most + * common thing to do will be to get the length. If the length is unknown, + * the value of this field will be (apr_size_t)(-1). + */ + apr_size_t length; + /** The start of the data in the bucket relative to the private base + * pointer. The vast majority of bucket types allow a fixed block of + * data to be referenced by multiple buckets, each bucket pointing to + * a different segment of the data. That segment starts at base+start + * and ends at base+start+length. + * If the length == (apr_size_t)(-1), then start == -1. + */ + apr_off_t start; + /** type-dependent data hangs off this pointer */ + void *data; + /** + * Pointer to function used to free the bucket. This function should + * always be defined and it should be consistent with the memory + * function used to allocate the bucket. For example, if malloc() is + * used to allocate the bucket, this pointer should point to free(). + * @param e Pointer to the bucket being freed + */ + void (*free)(void *e); + /** The freelist from which this bucket was allocated */ + apr_bucket_alloc_t *list; +}; + +/** A list of buckets */ +struct apr_bucket_brigade { + /** The pool to associate the brigade with. The data is not allocated out + * of the pool, but a cleanup is registered with this pool. If the + * brigade is destroyed by some mechanism other than pool destruction, + * the destroying function is responsible for killing the cleanup. + */ + apr_pool_t *p; + /** The buckets in the brigade are on this list. */ + /* + * The apr_bucket_list structure doesn't actually need a name tag + * because it has no existence independent of struct apr_bucket_brigade; + * the ring macros are designed so that you can leave the name tag + * argument empty in this situation but apparently the Windows compiler + * doesn't like that. + */ + APR_RING_HEAD(apr_bucket_list, apr_bucket) list; + /** The freelist from which this bucket was allocated */ + apr_bucket_alloc_t *bucket_alloc; +}; + + +/** + * Function called when a brigade should be flushed + */ +typedef apr_status_t (*apr_brigade_flush)(apr_bucket_brigade *bb, void *ctx); + +/* + * define APR_BUCKET_DEBUG if you want your brigades to be checked for + * validity at every possible instant. this will slow your code down + * substantially but is a very useful debugging tool. + */ +#ifdef APR_BUCKET_DEBUG + +#define APR_BRIGADE_CHECK_CONSISTENCY(b) \ + APR_RING_CHECK_CONSISTENCY(&(b)->list, apr_bucket, link) + +#define APR_BUCKET_CHECK_CONSISTENCY(e) \ + APR_RING_CHECK_ELEM_CONSISTENCY((e), apr_bucket, link) + +#else +/** + * checks the ring pointers in a bucket brigade for consistency. an + * abort() will be triggered if any inconsistencies are found. + * note: this is a no-op unless APR_BUCKET_DEBUG is defined. + * @param b The brigade + */ +#define APR_BRIGADE_CHECK_CONSISTENCY(b) +/** + * checks the brigade a bucket is in for ring consistency. an + * abort() will be triggered if any inconsistencies are found. + * note: this is a no-op unless APR_BUCKET_DEBUG is defined. + * @param e The bucket + */ +#define APR_BUCKET_CHECK_CONSISTENCY(e) +#endif + + +/** + * Wrappers around the RING macros to reduce the verbosity of the code + * that handles bucket brigades. + */ +/** + * The magic pointer value that indicates the head of the brigade + * @remark This is used to find the beginning and end of the brigade, eg: + *
+ *      while (e != APR_BRIGADE_SENTINEL(b)) {
+ *          ...
+ *          e = APR_BUCKET_NEXT(e);
+ *      }
+ * 
+ * @param b The brigade + * @return The magic pointer value + */ +#define APR_BRIGADE_SENTINEL(b) APR_RING_SENTINEL(&(b)->list, apr_bucket, link) + +/** + * Determine if the bucket brigade is empty + * @param b The brigade to check + * @return true or false + */ +#define APR_BRIGADE_EMPTY(b) APR_RING_EMPTY(&(b)->list, apr_bucket, link) + +/** + * Return the first bucket in a brigade + * @param b The brigade to query + * @return The first bucket in the brigade + */ +#define APR_BRIGADE_FIRST(b) APR_RING_FIRST(&(b)->list) +/** + * Return the last bucket in a brigade + * @param b The brigade to query + * @return The last bucket in the brigade + */ +#define APR_BRIGADE_LAST(b) APR_RING_LAST(&(b)->list) + +/** + * Insert a single bucket at the front of a brigade + * @param b The brigade to add to + * @param e The bucket to insert + */ +#define APR_BRIGADE_INSERT_HEAD(b, e) do { \ + apr_bucket *ap__b = (e); \ + APR_RING_INSERT_HEAD(&(b)->list, ap__b, apr_bucket, link); \ + APR_BRIGADE_CHECK_CONSISTENCY((b)); \ + } while (0) + +/** + * Insert a single bucket at the end of a brigade + * @param b The brigade to add to + * @param e The bucket to insert + */ +#define APR_BRIGADE_INSERT_TAIL(b, e) do { \ + apr_bucket *ap__b = (e); \ + APR_RING_INSERT_TAIL(&(b)->list, ap__b, apr_bucket, link); \ + APR_BRIGADE_CHECK_CONSISTENCY((b)); \ + } while (0) + +/** + * Concatenate brigade b onto the end of brigade a, leaving brigade b empty + * @param a The first brigade + * @param b The second brigade + */ +#define APR_BRIGADE_CONCAT(a, b) do { \ + APR_RING_CONCAT(&(a)->list, &(b)->list, apr_bucket, link); \ + APR_BRIGADE_CHECK_CONSISTENCY((a)); \ + } while (0) + +/** + * Prepend brigade b onto the beginning of brigade a, leaving brigade b empty + * @param a The first brigade + * @param b The second brigade + */ +#define APR_BRIGADE_PREPEND(a, b) do { \ + APR_RING_PREPEND(&(a)->list, &(b)->list, apr_bucket, link); \ + APR_BRIGADE_CHECK_CONSISTENCY((a)); \ + } while (0) + +/** + * Insert a single bucket before a specified bucket + * @param a The bucket to insert before + * @param b The bucket to insert + */ +#define APR_BUCKET_INSERT_BEFORE(a, b) do { \ + apr_bucket *ap__a = (a), *ap__b = (b); \ + APR_RING_INSERT_BEFORE(ap__a, ap__b, link); \ + APR_BUCKET_CHECK_CONSISTENCY(ap__a); \ + } while (0) + +/** + * Insert a single bucket after a specified bucket + * @param a The bucket to insert after + * @param b The bucket to insert + */ +#define APR_BUCKET_INSERT_AFTER(a, b) do { \ + apr_bucket *ap__a = (a), *ap__b = (b); \ + APR_RING_INSERT_AFTER(ap__a, ap__b, link); \ + APR_BUCKET_CHECK_CONSISTENCY(ap__a); \ + } while (0) + +/** + * Get the next bucket in the list + * @param e The current bucket + * @return The next bucket + */ +#define APR_BUCKET_NEXT(e) APR_RING_NEXT((e), link) +/** + * Get the previous bucket in the list + * @param e The current bucket + * @return The previous bucket + */ +#define APR_BUCKET_PREV(e) APR_RING_PREV((e), link) + +/** + * Remove a bucket from its bucket brigade + * @param e The bucket to remove + */ +#define APR_BUCKET_REMOVE(e) APR_RING_REMOVE((e), link) + +/** + * Initialize a new bucket's prev/next pointers + * @param e The bucket to initialize + */ +#define APR_BUCKET_INIT(e) APR_RING_ELEM_INIT((e), link) + +/** + * Determine if a bucket contains metadata. An empty bucket is + * safe to arbitrarily remove if and only if this is false. + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_METADATA(e) ((e)->type->is_metadata) + +/** + * Determine if a bucket is a FLUSH bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_FLUSH(e) ((e)->type == &apr_bucket_type_flush) +/** + * Determine if a bucket is an EOS bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_EOS(e) ((e)->type == &apr_bucket_type_eos) +/** + * Determine if a bucket is a FILE bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_FILE(e) ((e)->type == &apr_bucket_type_file) +/** + * Determine if a bucket is a PIPE bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_PIPE(e) ((e)->type == &apr_bucket_type_pipe) +/** + * Determine if a bucket is a SOCKET bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_SOCKET(e) ((e)->type == &apr_bucket_type_socket) +/** + * Determine if a bucket is a HEAP bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_HEAP(e) ((e)->type == &apr_bucket_type_heap) +/** + * Determine if a bucket is a TRANSIENT bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_TRANSIENT(e) ((e)->type == &apr_bucket_type_transient) +/** + * Determine if a bucket is a IMMORTAL bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_IMMORTAL(e) ((e)->type == &apr_bucket_type_immortal) +#if APR_HAS_MMAP +/** + * Determine if a bucket is a MMAP bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_MMAP(e) ((e)->type == &apr_bucket_type_mmap) +#endif +/** + * Determine if a bucket is a POOL bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_POOL(e) ((e)->type == &apr_bucket_type_pool) + +/* + * General-purpose reference counting for the various bucket types. + * + * Any bucket type that keeps track of the resources it uses (i.e. + * most of them except for IMMORTAL, TRANSIENT, and EOS) needs to + * attach a reference count to the resource so that it can be freed + * when the last bucket that uses it goes away. Resource-sharing may + * occur because of bucket splits or buckets that refer to globally + * cached data. */ + +/** @see apr_bucket_refcount */ +typedef struct apr_bucket_refcount apr_bucket_refcount; +/** + * The structure used to manage the shared resource must start with an + * apr_bucket_refcount which is updated by the general-purpose refcount + * code. A pointer to the bucket-type-dependent private data structure + * can be cast to a pointer to an apr_bucket_refcount and vice versa. + */ +struct apr_bucket_refcount { + /** The number of references to this bucket */ + int refcount; +}; + +/* ***** Reference-counted bucket types ***** */ + +/** @see apr_bucket_heap */ +typedef struct apr_bucket_heap apr_bucket_heap; +/** + * A bucket referring to data allocated off the heap. + */ +struct apr_bucket_heap { + /** Number of buckets using this memory */ + apr_bucket_refcount refcount; + /** The start of the data actually allocated. This should never be + * modified, it is only used to free the bucket. + */ + char *base; + /** how much memory was allocated */ + apr_size_t alloc_len; + /** function to use to delete the data */ + void (*free_func)(void *data); +}; + +/** @see apr_bucket_pool */ +typedef struct apr_bucket_pool apr_bucket_pool; +/** + * A bucket referring to data allocated from a pool + */ +struct apr_bucket_pool { + /** The pool bucket must be able to be easily morphed to a heap + * bucket if the pool gets cleaned up before all references are + * destroyed. This apr_bucket_heap structure is populated automatically + * when the pool gets cleaned up, and subsequent calls to pool_read() + * will result in the apr_bucket in question being morphed into a + * regular heap bucket. (To avoid having to do many extra refcount + * manipulations and b->data manipulations, the apr_bucket_pool + * struct actually *contains* the apr_bucket_heap struct that it + * will become as its first element; the two share their + * apr_bucket_refcount members.) + */ + apr_bucket_heap heap; + /** The block of data actually allocated from the pool. + * Segments of this block are referenced by adjusting + * the start and length of the apr_bucket accordingly. + * This will be NULL after the pool gets cleaned up. + */ + const char *base; + /** The pool the data was allocated from. When the pool + * is cleaned up, this gets set to NULL as an indicator + * to pool_read() that the data is now on the heap and + * so it should morph the bucket into a regular heap + * bucket before continuing. + */ + apr_pool_t *pool; + /** The freelist this structure was allocated from, which is + * needed in the cleanup phase in order to allocate space on the heap + */ + apr_bucket_alloc_t *list; +}; + +#if APR_HAS_MMAP +/** @see apr_bucket_mmap */ +typedef struct apr_bucket_mmap apr_bucket_mmap; +/** + * A bucket referring to an mmap()ed file + */ +struct apr_bucket_mmap { + /** Number of buckets using this memory */ + apr_bucket_refcount refcount; + /** The mmap this sub_bucket refers to */ + apr_mmap_t *mmap; +}; +#endif + +/** @see apr_bucket_file */ +typedef struct apr_bucket_file apr_bucket_file; +/** + * A bucket referring to an file + */ +struct apr_bucket_file { + /** Number of buckets using this memory */ + apr_bucket_refcount refcount; + /** The file this bucket refers to */ + apr_file_t *fd; + /** The pool into which any needed structures should + * be created while reading from this file bucket */ + apr_pool_t *readpool; +#if APR_HAS_MMAP + /** Whether this bucket should be memory-mapped if + * a caller tries to read from it */ + int can_mmap; +#endif /* APR_HAS_MMAP */ + /** File read block size */ + apr_size_t read_size; +}; + +/** @see apr_bucket_structs */ +typedef union apr_bucket_structs apr_bucket_structs; +/** + * A union of all bucket structures so we know what + * the max size is. + */ +union apr_bucket_structs { + apr_bucket b; /**< Bucket */ + apr_bucket_heap heap; /**< Heap */ + apr_bucket_pool pool; /**< Pool */ +#if APR_HAS_MMAP + apr_bucket_mmap mmap; /**< MMap */ +#endif + apr_bucket_file file; /**< File */ +}; + +/** + * The amount that apr_bucket_alloc() should allocate in the common case. + * Note: this is twice as big as apr_bucket_structs to allow breathing + * room for third-party bucket types. + */ +#define APR_BUCKET_ALLOC_SIZE APR_ALIGN_DEFAULT(2*sizeof(apr_bucket_structs)) + +/* ***** Bucket Brigade Functions ***** */ +/** + * Create a new bucket brigade. The bucket brigade is originally empty. + * @param p The pool to associate with the brigade. Data is not allocated out + * of the pool, but a cleanup is registered. + * @param list The bucket allocator to use + * @return The empty bucket brigade + */ +APU_DECLARE(apr_bucket_brigade *) apr_brigade_create(apr_pool_t *p, + apr_bucket_alloc_t *list); + +/** + * destroy an entire bucket brigade. This includes destroying all of the + * buckets within the bucket brigade's bucket list. + * @param b The bucket brigade to destroy + */ +APU_DECLARE(apr_status_t) apr_brigade_destroy(apr_bucket_brigade *b); + +/** + * empty out an entire bucket brigade. This includes destroying all of the + * buckets within the bucket brigade's bucket list. This is similar to + * apr_brigade_destroy(), except that it does not deregister the brigade's + * pool cleanup function. + * @param data The bucket brigade to clean up + * @remark Generally, you should use apr_brigade_destroy(). This function + * can be useful in situations where you have a single brigade that + * you wish to reuse many times by destroying all of the buckets in + * the brigade and putting new buckets into it later. + */ +APU_DECLARE(apr_status_t) apr_brigade_cleanup(void *data); + +/** + * Move the buckets from the tail end of the existing brigade @a b into + * the brigade @a a. If @a a is NULL a new brigade is created. Buckets + * from @a e to the last bucket (inclusively) of brigade @a b are moved + * from @a b to the returned brigade @a a. + * + * @param b The brigade to split + * @param e The first bucket to move + * @param a The brigade which should be used for the result or NULL if + * a new brigade should be created. The brigade @a a will be + * cleared if it is not empty. + * @return The brigade supplied in @a a or a new one if @a a was NULL. + * @warning Note that this function allocates a new brigade if @a a is + * NULL so memory consumption should be carefully considered. + */ +APU_DECLARE(apr_bucket_brigade *) apr_brigade_split_ex(apr_bucket_brigade *b, + apr_bucket *e, + apr_bucket_brigade *a); + +/** + * Create a new bucket brigade and move the buckets from the tail end + * of an existing brigade into the new brigade. Buckets from + * @a e to the last bucket (inclusively) of brigade @a b + * are moved from @a b to the returned brigade. + * @param b The brigade to split + * @param e The first bucket to move + * @return The new brigade + * @warning Note that this function always allocates a new brigade + * so memory consumption should be carefully considered. + */ +APU_DECLARE(apr_bucket_brigade *) apr_brigade_split(apr_bucket_brigade *b, + apr_bucket *e); + +/** + * Partition a bucket brigade at a given offset (in bytes from the start of + * the brigade). This is useful whenever a filter wants to use known ranges + * of bytes from the brigade; the ranges can even overlap. + * @param b The brigade to partition + * @param point The offset at which to partition the brigade + * @param after_point Returns a pointer to the first bucket after the partition + * @return APR_SUCCESS on success, APR_INCOMPLETE if the contents of the + * brigade were shorter than @a point, or an error code. + * @remark if APR_INCOMPLETE is returned, @a after_point will be set to + * the brigade sentinel. + */ +APU_DECLARE(apr_status_t) apr_brigade_partition(apr_bucket_brigade *b, + apr_off_t point, + apr_bucket **after_point); + +/** + * Return the total length of the brigade. + * @param bb The brigade to compute the length of + * @param read_all Read unknown-length buckets to force a size + * @param length Returns the length of the brigade (up to the end, or up + * to a bucket read error), or -1 if the brigade has buckets + * of indeterminate length and read_all is 0. + */ +APU_DECLARE(apr_status_t) apr_brigade_length(apr_bucket_brigade *bb, + int read_all, + apr_off_t *length); + +/** + * Take a bucket brigade and store the data in a flat char* + * @param bb The bucket brigade to create the char* from + * @param c The char* to write into + * @param len The maximum length of the char array. On return, it is the + * actual length of the char array. + */ +APU_DECLARE(apr_status_t) apr_brigade_flatten(apr_bucket_brigade *bb, + char *c, + apr_size_t *len); + +/** + * Creates a pool-allocated string representing a flat bucket brigade + * @param bb The bucket brigade to create the char array from + * @param c On return, the allocated char array + * @param len On return, the length of the char array. + * @param pool The pool to allocate the string from. + */ +APU_DECLARE(apr_status_t) apr_brigade_pflatten(apr_bucket_brigade *bb, + char **c, + apr_size_t *len, + apr_pool_t *pool); + +/** + * Split a brigade to represent one LF line. + * @param bbOut The bucket brigade that will have the LF line appended to. + * @param bbIn The input bucket brigade to search for a LF-line. + * @param block The blocking mode to be used to split the line. + * @param maxbytes The maximum bytes to read. If this many bytes are seen + * without a LF, the brigade will contain a partial line. + */ +APU_DECLARE(apr_status_t) apr_brigade_split_line(apr_bucket_brigade *bbOut, + apr_bucket_brigade *bbIn, + apr_read_type_e block, + apr_off_t maxbytes); + +/** + * Create an iovec of the elements in a bucket_brigade... return number + * of elements used. This is useful for writing to a file or to the + * network efficiently. + * @param b The bucket brigade to create the iovec from + * @param vec The iovec to create + * @param nvec The number of elements in the iovec. On return, it is the + * number of iovec elements actually filled out. + */ +APU_DECLARE(apr_status_t) apr_brigade_to_iovec(apr_bucket_brigade *b, + struct iovec *vec, int *nvec); + +/** + * This function writes a list of strings into a bucket brigade. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param va A list of strings to add + * @return APR_SUCCESS or error code. + */ +APU_DECLARE(apr_status_t) apr_brigade_vputstrs(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, + va_list va); + +/** + * This function writes a string into a bucket brigade. + * + * The apr_brigade_write function attempts to be efficient with the + * handling of heap buckets. Regardless of the amount of data stored + * inside a heap bucket, heap buckets are a fixed size to promote their + * reuse. + * + * If an attempt is made to write a string to a brigade that already + * ends with a heap bucket, this function will attempt to pack the + * string into the remaining space in the previous heap bucket, before + * allocating a new heap bucket. + * + * This function always returns APR_SUCCESS, unless a flush function is + * passed, in which case the return value of the flush function will be + * returned if used. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param str The string to add + * @param nbyte The number of bytes to write + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_write(apr_bucket_brigade *b, + apr_brigade_flush flush, void *ctx, + const char *str, apr_size_t nbyte); + +/** + * This function writes multiple strings into a bucket brigade. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param vec The strings to add (address plus length for each) + * @param nvec The number of entries in iovec + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_writev(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, + const struct iovec *vec, + apr_size_t nvec); + +/** + * This function writes a string into a bucket brigade. + * @param bb The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param str The string to add + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_puts(apr_bucket_brigade *bb, + apr_brigade_flush flush, void *ctx, + const char *str); + +/** + * This function writes a character into a bucket brigade. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param c The character to add + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_putc(apr_bucket_brigade *b, + apr_brigade_flush flush, void *ctx, + const char c); + +/** + * This function writes an unspecified number of strings into a bucket brigade. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param ... The strings to add + * @return APR_SUCCESS or error code + */ +APU_DECLARE_NONSTD(apr_status_t) apr_brigade_putstrs(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, ...); + +/** + * Evaluate a printf and put the resulting string at the end + * of the bucket brigade. + * @param b The brigade to write to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param fmt The format of the string to write + * @param ... The arguments to fill out the format + * @return APR_SUCCESS or error code + */ +APU_DECLARE_NONSTD(apr_status_t) apr_brigade_printf(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, + const char *fmt, ...) + __attribute__((format(printf,4,5))); + +/** + * Evaluate a printf and put the resulting string at the end + * of the bucket brigade. + * @param b The brigade to write to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param fmt The format of the string to write + * @param va The arguments to fill out the format + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_vprintf(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, + const char *fmt, va_list va); + +/** + * Utility function to insert a file (or a segment of a file) onto the + * end of the brigade. The file is split into multiple buckets if it + * is larger than the maximum size which can be represented by a + * single bucket. + * @param bb the brigade to insert into + * @param f the file to insert + * @param start the offset of the start of the segment + * @param len the length of the segment of the file to insert + * @param p pool from which file buckets are allocated + * @return the last bucket inserted + */ +APU_DECLARE(apr_bucket *) apr_brigade_insert_file(apr_bucket_brigade *bb, + apr_file_t *f, + apr_off_t start, + apr_off_t len, + apr_pool_t *p); + + + +/* ***** Bucket freelist functions ***** */ +/** + * Create a bucket allocator. + * @param p This pool's underlying apr_allocator_t is used to allocate memory + * for the bucket allocator. When the pool is destroyed, the bucket + * allocator's cleanup routine will free all memory that has been + * allocated from it. + * @remark The reason the allocator gets its memory from the pool's + * apr_allocator_t rather than from the pool itself is because + * the bucket allocator will free large memory blocks back to the + * allocator when it's done with them, thereby preventing memory + * footprint growth that would occur if we allocated from the pool. + * @warning The allocator must never be used by more than one thread at a time. + */ +APU_DECLARE_NONSTD(apr_bucket_alloc_t *) apr_bucket_alloc_create(apr_pool_t *p); + +/** + * Create a bucket allocator. + * @param allocator This apr_allocator_t is used to allocate both the bucket + * allocator and all memory handed out by the bucket allocator. The + * caller is responsible for destroying the bucket allocator and the + * apr_allocator_t -- no automatic cleanups will happen. + * @warning The allocator must never be used by more than one thread at a time. + */ +APU_DECLARE_NONSTD(apr_bucket_alloc_t *) apr_bucket_alloc_create_ex(apr_allocator_t *allocator); + +/** + * Destroy a bucket allocator. + * @param list The allocator to be destroyed + */ +APU_DECLARE_NONSTD(void) apr_bucket_alloc_destroy(apr_bucket_alloc_t *list); + +/** + * Get the aligned size corresponding to the requested size, but minus the + * allocator(s) overhead such that the allocation would remain in the + * same boundary. + * @param list The allocator from which to the memory would be allocated. + * @param size The requested size. + * @return The corresponding aligned/floored size. + */ +APU_DECLARE_NONSTD(apr_size_t) apr_bucket_alloc_aligned_floor(apr_bucket_alloc_t *list, + apr_size_t size) + __attribute__((nonnull(1))); + +/** + * Allocate memory for use by the buckets. + * @param size The amount to allocate. + * @param list The allocator from which to allocate the memory. + */ +APU_DECLARE_NONSTD(void *) apr_bucket_alloc(apr_size_t size, apr_bucket_alloc_t *list); + +/** + * Free memory previously allocated with apr_bucket_alloc(). + * @param block The block of memory to be freed. + */ +APU_DECLARE_NONSTD(void) apr_bucket_free(void *block); + + +/* ***** Bucket Functions ***** */ +/** + * Free the resources used by a bucket. If multiple buckets refer to + * the same resource it is freed when the last one goes away. + * @see apr_bucket_delete() + * @param e The bucket to destroy + */ +#define apr_bucket_destroy(e) do { \ + (e)->type->destroy((e)->data); \ + (e)->free(e); \ + } while (0) + +/** + * Delete a bucket by removing it from its brigade (if any) and then + * destroying it. + * @remark This mainly acts as an aid in avoiding code verbosity. It is + * the preferred exact equivalent to: + *
+ *      APR_BUCKET_REMOVE(e);
+ *      apr_bucket_destroy(e);
+ * 
+ * @param e The bucket to delete + */ +#define apr_bucket_delete(e) do { \ + APR_BUCKET_REMOVE(e); \ + apr_bucket_destroy(e); \ + } while (0) + +/** + * Read some data from the bucket. + * + * The apr_bucket_read function returns a convenient amount of data + * from the bucket provided, writing the address and length of the + * data to the pointers provided by the caller. The function tries + * as hard as possible to avoid a memory copy. + * + * Buckets are expected to be a member of a brigade at the time they + * are read. + * + * In typical application code, buckets are read in a loop, and after + * each bucket is read and processed, it is moved or deleted from the + * brigade and the next bucket read. + * + * The definition of "convenient" depends on the type of bucket that + * is being read, and is decided by APR. In the case of memory based + * buckets such as heap and immortal buckets, a pointer will be + * returned to the location of the buffer containing the complete + * contents of the bucket. + * + * Some buckets, such as the socket bucket, might have no concept + * of length. If an attempt is made to read such a bucket, the + * apr_bucket_read function will read a convenient amount of data + * from the socket. The socket bucket is magically morphed into a + * heap bucket containing the just-read data, and a new socket bucket + * is inserted just after this heap bucket. + * + * To understand why apr_bucket_read might do this, consider the loop + * described above to read and process buckets. The current bucket + * is magically morphed into a heap bucket and returned to the caller. + * The caller processes the data, and deletes the heap bucket, moving + * onto the next bucket, the new socket bucket. This process repeats, + * giving the illusion of a bucket brigade that contains potentially + * infinite amounts of data. It is up to the caller to decide at what + * point to stop reading buckets. + * + * Some buckets, such as the file bucket, might have a fixed size, + * but be significantly larger than is practical to store in RAM in + * one go. As with the socket bucket, if an attempt is made to read + * from a file bucket, the file bucket is magically morphed into a + * heap bucket containing a convenient amount of data read from the + * current offset in the file. During the read, the offset will be + * moved forward on the file, and a new file bucket will be inserted + * directly after the current bucket representing the remainder of the + * file. If the heap bucket was large enough to store the whole + * remainder of the file, no more file buckets are inserted, and the + * file bucket will disappear completely. + * + * The pattern for reading buckets described above does create the + * illusion that the code is willing to swallow buckets that might be + * too large for the system to handle in one go. This however is just + * an illusion: APR will always ensure that large (file) or infinite + * (socket) buckets are broken into convenient bite sized heap buckets + * before data is returned to the caller. + * + * There is a potential gotcha to watch for: if buckets are read in a + * loop, and aren't deleted after being processed, the potentially large + * bucket will slowly be converted into RAM resident heap buckets. If + * the file is larger than available RAM, an out of memory condition + * could be caused if the application is not careful to manage this. + * + * @param e The bucket to read from + * @param str The location to store a pointer to the data in + * @param len The location to store the amount of data read + * @param block Whether the read function blocks + */ +#define apr_bucket_read(e,str,len,block) (e)->type->read(e, str, len, block) + +/** + * Setaside data so that stack data is not destroyed on returning from + * the function + * @param e The bucket to setaside + * @param p The pool to setaside into + */ +#define apr_bucket_setaside(e,p) (e)->type->setaside(e,p) + +/** + * Split one bucket in two at the point provided. + * + * Once split, the original bucket becomes the first of the two new buckets. + * + * (It is assumed that the bucket is a member of a brigade when this + * function is called). + * @param e The bucket to split + * @param point The offset to split the bucket at + */ +#define apr_bucket_split(e,point) (e)->type->split(e, point) + +/** + * Copy a bucket. + * @param e The bucket to copy + * @param c Returns a pointer to the new bucket + */ +#define apr_bucket_copy(e,c) (e)->type->copy(e, c) + +/* Bucket type handling */ + +/** + * This function simply returns APR_SUCCESS to denote that the bucket does + * not require anything to happen for its setaside() function. This is + * appropriate for buckets that have "immortal" data -- the data will live + * at least as long as the bucket. + * @param data The bucket to setaside + * @param pool The pool defining the desired lifetime of the bucket data + * @return APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_setaside_noop(apr_bucket *data, + apr_pool_t *pool); + +/** + * A place holder function that signifies that the setaside function was not + * implemented for this bucket + * @param data The bucket to setaside + * @param pool The pool defining the desired lifetime of the bucket data + * @return APR_ENOTIMPL + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_setaside_notimpl(apr_bucket *data, + apr_pool_t *pool); + +/** + * A place holder function that signifies that the split function was not + * implemented for this bucket + * @param data The bucket to split + * @param point The location to split the bucket + * @return APR_ENOTIMPL + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_split_notimpl(apr_bucket *data, + apr_size_t point); + +/** + * A place holder function that signifies that the copy function was not + * implemented for this bucket + * @param e The bucket to copy + * @param c Returns a pointer to the new bucket + * @return APR_ENOTIMPL + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_copy_notimpl(apr_bucket *e, + apr_bucket **c); + +/** + * A place holder function that signifies that this bucket does not need + * to do anything special to be destroyed. That's only the case for buckets + * that either have no data (metadata buckets) or buckets whose data pointer + * points to something that's not a bucket-type-specific structure, as with + * simple buckets where data points to a string and pipe buckets where data + * points directly to the apr_file_t. + * @param data The bucket data to destroy + */ +APU_DECLARE_NONSTD(void) apr_bucket_destroy_noop(void *data); + +/** + * There is no apr_bucket_destroy_notimpl, because destruction is required + * to be implemented (it could be a noop, but only if that makes sense for + * the bucket type) + */ + +/* There is no apr_bucket_read_notimpl, because it is a required function + */ + + +/* All of the bucket types implemented by the core */ +/** + * The flush bucket type. This signifies that all data should be flushed to + * the next filter. The flush bucket should be sent with the other buckets. + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_flush; +/** + * The EOS bucket type. This signifies that there will be no more data, ever. + * All filters MUST send all data to the next filter when they receive a + * bucket of this type + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_eos; +/** + * The FILE bucket type. This bucket represents a file on disk + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_file; +/** + * The HEAP bucket type. This bucket represents a data allocated from the + * heap. + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_heap; +#if APR_HAS_MMAP +/** + * The MMAP bucket type. This bucket represents an MMAP'ed file + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_mmap; +#endif +/** + * The POOL bucket type. This bucket represents a data that was allocated + * from a pool. IF this bucket is still available when the pool is cleared, + * the data is copied on to the heap. + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_pool; +/** + * The PIPE bucket type. This bucket represents a pipe to another program. + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_pipe; +/** + * The IMMORTAL bucket type. This bucket represents a segment of data that + * the creator is willing to take responsibility for. The core will do + * nothing with the data in an immortal bucket + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_immortal; +/** + * The TRANSIENT bucket type. This bucket represents a data allocated off + * the stack. When the setaside function is called, this data is copied on + * to the heap + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_transient; +/** + * The SOCKET bucket type. This bucket represents a socket to another machine + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_socket; + + +/* ***** Simple buckets ***** */ + +/** + * Split a simple bucket into two at the given point. Most non-reference + * counting buckets that allow multiple references to the same block of + * data (eg transient and immortal) will use this as their split function + * without any additional type-specific handling. + * @param b The bucket to be split + * @param point The offset of the first byte in the new bucket + * @return APR_EINVAL if the point is not within the bucket; + * APR_ENOMEM if allocation failed; + * or APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_simple_split(apr_bucket *b, + apr_size_t point); + +/** + * Copy a simple bucket. Most non-reference-counting buckets that allow + * multiple references to the same block of data (eg transient and immortal) + * will use this as their copy function without any additional type-specific + * handling. + * @param a The bucket to copy + * @param b Returns a pointer to the new bucket + * @return APR_ENOMEM if allocation failed; + * or APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_simple_copy(apr_bucket *a, + apr_bucket **b); + + +/* ***** Shared, reference-counted buckets ***** */ + +/** + * Initialize a bucket containing reference-counted data that may be + * shared. The caller must allocate the bucket if necessary and + * initialize its type-dependent fields, and allocate and initialize + * its own private data structure. This function should only be called + * by type-specific bucket creation functions. + * @param b The bucket to initialize + * @param data A pointer to the private data structure + * with the reference count at the start + * @param start The start of the data in the bucket + * relative to the private base pointer + * @param length The length of the data in the bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_shared_make(apr_bucket *b, void *data, + apr_off_t start, + apr_size_t length); + +/** + * Decrement the refcount of the data in the bucket. This function + * should only be called by type-specific bucket destruction functions. + * @param data The private data pointer from the bucket to be destroyed + * @return TRUE or FALSE; TRUE if the reference count is now + * zero, indicating that the shared resource itself can + * be destroyed by the caller. + */ +APU_DECLARE(int) apr_bucket_shared_destroy(void *data); + +/** + * Split a bucket into two at the given point, and adjust the refcount + * to the underlying data. Most reference-counting bucket types will + * be able to use this function as their split function without any + * additional type-specific handling. + * @param b The bucket to be split + * @param point The offset of the first byte in the new bucket + * @return APR_EINVAL if the point is not within the bucket; + * APR_ENOMEM if allocation failed; + * or APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_shared_split(apr_bucket *b, + apr_size_t point); + +/** + * Copy a refcounted bucket, incrementing the reference count. Most + * reference-counting bucket types will be able to use this function + * as their copy function without any additional type-specific handling. + * @param a The bucket to copy + * @param b Returns a pointer to the new bucket + * @return APR_ENOMEM if allocation failed; + or APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_shared_copy(apr_bucket *a, + apr_bucket **b); + + +/* ***** Functions to Create Buckets of varying types ***** */ +/* + * Each bucket type foo has two initialization functions: + * apr_bucket_foo_make which sets up some already-allocated memory as a + * bucket of type foo; and apr_bucket_foo_create which allocates memory + * for the bucket, calls apr_bucket_make_foo, and initializes the + * bucket's list pointers. The apr_bucket_foo_make functions are used + * inside the bucket code to change the type of buckets in place; + * other code should call apr_bucket_foo_create. All the initialization + * functions change nothing if they fail. + */ + +/** + * Create an End of Stream bucket. This indicates that there is no more data + * coming from down the filter stack. All filters should flush at this point. + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_eos_create(apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in an EOS bucket. This indicates that there is no + * more data coming from down the filter stack. All filters should flush at + * this point. + * @param b The bucket to make into an EOS bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_eos_make(apr_bucket *b); + +/** + * Create a flush bucket. This indicates that filters should flush their + * data. There is no guarantee that they will flush it, but this is the + * best we can do. + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_flush_create(apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a FLUSH bucket. This indicates that filters + * should flush their data. There is no guarantee that they will flush it, + * but this is the best we can do. + * @param b The bucket to make into a FLUSH bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_flush_make(apr_bucket *b); + +/** + * Create a bucket referring to long-lived data. + * @param buf The data to insert into the bucket + * @param nbyte The size of the data to insert. + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_immortal_create(const char *buf, + apr_size_t nbyte, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to long-lived data + * @param b The bucket to make into a IMMORTAL bucket + * @param buf The data to insert into the bucket + * @param nbyte The size of the data to insert. + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_immortal_make(apr_bucket *b, + const char *buf, + apr_size_t nbyte); + +/** + * Create a bucket referring to data on the stack. + * @param buf The data to insert into the bucket + * @param nbyte The size of the data to insert. + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_transient_create(const char *buf, + apr_size_t nbyte, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to stack data + * @param b The bucket to make into a TRANSIENT bucket + * @param buf The data to insert into the bucket + * @param nbyte The size of the data to insert. + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_transient_make(apr_bucket *b, + const char *buf, + apr_size_t nbyte); + +/** + * Create a bucket referring to memory on the heap. If the caller asks + * for the data to be copied, this function always allocates 4K of + * memory so that more data can be added to the bucket without + * requiring another allocation. Therefore not all the data may be put + * into the bucket. If copying is not requested then the bucket takes + * over responsibility for free()ing the memory. + * @param buf The buffer to insert into the bucket + * @param nbyte The size of the buffer to insert. + * @param free_func Function to use to free the data; NULL indicates that the + * bucket should make a copy of the data + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_heap_create(const char *buf, + apr_size_t nbyte, + void (*free_func)(void *data), + apr_bucket_alloc_t *list); +/** + * Make the bucket passed in a bucket refer to heap data + * @param b The bucket to make into a HEAP bucket + * @param buf The buffer to insert into the bucket + * @param nbyte The size of the buffer to insert. + * @param free_func Function to use to free the data; NULL indicates that the + * bucket should make a copy of the data + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_heap_make(apr_bucket *b, const char *buf, + apr_size_t nbyte, + void (*free_func)(void *data)); + +/** + * Create a bucket referring to memory allocated from a pool. + * + * @param buf The buffer to insert into the bucket + * @param length The number of bytes referred to by this bucket + * @param pool The pool the memory was allocated from + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_pool_create(const char *buf, + apr_size_t length, + apr_pool_t *pool, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to pool data + * @param b The bucket to make into a pool bucket + * @param buf The buffer to insert into the bucket + * @param length The number of bytes referred to by this bucket + * @param pool The pool the memory was allocated from + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_pool_make(apr_bucket *b, const char *buf, + apr_size_t length, + apr_pool_t *pool); + +#if APR_HAS_MMAP +/** + * Create a bucket referring to mmap()ed memory. + * @param mm The mmap to insert into the bucket + * @param start The offset of the first byte in the mmap + * that this bucket refers to + * @param length The number of bytes referred to by this bucket + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_mmap_create(apr_mmap_t *mm, + apr_off_t start, + apr_size_t length, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to an MMAP'ed file + * @param b The bucket to make into a MMAP bucket + * @param mm The mmap to insert into the bucket + * @param start The offset of the first byte in the mmap + * that this bucket refers to + * @param length The number of bytes referred to by this bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_mmap_make(apr_bucket *b, apr_mmap_t *mm, + apr_off_t start, + apr_size_t length); +#endif + +/** + * Create a bucket referring to a socket. + * @param thissock The socket to put in the bucket + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_socket_create(apr_socket_t *thissock, + apr_bucket_alloc_t *list); +/** + * Make the bucket passed in a bucket refer to a socket + * @param b The bucket to make into a SOCKET bucket + * @param thissock The socket to put in the bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_socket_make(apr_bucket *b, + apr_socket_t *thissock); + +/** + * Create a bucket referring to a pipe. + * @param thispipe The pipe to put in the bucket + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_pipe_create(apr_file_t *thispipe, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to a pipe + * @param b The bucket to make into a PIPE bucket + * @param thispipe The pipe to put in the bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_pipe_make(apr_bucket *b, + apr_file_t *thispipe); + +/** + * Create a bucket referring to a file. + * @param fd The file to put in the bucket + * @param offset The offset where the data of interest begins in the file + * @param len The amount of data in the file we are interested in + * @param p The pool into which any needed structures should be created + * while reading from this file bucket + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + * @remark If the file is truncated such that the segment of the file + * referenced by the bucket no longer exists, an attempt to read + * from the bucket will fail with APR_EOF. + * @remark apr_brigade_insert_file() should generally be used to + * insert files into brigades, since that function can correctly + * handle large file issues. + */ +APU_DECLARE(apr_bucket *) apr_bucket_file_create(apr_file_t *fd, + apr_off_t offset, + apr_size_t len, + apr_pool_t *p, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to a file + * @param b The bucket to make into a FILE bucket + * @param fd The file to put in the bucket + * @param offset The offset where the data of interest begins in the file + * @param len The amount of data in the file we are interested in + * @param p The pool into which any needed structures should be created + * while reading from this file bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_file_make(apr_bucket *b, apr_file_t *fd, + apr_off_t offset, + apr_size_t len, apr_pool_t *p); + +/** + * Enable or disable memory-mapping for a FILE bucket (default is enabled) + * @param b The bucket + * @param enabled Whether memory-mapping should be enabled + * @return APR_SUCCESS normally, or an error code if the operation fails + */ +APU_DECLARE(apr_status_t) apr_bucket_file_enable_mmap(apr_bucket *b, + int enabled); + +/** + * Set the size of the read buffer allocated by a FILE bucket (default + * is @a APR_BUCKET_BUFF_SIZE) + * memory-mapping is disabled only) + * @param b The bucket + * @param size Size of the allocated buffers + * @return APR_SUCCESS normally, or an error code if the operation fails + * @remark Relevant/used only when memory-mapping is disabled (@see + * apr_bucket_file_enable_mmap) + */ +APU_DECLARE(apr_status_t) apr_bucket_file_set_buf_size(apr_bucket *e, + apr_size_t size); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_BUCKETS_H */ diff --git a/c/dependencies/linux/apr/include/apr_crypto.h b/c/dependencies/linux/apr/include/apr_crypto.h new file mode 100644 index 00000000..b90f3fec --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_crypto.h @@ -0,0 +1,507 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_CRYPTO_H +#define APR_CRYPTO_H + +#include "apu.h" +#include "apr_pools.h" +#include "apr_tables.h" +#include "apr_hash.h" +#include "apu_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_crypto.h + * @brief APR-UTIL Crypto library + */ +/** + * @defgroup APR_Util_Crypto Crypto routines + * @ingroup APR_Util + * @{ + */ + +#if APU_HAVE_CRYPTO + +#ifndef APU_CRYPTO_RECOMMENDED_DRIVER +#if APU_HAVE_COMMONCRYPTO +#define APU_CRYPTO_RECOMMENDED_DRIVER "commoncrypto" +#else +#if APU_HAVE_OPENSSL +#define APU_CRYPTO_RECOMMENDED_DRIVER "openssl" +#else +#if APU_HAVE_NSS +#define APU_CRYPTO_RECOMMENDED_DRIVER "nss" +#else +#if APU_HAVE_MSCNG +#define APU_CRYPTO_RECOMMENDED_DRIVER "mscng" +#else +#if APU_HAVE_MSCAPI +#define APU_CRYPTO_RECOMMENDED_DRIVER "mscapi" +#else +#endif +#endif +#endif +#endif +#endif +#endif + +/** + * Symmetric Key types understood by the library. + * + * NOTE: It is expected that this list will grow over time. + * + * Interoperability Matrix: + * + * The matrix is based on the testcrypto.c unit test, which attempts to + * test whether a simple encrypt/decrypt will succeed, as well as testing + * whether an encrypted string by one library can be decrypted by the + * others. + * + * Some libraries will successfully encrypt and decrypt their own data, + * but won't decrypt data from another library. It is hoped that over + * time these anomalies will be found and fixed, but until then it is + * recommended that ciphers are chosen that interoperate across platform. + * + * An X below means the test passes, it does not necessarily mean that + * encryption performed is correct or secure. Applications should stick + * to ciphers that pass the interoperablity tests on the right hand side + * of the table. + * + * Aligned data is data whose length is a multiple of the block size for + * the chosen cipher. Padded data is data that is not aligned by block + * size and must be padded by the crypto library. + * + * OpenSSL CommonCrypto NSS Interop + * Align Pad Align Pad Align Pad Align Pad + * 3DES_192/CBC X X X X X X X X + * 3DES_192/ECB X X X X + * AES_256/CBC X X X X X X X X + * AES_256/ECB X X X X X X + * AES_192/CBC X X X X X X + * AES_192/ECB X X X X X + * AES_128/CBC X X X X X X + * AES_128/ECB X X X X X + * + * Conclusion: for padded data, use 3DES_192/CBC or AES_256/CBC. For + * aligned data, use 3DES_192/CBC, AES_256/CBC or AES_256/ECB. + */ + +typedef enum +{ + APR_KEY_NONE, APR_KEY_3DES_192, /** 192 bit (3-Key) 3DES */ + APR_KEY_AES_128, /** 128 bit AES */ + APR_KEY_AES_192, /** 192 bit AES */ + APR_KEY_AES_256 +/** 256 bit AES */ +} apr_crypto_block_key_type_e; + +typedef enum +{ + APR_MODE_NONE, /** An error condition */ + APR_MODE_ECB, /** Electronic Code Book */ + APR_MODE_CBC +/** Cipher Block Chaining */ +} apr_crypto_block_key_mode_e; + +/* These are opaque structs. Instantiation is up to each backend */ +typedef struct apr_crypto_driver_t apr_crypto_driver_t; +typedef struct apr_crypto_t apr_crypto_t; +typedef struct apr_crypto_config_t apr_crypto_config_t; +typedef struct apr_crypto_key_t apr_crypto_key_t; +typedef struct apr_crypto_block_t apr_crypto_block_t; + +typedef struct apr_crypto_block_key_type_t { + apr_crypto_block_key_type_e type; + int keysize; + int blocksize; + int ivsize; +} apr_crypto_block_key_type_t; + +typedef struct apr_crypto_block_key_mode_t { + apr_crypto_block_key_mode_e mode; +} apr_crypto_block_key_mode_t; + +typedef struct apr_crypto_passphrase_t { + const char *pass; + apr_size_t passLen; + const unsigned char * salt; + apr_size_t saltLen; + int iterations; +} apr_crypto_passphrase_t; + +typedef struct apr_crypto_secret_t { + const unsigned char *secret; + apr_size_t secretLen; +} apr_crypto_secret_t; + +typedef enum { + /** Key is derived from a passphrase */ + APR_CRYPTO_KTYPE_PASSPHRASE = 1, + /** Key is derived from a raw key */ + APR_CRYPTO_KTYPE_SECRET = 2, +} apr_crypto_key_type; + +typedef struct apr_crypto_key_rec_t { + apr_crypto_key_type ktype; + apr_crypto_block_key_type_e type; + apr_crypto_block_key_mode_e mode; + int pad; + union { + apr_crypto_passphrase_t passphrase; + apr_crypto_secret_t secret; + } k; +} apr_crypto_key_rec_t; + +/** + * @brief Perform once-only initialisation. Call once only. + * + * @param pool - pool to register any shutdown cleanups, etc + * @return APR_NOTIMPL in case of no crypto support. + */ +APU_DECLARE(apr_status_t) apr_crypto_init(apr_pool_t *pool); + +/** + * @brief Zero out the buffer provided when the pool is cleaned up. + * + * @param pool - pool to register the cleanup + * @param buffer - buffer to zero out + * @param size - size of the buffer to zero out + */ +APU_DECLARE(apr_status_t) apr_crypto_clear(apr_pool_t *pool, void *buffer, + apr_size_t size); + +/** + * @brief Always zero out the buffer provided, without being optimized out by + * the compiler. + * + * @param buffer - buffer to zero out + * @param size - size of the buffer to zero out + */ +APU_DECLARE(apr_status_t) apr_crypto_memzero(void *buffer, apr_size_t size); + +/** + * @brief Timing attacks safe buffers comparison, where the executing time does + * not depend on the bytes compared but solely on the number of bytes. + * + * @param buf1 - first buffer to compare + * @param buf2 - second buffer to compare + * @param size - size of the buffers to compare + * @return 1 if the buffers are equals, 0 otherwise. + */ +APU_DECLARE(int) apr_crypto_equals(const void *buf1, const void *buf2, + apr_size_t size); + +/** + * @brief Get the driver struct for a name + * + * @param driver - pointer to driver struct. + * @param name - driver name + * @param params - array of initialisation parameters + * @param result - result and error message on failure + * @param pool - (process) pool to register cleanup + * @return APR_SUCCESS for success + * @return APR_ENOTIMPL for no driver (when DSO not enabled) + * @return APR_EDSOOPEN if DSO driver file can't be opened + * @return APR_ESYMNOTFOUND if the driver file doesn't contain a driver + * @remarks NSS: the params can have "dir", "key3", "cert7" and "secmod" + * keys, each followed by an equal sign and a value. Such key/value pairs can + * be delimited by space or tab. If the value contains a space, surround the + * whole key value pair in quotes: "dir=My Directory". + * @remarks OpenSSL: currently no params are supported. + */ +APU_DECLARE(apr_status_t) apr_crypto_get_driver( + const apr_crypto_driver_t **driver, + const char *name, const char *params, const apu_err_t **result, + apr_pool_t *pool); + +/** + * @brief Return the name of the driver. + * + * @param driver - The driver in use. + * @return The name of the driver. + */ +APU_DECLARE(const char *) apr_crypto_driver_name( + const apr_crypto_driver_t *driver); + +/** + * @brief Get the result of the last operation on a context. If the result + * is NULL, the operation was successful. + * @param result - the result structure + * @param f - context pointer + * @return APR_SUCCESS for success + */ +APU_DECLARE(apr_status_t) apr_crypto_error(const apu_err_t **result, + const apr_crypto_t *f); + +/** + * @brief Create a context for supporting encryption. Keys, certificates, + * algorithms and other parameters will be set per context. More than + * one context can be created at one time. A cleanup will be automatically + * registered with the given pool to guarantee a graceful shutdown. + * @param f - context pointer will be written here + * @param driver - driver to use + * @param params - array of key parameters + * @param pool - process pool + * @return APR_ENOENGINE when the engine specified does not exist. APR_EINITENGINE + * if the engine cannot be initialised. + * @remarks NSS: currently no params are supported. + * @remarks OpenSSL: the params can have "engine" as a key, followed by an equal + * sign and a value. + */ +APU_DECLARE(apr_status_t) apr_crypto_make(apr_crypto_t **f, + const apr_crypto_driver_t *driver, const char *params, + apr_pool_t *pool); + +/** + * @brief Get a hash table of key types, keyed by the name of the type against + * a pointer to apr_crypto_block_key_type_t, which in turn begins with an + * integer. + * + * @param types - hashtable of key types keyed to constants. + * @param f - encryption context + * @return APR_SUCCESS for success + */ +APU_DECLARE(apr_status_t) apr_crypto_get_block_key_types(apr_hash_t **types, + const apr_crypto_t *f); + +/** + * @brief Get a hash table of key modes, keyed by the name of the mode against + * a pointer to apr_crypto_block_key_mode_t, which in turn begins with an + * integer. + * + * @param modes - hashtable of key modes keyed to constants. + * @param f - encryption context + * @return APR_SUCCESS for success + */ +APU_DECLARE(apr_status_t) apr_crypto_get_block_key_modes(apr_hash_t **modes, + const apr_crypto_t *f); + +/** + * @brief Create a key from the provided secret or passphrase. The key is cleaned + * up when the context is cleaned, and may be reused with multiple encryption + * or decryption operations. + * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If + * *key is not NULL, *key must point at a previously created structure. + * @param key The key returned, see note. + * @param rec The key record, from which the key will be derived. + * @param f The context to use. + * @param p The pool to use. + * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend + * error occurred while generating the key. APR_ENOCIPHER if the type or mode + * is not supported by the particular backend. APR_EKEYTYPE if the key type is + * not known. APR_EPADDING if padding was requested but is not supported. + * APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_key(apr_crypto_key_t **key, + const apr_crypto_key_rec_t *rec, const apr_crypto_t *f, apr_pool_t *p); + +/** + * @brief Create a key from the given passphrase. By default, the PBKDF2 + * algorithm is used to generate the key from the passphrase. It is expected + * that the same pass phrase will generate the same key, regardless of the + * backend crypto platform used. The key is cleaned up when the context + * is cleaned, and may be reused with multiple encryption or decryption + * operations. + * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If + * *key is not NULL, *key must point at a previously created structure. + * @param key The key returned, see note. + * @param ivSize The size of the initialisation vector will be returned, based + * on whether an IV is relevant for this type of crypto. + * @param pass The passphrase to use. + * @param passLen The passphrase length in bytes + * @param salt The salt to use. + * @param saltLen The salt length in bytes + * @param type 3DES_192, AES_128, AES_192, AES_256. + * @param mode Electronic Code Book / Cipher Block Chaining. + * @param doPad Pad if necessary. + * @param iterations Number of iterations to use in algorithm + * @param f The context to use. + * @param p The pool to use. + * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend + * error occurred while generating the key. APR_ENOCIPHER if the type or mode + * is not supported by the particular backend. APR_EKEYTYPE if the key type is + * not known. APR_EPADDING if padding was requested but is not supported. + * APR_ENOTIMPL if not implemented. + * @deprecated Replaced by apr_crypto_key(). + */ +APU_DECLARE(apr_status_t) apr_crypto_passphrase(apr_crypto_key_t **key, + apr_size_t *ivSize, const char *pass, apr_size_t passLen, + const unsigned char * salt, apr_size_t saltLen, + const apr_crypto_block_key_type_e type, + const apr_crypto_block_key_mode_e mode, const int doPad, + const int iterations, const apr_crypto_t *f, apr_pool_t *p); + +/** + * @brief Initialise a context for encrypting arbitrary data using the given key. + * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If + * *ctx is not NULL, *ctx must point at a previously created structure. + * @param ctx The block context returned, see note. + * @param iv Optional initialisation vector. If the buffer pointed to is NULL, + * an IV will be created at random, in space allocated from the pool. + * If the buffer pointed to is not NULL, the IV in the buffer will be + * used. + * @param key The key structure to use. + * @param blockSize The block size of the cipher. + * @param p The pool to use. + * @return Returns APR_ENOIV if an initialisation vector is required but not specified. + * Returns APR_EINIT if the backend failed to initialise the context. Returns + * APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_encrypt_init( + apr_crypto_block_t **ctx, const unsigned char **iv, + const apr_crypto_key_t *key, apr_size_t *blockSize, apr_pool_t *p); + +/** + * @brief Encrypt data provided by in, write it to out. + * @note The number of bytes written will be written to outlen. If + * out is NULL, outlen will contain the maximum size of the + * buffer needed to hold the data, including any data + * generated by apr_crypto_block_encrypt_finish below. If *out points + * to NULL, a buffer sufficiently large will be created from + * the pool provided. If *out points to a not-NULL value, this + * value will be used as a buffer instead. + * @param out Address of a buffer to which data will be written, + * see note. + * @param outlen Length of the output will be written here. + * @param in Address of the buffer to read. + * @param inlen Length of the buffer to read. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if + * not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_encrypt(unsigned char **out, + apr_size_t *outlen, const unsigned char *in, apr_size_t inlen, + apr_crypto_block_t *ctx); + +/** + * @brief Encrypt final data block, write it to out. + * @note If necessary the final block will be written out after being + * padded. Typically the final block will be written to the + * same buffer used by apr_crypto_block_encrypt, offset by the + * number of bytes returned as actually written by the + * apr_crypto_block_encrypt() call. After this call, the context + * is cleaned and can be reused by apr_crypto_block_encrypt_init(). + * @param out Address of a buffer to which data will be written. This + * buffer must already exist, and is usually the same + * buffer used by apr_evp_crypt(). See note. + * @param outlen Length of the output will be written here. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. + * @return APR_EPADDING if padding was enabled and the block was incorrectly + * formatted. + * @return APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_encrypt_finish(unsigned char *out, + apr_size_t *outlen, apr_crypto_block_t *ctx); + +/** + * @brief Initialise a context for decrypting arbitrary data using the given key. + * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If + * *ctx is not NULL, *ctx must point at a previously created structure. + * @param ctx The block context returned, see note. + * @param blockSize The block size of the cipher. + * @param iv Optional initialisation vector. + * @param key The key structure to use. + * @param p The pool to use. + * @return Returns APR_ENOIV if an initialisation vector is required but not specified. + * Returns APR_EINIT if the backend failed to initialise the context. Returns + * APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_decrypt_init( + apr_crypto_block_t **ctx, apr_size_t *blockSize, + const unsigned char *iv, const apr_crypto_key_t *key, apr_pool_t *p); + +/** + * @brief Decrypt data provided by in, write it to out. + * @note The number of bytes written will be written to outlen. If + * out is NULL, outlen will contain the maximum size of the + * buffer needed to hold the data, including any data + * generated by apr_crypto_block_decrypt_finish below. If *out points + * to NULL, a buffer sufficiently large will be created from + * the pool provided. If *out points to a not-NULL value, this + * value will be used as a buffer instead. + * @param out Address of a buffer to which data will be written, + * see note. + * @param outlen Length of the output will be written here. + * @param in Address of the buffer to read. + * @param inlen Length of the buffer to read. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if + * not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_decrypt(unsigned char **out, + apr_size_t *outlen, const unsigned char *in, apr_size_t inlen, + apr_crypto_block_t *ctx); + +/** + * @brief Decrypt final data block, write it to out. + * @note If necessary the final block will be written out after being + * padded. Typically the final block will be written to the + * same buffer used by apr_crypto_block_decrypt, offset by the + * number of bytes returned as actually written by the + * apr_crypto_block_decrypt() call. After this call, the context + * is cleaned and can be reused by apr_crypto_block_decrypt_init(). + * @param out Address of a buffer to which data will be written. This + * buffer must already exist, and is usually the same + * buffer used by apr_evp_crypt(). See note. + * @param outlen Length of the output will be written here. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. + * @return APR_EPADDING if padding was enabled and the block was incorrectly + * formatted. + * @return APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_decrypt_finish(unsigned char *out, + apr_size_t *outlen, apr_crypto_block_t *ctx); + +/** + * @brief Clean encryption / decryption context. + * @note After cleanup, a context is free to be reused if necessary. + * @param ctx The block context to use. + * @return Returns APR_ENOTIMPL if not supported. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_cleanup(apr_crypto_block_t *ctx); + +/** + * @brief Clean encryption / decryption context. + * @note After cleanup, a context is free to be reused if necessary. + * @param f The context to use. + * @return Returns APR_ENOTIMPL if not supported. + */ +APU_DECLARE(apr_status_t) apr_crypto_cleanup(apr_crypto_t *f); + +/** + * @brief Shutdown the crypto library. + * @note After shutdown, it is expected that the init function can be called again. + * @param driver - driver to use + * @return Returns APR_ENOTIMPL if not supported. + */ +APU_DECLARE(apr_status_t) apr_crypto_shutdown( + const apr_crypto_driver_t *driver); + +#endif /* APU_HAVE_CRYPTO */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/c/dependencies/linux/apr/include/apr_cstr.h b/c/dependencies/linux/apr/include/apr_cstr.h new file mode 100644 index 00000000..3f1b1a09 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_cstr.h @@ -0,0 +1,292 @@ +/* ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * ==================================================================== + */ + +/** + * @file apr_cstr.h + * @brief C string goodies. + */ + +#ifndef APR_CSTR_H +#define APR_CSTR_H + +#include /* for apr_size_t */ +#include /* for apr_pool_t */ +#include /* for apr_array_header_t */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_cstr C (POSIX) locale string functions + * @ingroup apr_strings + * + * The apr_cstr_* functions provide traditional C char * string text handling, + * and notabilty they treat all text in the C (a.k.a. POSIX) locale using the + * minimal POSIX character set, represented in either ASCII or a corresponding + * EBCDIC subset. + * + * Character values outside of that set are treated as opaque bytes, and all + * multi-byte character sequences are handled as individual distinct octets. + * + * Multi-byte characters sequences whose octets fall in the ASCII range cause + * unexpected results, such as in the ISO-2022-JP code page where ASCII octets + * occur within both shift-state and multibyte sequences. + * + * In the case of the UTF-8 encoding, all multibyte characters all fall outside + * of the C/POSIX range of characters, so these functions are generally safe + * to use on UTF-8 strings. The programmer must be aware that each octet may + * not represent a distinct printable character in such encodings. + * + * The standard C99/POSIX string functions, rather than apr_cstr, should be + * used in all cases where the current locale and encoding of the text is + * significant. + * @{ + */ + + +/** Divide @a input into substrings, interpreting any char from @a sep + * as a token separator. + * + * Return an array of copies of those substrings (plain const char*), + * allocating both the array and the copies in @a pool. + * + * None of the elements added to the array contain any of the + * characters in @a sep_chars, and none of the new elements are empty + * (thus, it is possible that the returned array will have length + * zero). + * + * If @a chop_whitespace is TRUE, then remove leading and trailing + * whitespace from the returned strings. + * + * @since New in 1.6 + */ +APR_DECLARE(apr_array_header_t *) apr_cstr_split(const char *input, + const char *sep_chars, + int chop_whitespace, + apr_pool_t *pool); + +/** Like apr_cstr_split(), but append to existing @a array instead of + * creating a new one. Allocate the copied substrings in @a pool + * (i.e., caller decides whether or not to pass @a array->pool as @a pool). + * + * @since New in 1.6 + */ +APR_DECLARE(void) apr_cstr_split_append(apr_array_header_t *array, + const char *input, + const char *sep_chars, + int chop_whitespace, + apr_pool_t *pool); + + +/** Return @c TRUE iff @a str matches any of the elements of @a list, a list + * of zero or more glob patterns. + * + * @since New in 1.6 + */ +APR_DECLARE(int) apr_cstr_match_glob_list(const char *str, + const apr_array_header_t *list); + +/** Return @c TRUE iff @a str exactly matches any of the elements of @a list. + * + * @since New in 1.6 + */ +APR_DECLARE(int) apr_cstr_match_list(const char *str, + const apr_array_header_t *list); + +/** + * Get the next token from @a *str interpreting any char from @a sep as a + * token separator. Separators at the beginning of @a str will be skipped. + * Returns a pointer to the beginning of the first token in @a *str or NULL + * if no token is left. Modifies @a str such that the next call will return + * the next token. + * + * @note The content of @a *str may be modified by this function. + * + * @since New in 1.6. + */ +APR_DECLARE(char *) apr_cstr_tokenize(const char *sep, char **str); + +/** + * Return the number of line breaks in @a msg, allowing any kind of newline + * termination (CR, LF, CRLF, or LFCR), even inconsistent. + * + * @since New in 1.6. + */ +APR_DECLARE(int) apr_cstr_count_newlines(const char *msg); + +#if 0 /* XXX: stringbuf logic is not present in APR */ +/** + * Return a cstring which is the concatenation of @a strings (an array + * of char *) each followed by @a separator (that is, @a separator + * will also end the resulting string). Allocate the result in @a pool. + * If @a strings is empty, then return the empty string. + * + * @since New in 1.6. + */ +APR_DECLARE(char *) apr_cstr_join(const apr_array_header_t *strings, + const char *separator, + apr_pool_t *pool); +#endif + +/** + * Perform a case-insensitive comparison of two strings @a atr1 and @a atr2, + * treating upper and lower case values of the 26 standard C/POSIX alphabetic + * characters as equivalent. Extended latin characters outside of this set + * are treated as unique octets, irrespective of the current locale. + * + * Returns in integer greater than, equal to, or less than 0, + * according to whether @a str1 is considered greater than, equal to, + * or less than @a str2. + * + * @since New in 1.6. + */ +APR_DECLARE(int) apr_cstr_casecmp(const char *str1, const char *str2); + +/** + * Perform a case-insensitive comparison of two strings @a atr1 and @a atr2, + * treating upper and lower case values of the 26 standard C/POSIX alphabetic + * characters as equivalent. Extended latin characters outside of this set + * are treated as unique octets, irrespective of the current locale. + * + * Returns in integer greater than, equal to, or less than 0, + * according to whether @a str1 is considered greater than, equal to, + * or less than @a str2. + * + * @since New in 1.6. + */ +APR_DECLARE(int) apr_cstr_casecmpn(const char *str1, + const char *str2, + apr_size_t n); + +/** + * Parse the C string @a str into a 64 bit number, and return it in @a *n. + * Assume that the number is represented in base @a base. + * Raise an error if conversion fails (e.g. due to overflow), or if the + * converted number is smaller than @a minval or larger than @a maxval. + * + * Leading whitespace in @a str is skipped in a locale-dependent way. + * After that, the string may contain an optional '+' (positive, default) + * or '-' (negative) character, followed by an optional '0x' prefix if + * @a base is 0 or 16, followed by numeric digits appropriate for the base. + * If there are any more characters after the numeric digits, an error is + * returned. + * + * If @a base is zero, then a leading '0x' or '0X' prefix means hexadecimal, + * else a leading '0' means octal (implemented, though not documented, in + * apr_strtoi64() in APR 0.9.0 through 1.5.0), else use base ten. + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_strtoi64(apr_int64_t *n, const char *str, + apr_int64_t minval, + apr_int64_t maxval, + int base); + +/** + * Parse the C string @a str into a 64 bit number, and return it in @a *n. + * Assume that the number is represented in base 10. + * Raise an error if conversion fails (e.g. due to overflow). + * + * The behaviour otherwise is as described for apr_cstr_strtoi64(). + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_atoi64(apr_int64_t *n, const char *str); + +/** + * Parse the C string @a str into a 32 bit number, and return it in @a *n. + * Assume that the number is represented in base 10. + * Raise an error if conversion fails (e.g. due to overflow). + * + * The behaviour otherwise is as described for apr_cstr_strtoi64(). + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_atoi(int *n, const char *str); + +/** + * Parse the C string @a str into an unsigned 64 bit number, and return + * it in @a *n. Assume that the number is represented in base @a base. + * Raise an error if conversion fails (e.g. due to overflow), or if the + * converted number is smaller than @a minval or larger than @a maxval. + * + * Leading whitespace in @a str is skipped in a locale-dependent way. + * After that, the string may contain an optional '+' (positive, default) + * or '-' (negative) character, followed by an optional '0x' prefix if + * @a base is 0 or 16, followed by numeric digits appropriate for the base. + * If there are any more characters after the numeric digits, an error is + * returned. + * + * If @a base is zero, then a leading '0x' or '0X' prefix means hexadecimal, + * else a leading '0' means octal (as implemented, though not documented, in + * apr_strtoi64(), else use base ten. + * + * @warning The implementation returns APR_ERANGE if the parsed number + * is greater than APR_INT64_MAX, even if it is not greater than @a maxval. + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_strtoui64(apr_uint64_t *n, const char *str, + apr_uint64_t minval, + apr_uint64_t maxval, + int base); + +/** + * Parse the C string @a str into an unsigned 64 bit number, and return + * it in @a *n. Assume that the number is represented in base 10. + * Raise an error if conversion fails (e.g. due to overflow). + * + * The behaviour otherwise is as described for apr_cstr_strtoui64(), + * including the upper limit of APR_INT64_MAX. + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_atoui64(apr_uint64_t *n, const char *str); + +/** + * Parse the C string @a str into an unsigned 32 bit number, and return + * it in @a *n. Assume that the number is represented in base 10. + * Raise an error if conversion fails (e.g. due to overflow). + * + * The behaviour otherwise is as described for apr_cstr_strtoui64(), + * including the upper limit of APR_INT64_MAX. + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_atoui(unsigned int *n, const char *str); + +/** + * Skip the common prefix @a prefix from the C string @a str, and return + * a pointer to the next character after the prefix. + * Return @c NULL if @a str does not start with @a prefix. + * + * @since New in 1.6. + */ +APR_DECLARE(const char *) apr_cstr_skip_prefix(const char *str, + const char *prefix); + +/** @} */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* SVN_STRING_H */ diff --git a/c/dependencies/linux/apr/include/apr_date.h b/c/dependencies/linux/apr/include/apr_date.h new file mode 100644 index 00000000..b098b542 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_date.h @@ -0,0 +1,106 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_DATE_H +#define APR_DATE_H + +/** + * @file apr_date.h + * @brief APR-UTIL date routines + */ + +/** + * @defgroup APR_Util_Date Date routines + * @ingroup APR_Util + * @{ + */ + +/* + * apr_date.h: prototypes for date parsing utility routines + */ + +#include "apu.h" +#include "apr_time.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** A bad date. */ +#define APR_DATE_BAD ((apr_time_t)0) + +/** + * Compare a string to a mask + * @param data The string to compare + * @param mask Mask characters (arbitrary maximum is 256 characters): + *
+ *   '\@' - uppercase letter
+ *   '\$' - lowercase letter
+ *   '\&' - hex digit
+ *   '#' - digit
+ *   '~' - digit or space
+ *   '*' - swallow remaining characters
+ * 
+ * @remark The mask tests for an exact match for any other character + * @return 1 if the string matches, 0 otherwise + */ +APU_DECLARE(int) apr_date_checkmask(const char *data, const char *mask); + +/** + * Parses an HTTP date in one of three standard forms: + *
+ *     Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
+ *     Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
+ *     Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format
+ * 
+ * @param date The date in one of the three formats above + * @return the apr_time_t number of microseconds since 1 Jan 1970 GMT, or + * 0 if this would be out of range or if the date is invalid. + */ +APU_DECLARE(apr_time_t) apr_date_parse_http(const char *date); + +/** + * Parses a string resembling an RFC 822 date. This is meant to be + * leinent in its parsing of dates. Hence, this will parse a wider + * range of dates than apr_date_parse_http. + * + * The prominent mailer (or poster, if mailer is unknown) that has + * been seen in the wild is included for the unknown formats. + *
+ *     Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
+ *     Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
+ *     Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format
+ *     Sun, 6 Nov 1994 08:49:37 GMT   ; RFC 822, updated by RFC 1123
+ *     Sun, 06 Nov 94 08:49:37 GMT    ; RFC 822
+ *     Sun, 6 Nov 94 08:49:37 GMT     ; RFC 822
+ *     Sun, 06 Nov 94 08:49 GMT       ; Unknown [drtr\@ast.cam.ac.uk] 
+ *     Sun, 6 Nov 94 08:49 GMT        ; Unknown [drtr\@ast.cam.ac.uk]
+ *     Sun, 06 Nov 94 8:49:37 GMT     ; Unknown [Elm 70.85]
+ *     Sun, 6 Nov 94 8:49:37 GMT      ; Unknown [Elm 70.85] 
+ * 
+ * + * @param date The date in one of the formats above + * @return the apr_time_t number of microseconds since 1 Jan 1970 GMT, or + * 0 if this would be out of range or if the date is invalid. + */ +APU_DECLARE(apr_time_t) apr_date_parse_rfc(const char *date); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_DATE_H */ diff --git a/c/dependencies/linux/apr/include/apr_dbd.h b/c/dependencies/linux/apr/include/apr_dbd.h new file mode 100644 index 00000000..9912612b --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_dbd.h @@ -0,0 +1,549 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* Overview of what this is and does: + * http://www.apache.org/~niq/dbd.html + */ + +#ifndef APR_DBD_H +#define APR_DBD_H + +#include "apu.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_dbd.h + * @brief APR-UTIL DBD library + */ +/** + * @defgroup APR_Util_DBD DBD routines + * @ingroup APR_Util + * @{ + */ + +/** + * Mapping of C to SQL types, used for prepared statements. + * @remarks + * For apr_dbd_p[v]query/select functions, in and out parameters are always + * const char * (i.e. regular nul terminated strings). LOB types are passed + * with four (4) arguments: payload, length, table and column, all as const + * char *, where table and column are reserved for future use by Oracle. + * @remarks + * For apr_dbd_p[v]bquery/select functions, in and out parameters are + * described next to each enumeration constant and are generally native binary + * types or some APR data type. LOB types are passed with four (4) arguments: + * payload (char*), length (apr_size_t*), table (char*) and column (char*). + * Table and column are reserved for future use by Oracle. + */ +typedef enum { + APR_DBD_TYPE_NONE, + APR_DBD_TYPE_TINY, /**< \%hhd : in, out: char* */ + APR_DBD_TYPE_UTINY, /**< \%hhu : in, out: unsigned char* */ + APR_DBD_TYPE_SHORT, /**< \%hd : in, out: short* */ + APR_DBD_TYPE_USHORT, /**< \%hu : in, out: unsigned short* */ + APR_DBD_TYPE_INT, /**< \%d : in, out: int* */ + APR_DBD_TYPE_UINT, /**< \%u : in, out: unsigned int* */ + APR_DBD_TYPE_LONG, /**< \%ld : in, out: long* */ + APR_DBD_TYPE_ULONG, /**< \%lu : in, out: unsigned long* */ + APR_DBD_TYPE_LONGLONG, /**< \%lld : in, out: apr_int64_t* */ + APR_DBD_TYPE_ULONGLONG, /**< \%llu : in, out: apr_uint64_t* */ + APR_DBD_TYPE_FLOAT, /**< \%f : in, out: float* */ + APR_DBD_TYPE_DOUBLE, /**< \%lf : in, out: double* */ + APR_DBD_TYPE_STRING, /**< \%s : in: char*, out: char** */ + APR_DBD_TYPE_TEXT, /**< \%pDt : in: char*, out: char** */ + APR_DBD_TYPE_TIME, /**< \%pDi : in: char*, out: char** */ + APR_DBD_TYPE_DATE, /**< \%pDd : in: char*, out: char** */ + APR_DBD_TYPE_DATETIME, /**< \%pDa : in: char*, out: char** */ + APR_DBD_TYPE_TIMESTAMP, /**< \%pDs : in: char*, out: char** */ + APR_DBD_TYPE_ZTIMESTAMP, /**< \%pDz : in: char*, out: char** */ + APR_DBD_TYPE_BLOB, /**< \%pDb : in: char* apr_size_t* char* char*, out: apr_bucket_brigade* */ + APR_DBD_TYPE_CLOB, /**< \%pDc : in: char* apr_size_t* char* char*, out: apr_bucket_brigade* */ + APR_DBD_TYPE_NULL /**< \%pDn : in: void*, out: void** */ +} apr_dbd_type_e; + +/* These are opaque structs. Instantiation is up to each backend */ +typedef struct apr_dbd_driver_t apr_dbd_driver_t; +typedef struct apr_dbd_t apr_dbd_t; +typedef struct apr_dbd_transaction_t apr_dbd_transaction_t; +typedef struct apr_dbd_results_t apr_dbd_results_t; +typedef struct apr_dbd_row_t apr_dbd_row_t; +typedef struct apr_dbd_prepared_t apr_dbd_prepared_t; + +/** apr_dbd_init: perform once-only initialisation. Call once only. + * + * @param pool - pool to register any shutdown cleanups, etc + */ +APU_DECLARE(apr_status_t) apr_dbd_init(apr_pool_t *pool); + +/** apr_dbd_get_driver: get the driver struct for a name + * + * @param pool - (process) pool to register cleanup + * @param name - driver name + * @param driver - pointer to driver struct. + * @return APR_SUCCESS for success + * @return APR_ENOTIMPL for no driver (when DSO not enabled) + * @return APR_EDSOOPEN if DSO driver file can't be opened + * @return APR_ESYMNOTFOUND if the driver file doesn't contain a driver + */ +APU_DECLARE(apr_status_t) apr_dbd_get_driver(apr_pool_t *pool, const char *name, + const apr_dbd_driver_t **driver); + +/** apr_dbd_open_ex: open a connection to a backend + * + * @param driver - driver struct. + * @param pool - working pool + * @param params - arguments to driver (implementation-dependent) + * @param handle - pointer to handle to return + * @param error - descriptive error. + * @return APR_SUCCESS for success + * @return APR_EGENERAL if driver exists but connection failed + * @remarks PostgreSQL: the params is passed directly to the PQconnectdb() + * function (check PostgreSQL documentation for more details on the syntax). + * @remarks SQLite2: the params is split on a colon, with the first part used + * as the filename and second part converted to an integer and used as file + * mode. + * @remarks SQLite3: the params is passed directly to the sqlite3_open() + * function as a filename to be opened (check SQLite3 documentation for more + * details). + * @remarks Oracle: the params can have "user", "pass", "dbname" and "server" + * keys, each followed by an equal sign and a value. Such key/value pairs can + * be delimited by space, CR, LF, tab, semicolon, vertical bar or comma. + * @remarks MySQL: the params can have "host", "port", "user", "pass", + * "dbname", "sock", "flags" "fldsz", "group" and "reconnect" keys, each + * followed by an equal sign and a value. Such key/value pairs can be + * delimited by space, CR, LF, tab, semicolon, vertical bar or comma. For + * now, "flags" can only recognise CLIENT_FOUND_ROWS (check MySQL manual for + * details). The value associated with "fldsz" determines maximum amount of + * memory (in bytes) for each of the fields in the result set of prepared + * statements. By default, this value is 1 MB. The value associated with + * "group" determines which group from configuration file to use (see + * MYSQL_READ_DEFAULT_GROUP option of mysql_options() in MySQL manual). + * Reconnect is set to 1 by default (i.e. true). + */ +APU_DECLARE(apr_status_t) apr_dbd_open_ex(const apr_dbd_driver_t *driver, + apr_pool_t *pool, const char *params, + apr_dbd_t **handle, + const char **error); + +/** apr_dbd_open: open a connection to a backend + * + * @param driver - driver struct. + * @param pool - working pool + * @param params - arguments to driver (implementation-dependent) + * @param handle - pointer to handle to return + * @return APR_SUCCESS for success + * @return APR_EGENERAL if driver exists but connection failed + * @see apr_dbd_open_ex + */ +APU_DECLARE(apr_status_t) apr_dbd_open(const apr_dbd_driver_t *driver, + apr_pool_t *pool, const char *params, + apr_dbd_t **handle); + +/** apr_dbd_close: close a connection to a backend + * + * @param driver - driver struct. + * @param handle - handle to close + * @return APR_SUCCESS for success or error status + */ +APU_DECLARE(apr_status_t) apr_dbd_close(const apr_dbd_driver_t *driver, + apr_dbd_t *handle); + +/* apr-function-shaped versions of things */ + +/** apr_dbd_name: get the name of the driver + * + * @param driver - the driver + * @return - name + */ +APU_DECLARE(const char*) apr_dbd_name(const apr_dbd_driver_t *driver); + +/** apr_dbd_native_handle: get native database handle of the underlying db + * + * @param driver - the driver + * @param handle - apr_dbd handle + * @return - native handle + */ +APU_DECLARE(void*) apr_dbd_native_handle(const apr_dbd_driver_t *driver, + apr_dbd_t *handle); + +/** check_conn: check status of a database connection + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection to check + * @return APR_SUCCESS or error + */ +APU_DECLARE(int) apr_dbd_check_conn(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle); + +/** apr_dbd_set_dbname: select database name. May be a no-op if not supported. + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param name - the database to select + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_set_dbname(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, const char *name); + +/** apr_dbd_transaction_start: start a transaction. May be a no-op. + * + * @param driver - the driver + * @param pool - a pool to use for error messages (if any). + * @param handle - the db connection + * @param trans - ptr to a transaction. May be null on entry + * @return 0 for success or error code + * @remarks Note that transaction modes, set by calling + * apr_dbd_transaction_mode_set(), will affect all query/select calls within + * a transaction. By default, any error in query/select during a transaction + * will cause the transaction to inherit the error code and any further + * query/select calls will fail immediately. Put transaction in "ignore + * errors" mode to avoid that. Use "rollback" mode to do explicit rollback. + */ +APU_DECLARE(int) apr_dbd_transaction_start(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_t *handle, + apr_dbd_transaction_t **trans); + +/** apr_dbd_transaction_end: end a transaction + * (commit on success, rollback on error). + * May be a no-op. + * + * @param driver - the driver + * @param handle - the db connection + * @param trans - the transaction. + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_transaction_end(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_transaction_t *trans); + +#define APR_DBD_TRANSACTION_COMMIT 0x00 /**< commit the transaction */ +#define APR_DBD_TRANSACTION_ROLLBACK 0x01 /**< rollback the transaction */ +#define APR_DBD_TRANSACTION_IGNORE_ERRORS 0x02 /**< ignore transaction errors */ + +/** apr_dbd_transaction_mode_get: get the mode of transaction + * + * @param driver - the driver + * @param trans - the transaction + * @return mode of transaction + */ +APU_DECLARE(int) apr_dbd_transaction_mode_get(const apr_dbd_driver_t *driver, + apr_dbd_transaction_t *trans); + +/** apr_dbd_transaction_mode_set: set the mode of transaction + * + * @param driver - the driver + * @param trans - the transaction + * @param mode - new mode of the transaction + * @return the mode of transaction in force after the call + */ +APU_DECLARE(int) apr_dbd_transaction_mode_set(const apr_dbd_driver_t *driver, + apr_dbd_transaction_t *trans, + int mode); + +/** apr_dbd_query: execute an SQL query that doesn't return a result set + * + * @param driver - the driver + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the SQL statement to execute + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_query(const apr_dbd_driver_t *driver, apr_dbd_t *handle, + int *nrows, const char *statement); + +/** apr_dbd_select: execute an SQL query that returns a result set + * + * @param driver - the driver + * @param pool - pool to allocate the result set + * @param handle - the connection + * @param res - pointer to result set pointer. May point to NULL on entry + * @param statement - the SQL statement to execute + * @param random - 1 to support random access to results (seek any row); + * 0 to support only looping through results in order + * (async access - faster) + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_select(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, apr_dbd_results_t **res, + const char *statement, int random); + +/** apr_dbd_num_cols: get the number of columns in a results set + * + * @param driver - the driver + * @param res - result set. + * @return number of columns + */ +APU_DECLARE(int) apr_dbd_num_cols(const apr_dbd_driver_t *driver, + apr_dbd_results_t *res); + +/** apr_dbd_num_tuples: get the number of rows in a results set + * of a synchronous select + * + * @param driver - the driver + * @param res - result set. + * @return number of rows, or -1 if the results are asynchronous + */ +APU_DECLARE(int) apr_dbd_num_tuples(const apr_dbd_driver_t *driver, + apr_dbd_results_t *res); + +/** apr_dbd_get_row: get a row from a result set + * + * @param driver - the driver + * @param pool - pool to allocate the row + * @param res - result set pointer + * @param row - pointer to row pointer. May point to NULL on entry + * @param rownum - row number (counting from 1), or -1 for "next row". + * Ignored if random access is not supported. + * @return 0 for success, -1 for rownum out of range or data finished + */ +APU_DECLARE(int) apr_dbd_get_row(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_results_t *res, apr_dbd_row_t **row, + int rownum); + +/** apr_dbd_get_entry: get an entry from a row + * + * @param driver - the driver + * @param row - row pointer + * @param col - entry number + * @return value from the row, or NULL if col is out of bounds. + */ +APU_DECLARE(const char*) apr_dbd_get_entry(const apr_dbd_driver_t *driver, + apr_dbd_row_t *row, int col); + +/** apr_dbd_get_name: get an entry name from a result set + * + * @param driver - the driver + * @param res - result set pointer + * @param col - entry number + * @return name of the entry, or NULL if col is out of bounds. + */ +APU_DECLARE(const char*) apr_dbd_get_name(const apr_dbd_driver_t *driver, + apr_dbd_results_t *res, int col); + + +/** apr_dbd_error: get current error message (if any) + * + * @param driver - the driver + * @param handle - the connection + * @param errnum - error code from operation that returned an error + * @return the database current error message, or message for errnum + * (implementation-dependent whether errnum is ignored) + */ +APU_DECLARE(const char*) apr_dbd_error(const apr_dbd_driver_t *driver, + apr_dbd_t *handle, int errnum); + +/** apr_dbd_escape: escape a string so it is safe for use in query/select + * + * @param driver - the driver + * @param pool - pool to alloc the result from + * @param string - the string to escape + * @param handle - the connection + * @return the escaped, safe string + */ +APU_DECLARE(const char*) apr_dbd_escape(const apr_dbd_driver_t *driver, + apr_pool_t *pool, const char *string, + apr_dbd_t *handle); + +/** apr_dbd_prepare: prepare a statement + * + * @param driver - the driver + * @param pool - pool to alloc the result from + * @param handle - the connection + * @param query - the SQL query + * @param label - A label for the prepared statement. + * use NULL for temporary prepared statements + * (eg within a Request in httpd) + * @param statement - statement to prepare. May point to null on entry. + * @return 0 for success or error code + * @remarks To specify parameters of the prepared query, use \%s, \%d etc. + * (see below for full list) in place of database specific parameter syntax + * (e.g. for PostgreSQL, this would be $1, $2, for SQLite3 this would be ? + * etc.). For instance: "SELECT name FROM customers WHERE name=%s" would be + * a query that this function understands. + * @remarks Here is the full list of format specifiers that this function + * understands and what they map to in SQL: \%hhd (TINY INT), \%hhu (UNSIGNED + * TINY INT), \%hd (SHORT), \%hu (UNSIGNED SHORT), \%d (INT), \%u (UNSIGNED + * INT), \%ld (LONG), \%lu (UNSIGNED LONG), \%lld (LONG LONG), \%llu + * (UNSIGNED LONG LONG), \%f (FLOAT, REAL), \%lf (DOUBLE PRECISION), \%s + * (VARCHAR), \%pDt (TEXT), \%pDi (TIME), \%pDd (DATE), \%pDa (DATETIME), + * \%pDs (TIMESTAMP), \%pDz (TIMESTAMP WITH TIME ZONE), \%pDb (BLOB), \%pDc + * (CLOB) and \%pDn (NULL). Not all databases have support for all these + * types, so the underlying driver will attempt the "best match" where + * possible. A \% followed by any letter not in the above list will be + * interpreted as VARCHAR (i.e. \%s). + */ +APU_DECLARE(int) apr_dbd_prepare(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, const char *query, + const char *label, + apr_dbd_prepared_t **statement); + + +/** apr_dbd_pquery: query using a prepared statement + args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param nargs - ignored (for backward compatibility only) + * @param args - args to prepared statement + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_pquery(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, int nargs, + const char **args); + +/** apr_dbd_pselect: select using a prepared statement + args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param nargs - ignored (for backward compatibility only) + * @param args - args to prepared statement + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_pselect(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, int random, + int nargs, const char **args); + +/** apr_dbd_pvquery: query using a prepared statement + args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param ... - varargs list + * @return 0 for success or error code + */ +APU_DECLARE_NONSTD(int) apr_dbd_pvquery(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, ...); + +/** apr_dbd_pvselect: select using a prepared statement + args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param ... - varargs list + * @return 0 for success or error code + */ +APU_DECLARE_NONSTD(int) apr_dbd_pvselect(const apr_dbd_driver_t *driver, + apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, + int random, ...); + +/** apr_dbd_pbquery: query using a prepared statement + binary args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_pbquery(const apr_dbd_driver_t *driver, + apr_pool_t *pool, apr_dbd_t *handle, + int *nrows, apr_dbd_prepared_t *statement, + const void **args); + +/** apr_dbd_pbselect: select using a prepared statement + binary args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_pbselect(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_t *handle, apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, int random, + const void **args); + +/** apr_dbd_pvbquery: query using a prepared statement + binary args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param ... - varargs list of binary args + * @return 0 for success or error code + */ +APU_DECLARE_NONSTD(int) apr_dbd_pvbquery(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, ...); + +/** apr_dbd_pvbselect: select using a prepared statement + binary args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param ... - varargs list of binary args + * @return 0 for success or error code + */ +APU_DECLARE_NONSTD(int) apr_dbd_pvbselect(const apr_dbd_driver_t *driver, + apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, + int random, ...); + +/** apr_dbd_datum_get: get a binary entry from a row + * + * @param driver - the driver + * @param row - row pointer + * @param col - entry number + * @param type - type of data to get + * @param data - pointer to data, allocated by the caller + * @return APR_SUCCESS on success, APR_ENOENT if data is NULL or APR_EGENERAL + */ +APU_DECLARE(apr_status_t) apr_dbd_datum_get(const apr_dbd_driver_t *driver, + apr_dbd_row_t *row, int col, + apr_dbd_type_e type, void *data); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/c/dependencies/linux/apr/include/apr_dbm.h b/c/dependencies/linux/apr/include/apr_dbm.h new file mode 100644 index 00000000..ad1b4f39 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_dbm.h @@ -0,0 +1,227 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_DBM_H +#define APR_DBM_H + +#include "apu.h" +#include "apr.h" +#include "apr_errno.h" +#include "apr_pools.h" +#include "apr_file_info.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_dbm.h + * @brief APR-UTIL DBM library + */ +/** + * @defgroup APR_Util_DBM DBM routines + * @ingroup APR_Util + * @{ + */ +/** + * Structure for referencing a dbm + */ +typedef struct apr_dbm_t apr_dbm_t; + +/** + * Structure for referencing the datum record within a dbm + */ +typedef struct +{ + /** pointer to the 'data' to retrieve/store in the DBM */ + char *dptr; + /** size of the 'data' to retrieve/store in the DBM */ + apr_size_t dsize; +} apr_datum_t; + +/* modes to open the DB */ +#define APR_DBM_READONLY 1 /**< open for read-only access */ +#define APR_DBM_READWRITE 2 /**< open for read-write access */ +#define APR_DBM_RWCREATE 3 /**< open for r/w, create if needed */ +#define APR_DBM_RWTRUNC 4 /**< open for r/w, truncating an existing + DB if present */ +/** + * Open a dbm file by file name and type of DBM + * @param dbm The newly opened database + * @param type The type of the DBM (not all may be available at run time) + *
+ *  db   for Berkeley DB files
+ *  gdbm for GDBM files
+ *  ndbm for NDBM files
+ *  sdbm for SDBM files (always available)
+ *  default for the default DBM type
+ *  
+ * @param name The dbm file name to open + * @param mode The flag value + *
+ *           APR_DBM_READONLY   open for read-only access
+ *           APR_DBM_READWRITE  open for read-write access
+ *           APR_DBM_RWCREATE   open for r/w, create if needed
+ *           APR_DBM_RWTRUNC    open for r/w, truncate if already there
+ * 
+ * @param perm Permissions to apply to if created + * @param cntxt The pool to use when creating the dbm + * @remark The dbm name may not be a true file name, as many dbm packages + * append suffixes for seperate data and index files. + * @bug In apr-util 0.9 and 1.x, the type arg was case insensitive. This + * was highly inefficient, and as of 2.x the dbm name must be provided in + * the correct case (lower case for all bundled providers) + */ + +APU_DECLARE(apr_status_t) apr_dbm_open_ex(apr_dbm_t **dbm, const char* type, + const char *name, + apr_int32_t mode, apr_fileperms_t perm, + apr_pool_t *cntxt); + + +/** + * Open a dbm file by file name + * @param dbm The newly opened database + * @param name The dbm file name to open + * @param mode The flag value + *
+ *           APR_DBM_READONLY   open for read-only access
+ *           APR_DBM_READWRITE  open for read-write access
+ *           APR_DBM_RWCREATE   open for r/w, create if needed
+ *           APR_DBM_RWTRUNC    open for r/w, truncate if already there
+ * 
+ * @param perm Permissions to apply to if created + * @param cntxt The pool to use when creating the dbm + * @remark The dbm name may not be a true file name, as many dbm packages + * append suffixes for seperate data and index files. + */ +APU_DECLARE(apr_status_t) apr_dbm_open(apr_dbm_t **dbm, const char *name, + apr_int32_t mode, apr_fileperms_t perm, + apr_pool_t *cntxt); + +/** + * Close a dbm file previously opened by apr_dbm_open + * @param dbm The database to close + */ +APU_DECLARE(void) apr_dbm_close(apr_dbm_t *dbm); + +/** + * Fetch a dbm record value by key + * @param dbm The database + * @param key The key datum to find this record + * @param pvalue The value datum retrieved for this record + */ +APU_DECLARE(apr_status_t) apr_dbm_fetch(apr_dbm_t *dbm, apr_datum_t key, + apr_datum_t *pvalue); +/** + * Store a dbm record value by key + * @param dbm The database + * @param key The key datum to store this record by + * @param value The value datum to store in this record + */ +APU_DECLARE(apr_status_t) apr_dbm_store(apr_dbm_t *dbm, apr_datum_t key, + apr_datum_t value); + +/** + * Delete a dbm record value by key + * @param dbm The database + * @param key The key datum of the record to delete + * @remark It is not an error to delete a non-existent record. + */ +APU_DECLARE(apr_status_t) apr_dbm_delete(apr_dbm_t *dbm, apr_datum_t key); + +/** + * Search for a key within the dbm + * @param dbm The database + * @param key The datum describing a key to test + */ +APU_DECLARE(int) apr_dbm_exists(apr_dbm_t *dbm, apr_datum_t key); + +/** + * Retrieve the first record key from a dbm + * @param dbm The database + * @param pkey The key datum of the first record + */ +APU_DECLARE(apr_status_t) apr_dbm_firstkey(apr_dbm_t *dbm, apr_datum_t *pkey); + +/** + * Retrieve the next record key from a dbm + * @param dbm The database + * @param pkey The key datum of the next record + */ +APU_DECLARE(apr_status_t) apr_dbm_nextkey(apr_dbm_t *dbm, apr_datum_t *pkey); + +/** + * Proactively toss any memory associated with the apr_datum_t. + * @param dbm The database + * @param data The datum to free. + */ +APU_DECLARE(void) apr_dbm_freedatum(apr_dbm_t *dbm, apr_datum_t data); + +/** + * Report more information when an apr_dbm function fails. + * @param dbm The database + * @param errcode A DBM-specific value for the error (for logging). If this + * isn't needed, it may be NULL. + * @param errbuf Location to store the error text + * @param errbufsize The size of the provided buffer + * @return The errbuf parameter, for convenience. + */ +APU_DECLARE(char *) apr_dbm_geterror(apr_dbm_t *dbm, int *errcode, + char *errbuf, apr_size_t errbufsize); +/** + * If the specified file/path were passed to apr_dbm_open(), return the + * actual file/path names which would be (created and) used. At most, two + * files may be used; used2 may be NULL if only one file is used. + * @param pool The pool for allocating used1 and used2. + * @param type The type of DBM you require info on @see apr_dbm_open_ex + * @param pathname The path name to generate used-names from. + * @param used1 The first pathname used by the apr_dbm implementation. + * @param used2 The second pathname used by apr_dbm. If only one file is + * used by the specific implementation, this will be set to NULL. + * @return An error if the specified type is invalid. + * @remark The dbm file(s) don't need to exist. This function only manipulates + * the pathnames. + */ +APU_DECLARE(apr_status_t) apr_dbm_get_usednames_ex(apr_pool_t *pool, + const char *type, + const char *pathname, + const char **used1, + const char **used2); + +/** + * If the specified file/path were passed to apr_dbm_open(), return the + * actual file/path names which would be (created and) used. At most, two + * files may be used; used2 may be NULL if only one file is used. + * @param pool The pool for allocating used1 and used2. + * @param pathname The path name to generate used-names from. + * @param used1 The first pathname used by the apr_dbm implementation. + * @param used2 The second pathname used by apr_dbm. If only one file is + * used by the specific implementation, this will be set to NULL. + * @remark The dbm file(s) don't need to exist. This function only manipulates + * the pathnames. + */ +APU_DECLARE(void) apr_dbm_get_usednames(apr_pool_t *pool, + const char *pathname, + const char **used1, + const char **used2); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_DBM_H */ diff --git a/c/dependencies/linux/apr/include/apr_dso.h b/c/dependencies/linux/apr/include/apr_dso.h new file mode 100644 index 00000000..ac701cfd --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_dso.h @@ -0,0 +1,94 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_DSO_DOT_H +#define APR_DSO_DOT_H + +/** + * @file apr_dso.h + * @brief APR Dynamic Object Handling Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_dso Dynamic Object Handling + * @ingroup APR + * @{ + */ + +#if APR_HAS_DSO || defined(DOXYGEN) + +/** + * Structure for referencing dynamic objects + */ +typedef struct apr_dso_handle_t apr_dso_handle_t; + +/** + * Structure for referencing symbols from dynamic objects + */ +typedef void * apr_dso_handle_sym_t; + +/** + * Load a DSO library. + * @param res_handle Location to store new handle for the DSO. + * @param path Path to the DSO library + * @param ctx Pool to use. + * @bug We aught to provide an alternative to RTLD_GLOBAL, which + * is the only supported method of loading DSOs today. + */ +APR_DECLARE(apr_status_t) apr_dso_load(apr_dso_handle_t **res_handle, + const char *path, apr_pool_t *ctx); + +/** + * Close a DSO library. + * @param handle handle to close. + */ +APR_DECLARE(apr_status_t) apr_dso_unload(apr_dso_handle_t *handle); + +/** + * Load a symbol from a DSO handle. + * @param ressym Location to store the loaded symbol + * @param handle handle to load the symbol from. + * @param symname Name of the symbol to load. + */ +APR_DECLARE(apr_status_t) apr_dso_sym(apr_dso_handle_sym_t *ressym, + apr_dso_handle_t *handle, + const char *symname); + +/** + * Report more information when a DSO function fails. + * @param dso The dso handle that has been opened + * @param buf Location to store the dso error + * @param bufsize The size of the provided buffer + */ +APR_DECLARE(const char *) apr_dso_error(apr_dso_handle_t *dso, char *buf, apr_size_t bufsize); + +#endif /* APR_HAS_DSO */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/c/dependencies/linux/apr/include/apr_encode.h b/c/dependencies/linux/apr/include/apr_encode.h new file mode 100644 index 00000000..20fc932f --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_encode.h @@ -0,0 +1,569 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_encode.h + * @brief APR-UTIL Encoding + */ +#ifndef APR_ENCODE_H +#define APR_ENCODE_H + +#include "apr.h" +#include "apr_general.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Encode Base64/Base64Url/Base32/Base32Hex/Base16 Encoding + * @ingroup APR_Util + * @{ + */ + +/** + * RFC4648 and RFC7515 compliant BASE64, BASE64URL, BASE32, BASE32HEX + * and BASE16 encode/decode functions. + * + * The following encodings are supported: + * + * - Base 64 Encoding + * + * o Use flag APR_ENCODE_NONE + * o https://tools.ietf.org/html/rfc4648#section-4 + * + * - Base 64 Encoding with URL and Filename Safe Alphabet + * + * o Use flag APR_ENCODE_URL + * o https://tools.ietf.org/html/rfc4648#section-5 + * + * - Base 64 URL Encoding without Padding + * + * o Use flag APR_ENCODE_BASE64URL + * o https://tools.ietf.org/html/rfc7515#appendix-C + * + * - Base 32 Encoding + * + * o Use flag APR_ENCODE_NONE + * o https://tools.ietf.org/html/rfc4648#section-6 + * + * - Base 32 Encoding with Extended Hex Alphabet + * + * o Use flag APR_ENCODE_BASE32HEX + * o https://tools.ietf.org/html/rfc4648#section-7 + * + * - Base 16 Encoding + * + * o Use flags APR_ENCODE_NONE/APR_ENCODE_COLON + * o https://tools.ietf.org/html/rfc4648#section-8 + * + * If a non valid character of any kind including whitespace is passed to any + * of the decoder functions, APR_BADCH will be returned. In this case decoding + * will still take place, but the results can not be trusted. + * + * If APR_ENCODE_RELAXED is passed to the decoder functions, decoding will be + * attempted up until the first non valid character. If this results in an + * invalid state in the decoder, such as but not limited to an odd number of + * base16 characters, APR_BADCH will still be returned. + * + * If APR_ENCODE_RELAXED is not passed to a decoder function, the decoding will + * be done in constant time regardless of whether the result returns APR_SUCCESS + * or APR_BADCH. + * + * If the dest parameter is NULL, the maximum theoretical buffer size is + * returned in the len field, including space for a terminating zero character + * if the destination is a string. This value can be used to allocate buffers + * of a suitable safe size. + * + * If the dest parameter is provided, the encoding or decoding will take place, + * and the actual number of characters written is returned in the len field, + * ignoring any terminating zero. + * + * Plain strings are not assumed '\0' terminated unless APR_ENCODE_STRING is + * provided. + * + */ + +/** + * When passing a string to one of the encode functions, this value can be + * passed to indicate a string-valued key, and have the length computed + * automatically. + */ +#define APR_ENCODE_STRING (-1) + +/** + * Generate RFC4648 base16/base32/base64. + */ +#define APR_ENCODE_NONE 0 + +/** + * If relaxed, decode up until the first non base16/base32/base64 character. + */ +#define APR_ENCODE_RELAXED 1 + +/** + * Omit the padding character (=) while encoding. + */ +#define APR_ENCODE_NOPADDING 2 + +/** + * Generate RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet + */ +#define APR_ENCODE_URL 4 + +/** + * Generate RFC7515 BASE64URL + */ +#define APR_ENCODE_BASE64URL (APR_ENCODE_NOPADDING | APR_ENCODE_URL) + +/** + * Generate base32hex encoding instead of base32 encoding + */ +#define APR_ENCODE_BASE32HEX 8 + +/** + * Generate base16 with colons between each token. + */ +#define APR_ENCODE_COLON 16 + +/** + * Generate base16 with lower case characters. + */ +#define APR_ENCODE_LOWER 32 + +/** + * Convert text data to base64. + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 64 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_URL, + * use RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet. + * If APR_ENCODE_BASE64URL, use RFC7515 base64url Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination string, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base64(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert binary data to base64. + * @param dest The destination string, can be NULL. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 64 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_URL, + * use RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet. + * If APR_ENCODE_BASE64URL, use RFC7515 base64url Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination string, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base64_binary(char *dest, const unsigned char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert text data to base64, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 64 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_URL, + * use RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet. + * If APR_ENCODE_BASE64URL, use RFC7515 base64url Encoding. + * @param len If present, returns the number of characters written excluding + * the zero pad. + * @return A zero padded string allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *)apr_pencode_base64(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len)__attribute__((nonnull(1))); + +/** + * Convert binary data to base64, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 64 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_URL, + * use RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet. + * If APR_ENCODE_BASE64URL, use RFC7515 base64url Encoding. + * @param len If present, returns the number of characters written excluding + * the zero pad. + * @return A zero padded string allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *)apr_pencode_base64_binary(apr_pool_t * p, const unsigned char *src, + apr_ssize_t slen, int flags, apr_size_t * len)__attribute__((nonnull(1))); + +/** + * Convert base64 or base64url with or without padding to text data. + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, attempt to decode the full original buffer, + * and return NULL if any bad character is detected. If APR_ENCODE_RELAXED, + * decode until the first non base64/base64url character. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination string, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL, or APR_BADCH + * if a non hex character is present. + */ +APR_DECLARE(apr_status_t) apr_decode_base64(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base64 or base64url with or without padding to binary data. + * @param dest The destination buffer, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, attempt to decode the full original buffer, + * and return NULL if any bad character is detected. If APR_ENCODE_RELAXED, + * decode until the first non base64/base64url character. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the src was NULL, or APR_BADCH + * if a non base64 character is present. + */ +APR_DECLARE(apr_status_t) apr_decode_base64_binary(unsigned char *dest, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base64 or base64url with or without padding to text data, and + * return the results from a pool. + * @param p Pool to allocate from. + * @param src The base64 string to decode. + * @param slen The length of the base64 string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, attempt to decode the full original buffer, + * and return NULL if any bad character is detected. If APR_ENCODE_RELAXED, + * decode until the first non base64/base64url character. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A string allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const char *)apr_pdecode_base64(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert base64 or base64url with or without padding to binary data, and + * return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, attempt to decode the full original buffer, + * and return NULL if any bad character is detected. If APR_ENCODE_RELAXED, + * decode until the first non base64/base64url character. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A buffer allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const unsigned char *)apr_pdecode_base64_binary(apr_pool_t * p, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert text data to base32. + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 32 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_BASE32HEX, + * use RFC4648 base32hex Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination string, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base32(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert binary data to base32. + * @param dest The destination string, can be NULL. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 32 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_BASE32HEX, + * use RFC4648 base32hex Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination string, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base32_binary(char *dest, const unsigned char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert text data to base32, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 32 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_BASE32HEX, + * use RFC4648 base32hex Encoding. + * @param len If present, returns the number of characters written excluding + * the zero pad. + * @return A zero padded string allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *)apr_pencode_base32(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert binary data to base32, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 32 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_BASE32HEX, + * use RFC7515 base32hex Encoding. + * @param len If present, returns the number of characters written excluding + * the zero pad. + * @return A zero padded string allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *)apr_pencode_base32_binary(apr_pool_t * p, const unsigned char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert base32 or base32hex with or without padding to text data. + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 32 Encoding. If + * APR_ENCODE_BASE32HEX, use RFC4648 base32hex Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL, or APR_BADCH + * if a non base32 character is present. + */ +APR_DECLARE(apr_status_t) apr_decode_base32(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base32 or base32hex with or without padding to binary data. + * @param dest The destination buffer, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 32 Encoding. If + * APR_ENCODE_BASE32HEX, use RFC4648 base32hex Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the src was NULL, or APR_BADCH + * if a non base32 character is present. + */ +APR_DECLARE(apr_status_t) apr_decode_base32_binary(unsigned char *dest, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base32 or base32hex with or without padding to text data, and + * return the results from a pool. + * @param p Pool to allocate from. + * @param src The base32 string to decode. + * @param slen The length of the base32 string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 32 Encoding. If + * APR_ENCODE_BASE32HEX, use RFC4648 base32hex Encoding. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A string allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const char *)apr_pdecode_base32(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert base32 or base32hex with or without padding to binary data, and + * return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 32 Encoding. If + * APR_ENCODE_BASE32HEX, use RFC4648 base32hex Encoding. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A buffer allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const unsigned char *)apr_pdecode_base32_binary(apr_pool_t * p, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert text data to base16 (hex). + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, separate each token with a colon. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base16(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert binary data to base16 (hex). + * @param dest The destination string, can be NULL. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, separate each token with a colon. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base16_binary(char *dest, + const unsigned char *src, apr_ssize_t slen, int flags, + apr_size_t * len); + +/** + * Convert text data to base16 (hex), and return the results from a + * pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, separate each token with a colon. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A string allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const char *)apr_pencode_base16(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert binary data to base16 (hex), and return the results from a + * pool. + * @param p Pool to allocate from. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, separate each token with a colon. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A string allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const char *)apr_pencode_base16_binary(apr_pool_t * p, + const unsigned char *src, apr_ssize_t slen, + int flags, apr_size_t * len)__attribute__((nonnull(1))); + +/** + * Convert base16 (hex) to text data. + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, allow tokens to be separated with a colon. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL, or APR_BADCH + * if a non hex character is present. A zero pad is appended to the buffer. + */ +APR_DECLARE(apr_status_t) apr_decode_base16(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base16 (hex) to binary data. + * @param dest The destination buffer, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, allow tokens to be separated with a colon. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL, or APR_BADCH + * if a non hex character is present. No zero pad is written to the buffer. + */ +APR_DECLARE(apr_status_t) apr_decode_base16_binary(unsigned char *dest, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base16 (hex) and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, allow tokens to be separated with a colon. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A buffer allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const char *)apr_pdecode_base16(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert base16 (hex) to binary data, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, allow tokens to be separated with a colon. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A buffer allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const unsigned char *)apr_pdecode_base16_binary(apr_pool_t * p, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ENCODE_H */ diff --git a/c/dependencies/linux/apr/include/apr_env.h b/c/dependencies/linux/apr/include/apr_env.h new file mode 100644 index 00000000..85ab6704 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_env.h @@ -0,0 +1,67 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ENV_H +#define APR_ENV_H +/** + * @file apr_env.h + * @brief APR Environment functions + */ +#include "apr_errno.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_env Functions for manipulating the environment + * @ingroup APR + * @{ + */ + +/** + * Get the value of an environment variable + * @param value the returned value, allocated from @a pool + * @param envvar the name of the environment variable + * @param pool where to allocate @a value and any temporary storage from + */ +APR_DECLARE(apr_status_t) apr_env_get(char **value, const char *envvar, + apr_pool_t *pool); + +/** + * Set the value of an environment variable + * @param envvar the name of the environment variable + * @param value the value to set + * @param pool where to allocate temporary storage from + */ +APR_DECLARE(apr_status_t) apr_env_set(const char *envvar, const char *value, + apr_pool_t *pool); + +/** + * Delete a variable from the environment + * @param envvar the name of the environment variable + * @param pool where to allocate temporary storage from + */ +APR_DECLARE(apr_status_t) apr_env_delete(const char *envvar, apr_pool_t *pool); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_ENV_H */ diff --git a/c/dependencies/linux/apr/include/apr_errno.h b/c/dependencies/linux/apr/include/apr_errno.h new file mode 100644 index 00000000..8fa6628b --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_errno.h @@ -0,0 +1,1342 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ERRNO_H +#define APR_ERRNO_H + +/** + * @file apr_errno.h + * @brief APR Error Codes + */ + +#include "apr.h" + +#if APR_HAVE_ERRNO_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_errno Error Codes + * @ingroup APR + * @{ + */ + +/** + * Type for specifying an error or status code. + */ +typedef int apr_status_t; + +/** + * Return a human readable string describing the specified error. + * @param statcode The error code to get a string for. + * @param buf A buffer to hold the error string. + * @param bufsize Size of the buffer to hold the string. + */ +APR_DECLARE(char *) apr_strerror(apr_status_t statcode, char *buf, + apr_size_t bufsize); + +#if defined(DOXYGEN) +/** + * @def APR_FROM_OS_ERROR(os_err_type syserr) + * Fold a platform specific error into an apr_status_t code. + * @return apr_status_t + * @param e The platform os error code. + * @warning macro implementation; the syserr argument may be evaluated + * multiple times. + */ +#define APR_FROM_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e + APR_OS_START_SYSERR) + +/** + * @def APR_TO_OS_ERROR(apr_status_t statcode) + * @return os_err_type + * Fold an apr_status_t code back to the native platform defined error. + * @param e The apr_status_t folded platform os error code. + * @warning macro implementation; the statcode argument may be evaluated + * multiple times. If the statcode was not created by apr_get_os_error + * or APR_FROM_OS_ERROR, the results are undefined. + */ +#define APR_TO_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e - APR_OS_START_SYSERR) + +/** @def apr_get_os_error() + * @return apr_status_t the last platform error, folded into apr_status_t, on most platforms + * @remark This retrieves errno, or calls a GetLastError() style function, and + * folds it with APR_FROM_OS_ERROR. Some platforms (such as OS2) have no + * such mechanism, so this call may be unsupported. Do NOT use this + * call for socket errors from socket, send, recv etc! + */ + +/** @def apr_set_os_error(e) + * Reset the last platform error, unfolded from an apr_status_t, on some platforms + * @param e The OS error folded in a prior call to APR_FROM_OS_ERROR() + * @warning This is a macro implementation; the statcode argument may be evaluated + * multiple times. If the statcode was not created by apr_get_os_error + * or APR_FROM_OS_ERROR, the results are undefined. This macro sets + * errno, or calls a SetLastError() style function, unfolding statcode + * with APR_TO_OS_ERROR. Some platforms (such as OS2) have no such + * mechanism, so this call may be unsupported. + */ + +/** @def apr_get_netos_error() + * Return the last socket error, folded into apr_status_t, on all platforms + * @remark This retrieves errno or calls a GetLastSocketError() style function, + * and folds it with APR_FROM_OS_ERROR. + */ + +/** @def apr_set_netos_error(e) + * Reset the last socket error, unfolded from an apr_status_t + * @param e The socket error folded in a prior call to APR_FROM_OS_ERROR() + * @warning This is a macro implementation; the statcode argument may be evaluated + * multiple times. If the statcode was not created by apr_get_os_error + * or APR_FROM_OS_ERROR, the results are undefined. This macro sets + * errno, or calls a WSASetLastError() style function, unfolding + * socketcode with APR_TO_OS_ERROR. + */ + +#endif /* defined(DOXYGEN) */ + +/** + * APR_OS_START_ERROR is where the APR specific error values start. + */ +#define APR_OS_START_ERROR 20000 +/** + * APR_OS_ERRSPACE_SIZE is the maximum number of errors you can fit + * into one of the error/status ranges below -- except for + * APR_OS_START_USERERR, which see. + */ +#define APR_OS_ERRSPACE_SIZE 50000 +/** + * APR_UTIL_ERRSPACE_SIZE is the size of the space that is reserved for + * use within apr-util. This space is reserved above that used by APR + * internally. + * @note This number MUST be smaller than APR_OS_ERRSPACE_SIZE by a + * large enough amount that APR has sufficient room for its + * codes. + */ +#define APR_UTIL_ERRSPACE_SIZE 20000 +/** + * APR_OS_START_STATUS is where the APR specific status codes start. + */ +#define APR_OS_START_STATUS (APR_OS_START_ERROR + APR_OS_ERRSPACE_SIZE) +/** + * APR_UTIL_START_STATUS is where APR-Util starts defining its + * status codes. + */ +#define APR_UTIL_START_STATUS (APR_OS_START_STATUS + \ + (APR_OS_ERRSPACE_SIZE - APR_UTIL_ERRSPACE_SIZE)) +/** + * APR_OS_START_USERERR are reserved for applications that use APR that + * layer their own error codes along with APR's. Note that the + * error immediately following this one is set ten times farther + * away than usual, so that users of apr have a lot of room in + * which to declare custom error codes. + * + * In general applications should try and create unique error codes. To try + * and assist in finding suitable ranges of numbers to use, the following + * ranges are known to be used by the listed applications. If your + * application defines error codes please advise the range of numbers it + * uses to dev@apr.apache.org for inclusion in this list. + * + * Ranges shown are in relation to APR_OS_START_USERERR + * + * Subversion - Defined ranges, of less than 100, at intervals of 5000 + * starting at an offset of 5000, e.g. + * +5000 to 5100, +10000 to 10100 + * + * Apache HTTPD - +2000 to 2999 + */ +#define APR_OS_START_USERERR (APR_OS_START_STATUS + APR_OS_ERRSPACE_SIZE) +/** + * APR_OS_START_USEERR is obsolete, defined for compatibility only. + * Use APR_OS_START_USERERR instead. + */ +#define APR_OS_START_USEERR APR_OS_START_USERERR +/** + * APR_OS_START_CANONERR is where APR versions of errno values are defined + * on systems which don't have the corresponding errno. + */ +#define APR_OS_START_CANONERR (APR_OS_START_USERERR \ + + (APR_OS_ERRSPACE_SIZE * 10)) +/** + * APR_OS_START_EAIERR folds EAI_ error codes from getaddrinfo() into + * apr_status_t values. + */ +#define APR_OS_START_EAIERR (APR_OS_START_CANONERR + APR_OS_ERRSPACE_SIZE) +/** + * APR_OS_START_SYSERR folds platform-specific system error values into + * apr_status_t values. + */ +#define APR_OS_START_SYSERR (APR_OS_START_EAIERR + APR_OS_ERRSPACE_SIZE) + +/** + * @defgroup APR_ERROR_map APR Error Space + *
+ * The following attempts to show the relation of the various constants
+ * used for mapping APR Status codes.
+ *
+ *       0
+ *
+ *  20,000     APR_OS_START_ERROR
+ *
+ *         + APR_OS_ERRSPACE_SIZE (50,000)
+ *
+ *  70,000      APR_OS_START_STATUS
+ *
+ *         + APR_OS_ERRSPACE_SIZE - APR_UTIL_ERRSPACE_SIZE (30,000)
+ *
+ * 100,000      APR_UTIL_START_STATUS
+ *
+ *         + APR_UTIL_ERRSPACE_SIZE (20,000)
+ *
+ * 120,000      APR_OS_START_USERERR
+ *
+ *         + 10 x APR_OS_ERRSPACE_SIZE (50,000 * 10)
+ *
+ * 620,000      APR_OS_START_CANONERR
+ *
+ *         + APR_OS_ERRSPACE_SIZE (50,000)
+ *
+ * 670,000      APR_OS_START_EAIERR
+ *
+ *         + APR_OS_ERRSPACE_SIZE (50,000)
+ *
+ * 720,000      APR_OS_START_SYSERR
+ *
+ * 
+ */ + +/** no error. */ +#define APR_SUCCESS 0 + +/** + * @defgroup APR_Error APR Error Values + *
+ * APR ERROR VALUES
+ * APR_ENOSTAT      APR was unable to perform a stat on the file
+ * APR_ENOPOOL      APR was not provided a pool with which to allocate memory
+ * APR_EBADDATE     APR was given an invalid date
+ * APR_EINVALSOCK   APR was given an invalid socket
+ * APR_ENOPROC      APR was not given a process structure
+ * APR_ENOTIME      APR was not given a time structure
+ * APR_ENODIR       APR was not given a directory structure
+ * APR_ENOLOCK      APR was not given a lock structure
+ * APR_ENOPOLL      APR was not given a poll structure
+ * APR_ENOSOCKET    APR was not given a socket
+ * APR_ENOTHREAD    APR was not given a thread structure
+ * APR_ENOTHDKEY    APR was not given a thread key structure
+ * APR_ENOSHMAVAIL  There is no more shared memory available
+ * APR_EDSOOPEN     APR was unable to open the dso object.  For more
+ *                  information call apr_dso_error().
+ * APR_EGENERAL     General failure (specific information not available)
+ * APR_EBADIP       The specified IP address is invalid
+ * APR_EBADMASK     The specified netmask is invalid
+ * APR_ESYMNOTFOUND Could not find the requested symbol
+ * APR_ENOTENOUGHENTROPY Not enough entropy to continue
+ * 
+ * + *
+ * APR STATUS VALUES
+ * APR_INCHILD        Program is currently executing in the child
+ * APR_INPARENT       Program is currently executing in the parent
+ * APR_DETACH         The thread is detached
+ * APR_NOTDETACH      The thread is not detached
+ * APR_CHILD_DONE     The child has finished executing
+ * APR_CHILD_NOTDONE  The child has not finished executing
+ * APR_TIMEUP         The operation did not finish before the timeout
+ * APR_INCOMPLETE     The operation was incomplete although some processing
+ *                    was performed and the results are partially valid
+ * APR_BADCH          Getopt found an option not in the option string
+ * APR_BADARG         Getopt found an option that is missing an argument
+ *                    and an argument was specified in the option string
+ * APR_EOF            APR has encountered the end of the file
+ * APR_NOTFOUND       APR was unable to find the socket in the poll structure
+ * APR_ANONYMOUS      APR is using anonymous shared memory
+ * APR_FILEBASED      APR is using a file name as the key to the shared memory
+ * APR_KEYBASED       APR is using a shared key as the key to the shared memory
+ * APR_EINIT          Ininitalizer value.  If no option has been found, but
+ *                    the status variable requires a value, this should be used
+ * APR_ENOTIMPL       The APR function has not been implemented on this
+ *                    platform, either because nobody has gotten to it yet,
+ *                    or the function is impossible on this platform.
+ * APR_EMISMATCH      Two passwords do not match.
+ * APR_EABSOLUTE      The given path was absolute.
+ * APR_ERELATIVE      The given path was relative.
+ * APR_EINCOMPLETE    The given path was neither relative nor absolute.
+ * APR_EABOVEROOT     The given path was above the root path.
+ * APR_EBUSY          The given lock was busy.
+ * APR_EPROC_UNKNOWN  The given process wasn't recognized by APR
+ * 
+ * @{ + */ +/** @see APR_STATUS_IS_ENOSTAT */ +#define APR_ENOSTAT (APR_OS_START_ERROR + 1) +/** @see APR_STATUS_IS_ENOPOOL */ +#define APR_ENOPOOL (APR_OS_START_ERROR + 2) +/* empty slot: +3 */ +/** @see APR_STATUS_IS_EBADDATE */ +#define APR_EBADDATE (APR_OS_START_ERROR + 4) +/** @see APR_STATUS_IS_EINVALSOCK */ +#define APR_EINVALSOCK (APR_OS_START_ERROR + 5) +/** @see APR_STATUS_IS_ENOPROC */ +#define APR_ENOPROC (APR_OS_START_ERROR + 6) +/** @see APR_STATUS_IS_ENOTIME */ +#define APR_ENOTIME (APR_OS_START_ERROR + 7) +/** @see APR_STATUS_IS_ENODIR */ +#define APR_ENODIR (APR_OS_START_ERROR + 8) +/** @see APR_STATUS_IS_ENOLOCK */ +#define APR_ENOLOCK (APR_OS_START_ERROR + 9) +/** @see APR_STATUS_IS_ENOPOLL */ +#define APR_ENOPOLL (APR_OS_START_ERROR + 10) +/** @see APR_STATUS_IS_ENOSOCKET */ +#define APR_ENOSOCKET (APR_OS_START_ERROR + 11) +/** @see APR_STATUS_IS_ENOTHREAD */ +#define APR_ENOTHREAD (APR_OS_START_ERROR + 12) +/** @see APR_STATUS_IS_ENOTHDKEY */ +#define APR_ENOTHDKEY (APR_OS_START_ERROR + 13) +/** @see APR_STATUS_IS_EGENERAL */ +#define APR_EGENERAL (APR_OS_START_ERROR + 14) +/** @see APR_STATUS_IS_ENOSHMAVAIL */ +#define APR_ENOSHMAVAIL (APR_OS_START_ERROR + 15) +/** @see APR_STATUS_IS_EBADIP */ +#define APR_EBADIP (APR_OS_START_ERROR + 16) +/** @see APR_STATUS_IS_EBADMASK */ +#define APR_EBADMASK (APR_OS_START_ERROR + 17) +/* empty slot: +18 */ +/** @see APR_STATUS_IS_EDSOPEN */ +#define APR_EDSOOPEN (APR_OS_START_ERROR + 19) +/** @see APR_STATUS_IS_EABSOLUTE */ +#define APR_EABSOLUTE (APR_OS_START_ERROR + 20) +/** @see APR_STATUS_IS_ERELATIVE */ +#define APR_ERELATIVE (APR_OS_START_ERROR + 21) +/** @see APR_STATUS_IS_EINCOMPLETE */ +#define APR_EINCOMPLETE (APR_OS_START_ERROR + 22) +/** @see APR_STATUS_IS_EABOVEROOT */ +#define APR_EABOVEROOT (APR_OS_START_ERROR + 23) +/** @see APR_STATUS_IS_EBADPATH */ +#define APR_EBADPATH (APR_OS_START_ERROR + 24) +/** @see APR_STATUS_IS_EPATHWILD */ +#define APR_EPATHWILD (APR_OS_START_ERROR + 25) +/** @see APR_STATUS_IS_ESYMNOTFOUND */ +#define APR_ESYMNOTFOUND (APR_OS_START_ERROR + 26) +/** @see APR_STATUS_IS_EPROC_UNKNOWN */ +#define APR_EPROC_UNKNOWN (APR_OS_START_ERROR + 27) +/** @see APR_STATUS_IS_ENOTENOUGHENTROPY */ +#define APR_ENOTENOUGHENTROPY (APR_OS_START_ERROR + 28) +/** @} */ + +/** + * @defgroup APR_STATUS_IS Status Value Tests + * @warning For any particular error condition, more than one of these tests + * may match. This is because platform-specific error codes may not + * always match the semantics of the POSIX codes these tests (and the + * corresponding APR error codes) are named after. A notable example + * are the APR_STATUS_IS_ENOENT and APR_STATUS_IS_ENOTDIR tests on + * Win32 platforms. The programmer should always be aware of this and + * adjust the order of the tests accordingly. + * @{ + */ +/** + * APR was unable to perform a stat on the file + * @warning always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_ENOSTAT(s) ((s) == APR_ENOSTAT) +/** + * APR was not provided a pool with which to allocate memory + * @warning always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_ENOPOOL(s) ((s) == APR_ENOPOOL) +/** APR was given an invalid date */ +#define APR_STATUS_IS_EBADDATE(s) ((s) == APR_EBADDATE) +/** APR was given an invalid socket */ +#define APR_STATUS_IS_EINVALSOCK(s) ((s) == APR_EINVALSOCK) +/** APR was not given a process structure */ +#define APR_STATUS_IS_ENOPROC(s) ((s) == APR_ENOPROC) +/** APR was not given a time structure */ +#define APR_STATUS_IS_ENOTIME(s) ((s) == APR_ENOTIME) +/** APR was not given a directory structure */ +#define APR_STATUS_IS_ENODIR(s) ((s) == APR_ENODIR) +/** APR was not given a lock structure */ +#define APR_STATUS_IS_ENOLOCK(s) ((s) == APR_ENOLOCK) +/** APR was not given a poll structure */ +#define APR_STATUS_IS_ENOPOLL(s) ((s) == APR_ENOPOLL) +/** APR was not given a socket */ +#define APR_STATUS_IS_ENOSOCKET(s) ((s) == APR_ENOSOCKET) +/** APR was not given a thread structure */ +#define APR_STATUS_IS_ENOTHREAD(s) ((s) == APR_ENOTHREAD) +/** APR was not given a thread key structure */ +#define APR_STATUS_IS_ENOTHDKEY(s) ((s) == APR_ENOTHDKEY) +/** Generic Error which can not be put into another spot */ +#define APR_STATUS_IS_EGENERAL(s) ((s) == APR_EGENERAL) +/** There is no more shared memory available */ +#define APR_STATUS_IS_ENOSHMAVAIL(s) ((s) == APR_ENOSHMAVAIL) +/** The specified IP address is invalid */ +#define APR_STATUS_IS_EBADIP(s) ((s) == APR_EBADIP) +/** The specified netmask is invalid */ +#define APR_STATUS_IS_EBADMASK(s) ((s) == APR_EBADMASK) +/* empty slot: +18 */ +/** + * APR was unable to open the dso object. + * For more information call apr_dso_error(). + */ +#if defined(WIN32) +#define APR_STATUS_IS_EDSOOPEN(s) ((s) == APR_EDSOOPEN \ + || APR_TO_OS_ERROR(s) == ERROR_MOD_NOT_FOUND) +#else +#define APR_STATUS_IS_EDSOOPEN(s) ((s) == APR_EDSOOPEN) +#endif +/** The given path was absolute. */ +#define APR_STATUS_IS_EABSOLUTE(s) ((s) == APR_EABSOLUTE) +/** The given path was relative. */ +#define APR_STATUS_IS_ERELATIVE(s) ((s) == APR_ERELATIVE) +/** The given path was neither relative nor absolute. */ +#define APR_STATUS_IS_EINCOMPLETE(s) ((s) == APR_EINCOMPLETE) +/** The given path was above the root path. */ +#define APR_STATUS_IS_EABOVEROOT(s) ((s) == APR_EABOVEROOT) +/** The given path was bad. */ +#define APR_STATUS_IS_EBADPATH(s) ((s) == APR_EBADPATH) +/** The given path contained wildcards. */ +#define APR_STATUS_IS_EPATHWILD(s) ((s) == APR_EPATHWILD) +/** Could not find the requested symbol. + * For more information call apr_dso_error(). + */ +#if defined(WIN32) +#define APR_STATUS_IS_ESYMNOTFOUND(s) ((s) == APR_ESYMNOTFOUND \ + || APR_TO_OS_ERROR(s) == ERROR_PROC_NOT_FOUND) +#else +#define APR_STATUS_IS_ESYMNOTFOUND(s) ((s) == APR_ESYMNOTFOUND) +#endif +/** The given process was not recognized by APR. */ +#define APR_STATUS_IS_EPROC_UNKNOWN(s) ((s) == APR_EPROC_UNKNOWN) +/** APR could not gather enough entropy to continue. */ +#define APR_STATUS_IS_ENOTENOUGHENTROPY(s) ((s) == APR_ENOTENOUGHENTROPY) + +/** @} */ + +/** + * @addtogroup APR_Error + * @{ + */ +/** @see APR_STATUS_IS_INCHILD */ +#define APR_INCHILD (APR_OS_START_STATUS + 1) +/** @see APR_STATUS_IS_INPARENT */ +#define APR_INPARENT (APR_OS_START_STATUS + 2) +/** @see APR_STATUS_IS_DETACH */ +#define APR_DETACH (APR_OS_START_STATUS + 3) +/** @see APR_STATUS_IS_NOTDETACH */ +#define APR_NOTDETACH (APR_OS_START_STATUS + 4) +/** @see APR_STATUS_IS_CHILD_DONE */ +#define APR_CHILD_DONE (APR_OS_START_STATUS + 5) +/** @see APR_STATUS_IS_CHILD_NOTDONE */ +#define APR_CHILD_NOTDONE (APR_OS_START_STATUS + 6) +/** @see APR_STATUS_IS_TIMEUP */ +#define APR_TIMEUP (APR_OS_START_STATUS + 7) +/** @see APR_STATUS_IS_INCOMPLETE */ +#define APR_INCOMPLETE (APR_OS_START_STATUS + 8) +/* empty slot: +9 */ +/* empty slot: +10 */ +/* empty slot: +11 */ +/** @see APR_STATUS_IS_BADCH */ +#define APR_BADCH (APR_OS_START_STATUS + 12) +/** @see APR_STATUS_IS_BADARG */ +#define APR_BADARG (APR_OS_START_STATUS + 13) +/** @see APR_STATUS_IS_EOF */ +#define APR_EOF (APR_OS_START_STATUS + 14) +/** @see APR_STATUS_IS_NOTFOUND */ +#define APR_NOTFOUND (APR_OS_START_STATUS + 15) +/* empty slot: +16 */ +/* empty slot: +17 */ +/* empty slot: +18 */ +/** @see APR_STATUS_IS_ANONYMOUS */ +#define APR_ANONYMOUS (APR_OS_START_STATUS + 19) +/** @see APR_STATUS_IS_FILEBASED */ +#define APR_FILEBASED (APR_OS_START_STATUS + 20) +/** @see APR_STATUS_IS_KEYBASED */ +#define APR_KEYBASED (APR_OS_START_STATUS + 21) +/** @see APR_STATUS_IS_EINIT */ +#define APR_EINIT (APR_OS_START_STATUS + 22) +/** @see APR_STATUS_IS_ENOTIMPL */ +#define APR_ENOTIMPL (APR_OS_START_STATUS + 23) +/** @see APR_STATUS_IS_EMISMATCH */ +#define APR_EMISMATCH (APR_OS_START_STATUS + 24) +/** @see APR_STATUS_IS_EBUSY */ +#define APR_EBUSY (APR_OS_START_STATUS + 25) +/** @} */ + +/** + * @addtogroup APR_STATUS_IS + * @{ + */ +/** + * Program is currently executing in the child + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code */ +#define APR_STATUS_IS_INCHILD(s) ((s) == APR_INCHILD) +/** + * Program is currently executing in the parent + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_INPARENT(s) ((s) == APR_INPARENT) +/** + * The thread is detached + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_DETACH(s) ((s) == APR_DETACH) +/** + * The thread is not detached + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_NOTDETACH(s) ((s) == APR_NOTDETACH) +/** + * The child has finished executing + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_CHILD_DONE(s) ((s) == APR_CHILD_DONE) +/** + * The child has not finished executing + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_CHILD_NOTDONE(s) ((s) == APR_CHILD_NOTDONE) +/** + * The operation did not finish before the timeout + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_TIMEUP(s) ((s) == APR_TIMEUP) +/** + * The operation was incomplete although some processing was performed + * and the results are partially valid. + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_INCOMPLETE(s) ((s) == APR_INCOMPLETE) +/* empty slot: +9 */ +/* empty slot: +10 */ +/* empty slot: +11 */ +/** + * Getopt found an option not in the option string + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_BADCH(s) ((s) == APR_BADCH) +/** + * Getopt found an option not in the option string and an argument was + * specified in the option string + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_BADARG(s) ((s) == APR_BADARG) +/** + * APR has encountered the end of the file + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_EOF(s) ((s) == APR_EOF) +/** + * APR was unable to find the socket in the poll structure + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_NOTFOUND(s) ((s) == APR_NOTFOUND) +/* empty slot: +16 */ +/* empty slot: +17 */ +/* empty slot: +18 */ +/** + * APR is using anonymous shared memory + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_ANONYMOUS(s) ((s) == APR_ANONYMOUS) +/** + * APR is using a file name as the key to the shared memory + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_FILEBASED(s) ((s) == APR_FILEBASED) +/** + * APR is using a shared key as the key to the shared memory + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_KEYBASED(s) ((s) == APR_KEYBASED) +/** + * Ininitalizer value. If no option has been found, but + * the status variable requires a value, this should be used + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_EINIT(s) ((s) == APR_EINIT) +/** + * The APR function has not been implemented on this + * platform, either because nobody has gotten to it yet, + * or the function is impossible on this platform. + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_ENOTIMPL(s) ((s) == APR_ENOTIMPL) +/** + * Two passwords do not match. + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_EMISMATCH(s) ((s) == APR_EMISMATCH) +/** + * The given lock was busy + * @warning always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_EBUSY(s) ((s) == APR_EBUSY) + +/** @} */ + +/** + * @addtogroup APR_Error APR Error Values + * @{ + */ +/* APR CANONICAL ERROR VALUES */ +/** @see APR_STATUS_IS_EACCES */ +#ifdef EACCES +#define APR_EACCES EACCES +#else +#define APR_EACCES (APR_OS_START_CANONERR + 1) +#endif + +/** @see APR_STATUS_IS_EEXIST */ +#ifdef EEXIST +#define APR_EEXIST EEXIST +#else +#define APR_EEXIST (APR_OS_START_CANONERR + 2) +#endif + +/** @see APR_STATUS_IS_ENAMETOOLONG */ +#ifdef ENAMETOOLONG +#define APR_ENAMETOOLONG ENAMETOOLONG +#else +#define APR_ENAMETOOLONG (APR_OS_START_CANONERR + 3) +#endif + +/** @see APR_STATUS_IS_ENOENT */ +#ifdef ENOENT +#define APR_ENOENT ENOENT +#else +#define APR_ENOENT (APR_OS_START_CANONERR + 4) +#endif + +/** @see APR_STATUS_IS_ENOTDIR */ +#ifdef ENOTDIR +#define APR_ENOTDIR ENOTDIR +#else +#define APR_ENOTDIR (APR_OS_START_CANONERR + 5) +#endif + +/** @see APR_STATUS_IS_ENOSPC */ +#ifdef ENOSPC +#define APR_ENOSPC ENOSPC +#else +#define APR_ENOSPC (APR_OS_START_CANONERR + 6) +#endif + +/** @see APR_STATUS_IS_ENOMEM */ +#ifdef ENOMEM +#define APR_ENOMEM ENOMEM +#else +#define APR_ENOMEM (APR_OS_START_CANONERR + 7) +#endif + +/** @see APR_STATUS_IS_EMFILE */ +#ifdef EMFILE +#define APR_EMFILE EMFILE +#else +#define APR_EMFILE (APR_OS_START_CANONERR + 8) +#endif + +/** @see APR_STATUS_IS_ENFILE */ +#ifdef ENFILE +#define APR_ENFILE ENFILE +#else +#define APR_ENFILE (APR_OS_START_CANONERR + 9) +#endif + +/** @see APR_STATUS_IS_EBADF */ +#ifdef EBADF +#define APR_EBADF EBADF +#else +#define APR_EBADF (APR_OS_START_CANONERR + 10) +#endif + +/** @see APR_STATUS_IS_EINVAL */ +#ifdef EINVAL +#define APR_EINVAL EINVAL +#else +#define APR_EINVAL (APR_OS_START_CANONERR + 11) +#endif + +/** @see APR_STATUS_IS_ESPIPE */ +#ifdef ESPIPE +#define APR_ESPIPE ESPIPE +#else +#define APR_ESPIPE (APR_OS_START_CANONERR + 12) +#endif + +/** + * @see APR_STATUS_IS_EAGAIN + * @warning use APR_STATUS_IS_EAGAIN instead of just testing this value + */ +#ifdef EAGAIN +#define APR_EAGAIN EAGAIN +#elif defined(EWOULDBLOCK) +#define APR_EAGAIN EWOULDBLOCK +#else +#define APR_EAGAIN (APR_OS_START_CANONERR + 13) +#endif + +/** @see APR_STATUS_IS_EINTR */ +#ifdef EINTR +#define APR_EINTR EINTR +#else +#define APR_EINTR (APR_OS_START_CANONERR + 14) +#endif + +/** @see APR_STATUS_IS_ENOTSOCK */ +#ifdef ENOTSOCK +#define APR_ENOTSOCK ENOTSOCK +#else +#define APR_ENOTSOCK (APR_OS_START_CANONERR + 15) +#endif + +/** @see APR_STATUS_IS_ECONNREFUSED */ +#ifdef ECONNREFUSED +#define APR_ECONNREFUSED ECONNREFUSED +#else +#define APR_ECONNREFUSED (APR_OS_START_CANONERR + 16) +#endif + +/** @see APR_STATUS_IS_EINPROGRESS */ +#ifdef EINPROGRESS +#define APR_EINPROGRESS EINPROGRESS +#else +#define APR_EINPROGRESS (APR_OS_START_CANONERR + 17) +#endif + +/** + * @see APR_STATUS_IS_ECONNABORTED + * @warning use APR_STATUS_IS_ECONNABORTED instead of just testing this value + */ + +#ifdef ECONNABORTED +#define APR_ECONNABORTED ECONNABORTED +#else +#define APR_ECONNABORTED (APR_OS_START_CANONERR + 18) +#endif + +/** @see APR_STATUS_IS_ECONNRESET */ +#ifdef ECONNRESET +#define APR_ECONNRESET ECONNRESET +#else +#define APR_ECONNRESET (APR_OS_START_CANONERR + 19) +#endif + +/** @see APR_STATUS_IS_ETIMEDOUT + * @deprecated */ +#ifdef ETIMEDOUT +#define APR_ETIMEDOUT ETIMEDOUT +#else +#define APR_ETIMEDOUT (APR_OS_START_CANONERR + 20) +#endif + +/** @see APR_STATUS_IS_EHOSTUNREACH */ +#ifdef EHOSTUNREACH +#define APR_EHOSTUNREACH EHOSTUNREACH +#else +#define APR_EHOSTUNREACH (APR_OS_START_CANONERR + 21) +#endif + +/** @see APR_STATUS_IS_ENETUNREACH */ +#ifdef ENETUNREACH +#define APR_ENETUNREACH ENETUNREACH +#else +#define APR_ENETUNREACH (APR_OS_START_CANONERR + 22) +#endif + +/** @see APR_STATUS_IS_EFTYPE */ +#ifdef EFTYPE +#define APR_EFTYPE EFTYPE +#else +#define APR_EFTYPE (APR_OS_START_CANONERR + 23) +#endif + +/** @see APR_STATUS_IS_EPIPE */ +#ifdef EPIPE +#define APR_EPIPE EPIPE +#else +#define APR_EPIPE (APR_OS_START_CANONERR + 24) +#endif + +/** @see APR_STATUS_IS_EXDEV */ +#ifdef EXDEV +#define APR_EXDEV EXDEV +#else +#define APR_EXDEV (APR_OS_START_CANONERR + 25) +#endif + +/** @see APR_STATUS_IS_ENOTEMPTY */ +#ifdef ENOTEMPTY +#define APR_ENOTEMPTY ENOTEMPTY +#else +#define APR_ENOTEMPTY (APR_OS_START_CANONERR + 26) +#endif + +/** @see APR_STATUS_IS_EAFNOSUPPORT */ +#ifdef EAFNOSUPPORT +#define APR_EAFNOSUPPORT EAFNOSUPPORT +#else +#define APR_EAFNOSUPPORT (APR_OS_START_CANONERR + 27) +#endif + +/** @see APR_STATUS_IS_EOPNOTSUPP */ +#ifdef EOPNOTSUPP +#define APR_EOPNOTSUPP EOPNOTSUPP +#else +#define APR_EOPNOTSUPP (APR_OS_START_CANONERR + 28) +#endif + +/** @see APR_STATUS_IS_ERANGE */ +#ifdef ERANGE +#define APR_ERANGE ERANGE +#else +#define APR_ERANGE (APR_OS_START_CANONERR + 29) +#endif + +/** @} */ + +#if defined(OS2) && !defined(DOXYGEN) + +#define APR_FROM_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e + APR_OS_START_SYSERR) +#define APR_TO_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e - APR_OS_START_SYSERR) + +#define INCL_DOSERRORS +#define INCL_DOS + +/* Leave these undefined. + * OS2 doesn't rely on the errno concept. + * The API calls always return a result codes which + * should be filtered through APR_FROM_OS_ERROR(). + * + * #define apr_get_os_error() (APR_FROM_OS_ERROR(GetLastError())) + * #define apr_set_os_error(e) (SetLastError(APR_TO_OS_ERROR(e))) + */ + +/* A special case, only socket calls require this; + */ +#define apr_get_netos_error() (APR_FROM_OS_ERROR(errno)) +#define apr_set_netos_error(e) (errno = APR_TO_OS_ERROR(e)) + +/* And this needs to be greped away for good: + */ +#define APR_OS2_STATUS(e) (APR_FROM_OS_ERROR(e)) + +/* These can't sit in a private header, so in spite of the extra size, + * they need to be made available here. + */ +#define SOCBASEERR 10000 +#define SOCEPERM (SOCBASEERR+1) /* Not owner */ +#define SOCESRCH (SOCBASEERR+3) /* No such process */ +#define SOCEINTR (SOCBASEERR+4) /* Interrupted system call */ +#define SOCENXIO (SOCBASEERR+6) /* No such device or address */ +#define SOCEBADF (SOCBASEERR+9) /* Bad file number */ +#define SOCEACCES (SOCBASEERR+13) /* Permission denied */ +#define SOCEFAULT (SOCBASEERR+14) /* Bad address */ +#define SOCEINVAL (SOCBASEERR+22) /* Invalid argument */ +#define SOCEMFILE (SOCBASEERR+24) /* Too many open files */ +#define SOCEPIPE (SOCBASEERR+32) /* Broken pipe */ +#define SOCEOS2ERR (SOCBASEERR+100) /* OS/2 Error */ +#define SOCEWOULDBLOCK (SOCBASEERR+35) /* Operation would block */ +#define SOCEINPROGRESS (SOCBASEERR+36) /* Operation now in progress */ +#define SOCEALREADY (SOCBASEERR+37) /* Operation already in progress */ +#define SOCENOTSOCK (SOCBASEERR+38) /* Socket operation on non-socket */ +#define SOCEDESTADDRREQ (SOCBASEERR+39) /* Destination address required */ +#define SOCEMSGSIZE (SOCBASEERR+40) /* Message too long */ +#define SOCEPROTOTYPE (SOCBASEERR+41) /* Protocol wrong type for socket */ +#define SOCENOPROTOOPT (SOCBASEERR+42) /* Protocol not available */ +#define SOCEPROTONOSUPPORT (SOCBASEERR+43) /* Protocol not supported */ +#define SOCESOCKTNOSUPPORT (SOCBASEERR+44) /* Socket type not supported */ +#define SOCEOPNOTSUPP (SOCBASEERR+45) /* Operation not supported on socket */ +#define SOCEPFNOSUPPORT (SOCBASEERR+46) /* Protocol family not supported */ +#define SOCEAFNOSUPPORT (SOCBASEERR+47) /* Address family not supported by protocol family */ +#define SOCEADDRINUSE (SOCBASEERR+48) /* Address already in use */ +#define SOCEADDRNOTAVAIL (SOCBASEERR+49) /* Can't assign requested address */ +#define SOCENETDOWN (SOCBASEERR+50) /* Network is down */ +#define SOCENETUNREACH (SOCBASEERR+51) /* Network is unreachable */ +#define SOCENETRESET (SOCBASEERR+52) /* Network dropped connection on reset */ +#define SOCECONNABORTED (SOCBASEERR+53) /* Software caused connection abort */ +#define SOCECONNRESET (SOCBASEERR+54) /* Connection reset by peer */ +#define SOCENOBUFS (SOCBASEERR+55) /* No buffer space available */ +#define SOCEISCONN (SOCBASEERR+56) /* Socket is already connected */ +#define SOCENOTCONN (SOCBASEERR+57) /* Socket is not connected */ +#define SOCESHUTDOWN (SOCBASEERR+58) /* Can't send after socket shutdown */ +#define SOCETOOMANYREFS (SOCBASEERR+59) /* Too many references: can't splice */ +#define SOCETIMEDOUT (SOCBASEERR+60) /* Connection timed out */ +#define SOCECONNREFUSED (SOCBASEERR+61) /* Connection refused */ +#define SOCELOOP (SOCBASEERR+62) /* Too many levels of symbolic links */ +#define SOCENAMETOOLONG (SOCBASEERR+63) /* File name too long */ +#define SOCEHOSTDOWN (SOCBASEERR+64) /* Host is down */ +#define SOCEHOSTUNREACH (SOCBASEERR+65) /* No route to host */ +#define SOCENOTEMPTY (SOCBASEERR+66) /* Directory not empty */ + +/* APR CANONICAL ERROR TESTS */ +#define APR_STATUS_IS_EACCES(s) ((s) == APR_EACCES \ + || (s) == APR_OS_START_SYSERR + ERROR_ACCESS_DENIED \ + || (s) == APR_OS_START_SYSERR + ERROR_SHARING_VIOLATION) +#define APR_STATUS_IS_EEXIST(s) ((s) == APR_EEXIST \ + || (s) == APR_OS_START_SYSERR + ERROR_OPEN_FAILED \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_EXISTS \ + || (s) == APR_OS_START_SYSERR + ERROR_ALREADY_EXISTS \ + || (s) == APR_OS_START_SYSERR + ERROR_ACCESS_DENIED) +#define APR_STATUS_IS_ENAMETOOLONG(s) ((s) == APR_ENAMETOOLONG \ + || (s) == APR_OS_START_SYSERR + ERROR_FILENAME_EXCED_RANGE \ + || (s) == APR_OS_START_SYSERR + SOCENAMETOOLONG) +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_PATH_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_MORE_FILES \ + || (s) == APR_OS_START_SYSERR + ERROR_OPEN_FAILED) +#define APR_STATUS_IS_ENOTDIR(s) ((s) == APR_ENOTDIR) +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC \ + || (s) == APR_OS_START_SYSERR + ERROR_DISK_FULL) +#define APR_STATUS_IS_ENOMEM(s) ((s) == APR_ENOMEM) +#define APR_STATUS_IS_EMFILE(s) ((s) == APR_EMFILE \ + || (s) == APR_OS_START_SYSERR + ERROR_TOO_MANY_OPEN_FILES) +#define APR_STATUS_IS_ENFILE(s) ((s) == APR_ENFILE) +#define APR_STATUS_IS_EBADF(s) ((s) == APR_EBADF \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_HANDLE) +#define APR_STATUS_IS_EINVAL(s) ((s) == APR_EINVAL \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_PARAMETER \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_FUNCTION) +#define APR_STATUS_IS_ESPIPE(s) ((s) == APR_ESPIPE \ + || (s) == APR_OS_START_SYSERR + ERROR_NEGATIVE_SEEK) +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_DATA \ + || (s) == APR_OS_START_SYSERR + SOCEWOULDBLOCK \ + || (s) == APR_OS_START_SYSERR + ERROR_LOCK_VIOLATION) +#define APR_STATUS_IS_EINTR(s) ((s) == APR_EINTR \ + || (s) == APR_OS_START_SYSERR + SOCEINTR) +#define APR_STATUS_IS_ENOTSOCK(s) ((s) == APR_ENOTSOCK \ + || (s) == APR_OS_START_SYSERR + SOCENOTSOCK) +#define APR_STATUS_IS_ECONNREFUSED(s) ((s) == APR_ECONNREFUSED \ + || (s) == APR_OS_START_SYSERR + SOCECONNREFUSED) +#define APR_STATUS_IS_EINPROGRESS(s) ((s) == APR_EINPROGRESS \ + || (s) == APR_OS_START_SYSERR + SOCEINPROGRESS) +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED \ + || (s) == APR_OS_START_SYSERR + SOCECONNABORTED) +#define APR_STATUS_IS_ECONNRESET(s) ((s) == APR_ECONNRESET \ + || (s) == APR_OS_START_SYSERR + SOCECONNRESET) +/* XXX deprecated */ +#define APR_STATUS_IS_ETIMEDOUT(s) ((s) == APR_ETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + SOCETIMEDOUT) +#undef APR_STATUS_IS_TIMEUP +#define APR_STATUS_IS_TIMEUP(s) ((s) == APR_TIMEUP \ + || (s) == APR_OS_START_SYSERR + SOCETIMEDOUT) +#define APR_STATUS_IS_EHOSTUNREACH(s) ((s) == APR_EHOSTUNREACH \ + || (s) == APR_OS_START_SYSERR + SOCEHOSTUNREACH) +#define APR_STATUS_IS_ENETUNREACH(s) ((s) == APR_ENETUNREACH \ + || (s) == APR_OS_START_SYSERR + SOCENETUNREACH) +#define APR_STATUS_IS_EFTYPE(s) ((s) == APR_EFTYPE) +#define APR_STATUS_IS_EPIPE(s) ((s) == APR_EPIPE \ + || (s) == APR_OS_START_SYSERR + ERROR_BROKEN_PIPE \ + || (s) == APR_OS_START_SYSERR + SOCEPIPE) +#define APR_STATUS_IS_EXDEV(s) ((s) == APR_EXDEV \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_SAME_DEVICE) +#define APR_STATUS_IS_ENOTEMPTY(s) ((s) == APR_ENOTEMPTY \ + || (s) == APR_OS_START_SYSERR + ERROR_DIR_NOT_EMPTY \ + || (s) == APR_OS_START_SYSERR + ERROR_ACCESS_DENIED) +#define APR_STATUS_IS_EAFNOSUPPORT(s) ((s) == APR_AFNOSUPPORT \ + || (s) == APR_OS_START_SYSERR + SOCEAFNOSUPPORT) +#define APR_STATUS_IS_EOPNOTSUPP(s) ((s) == APR_EOPNOTSUPP \ + || (s) == APR_OS_START_SYSERR + SOCEOPNOTSUPP) +#define APR_STATUS_IS_ERANGE(s) ((s) == APR_ERANGE) + +/* + Sorry, too tired to wrap this up for OS2... feel free to + fit the following into their best matches. + + { ERROR_NO_SIGNAL_SENT, ESRCH }, + { SOCEALREADY, EALREADY }, + { SOCEDESTADDRREQ, EDESTADDRREQ }, + { SOCEMSGSIZE, EMSGSIZE }, + { SOCEPROTOTYPE, EPROTOTYPE }, + { SOCENOPROTOOPT, ENOPROTOOPT }, + { SOCEPROTONOSUPPORT, EPROTONOSUPPORT }, + { SOCESOCKTNOSUPPORT, ESOCKTNOSUPPORT }, + { SOCEPFNOSUPPORT, EPFNOSUPPORT }, + { SOCEADDRINUSE, EADDRINUSE }, + { SOCEADDRNOTAVAIL, EADDRNOTAVAIL }, + { SOCENETDOWN, ENETDOWN }, + { SOCENETRESET, ENETRESET }, + { SOCENOBUFS, ENOBUFS }, + { SOCEISCONN, EISCONN }, + { SOCENOTCONN, ENOTCONN }, + { SOCESHUTDOWN, ESHUTDOWN }, + { SOCETOOMANYREFS, ETOOMANYREFS }, + { SOCELOOP, ELOOP }, + { SOCEHOSTDOWN, EHOSTDOWN }, + { SOCENOTEMPTY, ENOTEMPTY }, + { SOCEPIPE, EPIPE } +*/ + +#elif defined(WIN32) && !defined(DOXYGEN) /* !defined(OS2) */ + +#define APR_FROM_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e + APR_OS_START_SYSERR) +#define APR_TO_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e - APR_OS_START_SYSERR) + +#define apr_get_os_error() (APR_FROM_OS_ERROR(GetLastError())) +#define apr_set_os_error(e) (SetLastError(APR_TO_OS_ERROR(e))) + +/* A special case, only socket calls require this: + */ +#define apr_get_netos_error() (APR_FROM_OS_ERROR(WSAGetLastError())) +#define apr_set_netos_error(e) (WSASetLastError(APR_TO_OS_ERROR(e))) + +/* APR CANONICAL ERROR TESTS */ +#define APR_STATUS_IS_EACCES(s) ((s) == APR_EACCES \ + || (s) == APR_OS_START_SYSERR + ERROR_ACCESS_DENIED \ + || (s) == APR_OS_START_SYSERR + ERROR_CANNOT_MAKE \ + || (s) == APR_OS_START_SYSERR + ERROR_CURRENT_DIRECTORY \ + || (s) == APR_OS_START_SYSERR + ERROR_DRIVE_LOCKED \ + || (s) == APR_OS_START_SYSERR + ERROR_FAIL_I24 \ + || (s) == APR_OS_START_SYSERR + ERROR_LOCK_VIOLATION \ + || (s) == APR_OS_START_SYSERR + ERROR_LOCK_FAILED \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_LOCKED \ + || (s) == APR_OS_START_SYSERR + ERROR_NETWORK_ACCESS_DENIED \ + || (s) == APR_OS_START_SYSERR + ERROR_SHARING_VIOLATION) +#define APR_STATUS_IS_EEXIST(s) ((s) == APR_EEXIST \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_EXISTS \ + || (s) == APR_OS_START_SYSERR + ERROR_ALREADY_EXISTS) +#define APR_STATUS_IS_ENAMETOOLONG(s) ((s) == APR_ENAMETOOLONG \ + || (s) == APR_OS_START_SYSERR + ERROR_FILENAME_EXCED_RANGE \ + || (s) == APR_OS_START_SYSERR + WSAENAMETOOLONG) +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_PATH_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_OPEN_FAILED \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_MORE_FILES) +#define APR_STATUS_IS_ENOTDIR(s) ((s) == APR_ENOTDIR \ + || (s) == APR_OS_START_SYSERR + ERROR_PATH_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_NETPATH \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_NET_NAME \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_PATHNAME \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_DRIVE \ + || (s) == APR_OS_START_SYSERR + ERROR_DIRECTORY) +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC \ + || (s) == APR_OS_START_SYSERR + ERROR_DISK_FULL) +#define APR_STATUS_IS_ENOMEM(s) ((s) == APR_ENOMEM \ + || (s) == APR_OS_START_SYSERR + ERROR_ARENA_TRASHED \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_ENOUGH_MEMORY \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_BLOCK \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_ENOUGH_QUOTA \ + || (s) == APR_OS_START_SYSERR + ERROR_OUTOFMEMORY) +#define APR_STATUS_IS_EMFILE(s) ((s) == APR_EMFILE \ + || (s) == APR_OS_START_SYSERR + ERROR_TOO_MANY_OPEN_FILES) +#define APR_STATUS_IS_ENFILE(s) ((s) == APR_ENFILE) +#define APR_STATUS_IS_EBADF(s) ((s) == APR_EBADF \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_HANDLE \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_TARGET_HANDLE) +#define APR_STATUS_IS_EINVAL(s) ((s) == APR_EINVAL \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_ACCESS \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_DATA \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_FUNCTION \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_HANDLE \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_PARAMETER \ + || (s) == APR_OS_START_SYSERR + ERROR_NEGATIVE_SEEK) +#define APR_STATUS_IS_ESPIPE(s) ((s) == APR_ESPIPE \ + || (s) == APR_OS_START_SYSERR + ERROR_SEEK_ON_DEVICE \ + || (s) == APR_OS_START_SYSERR + ERROR_NEGATIVE_SEEK) +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_DATA \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_PROC_SLOTS \ + || (s) == APR_OS_START_SYSERR + ERROR_NESTING_NOT_ALLOWED \ + || (s) == APR_OS_START_SYSERR + ERROR_MAX_THRDS_REACHED \ + || (s) == APR_OS_START_SYSERR + ERROR_LOCK_VIOLATION \ + || (s) == APR_OS_START_SYSERR + WSAEWOULDBLOCK) +#define APR_STATUS_IS_EINTR(s) ((s) == APR_EINTR \ + || (s) == APR_OS_START_SYSERR + WSAEINTR) +#define APR_STATUS_IS_ENOTSOCK(s) ((s) == APR_ENOTSOCK \ + || (s) == APR_OS_START_SYSERR + WSAENOTSOCK) +#define APR_STATUS_IS_ECONNREFUSED(s) ((s) == APR_ECONNREFUSED \ + || (s) == APR_OS_START_SYSERR + WSAECONNREFUSED) +#define APR_STATUS_IS_EINPROGRESS(s) ((s) == APR_EINPROGRESS \ + || (s) == APR_OS_START_SYSERR + WSAEINPROGRESS) +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED \ + || (s) == APR_OS_START_SYSERR + WSAECONNABORTED) +#define APR_STATUS_IS_ECONNRESET(s) ((s) == APR_ECONNRESET \ + || (s) == APR_OS_START_SYSERR + ERROR_NETNAME_DELETED \ + || (s) == APR_OS_START_SYSERR + WSAECONNRESET) +/* XXX deprecated */ +#define APR_STATUS_IS_ETIMEDOUT(s) ((s) == APR_ETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WSAETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WAIT_TIMEOUT) +#undef APR_STATUS_IS_TIMEUP +#define APR_STATUS_IS_TIMEUP(s) ((s) == APR_TIMEUP \ + || (s) == APR_OS_START_SYSERR + WSAETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WAIT_TIMEOUT) +#define APR_STATUS_IS_EHOSTUNREACH(s) ((s) == APR_EHOSTUNREACH \ + || (s) == APR_OS_START_SYSERR + WSAEHOSTUNREACH) +#define APR_STATUS_IS_ENETUNREACH(s) ((s) == APR_ENETUNREACH \ + || (s) == APR_OS_START_SYSERR + WSAENETUNREACH) +#define APR_STATUS_IS_EFTYPE(s) ((s) == APR_EFTYPE \ + || (s) == APR_OS_START_SYSERR + ERROR_EXE_MACHINE_TYPE_MISMATCH \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_DLL \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_MODULETYPE \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_EXE_FORMAT \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_EXE_SIGNATURE \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_CORRUPT \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_FORMAT) +#define APR_STATUS_IS_EPIPE(s) ((s) == APR_EPIPE \ + || (s) == APR_OS_START_SYSERR + ERROR_BROKEN_PIPE) +#define APR_STATUS_IS_EXDEV(s) ((s) == APR_EXDEV \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_SAME_DEVICE) +#define APR_STATUS_IS_ENOTEMPTY(s) ((s) == APR_ENOTEMPTY \ + || (s) == APR_OS_START_SYSERR + ERROR_DIR_NOT_EMPTY) +#define APR_STATUS_IS_EAFNOSUPPORT(s) ((s) == APR_EAFNOSUPPORT \ + || (s) == APR_OS_START_SYSERR + WSAEAFNOSUPPORT) +#define APR_STATUS_IS_EOPNOTSUPP(s) ((s) == APR_EOPNOTSUPP \ + || (s) == APR_OS_START_SYSERR + WSAEOPNOTSUPP) +#define APR_STATUS_IS_ERANGE(s) ((s) == APR_ERANGE) + +#elif defined(NETWARE) && defined(USE_WINSOCK) && !defined(DOXYGEN) /* !defined(OS2) && !defined(WIN32) */ + +#define APR_FROM_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e + APR_OS_START_SYSERR) +#define APR_TO_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e - APR_OS_START_SYSERR) + +#define apr_get_os_error() (errno) +#define apr_set_os_error(e) (errno = (e)) + +/* A special case, only socket calls require this: */ +#define apr_get_netos_error() (APR_FROM_OS_ERROR(WSAGetLastError())) +#define apr_set_netos_error(e) (WSASetLastError(APR_TO_OS_ERROR(e))) + +/* APR CANONICAL ERROR TESTS */ +#define APR_STATUS_IS_EACCES(s) ((s) == APR_EACCES) +#define APR_STATUS_IS_EEXIST(s) ((s) == APR_EEXIST) +#define APR_STATUS_IS_ENAMETOOLONG(s) ((s) == APR_ENAMETOOLONG) +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT) +#define APR_STATUS_IS_ENOTDIR(s) ((s) == APR_ENOTDIR) +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC) +#define APR_STATUS_IS_ENOMEM(s) ((s) == APR_ENOMEM) +#define APR_STATUS_IS_EMFILE(s) ((s) == APR_EMFILE) +#define APR_STATUS_IS_ENFILE(s) ((s) == APR_ENFILE) +#define APR_STATUS_IS_EBADF(s) ((s) == APR_EBADF) +#define APR_STATUS_IS_EINVAL(s) ((s) == APR_EINVAL) +#define APR_STATUS_IS_ESPIPE(s) ((s) == APR_ESPIPE) + +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN \ + || (s) == EWOULDBLOCK \ + || (s) == APR_OS_START_SYSERR + WSAEWOULDBLOCK) +#define APR_STATUS_IS_EINTR(s) ((s) == APR_EINTR \ + || (s) == APR_OS_START_SYSERR + WSAEINTR) +#define APR_STATUS_IS_ENOTSOCK(s) ((s) == APR_ENOTSOCK \ + || (s) == APR_OS_START_SYSERR + WSAENOTSOCK) +#define APR_STATUS_IS_ECONNREFUSED(s) ((s) == APR_ECONNREFUSED \ + || (s) == APR_OS_START_SYSERR + WSAECONNREFUSED) +#define APR_STATUS_IS_EINPROGRESS(s) ((s) == APR_EINPROGRESS \ + || (s) == APR_OS_START_SYSERR + WSAEINPROGRESS) +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED \ + || (s) == APR_OS_START_SYSERR + WSAECONNABORTED) +#define APR_STATUS_IS_ECONNRESET(s) ((s) == APR_ECONNRESET \ + || (s) == APR_OS_START_SYSERR + WSAECONNRESET) +/* XXX deprecated */ +#define APR_STATUS_IS_ETIMEDOUT(s) ((s) == APR_ETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WSAETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WAIT_TIMEOUT) +#undef APR_STATUS_IS_TIMEUP +#define APR_STATUS_IS_TIMEUP(s) ((s) == APR_TIMEUP \ + || (s) == APR_OS_START_SYSERR + WSAETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WAIT_TIMEOUT) +#define APR_STATUS_IS_EHOSTUNREACH(s) ((s) == APR_EHOSTUNREACH \ + || (s) == APR_OS_START_SYSERR + WSAEHOSTUNREACH) +#define APR_STATUS_IS_ENETUNREACH(s) ((s) == APR_ENETUNREACH \ + || (s) == APR_OS_START_SYSERR + WSAENETUNREACH) +#define APR_STATUS_IS_ENETDOWN(s) ((s) == APR_OS_START_SYSERR + WSAENETDOWN) +#define APR_STATUS_IS_EFTYPE(s) ((s) == APR_EFTYPE) +#define APR_STATUS_IS_EPIPE(s) ((s) == APR_EPIPE) +#define APR_STATUS_IS_EXDEV(s) ((s) == APR_EXDEV) +#define APR_STATUS_IS_ENOTEMPTY(s) ((s) == APR_ENOTEMPTY) +#define APR_STATUS_IS_EAFNOSUPPORT(s) ((s) == APR_EAFNOSUPPORT \ + || (s) == APR_OS_START_SYSERR + WSAEAFNOSUPPORT) +#define APR_STATUS_IS_EOPNOTSUPP(s) ((s) == APR_EOPNOTSUPP \ + || (s) == APR_OS_START_SYSERR + WSAEOPNOTSUPP) +#define APR_STATUS_IS_ERANGE(s) ((s) == APR_ERANGE) + +#else /* !defined(NETWARE) && !defined(OS2) && !defined(WIN32) */ + +/* + * os error codes are clib error codes + */ +#define APR_FROM_OS_ERROR(e) (e) +#define APR_TO_OS_ERROR(e) (e) + +#define apr_get_os_error() (errno) +#define apr_set_os_error(e) (errno = (e)) + +/* A special case, only socket calls require this: + */ +#define apr_get_netos_error() (errno) +#define apr_set_netos_error(e) (errno = (e)) + +/** + * @addtogroup APR_STATUS_IS + * @{ + */ + +/** permission denied */ +#define APR_STATUS_IS_EACCES(s) ((s) == APR_EACCES) +/** file exists */ +#define APR_STATUS_IS_EEXIST(s) ((s) == APR_EEXIST) +/** path name is too long */ +#define APR_STATUS_IS_ENAMETOOLONG(s) ((s) == APR_ENAMETOOLONG) +/** + * no such file or directory + * @remark + * EMVSCATLG can be returned by the automounter on z/OS for + * paths which do not exist. + */ +#ifdef EMVSCATLG +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT \ + || (s) == EMVSCATLG) +#else +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT) +#endif +/** not a directory */ +#define APR_STATUS_IS_ENOTDIR(s) ((s) == APR_ENOTDIR) +/** no space left on device */ +#ifdef EDQUOT +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC \ + || (s) == EDQUOT) +#else +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC) +#endif +/** not enough memory */ +#define APR_STATUS_IS_ENOMEM(s) ((s) == APR_ENOMEM) +/** too many open files */ +#define APR_STATUS_IS_EMFILE(s) ((s) == APR_EMFILE) +/** file table overflow */ +#define APR_STATUS_IS_ENFILE(s) ((s) == APR_ENFILE) +/** bad file # */ +#define APR_STATUS_IS_EBADF(s) ((s) == APR_EBADF) +/** invalid argument */ +#define APR_STATUS_IS_EINVAL(s) ((s) == APR_EINVAL) +/** illegal seek */ +#define APR_STATUS_IS_ESPIPE(s) ((s) == APR_ESPIPE) + +/** operation would block */ +#if !defined(EWOULDBLOCK) || !defined(EAGAIN) +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN) +#elif (EWOULDBLOCK == EAGAIN) +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN) +#else +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN \ + || (s) == EWOULDBLOCK) +#endif + +/** interrupted system call */ +#define APR_STATUS_IS_EINTR(s) ((s) == APR_EINTR) +/** socket operation on a non-socket */ +#define APR_STATUS_IS_ENOTSOCK(s) ((s) == APR_ENOTSOCK) +/** Connection Refused */ +#define APR_STATUS_IS_ECONNREFUSED(s) ((s) == APR_ECONNREFUSED) +/** operation now in progress */ +#define APR_STATUS_IS_EINPROGRESS(s) ((s) == APR_EINPROGRESS) + +/** + * Software caused connection abort + * @remark + * EPROTO on certain older kernels really means ECONNABORTED, so we need to + * ignore it for them. See discussion in new-httpd archives nh.9701 & nh.9603 + * + * There is potentially a bug in Solaris 2.x x<6, and other boxes that + * implement tcp sockets in userland (i.e. on top of STREAMS). On these + * systems, EPROTO can actually result in a fatal loop. See PR#981 for + * example. It's hard to handle both uses of EPROTO. + */ +#ifdef EPROTO +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED \ + || (s) == EPROTO) +#else +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED) +#endif + +/** Connection Reset by peer */ +#define APR_STATUS_IS_ECONNRESET(s) ((s) == APR_ECONNRESET) +/** Operation timed out + * @deprecated */ +#define APR_STATUS_IS_ETIMEDOUT(s) ((s) == APR_ETIMEDOUT) +/** no route to host */ +#define APR_STATUS_IS_EHOSTUNREACH(s) ((s) == APR_EHOSTUNREACH) +/** network is unreachable */ +#define APR_STATUS_IS_ENETUNREACH(s) ((s) == APR_ENETUNREACH) +/** inappropriate file type or format */ +#define APR_STATUS_IS_EFTYPE(s) ((s) == APR_EFTYPE) +/** broken pipe */ +#define APR_STATUS_IS_EPIPE(s) ((s) == APR_EPIPE) +/** cross device link */ +#define APR_STATUS_IS_EXDEV(s) ((s) == APR_EXDEV) +/** Directory Not Empty */ +#define APR_STATUS_IS_ENOTEMPTY(s) ((s) == APR_ENOTEMPTY || \ + (s) == APR_EEXIST) +/** Address Family not supported */ +#define APR_STATUS_IS_EAFNOSUPPORT(s) ((s) == APR_EAFNOSUPPORT) +/** Socket operation not supported */ +#define APR_STATUS_IS_EOPNOTSUPP(s) ((s) == APR_EOPNOTSUPP) + +/** Numeric value not representable */ +#define APR_STATUS_IS_ERANGE(s) ((s) == APR_ERANGE) +/** @} */ + +#endif /* !defined(NETWARE) && !defined(OS2) && !defined(WIN32) */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_ERRNO_H */ diff --git a/c/dependencies/linux/apr/include/apr_escape.h b/c/dependencies/linux/apr/include/apr_escape.h new file mode 100644 index 00000000..ed048c95 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_escape.h @@ -0,0 +1,431 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file apr_escape.h + * @brief APR-UTIL Escaping + */ +#ifndef APR_ESCAPE_H +#define APR_ESCAPE_H +#include "apr.h" +#include "apr_general.h" +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Escaping Escape functions + * @ingroup APR + * @{ + */ + +/* Simple escape/unescape functions. + * + * The design goal of these functions are: + * + * - Avoid unnecessary work. + * + * In most cases the strings passed in do not need to be escaped at all. In + * these cases the original string will be returned. + * + * - Lowest possible memory footprint. + * + * The amount of memory allocated for a given encoding is calculated based + * on the exact amount of memory needed, and not the theoretical worst case + * scenario. + * + */ + +/** + * When passing a string to one of the escape functions, this value can be + * passed to indicate a string-valued key, and have the length computed + * automatically. + */ +#define APR_ESCAPE_STRING (-1) + +/** + * Apply LDAP distinguished name escaping as per RFC4514. + */ +#define APR_ESCAPE_LDAP_DN (0x01) + +/** + * Apply LDAP filter escaping as per RFC4515. + */ +#define APR_ESCAPE_LDAP_FILTER (0x02) + +/** + * Apply both RFC4514 and RFC4515 LDAP escaping. + */ +#define APR_ESCAPE_LDAP_ALL (0x03) + +/** + * Perform shell escaping on the provided string. + * + * Shell escaping causes characters to be prefixed with a '\' character. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_shell(char *escaped, const char *str, + apr_ssize_t slen, apr_size_t *len); + +/** + * Perform shell escaping on the provided string, returning the result + * from the pool. + * + * Shell escaping causes characters to be prefixed with a '\' character. + * + * If no characters were escaped, the original string is returned. + * @param p Pool to allocate from + * @param str The original string + * @return the encoded string, allocated from the pool, or the original + * string if no escaping took place or the string was NULL. + */ +APR_DECLARE(const char *) apr_pescape_shell(apr_pool_t *p, const char *str) + __attribute__((nonnull(1))); + +/** + * Unescapes a URL, leaving reserved characters intact. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param url String to be unescaped + * @param slen The length of the original url, or APR_ESCAPE_STRING + * @param forbid Optional list of forbidden characters, in addition to + * 0x00 + * @param reserved Optional list of reserved characters that will be + * left unescaped + * @param plus If non zero, '+' is converted to ' ' as per + * application/x-www-form-urlencoded encoding + * @param len If set, the length of the escaped string will be returned + * @return APR_SUCCESS on success, APR_NOTFOUND if no characters are + * decoded or the string is NULL, APR_EINVAL if a bad escape sequence is + * found, APR_BADCH if a character on the forbid list is found. + */ +APR_DECLARE(apr_status_t) apr_unescape_url(char *escaped, const char *url, + apr_ssize_t slen, const char *forbid, const char *reserved, int plus, + apr_size_t *len); + +/** + * Unescapes a URL, leaving reserved characters intact, returning the + * result from a pool. + * @param p Pool to allocate from + * @param url String to be unescaped in place + * @param forbid Optional list of forbidden characters, in addition to + * 0x00 + * @param reserved Optional list of reserved characters that will be + * left unescaped + * @param plus If non zero, '+' is converted to ' ' as per + * application/x-www-form-urlencoded encoding + * @return A string allocated from the pool on success, the original string + * if no characters are decoded, or NULL if a bad escape sequence is found + * or if a character on the forbid list is found, or if the original string + * was NULL. + */ +APR_DECLARE(const char *) apr_punescape_url(apr_pool_t *p, const char *url, + const char *forbid, const char *reserved, int plus) + __attribute__((nonnull(1))); + +/** + * Escape a path segment, as defined in RFC1808. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_path_segment(char *escaped, + const char *str, apr_ssize_t slen, apr_size_t *len); + +/** + * Escape a path segment, as defined in RFC1808, returning the result from a + * pool. + * @param p Pool to allocate from + * @param str String to be escaped + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or the string is NULL. + */ +APR_DECLARE(const char *) apr_pescape_path_segment(apr_pool_t *p, + const char *str) __attribute__((nonnull(1))); + +/** + * Converts an OS path to a URL, in an OS dependent way, as defined in RFC1808. + * In all cases if a ':' occurs before the first '/' in the URL, the URL should + * be prefixed with "./" (or the ':' escaped). In the case of Unix, this means + * leaving '/' alone, but otherwise doing what escape_path_segment() does. For + * efficiency reasons, we don't use escape_path_segment(), which is provided for + * reference. Again, RFC 1808 is where this stuff is defined. + * + * If partial is set, os_escape_path() assumes that the path will be appended to + * something with a '/' in it (and thus does not prefix "./"). + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param path The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param partial If non zero, suppresses the prepending of "./" + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or if the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_path(char *escaped, const char *path, + apr_ssize_t slen, int partial, apr_size_t *len); + +/** + * Converts an OS path to a URL, in an OS dependent way, as defined in RFC1808, + * returning the result from a pool. + * + * In all cases if a ':' occurs before the first '/' in the URL, the URL should + * be prefixed with "./" (or the ':' escaped). In the case of Unix, this means + * leaving '/' alone, but otherwise doing what escape_path_segment() does. For + * efficiency reasons, we don't use escape_path_segment(), which is provided for + * reference. Again, RFC 1808 is where this stuff is defined. + * + * If partial is set, os_escape_path() assumes that the path will be appended to + * something with a '/' in it (and thus does not prefix "./"). + * @param p Pool to allocate from + * @param str The original string + * @param partial If non zero, suppresses the prepending of "./" + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or if the string was NULL. + */ +APR_DECLARE(const char *) apr_pescape_path(apr_pool_t *p, const char *str, + int partial) __attribute__((nonnull(1))); + +/** + * Urlencode a string, as defined in + * http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or if the stirng was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_urlencoded(char *escaped, const char *str, + apr_ssize_t slen, apr_size_t *len); + +/** + * Urlencode a string, as defined in + * http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1, returning + * the result from a pool. + * @param p Pool to allocate from + * @param str String to be escaped + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or if the string was NULL. + */ +APR_DECLARE(const char *) apr_pescape_urlencoded(apr_pool_t *p, + const char *str) __attribute__((nonnull(1))); + +/** + * Apply entity encoding to a string. Characters are replaced as follows: + * '<' becomes '\<', '>' becomes '\>', '&' becomes '\&', the + * double quote becomes '\"" and the single quote becomes '\''. + * + * If toasc is not zero, any non ascii character will be encoded as + * '%\#ddd;', where ddd is the decimal code of the character. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param toasc If non zero, encode non ascii characters + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_entity(char *escaped, const char *str, + apr_ssize_t slen, int toasc, apr_size_t *len); + +/** + * Apply entity encoding to a string, returning the result from a pool. + * Characters are replaced as follows: '<' becomes '\<', '>' becomes + * '\>', '&' becomes '\&', the double quote becomes '\"" and the + * single quote becomes '\''. + * @param p Pool to allocate from + * @param str The original string + * @param toasc If non zero, encode non ascii characters + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or the string is NULL. + */ +APR_DECLARE(const char *) apr_pescape_entity(apr_pool_t *p, const char *str, + int toasc) __attribute__((nonnull(1))); + +/** + * Decodes html entities or numeric character references in a string. If + * the string to be unescaped is syntactically incorrect, then the + * following fixups will be made: + * unknown entities will be left undecoded; + * references to unused numeric characters will be deleted. + * In particular, � will not be decoded, but will be deleted. + * @param unescaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_unescape_entity(char *unescaped, const char *str, + apr_ssize_t slen, apr_size_t *len); + +/** + * Decodes html entities or numeric character references in a string. If + * the string to be unescaped is syntactically incorrect, then the + * following fixups will be made: + * unknown entities will be left undecoded; + * references to unused numeric characters will be deleted. + * In particular, � will not be decoded, but will be deleted. + * @param p Pool to allocate from + * @param str The original string + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or the string is NULL. + */ +APR_DECLARE(const char *) apr_punescape_entity(apr_pool_t *p, const char *str) + __attribute__((nonnull(1))); + +/** + * Escape control characters in a string, as performed by the shell's + * 'echo' command. Characters are replaced as follows: + * \\a alert (bell), \\b backspace, \\f form feed, \\n new line, \\r carriage + * return, \\t horizontal tab, \\v vertical tab, \\ backslash. + * + * Any non ascii character will be encoded as '\\xHH', where HH is the hex + * code of the character. + * + * If quote is not zero, the double quote character will also be escaped. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param quote If non zero, encode double quotes + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_echo(char *escaped, const char *str, + apr_ssize_t slen, int quote, apr_size_t *len); + +/** + * Escape control characters in a string, as performed by the shell's + * 'echo' command, and return the results from a pool. Characters are + * replaced as follows: \\a alert (bell), \\b backspace, \\f form feed, + * \\n new line, \\r carriage return, \\t horizontal tab, \\v vertical tab, + * \\ backslash. + * + * Any non ascii character will be encoded as '\\xHH', where HH is the hex + * code of the character. + * + * If quote is not zero, the double quote character will also be escaped. + * @param p Pool to allocate from + * @param str The original string + * @param quote If non zero, encode double quotes + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or the string is NULL. + */ +APR_DECLARE(const char *) apr_pescape_echo(apr_pool_t *p, const char *str, + int quote); + +/** + * Convert binary data to a hex encoding. + * @param dest The destination buffer, can be NULL + * @param src The original buffer + * @param srclen The length of the original buffer + * @param colon If not zero, insert colon characters between hex digits. + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_hex(char *dest, const void *src, + apr_size_t srclen, int colon, apr_size_t *len); + +/** + * Convert binary data to a hex encoding, and return the results from a + * pool. + * @param p Pool to allocate from + * @param src The original buffer + * @param slen The length of the original buffer + * @param colon If not zero, insert colon characters between hex digits. + * @return A zero padded buffer allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *) apr_pescape_hex(apr_pool_t *p, const void *src, + apr_size_t slen, int colon) __attribute__((nonnull(1))); + +/** + * Convert hex encoded string to binary data. + * @param dest The destination buffer, can be NULL + * @param str The original buffer + * @param slen The length of the original buffer + * @param colon If not zero, ignore colon characters between hex digits. + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL, or APR_BADCH + * if a non hex character is present. + */ +APR_DECLARE(apr_status_t) apr_unescape_hex(void *dest, const char *str, + apr_ssize_t slen, int colon, apr_size_t *len); + +/** + * Convert hex encoding to binary data, and return the results from a pool. + * If the colon character appears between pairs of hex digits, it will be + * ignored. + * @param p Pool to allocate from + * @param str The original string + * @param colon If not zero, ignore colon characters between hex digits. + * @param len If present, returns the length of the final buffer + * @return A buffer allocated from the pool on success, or NULL if src was + * NULL, or a bad character was present. + */ +APR_DECLARE(const void *) apr_punescape_hex(apr_pool_t *p, const char *str, + int colon, apr_size_t *len); + +/** + * Apply LDAP escaping to binary data. Characters from RFC4514 and RFC4515 + * are escaped with their hex equivalents. + * @param dest The destination buffer, can be NULL + * @param src The original buffer + * @param srclen The length of the original buffer + * @param flags APR_ESCAPE_LDAP_DN for RFC4514, APR_ESCAPE_LDAP_FILTER for + * RFC4515, APR_ESCAPE_LDAP_ALL for both + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_ldap(char *dest, const void *src, + apr_ssize_t srclen, int flags, apr_size_t *len); + +/** + * Apply LDAP escaping to binary data, and return the results from a + * pool. Characters from RFC4514 and RFC4515 are escaped with their hex + * equivalents. + * @param p Pool to allocate from + * @param src The original buffer + * @param slen The length of the original buffer + * @param flags APR_ESCAPE_LDAP_DN for RFC4514, APR_ESCAPE_LDAP_FILTER for + * RFC4515, APR_ESCAPE_LDAP_ALL for both + * @return A zero padded buffer allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *) apr_pescape_ldap(apr_pool_t *p, const void *src, + apr_ssize_t slen, int flags) __attribute__((nonnull(1))); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ESCAPE_H */ diff --git a/c/dependencies/linux/apr/include/apr_file_info.h b/c/dependencies/linux/apr/include/apr_file_info.h new file mode 100644 index 00000000..cfddc68d --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_file_info.h @@ -0,0 +1,428 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_FILE_INFO_H +#define APR_FILE_INFO_H + +/** + * @file apr_file_info.h + * @brief APR File Information + */ + +#include "apr.h" +#include "apr_user.h" +#include "apr_pools.h" +#include "apr_tables.h" +#include "apr_time.h" +#include "apr_errno.h" + +#if APR_HAVE_SYS_UIO_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_file_info File Information + * @ingroup APR + * @{ + */ + +/* Many applications use the type member to determine the + * existance of a file or initialization of the file info, + * so the APR_NOFILE value must be distinct from APR_UNKFILE. + */ + +/** apr_filetype_e values for the filetype member of the + * apr_file_info_t structure + * @warning Not all of the filetypes below can be determined. + * For example, a given platform might not correctly report + * a socket descriptor as APR_SOCK if that type isn't + * well-identified on that platform. In such cases where + * a filetype exists but cannot be described by the recognized + * flags below, the filetype will be APR_UNKFILE. If the + * filetype member is not determined, the type will be APR_NOFILE. + */ + +typedef enum { + APR_NOFILE = 0, /**< no file type determined */ + APR_REG, /**< a regular file */ + APR_DIR, /**< a directory */ + APR_CHR, /**< a character device */ + APR_BLK, /**< a block device */ + APR_PIPE, /**< a FIFO / pipe */ + APR_LNK, /**< a symbolic link */ + APR_SOCK, /**< a [unix domain] socket */ + APR_UNKFILE = 127 /**< a file of some other unknown type */ +} apr_filetype_e; + +/** + * @defgroup apr_file_permissions File Permissions flags + * @{ + */ + +#define APR_FPROT_USETID 0x8000 /**< Set user id */ +#define APR_FPROT_UREAD 0x0400 /**< Read by user */ +#define APR_FPROT_UWRITE 0x0200 /**< Write by user */ +#define APR_FPROT_UEXECUTE 0x0100 /**< Execute by user */ + +#define APR_FPROT_GSETID 0x4000 /**< Set group id */ +#define APR_FPROT_GREAD 0x0040 /**< Read by group */ +#define APR_FPROT_GWRITE 0x0020 /**< Write by group */ +#define APR_FPROT_GEXECUTE 0x0010 /**< Execute by group */ + +#define APR_FPROT_WSTICKY 0x2000 /**< Sticky bit */ +#define APR_FPROT_WREAD 0x0004 /**< Read by others */ +#define APR_FPROT_WWRITE 0x0002 /**< Write by others */ +#define APR_FPROT_WEXECUTE 0x0001 /**< Execute by others */ + +#define APR_FPROT_OS_DEFAULT 0x0FFF /**< use OS's default permissions */ + +/* additional permission flags for apr_file_copy and apr_file_append */ +#define APR_FPROT_FILE_SOURCE_PERMS 0x1000 /**< Copy source file's permissions */ + +/* backcompat */ +#define APR_USETID APR_FPROT_USETID /**< @deprecated @see APR_FPROT_USETID */ +#define APR_UREAD APR_FPROT_UREAD /**< @deprecated @see APR_FPROT_UREAD */ +#define APR_UWRITE APR_FPROT_UWRITE /**< @deprecated @see APR_FPROT_UWRITE */ +#define APR_UEXECUTE APR_FPROT_UEXECUTE /**< @deprecated @see APR_FPROT_UEXECUTE */ +#define APR_GSETID APR_FPROT_GSETID /**< @deprecated @see APR_FPROT_GSETID */ +#define APR_GREAD APR_FPROT_GREAD /**< @deprecated @see APR_FPROT_GREAD */ +#define APR_GWRITE APR_FPROT_GWRITE /**< @deprecated @see APR_FPROT_GWRITE */ +#define APR_GEXECUTE APR_FPROT_GEXECUTE /**< @deprecated @see APR_FPROT_GEXECUTE */ +#define APR_WSTICKY APR_FPROT_WSTICKY /**< @deprecated @see APR_FPROT_WSTICKY */ +#define APR_WREAD APR_FPROT_WREAD /**< @deprecated @see APR_FPROT_WREAD */ +#define APR_WWRITE APR_FPROT_WWRITE /**< @deprecated @see APR_FPROT_WWRITE */ +#define APR_WEXECUTE APR_FPROT_WEXECUTE /**< @deprecated @see APR_FPROT_WEXECUTE */ +#define APR_OS_DEFAULT APR_FPROT_OS_DEFAULT /**< @deprecated @see APR_FPROT_OS_DEFAULT */ +#define APR_FILE_SOURCE_PERMS APR_FPROT_FILE_SOURCE_PERMS /**< @deprecated @see APR_FPROT_FILE_SOURCE_PERMS */ + +/** @} */ + + +/** + * Structure for referencing directories. + */ +typedef struct apr_dir_t apr_dir_t; +/** + * Structure for determining file permissions. + */ +typedef apr_int32_t apr_fileperms_t; +#if (defined WIN32) || (defined NETWARE) +/** + * Structure for determining the device the file is on. + */ +typedef apr_uint32_t apr_dev_t; +#else +/** + * Structure for determining the device the file is on. + */ +typedef dev_t apr_dev_t; +#endif + +/** + * @defgroup apr_file_stat Stat Functions + * @{ + */ +/** file info structure */ +typedef struct apr_finfo_t apr_finfo_t; + +#define APR_FINFO_LINK 0x00000001 /**< Stat the link not the file itself if it is a link */ +#define APR_FINFO_MTIME 0x00000010 /**< Modification Time */ +#define APR_FINFO_CTIME 0x00000020 /**< Creation or inode-changed time */ +#define APR_FINFO_ATIME 0x00000040 /**< Access Time */ +#define APR_FINFO_SIZE 0x00000100 /**< Size of the file */ +#define APR_FINFO_CSIZE 0x00000200 /**< Storage size consumed by the file */ +#define APR_FINFO_DEV 0x00001000 /**< Device */ +#define APR_FINFO_INODE 0x00002000 /**< Inode */ +#define APR_FINFO_NLINK 0x00004000 /**< Number of links */ +#define APR_FINFO_TYPE 0x00008000 /**< Type */ +#define APR_FINFO_USER 0x00010000 /**< User */ +#define APR_FINFO_GROUP 0x00020000 /**< Group */ +#define APR_FINFO_UPROT 0x00100000 /**< User protection bits */ +#define APR_FINFO_GPROT 0x00200000 /**< Group protection bits */ +#define APR_FINFO_WPROT 0x00400000 /**< World protection bits */ +#define APR_FINFO_ICASE 0x01000000 /**< if dev is case insensitive */ +#define APR_FINFO_NAME 0x02000000 /**< ->name in proper case */ + +#define APR_FINFO_MIN 0x00008170 /**< type, mtime, ctime, atime, size */ +#define APR_FINFO_IDENT 0x00003000 /**< dev and inode */ +#define APR_FINFO_OWNER 0x00030000 /**< user and group */ +#define APR_FINFO_PROT 0x00700000 /**< all protections */ +#define APR_FINFO_NORM 0x0073b170 /**< an atomic unix apr_stat() */ +#define APR_FINFO_DIRENT 0x02000000 /**< an atomic unix apr_dir_read() */ + +/** + * The file information structure. This is analogous to the POSIX + * stat structure. + */ +struct apr_finfo_t { + /** Allocates memory and closes lingering handles in the specified pool */ + apr_pool_t *pool; + /** The bitmask describing valid fields of this apr_finfo_t structure + * including all available 'wanted' fields and potentially more */ + apr_int32_t valid; + /** The access permissions of the file. Mimics Unix access rights. */ + apr_fileperms_t protection; + /** The type of file. One of APR_REG, APR_DIR, APR_CHR, APR_BLK, APR_PIPE, + * APR_LNK or APR_SOCK. If the type is undetermined, the value is APR_NOFILE. + * If the type cannot be determined, the value is APR_UNKFILE. + */ + apr_filetype_e filetype; + /** The user id that owns the file */ + apr_uid_t user; + /** The group id that owns the file */ + apr_gid_t group; + /** The inode of the file. */ + apr_ino_t inode; + /** The id of the device the file is on. */ + apr_dev_t device; + /** The number of hard links to the file. */ + apr_int32_t nlink; + /** The size of the file */ + apr_off_t size; + /** The storage size consumed by the file */ + apr_off_t csize; + /** The time the file was last accessed */ + apr_time_t atime; + /** The time the file was last modified */ + apr_time_t mtime; + /** The time the file was created, or the inode was last changed */ + apr_time_t ctime; + /** The pathname of the file (possibly unrooted) */ + const char *fname; + /** The file's name (no path) in filesystem case */ + const char *name; + /** Unused */ + struct apr_file_t *filehand; +}; + +/** + * get the specified file's stats. The file is specified by filename, + * instead of using a pre-opened file. + * @param finfo Where to store the information about the file, which is + * never touched if the call fails. + * @param fname The name of the file to stat. + * @param wanted The desired apr_finfo_t fields, as a bit flag of APR_FINFO_ + values + * @param pool the pool to use to allocate the new file. + * + * @note If @c APR_INCOMPLETE is returned all the fields in @a finfo may + * not be filled in, and you need to check the @c finfo->valid bitmask + * to verify that what you're looking for is there. + */ +APR_DECLARE(apr_status_t) apr_stat(apr_finfo_t *finfo, const char *fname, + apr_int32_t wanted, apr_pool_t *pool); + +/** @} */ +/** + * @defgroup apr_dir Directory Manipulation Functions + * @{ + */ + +/** + * Open the specified directory. + * @param new_dir The opened directory descriptor. + * @param dirname The full path to the directory (use / on all systems) + * @param pool The pool to use. + */ +APR_DECLARE(apr_status_t) apr_dir_open(apr_dir_t **new_dir, + const char *dirname, + apr_pool_t *pool); + +/** + * close the specified directory. + * @param thedir the directory descriptor to close. + */ +APR_DECLARE(apr_status_t) apr_dir_close(apr_dir_t *thedir); + +/** + * Read the next entry from the specified directory. + * @param finfo the file info structure and filled in by apr_dir_read + * @param wanted The desired apr_finfo_t fields, as a bit flag of APR_FINFO_ + values + * @param thedir the directory descriptor returned from apr_dir_open + * @remark No ordering is guaranteed for the entries read. + * + * @note If @c APR_INCOMPLETE is returned all the fields in @a finfo may + * not be filled in, and you need to check the @c finfo->valid bitmask + * to verify that what you're looking for is there. When no more + * entries are available, APR_ENOENT is returned. + */ +APR_DECLARE(apr_status_t) apr_dir_read(apr_finfo_t *finfo, apr_int32_t wanted, + apr_dir_t *thedir); + +/** + * Rewind the directory to the first entry. + * @param thedir the directory descriptor to rewind. + */ +APR_DECLARE(apr_status_t) apr_dir_rewind(apr_dir_t *thedir); +/** @} */ + +/** + * @defgroup apr_filepath Filepath Manipulation Functions + * @{ + */ + +/** Cause apr_filepath_merge to fail if addpath is above rootpath + * @bug in APR 0.9 and 1.x, this flag's behavior is undefined + * if the rootpath is NULL or empty. In APR 2.0 this should be + * changed to imply NOTABSOLUTE if the rootpath is NULL or empty. + */ +#define APR_FILEPATH_NOTABOVEROOT 0x01 + +/** internal: Only meaningful with APR_FILEPATH_NOTABOVEROOT */ +#define APR_FILEPATH_SECUREROOTTEST 0x02 + +/** Cause apr_filepath_merge to fail if addpath is above rootpath, + * even given a rootpath /foo/bar and an addpath ../bar/bash + */ +#define APR_FILEPATH_SECUREROOT 0x03 + +/** Fail apr_filepath_merge if the merged path is relative */ +#define APR_FILEPATH_NOTRELATIVE 0x04 + +/** Fail apr_filepath_merge if the merged path is absolute */ +#define APR_FILEPATH_NOTABSOLUTE 0x08 + +/** Return the file system's native path format (e.g. path delimiters + * of ':' on MacOS9, '\' on Win32, etc.) */ +#define APR_FILEPATH_NATIVE 0x10 + +/** Resolve the true case of existing directories and file elements + * of addpath, (resolving any aliases on Win32) and append a proper + * trailing slash if a directory + */ +#define APR_FILEPATH_TRUENAME 0x20 + +/** + * Extract the rootpath from the given filepath + * @param rootpath the root file path returned with APR_SUCCESS or APR_EINCOMPLETE + * @param filepath the pathname to parse for its root component + * @param flags the desired rules to apply, from + *
+ *      APR_FILEPATH_NATIVE    Use native path separators (e.g. '\' on Win32)
+ *      APR_FILEPATH_TRUENAME  Tests that the root exists, and makes it proper
+ * 
+ * @param p the pool to allocate the new path string from + * @remark on return, filepath points to the first non-root character in the + * given filepath. In the simplest example, given a filepath of "/foo", + * returns the rootpath of "/" and filepath points at "foo". This is far + * more complex on other platforms, which will canonicalize the root form + * to a consistant format, given the APR_FILEPATH_TRUENAME flag, and also + * test for the validity of that root (e.g., that a drive d:/ or network + * share //machine/foovol/). + * The function returns APR_ERELATIVE if filepath isn't rooted (an + * error), APR_EINCOMPLETE if the root path is ambiguous (but potentially + * legitimate, e.g. "/" on Windows is incomplete because it doesn't specify + * the drive letter), or APR_EBADPATH if the root is simply invalid. + * APR_SUCCESS is returned if filepath is an absolute path. + */ +APR_DECLARE(apr_status_t) apr_filepath_root(const char **rootpath, + const char **filepath, + apr_int32_t flags, + apr_pool_t *p); + +/** + * Merge additional file path onto the previously processed rootpath + * @param newpath the merged paths returned + * @param rootpath the root file path (NULL uses the current working path) + * @param addpath the path to add to the root path + * @param flags the desired APR_FILEPATH_ rules to apply when merging + * @param p the pool to allocate the new path string from + * @remark if the flag APR_FILEPATH_TRUENAME is given, and the addpath + * contains wildcard characters ('*', '?') on platforms that don't support + * such characters within filenames, the paths will be merged, but the + * result code will be APR_EPATHWILD, and all further segments will not + * reflect the true filenames including the wildcard and following segments. + */ +APR_DECLARE(apr_status_t) apr_filepath_merge(char **newpath, + const char *rootpath, + const char *addpath, + apr_int32_t flags, + apr_pool_t *p); + +/** + * Split a search path into separate components + * @param pathelts the returned components of the search path + * @param liststr the search path (e.g., getenv("PATH")) + * @param p the pool to allocate the array and path components from + * @remark empty path components do not become part of @a pathelts. + * @remark the path separator in @a liststr is system specific; + * e.g., ':' on Unix, ';' on Windows, etc. + */ +APR_DECLARE(apr_status_t) apr_filepath_list_split(apr_array_header_t **pathelts, + const char *liststr, + apr_pool_t *p); + +/** + * Merge a list of search path components into a single search path + * @param liststr the returned search path; may be NULL if @a pathelts is empty + * @param pathelts the components of the search path + * @param p the pool to allocate the search path from + * @remark emtpy strings in the source array are ignored. + * @remark the path separator in @a liststr is system specific; + * e.g., ':' on Unix, ';' on Windows, etc. + */ +APR_DECLARE(apr_status_t) apr_filepath_list_merge(char **liststr, + apr_array_header_t *pathelts, + apr_pool_t *p); + +/** + * Return the default file path (for relative file names) + * @param path the default path string returned + * @param flags optional flag APR_FILEPATH_NATIVE to retrieve the + * default file path in os-native format. + * @param p the pool to allocate the default path string from + */ +APR_DECLARE(apr_status_t) apr_filepath_get(char **path, apr_int32_t flags, + apr_pool_t *p); + +/** + * Set the default file path (for relative file names) + * @param path the default path returned + * @param p the pool to allocate any working storage + */ +APR_DECLARE(apr_status_t) apr_filepath_set(const char *path, apr_pool_t *p); + +/** The FilePath character encoding is unknown */ +#define APR_FILEPATH_ENCODING_UNKNOWN 0 + +/** The FilePath character encoding is locale-dependent */ +#define APR_FILEPATH_ENCODING_LOCALE 1 + +/** The FilePath character encoding is UTF-8 */ +#define APR_FILEPATH_ENCODING_UTF8 2 + +/** + * Determine the encoding used internally by the FilePath functions + * @param style points to a variable which receives the encoding style flag + * @param p the pool to allocate any working storage + * @remark Use apr_os_locale_encoding() and/or apr_os_default_encoding() + * to get the name of the path encoding if it's not UTF-8. + */ +APR_DECLARE(apr_status_t) apr_filepath_encoding(int *style, apr_pool_t *p); +/** @} */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_FILE_INFO_H */ diff --git a/c/dependencies/linux/apr/include/apr_file_io.h b/c/dependencies/linux/apr/include/apr_file_io.h new file mode 100644 index 00000000..af931939 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_file_io.h @@ -0,0 +1,1005 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_FILE_IO_H +#define APR_FILE_IO_H + +/** + * @file apr_file_io.h + * @brief APR File I/O Handling + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_time.h" +#include "apr_errno.h" +#include "apr_file_info.h" +#include "apr_inherit.h" + +#define APR_WANT_STDIO /**< for SEEK_* */ +#define APR_WANT_IOVEC /**< for apr_file_writev */ +#include "apr_want.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_file_io File I/O Handling Functions + * @ingroup APR + * @{ + */ + +/** + * @defgroup apr_file_open_flags File Open Flags/Routines + * @{ + */ + +/* Note to implementors: Values in the range 0x00100000--0x80000000 + are reserved for platform-specific values. */ + +#define APR_FOPEN_READ 0x00001 /**< Open the file for reading */ +#define APR_FOPEN_WRITE 0x00002 /**< Open the file for writing */ +#define APR_FOPEN_CREATE 0x00004 /**< Create the file if not there */ +#define APR_FOPEN_APPEND 0x00008 /**< Append to the end of the file */ +#define APR_FOPEN_TRUNCATE 0x00010 /**< Open the file and truncate + to 0 length */ +#define APR_FOPEN_BINARY 0x00020 /**< Open the file in binary mode + (This flag is ignored on UNIX + because it has no meaning)*/ +#define APR_FOPEN_EXCL 0x00040 /**< Open should fail if #APR_FOPEN_CREATE + and file exists. */ +#define APR_FOPEN_BUFFERED 0x00080 /**< Open the file for buffered I/O */ +#define APR_FOPEN_DELONCLOSE 0x00100 /**< Delete the file after close */ +#define APR_FOPEN_XTHREAD 0x00200 /**< Platform dependent tag to open + the file for use across multiple + threads */ +#define APR_FOPEN_SHARELOCK 0x00400 /**< Platform dependent support for + higher level locked read/write + access to support writes across + process/machines */ +#define APR_FOPEN_NOCLEANUP 0x00800 /**< Do not register a cleanup + when the file is opened. The + apr_os_file_t handle in apr_file_t + will not be closed when the pool + is destroyed. */ +#define APR_FOPEN_SENDFILE_ENABLED 0x01000 /**< Advisory flag that this + file should support + apr_socket_sendfile operation */ +#define APR_FOPEN_LARGEFILE 0x04000 /**< Platform dependent flag to enable + * large file support, see WARNING below + */ +#define APR_FOPEN_SPARSE 0x08000 /**< Platform dependent flag to enable + * sparse file support, see WARNING below + */ +#define APR_FOPEN_NONBLOCK 0x40000 /**< Platform dependent flag to enable + * non blocking file io */ + + +/* backcompat */ +#define APR_READ APR_FOPEN_READ /**< @deprecated @see APR_FOPEN_READ */ +#define APR_WRITE APR_FOPEN_WRITE /**< @deprecated @see APR_FOPEN_WRITE */ +#define APR_CREATE APR_FOPEN_CREATE /**< @deprecated @see APR_FOPEN_CREATE */ +#define APR_APPEND APR_FOPEN_APPEND /**< @deprecated @see APR_FOPEN_APPEND */ +#define APR_TRUNCATE APR_FOPEN_TRUNCATE /**< @deprecated @see APR_FOPEN_TRUNCATE */ +#define APR_BINARY APR_FOPEN_BINARY /**< @deprecated @see APR_FOPEN_BINARY */ +#define APR_EXCL APR_FOPEN_EXCL /**< @deprecated @see APR_FOPEN_EXCL */ +#define APR_BUFFERED APR_FOPEN_BUFFERED /**< @deprecated @see APR_FOPEN_BUFFERED */ +#define APR_DELONCLOSE APR_FOPEN_DELONCLOSE /**< @deprecated @see APR_FOPEN_DELONCLOSE */ +#define APR_XTHREAD APR_FOPEN_XTHREAD /**< @deprecated @see APR_FOPEN_XTHREAD */ +#define APR_SHARELOCK APR_FOPEN_SHARELOCK /**< @deprecated @see APR_FOPEN_SHARELOCK */ +#define APR_FILE_NOCLEANUP APR_FOPEN_NOCLEANUP /**< @deprecated @see APR_FOPEN_NOCLEANUP */ +#define APR_SENDFILE_ENABLED APR_FOPEN_SENDFILE_ENABLED /**< @deprecated @see APR_FOPEN_SENDFILE_ENABLED */ +#define APR_LARGEFILE APR_FOPEN_LARGEFILE /**< @deprecated @see APR_FOPEN_LARGEFILE */ + +/** @def APR_FOPEN_LARGEFILE + * @warning APR_FOPEN_LARGEFILE flag only has effect on some + * platforms where sizeof(apr_off_t) == 4. Where implemented, it + * allows opening and writing to a file which exceeds the size which + * can be represented by apr_off_t (2 gigabytes). When a file's size + * does exceed 2Gb, apr_file_info_get() will fail with an error on the + * descriptor, likewise apr_stat()/apr_lstat() will fail on the + * filename. apr_dir_read() will fail with #APR_INCOMPLETE on a + * directory entry for a large file depending on the particular + * APR_FINFO_* flags. Generally, it is not recommended to use this + * flag. + * + * @def APR_FOPEN_SPARSE + * @warning APR_FOPEN_SPARSE may, depending on platform, convert a + * normal file to a sparse file. Some applications may be unable + * to decipher a sparse file, so it's critical that the sparse file + * flag should only be used for files accessed only by APR or other + * applications known to be able to decipher them. APR does not + * guarantee that it will compress the file into sparse segments + * if it was previously created and written without the sparse flag. + * On platforms which do not understand, or on file systems which + * cannot handle sparse files, the flag is ignored by apr_file_open(). + * + * @def APR_FOPEN_NONBLOCK + * @warning APR_FOPEN_NONBLOCK is not implemented on all platforms. + * Callers should be prepared for it to fail with #APR_ENOTIMPL. + */ + +/** @} */ + +/** + * @defgroup apr_file_seek_flags File Seek Flags + * @{ + */ + +/* flags for apr_file_seek */ +/** Set the file position */ +#define APR_SET SEEK_SET +/** Current */ +#define APR_CUR SEEK_CUR +/** Go to end of file */ +#define APR_END SEEK_END +/** @} */ + +/** + * @defgroup apr_file_attrs_set_flags File Attribute Flags + * @{ + */ + +/* flags for apr_file_attrs_set */ +#define APR_FILE_ATTR_READONLY 0x01 /**< File is read-only */ +#define APR_FILE_ATTR_EXECUTABLE 0x02 /**< File is executable */ +#define APR_FILE_ATTR_HIDDEN 0x04 /**< File is hidden */ +/** @} */ + +/** + * @defgroup apr_file_writev{_full} max iovec size + * @{ + */ +#if defined(DOXYGEN) +#define APR_MAX_IOVEC_SIZE 1024 /**< System dependent maximum + size of an iovec array */ +#elif defined(IOV_MAX) +#define APR_MAX_IOVEC_SIZE IOV_MAX +#elif defined(MAX_IOVEC) +#define APR_MAX_IOVEC_SIZE MAX_IOVEC +#else +#define APR_MAX_IOVEC_SIZE 1024 +#endif +/** @} */ + +/** File attributes */ +typedef apr_uint32_t apr_fileattrs_t; + +/** Type to pass as whence argument to apr_file_seek. */ +typedef int apr_seek_where_t; + +/** + * Structure for referencing files. + */ +typedef struct apr_file_t apr_file_t; + +/* File lock types/flags */ +/** + * @defgroup apr_file_lock_types File Lock Types + * @{ + */ + +#define APR_FLOCK_SHARED 1 /**< Shared lock. More than one process + or thread can hold a shared lock + at any given time. Essentially, + this is a "read lock", preventing + writers from establishing an + exclusive lock. */ +#define APR_FLOCK_EXCLUSIVE 2 /**< Exclusive lock. Only one process + may hold an exclusive lock at any + given time. This is analogous to + a "write lock". */ + +#define APR_FLOCK_TYPEMASK 0x000F /**< mask to extract lock type */ +#define APR_FLOCK_NONBLOCK 0x0010 /**< do not block while acquiring the + file lock */ +/** @} */ + +/** + * Open the specified file. + * @param newf The opened file descriptor. + * @param fname The full path to the file (using / on all systems) + * @param flag Or'ed value of: + * @li #APR_FOPEN_READ open for reading + * @li #APR_FOPEN_WRITE open for writing + * @li #APR_FOPEN_CREATE create the file if not there + * @li #APR_FOPEN_APPEND file ptr is set to end prior to all writes + * @li #APR_FOPEN_TRUNCATE set length to zero if file exists + * @li #APR_FOPEN_BINARY not a text file + * @li #APR_FOPEN_BUFFERED buffer the data. Default is non-buffered + * @li #APR_FOPEN_EXCL return error if #APR_FOPEN_CREATE and file exists + * @li #APR_FOPEN_DELONCLOSE delete the file after closing + * @li #APR_FOPEN_XTHREAD Platform dependent tag to open the file + * for use across multiple threads + * @li #APR_FOPEN_SHARELOCK Platform dependent support for higher + * level locked read/write access to support + * writes across process/machines + * @li #APR_FOPEN_NOCLEANUP Do not register a cleanup with the pool + * passed in on the @a pool argument (see below) + * @li #APR_FOPEN_SENDFILE_ENABLED Open with appropriate platform semantics + * for sendfile operations. Advisory only, + * apr_socket_sendfile does not check this flag + * @li #APR_FOPEN_LARGEFILE Platform dependent flag to enable large file + * support, see WARNING below + * @li #APR_FOPEN_SPARSE Platform dependent flag to enable sparse file + * support, see WARNING below + * @li #APR_FOPEN_NONBLOCK Platform dependent flag to enable + * non blocking file io + * @param perm Access permissions for file. + * @param pool The pool to use. + * @remark If perm is #APR_FPROT_OS_DEFAULT and the file is being created, + * appropriate default permissions will be used. + * @remark By default, the returned file descriptor will not be + * inherited by child processes created by apr_proc_create(). This + * can be changed using apr_file_inherit_set(). + */ +APR_DECLARE(apr_status_t) apr_file_open(apr_file_t **newf, const char *fname, + apr_int32_t flag, apr_fileperms_t perm, + apr_pool_t *pool); + +/** + * Close the specified file. + * @param file The file descriptor to close. + */ +APR_DECLARE(apr_status_t) apr_file_close(apr_file_t *file); + +/** + * Delete the specified file. + * @param path The full path to the file (using / on all systems) + * @param pool The pool to use. + * @remark If the file is open, it won't be removed until all + * instances are closed. + */ +APR_DECLARE(apr_status_t) apr_file_remove(const char *path, apr_pool_t *pool); + +/** + * Rename the specified file. + * @param from_path The full path to the original file (using / on all systems) + * @param to_path The full path to the new file (using / on all systems) + * @param pool The pool to use. + * @warning If a file exists at the new location, then it will be + * overwritten. Moving files or directories across devices may not be + * possible. + */ +APR_DECLARE(apr_status_t) apr_file_rename(const char *from_path, + const char *to_path, + apr_pool_t *pool); + +/** + * Create a hard link to the specified file. + * @param from_path The full path to the original file (using / on all systems) + * @param to_path The full path to the new file (using / on all systems) + * @remark Both files must reside on the same device. + */ +APR_DECLARE(apr_status_t) apr_file_link(const char *from_path, + const char *to_path); + +/** + * Copy the specified file to another file. + * @param from_path The full path to the original file (using / on all systems) + * @param to_path The full path to the new file (using / on all systems) + * @param perms Access permissions for the new file if it is created. + * In place of the usual or'd combination of file permissions, the + * value #APR_FPROT_FILE_SOURCE_PERMS may be given, in which case the source + * file's permissions are copied. + * @param pool The pool to use. + * @remark The new file does not need to exist, it will be created if required. + * @warning If the new file already exists, its contents will be overwritten. + */ +APR_DECLARE(apr_status_t) apr_file_copy(const char *from_path, + const char *to_path, + apr_fileperms_t perms, + apr_pool_t *pool); + +/** + * Append the specified file to another file. + * @param from_path The full path to the source file (use / on all systems) + * @param to_path The full path to the destination file (use / on all systems) + * @param perms Access permissions for the destination file if it is created. + * In place of the usual or'd combination of file permissions, the + * value #APR_FPROT_FILE_SOURCE_PERMS may be given, in which case the source + * file's permissions are copied. + * @param pool The pool to use. + * @remark The new file does not need to exist, it will be created if required. + * @remark Note that advanced filesystem permissions such as ACLs are not + * duplicated by this API. The target permissions (including duplicating the + * source file permissions) are assigned only when the target file does not yet + * exist. + */ +APR_DECLARE(apr_status_t) apr_file_append(const char *from_path, + const char *to_path, + apr_fileperms_t perms, + apr_pool_t *pool); + +/** + * Are we at the end of the file + * @param fptr The apr file we are testing. + * @remark Returns #APR_EOF if we are at the end of file, #APR_SUCCESS otherwise. + */ +APR_DECLARE(apr_status_t) apr_file_eof(apr_file_t *fptr); + +/** + * Open standard error as an apr file pointer. + * @param thefile The apr file to use as stderr. + * @param pool The pool to allocate the file out of. + * + * @remark The only reason that the apr_file_open_std* functions exist + * is that you may not always have a stderr/out/in on Windows. This + * is generally a problem with newer versions of Windows and services. + * + * @remark The other problem is that the C library functions generally work + * differently on Windows and Unix. So, by using apr_file_open_std* + * functions, you can get a handle to an APR struct that works with + * the APR functions which are supposed to work identically on all + * platforms. + */ +APR_DECLARE(apr_status_t) apr_file_open_stderr(apr_file_t **thefile, + apr_pool_t *pool); + +/** + * open standard output as an apr file pointer. + * @param thefile The apr file to use as stdout. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_stdout(apr_file_t **thefile, + apr_pool_t *pool); + +/** + * open standard input as an apr file pointer. + * @param thefile The apr file to use as stdin. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_stdin(apr_file_t **thefile, + apr_pool_t *pool); + +/** + * open standard error as an apr file pointer, with flags. + * @param thefile The apr file to use as stderr. + * @param flags The flags to open the file with. Only the + * @li #APR_FOPEN_EXCL + * @li #APR_FOPEN_BUFFERED + * @li #APR_FOPEN_XTHREAD + * @li #APR_FOPEN_SHARELOCK + * @li #APR_FOPEN_SENDFILE_ENABLED + * @li #APR_FOPEN_LARGEFILE + * + * flags should be used. The #APR_FOPEN_WRITE flag will + * be set unconditionally. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_flags_stderr(apr_file_t **thefile, + apr_int32_t flags, + apr_pool_t *pool); + +/** + * open standard output as an apr file pointer, with flags. + * @param thefile The apr file to use as stdout. + * @param flags The flags to open the file with. Only the + * @li #APR_FOPEN_EXCL + * @li #APR_FOPEN_BUFFERED + * @li #APR_FOPEN_XTHREAD + * @li #APR_FOPEN_SHARELOCK + * @li #APR_FOPEN_SENDFILE_ENABLED + * @li #APR_FOPEN_LARGEFILE + * + * flags should be used. The #APR_FOPEN_WRITE flag will + * be set unconditionally. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_flags_stdout(apr_file_t **thefile, + apr_int32_t flags, + apr_pool_t *pool); + +/** + * open standard input as an apr file pointer, with flags. + * @param thefile The apr file to use as stdin. + * @param flags The flags to open the file with. Only the + * @li #APR_FOPEN_EXCL + * @li #APR_FOPEN_BUFFERED + * @li #APR_FOPEN_XTHREAD + * @li #APR_FOPEN_SHARELOCK + * @li #APR_FOPEN_SENDFILE_ENABLED + * @li #APR_FOPEN_LARGEFILE + * + * flags should be used. The #APR_FOPEN_WRITE flag will + * be set unconditionally. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_flags_stdin(apr_file_t **thefile, + apr_int32_t flags, + apr_pool_t *pool); + +/** + * Read data from the specified file. + * @param thefile The file descriptor to read from. + * @param buf The buffer to store the data to. + * @param nbytes On entry, the number of bytes to read; on exit, the number + * of bytes read. + * + * @remark apr_file_read() will read up to the specified number of + * bytes, but never more. If there isn't enough data to fill that + * number of bytes, all of the available data is read. The third + * argument is modified to reflect the number of bytes read. If a + * char was put back into the stream via ungetc, it will be the first + * character returned. + * + * @remark It is not possible for both bytes to be read and an #APR_EOF + * or other error to be returned. #APR_EINTR is never returned. + */ +APR_DECLARE(apr_status_t) apr_file_read(apr_file_t *thefile, void *buf, + apr_size_t *nbytes); + +/** + * Write data to the specified file. + * @param thefile The file descriptor to write to. + * @param buf The buffer which contains the data. + * @param nbytes On entry, the number of bytes to write; on exit, the number + * of bytes written. + * + * @remark apr_file_write() will write up to the specified number of + * bytes, but never more. If the OS cannot write that many bytes, it + * will write as many as it can. The third argument is modified to + * reflect the * number of bytes written. + * + * @remark It is possible for both bytes to be written and an error to + * be returned. #APR_EINTR is never returned. + */ +APR_DECLARE(apr_status_t) apr_file_write(apr_file_t *thefile, const void *buf, + apr_size_t *nbytes); + +/** + * Write data from iovec array to the specified file. + * @param thefile The file descriptor to write to. + * @param vec The array from which to get the data to write to the file. + * @param nvec The number of elements in the struct iovec array. This must + * be smaller than #APR_MAX_IOVEC_SIZE. If it isn't, the function + * will fail with #APR_EINVAL. + * @param nbytes The number of bytes written. + * + * @remark It is possible for both bytes to be written and an error to + * be returned. #APR_EINTR is never returned. + * + * @remark apr_file_writev() is available even if the underlying + * operating system doesn't provide writev(). + */ +APR_DECLARE(apr_status_t) apr_file_writev(apr_file_t *thefile, + const struct iovec *vec, + apr_size_t nvec, apr_size_t *nbytes); + +/** + * Read data from the specified file, ensuring that the buffer is filled + * before returning. + * @param thefile The file descriptor to read from. + * @param buf The buffer to store the data to. + * @param nbytes The number of bytes to read. + * @param bytes_read If non-NULL, this will contain the number of bytes read. + * + * @remark apr_file_read_full() will read up to the specified number of + * bytes, but never more. If there isn't enough data to fill that + * number of bytes, then the process/thread will block until it is + * available or EOF is reached. If a char was put back into the + * stream via ungetc, it will be the first character returned. + * + * @remark It is possible for both bytes to be read and an error to be + * returned. And if *bytes_read is less than nbytes, an accompanying + * error is _always_ returned. + * + * @remark #APR_EINTR is never returned. + */ +APR_DECLARE(apr_status_t) apr_file_read_full(apr_file_t *thefile, void *buf, + apr_size_t nbytes, + apr_size_t *bytes_read); + +/** + * Write data to the specified file, ensuring that all of the data is + * written before returning. + * @param thefile The file descriptor to write to. + * @param buf The buffer which contains the data. + * @param nbytes The number of bytes to write. + * @param bytes_written If non-NULL, set to the number of bytes written. + * + * @remark apr_file_write_full() will write up to the specified number of + * bytes, but never more. If the OS cannot write that many bytes, the + * process/thread will block until they can be written. Exceptional + * error such as "out of space" or "pipe closed" will terminate with + * an error. + * + * @remark It is possible for both bytes to be written and an error to + * be returned. And if *bytes_written is less than nbytes, an + * accompanying error is _always_ returned. + * + * @remark #APR_EINTR is never returned. + */ +APR_DECLARE(apr_status_t) apr_file_write_full(apr_file_t *thefile, + const void *buf, + apr_size_t nbytes, + apr_size_t *bytes_written); + + +/** + * Write data from iovec array to the specified file, ensuring that all of the + * data is written before returning. + * @param thefile The file descriptor to write to. + * @param vec The array from which to get the data to write to the file. + * @param nvec The number of elements in the struct iovec array. This must + * be smaller than #APR_MAX_IOVEC_SIZE. If it isn't, the function + * will fail with #APR_EINVAL. + * @param nbytes The number of bytes written. + * + * @remark apr_file_writev_full() is available even if the underlying + * operating system doesn't provide writev(). + */ +APR_DECLARE(apr_status_t) apr_file_writev_full(apr_file_t *thefile, + const struct iovec *vec, + apr_size_t nvec, + apr_size_t *nbytes); +/** + * Write a character into the specified file. + * @param ch The character to write. + * @param thefile The file descriptor to write to + */ +APR_DECLARE(apr_status_t) apr_file_putc(char ch, apr_file_t *thefile); + +/** + * Read a character from the specified file. + * @param ch The character to read into + * @param thefile The file descriptor to read from + */ +APR_DECLARE(apr_status_t) apr_file_getc(char *ch, apr_file_t *thefile); + +/** + * Put a character back onto a specified stream. + * @param ch The character to write. + * @param thefile The file descriptor to write to + */ +APR_DECLARE(apr_status_t) apr_file_ungetc(char ch, apr_file_t *thefile); + +/** + * Read a line from the specified file + * @param str The buffer to store the string in. + * @param len The length of the string + * @param thefile The file descriptor to read from + * @remark The buffer will be NUL-terminated if any characters are stored. + * The newline at the end of the line will not be stripped. + */ +APR_DECLARE(apr_status_t) apr_file_gets(char *str, int len, + apr_file_t *thefile); + +/** + * Write the string into the specified file. + * @param str The string to write. + * @param thefile The file descriptor to write to + */ +APR_DECLARE(apr_status_t) apr_file_puts(const char *str, apr_file_t *thefile); + +/** + * Flush the file's buffer. + * @param thefile The file descriptor to flush + */ +APR_DECLARE(apr_status_t) apr_file_flush(apr_file_t *thefile); + +/** + * Transfer all file modified data and metadata to disk. + * @param thefile The file descriptor to sync + */ +APR_DECLARE(apr_status_t) apr_file_sync(apr_file_t *thefile); + +/** + * Transfer all file modified data to disk. + * @param thefile The file descriptor to sync + */ +APR_DECLARE(apr_status_t) apr_file_datasync(apr_file_t *thefile); + +/** + * Duplicate the specified file descriptor. + * @param new_file The structure to duplicate into. + * @param old_file The file to duplicate. + * @param p The pool to use for the new file. + * @remark *new_file must point to a valid apr_file_t, or point to NULL. + */ +APR_DECLARE(apr_status_t) apr_file_dup(apr_file_t **new_file, + apr_file_t *old_file, + apr_pool_t *p); + +/** + * Duplicate the specified file descriptor and close the original + * @param new_file The old file that is to be closed and reused + * @param old_file The file to duplicate + * @param p The pool to use for the new file + * + * @remark new_file MUST point at a valid apr_file_t. It cannot be NULL. + */ +APR_DECLARE(apr_status_t) apr_file_dup2(apr_file_t *new_file, + apr_file_t *old_file, + apr_pool_t *p); + +/** + * Move the specified file descriptor to a new pool + * @param new_file Pointer in which to return the new apr_file_t + * @param old_file The file to move + * @param p The pool to which the descriptor is to be moved + * @remark Unlike apr_file_dup2(), this function doesn't do an + * OS dup() operation on the underlying descriptor; it just + * moves the descriptor's apr_file_t wrapper to a new pool. + * @remark The new pool need not be an ancestor of old_file's pool. + * @remark After calling this function, old_file may not be used + */ +APR_DECLARE(apr_status_t) apr_file_setaside(apr_file_t **new_file, + apr_file_t *old_file, + apr_pool_t *p); + +/** + * Give the specified apr file handle a new buffer + * @param thefile The file handle that is to be modified + * @param buffer The buffer + * @param bufsize The size of the buffer + * @remark It is possible to add a buffer to previously unbuffered + * file handles, the #APR_FOPEN_BUFFERED flag will be added to + * the file handle's flags. Likewise, with buffer=NULL and + * bufsize=0 arguments it is possible to make a previously + * buffered file handle unbuffered. + */ +APR_DECLARE(apr_status_t) apr_file_buffer_set(apr_file_t *thefile, + char * buffer, + apr_size_t bufsize); + +/** + * Get the size of any buffer for the specified apr file handle + * @param thefile The file handle + */ +APR_DECLARE(apr_size_t) apr_file_buffer_size_get(apr_file_t *thefile); + +/** + * Move the read/write file offset to a specified byte within a file. + * @param thefile The file descriptor + * @param where How to move the pointer, one of: + * @li #APR_SET -- set the offset to offset + * @li #APR_CUR -- add the offset to the current position + * @li #APR_END -- add the offset to the current file size + * @param offset The offset to move the pointer to. + * @remark The third argument is modified to be the offset the pointer + was actually moved to. + */ +APR_DECLARE(apr_status_t) apr_file_seek(apr_file_t *thefile, + apr_seek_where_t where, + apr_off_t *offset); + +/** + * Create an anonymous pipe. + * @param in The newly created pipe's file for reading. + * @param out The newly created pipe's file for writing. + * @param pool The pool to operate on. + * @remark By default, the returned file descriptors will be inherited + * by child processes created using apr_proc_create(). This can be + * changed using apr_file_inherit_unset(). + * @bug Some platforms cannot toggle between blocking and nonblocking, + * and when passing a pipe as a standard handle to an application which + * does not expect it, a non-blocking stream will fluxor the client app. + * @deprecated @see apr_file_pipe_create_pools() + */ +APR_DECLARE(apr_status_t) apr_file_pipe_create(apr_file_t **in, + apr_file_t **out, + apr_pool_t *pool); + +/** + * Create an anonymous pipe which portably supports async timeout options. + * @param in The newly created pipe's file for reading. + * @param out The newly created pipe's file for writing. + * @param blocking one of these values defined in apr_thread_proc.h; + * @li #APR_FULL_BLOCK + * @li #APR_READ_BLOCK + * @li #APR_WRITE_BLOCK + * @li #APR_FULL_NONBLOCK + * @param pool The pool to operate on. + * @remark By default, the returned file descriptors will be inherited + * by child processes created using apr_proc_create(). This can be + * changed using apr_file_inherit_unset(). + * @remark Some platforms cannot toggle between blocking and nonblocking, + * and when passing a pipe as a standard handle to an application which + * does not expect it, a non-blocking stream will fluxor the client app. + * Use this function rather than apr_file_pipe_create() to create pipes + * where one or both ends require non-blocking semantics. + * @deprecated @see apr_file_pipe_create_pools() + */ +APR_DECLARE(apr_status_t) apr_file_pipe_create_ex(apr_file_t **in, + apr_file_t **out, + apr_int32_t blocking, + apr_pool_t *pool); + +/** + * Create an anonymous pipe which portably supports async timeout options, + * placing each side of the pipe in a different pool. + * @param in The newly created pipe's file for reading. + * @param out The newly created pipe's file for writing. + * @param blocking one of these values defined in apr_thread_proc.h; + * @li #APR_FULL_BLOCK + * @li #APR_READ_BLOCK + * @li #APR_WRITE_BLOCK + * @li #APR_FULL_NONBLOCK + * @param pool_in The pool for the reading pipe. + * @param pool_out The pool for the writing pipe. + * @remark By default, the returned file descriptors will be inherited + * by child processes created using apr_proc_create(). This can be + * changed using apr_file_inherit_unset(). + * @remark Some platforms cannot toggle between blocking and nonblocking, + * and when passing a pipe as a standard handle to an application which + * does not expect it, a non-blocking stream will fluxor the client app. + * Use this function rather than apr_file_pipe_create() to create pipes + * where one or both ends require non-blocking semantics. + */ +APR_DECLARE(apr_status_t) apr_file_pipe_create_pools(apr_file_t **in, + apr_file_t **out, + apr_int32_t blocking, + apr_pool_t *pool_in, + apr_pool_t *pool_out); + +/** + * Create a named pipe. + * @param filename The filename of the named pipe + * @param perm The permissions for the newly created pipe. + * @param pool The pool to operate on. + */ +APR_DECLARE(apr_status_t) apr_file_namedpipe_create(const char *filename, + apr_fileperms_t perm, + apr_pool_t *pool); + +/** + * Get the timeout value for a pipe or manipulate the blocking state. + * @param thepipe The pipe we are getting a timeout for. + * @param timeout The current timeout value in microseconds. + */ +APR_DECLARE(apr_status_t) apr_file_pipe_timeout_get(apr_file_t *thepipe, + apr_interval_time_t *timeout); + +/** + * Set the timeout value for a pipe or manipulate the blocking state. + * @param thepipe The pipe we are setting a timeout on. + * @param timeout The timeout value in microseconds. Values < 0 mean wait + * forever, 0 means do not wait at all. + */ +APR_DECLARE(apr_status_t) apr_file_pipe_timeout_set(apr_file_t *thepipe, + apr_interval_time_t timeout); + +/** file (un)locking functions. */ + +/** + * Establish a lock on the specified, open file. The lock may be advisory + * or mandatory, at the discretion of the platform. The lock applies to + * the file as a whole, rather than a specific range. Locks are established + * on a per-thread/process basis; a second lock by the same thread will not + * block. + * @param thefile The file to lock. + * @param type The type of lock to establish on the file. + */ +APR_DECLARE(apr_status_t) apr_file_lock(apr_file_t *thefile, int type); + +/** + * Remove any outstanding locks on the file. + * @param thefile The file to unlock. + */ +APR_DECLARE(apr_status_t) apr_file_unlock(apr_file_t *thefile); + +/**accessor and general file_io functions. */ + +/** + * return the file name of the current file. + * @param new_path The path of the file. + * @param thefile The currently open file. + */ +APR_DECLARE(apr_status_t) apr_file_name_get(const char **new_path, + apr_file_t *thefile); + +/** + * Return the data associated with the current file. + * @param data The user data associated with the file. + * @param key The key to use for retrieving data associated with this file. + * @param file The currently open file. + */ +APR_DECLARE(apr_status_t) apr_file_data_get(void **data, const char *key, + apr_file_t *file); + +/** + * Set the data associated with the current file. + * @param file The currently open file. + * @param data The user data to associate with the file. + * @param key The key to use for associating data with the file. + * @param cleanup The cleanup routine to use when the file is destroyed. + */ +APR_DECLARE(apr_status_t) apr_file_data_set(apr_file_t *file, void *data, + const char *key, + apr_status_t (*cleanup)(void *)); + +/** + * Write a string to a file using a printf format. + * @param fptr The file to write to. + * @param format The format string + * @param ... The values to substitute in the format string + * @return The number of bytes written + */ +APR_DECLARE_NONSTD(int) apr_file_printf(apr_file_t *fptr, + const char *format, ...) + __attribute__((format(printf,2,3))); + +/** + * set the specified file's permission bits. + * @param fname The file (name) to apply the permissions to. + * @param perms The permission bits to apply to the file. + * + * @warning Some platforms may not be able to apply all of the + * available permission bits; #APR_INCOMPLETE will be returned if some + * permissions are specified which could not be set. + * + * @warning Platforms which do not implement this feature will return + * #APR_ENOTIMPL. + */ +APR_DECLARE(apr_status_t) apr_file_perms_set(const char *fname, + apr_fileperms_t perms); + +/** + * Set attributes of the specified file. + * @param fname The full path to the file (using / on all systems) + * @param attributes Or'd combination of + * @li #APR_FILE_ATTR_READONLY - make the file readonly + * @li #APR_FILE_ATTR_EXECUTABLE - make the file executable + * @li #APR_FILE_ATTR_HIDDEN - make the file hidden + * @param attr_mask Mask of valid bits in attributes. + * @param pool the pool to use. + * @remark This function should be used in preference to explicit manipulation + * of the file permissions, because the operations to provide these + * attributes are platform specific and may involve more than simply + * setting permission bits. + * @warning Platforms which do not implement this feature will return + * #APR_ENOTIMPL. + */ +APR_DECLARE(apr_status_t) apr_file_attrs_set(const char *fname, + apr_fileattrs_t attributes, + apr_fileattrs_t attr_mask, + apr_pool_t *pool); + +/** + * Set the mtime of the specified file. + * @param fname The full path to the file (using / on all systems) + * @param mtime The mtime to apply to the file. + * @param pool The pool to use. + * @warning Platforms which do not implement this feature will return + * #APR_ENOTIMPL. + */ +APR_DECLARE(apr_status_t) apr_file_mtime_set(const char *fname, + apr_time_t mtime, + apr_pool_t *pool); + +/** + * Create a new directory on the file system. + * @param path the path for the directory to be created. (use / on all systems) + * @param perm Permissions for the new directory. + * @param pool the pool to use. + */ +APR_DECLARE(apr_status_t) apr_dir_make(const char *path, apr_fileperms_t perm, + apr_pool_t *pool); + +/** Creates a new directory on the file system, but behaves like + * 'mkdir -p'. Creates intermediate directories as required. No error + * will be reported if PATH already exists. + * @param path the path for the directory to be created. (use / on all systems) + * @param perm Permissions for the new directory. + * @param pool the pool to use. + */ +APR_DECLARE(apr_status_t) apr_dir_make_recursive(const char *path, + apr_fileperms_t perm, + apr_pool_t *pool); + +/** + * Remove directory from the file system. + * @param path the path for the directory to be removed. (use / on all systems) + * @param pool the pool to use. + * @remark Removing a directory which is in-use (e.g., the current working + * directory, or during apr_dir_read, or with an open file) is not portable. + */ +APR_DECLARE(apr_status_t) apr_dir_remove(const char *path, apr_pool_t *pool); + +/** + * get the specified file's stats. + * @param finfo Where to store the information about the file. + * @param wanted The desired apr_finfo_t fields, as a bit flag of APR_FINFO_* values + * @param thefile The file to get information about. + */ +APR_DECLARE(apr_status_t) apr_file_info_get(apr_finfo_t *finfo, + apr_int32_t wanted, + apr_file_t *thefile); + + +/** + * Truncate the file's length to the specified offset + * @param fp The file to truncate + * @param offset The offset to truncate to. + * @remark The read/write file offset is repositioned to offset. + */ +APR_DECLARE(apr_status_t) apr_file_trunc(apr_file_t *fp, apr_off_t offset); + +/** + * Retrieve the flags that were passed into apr_file_open() + * when the file was opened. + * @return apr_int32_t the flags + */ +APR_DECLARE(apr_int32_t) apr_file_flags_get(apr_file_t *f); + +/** + * Get the pool used by the file. + */ +APR_POOL_DECLARE_ACCESSOR(file); + +/** + * Set a file to be inherited by child processes. + * + */ +APR_DECLARE_INHERIT_SET(file); + +/** + * Unset a file from being inherited by child processes. + */ +APR_DECLARE_INHERIT_UNSET(file); + +/** + * Open a temporary file + * @param fp The apr file to use as a temporary file. + * @param templ The template to use when creating a temp file. + * @param flags The flags to open the file with. If this is zero, + * the file is opened with + * #APR_FOPEN_CREATE | #APR_FOPEN_READ | #APR_FOPEN_WRITE | + * #APR_FOPEN_EXCL | #APR_FOPEN_DELONCLOSE + * @param p The pool to allocate the file out of. + * @remark + * This function generates a unique temporary file name from template. + * The last six characters of template must be XXXXXX and these are replaced + * with a string that makes the filename unique. Since it will be modified, + * template must not be a string constant, but should be declared as a character + * array. + * + */ +APR_DECLARE(apr_status_t) apr_file_mktemp(apr_file_t **fp, char *templ, + apr_int32_t flags, apr_pool_t *p); + + +/** + * Find an existing directory suitable as a temporary storage location. + * @param temp_dir The temp directory. + * @param p The pool to use for any necessary allocations. + * @remark + * This function uses an algorithm to search for a directory that an + * an application can use for temporary storage. + * + */ +APR_DECLARE(apr_status_t) apr_temp_dir_get(const char **temp_dir, + apr_pool_t *p); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_FILE_IO_H */ diff --git a/c/dependencies/linux/apr/include/apr_fnmatch.h b/c/dependencies/linux/apr/include/apr_fnmatch.h new file mode 100644 index 00000000..e8f6b03c --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_fnmatch.h @@ -0,0 +1,153 @@ +/* + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)fnmatch.h 8.1 (Berkeley) 6/2/93 + */ + +/* This file has been modified by the Apache Software Foundation. */ +#ifndef _APR_FNMATCH_H_ +#define _APR_FNMATCH_H_ + +/** + * @file apr_fnmatch.h + * @brief APR FNMatch Functions + */ + +#include "apr_errno.h" +#include "apr_tables.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_fnmatch Filename Matching Functions + * @ingroup APR + * @{ + */ + +#define APR_FNM_NOMATCH 1 /**< Match failed. */ + +#define APR_FNM_NOESCAPE 0x01 /**< Disable backslash escaping. */ +#define APR_FNM_PATHNAME 0x02 /**< Slash must be matched by slash. */ +#define APR_FNM_PERIOD 0x04 /**< Period must be matched by period. */ +#define APR_FNM_CASE_BLIND 0x08 /**< Compare characters case-insensitively. */ + +/** + * Try to match the string to the given pattern, return APR_SUCCESS if + * match, else return APR_FNM_NOMATCH. Note that there is no such thing as + * an illegal pattern. + * + * With all flags unset, a pattern is interpreted as such: + * + * PATTERN: Backslash followed by any character, including another + * backslash.
+ * MATCHES: That character exactly. + * + *

+ * PATTERN: ?
+ * MATCHES: Any single character. + *

+ * + *

+ * PATTERN: *
+ * MATCHES: Any sequence of zero or more characters. (Note that multiple + * *s in a row are equivalent to one.) + * + * PATTERN: Any character other than \?*[ or a \ at the end of the pattern
+ * MATCHES: That character exactly. (Case sensitive.) + * + * PATTERN: [ followed by a class description followed by ]
+ * MATCHES: A single character described by the class description. + * (Never matches, if the class description reaches until the + * end of the string without a ].) If the first character of + * the class description is ^ or !, the sense of the description + * is reversed. The rest of the class description is a list of + * single characters or pairs of characters separated by -. Any + * of those characters can have a backslash in front of them, + * which is ignored; this lets you use the characters ] and - + * in the character class, as well as ^ and ! at the + * beginning. The pattern matches a single character if it + * is one of the listed characters or falls into one of the + * listed ranges (inclusive, case sensitive). Ranges with + * the first character larger than the second are legal but + * never match. Edge cases: [] never matches, and [^] and [!] + * always match without consuming a character. + * + * Note that these patterns attempt to match the entire string, not + * just find a substring matching the pattern. + * + * @param pattern The pattern to match to + * @param strings The string we are trying to match + * @param flags flags to use in the match. Bitwise OR of: + *

+ *              APR_FNM_NOESCAPE       Disable backslash escaping
+ *              APR_FNM_PATHNAME       Slash must be matched by slash
+ *              APR_FNM_PERIOD         Period must be matched by period
+ *              APR_FNM_CASE_BLIND     Compare characters case-insensitively.
+ * 
+ */ + +APR_DECLARE(apr_status_t) apr_fnmatch(const char *pattern, + const char *strings, int flags); + +/** + * Determine if the given pattern is a regular expression. + * @param pattern The pattern to search for glob characters. + * @return non-zero if pattern has any glob characters in it + */ +APR_DECLARE(int) apr_fnmatch_test(const char *pattern); + +/** + * Find all files that match a specified pattern in a directory. + * @param dir_pattern The pattern to use for finding files, appended + * to the search directory. The pattern is anything following the + * final forward or backward slash in the parameter. If no slash + * is found, the current directory is searched. + * @param result Array to use when storing the results + * @param p The pool to use. + * @return APR_SUCCESS if no processing errors occurred, APR error + * code otherwise + * @remark The returned array may be empty even if APR_SUCCESS was + * returned. + */ +APR_DECLARE(apr_status_t) apr_match_glob(const char *dir_pattern, + apr_array_header_t **result, + apr_pool_t *p); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !_APR_FNMATCH_H_ */ diff --git a/c/dependencies/linux/apr/include/apr_general.h b/c/dependencies/linux/apr/include/apr_general.h new file mode 100644 index 00000000..fa073c85 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_general.h @@ -0,0 +1,244 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_GENERAL_H +#define APR_GENERAL_H + +/** + * @file apr_general.h + * This is collection of oddballs that didn't fit anywhere else, + * and might move to more appropriate headers with the release + * of APR 1.0. + * @brief APR Miscellaneous library routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" + +#if APR_HAVE_SIGNAL_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_general Miscellaneous library routines + * @ingroup APR + * This is collection of oddballs that didn't fit anywhere else, + * and might move to more appropriate headers with the release + * of APR 1.0. + * @{ + */ + +/** FALSE */ +#ifndef FALSE +#define FALSE 0 +#endif +/** TRUE */ +#ifndef TRUE +#define TRUE (!FALSE) +#endif + +/** a space */ +#define APR_ASCII_BLANK '\040' +/** a carrige return */ +#define APR_ASCII_CR '\015' +/** a line feed */ +#define APR_ASCII_LF '\012' +/** a tab */ +#define APR_ASCII_TAB '\011' + +/** signal numbers typedef */ +typedef int apr_signum_t; + +/** + * Finding offsets of elements within structures. + * Taken from the X code... they've sweated portability of this stuff + * so we don't have to. Sigh... + * @param p_type pointer type name + * @param field data field within the structure pointed to + * @return offset + */ + +#if defined(CRAY) || (defined(__arm) && !(defined(LINUX) || defined(__FreeBSD__))) +#ifdef __STDC__ +#define APR_OFFSET(p_type,field) _Offsetof(p_type,field) +#else +#ifdef CRAY2 +#define APR_OFFSET(p_type,field) \ + (sizeof(int)*((unsigned int)&(((p_type)NULL)->field))) + +#else /* !CRAY2 */ + +#define APR_OFFSET(p_type,field) ((unsigned int)&(((p_type)NULL)->field)) + +#endif /* !CRAY2 */ +#endif /* __STDC__ */ +#else /* ! (CRAY || __arm) */ + +#define APR_OFFSET(p_type,field) \ + ((long) (((char *) (&(((p_type)NULL)->field))) - ((char *) NULL))) + +#endif /* !CRAY */ + +/** + * Finding offsets of elements within structures. + * @param s_type structure type name + * @param field data field within the structure + * @return offset + */ +#if defined(offsetof) && !defined(__cplusplus) +#define APR_OFFSETOF(s_type,field) offsetof(s_type,field) +#else +#define APR_OFFSETOF(s_type,field) APR_OFFSET(s_type*,field) +#endif + +#ifndef DOXYGEN + +/* A couple of prototypes for functions in case some platform doesn't + * have it + */ +#if (!APR_HAVE_STRCASECMP) && (APR_HAVE_STRICMP) +#define strcasecmp(s1, s2) stricmp(s1, s2) +#elif (!APR_HAVE_STRCASECMP) +int strcasecmp(const char *a, const char *b); +#endif + +#if (!APR_HAVE_STRNCASECMP) && (APR_HAVE_STRNICMP) +#define strncasecmp(s1, s2, n) strnicmp(s1, s2, n) +#elif (!APR_HAVE_STRNCASECMP) +int strncasecmp(const char *a, const char *b, size_t n); +#endif + +#endif + +/** + * Alignment macros + */ + +/* APR_ALIGN() is only to be used to align on a power of 2 boundary */ +#define APR_ALIGN(size, boundary) \ + (((size) + ((boundary) - 1)) & ~((boundary) - 1)) + +/** Default alignment */ +#define APR_ALIGN_DEFAULT(size) APR_ALIGN(size, 8) + + +/** + * String and memory functions + */ + +/* APR_STRINGIFY is defined here, and also in apr_release.h, so wrap it */ +#ifndef APR_STRINGIFY +/** Properly quote a value as a string in the C preprocessor */ +#define APR_STRINGIFY(n) APR_STRINGIFY_HELPER(n) +/** Helper macro for APR_STRINGIFY */ +#define APR_STRINGIFY_HELPER(n) #n +#endif + +#if (!APR_HAVE_MEMMOVE) +#define memmove(a,b,c) bcopy(b,a,c) +#endif + +#if (!APR_HAVE_MEMCHR) +void *memchr(const void *s, int c, size_t n); +#endif + +/** @} */ + +/** + * @defgroup apr_library Library initialization and termination + * @{ + */ + +/** + * Setup any APR internal data structures. This MUST be the first function + * called for any APR library. It is safe to call apr_initialize several + * times as long as apr_terminate() is called the same number of times. + * @remark See apr_app_initialize() if this is an application, rather than + * a library consumer of apr. + */ +APR_DECLARE(apr_status_t) apr_initialize(void); + +/** + * Set up an application with normalized argc, argv (and optionally env) in + * order to deal with platform-specific oddities, such as Win32 services, + * code pages and signals. This must be the first function called for any + * APR program. + * @param argc Pointer to the argc that may be corrected + * @param argv Pointer to the argv that may be corrected + * @param env Pointer to the env that may be corrected, may be NULL + * @remark See apr_initialize() if this is a library consumer of apr. + * Otherwise, this call is identical to apr_initialize(), and must be closed + * with a call to apr_terminate() at the end of program execution. + */ +APR_DECLARE(apr_status_t) apr_app_initialize(int *argc, + char const * const * *argv, + char const * const * *env); + +/** + * Tear down any APR internal data structures which aren't torn down + * automatically. apr_terminate must be called once for every call to + * apr_initialize() or apr_app_initialize(). + * @remark An APR program must call this function at termination once it + * has stopped using APR services. The APR developers suggest using + * @c atexit(apr_terminate) to ensure this is called. When using APR + * from a language other than C that has problems with the calling + * convention, use apr_terminate2() instead. + * @see apr_terminate2 + */ +APR_DECLARE_NONSTD(void) apr_terminate(void); + +/** + * Tear down any APR internal data structures which aren't torn down + * automatically, same as apr_terminate() + * @remark An APR program must call either the apr_terminate() or apr_terminate2 + * function once it it has finished using APR services. The APR + * developers suggest using @c atexit(apr_terminate) to ensure this is done. + * apr_terminate2 exists to allow non-c language apps to tear down apr, + * while apr_terminate() is recommended from c language applications. + */ +APR_DECLARE(void) apr_terminate2(void); + +/** @} */ + +/** + * @defgroup apr_random Random Functions + * @{ + */ + +#if APR_HAS_RANDOM || defined(DOXYGEN) + +/* TODO: I'm not sure this is the best place to put this prototype...*/ +/** + * Generate random bytes. + * @param buf Buffer to fill with random bytes + * @param length Length of buffer in bytes + */ +APR_DECLARE(apr_status_t) apr_generate_random_bytes(unsigned char * buf, + apr_size_t length); + +#endif +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_GENERAL_H */ diff --git a/c/dependencies/linux/apr/include/apr_getopt.h b/c/dependencies/linux/apr/include/apr_getopt.h new file mode 100644 index 00000000..75ad5663 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_getopt.h @@ -0,0 +1,160 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_GETOPT_H +#define APR_GETOPT_H + +/** + * @file apr_getopt.h + * @brief APR Command Arguments (getopt) + */ + +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_getopt Command Argument Parsing + * @ingroup APR + * @{ + */ + +/** + * An @c apr_getopt_t error callback function. + * + * @a arg is this @c apr_getopt_t's @c errarg member. + */ +typedef void (apr_getopt_err_fn_t)(void *arg, const char *err, ...); + +/** @see apr_getopt_t */ +typedef struct apr_getopt_t apr_getopt_t; + +/** + * Structure to store command line argument information. + */ +struct apr_getopt_t { + /** context for processing */ + apr_pool_t *cont; + /** function to print error message (NULL == no messages) */ + apr_getopt_err_fn_t *errfn; + /** user defined first arg to pass to error message */ + void *errarg; + /** index into parent argv vector */ + int ind; + /** character checked for validity */ + int opt; + /** reset getopt */ + int reset; + /** count of arguments */ + int argc; + /** array of pointers to arguments */ + const char **argv; + /** argument associated with option */ + char const* place; + /** set to nonzero to support interleaving options with regular args */ + int interleave; + /** start of non-option arguments skipped for interleaving */ + int skip_start; + /** end of non-option arguments skipped for interleaving */ + int skip_end; +}; + +/** @see apr_getopt_option_t */ +typedef struct apr_getopt_option_t apr_getopt_option_t; + +/** + * Structure used to describe options that getopt should search for. + */ +struct apr_getopt_option_t { + /** long option name, or NULL if option has no long name */ + const char *name; + /** option letter, or a value greater than 255 if option has no letter */ + int optch; + /** nonzero if option takes an argument */ + int has_arg; + /** a description of the option */ + const char *description; +}; + +/** + * Initialize the arguments for parsing by apr_getopt(). + * @param os The options structure created for apr_getopt() + * @param cont The pool to operate on + * @param argc The number of arguments to parse + * @param argv The array of arguments to parse + * @remark Arguments 3 and 4 are most commonly argc and argv from main(argc, argv) + * The (*os)->errfn is initialized to fprintf(stderr... but may be overridden. + */ +APR_DECLARE(apr_status_t) apr_getopt_init(apr_getopt_t **os, apr_pool_t *cont, + int argc, const char * const *argv); + +/** + * Parse the options initialized by apr_getopt_init(). + * @param os The apr_opt_t structure returned by apr_getopt_init() + * @param opts A string of characters that are acceptable options to the + * program. Characters followed by ":" are required to have an + * option associated + * @param option_ch The next option character parsed + * @param option_arg The argument following the option character: + * @return There are four potential status values on exit. They are: + *
+ *             APR_EOF      --  No more options to parse
+ *             APR_BADCH    --  Found a bad option character
+ *             APR_BADARG   --  No argument followed the option flag
+ *             APR_SUCCESS  --  The next option was found.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_getopt(apr_getopt_t *os, const char *opts, + char *option_ch, const char **option_arg); + +/** + * Parse the options initialized by apr_getopt_init(), accepting long + * options beginning with "--" in addition to single-character + * options beginning with "-". + * @param os The apr_getopt_t structure created by apr_getopt_init() + * @param opts A pointer to a list of apr_getopt_option_t structures, which + * can be initialized with { "name", optch, has_args }. has_args + * is nonzero if the option requires an argument. A structure + * with an optch value of 0 terminates the list. + * @param option_ch Receives the value of "optch" from the apr_getopt_option_t + * structure corresponding to the next option matched. + * @param option_arg Receives the argument following the option, if any. + * @return There are four potential status values on exit. They are: + *
+ *             APR_EOF      --  No more options to parse
+ *             APR_BADCH    --  Found a bad option character
+ *             APR_BADARG   --  No argument followed the option flag
+ *             APR_SUCCESS  --  The next option was found.
+ * 
+ * When APR_SUCCESS is returned, os->ind gives the index of the first + * non-option argument. On error, a message will be printed to stdout unless + * os->err is set to 0. If os->interleave is set to nonzero, options can come + * after arguments, and os->argv will be permuted to leave non-option arguments + * at the end (the original argv is unaffected). + */ +APR_DECLARE(apr_status_t) apr_getopt_long(apr_getopt_t *os, + const apr_getopt_option_t *opts, + int *option_ch, + const char **option_arg); +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_GETOPT_H */ diff --git a/c/dependencies/linux/apr/include/apr_global_mutex.h b/c/dependencies/linux/apr/include/apr_global_mutex.h new file mode 100644 index 00000000..e3cba23f --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_global_mutex.h @@ -0,0 +1,195 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_GLOBAL_MUTEX_H +#define APR_GLOBAL_MUTEX_H + +/** + * @file apr_global_mutex.h + * @brief APR Global Locking Routines + */ + +#include "apr.h" +#include "apr_proc_mutex.h" /* only for apr_lockmech_e */ +#include "apr_pools.h" +#include "apr_errno.h" +#if APR_PROC_MUTEX_IS_GLOBAL +#include "apr_proc_mutex.h" +#endif +#include "apr_time.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_GlobalMutex Global Locking Routines + * @ingroup APR + * @{ + */ + +#if !APR_PROC_MUTEX_IS_GLOBAL || defined(DOXYGEN) + +/** Opaque global mutex structure. */ +typedef struct apr_global_mutex_t apr_global_mutex_t; + +/* Function definitions */ + +/** + * Create and initialize a mutex that can be used to synchronize both + * processes and threads. Note: There is considerable overhead in using + * this API if only cross-process or cross-thread mutual exclusion is + * required. See apr_proc_mutex.h and apr_thread_mutex.h for more + * specialized lock routines. + * @param mutex the memory address where the newly created mutex will be + * stored. + * @param fname A file name to use if the lock mechanism requires one. This + * argument should always be provided. The lock code itself will + * determine if it should be used. + * @param mech The mechanism to use for the interprocess lock, if any; one of + *
+ *            APR_LOCK_FCNTL
+ *            APR_LOCK_FLOCK
+ *            APR_LOCK_SYSVSEM
+ *            APR_LOCK_POSIXSEM
+ *            APR_LOCK_PROC_PTHREAD
+ *            APR_LOCK_DEFAULT     pick the default mechanism for the platform
+ *            APR_LOCK_DEFAULT_TIMED pick the default timed mechanism
+ * 
+ * @param pool the pool from which to allocate the mutex. + * @warning Check APR_HAS_foo_SERIALIZE defines to see if the platform supports + * APR_LOCK_foo. Only APR_LOCK_DEFAULT is portable. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_create(apr_global_mutex_t **mutex, + const char *fname, + apr_lockmech_e mech, + apr_pool_t *pool); + +/** + * Re-open a mutex in a child process. + * @param mutex The newly re-opened mutex structure. + * @param fname A file name to use if the mutex mechanism requires one. This + * argument should always be provided. The mutex code itself will + * determine if it should be used. This filename should be the + * same one that was passed to apr_global_mutex_create(). + * @param pool The pool to operate on. + * @remark This function must be called to maintain portability, even + * if the underlying lock mechanism does not require it. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_child_init( + apr_global_mutex_t **mutex, + const char *fname, + apr_pool_t *pool); + +/** + * Acquire the lock for the given mutex. If the mutex is already locked, + * the current thread will be put to sleep until the lock becomes available. + * @param mutex the mutex on which to acquire the lock. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_lock(apr_global_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex. If the mutex has already + * been acquired, the call returns immediately with APR_EBUSY. Note: it + * is important that the APR_STATUS_IS_EBUSY(s) macro be used to determine + * if the return value was APR_EBUSY, for portability reasons. + * @param mutex the mutex on which to attempt the lock acquiring. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_trylock(apr_global_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex until timeout expires. + * If the acquisition time outs, the call returns with APR_TIMEUP. + * @param mutex the mutex on which to attempt the lock acquiring. + * @param timeout the relative timeout (microseconds). + * @note A negative or nul timeout means immediate attempt, returning + * APR_TIMEUP without blocking if it the lock is already acquired. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_timedlock(apr_global_mutex_t *mutex, + apr_interval_time_t timeout); + +/** + * Release the lock for the given mutex. + * @param mutex the mutex from which to release the lock. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_unlock(apr_global_mutex_t *mutex); + +/** + * Destroy the mutex and free the memory associated with the lock. + * @param mutex the mutex to destroy. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_destroy(apr_global_mutex_t *mutex); + +/** + * Return the name of the lockfile for the mutex, or NULL + * if the mutex doesn't use a lock file + */ +APR_DECLARE(const char *) apr_global_mutex_lockfile(apr_global_mutex_t *mutex); + +/** + * Get the mechanism of the mutex, as it relates to the actual method + * used for the underlying apr_proc_mutex_t. + * @param mutex the mutex to get the mechanism from. + */ +APR_DECLARE(apr_lockmech_e) apr_global_mutex_mech(apr_global_mutex_t *mutex); + +/** + * Get the mechanism's name of the mutex, as it relates to the actual method + * used for the underlying apr_proc_mutex_t. + * @param mutex the mutex to get the mechanism's name from. + */ +APR_DECLARE(const char *) apr_global_mutex_name(apr_global_mutex_t *mutex); + +/** + * Set mutex permissions. + */ +APR_PERMS_SET_IMPLEMENT(global_mutex); + +/** + * Get the pool used by this global_mutex. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(global_mutex); + +#else /* APR_PROC_MUTEX_IS_GLOBAL */ + +/* Some platforms [e.g. Win32] have cross process locks that are truly + * global locks, since there isn't the concept of cross-process locks. + * Define these platforms in terms of an apr_proc_mutex_t. + */ + +#define apr_global_mutex_t apr_proc_mutex_t +#define apr_global_mutex_create apr_proc_mutex_create +#define apr_global_mutex_child_init apr_proc_mutex_child_init +#define apr_global_mutex_lock apr_proc_mutex_lock +#define apr_global_mutex_trylock apr_proc_mutex_trylock +#define apr_global_mutex_unlock apr_proc_mutex_unlock +#define apr_global_mutex_destroy apr_proc_mutex_destroy +#define apr_global_mutex_lockfile apr_proc_mutex_lockfile +#define apr_global_mutex_mech apr_proc_mutex_mech +#define apr_global_mutex_name apr_proc_mutex_name +#define apr_global_mutex_perms_set apr_proc_mutex_perms_set +#define apr_global_mutex_pool_get apr_proc_mutex_pool_get + +#endif + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ndef APR_GLOBAL_MUTEX_H */ diff --git a/c/dependencies/linux/apr/include/apr_hash.h b/c/dependencies/linux/apr/include/apr_hash.h new file mode 100644 index 00000000..2276f84c --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_hash.h @@ -0,0 +1,283 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_HASH_H +#define APR_HASH_H + +/** + * @file apr_hash.h + * @brief APR Hash Tables + */ + +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_hash Hash Tables + * @ingroup APR + * @{ + */ + +/** + * When passing a key to apr_hash_set or apr_hash_get, this value can be + * passed to indicate a string-valued key, and have apr_hash compute the + * length automatically. + * + * @remark apr_hash will use strlen(key) for the length. The NUL terminator + * is not included in the hash value (why throw a constant in?). + * Since the hash table merely references the provided key (rather + * than copying it), apr_hash_this() will return the NUL-term'd key. + */ +#define APR_HASH_KEY_STRING (-1) + +/** + * Abstract type for hash tables. + */ +typedef struct apr_hash_t apr_hash_t; + +/** + * Abstract type for scanning hash tables. + */ +typedef struct apr_hash_index_t apr_hash_index_t; + +/** + * Callback functions for calculating hash values. + * @param key The key. + * @param klen The length of the key, or APR_HASH_KEY_STRING to use the string + * length. If APR_HASH_KEY_STRING then returns the actual key length. + */ +typedef unsigned int (*apr_hashfunc_t)(const char *key, apr_ssize_t *klen); + +/** + * The default hash function. + */ +APR_DECLARE_NONSTD(unsigned int) apr_hashfunc_default(const char *key, + apr_ssize_t *klen); + +/** + * Create a hash table. + * @param pool The pool to allocate the hash table out of + * @return The hash table just created + */ +APR_DECLARE(apr_hash_t *) apr_hash_make(apr_pool_t *pool); + +/** + * Create a hash table with a custom hash function + * @param pool The pool to allocate the hash table out of + * @param hash_func A custom hash function. + * @return The hash table just created + */ +APR_DECLARE(apr_hash_t *) apr_hash_make_custom(apr_pool_t *pool, + apr_hashfunc_t hash_func); + +/** + * Make a copy of a hash table + * @param pool The pool from which to allocate the new hash table + * @param h The hash table to clone + * @return The hash table just created + * @remark Makes a shallow copy + */ +APR_DECLARE(apr_hash_t *) apr_hash_copy(apr_pool_t *pool, + const apr_hash_t *h); + +/** + * Associate a value with a key in a hash table. + * @param ht The hash table + * @param key Pointer to the key + * @param klen Length of the key. Can be APR_HASH_KEY_STRING to use the string length. + * @param val Value to associate with the key + * @remark If the value is NULL the hash entry is deleted. The key is stored as is, + * and so must have a lifetime at least as long as the hash table's pool. + */ +APR_DECLARE(void) apr_hash_set(apr_hash_t *ht, const void *key, + apr_ssize_t klen, const void *val); + +/** + * Look up the value associated with a key in a hash table. + * @param ht The hash table + * @param key Pointer to the key + * @param klen Length of the key. Can be APR_HASH_KEY_STRING to use the string length. + * @return Returns NULL if the key is not present. + */ +APR_DECLARE(void *) apr_hash_get(apr_hash_t *ht, const void *key, + apr_ssize_t klen); + +/** + * Start iterating over the entries in a hash table. + * @param p The pool to allocate the apr_hash_index_t iterator. If this + * pool is NULL, then an internal, non-thread-safe iterator is used. + * @param ht The hash table + * @return The iteration state + * @remark There is no restriction on adding or deleting hash entries during + * an iteration (although the results may be unpredictable unless all you do + * is delete the current entry) and multiple iterations can be in + * progress at the same time. + * + * @par Example: + * + * @code + * int sum_values(apr_pool_t *p, apr_hash_t *ht) + * { + * apr_hash_index_t *hi; + * void *val; + * int sum = 0; + * for (hi = apr_hash_first(p, ht); hi; hi = apr_hash_next(hi)) { + * apr_hash_this(hi, NULL, NULL, &val); + * sum += *(int *)val; + * } + * return sum; + * } + * @endcode + */ +APR_DECLARE(apr_hash_index_t *) apr_hash_first(apr_pool_t *p, apr_hash_t *ht); + +/** + * Continue iterating over the entries in a hash table. + * @param hi The iteration state + * @return a pointer to the updated iteration state. NULL if there are no more + * entries. + */ +APR_DECLARE(apr_hash_index_t *) apr_hash_next(apr_hash_index_t *hi); + +/** + * Get the current entry's details from the iteration state. + * @param hi The iteration state + * @param key Return pointer for the pointer to the key. + * @param klen Return pointer for the key length. + * @param val Return pointer for the associated value. + * @remark The return pointers should point to a variable that will be set to the + * corresponding data, or they may be NULL if the data isn't interesting. + */ +APR_DECLARE(void) apr_hash_this(apr_hash_index_t *hi, const void **key, + apr_ssize_t *klen, void **val); + +/** + * Get the current entry's key from the iteration state. + * @param hi The iteration state + * @return The pointer to the key + */ +APR_DECLARE(const void*) apr_hash_this_key(apr_hash_index_t *hi); + +/** + * Get the current entry's key length from the iteration state. + * @param hi The iteration state + * @return The key length + */ +APR_DECLARE(apr_ssize_t) apr_hash_this_key_len(apr_hash_index_t *hi); + +/** + * Get the current entry's value from the iteration state. + * @param hi The iteration state + * @return The pointer to the value + */ +APR_DECLARE(void*) apr_hash_this_val(apr_hash_index_t *hi); + +/** + * Get the number of key/value pairs in the hash table. + * @param ht The hash table + * @return The number of key/value pairs in the hash table. + */ +APR_DECLARE(unsigned int) apr_hash_count(apr_hash_t *ht); + +/** + * Clear any key/value pairs in the hash table. + * @param ht The hash table + */ +APR_DECLARE(void) apr_hash_clear(apr_hash_t *ht); + +/** + * Merge two hash tables into one new hash table. The values of the overlay + * hash override the values of the base if both have the same key. Both + * hash tables must use the same hash function. + * @param p The pool to use for the new hash table + * @param overlay The table to add to the initial table + * @param base The table that represents the initial values of the new table + * @return A new hash table containing all of the data from the two passed in + */ +APR_DECLARE(apr_hash_t *) apr_hash_overlay(apr_pool_t *p, + const apr_hash_t *overlay, + const apr_hash_t *base); + +/** + * Merge two hash tables into one new hash table. If the same key + * is present in both tables, call the supplied merge function to + * produce a merged value for the key in the new table. Both + * hash tables must use the same hash function. + * @param p The pool to use for the new hash table + * @param h1 The first of the tables to merge + * @param h2 The second of the tables to merge + * @param merger A callback function to merge values, or NULL to + * make values from h1 override values from h2 (same semantics as + * apr_hash_overlay()) + * @param data Client data to pass to the merger function + * @return A new hash table containing all of the data from the two passed in + */ +APR_DECLARE(apr_hash_t *) apr_hash_merge(apr_pool_t *p, + const apr_hash_t *h1, + const apr_hash_t *h2, + void * (*merger)(apr_pool_t *p, + const void *key, + apr_ssize_t klen, + const void *h1_val, + const void *h2_val, + const void *data), + const void *data); + +/** + * Declaration prototype for the iterator callback function of apr_hash_do(). + * + * @param rec The data passed as the first argument to apr_hash_[v]do() + * @param key The key from this iteration of the hash table + * @param klen The key length from this iteration of the hash table + * @param value The value from this iteration of the hash table + * @remark Iteration continues while this callback function returns non-zero. + * To export the callback function for apr_hash_do() it must be declared + * in the _NONSTD convention. + */ +typedef int (apr_hash_do_callback_fn_t)(void *rec, const void *key, + apr_ssize_t klen, + const void *value); + +/** + * Iterate over a hash table running the provided function once for every + * element in the hash table. The @param comp function will be invoked for + * every element in the hash table. + * + * @param comp The function to run + * @param rec The data to pass as the first argument to the function + * @param ht The hash table to iterate over + * @return FALSE if one of the comp() iterations returned zero; TRUE if all + * iterations returned non-zero + * @see apr_hash_do_callback_fn_t + */ +APR_DECLARE(int) apr_hash_do(apr_hash_do_callback_fn_t *comp, + void *rec, const apr_hash_t *ht); + +/** + * Get a pointer to the pool which the hash table was created in + */ +APR_POOL_DECLARE_ACCESSOR(hash); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_HASH_H */ diff --git a/c/dependencies/linux/apr/include/apr_hooks.h b/c/dependencies/linux/apr/include/apr_hooks.h new file mode 100644 index 00000000..eee16e3c --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_hooks.h @@ -0,0 +1,358 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_HOOKS_H +#define APR_HOOKS_H + +#include "apu.h" +/* For apr_array_header_t */ +#include "apr_tables.h" + +/** + * @file apr_hooks.h + * @brief Apache hook functions + */ + +#ifdef __cplusplus +extern "C" { +#endif +/** + * @defgroup APR_Util_Hook Hook Functions + * @ingroup APR_Util + * @{ + */ + +/** + * @defgroup apr_hook_probes Hook probe capability + * APR hooks provide a trace probe capability for capturing + * the flow of control and return values with hooks. + * + * In order to use this facility, the application must define + * the symbol APR_HOOK_PROBES_ENABLED and the four APR_HOOK_PROBE_ + * macros described below before including apr_hooks.h in files + * that use the APR_IMPLEMENT_EXTERNAL_HOOK_* macros. + * + * This probe facility is not provided for APR optional hooks. + * @{ + */ + +#ifdef APR_HOOK_PROBES_ENABLED +#define APR_HOOK_INT_DCL_UD void *ud = NULL +#else +/** internal implementation detail to avoid the ud declaration when + * hook probes are not used + */ +#define APR_HOOK_INT_DCL_UD +/** + * User-defined hook probe macro that is invoked when the hook + * is run, before calling any hook functions. + * @param ud A void * user data field that should be filled in by + * this macro, and will be provided to the other hook probe macros. + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param args The argument list to the hook functions, with enclosing + * parens. + */ +#define APR_HOOK_PROBE_ENTRY(ud,ns,name,args) +/** + * User-defined hook probe macro that is invoked after the hook + * has run. + * @param ud A void * user data field that was filled in by the user- + * provided APR_HOOK_PROBE_ENTRY(). + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param rv The return value of the hook, or 0 if the hook is void. + * @param args The argument list to the hook functions, with enclosing + * parens. + */ +#define APR_HOOK_PROBE_RETURN(ud,ns,name,rv,args) +/** + * User-defined hook probe macro that is invoked before calling a + * hook function. + * @param ud A void * user data field that was filled in by the user- + * provided APR_HOOK_PROBE_ENTRY(). + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param src The value of apr_hook_debug_current at the time the function + * was hooked (usually the source file implementing the hook function). + * @param args The argument list to the hook functions, with enclosing + * parens. + */ +#define APR_HOOK_PROBE_INVOKE(ud,ns,name,src,args) +/** + * User-defined hook probe macro that is invoked after calling a + * hook function. + * @param ud A void * user data field that was filled in by the user- + * provided APR_HOOK_PROBE_ENTRY(). + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param src The value of apr_hook_debug_current at the time the function + * was hooked (usually the source file implementing the hook function). + * @param rv The return value of the hook function, or 0 if the hook is void. + * @param args The argument list to the hook functions, with enclosing + * parens. + */ +#define APR_HOOK_PROBE_COMPLETE(ud,ns,name,src,rv,args) +#endif + +/** @} */ + +/** macro to return the prototype of the hook function */ +#define APR_IMPLEMENT_HOOK_GET_PROTO(ns,link,name) \ +link##_DECLARE(apr_array_header_t *) ns##_hook_get_##name(void) + +/** macro to declare the hook correctly */ +#define APR_DECLARE_EXTERNAL_HOOK(ns,link,ret,name,args) \ +typedef ret ns##_HOOK_##name##_t args; \ +link##_DECLARE(void) ns##_hook_##name(ns##_HOOK_##name##_t *pf, \ + const char * const *aszPre, \ + const char * const *aszSucc, int nOrder); \ +link##_DECLARE(ret) ns##_run_##name args; \ +APR_IMPLEMENT_HOOK_GET_PROTO(ns,link,name); \ +typedef struct ns##_LINK_##name##_t \ + { \ + ns##_HOOK_##name##_t *pFunc; \ + const char *szName; \ + const char * const *aszPredecessors; \ + const char * const *aszSuccessors; \ + int nOrder; \ + } ns##_LINK_##name##_t; + +/** macro to declare the hook structure */ +#define APR_HOOK_STRUCT(members) \ +static struct { members } _hooks; + +/** macro to link the hook structure */ +#define APR_HOOK_LINK(name) \ + apr_array_header_t *link_##name; + +/** macro to implement the hook */ +#define APR_IMPLEMENT_EXTERNAL_HOOK_BASE(ns,link,name) \ +link##_DECLARE(void) ns##_hook_##name(ns##_HOOK_##name##_t *pf,const char * const *aszPre, \ + const char * const *aszSucc,int nOrder) \ + { \ + ns##_LINK_##name##_t *pHook; \ + if(!_hooks.link_##name) \ + { \ + _hooks.link_##name=apr_array_make(apr_hook_global_pool,1,sizeof(ns##_LINK_##name##_t)); \ + apr_hook_sort_register(#name,&_hooks.link_##name); \ + } \ + pHook=apr_array_push(_hooks.link_##name); \ + pHook->pFunc=pf; \ + pHook->aszPredecessors=aszPre; \ + pHook->aszSuccessors=aszSucc; \ + pHook->nOrder=nOrder; \ + pHook->szName=apr_hook_debug_current; \ + if(apr_hook_debug_enabled) \ + apr_hook_debug_show(#name,aszPre,aszSucc); \ + } \ + APR_IMPLEMENT_HOOK_GET_PROTO(ns,link,name) \ + { \ + return _hooks.link_##name; \ + } + +/** + * Implement a hook that has no return code, and therefore runs all of the + * registered functions + * @param ns The namespace prefix of the hook functions + * @param link The linkage declaration prefix of the hook + * @param name The name of the hook + * @param args_decl The declaration of the arguments for the hook + * @param args_use The names for the arguments for the hook + * @note The link prefix FOO corresponds to FOO_DECLARE() macros, which + * provide export linkage from the module that IMPLEMENTs the hook, and + * import linkage from external modules that link to the hook's module. + */ +#define APR_IMPLEMENT_EXTERNAL_HOOK_VOID(ns,link,name,args_decl,args_use) \ +APR_IMPLEMENT_EXTERNAL_HOOK_BASE(ns,link,name) \ +link##_DECLARE(void) ns##_run_##name args_decl \ + { \ + ns##_LINK_##name##_t *pHook; \ + int n; \ + APR_HOOK_INT_DCL_UD; \ +\ + APR_HOOK_PROBE_ENTRY(ud, ns, name, args_use); \ +\ + if(_hooks.link_##name) \ + { \ + pHook=(ns##_LINK_##name##_t *)_hooks.link_##name->elts; \ + for(n=0 ; n < _hooks.link_##name->nelts ; ++n) \ + { \ + APR_HOOK_PROBE_INVOKE(ud, ns, name, (char *)pHook[n].szName, args_use); \ + pHook[n].pFunc args_use; \ + APR_HOOK_PROBE_COMPLETE(ud, ns, name, (char *)pHook[n].szName, 0, args_use); \ + } \ + } \ +\ + APR_HOOK_PROBE_RETURN(ud, ns, name, 0, args_use); \ +\ + } + +/* FIXME: note that this returns ok when nothing is run. I suspect it should + really return decline, but that breaks Apache currently - Ben +*/ +/** + * Implement a hook that runs until one of the functions returns something + * other than OK or DECLINE + * @param ns The namespace prefix of the hook functions + * @param link The linkage declaration prefix of the hook + * @param ret Type to return + * @param name The name of the hook + * @param args_decl The declaration of the arguments for the hook + * @param args_use The names for the arguments for the hook + * @param ok Success value + * @param decline Decline value + * @note The link prefix FOO corresponds to FOO_DECLARE() macros, which + * provide export linkage from the module that IMPLEMENTs the hook, and + * import linkage from external modules that link to the hook's module. + */ +#define APR_IMPLEMENT_EXTERNAL_HOOK_RUN_ALL(ns,link,ret,name,args_decl,args_use,ok,decline) \ +APR_IMPLEMENT_EXTERNAL_HOOK_BASE(ns,link,name) \ +link##_DECLARE(ret) ns##_run_##name args_decl \ + { \ + ns##_LINK_##name##_t *pHook; \ + int n; \ + ret rv = ok; \ + APR_HOOK_INT_DCL_UD; \ +\ + APR_HOOK_PROBE_ENTRY(ud, ns, name, args_use); \ +\ + if(_hooks.link_##name) \ + { \ + pHook=(ns##_LINK_##name##_t *)_hooks.link_##name->elts; \ + for(n=0 ; n < _hooks.link_##name->nelts ; ++n) \ + { \ + APR_HOOK_PROBE_INVOKE(ud, ns, name, (char *)pHook[n].szName, args_use); \ + rv=pHook[n].pFunc args_use; \ + APR_HOOK_PROBE_COMPLETE(ud, ns, name, (char *)pHook[n].szName, rv, args_use); \ + if(rv != ok && rv != decline) \ + break; \ + rv = ok; \ + } \ + } \ +\ + APR_HOOK_PROBE_RETURN(ud, ns, name, rv, args_use); \ +\ + return rv; \ + } + + +/** + * Implement a hook that runs until the first function returns something + * other than the value of decline + * @param ns The namespace prefix of the hook functions + * @param link The linkage declaration prefix of the hook + * @param name The name of the hook + * @param ret Type to return + * @param args_decl The declaration of the arguments for the hook + * @param args_use The names for the arguments for the hook + * @param decline Decline value + * @note The link prefix FOO corresponds to FOO_DECLARE() macros, which + * provide export linkage from the module that IMPLEMENTs the hook, and + * import linkage from external modules that link to the hook's module. + */ +#define APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(ns,link,ret,name,args_decl,args_use,decline) \ +APR_IMPLEMENT_EXTERNAL_HOOK_BASE(ns,link,name) \ +link##_DECLARE(ret) ns##_run_##name args_decl \ + { \ + ns##_LINK_##name##_t *pHook; \ + int n; \ + ret rv = decline; \ + APR_HOOK_INT_DCL_UD; \ +\ + APR_HOOK_PROBE_ENTRY(ud, ns, name, args_use); \ +\ + if(_hooks.link_##name) \ + { \ + pHook=(ns##_LINK_##name##_t *)_hooks.link_##name->elts; \ + for(n=0 ; n < _hooks.link_##name->nelts ; ++n) \ + { \ + APR_HOOK_PROBE_INVOKE(ud, ns, name, (char *)pHook[n].szName, args_use); \ + rv=pHook[n].pFunc args_use; \ + APR_HOOK_PROBE_COMPLETE(ud, ns, name, (char *)pHook[n].szName, rv, args_use); \ +\ + if(rv != decline) \ + break; \ + } \ + } \ +\ + APR_HOOK_PROBE_RETURN(ud, ns, name, rv, args_use); \ +\ + return rv; \ + } + + /* Hook orderings */ +/** run this hook first, before ANYTHING */ +#define APR_HOOK_REALLY_FIRST (-10) +/** run this hook first */ +#define APR_HOOK_FIRST 0 +/** run this hook somewhere */ +#define APR_HOOK_MIDDLE 10 +/** run this hook after every other hook which is defined*/ +#define APR_HOOK_LAST 20 +/** run this hook last, after EVERYTHING */ +#define APR_HOOK_REALLY_LAST 30 + +/** + * The global pool used to allocate any memory needed by the hooks. + */ +APU_DECLARE_DATA extern apr_pool_t *apr_hook_global_pool; + +/** + * A global variable to determine if debugging information about the + * hooks functions should be printed. + */ +APU_DECLARE_DATA extern int apr_hook_debug_enabled; + +/** + * The name of the module that is currently registering a function. + */ +APU_DECLARE_DATA extern const char *apr_hook_debug_current; + +/** + * Register a hook function to be sorted. + * @param szHookName The name of the Hook the function is registered for + * @param aHooks The array which stores all of the functions for this hook + */ +APU_DECLARE(void) apr_hook_sort_register(const char *szHookName, + apr_array_header_t **aHooks); +/** + * Sort all of the registered functions for a given hook. + */ +APU_DECLARE(void) apr_hook_sort_all(void); + +/** + * Print all of the information about the current hook. This is used for + * debugging purposes. + * @param szName The name of the hook + * @param aszPre All of the functions in the predecessor array + * @param aszSucc All of the functions in the successor array + */ +APU_DECLARE(void) apr_hook_debug_show(const char *szName, + const char * const *aszPre, + const char * const *aszSucc); + +/** + * Remove all currently registered functions. + */ +APU_DECLARE(void) apr_hook_deregister_all(void); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_HOOKS_H */ diff --git a/c/dependencies/linux/apr/include/apr_inherit.h b/c/dependencies/linux/apr/include/apr_inherit.h new file mode 100644 index 00000000..b9fe56fe --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_inherit.h @@ -0,0 +1,51 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_INHERIT_H +#define APR_INHERIT_H + +/** + * @file apr_inherit.h + * @brief APR File Handle Inheritance Helpers + * @remark This internal header includes internal declaration helpers + * for other headers to declare apr_foo_inherit_[un]set functions. + */ + +/** + * Prototype for type-specific declarations of apr_foo_inherit_set + * functions. + * @remark Doxygen unwraps this macro (via doxygen.conf) to provide + * actual help for each specific occurrence of apr_foo_inherit_set. + * @remark the linkage is specified for APR. It would be possible to expand + * the macros to support other linkages. + */ +#define APR_DECLARE_INHERIT_SET(type) \ + APR_DECLARE(apr_status_t) apr_##type##_inherit_set( \ + apr_##type##_t *the##type) + +/** + * Prototype for type-specific declarations of apr_foo_inherit_unset + * functions. + * @remark Doxygen unwraps this macro (via doxygen.conf) to provide + * actual help for each specific occurrence of apr_foo_inherit_unset. + * @remark the linkage is specified for APR. It would be possible to expand + * the macros to support other linkages. + */ +#define APR_DECLARE_INHERIT_UNSET(type) \ + APR_DECLARE(apr_status_t) apr_##type##_inherit_unset( \ + apr_##type##_t *the##type) + +#endif /* ! APR_INHERIT_H */ diff --git a/c/dependencies/linux/apr/include/apr_ldap.h b/c/dependencies/linux/apr/include/apr_ldap.h new file mode 100644 index 00000000..bd328537 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_ldap.h @@ -0,0 +1,197 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_ldap.h is generated from apr_ldap.h.in by configure -- do not edit apr_ldap.h + */ +/** + * @file apr_ldap.h + * @brief APR-UTIL LDAP + */ +#ifndef APU_LDAP_H +#define APU_LDAP_H + +/** + * @defgroup APR_Util_LDAP LDAP + * @ingroup APR_Util + * @{ + */ + +/* this will be defined if LDAP support was compiled into apr-util */ +#define APR_HAS_LDAP 0 + +/* identify the LDAP toolkit used */ +#define APR_HAS_NETSCAPE_LDAPSDK 0 +#define APR_HAS_SOLARIS_LDAPSDK 0 +#define APR_HAS_NOVELL_LDAPSDK 0 +#define APR_HAS_MOZILLA_LDAPSDK 0 +#define APR_HAS_OPENLDAP_LDAPSDK 0 +#define APR_HAS_MICROSOFT_LDAPSDK 0 +#define APR_HAS_TIVOLI_LDAPSDK 0 +#define APR_HAS_ZOS_LDAPSDK 0 +#define APR_HAS_OTHER_LDAPSDK 0 + + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/* + * The following #defines are DEPRECATED and should not be used for + * anything. They remain to maintain binary compatibility. + * The original code defined the OPENLDAP SDK as present regardless + * of what really was there, which was way bogus. In addition, the + * apr_ldap_url_parse*() functions have been rewritten specifically for + * APR, so the APR_HAS_LDAP_URL_PARSE macro is forced to zero. + */ +#if APR_HAS_TIVOLI_LDAPSDK +#define APR_HAS_LDAP_SSL 0 +#else +#define APR_HAS_LDAP_SSL 1 +#endif +#define APR_HAS_LDAP_URL_PARSE 0 + +#if APR_HAS_OPENLDAP_LDAPSDK && !defined(LDAP_DEPRECATED) +/* Ensure that the "deprecated" interfaces are still exposed + * with OpenLDAP >= 2.3; these were exposed by default in earlier + * releases. */ +#define LDAP_DEPRECATED 1 +#endif + +/* + * Include the standard LDAP header files. + */ + + + + + + +/* + * Detected standard functions + */ +#define APR_HAS_LDAPSSL_CLIENT_INIT 0 +#define APR_HAS_LDAPSSL_CLIENT_DEINIT 0 +#define APR_HAS_LDAPSSL_ADD_TRUSTED_CERT 0 +#define APR_HAS_LDAP_START_TLS_S 0 +#define APR_HAS_LDAP_SSLINIT 0 +#define APR_HAS_LDAPSSL_INIT 0 +#define APR_HAS_LDAPSSL_INSTALL_ROUTINES 0 + +/* + * Make sure the secure LDAP port is defined + */ +#ifndef LDAPS_PORT +#define LDAPS_PORT 636 /* ldaps:/// default LDAP over TLS port */ +#endif + +/* + * For ldap function calls that input a size limit on the number of returned elements + * Some SDKs do not have the define for LDAP_DEFAULT_LIMIT (-1) or LDAP_NO_LIMIT (0) + * LDAP_DEFAULT_LIMIT is preferred as it allows inheritance from whatever the SDK + * or process is configured for. + */ +#ifdef LDAP_DEFAULT_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_DEFAULT_LIMIT +#else +#ifdef LDAP_NO_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_NO_LIMIT +#endif +#endif + +#ifndef APR_LDAP_SIZELIMIT +#define APR_LDAP_SIZELIMIT 0 /* equivalent to LDAP_NO_LIMIT, and what goes on the wire */ +#endif + +/* + * z/OS is missing some defines + */ +#ifndef LDAP_VERSION_MAX +#define LDAP_VERSION_MAX LDAP_VERSION +#endif +#if APR_HAS_ZOS_LDAPSDK +#define LDAP_VENDOR_NAME "IBM z/OS" +#endif + +/* Note: Macros defining const casting has been removed in APR v1.0, + * pending real support for LDAP v2.0 toolkits. + * + * In the mean time, please use an LDAP v3.0 toolkit. + */ +#if LDAP_VERSION_MAX <= 2 +#error Support for LDAP v2.0 toolkits has been removed from apr-util. Please use an LDAP v3.0 toolkit. +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * This structure allows the C LDAP API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apr_ldap_err_t { + const char *reason; + const char *msg; + int rc; +} apr_ldap_err_t; + +#ifdef __cplusplus +} +#endif + +/* The MS SDK returns LDAP_UNAVAILABLE when the backend has closed the connection + * between LDAP calls. Protect with APR_HAS_MICROSOFT_LDAPSDK in case someone + * manually chooses another SDK on Windows + */ +#if APR_HAS_MICROSOFT_LDAPSDK +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN \ + || (s) == LDAP_UNAVAILABLE) +#else +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN) +#endif + +/* These symbols are not actually exported in a DSO build, but mapped into + * a private exported function array for apr_ldap_stub to bind dynamically. + * Rename them appropriately to protect the global namespace. + */ +#ifdef APU_DSO_LDAP_BUILD + +#define apr_ldap_info apr__ldap_info +#define apr_ldap_init apr__ldap_init +#define apr_ldap_ssl_init apr__ldap_ssl_init +#define apr_ldap_ssl_deinit apr__ldap_ssl_deinit +#define apr_ldap_get_option apr__ldap_get_option +#define apr_ldap_set_option apr__ldap_set_option +#define apr_ldap_rebind_init apr__ldap_rebind_init +#define apr_ldap_rebind_add apr__ldap_rebind_add +#define apr_ldap_rebind_remove apr__ldap_rebind_remove + +#define APU_DECLARE_LDAP(type) type +#else +#define APU_DECLARE_LDAP(type) APU_DECLARE(type) +#endif + +#include "apr_ldap_url.h" +#include "apr_ldap_init.h" +#include "apr_ldap_option.h" +#include "apr_ldap_rebind.h" + +#endif /* APR_HAS_LDAP */ +/** @} */ +#endif /* APU_LDAP_H */ diff --git a/c/dependencies/linux/apr/include/apr_ldap_init.h b/c/dependencies/linux/apr/include/apr_ldap_init.h new file mode 100644 index 00000000..aeb6d9bb --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_ldap_init.h @@ -0,0 +1,165 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_ldap_init.h + * @brief APR-UTIL LDAP ldap_init() functions + */ +#ifndef APR_LDAP_INIT_H +#define APR_LDAP_INIT_H + +/** + * @addtogroup APR_Util_LDAP + * @{ + */ + +#include "apr_ldap.h" + +#if APR_HAS_LDAP + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + + +/** + * Macro to detect security related return values. + */ +#if defined(LDAP_INSUFFICIENT_ACCESS) +#define APU_LDAP_INSUFFICIENT_ACCESS LDAP_INSUFFICIENT_ACCESS +#elif defined(LDAP_INSUFFICIENT_RIGHTS) +#define APU_LDAP_INSUFFICIENT_ACCESS LDAP_INSUFFICIENT_RIGHTS +#elif defined(APR_HAS_MICROSOFT_LDAPSDK) +/* The macros above fail to contemplate that LDAP_RETCODE values + * may be represented by an enum. autoconf tests would be much + * more robust. + */ +#define APU_LDAP_INSUFFICIENT_ACCESS LDAP_INSUFFICIENT_RIGHTS +#else +#error The security return codes must be added to support this LDAP toolkit. +#endif + +#if defined(LDAP_SECURITY_ERROR) +#define APU_LDAP_SECURITY_ERROR LDAP_SECURITY_ERROR +#else +#define APU_LDAP_SECURITY_ERROR(n) \ + (LDAP_INAPPROPRIATE_AUTH == n) ? 1 \ + : (LDAP_INVALID_CREDENTIALS == n) ? 1 \ + : (APU_LDAP_INSUFFICIENT_ACCESS == n) ? 1 \ + : 0 +#endif + + +/** + * APR LDAP SSL Initialise function + * + * This function initialises SSL on the underlying LDAP toolkit + * if this is necessary. + * + * If a CA certificate is provided, this is set, however the setting + * of certificates via this method has been deprecated and will be removed in + * APR v2.0. + * + * The apr_ldap_set_option() function with the APR_LDAP_OPT_TLS_CERT option + * should be used instead to set certificates. + * + * If SSL support is not available on this platform, or a problem + * was encountered while trying to set the certificate, the function + * will return APR_EGENERAL. Further LDAP specific error information + * can be found in result_err. + * @param pool The pool to use + * @param cert_auth_file The name of the certificate to use, can be NULL + * @param cert_file_type The type of certificate specified. See the + * apr_ldap_set_option() APR_LDAP_OPT_TLS_CERT option for details. + * @param result_err The returned result + */ +APU_DECLARE_LDAP(int) apr_ldap_ssl_init(apr_pool_t *pool, + const char *cert_auth_file, + int cert_file_type, + apr_ldap_err_t **result_err); + +/** + * APR LDAP SSL De-Initialise function + * + * This function tears down any SSL certificate setup previously + * set using apr_ldap_ssl_init(). It should be called to clean + * up if a graceful restart of a service is attempted. + * @todo currently we do not check whether apr_ldap_ssl_init() + * has been called first - we probably should. + */ +APU_DECLARE_LDAP(int) apr_ldap_ssl_deinit(void); + +/** + * APR LDAP initialise function + * + * This function is responsible for initialising an LDAP + * connection in a toolkit independant way. It does the + * job of ldap_init() from the C api. + * + * It handles both the SSL and non-SSL case, and attempts + * to hide the complexity setup from the user. This function + * assumes that any certificate setup necessary has already + * been done. + * + * If SSL or STARTTLS needs to be enabled, and the underlying + * toolkit supports it, the following values are accepted for + * secure: + * + * APR_LDAP_NONE: No encryption + * APR_LDAP_SSL: SSL encryption (ldaps://) + * APR_LDAP_STARTTLS: Force STARTTLS on ldap:// + * @remark The Novell toolkit is only able to set the SSL mode via this + * function. To work around this limitation, set the SSL mode here if no + * per connection client certificates are present, otherwise set secure + * APR_LDAP_NONE here, then set the per connection client certificates, + * followed by setting the SSL mode via apr_ldap_set_option(). As Novell + * does not support per connection client certificates, this problem is + * worked around while still being compatible with other LDAP toolkits. + * @param pool The pool to use + * @param ldap The LDAP handle + * @param hostname The name of the host to connect to. This can be either a + * DNS name, or an IP address. + * @param portno The port to connect to + * @param secure The security mode to set + * @param result_err The returned result + */ +APU_DECLARE_LDAP(int) apr_ldap_init(apr_pool_t *pool, + LDAP **ldap, + const char *hostname, + int portno, + int secure, + apr_ldap_err_t **result_err); + +/** + * APR LDAP info function + * + * This function returns a string describing the LDAP toolkit + * currently in use. The string is placed inside result_err->reason. + * @param pool The pool to use + * @param result_err The returned result + */ +APU_DECLARE_LDAP(int) apr_ldap_info(apr_pool_t *pool, + apr_ldap_err_t **result_err); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_HAS_LDAP */ + +/** @} */ + +#endif /* APR_LDAP_URL_H */ diff --git a/c/dependencies/linux/apr/include/apr_ldap_option.h b/c/dependencies/linux/apr/include/apr_ldap_option.h new file mode 100644 index 00000000..0ff8a862 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_ldap_option.h @@ -0,0 +1,254 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_ldap_option.h + * @brief APR-UTIL LDAP ldap_*_option() functions + */ +#ifndef APR_LDAP_OPTION_H +#define APR_LDAP_OPTION_H + +/** + * @addtogroup APR_Util_LDAP + * @{ + */ + +#include "apr_ldap.h" + +#if APR_HAS_LDAP + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* + * The following defines handle the different TLS certificate + * options available. If these options are missing, APR will try and + * emulate support for this using the deprecated ldap_start_tls_s() + * function. + */ +/** + * Set SSL mode to one of APR_LDAP_NONE, APR_LDAP_SSL, APR_LDAP_STARTTLS + * or APR_LDAP_STOPTLS. + */ +#define APR_LDAP_OPT_TLS 0x6fff +/** + * Set zero or more CA certificates, client certificates or private + * keys globally, or per connection (where supported). + */ +#define APR_LDAP_OPT_TLS_CERT 0x6ffe +/** + * Set the LDAP library to no verify the server certificate. This means + * all servers are considered trusted. + */ +#define APR_LDAP_OPT_VERIFY_CERT 0x6ffd +/** + * Set the LDAP library to indicate if referrals should be chased during + * LDAP searches. + */ +#define APR_LDAP_OPT_REFERRALS 0x6ffc +/** + * Set the LDAP library to indicate a maximum number of referral hops to + * chase before giving up on the search. + */ +#define APR_LDAP_OPT_REFHOPLIMIT 0x6ffb + +/** + * Structures for the apr_set_option() cases + */ + +/** + * APR_LDAP_OPT_TLS_CERT + * + * This structure includes possible options to set certificates on + * system initialisation. Different SDKs have different certificate + * requirements, and to achieve this multiple certificates must be + * specified at once passed as an (apr_array_header_t *). + * + * Netscape: + * Needs the CA cert database (cert7.db), the client cert database (key3.db) + * and the security module file (secmod.db) set at the system initialisation + * time. Three types are supported: APR_LDAP_CERT7_DB, APR_LDAP_KEY3_DB and + * APR_LDAP_SECMOD. + * + * To specify a client cert connection, a certificate nickname needs to be + * provided with a type of APR_LDAP_CERT. + * int ldapssl_enable_clientauth( LDAP *ld, char *keynickname, + * char *keypasswd, char *certnickname ); + * keynickname is currently not used, and should be set to "" + * + * Novell: + * Needs CA certificates and client certificates set at system initialisation + * time. Three types are supported: APR_LDAP_CA*, APR_LDAP_CERT* and + * APR_LDAP_KEY*. + * + * Certificates cannot be specified per connection. + * + * The functions used are: + * ldapssl_add_trusted_cert(serverTrustedRoot, serverTrustedRootEncoding); + * Clients certs and keys are set at system initialisation time with + * int ldapssl_set_client_cert ( + * void *cert, + * int type + * void *password); + * type can be LDAPSSL_CERT_FILETYPE_B64 or LDAPSSL_CERT_FILETYPE_DER + * ldapssl_set_client_private_key(clientPrivateKey, + * clientPrivateKeyEncoding, + * clientPrivateKeyPassword); + * + * OpenSSL: + * Needs one or more CA certificates to be set at system initialisation time + * with a type of APR_LDAP_CA*. + * + * May have one or more client certificates set per connection with a type of + * APR_LDAP_CERT*, and keys with APR_LDAP_KEY*. + */ +/** CA certificate type unknown */ +#define APR_LDAP_CA_TYPE_UNKNOWN 0 +/** binary DER encoded CA certificate */ +#define APR_LDAP_CA_TYPE_DER 1 +/** PEM encoded CA certificate */ +#define APR_LDAP_CA_TYPE_BASE64 2 +/** Netscape/Mozilla cert7.db CA certificate database */ +#define APR_LDAP_CA_TYPE_CERT7_DB 3 +/** Netscape/Mozilla secmod file */ +#define APR_LDAP_CA_TYPE_SECMOD 4 +/** Client certificate type unknown */ +#define APR_LDAP_CERT_TYPE_UNKNOWN 5 +/** binary DER encoded client certificate */ +#define APR_LDAP_CERT_TYPE_DER 6 +/** PEM encoded client certificate */ +#define APR_LDAP_CERT_TYPE_BASE64 7 +/** Netscape/Mozilla key3.db client certificate database */ +#define APR_LDAP_CERT_TYPE_KEY3_DB 8 +/** Netscape/Mozilla client certificate nickname */ +#define APR_LDAP_CERT_TYPE_NICKNAME 9 +/** Private key type unknown */ +#define APR_LDAP_KEY_TYPE_UNKNOWN 10 +/** binary DER encoded private key */ +#define APR_LDAP_KEY_TYPE_DER 11 +/** PEM encoded private key */ +#define APR_LDAP_KEY_TYPE_BASE64 12 +/** PKCS#12 encoded client certificate */ +#define APR_LDAP_CERT_TYPE_PFX 13 +/** PKCS#12 encoded private key */ +#define APR_LDAP_KEY_TYPE_PFX 14 +/** Openldap directory full of base64-encoded cert + * authorities with hashes in corresponding .0 directory + */ +#define APR_LDAP_CA_TYPE_CACERTDIR_BASE64 15 + + +/** + * Certificate structure. + * + * This structure is used to store certificate details. An array of + * these structures is passed to apr_ldap_set_option() to set CA + * and client certificates. + * @param type Type of certificate APR_LDAP_*_TYPE_* + * @param path Path, file or nickname of the certificate + * @param password Optional password, can be NULL + */ +typedef struct apr_ldap_opt_tls_cert_t apr_ldap_opt_tls_cert_t; +struct apr_ldap_opt_tls_cert_t { + int type; + const char *path; + const char *password; +}; + +/** + * APR_LDAP_OPT_TLS + * + * This sets the SSL level on the LDAP handle. + * + * Netscape/Mozilla: + * Supports SSL, but not STARTTLS + * SSL is enabled by calling ldapssl_install_routines(). + * + * Novell: + * Supports SSL and STARTTLS. + * SSL is enabled by calling ldapssl_install_routines(). Note that calling + * other ldap functions before ldapssl_install_routines() may cause this + * function to fail. + * STARTTLS is enabled by calling ldapssl_start_tls_s() after calling + * ldapssl_install_routines() (check this). + * + * OpenLDAP: + * Supports SSL and supports STARTTLS, but none of this is documented: + * http://www.openldap.org/lists/openldap-software/200409/msg00618.html + * Documentation for both SSL support and STARTTLS has been deleted from + * the OpenLDAP documentation and website. + */ + +/** No encryption */ +#define APR_LDAP_NONE 0 +/** SSL encryption (ldaps://) */ +#define APR_LDAP_SSL 1 +/** TLS encryption (STARTTLS) */ +#define APR_LDAP_STARTTLS 2 +/** end TLS encryption (STOPTLS) */ +#define APR_LDAP_STOPTLS 3 + +/** + * APR LDAP get option function + * + * This function gets option values from a given LDAP session if + * one was specified. It maps to the native ldap_get_option() function. + * @param pool The pool to use + * @param ldap The LDAP handle + * @param option The LDAP_OPT_* option to return + * @param outvalue The value returned (if any) + * @param result_err The apr_ldap_err_t structure contained detailed results + * of the operation. + */ +APU_DECLARE_LDAP(int) apr_ldap_get_option(apr_pool_t *pool, + LDAP *ldap, + int option, + void *outvalue, + apr_ldap_err_t **result_err); + +/** + * APR LDAP set option function + * + * This function sets option values to a given LDAP session if + * one was specified. It maps to the native ldap_set_option() function. + * + * Where an option is not supported by an LDAP toolkit, this function + * will try and apply legacy functions to achieve the same effect, + * depending on the platform. + * @param pool The pool to use + * @param ldap The LDAP handle + * @param option The LDAP_OPT_* option to set + * @param invalue The value to set + * @param result_err The apr_ldap_err_t structure contained detailed results + * of the operation. + */ +APU_DECLARE_LDAP(int) apr_ldap_set_option(apr_pool_t *pool, + LDAP *ldap, + int option, + const void *invalue, + apr_ldap_err_t **result_err); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_HAS_LDAP */ + +/** @} */ + +#endif /* APR_LDAP_OPTION_H */ + diff --git a/c/dependencies/linux/apr/include/apr_ldap_rebind.h b/c/dependencies/linux/apr/include/apr_ldap_rebind.h new file mode 100644 index 00000000..342a17c3 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_ldap_rebind.h @@ -0,0 +1,98 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The APR LDAP rebind functions provide an implementation of + * a rebind procedure that can be used to allow clients to chase referrals, + * using the same credentials used to log in originally. + * + * Use of this implementation is optional. + * + * @file apr_ldap_rebind.h + * @brief Apache LDAP library + */ + +#ifndef APU_LDAP_REBIND_H +#define APU_LDAP_REBIND_H + +/** + * @addtogroup APR_Util_LDAP + * @{ + **/ + +#if defined(DOXYGEN) +#include "apr_ldap.h" +#endif + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/** + * APR LDAP initialize rebind lock + * + * This function creates the lock for controlling access to the xref list.. + * @param pool Pool to use when creating the xref_lock. + */ +APU_DECLARE_LDAP(apr_status_t) apr_ldap_rebind_init(apr_pool_t *pool); + + +/** + * APR LDAP rebind_add function + * + * This function creates a cross reference entry for the specified ldap + * connection. The rebind callback function will look up this ldap + * connection so it can retrieve the bindDN and bindPW for use in any + * binds while referrals are being chased. + * + * This function will add the callback to the LDAP handle passed in. + * + * A cleanup is registered within the pool provided to remove this + * entry when the pool is removed. Alternatively apr_ldap_rebind_remove() + * can be called to explicitly remove the entry at will. + * + * @param pool The pool to use + * @param ld The LDAP connectionhandle + * @param bindDN The bind DN to be used for any binds while chasing + * referrals on this ldap connection. + * @param bindPW The bind Password to be used for any binds while + * chasing referrals on this ldap connection. + */ +APU_DECLARE_LDAP(apr_status_t) apr_ldap_rebind_add(apr_pool_t *pool, + LDAP *ld, + const char *bindDN, + const char *bindPW); + +/** + * APR LDAP rebind_remove function + * + * This function removes the rebind cross reference entry for the + * specified ldap connection. + * + * If not explicitly removed, this function will be called automatically + * when the pool is cleaned up. + * + * @param ld The LDAP connectionhandle + */ +APU_DECLARE_LDAP(apr_status_t) apr_ldap_rebind_remove(LDAP *ld); + +#endif /* APR_HAS_LDAP */ + +/** @} */ + +#endif /* APU_LDAP_REBIND_H */ + diff --git a/c/dependencies/linux/apr/include/apr_ldap_url.h b/c/dependencies/linux/apr/include/apr_ldap_url.h new file mode 100644 index 00000000..a71f5b3c --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_ldap_url.h @@ -0,0 +1,120 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_ldap_url.h + * @brief APR-UTIL LDAP ldap_init() functions + */ +#ifndef APR_LDAP_URL_H +#define APR_LDAP_URL_H + +/** + * @addtogroup APR_Util_LDAP + * @{ + */ + +#if defined(DOXYGEN) +#include "apr_ldap.h" +#endif + +#if APR_HAS_LDAP + +#include "apu.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** Structure to access an exploded LDAP URL */ +typedef struct apr_ldap_url_desc_t { + struct apr_ldap_url_desc_t *lud_next; + char *lud_scheme; + char *lud_host; + int lud_port; + char *lud_dn; + char **lud_attrs; + int lud_scope; + char *lud_filter; + char **lud_exts; + int lud_crit_exts; +} apr_ldap_url_desc_t; + +#ifndef APR_LDAP_URL_SUCCESS +#define APR_LDAP_URL_SUCCESS 0x00 /* Success */ +#define APR_LDAP_URL_ERR_MEM 0x01 /* can't allocate memory space */ +#define APR_LDAP_URL_ERR_PARAM 0x02 /* parameter is bad */ +#define APR_LDAP_URL_ERR_BADSCHEME 0x03 /* URL doesn't begin with "ldap[si]://" */ +#define APR_LDAP_URL_ERR_BADENCLOSURE 0x04 /* URL is missing trailing ">" */ +#define APR_LDAP_URL_ERR_BADURL 0x05 /* URL is bad */ +#define APR_LDAP_URL_ERR_BADHOST 0x06 /* host port is bad */ +#define APR_LDAP_URL_ERR_BADATTRS 0x07 /* bad (or missing) attributes */ +#define APR_LDAP_URL_ERR_BADSCOPE 0x08 /* scope string is invalid (or missing) */ +#define APR_LDAP_URL_ERR_BADFILTER 0x09 /* bad or missing filter */ +#define APR_LDAP_URL_ERR_BADEXTS 0x0a /* bad or missing extensions */ +#endif + +/** + * Is this URL an ldap url? ldap:// + * @param url The url to test + */ +APU_DECLARE(int) apr_ldap_is_ldap_url(const char *url); + +/** + * Is this URL an SSL ldap url? ldaps:// + * @param url The url to test + */ +APU_DECLARE(int) apr_ldap_is_ldaps_url(const char *url); + +/** + * Is this URL an ldap socket url? ldapi:// + * @param url The url to test + */ +APU_DECLARE(int) apr_ldap_is_ldapi_url(const char *url); + +/** + * Parse an LDAP URL. + * @param pool The pool to use + * @param url_in The URL to parse + * @param ludpp The structure to return the exploded URL + * @param result_err The result structure of the operation + */ +APU_DECLARE(int) apr_ldap_url_parse_ext(apr_pool_t *pool, + const char *url_in, + apr_ldap_url_desc_t **ludpp, + apr_ldap_err_t **result_err); + +/** + * Parse an LDAP URL. + * @param pool The pool to use + * @param url_in The URL to parse + * @param ludpp The structure to return the exploded URL + * @param result_err The result structure of the operation + */ +APU_DECLARE(int) apr_ldap_url_parse(apr_pool_t *pool, + const char *url_in, + apr_ldap_url_desc_t **ludpp, + apr_ldap_err_t **result_err); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_HAS_LDAP */ + +/** @} */ + +#endif /* APR_LDAP_URL_H */ diff --git a/c/dependencies/linux/apr/include/apr_lib.h b/c/dependencies/linux/apr/include/apr_lib.h new file mode 100644 index 00000000..466e8185 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_lib.h @@ -0,0 +1,241 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_LIB_H +#define APR_LIB_H + +/** + * @file apr_lib.h + * This is collection of oddballs that didn't fit anywhere else, + * and might move to more appropriate headers with the release + * of APR 1.0. + * @brief APR general purpose library routines + */ + +#include "apr.h" +#include "apr_errno.h" + +#if APR_HAVE_CTYPE_H +#include +#endif +#if APR_HAVE_STDARG_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_lib General Purpose Library Routines + * @ingroup APR + * This is collection of oddballs that didn't fit anywhere else, + * and might move to more appropriate headers with the release + * of APR 1.0. + * @{ + */ + +/** A constant representing a 'large' string. */ +#define HUGE_STRING_LEN 8192 + +/* + * Define the structures used by the APR general-purpose library. + */ + +/** @see apr_vformatter_buff_t */ +typedef struct apr_vformatter_buff_t apr_vformatter_buff_t; + +/** + * Structure used by the variable-formatter routines. + */ +struct apr_vformatter_buff_t { + /** The current position */ + char *curpos; + /** The end position of the format string */ + char *endpos; +}; + +/** + * return the final element of the pathname + * @param pathname The path to get the final element of + * @return the final element of the path + * @remark + *
+ * For example:
+ *                 "/foo/bar/gum"    -> "gum"
+ *                 "/foo/bar/gum/"   -> ""
+ *                 "gum"             -> "gum"
+ *                 "bs\\path\\stuff" -> "stuff"
+ * 
+ */ +APR_DECLARE(const char *) apr_filepath_name_get(const char *pathname); + +/** + * apr_killpg + * Small utility macros to make things easier to read. Not usually a + * goal, to be sure.. + */ + +#ifdef WIN32 +#define apr_killpg(x, y) +#else /* WIN32 */ +#ifdef NO_KILLPG +#define apr_killpg(x, y) (kill (-(x), (y))) +#else /* NO_KILLPG */ +#define apr_killpg(x, y) (killpg ((x), (y))) +#endif /* NO_KILLPG */ +#endif /* WIN32 */ + +/** + * apr_vformatter() is a generic printf-style formatting routine + * with some extensions. + * @param flush_func The function to call when the buffer is full + * @param c The buffer to write to + * @param fmt The format string + * @param ap The arguments to use to fill out the format string. + * + * @remark + *
+ * The extensions are:
+ *
+ * - %%pA takes a struct in_addr *, and prints it as a.b.c.d
+ * - %%pI takes an apr_sockaddr_t * and prints it as a.b.c.d:port or
+ * \[ipv6-address\]:port
+ * - %%pT takes an apr_os_thread_t * and prints it in decimal
+ * ('0' is printed if !APR_HAS_THREADS)
+ * - %%pt takes an apr_os_thread_t * and prints it in hexadecimal
+ * ('0' is printed if !APR_HAS_THREADS)
+ * - %%pm takes an apr_status_t * and prints the appropriate error
+ * string (from apr_strerror) corresponding to that error code.
+ * - %%pp takes a void * and outputs it in hex
+ * - %%pB takes a apr_uint32_t * as bytes and outputs it's apr_strfsize
+ * - %%pF same as above, but takes a apr_off_t *
+ * - %%pS same as above, but takes a apr_size_t *
+ *
+ * %%pA, %%pI, %%pT, %%pp are available from APR 1.0.0 onwards (and in 0.9.x).
+ * %%pt is only available from APR 1.2.0 onwards.
+ * %%pm, %%pB, %%pF and %%pS are only available from APR 1.3.0 onwards.
+ *
+ * The %%p hacks are to force gcc's printf warning code to skip
+ * over a pointer argument without complaining.  This does
+ * mean that the ANSI-style %%p (output a void * in hex format) won't
+ * work as expected at all, but that seems to be a fair trade-off
+ * for the increased robustness of having printf-warnings work.
+ *
+ * Additionally, apr_vformatter allows for arbitrary output methods
+ * using the apr_vformatter_buff and flush_func.
+ *
+ * The apr_vformatter_buff has two elements curpos and endpos.
+ * curpos is where apr_vformatter will write the next byte of output.
+ * It proceeds writing output to curpos, and updating curpos, until
+ * either the end of output is reached, or curpos == endpos (i.e. the
+ * buffer is full).
+ *
+ * If the end of output is reached, apr_vformatter returns the
+ * number of bytes written.
+ *
+ * When the buffer is full, the flush_func is called.  The flush_func
+ * can return -1 to indicate that no further output should be attempted,
+ * and apr_vformatter will return immediately with -1.  Otherwise
+ * the flush_func should flush the buffer in whatever manner is
+ * appropriate, re apr_pool_t nitialize curpos and endpos, and return 0.
+ *
+ * Note that flush_func is only invoked as a result of attempting to
+ * write another byte at curpos when curpos >= endpos.  So for
+ * example, it's possible when the output exactly matches the buffer
+ * space available that curpos == endpos will be true when
+ * apr_vformatter returns.
+ *
+ * apr_vformatter does not call out to any other code, it is entirely
+ * self-contained.  This allows the callers to do things which are
+ * otherwise "unsafe".  For example, apr_psprintf uses the "scratch"
+ * space at the unallocated end of a block, and doesn't actually
+ * complete the allocation until apr_vformatter returns.  apr_psprintf
+ * would be completely broken if apr_vformatter were to call anything
+ * that used this same pool.  Similarly http_bprintf() uses the "scratch"
+ * space at the end of its output buffer, and doesn't actually note
+ * that the space is in use until it either has to flush the buffer
+ * or until apr_vformatter returns.
+ * 
+ */ +APR_DECLARE(int) apr_vformatter(int (*flush_func)(apr_vformatter_buff_t *b), + apr_vformatter_buff_t *c, const char *fmt, + va_list ap); + +/** + * Display a prompt and read in the password from stdin. + * @param prompt The prompt to display + * @param pwbuf Buffer to store the password + * @param bufsize The length of the password buffer. + * @remark If the password entered must be truncated to fit in + * the provided buffer, APR_ENAMETOOLONG will be returned. + * Note that the bufsize paramater is passed by reference for no + * reason; its value will never be modified by the apr_password_get() + * function. + */ +APR_DECLARE(apr_status_t) apr_password_get(const char *prompt, char *pwbuf, + apr_size_t *bufsize); + +/** @} */ + +/** + * @defgroup apr_ctype ctype functions + * These macros allow correct support of 8-bit characters on systems which + * support 8-bit characters. Pretty dumb how the cast is required, but + * that's legacy libc for ya. These new macros do not support EOF like + * the standard macros do. Tough. + * @{ + */ +/** @see isalnum */ +#define apr_isalnum(c) (isalnum(((unsigned char)(c)))) +/** @see isalpha */ +#define apr_isalpha(c) (isalpha(((unsigned char)(c)))) +/** @see iscntrl */ +#define apr_iscntrl(c) (iscntrl(((unsigned char)(c)))) +/** @see isdigit */ +#define apr_isdigit(c) (isdigit(((unsigned char)(c)))) +/** @see isgraph */ +#define apr_isgraph(c) (isgraph(((unsigned char)(c)))) +/** @see islower*/ +#define apr_islower(c) (islower(((unsigned char)(c)))) +/** @see isascii */ +#ifdef isascii +#define apr_isascii(c) (isascii(((unsigned char)(c)))) +#else +#define apr_isascii(c) (((c) & ~0x7f)==0) +#endif +/** @see isprint */ +#define apr_isprint(c) (isprint(((unsigned char)(c)))) +/** @see ispunct */ +#define apr_ispunct(c) (ispunct(((unsigned char)(c)))) +/** @see isspace */ +#define apr_isspace(c) (isspace(((unsigned char)(c)))) +/** @see isupper */ +#define apr_isupper(c) (isupper(((unsigned char)(c)))) +/** @see isxdigit */ +#define apr_isxdigit(c) (isxdigit(((unsigned char)(c)))) +/** @see tolower */ +#define apr_tolower(c) (tolower(((unsigned char)(c)))) +/** @see toupper */ +#define apr_toupper(c) (toupper(((unsigned char)(c)))) + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_LIB_H */ diff --git a/c/dependencies/linux/apr/include/apr_md4.h b/c/dependencies/linux/apr/include/apr_md4.h new file mode 100644 index 00000000..43fb33e3 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_md4.h @@ -0,0 +1,135 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* This is derived from material copyright RSA Data Security, Inc. + * Their notice is reproduced below in its entirety. + * + * Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All + * rights reserved. + * + * License to copy and use this software is granted provided that it + * is identified as the "RSA Data Security, Inc. MD4 Message-Digest + * Algorithm" in all material mentioning or referencing this software + * or this function. + * + * License is also granted to make and use derivative works provided + * that such works are identified as "derived from the RSA Data + * Security, Inc. MD4 Message-Digest Algorithm" in all material + * mentioning or referencing the derived work. + * + * RSA Data Security, Inc. makes no representations concerning either + * the merchantability of this software or the suitability of this + * software for any particular purpose. It is provided "as is" + * without express or implied warranty of any kind. + * + * These notices must be retained in any copies of any part of this + * documentation and/or software. + */ + +#ifndef APR_MD4_H +#define APR_MD4_H + +#include "apu.h" +#include "apr_xlate.h" +/** + * @file apr_md4.h + * @brief APR-UTIL MD4 Library + */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_MD4 MD4 Library + * @ingroup APR_Util + * @{ + */ + +/** The digestsize for MD4 */ +#define APR_MD4_DIGESTSIZE 16 + +/** @see apr_md4_ctx_t */ +typedef struct apr_md4_ctx_t apr_md4_ctx_t; + +/** MD4 context. */ +struct apr_md4_ctx_t { + /** state (ABCD) */ + apr_uint32_t state[4]; + /** number of bits, modulo 2^64 (lsb first) */ + apr_uint32_t count[2]; + /** input buffer */ + unsigned char buffer[64]; +#if APR_HAS_XLATE + /** translation handle */ + apr_xlate_t *xlate; +#endif +}; + +/** + * MD4 Initialize. Begins an MD4 operation, writing a new context. + * @param context The MD4 context to initialize. + */ +APU_DECLARE(apr_status_t) apr_md4_init(apr_md4_ctx_t *context); + +#if APR_HAS_XLATE +/** + * MDr4 translation setup. Provides the APR translation handle to be used + * for translating the content before calculating the digest. + * @param context The MD4 content to set the translation for. + * @param xlate The translation handle to use for this MD4 context + */ +APU_DECLARE(apr_status_t) apr_md4_set_xlate(apr_md4_ctx_t *context, + apr_xlate_t *xlate); +#else +#define apr_md4_set_xlate(context, xlate) APR_ENOTIMPL +#endif + +/** + * MD4 block update operation. Continue an MD4 message-digest operation, + * processing another message block, and updating the context. + * @param context The MD4 content to update. + * @param input next message block to update + * @param inputLen The length of the next message block + */ +APU_DECLARE(apr_status_t) apr_md4_update(apr_md4_ctx_t *context, + const unsigned char *input, + apr_size_t inputLen); + +/** + * MD4 finalization. Ends an MD4 message-digest operation, writing the + * message digest and zeroing the context + * @param digest The final MD4 digest + * @param context The MD4 content we are finalizing. + */ +APU_DECLARE(apr_status_t) apr_md4_final( + unsigned char digest[APR_MD4_DIGESTSIZE], + apr_md4_ctx_t *context); + +/** + * MD4 digest computation + * @param digest The MD4 digest + * @param input message block to use + * @param inputLen The length of the message block + */ +APU_DECLARE(apr_status_t) apr_md4(unsigned char digest[APR_MD4_DIGESTSIZE], + const unsigned char *input, + apr_size_t inputLen); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_MD4_H */ diff --git a/c/dependencies/linux/apr/include/apr_md5.h b/c/dependencies/linux/apr/include/apr_md5.h new file mode 100644 index 00000000..e0202dfd --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_md5.h @@ -0,0 +1,176 @@ +/* + * This is work is derived from material Copyright RSA Data Security, Inc. + * + * The RSA copyright statement and Licence for that original material is + * included below. This is followed by the Apache copyright statement and + * licence for the modifications made to that material. + */ + +/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All + rights reserved. + + License to copy and use this software is granted provided that it + is identified as the "RSA Data Security, Inc. MD5 Message-Digest + Algorithm" in all material mentioning or referencing this software + or this function. + + License is also granted to make and use derivative works provided + that such works are identified as "derived from the RSA Data + Security, Inc. MD5 Message-Digest Algorithm" in all material + mentioning or referencing the derived work. + + RSA Data Security, Inc. makes no representations concerning either + the merchantability of this software or the suitability of this + software for any particular purpose. It is provided "as is" + without express or implied warranty of any kind. + + These notices must be retained in any copies of any part of this + documentation and/or software. + */ + +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_MD5_H +#define APR_MD5_H + +#include "apu.h" +#include "apr_xlate.h" + +#ifdef __cplusplus +extern "C" { +#endif +/** + * @file apr_md5.h + * @brief APR MD5 Routines + */ + +/** + * @defgroup APR_MD5 MD5 Routines + * @ingroup APR + * @{ + */ + +/** The MD5 digest size */ +#define APR_MD5_DIGESTSIZE 16 + +/** @see apr_md5_ctx_t */ +typedef struct apr_md5_ctx_t apr_md5_ctx_t; + +/** MD5 context. */ +struct apr_md5_ctx_t { + /** state (ABCD) */ + apr_uint32_t state[4]; + /** number of bits, modulo 2^64 (lsb first) */ + apr_uint32_t count[2]; + /** input buffer */ + unsigned char buffer[64]; + /** translation handle + * ignored if xlate is unsupported + */ + apr_xlate_t *xlate; +}; + +/** + * MD5 Initialize. Begins an MD5 operation, writing a new context. + * @param context The MD5 context to initialize. + */ +APU_DECLARE(apr_status_t) apr_md5_init(apr_md5_ctx_t *context); + +/** + * MD5 translation setup. Provides the APR translation handle to be used + * for translating the content before calculating the digest. + * @param context The MD5 content to set the translation for. + * @param xlate The translation handle to use for this MD5 context + */ +APU_DECLARE(apr_status_t) apr_md5_set_xlate(apr_md5_ctx_t *context, + apr_xlate_t *xlate); + +/** + * MD5 block update operation. Continue an MD5 message-digest operation, + * processing another message block, and updating the context. + * @param context The MD5 content to update. + * @param input next message block to update + * @param inputLen The length of the next message block + */ +APU_DECLARE(apr_status_t) apr_md5_update(apr_md5_ctx_t *context, + const void *input, + apr_size_t inputLen); + +/** + * MD5 finalization. Ends an MD5 message-digest operation, writing the + * message digest and zeroing the context + * @param digest The final MD5 digest + * @param context The MD5 content we are finalizing. + */ +APU_DECLARE(apr_status_t) apr_md5_final(unsigned char digest[APR_MD5_DIGESTSIZE], + apr_md5_ctx_t *context); + +/** + * MD5 in one step + * @param digest The final MD5 digest + * @param input The message block to use + * @param inputLen The length of the message block + */ +APU_DECLARE(apr_status_t) apr_md5(unsigned char digest[APR_MD5_DIGESTSIZE], + const void *input, + apr_size_t inputLen); + +/** + * Encode a password using an MD5 algorithm + * @param password The password to encode + * @param salt The salt string to use for the encoding + * @param result The string to store the encoded password in + * @param nbytes The size of the result buffer + */ +APU_DECLARE(apr_status_t) apr_md5_encode(const char *password, const char *salt, + char *result, apr_size_t nbytes); + +/** + * Encode a password using the bcrypt algorithm + * @param password The password to encode + * @param count The cost of the encoding, possible values are 4 to 31 + * @param salt Pointer to binary data to be used as salt for the encoding + * @param salt_len The size of the salt data (must be >= 16) + * @param out The string to store the encoded password in + * @param out_len The size of the result buffer (must be >= 61) + */ +APU_DECLARE(apr_status_t) apr_bcrypt_encode(const char *pw, + unsigned int count, + const unsigned char *salt, + apr_size_t salt_len, + char *out, apr_size_t out_len); + +/** + * Validate hashes created by APR-supported algorithms: md5, bcrypt, and sha1. + * hashes created by crypt are supported only on platforms that provide + * crypt(3), so don't rely on that function unless you know that your + * application will be run only on platforms that support it. On platforms + * that don't support crypt(3), this falls back to a clear text string + * comparison. + * @param passwd The password to validate + * @param hash The password to validate against + */ +APU_DECLARE(apr_status_t) apr_password_validate(const char *passwd, + const char *hash); + + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_MD5_H */ diff --git a/c/dependencies/linux/apr/include/apr_memcache.h b/c/dependencies/linux/apr/include/apr_memcache.h new file mode 100644 index 00000000..82878825 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_memcache.h @@ -0,0 +1,444 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_MEMCACHE_H +#define APR_MEMCACHE_H + +/** + * @file apr_memcache.h + * @brief Client interface for memcached + * @remark To use this interface you must have a separate memcached + * server running. See the memcached website at http://www.danga.com/memcached/ + * for more information. + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_time.h" +#include "apr_strings.h" +#include "apr_network_io.h" +#include "apr_ring.h" +#include "apr_buckets.h" +#include "apr_reslist.h" +#include "apr_hash.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_Util_MC Memcached Client Routines + * @ingroup APR_Util + * @{ + */ + +/** Specifies the status of a memcached server */ +typedef enum +{ + APR_MC_SERVER_LIVE, /**< Server is alive and responding to requests */ + APR_MC_SERVER_DEAD /**< Server is not responding to requests */ +} apr_memcache_server_status_t; + +/** Opaque memcache client connection object */ +typedef struct apr_memcache_conn_t apr_memcache_conn_t; + +/** Memcache Server Info Object */ +typedef struct apr_memcache_server_t apr_memcache_server_t; +struct apr_memcache_server_t +{ + const char *host; /**< Hostname of this Server */ + apr_port_t port; /**< Port of this Server */ + apr_memcache_server_status_t status; /**< @see apr_memcache_server_status_t */ +#if APR_HAS_THREADS || defined(DOXYGEN) + apr_reslist_t *conns; /**< Resource list of actual client connections */ +#else + apr_memcache_conn_t *conn; +#endif + apr_pool_t *p; /** Pool to use for private allocations */ +#if APR_HAS_THREADS + apr_thread_mutex_t *lock; +#endif + apr_time_t btime; +}; + +/* Custom hash callback function prototype, user for server selection. +* @param baton user selected baton +* @param data data to hash +* @param data_len length of data +*/ +typedef apr_uint32_t (*apr_memcache_hash_func)(void *baton, + const char *data, + const apr_size_t data_len); + +typedef struct apr_memcache_t apr_memcache_t; + +/* Custom Server Select callback function prototype. +* @param baton user selected baton +* @param mc memcache instance, use mc->live_servers to select a node +* @param hash hash of the selected key. +*/ +typedef apr_memcache_server_t* (*apr_memcache_server_func)(void *baton, + apr_memcache_t *mc, + const apr_uint32_t hash); + +/** Container for a set of memcached servers */ +struct apr_memcache_t +{ + apr_uint32_t flags; /**< Flags, Not currently used */ + apr_uint16_t nalloc; /**< Number of Servers Allocated */ + apr_uint16_t ntotal; /**< Number of Servers Added */ + apr_memcache_server_t **live_servers; /**< Array of Servers */ + apr_pool_t *p; /** Pool to use for allocations */ + void *hash_baton; + apr_memcache_hash_func hash_func; + void *server_baton; + apr_memcache_server_func server_func; +}; + +/** Returned Data from a multiple get */ +typedef struct +{ + apr_status_t status; + const char* key; + apr_size_t len; + char *data; + apr_uint16_t flags; +} apr_memcache_value_t; + +/** + * Creates a crc32 hash used to split keys between servers + * @param mc The memcache client object to use + * @param data Data to be hashed + * @param data_len Length of the data to use + * @return crc32 hash of data + * @remark The crc32 hash is not compatible with old memcached clients. + */ +APU_DECLARE(apr_uint32_t) apr_memcache_hash(apr_memcache_t *mc, + const char *data, + const apr_size_t data_len); + +/** + * Pure CRC32 Hash. Used by some clients. + */ +APU_DECLARE(apr_uint32_t) apr_memcache_hash_crc32(void *baton, + const char *data, + const apr_size_t data_len); + +/** + * hash compatible with the standard Perl Client. + */ +APU_DECLARE(apr_uint32_t) apr_memcache_hash_default(void *baton, + const char *data, + const apr_size_t data_len); + +/** + * Picks a server based on a hash + * @param mc The memcache client object to use + * @param hash Hashed value of a Key + * @return server that controls specified hash + * @see apr_memcache_hash + */ +APU_DECLARE(apr_memcache_server_t *) apr_memcache_find_server_hash(apr_memcache_t *mc, + const apr_uint32_t hash); + +/** + * server selection compatible with the standard Perl Client. + */ +APU_DECLARE(apr_memcache_server_t *) apr_memcache_find_server_hash_default(void *baton, + apr_memcache_t *mc, + const apr_uint32_t hash); + +/** + * Adds a server to a client object + * @param mc The memcache client object to use + * @param server Server to add + * @remark Adding servers is not thread safe, and should be done once at startup. + * @warning Changing servers after startup may cause keys to go to + * different servers. + */ +APU_DECLARE(apr_status_t) apr_memcache_add_server(apr_memcache_t *mc, + apr_memcache_server_t *server); + + +/** + * Finds a Server object based on a hostname/port pair + * @param mc The memcache client object to use + * @param host Hostname of the server + * @param port Port of the server + * @return Server with matching Hostname and Port, or NULL if none was found. + */ +APU_DECLARE(apr_memcache_server_t *) apr_memcache_find_server(apr_memcache_t *mc, + const char *host, + apr_port_t port); + +/** + * Enables a Server for use again + * @param mc The memcache client object to use + * @param ms Server to Activate + */ +APU_DECLARE(apr_status_t) apr_memcache_enable_server(apr_memcache_t *mc, + apr_memcache_server_t *ms); + + +/** + * Disable a Server + * @param mc The memcache client object to use + * @param ms Server to Disable + */ +APU_DECLARE(apr_status_t) apr_memcache_disable_server(apr_memcache_t *mc, + apr_memcache_server_t *ms); + +/** + * Creates a new Server Object + * @param p Pool to use + * @param host hostname of the server + * @param port port of the server + * @param min minimum number of client sockets to open + * @param smax soft maximum number of client connections to open + * @param max hard maximum number of client connections + * @param ttl time to live in microseconds of a client connection + * @param ns location of the new server object + * @see apr_reslist_create + * @remark min, smax, and max are only used when APR_HAS_THREADS + */ +APU_DECLARE(apr_status_t) apr_memcache_server_create(apr_pool_t *p, + const char *host, + apr_port_t port, + apr_uint32_t min, + apr_uint32_t smax, + apr_uint32_t max, + apr_uint32_t ttl, + apr_memcache_server_t **ns); +/** + * Creates a new memcached client object + * @param p Pool to use + * @param max_servers maximum number of servers + * @param flags Not currently used + * @param mc location of the new memcache client object + */ +APU_DECLARE(apr_status_t) apr_memcache_create(apr_pool_t *p, + apr_uint16_t max_servers, + apr_uint32_t flags, + apr_memcache_t **mc); + +/** + * Gets a value from the server, allocating the value out of p + * @param mc client to use + * @param p Pool to use + * @param key null terminated string containing the key + * @param baton location of the allocated value + * @param len length of data at baton + * @param flags any flags set by the client for this key + * @return + */ +APU_DECLARE(apr_status_t) apr_memcache_getp(apr_memcache_t *mc, + apr_pool_t *p, + const char* key, + char **baton, + apr_size_t *len, + apr_uint16_t *flags); + + +/** + * Add a key to a hash for a multiget query + * if the hash (*value) is NULL it will be created + * @param data_pool pool from where the hash and their items are created from + * @param key null terminated string containing the key + * @param values hash of keys and values that this key will be added to + * @return + */ +APU_DECLARE(void) apr_memcache_add_multget_key(apr_pool_t *data_pool, + const char* key, + apr_hash_t **values); + +/** + * Gets multiple values from the server, allocating the values out of p + * @param mc client to use + * @param temp_pool Pool used for temporary allocations. May be cleared inside this + * call. + * @param data_pool Pool used to allocate data for the returned values. + * @param values hash of apr_memcache_value_t keyed by strings, contains the + * result of the multiget call. + * @return + */ +APU_DECLARE(apr_status_t) apr_memcache_multgetp(apr_memcache_t *mc, + apr_pool_t *temp_pool, + apr_pool_t *data_pool, + apr_hash_t *values); + +/** + * Sets a value by key on the server + * @param mc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param timeout time in seconds for the data to live on the server + * @param flags any flags set by the client for this key + */ +APU_DECLARE(apr_status_t) apr_memcache_set(apr_memcache_t *mc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint32_t timeout, + apr_uint16_t flags); + +/** + * Adds value by key on the server + * @param mc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param timeout time for the data to live on the server + * @param flags any flags set by the client for this key + * @return APR_SUCCESS if the key was added, APR_EEXIST if the key + * already exists on the server. + */ +APU_DECLARE(apr_status_t) apr_memcache_add(apr_memcache_t *mc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint32_t timeout, + apr_uint16_t flags); + +/** + * Replaces value by key on the server + * @param mc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param timeout time for the data to live on the server + * @param flags any flags set by the client for this key + * @return APR_SUCCESS if the key was added, APR_EEXIST if the key + * did not exist on the server. + */ +APU_DECLARE(apr_status_t) apr_memcache_replace(apr_memcache_t *mc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint32_t timeout, + apr_uint16_t flags); +/** + * Deletes a key from a server + * @param mc client to use + * @param key null terminated string containing the key + * @param timeout time for the delete to stop other clients from adding + */ +APU_DECLARE(apr_status_t) apr_memcache_delete(apr_memcache_t *mc, + const char *key, + apr_uint32_t timeout); + +/** + * Increments a value + * @param mc client to use + * @param key null terminated string containing the key + * @param n number to increment by + * @param nv new value after incrementing + */ +APU_DECLARE(apr_status_t) apr_memcache_incr(apr_memcache_t *mc, + const char *key, + apr_int32_t n, + apr_uint32_t *nv); + +/** + * Decrements a value + * @param mc client to use + * @param key null terminated string containing the key + * @param n number to decrement by + * @param new_value new value after decrementing + */ +APU_DECLARE(apr_status_t) apr_memcache_decr(apr_memcache_t *mc, + const char *key, + apr_int32_t n, + apr_uint32_t *new_value); + +/** + * Query a server's version + * @param ms server to query + * @param p Pool to allocate answer from + * @param baton location to store server version string + * @param len length of the server version string + */ +APU_DECLARE(apr_status_t) apr_memcache_version(apr_memcache_server_t *ms, + apr_pool_t *p, + char **baton); + +typedef struct +{ + /** Version string of this server */ + const char *version; + /** Process id of this server process */ + apr_uint32_t pid; + /** Number of seconds this server has been running */ + apr_uint32_t uptime; + /** current UNIX time according to the server */ + apr_time_t time; + /** The size of a pointer on the current machine */ + apr_uint32_t pointer_size; + /** Accumulated user time for this process */ + apr_time_t rusage_user; + /** Accumulated system time for this process */ + apr_time_t rusage_system; + /** Current number of items stored by the server */ + apr_uint32_t curr_items; + /** Total number of items stored by this server */ + apr_uint32_t total_items; + /** Current number of bytes used by this server to store items */ + apr_uint64_t bytes; + /** Number of open connections */ + apr_uint32_t curr_connections; + /** Total number of connections opened since the server started running */ + apr_uint32_t total_connections; + /** Number of connection structures allocated by the server */ + apr_uint32_t connection_structures; + /** Cumulative number of retrieval requests */ + apr_uint32_t cmd_get; + /** Cumulative number of storage requests */ + apr_uint32_t cmd_set; + /** Number of keys that have been requested and found present */ + apr_uint32_t get_hits; + /** Number of items that have been requested and not found */ + apr_uint32_t get_misses; + /** Number of items removed from cache because they passed their + expiration time */ + apr_uint64_t evictions; + /** Total number of bytes read by this server */ + apr_uint64_t bytes_read; + /** Total number of bytes sent by this server */ + apr_uint64_t bytes_written; + /** Number of bytes this server is allowed to use for storage. */ + apr_uint32_t limit_maxbytes; + /** Number of threads the server is running (if built with threading) */ + apr_uint32_t threads; +} apr_memcache_stats_t; + +/** + * Query a server for statistics + * @param ms server to query + * @param p Pool to allocate answer from + * @param stats location of the new statistics structure + */ +APU_DECLARE(apr_status_t) apr_memcache_stats(apr_memcache_server_t *ms, + apr_pool_t *p, + apr_memcache_stats_t **stats); + + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_MEMCACHE_H */ diff --git a/c/dependencies/linux/apr/include/apr_mmap.h b/c/dependencies/linux/apr/include/apr_mmap.h new file mode 100644 index 00000000..c14de192 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_mmap.h @@ -0,0 +1,171 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_MMAP_H +#define APR_MMAP_H + +/** + * @file apr_mmap.h + * @brief APR MMAP routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_ring.h" +#include "apr_file_io.h" /* for apr_file_t */ + +#ifdef BEOS +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_mmap MMAP (Memory Map) Routines + * @ingroup APR + * @{ + */ + +/** MMap opened for reading */ +#define APR_MMAP_READ 1 +/** MMap opened for writing */ +#define APR_MMAP_WRITE 2 + +/** @see apr_mmap_t */ +typedef struct apr_mmap_t apr_mmap_t; + +/** + * @remark + * As far as I can tell the only really sane way to store an MMAP is as a + * void * and a length. BeOS requires this area_id, but that's just a little + * something extra. I am exposing this type, because it doesn't make much + * sense to keep it private, and opening it up makes some stuff easier in + * Apache. + */ +/** The MMAP structure */ +struct apr_mmap_t { + /** The pool the mmap structure was allocated out of. */ + apr_pool_t *cntxt; +#ifdef BEOS + /** An area ID. Only valid on BeOS */ + area_id area; +#endif +#ifdef WIN32 + /** The handle of the file mapping */ + HANDLE mhandle; + /** The start of the real memory page area (mapped view) */ + void *mv; + /** The physical start, size and offset */ + apr_off_t pstart; + apr_size_t psize; + apr_off_t poffset; +#endif + /** The start of the memory mapped area */ + void *mm; + /** The amount of data in the mmap */ + apr_size_t size; + /** ring of apr_mmap_t's that reference the same + * mmap'ed region; acts in place of a reference count */ + APR_RING_ENTRY(apr_mmap_t) link; +}; + +#if APR_HAS_MMAP || defined(DOXYGEN) + +/** @def APR_MMAP_THRESHOLD + * Files have to be at least this big before they're mmap()d. This is to deal + * with systems where the expense of doing an mmap() and an munmap() outweighs + * the benefit for small files. It shouldn't be set lower than 1. + */ +#ifdef MMAP_THRESHOLD +# define APR_MMAP_THRESHOLD MMAP_THRESHOLD +#else +# ifdef SUNOS4 +# define APR_MMAP_THRESHOLD (8*1024) +# else +# define APR_MMAP_THRESHOLD 1 +# endif /* SUNOS4 */ +#endif /* MMAP_THRESHOLD */ + +/** @def APR_MMAP_LIMIT + * Maximum size of MMap region + */ +#ifdef MMAP_LIMIT +# define APR_MMAP_LIMIT MMAP_LIMIT +#else +# define APR_MMAP_LIMIT (4*1024*1024) +#endif /* MMAP_LIMIT */ + +/** Can this file be MMaped */ +#define APR_MMAP_CANDIDATE(filelength) \ + ((filelength >= APR_MMAP_THRESHOLD) && (filelength < APR_MMAP_LIMIT)) + +/* Function definitions */ + +/** + * Create a new mmap'ed file out of an existing APR file. + * @param newmmap The newly created mmap'ed file. + * @param file The file to turn into an mmap. + * @param offset The offset into the file to start the data pointer at. + * @param size The size of the file + * @param flag bit-wise or of: + *
+ *          APR_MMAP_READ       MMap opened for reading
+ *          APR_MMAP_WRITE      MMap opened for writing
+ * 
+ * @param cntxt The pool to use when creating the mmap. + */ +APR_DECLARE(apr_status_t) apr_mmap_create(apr_mmap_t **newmmap, + apr_file_t *file, apr_off_t offset, + apr_size_t size, apr_int32_t flag, + apr_pool_t *cntxt); + +/** + * Duplicate the specified MMAP. + * @param new_mmap The structure to duplicate into. + * @param old_mmap The mmap to duplicate. + * @param p The pool to use for new_mmap. + */ +APR_DECLARE(apr_status_t) apr_mmap_dup(apr_mmap_t **new_mmap, + apr_mmap_t *old_mmap, + apr_pool_t *p); + +/** + * Remove a mmap'ed. + * @param mm The mmap'ed file. + */ +APR_DECLARE(apr_status_t) apr_mmap_delete(apr_mmap_t *mm); + +/** + * Move the pointer into the mmap'ed file to the specified offset. + * @param addr The pointer to the offset specified. + * @param mm The mmap'ed file. + * @param offset The offset to move to. + */ +APR_DECLARE(apr_status_t) apr_mmap_offset(void **addr, apr_mmap_t *mm, + apr_off_t offset); + +#endif /* APR_HAS_MMAP */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_MMAP_H */ diff --git a/c/dependencies/linux/apr/include/apr_network_io.h b/c/dependencies/linux/apr/include/apr_network_io.h new file mode 100644 index 00000000..7d6957bc --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_network_io.h @@ -0,0 +1,951 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_NETWORK_IO_H +#define APR_NETWORK_IO_H +/** + * @file apr_network_io.h + * @brief APR Network library + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_file_io.h" +#include "apr_errno.h" +#include "apr_inherit.h" +#include "apr_perms_set.h" + +#if APR_HAVE_NETINET_IN_H +#include +#endif +#if APR_HAVE_SYS_UN_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_network_io Network Routines + * @ingroup APR + * @{ + */ + +#ifndef APR_MAX_SECS_TO_LINGER +/** Maximum seconds to linger */ +#define APR_MAX_SECS_TO_LINGER 30 +#endif + +#ifndef APRMAXHOSTLEN +/** Maximum hostname length */ +#define APRMAXHOSTLEN 256 +#endif + +#ifndef APR_ANYADDR +/** Default 'any' address */ +#define APR_ANYADDR "0.0.0.0" +#endif + +/** + * @defgroup apr_sockopt Socket option definitions + * @{ + */ +#define APR_SO_LINGER 1 /**< Linger */ +#define APR_SO_KEEPALIVE 2 /**< Keepalive */ +#define APR_SO_DEBUG 4 /**< Debug */ +#define APR_SO_NONBLOCK 8 /**< Non-blocking IO */ +#define APR_SO_REUSEADDR 16 /**< Reuse addresses */ +#define APR_SO_SNDBUF 64 /**< Send buffer */ +#define APR_SO_RCVBUF 128 /**< Receive buffer */ +#define APR_SO_DISCONNECTED 256 /**< Disconnected */ +#define APR_TCP_NODELAY 512 /**< For SCTP sockets, this is mapped + * to STCP_NODELAY internally. + */ +#define APR_TCP_NOPUSH 1024 /**< No push */ +#define APR_RESET_NODELAY 2048 /**< This flag is ONLY set internally + * when we set APR_TCP_NOPUSH with + * APR_TCP_NODELAY set to tell us that + * APR_TCP_NODELAY should be turned on + * again when NOPUSH is turned off + */ +#define APR_INCOMPLETE_READ 4096 /**< Set on non-blocking sockets + * (timeout != 0) on which the + * previous read() did not fill a buffer + * completely. the next apr_socket_recv() + * will first call select()/poll() rather than + * going straight into read(). (Can also + * be set by an application to force a + * select()/poll() call before the next + * read, in cases where the app expects + * that an immediate read would fail.) + */ +#define APR_INCOMPLETE_WRITE 8192 /**< like APR_INCOMPLETE_READ, but for write + * @see APR_INCOMPLETE_READ + */ +#define APR_IPV6_V6ONLY 16384 /**< Don't accept IPv4 connections on an + * IPv6 listening socket. + */ +#define APR_TCP_DEFER_ACCEPT 32768 /**< Delay accepting of new connections + * until data is available. + * @see apr_socket_accept_filter + */ +#define APR_SO_BROADCAST 65536 /**< Allow broadcast + */ +#define APR_SO_FREEBIND 131072 /**< Allow binding to addresses not owned + * by any interface + */ + +/** @} */ + +/** Define what type of socket shutdown should occur. */ +typedef enum { + APR_SHUTDOWN_READ, /**< no longer allow read request */ + APR_SHUTDOWN_WRITE, /**< no longer allow write requests */ + APR_SHUTDOWN_READWRITE /**< no longer allow read or write requests */ +} apr_shutdown_how_e; + +#define APR_IPV4_ADDR_OK 0x01 /**< @see apr_sockaddr_info_get() */ +#define APR_IPV6_ADDR_OK 0x02 /**< @see apr_sockaddr_info_get() */ + +#if (!APR_HAVE_IN_ADDR) +/** + * We need to make sure we always have an in_addr type, so APR will just + * define it ourselves, if the platform doesn't provide it. + */ +struct in_addr { + apr_uint32_t s_addr; /**< storage to hold the IP# */ +}; +#endif + +/** @def APR_INADDR_NONE + * Not all platforms have a real INADDR_NONE. This macro replaces + * INADDR_NONE on all platforms. + */ +#ifdef INADDR_NONE +#define APR_INADDR_NONE INADDR_NONE +#else +#define APR_INADDR_NONE ((unsigned int) 0xffffffff) +#endif + +/** + * @def APR_INET + * Not all platforms have these defined, so we'll define them here + * The default values come from FreeBSD 4.1.1 + */ +#define APR_INET AF_INET +/** @def APR_UNSPEC + * Let the system decide which address family to use + */ +#ifdef AF_UNSPEC +#define APR_UNSPEC AF_UNSPEC +#else +#define APR_UNSPEC 0 +#endif +#if APR_HAVE_IPV6 +/** @def APR_INET6 +* IPv6 Address Family. Not all platforms may have this defined. +*/ + +#define APR_INET6 AF_INET6 +#endif + +#if APR_HAVE_SOCKADDR_UN +#if defined (AF_UNIX) +#define APR_UNIX AF_UNIX +#elif defined(AF_LOCAL) +#define APR_UNIX AF_LOCAL +#else +#error "Neither AF_UNIX nor AF_LOCAL is defined" +#endif +#else /* !APR_HAVE_SOCKADDR_UN */ +#if defined (AF_UNIX) +#define APR_UNIX AF_UNIX +#elif defined(AF_LOCAL) +#define APR_UNIX AF_LOCAL +#else +/* TODO: Use a smarter way to detect unique APR_UNIX value */ +#define APR_UNIX 1234 +#endif +#endif + +/** + * @defgroup IP_Proto IP Protocol Definitions for use when creating sockets + * @{ + */ +#define APR_PROTO_TCP 6 /**< TCP */ +#define APR_PROTO_UDP 17 /**< UDP */ +#define APR_PROTO_SCTP 132 /**< SCTP */ +/** @} */ + +/** + * Enum used to denote either the local and remote endpoint of a + * connection. + */ +typedef enum { + APR_LOCAL, /**< Socket information for local end of connection */ + APR_REMOTE /**< Socket information for remote end of connection */ +} apr_interface_e; + +/** + * The specific declaration of inet_addr's ... some platforms fall back + * inet_network (this is not good, but necessary) + */ + +#if APR_HAVE_INET_ADDR +#define apr_inet_addr inet_addr +#elif APR_HAVE_INET_NETWORK /* only DGUX, as far as I know */ +/** + * @warning + * not generally safe... inet_network() and inet_addr() perform + * different functions */ +#define apr_inet_addr inet_network +#endif + +/** A structure to represent sockets */ +typedef struct apr_socket_t apr_socket_t; +/** + * A structure to encapsulate headers and trailers for apr_socket_sendfile + */ +typedef struct apr_hdtr_t apr_hdtr_t; +/** A structure to represent in_addr */ +typedef struct in_addr apr_in_addr_t; +/** A structure to represent an IP subnet */ +typedef struct apr_ipsubnet_t apr_ipsubnet_t; + +/** @remark use apr_uint16_t just in case some system has a short that isn't 16 bits... */ +typedef apr_uint16_t apr_port_t; + +/** @remark It's defined here as I think it should all be platform safe... + * @see apr_sockaddr_t + */ +typedef struct apr_sockaddr_t apr_sockaddr_t; +/** + * APRs socket address type, used to ensure protocol independence + */ +struct apr_sockaddr_t { + /** The pool to use... */ + apr_pool_t *pool; + /** The hostname */ + char *hostname; + /** Either a string of the port number or the service name for the port */ + char *servname; + /** The numeric port */ + apr_port_t port; + /** The family */ + apr_int32_t family; + /** How big is the sockaddr we're using? */ + apr_socklen_t salen; + /** How big is the ip address structure we're using? */ + int ipaddr_len; + /** How big should the address buffer be? 16 for v4 or 46 for v6 + * used in inet_ntop... */ + int addr_str_len; + /** This points to the IP address structure within the appropriate + * sockaddr structure. */ + void *ipaddr_ptr; + /** If multiple addresses were found by apr_sockaddr_info_get(), this + * points to a representation of the next address. */ + apr_sockaddr_t *next; + /** Union of either IPv4 or IPv6 sockaddr. */ + union { + /** IPv4 sockaddr structure */ + struct sockaddr_in sin; +#if APR_HAVE_IPV6 + /** IPv6 sockaddr structure */ + struct sockaddr_in6 sin6; +#endif +#if APR_HAVE_SA_STORAGE + /** Placeholder to ensure that the size of this union is not + * dependent on whether APR_HAVE_IPV6 is defined. */ + struct sockaddr_storage sas; +#endif +#if APR_HAVE_SOCKADDR_UN + /** Unix domain socket sockaddr structure */ + struct sockaddr_un unx; +#endif + } sa; +}; + +#if APR_HAS_SENDFILE +/** + * Support reusing the socket on platforms which support it (from disconnect, + * specifically Win32. + * @remark Optional flag passed into apr_socket_sendfile() + */ +#define APR_SENDFILE_DISCONNECT_SOCKET 1 +#endif + +/** A structure to encapsulate headers and trailers for apr_socket_sendfile */ +struct apr_hdtr_t { + /** An iovec to store the headers sent before the file. */ + struct iovec* headers; + /** number of headers in the iovec */ + int numheaders; + /** An iovec to store the trailers sent after the file. */ + struct iovec* trailers; + /** number of trailers in the iovec */ + int numtrailers; +}; + +/* function definitions */ + +/** + * Create a socket. + * @param new_sock The new socket that has been set up. + * @param family The address family of the socket (e.g., APR_INET). + * @param type The type of the socket (e.g., SOCK_STREAM). + * @param protocol The protocol of the socket (e.g., APR_PROTO_TCP). + * @param cont The pool for the apr_socket_t and associated storage. + * @note The pool will be used by various functions that operate on the + * socket. The caller must ensure that it is not used by other threads + * at the same time. + */ +APR_DECLARE(apr_status_t) apr_socket_create(apr_socket_t **new_sock, + int family, int type, + int protocol, + apr_pool_t *cont); + +/** + * Shutdown either reading, writing, or both sides of a socket. + * @param thesocket The socket to close + * @param how How to shutdown the socket. One of: + *
+ *            APR_SHUTDOWN_READ         no longer allow read requests
+ *            APR_SHUTDOWN_WRITE        no longer allow write requests
+ *            APR_SHUTDOWN_READWRITE    no longer allow read or write requests 
+ * 
+ * @see apr_shutdown_how_e + * @remark This does not actually close the socket descriptor, it just + * controls which calls are still valid on the socket. + */ +APR_DECLARE(apr_status_t) apr_socket_shutdown(apr_socket_t *thesocket, + apr_shutdown_how_e how); + +/** + * Close a socket. + * @param thesocket The socket to close + */ +APR_DECLARE(apr_status_t) apr_socket_close(apr_socket_t *thesocket); + +/** + * Bind the socket to its associated port + * @param sock The socket to bind + * @param sa The socket address to bind to + * @remark This may be where we will find out if there is any other process + * using the selected port. + */ +APR_DECLARE(apr_status_t) apr_socket_bind(apr_socket_t *sock, + apr_sockaddr_t *sa); + +/** + * Listen to a bound socket for connections. + * @param sock The socket to listen on + * @param backlog The number of outstanding connections allowed in the sockets + * listen queue. If this value is less than zero, the listen + * queue size is set to zero. + */ +APR_DECLARE(apr_status_t) apr_socket_listen(apr_socket_t *sock, + apr_int32_t backlog); + +/** + * Accept a new connection request + * @param new_sock A copy of the socket that is connected to the socket that + * made the connection request. This is the socket which should + * be used for all future communication. + * @param sock The socket we are listening on. + * @param connection_pool The pool for the new socket. + * @note The pool will be used by various functions that operate on the + * socket. The caller must ensure that it is not used by other threads + * at the same time. + */ +APR_DECLARE(apr_status_t) apr_socket_accept(apr_socket_t **new_sock, + apr_socket_t *sock, + apr_pool_t *connection_pool); + +/** + * Issue a connection request to a socket either on the same machine + * or a different one. + * @param sock The socket we wish to use for our side of the connection + * @param sa The address of the machine we wish to connect to. + */ +APR_DECLARE(apr_status_t) apr_socket_connect(apr_socket_t *sock, + apr_sockaddr_t *sa); + +/** + * Determine whether the receive part of the socket has been closed by + * the peer (such that a subsequent call to apr_socket_read would + * return APR_EOF), if the socket's receive buffer is empty. This + * function does not block waiting for I/O. + * + * @param sock The socket to check + * @param atreadeof If APR_SUCCESS is returned, *atreadeof is set to + * non-zero if a subsequent read would return APR_EOF + * @return an error is returned if it was not possible to determine the + * status, in which case *atreadeof is not changed. + */ +APR_DECLARE(apr_status_t) apr_socket_atreadeof(apr_socket_t *sock, + int *atreadeof); + +/** + * Create apr_sockaddr_t from hostname, address family, and port. + * @param sa The new apr_sockaddr_t. + * @param hostname The hostname or numeric address string to resolve/parse, or + * NULL to build an address that corresponds to 0.0.0.0 or :: + * or in case of APR_UNIX family it is absolute socket filename. + * @param family The address family to use, or APR_UNSPEC if the system should + * decide. + * @param port The port number. + * @param flags Special processing flags: + *
+ *       APR_IPV4_ADDR_OK          first query for IPv4 addresses; only look
+ *                                 for IPv6 addresses if the first query failed;
+ *                                 only valid if family is APR_UNSPEC and hostname
+ *                                 isn't NULL; mutually exclusive with
+ *                                 APR_IPV6_ADDR_OK
+ *       APR_IPV6_ADDR_OK          first query for IPv6 addresses; only look
+ *                                 for IPv4 addresses if the first query failed;
+ *                                 only valid if family is APR_UNSPEC and hostname
+ *                                 isn't NULL and APR_HAVE_IPV6; mutually exclusive
+ *                                 with APR_IPV4_ADDR_OK
+ * 
+ * @param p The pool for the apr_sockaddr_t and associated storage. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_info_get(apr_sockaddr_t **sa, + const char *hostname, + apr_int32_t family, + apr_port_t port, + apr_int32_t flags, + apr_pool_t *p); + +/** + * Copy apr_sockaddr_t src to dst on pool p. + * @param dst The destination apr_sockaddr_t. + * @param src The source apr_sockaddr_t. + * @param p The pool for the apr_sockaddr_t and associated storage. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_info_copy(apr_sockaddr_t **dst, + const apr_sockaddr_t *src, + apr_pool_t *p); + +/* Set the zone of an IPv6 link-local address object. + * @param sa Socket address object + * @param zone_id Zone ID (textual "eth0" or numeric "3"). + * @return Returns APR_EBADIP for non-IPv6 socket or an IPv6 address + * which isn't link-local. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_zone_set(apr_sockaddr_t *sa, + const char *zone_id); + + +/* Retrieve the zone of an IPv6 link-local address object. + * @param sa Socket address object + * @param name If non-NULL, set to the textual representation of the zone id + * @param id If non-NULL, set to the integer zone id + * @param p Pool from which *name is allocated if used. + * @return Returns APR_EBADIP for non-IPv6 socket or socket without any zone id + * set, or other error if the interface could not be mapped to a name. + * @remark Both name and id may be NULL, neither are modified if + * non-NULL in error cases. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_zone_get(const apr_sockaddr_t *sa, + const char **name, + apr_uint32_t *id, + apr_pool_t *p); + +/** + * Look up the host name from an apr_sockaddr_t. + * @param hostname The hostname. + * @param sa The apr_sockaddr_t. + * @param flags Special processing flags. + * @remark Results can vary significantly between platforms + * when processing wildcard socket addresses. + */ +APR_DECLARE(apr_status_t) apr_getnameinfo(char **hostname, + apr_sockaddr_t *sa, + apr_int32_t flags); + +/** + * Parse hostname/IP address with scope id and port. + * + * Any of the following strings are accepted: + * 8080 (just the port number) + * www.apache.org (just the hostname) + * www.apache.org:8080 (hostname and port number) + * [fe80::1]:80 (IPv6 numeric address string only) + * [fe80::1%eth0] (IPv6 numeric address string and scope id) + * + * Invalid strings: + * (empty string) + * [abc] (not valid IPv6 numeric address string) + * abc:65536 (invalid port number) + * + * @param addr The new buffer containing just the hostname. On output, *addr + * will be NULL if no hostname/IP address was specfied. + * @param scope_id The new buffer containing just the scope id. On output, + * *scope_id will be NULL if no scope id was specified. + * @param port The port number. On output, *port will be 0 if no port was + * specified. + * ### FIXME: 0 is a legal port (per RFC 1700). this should + * ### return something besides zero if the port is missing. + * @param str The input string to be parsed. + * @param p The pool from which *addr and *scope_id are allocated. + * @remark If scope id shouldn't be allowed, check for scope_id != NULL in + * addition to checking the return code. If addr/hostname should be + * required, check for addr == NULL in addition to checking the + * return code. + */ +APR_DECLARE(apr_status_t) apr_parse_addr_port(char **addr, + char **scope_id, + apr_port_t *port, + const char *str, + apr_pool_t *p); + +/** + * Get name of the current machine + * @param buf A buffer to store the hostname in. + * @param len The maximum length of the hostname that can be stored in the + * buffer provided. The suggested length is APRMAXHOSTLEN + 1. + * @param cont The pool to use. + * @remark If the buffer was not large enough, an error will be returned. + */ +APR_DECLARE(apr_status_t) apr_gethostname(char *buf, int len, apr_pool_t *cont); + +/** + * Return the data associated with the current socket + * @param data The user data associated with the socket. + * @param key The key to associate with the user data. + * @param sock The currently open socket. + */ +APR_DECLARE(apr_status_t) apr_socket_data_get(void **data, const char *key, + apr_socket_t *sock); + +/** + * Set the data associated with the current socket. + * @param sock The currently open socket. + * @param data The user data to associate with the socket. + * @param key The key to associate with the data. + * @param cleanup The cleanup to call when the socket is destroyed. + */ +APR_DECLARE(apr_status_t) apr_socket_data_set(apr_socket_t *sock, void *data, + const char *key, + apr_status_t (*cleanup)(void*)); + +/** + * Send data over a network. + * @param sock The socket to send the data over. + * @param buf The buffer which contains the data to be sent. + * @param len On entry, the number of bytes to send; on exit, the number + * of bytes sent. + * @remark + *
+ * This functions acts like a blocking write by default.  To change 
+ * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK
+ * socket option.
+ *
+ * It is possible for both bytes to be sent and an error to be returned.
+ *
+ * APR_EINTR is never returned.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_socket_send(apr_socket_t *sock, const char *buf, + apr_size_t *len); + +/** + * Send multiple buffers over a network. + * @param sock The socket to send the data over. + * @param vec The array of iovec structs containing the data to send + * @param nvec The number of iovec structs in the array + * @param len Receives the number of bytes actually written + * @remark + *
+ * This functions acts like a blocking write by default.  To change 
+ * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK
+ * socket option.
+ * The number of bytes actually sent is stored in argument 4.
+ *
+ * It is possible for both bytes to be sent and an error to be returned.
+ *
+ * APR_EINTR is never returned.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_socket_sendv(apr_socket_t *sock, + const struct iovec *vec, + apr_int32_t nvec, apr_size_t *len); + +/** + * @param sock The socket to send from + * @param where The apr_sockaddr_t describing where to send the data + * @param flags The flags to use + * @param buf The data to send + * @param len The length of the data to send + */ +APR_DECLARE(apr_status_t) apr_socket_sendto(apr_socket_t *sock, + apr_sockaddr_t *where, + apr_int32_t flags, const char *buf, + apr_size_t *len); + +/** + * Read data from a socket. On success, the address of the peer from + * which the data was sent is copied into the @a from parameter, and the + * @a len parameter is updated to give the number of bytes written to + * @a buf. + * + * @param from Updated with the address from which the data was received + * @param sock The socket to use + * @param flags The flags to use + * @param buf The buffer to use + * @param len The length of the available buffer + */ + +APR_DECLARE(apr_status_t) apr_socket_recvfrom(apr_sockaddr_t *from, + apr_socket_t *sock, + apr_int32_t flags, char *buf, + apr_size_t *len); + +#if APR_HAS_SENDFILE || defined(DOXYGEN) + +/** + * Send a file from an open file descriptor to a socket, along with + * optional headers and trailers + * @param sock The socket to which we're writing + * @param file The open file from which to read + * @param hdtr A structure containing the headers and trailers to send + * @param offset Offset into the file where we should begin writing + * @param len (input) - Number of bytes to send from the file + * (output) - Number of bytes actually sent, + * including headers, file, and trailers + * @param flags APR flags that are mapped to OS specific flags + * @remark This functions acts like a blocking write by default. To change + * this behavior, use apr_socket_timeout_set() or the + * APR_SO_NONBLOCK socket option. + * The number of bytes actually sent is stored in the len parameter. + * The offset parameter is passed by reference for no reason; its + * value will never be modified by the apr_socket_sendfile() function. + */ +APR_DECLARE(apr_status_t) apr_socket_sendfile(apr_socket_t *sock, + apr_file_t *file, + apr_hdtr_t *hdtr, + apr_off_t *offset, + apr_size_t *len, + apr_int32_t flags); + +#endif /* APR_HAS_SENDFILE */ + +/** + * Read data from a network. + * @param sock The socket to read the data from. + * @param buf The buffer to store the data in. + * @param len On entry, the number of bytes to receive; on exit, the number + * of bytes received. + * @remark + *
+ * This functions acts like a blocking read by default.  To change 
+ * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK
+ * socket option.
+ * The number of bytes actually received is stored in argument 3.
+ *
+ * It is possible for both bytes to be received and an APR_EOF or
+ * other error to be returned.
+ *
+ * APR_EINTR is never returned.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_socket_recv(apr_socket_t *sock, + char *buf, apr_size_t *len); + +/** + * Setup socket options for the specified socket + * @param sock The socket to set up. + * @param opt The option we would like to configure. One of: + *
+ *            APR_SO_DEBUG      --  turn on debugging information 
+ *            APR_SO_KEEPALIVE  --  keep connections active
+ *            APR_SO_LINGER     --  lingers on close if data is present
+ *            APR_SO_NONBLOCK   --  Turns blocking on/off for socket
+ *                                  When this option is enabled, use
+ *                                  the APR_STATUS_IS_EAGAIN() macro to
+ *                                  see if a send or receive function
+ *                                  could not transfer data without
+ *                                  blocking.
+ *            APR_SO_REUSEADDR  --  The rules used in validating addresses
+ *                                  supplied to bind should allow reuse
+ *                                  of local addresses.
+ *            APR_SO_SNDBUF     --  Set the SendBufferSize
+ *            APR_SO_RCVBUF     --  Set the ReceiveBufferSize
+ *            APR_SO_FREEBIND   --  Allow binding to non-local IP address.
+ * 
+ * @param on Value for the option. + */ +APR_DECLARE(apr_status_t) apr_socket_opt_set(apr_socket_t *sock, + apr_int32_t opt, apr_int32_t on); + +/** + * Setup socket timeout for the specified socket + * @param sock The socket to set up. + * @param t Value for the timeout. + *
+ *   t > 0  -- read and write calls return APR_TIMEUP if specified time
+ *             elapsess with no data read or written
+ *   t == 0 -- read and write calls never block
+ *   t < 0  -- read and write calls block
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_socket_timeout_set(apr_socket_t *sock, + apr_interval_time_t t); + +/** + * Query socket options for the specified socket + * @param sock The socket to query + * @param opt The option we would like to query. One of: + *
+ *            APR_SO_DEBUG      --  turn on debugging information 
+ *            APR_SO_KEEPALIVE  --  keep connections active
+ *            APR_SO_LINGER     --  lingers on close if data is present
+ *            APR_SO_NONBLOCK   --  Turns blocking on/off for socket
+ *            APR_SO_REUSEADDR  --  The rules used in validating addresses
+ *                                  supplied to bind should allow reuse
+ *                                  of local addresses.
+ *            APR_SO_SNDBUF     --  Set the SendBufferSize
+ *            APR_SO_RCVBUF     --  Set the ReceiveBufferSize
+ *            APR_SO_DISCONNECTED -- Query the disconnected state of the socket.
+ *                                  (Currently only used on Windows)
+ * 
+ * @param on Socket option returned on the call. + */ +APR_DECLARE(apr_status_t) apr_socket_opt_get(apr_socket_t *sock, + apr_int32_t opt, apr_int32_t *on); + +/** + * Query socket timeout for the specified socket + * @param sock The socket to query + * @param t Socket timeout returned from the query. + */ +APR_DECLARE(apr_status_t) apr_socket_timeout_get(apr_socket_t *sock, + apr_interval_time_t *t); + +/** + * Query the specified socket if at the OOB/Urgent data mark + * @param sock The socket to query + * @param atmark Is set to true if socket is at the OOB/urgent mark, + * otherwise is set to false. + */ +APR_DECLARE(apr_status_t) apr_socket_atmark(apr_socket_t *sock, + int *atmark); + +/** + * Return an address associated with a socket; either the address to + * which the socket is bound locally or the address of the peer + * to which the socket is connected. + * @param sa The returned apr_sockaddr_t. + * @param which Whether to retrieve the local or remote address + * @param sock The socket to use + */ +APR_DECLARE(apr_status_t) apr_socket_addr_get(apr_sockaddr_t **sa, + apr_interface_e which, + apr_socket_t *sock); + +/** + * Return the IP address (in numeric address string format) in + * an APR socket address. APR will allocate storage for the IP address + * string from the pool of the apr_sockaddr_t. + * @param addr The IP address. + * @param sockaddr The socket address to reference. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_ip_get(char **addr, + apr_sockaddr_t *sockaddr); + +/** + * Write the IP address (in numeric address string format) of the APR + * socket address @a sockaddr into the buffer @a buf (of size @a buflen). + * @param sockaddr The socket address to reference. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_ip_getbuf(char *buf, apr_size_t buflen, + apr_sockaddr_t *sockaddr); + +/** + * See if the IP addresses in two APR socket addresses are + * equivalent. Appropriate logic is present for comparing + * IPv4-mapped IPv6 addresses with IPv4 addresses. + * + * @param addr1 One of the APR socket addresses. + * @param addr2 The other APR socket address. + * @remark The return value will be non-zero if the addresses + * are equivalent. + */ +APR_DECLARE(int) apr_sockaddr_equal(const apr_sockaddr_t *addr1, + const apr_sockaddr_t *addr2); + +/** + * See if the IP address in an APR socket address refers to the wildcard + * address for the protocol family (e.g., INADDR_ANY for IPv4). + * + * @param addr The APR socket address to examine. + * @remark The return value will be non-zero if the address is + * initialized and is the wildcard address. + */ +APR_DECLARE(int) apr_sockaddr_is_wildcard(const apr_sockaddr_t *addr); + +/** +* Return the type of the socket. +* @param sock The socket to query. +* @param type The returned type (e.g., SOCK_STREAM). +*/ +APR_DECLARE(apr_status_t) apr_socket_type_get(apr_socket_t *sock, + int *type); + +/** + * Given an apr_sockaddr_t and a service name, set the port for the service + * @param sockaddr The apr_sockaddr_t that will have its port set + * @param servname The name of the service you wish to use + */ +APR_DECLARE(apr_status_t) apr_getservbyname(apr_sockaddr_t *sockaddr, + const char *servname); +/** + * Build an ip-subnet representation from an IP address and optional netmask or + * number-of-bits. + * @param ipsub The new ip-subnet representation + * @param ipstr The input IP address string + * @param mask_or_numbits The input netmask or number-of-bits string, or NULL + * @param p The pool to allocate from + */ +APR_DECLARE(apr_status_t) apr_ipsubnet_create(apr_ipsubnet_t **ipsub, + const char *ipstr, + const char *mask_or_numbits, + apr_pool_t *p); + +/** + * Test the IP address in an apr_sockaddr_t against a pre-built ip-subnet + * representation. + * @param ipsub The ip-subnet representation + * @param sa The socket address to test + * @return non-zero if the socket address is within the subnet, 0 otherwise + */ +APR_DECLARE(int) apr_ipsubnet_test(apr_ipsubnet_t *ipsub, apr_sockaddr_t *sa); + +#if APR_HAS_SO_ACCEPTFILTER || defined(DOXYGEN) +/** + * Set an OS level accept filter. + * @param sock The socket to put the accept filter on. + * @param name The accept filter + * @param args Any extra args to the accept filter. Passing NULL here removes + * the accept filter. + * @bug name and args should have been declared as const char *, as they are in + * APR 2.0 + */ +apr_status_t apr_socket_accept_filter(apr_socket_t *sock, char *name, + char *args); +#endif + +/** + * Return the protocol of the socket. + * @param sock The socket to query. + * @param protocol The returned protocol (e.g., APR_PROTO_TCP). + */ +APR_DECLARE(apr_status_t) apr_socket_protocol_get(apr_socket_t *sock, + int *protocol); + +/** + * Get the pool used by the socket. + */ +APR_POOL_DECLARE_ACCESSOR(socket); + +/** + * Set a socket to be inherited by child processes. + */ +APR_DECLARE_INHERIT_SET(socket); + +/** + * Unset a socket from being inherited by child processes. + */ +APR_DECLARE_INHERIT_UNSET(socket); + +/** + * Set socket permissions. + */ +APR_PERMS_SET_IMPLEMENT(socket); + +/** + * @defgroup apr_mcast IP Multicast + * @{ + */ + +/** + * Join a Multicast Group + * @param sock The socket to join a multicast group + * @param join The address of the multicast group to join + * @param iface Address of the interface to use. If NULL is passed, the + * default multicast interface will be used. (OS Dependent) + * @param source Source Address to accept transmissions from (non-NULL + * implies Source-Specific Multicast) + */ +APR_DECLARE(apr_status_t) apr_mcast_join(apr_socket_t *sock, + apr_sockaddr_t *join, + apr_sockaddr_t *iface, + apr_sockaddr_t *source); + +/** + * Leave a Multicast Group. All arguments must be the same as + * apr_mcast_join. + * @param sock The socket to leave a multicast group + * @param addr The address of the multicast group to leave + * @param iface Address of the interface to use. If NULL is passed, the + * default multicast interface will be used. (OS Dependent) + * @param source Source Address to accept transmissions from (non-NULL + * implies Source-Specific Multicast) + */ +APR_DECLARE(apr_status_t) apr_mcast_leave(apr_socket_t *sock, + apr_sockaddr_t *addr, + apr_sockaddr_t *iface, + apr_sockaddr_t *source); + +/** + * Set the Multicast Time to Live (ttl) for a multicast transmission. + * @param sock The socket to set the multicast ttl + * @param ttl Time to live to Assign. 0-255, default=1 + * @remark If the TTL is 0, packets will only be seen by sockets on + * the local machine, and only when multicast loopback is enabled. + */ +APR_DECLARE(apr_status_t) apr_mcast_hops(apr_socket_t *sock, + apr_byte_t ttl); + +/** + * Toggle IP Multicast Loopback + * @param sock The socket to set multicast loopback + * @param opt 0=disable, 1=enable + */ +APR_DECLARE(apr_status_t) apr_mcast_loopback(apr_socket_t *sock, + apr_byte_t opt); + + +/** + * Set the Interface to be used for outgoing Multicast Transmissions. + * @param sock The socket to set the multicast interface on + * @param iface Address of the interface to use for Multicast + */ +APR_DECLARE(apr_status_t) apr_mcast_interface(apr_socket_t *sock, + apr_sockaddr_t *iface); + +/** @} */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_NETWORK_IO_H */ + diff --git a/c/dependencies/linux/apr/include/apr_optional.h b/c/dependencies/linux/apr/include/apr_optional.h new file mode 100644 index 00000000..3301d66e --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_optional.h @@ -0,0 +1,92 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_OPTIONAL_H +#define APR_OPTIONAL_H + +#include "apu.h" +/** + * @file apr_optional.h + * @brief APR-UTIL registration of functions exported by modules + */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Opt Optional Functions + * @ingroup APR_Util + * + * Typesafe registration and retrieval of functions that may not be present + * (i.e. functions exported by optional modules) + * @{ + */ + +/** + * The type of an optional function. + * @param name The name of the function + */ +#define APR_OPTIONAL_FN_TYPE(name) apr_OFN_##name##_t + +/** + * Declare an optional function. + * @param ret The return type of the function + * @param name The name of the function + * @param args The function arguments (including brackets) + */ +#define APR_DECLARE_OPTIONAL_FN(ret,name,args) \ +typedef ret (APR_OPTIONAL_FN_TYPE(name)) args + +/** + * XXX: This doesn't belong here, then! + * Private function! DO NOT USE! + * @internal + */ + +typedef void (apr_opt_fn_t)(void); +/** @internal */ +APU_DECLARE_NONSTD(void) apr_dynamic_fn_register(const char *szName, + apr_opt_fn_t *pfn); + +/** + * Register an optional function. This can be later retrieved, type-safely, by + * name. Like all global functions, the name must be unique. Note that, + * confusingly but correctly, the function itself can be static! + * @param name The name of the function + */ +#define APR_REGISTER_OPTIONAL_FN(name) do { \ + APR_OPTIONAL_FN_TYPE(name) *apu__opt = name; \ + apr_dynamic_fn_register(#name,(apr_opt_fn_t *)apu__opt); \ +} while (0) + +/** @internal + * Private function! DO NOT USE! + */ +APU_DECLARE(apr_opt_fn_t *) apr_dynamic_fn_retrieve(const char *szName); + +/** + * Retrieve an optional function. Returns NULL if the function is not present. + * @param name The name of the function + */ +#define APR_RETRIEVE_OPTIONAL_FN(name) \ + (APR_OPTIONAL_FN_TYPE(name) *)apr_dynamic_fn_retrieve(#name) + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_OPTIONAL_H */ diff --git a/c/dependencies/linux/apr/include/apr_optional_hooks.h b/c/dependencies/linux/apr/include/apr_optional_hooks.h new file mode 100644 index 00000000..8265f03f --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_optional_hooks.h @@ -0,0 +1,117 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file apr_optional_hooks.h + * @brief Apache optional hook functions + */ + + +#ifndef APR_OPTIONAL_HOOK_H +#define APR_OPTIONAL_HOOK_H + +#include "apr_tables.h" + +#ifdef __cplusplus +extern "C" { +#endif +/** + * @defgroup APR_Util_OPT_HOOK Optional Hook Functions + * @ingroup APR_Util_Hook + * @{ + */ +/** + * Function to implement the APR_OPTIONAL_HOOK Macro + * @internal + * @see APR_OPTIONAL_HOOK + * + * @param szName The name of the hook + * @param pfn A pointer to a function that will be called + * @param aszPre a NULL-terminated array of strings that name modules whose hooks should precede this one + * @param aszSucc a NULL-terminated array of strings that name modules whose hooks should succeed this one + * @param nOrder an integer determining order before honouring aszPre and aszSucc (for example HOOK_MIDDLE) + */ + + +APU_DECLARE(void) apr_optional_hook_add(const char *szName,void (*pfn)(void), + const char * const *aszPre, + const char * const *aszSucc, + int nOrder); + +/** + * Hook to an optional hook. + * + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param pfn A pointer to a function that will be called + * @param aszPre a NULL-terminated array of strings that name modules whose hooks should precede this one + * @param aszSucc a NULL-terminated array of strings that name modules whose hooks should succeed this one + * @param nOrder an integer determining order before honouring aszPre and aszSucc (for example HOOK_MIDDLE) + */ + +#define APR_OPTIONAL_HOOK(ns,name,pfn,aszPre,aszSucc,nOrder) do { \ + ns##_HOOK_##name##_t *apu__hook = pfn; \ + apr_optional_hook_add(#name,(void (*)(void))apu__hook,aszPre, aszSucc, nOrder); \ +} while (0) + +/** + * @internal + * @param szName - the name of the function + * @return the hook structure for a given hook + */ +APU_DECLARE(apr_array_header_t *) apr_optional_hook_get(const char *szName); + +/** + * Implement an optional hook that runs until one of the functions + * returns something other than OK or DECLINE. + * + * @param ns The namespace prefix of the hook functions + * @param link The linkage declaration prefix of the hook + * @param ret The type of the return value of the hook + * @param ret The type of the return value of the hook + * @param name The name of the hook + * @param args_decl The declaration of the arguments for the hook + * @param args_use The names for the arguments for the hook + * @param ok Success value + * @param decline Decline value + */ +#define APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(ns,link,ret,name,args_decl,args_use,ok,decline) \ +link##_DECLARE(ret) ns##_run_##name args_decl \ + { \ + ns##_LINK_##name##_t *pHook; \ + int n; \ + ret rv; \ + apr_array_header_t *pHookArray=apr_optional_hook_get(#name); \ +\ + if(!pHookArray) \ + return ok; \ +\ + pHook=(ns##_LINK_##name##_t *)pHookArray->elts; \ + for(n=0 ; n < pHookArray->nelts ; ++n) \ + { \ + rv=(pHook[n].pFunc)args_use; \ +\ + if(rv != ok && rv != decline) \ + return rv; \ + } \ + return ok; \ + } + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_OPTIONAL_HOOK_H */ diff --git a/c/dependencies/linux/apr/include/apr_perms_set.h b/c/dependencies/linux/apr/include/apr_perms_set.h new file mode 100644 index 00000000..92a1362b --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_perms_set.h @@ -0,0 +1,65 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_PERMS_SET_H +#define APR_PERMS_SET_H + +/** + * @file apr_perms_set.h + * @brief APR Process Locking Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_user.h" +#include "apr_file_info.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_perms_set Object permission set functions + * @ingroup APR + * @{ + */ + +/** Permission set callback function. */ +typedef apr_status_t (apr_perms_setfn_t)(void *object, apr_fileperms_t perms, + apr_uid_t uid, apr_gid_t gid); + +#define APR_PERMS_SET_IMPLEMENT(type) \ + APR_DECLARE(apr_status_t) apr_##type##_perms_set \ + (void *the##type, apr_fileperms_t perms, \ + apr_uid_t uid, apr_gid_t gid) + +#define APR_PERMS_SET_ENOTIMPL(type) \ + APR_DECLARE(apr_status_t) apr_##type##_perms_set \ + (void *the##type, apr_fileperms_t perms, \ + apr_uid_t uid, apr_gid_t gid) \ + { return APR_ENOTIMPL ; } + +#define APR_PERMS_SET_FN(type) apr_##type##_perms_set + + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_PERMS_SET */ diff --git a/c/dependencies/linux/apr/include/apr_poll.h b/c/dependencies/linux/apr/include/apr_poll.h new file mode 100644 index 00000000..482d6ee1 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_poll.h @@ -0,0 +1,446 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_POLL_H +#define APR_POLL_H +/** + * @file apr_poll.h + * @brief APR Poll interface + */ +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_inherit.h" +#include "apr_file_io.h" +#include "apr_network_io.h" + +#if APR_HAVE_NETINET_IN_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_poll Poll Routines + * @ingroup APR + * @{ + */ + +/** + * @defgroup pollopts Poll options + * @ingroup apr_poll + * @{ + */ +#define APR_POLLIN 0x001 /**< Can read without blocking */ +#define APR_POLLPRI 0x002 /**< Priority data available */ +#define APR_POLLOUT 0x004 /**< Can write without blocking */ +#define APR_POLLERR 0x010 /**< Pending error */ +#define APR_POLLHUP 0x020 /**< Hangup occurred */ +#define APR_POLLNVAL 0x040 /**< Descriptor invalid */ +/** @} */ + +/** + * @defgroup pollflags Pollset Flags + * @ingroup apr_poll + * @{ + */ +#define APR_POLLSET_THREADSAFE 0x001 /**< Adding or removing a descriptor is + * thread-safe + */ +#define APR_POLLSET_NOCOPY 0x002 /**< Descriptors passed to apr_pollset_add() + * are not copied + */ +#define APR_POLLSET_WAKEABLE 0x004 /**< Poll operations are interruptable by + * apr_pollset_wakeup() or apr_pollcb_wakeup() + */ +#define APR_POLLSET_NODEFAULT 0x010 /**< Do not try to use the default method if + * the specified non-default method cannot be + * used + */ +/** @} */ + +/** + * Pollset Methods + */ +typedef enum { + APR_POLLSET_DEFAULT, /**< Platform default poll method */ + APR_POLLSET_SELECT, /**< Poll uses select method */ + APR_POLLSET_KQUEUE, /**< Poll uses kqueue method */ + APR_POLLSET_PORT, /**< Poll uses Solaris event port method */ + APR_POLLSET_EPOLL, /**< Poll uses epoll method */ + APR_POLLSET_POLL, /**< Poll uses poll method */ + APR_POLLSET_AIO_MSGQ /**< Poll uses z/OS asio method */ +} apr_pollset_method_e; + +/** Used in apr_pollfd_t to determine what the apr_descriptor is */ +typedef enum { + APR_NO_DESC, /**< nothing here */ + APR_POLL_SOCKET, /**< descriptor refers to a socket */ + APR_POLL_FILE, /**< descriptor refers to a file */ + APR_POLL_LASTDESC /**< @deprecated descriptor is the last one in the list */ +} apr_datatype_e ; + +/** Union of either an APR file or socket. */ +typedef union { + apr_file_t *f; /**< file */ + apr_socket_t *s; /**< socket */ +} apr_descriptor; + +/** @see apr_pollfd_t */ +typedef struct apr_pollfd_t apr_pollfd_t; + +/** Poll descriptor set. */ +struct apr_pollfd_t { + apr_pool_t *p; /**< associated pool */ + apr_datatype_e desc_type; /**< descriptor type */ + apr_int16_t reqevents; /**< requested events */ + apr_int16_t rtnevents; /**< returned events */ + apr_descriptor desc; /**< @see apr_descriptor */ + void *client_data; /**< allows app to associate context */ +}; + + +/* General-purpose poll API for arbitrarily large numbers of + * file descriptors + */ + +/** Opaque structure used for pollset API */ +typedef struct apr_pollset_t apr_pollset_t; + +/** + * Set up a pollset object + * @param pollset The pointer in which to return the newly created object + * @param size The maximum number of descriptors that this pollset can hold + * @param p The pool from which to allocate the pollset + * @param flags Optional flags to modify the operation of the pollset. + * + * @remark If flags contains APR_POLLSET_THREADSAFE, then a pollset is + * created on which it is safe to make concurrent calls to + * apr_pollset_add(), apr_pollset_remove() and apr_pollset_poll() + * from separate threads. This feature is only supported on some + * platforms; the apr_pollset_create() call will fail with + * APR_ENOTIMPL on platforms where it is not supported. + * @remark If flags contains APR_POLLSET_WAKEABLE, then a pollset is + * created with an additional internal pipe object used for the + * apr_pollset_wakeup() call. The actual size of pollset is + * in that case @a size + 1. This feature is only supported on some + * platforms; the apr_pollset_create() call will fail with + * APR_ENOTIMPL on platforms where it is not supported. + * @remark If flags contains APR_POLLSET_NOCOPY, then the apr_pollfd_t + * structures passed to apr_pollset_add() are not copied and + * must have a lifetime at least as long as the pollset. + * @remark Some poll methods (including APR_POLLSET_KQUEUE, + * APR_POLLSET_PORT, and APR_POLLSET_EPOLL) do not have a + * fixed limit on the size of the pollset. For these methods, + * the size parameter controls the maximum number of + * descriptors that will be returned by a single call to + * apr_pollset_poll(). + */ +APR_DECLARE(apr_status_t) apr_pollset_create(apr_pollset_t **pollset, + apr_uint32_t size, + apr_pool_t *p, + apr_uint32_t flags); + +/** + * Set up a pollset object + * @param pollset The pointer in which to return the newly created object + * @param size The maximum number of descriptors that this pollset can hold + * @param p The pool from which to allocate the pollset + * @param flags Optional flags to modify the operation of the pollset. + * @param method Poll method to use. See #apr_pollset_method_e. If this + * method cannot be used, the default method will be used unless the + * APR_POLLSET_NODEFAULT flag has been specified. + * + * @remark If flags contains APR_POLLSET_THREADSAFE, then a pollset is + * created on which it is safe to make concurrent calls to + * apr_pollset_add(), apr_pollset_remove() and apr_pollset_poll() + * from separate threads. This feature is only supported on some + * platforms; the apr_pollset_create_ex() call will fail with + * APR_ENOTIMPL on platforms where it is not supported. + * @remark If flags contains APR_POLLSET_WAKEABLE, then a pollset is + * created with additional internal pipe object used for the + * apr_pollset_wakeup() call. The actual size of pollset is + * in that case size + 1. This feature is only supported on some + * platforms; the apr_pollset_create_ex() call will fail with + * APR_ENOTIMPL on platforms where it is not supported. + * @remark If flags contains APR_POLLSET_NOCOPY, then the apr_pollfd_t + * structures passed to apr_pollset_add() are not copied and + * must have a lifetime at least as long as the pollset. + * @remark Some poll methods (including APR_POLLSET_KQUEUE, + * APR_POLLSET_PORT, and APR_POLLSET_EPOLL) do not have a + * fixed limit on the size of the pollset. For these methods, + * the size parameter controls the maximum number of + * descriptors that will be returned by a single call to + * apr_pollset_poll(). + */ +APR_DECLARE(apr_status_t) apr_pollset_create_ex(apr_pollset_t **pollset, + apr_uint32_t size, + apr_pool_t *p, + apr_uint32_t flags, + apr_pollset_method_e method); + +/** + * Destroy a pollset object + * @param pollset The pollset to destroy + */ +APR_DECLARE(apr_status_t) apr_pollset_destroy(apr_pollset_t *pollset); + +/** + * Add a socket or file descriptor to a pollset + * @param pollset The pollset to which to add the descriptor + * @param descriptor The descriptor to add + * @remark If you set client_data in the descriptor, that value + * will be returned in the client_data field whenever this + * descriptor is signalled in apr_pollset_poll(). + * @remark If the pollset has been created with APR_POLLSET_THREADSAFE + * and thread T1 is blocked in a call to apr_pollset_poll() for + * this same pollset that is being modified via apr_pollset_add() + * in thread T2, the currently executing apr_pollset_poll() call in + * T1 will either: (1) automatically include the newly added descriptor + * in the set of descriptors it is watching or (2) return immediately + * with APR_EINTR. Option (1) is recommended, but option (2) is + * allowed for implementations where option (1) is impossible + * or impractical. + * @remark If the pollset has been created with APR_POLLSET_NOCOPY, the + * apr_pollfd_t structure referenced by descriptor will not be copied + * and must have a lifetime at least as long as the pollset. + * @remark Do not add the same socket or file descriptor to the same pollset + * multiple times, even if the requested events differ for the + * different calls to apr_pollset_add(). If the events of interest + * for a descriptor change, you must first remove the descriptor + * from the pollset with apr_pollset_remove(), then add it again + * specifying all requested events. + */ +APR_DECLARE(apr_status_t) apr_pollset_add(apr_pollset_t *pollset, + const apr_pollfd_t *descriptor); + +/** + * Remove a descriptor from a pollset + * @param pollset The pollset from which to remove the descriptor + * @param descriptor The descriptor to remove + * @remark If the descriptor is not found, APR_NOTFOUND is returned. + * @remark If the pollset has been created with APR_POLLSET_THREADSAFE + * and thread T1 is blocked in a call to apr_pollset_poll() for + * this same pollset that is being modified via apr_pollset_remove() + * in thread T2, the currently executing apr_pollset_poll() call in + * T1 will either: (1) automatically exclude the newly added descriptor + * in the set of descriptors it is watching or (2) return immediately + * with APR_EINTR. Option (1) is recommended, but option (2) is + * allowed for implementations where option (1) is impossible + * or impractical. + * @remark apr_pollset_remove() cannot be used to remove a subset of requested + * events for a descriptor. The reqevents field in the apr_pollfd_t + * parameter must contain the same value when removing as when adding. + */ +APR_DECLARE(apr_status_t) apr_pollset_remove(apr_pollset_t *pollset, + const apr_pollfd_t *descriptor); + +/** + * Block for activity on the descriptor(s) in a pollset + * @param pollset The pollset to use + * @param timeout The amount of time in microseconds to wait. This is a + * maximum, not a minimum. If a descriptor is signalled, the + * function will return before this time. If timeout is + * negative, the function will block until a descriptor is + * signalled or until apr_pollset_wakeup() has been called. + * @param num Number of signalled descriptors (output parameter) + * @param descriptors Array of signalled descriptors (output parameter) + * @remark APR_EINTR will be returned if the pollset has been created with + * APR_POLLSET_WAKEABLE, apr_pollset_wakeup() has been called while + * waiting for activity, and there were no signalled descriptors at the + * time of the wakeup call. + * @remark Multiple signalled conditions for the same descriptor may be reported + * in one or more returned apr_pollfd_t structures, depending on the + * implementation. + */ +APR_DECLARE(apr_status_t) apr_pollset_poll(apr_pollset_t *pollset, + apr_interval_time_t timeout, + apr_int32_t *num, + const apr_pollfd_t **descriptors); + +/** + * Interrupt the blocked apr_pollset_poll() call. + * @param pollset The pollset to use + * @remark If the pollset was not created with APR_POLLSET_WAKEABLE the + * return value is APR_EINIT. + */ +APR_DECLARE(apr_status_t) apr_pollset_wakeup(apr_pollset_t *pollset); + +/** + * Poll the descriptors in the poll structure + * @param aprset The poll structure we will be using. + * @param numsock The number of descriptors we are polling + * @param nsds The number of descriptors signalled (output parameter) + * @param timeout The amount of time in microseconds to wait. This is a + * maximum, not a minimum. If a descriptor is signalled, the + * function will return before this time. If timeout is + * negative, the function will block until a descriptor is + * signalled or until apr_pollset_wakeup() has been called. + * @remark The number of descriptors signalled is returned in the third argument. + * This is a blocking call, and it will not return until either a + * descriptor has been signalled or the timeout has expired. + * @remark The rtnevents field in the apr_pollfd_t array will only be filled- + * in if the return value is APR_SUCCESS. + */ +APR_DECLARE(apr_status_t) apr_poll(apr_pollfd_t *aprset, apr_int32_t numsock, + apr_int32_t *nsds, + apr_interval_time_t timeout); + +/** + * Return a printable representation of the pollset method. + * @param pollset The pollset to use + */ +APR_DECLARE(const char *) apr_pollset_method_name(apr_pollset_t *pollset); + +/** + * Return a printable representation of the default pollset method + * (APR_POLLSET_DEFAULT). + */ +APR_DECLARE(const char *) apr_poll_method_defname(void); + +/** Opaque structure used for pollcb API */ +typedef struct apr_pollcb_t apr_pollcb_t; + +/** + * Set up a pollcb object + * @param pollcb The pointer in which to return the newly created object + * @param size The maximum number of descriptors that a single _poll can return. + * @param p The pool from which to allocate the pollcb + * @param flags Optional flags to modify the operation of the pollcb. + * + * @remark If flags contains APR_POLLSET_WAKEABLE, then a pollcb is + * created with an additional internal pipe object used for the + * apr_pollcb_wakeup() call. The actual size of pollcb is + * in that case @a size + 1. + * @remark Pollcb is only supported on some platforms; the apr_pollcb_create() + * call will fail with APR_ENOTIMPL on platforms where it is not supported. + */ +APR_DECLARE(apr_status_t) apr_pollcb_create(apr_pollcb_t **pollcb, + apr_uint32_t size, + apr_pool_t *p, + apr_uint32_t flags); + +/** + * Set up a pollcb object + * @param pollcb The pointer in which to return the newly created object + * @param size The maximum number of descriptors that a single _poll can return. + * @param p The pool from which to allocate the pollcb + * @param flags Optional flags to modify the operation of the pollcb. + * @param method Poll method to use. See #apr_pollset_method_e. If this + * method cannot be used, the default method will be used unless the + * APR_POLLSET_NODEFAULT flag has been specified. + * + * @remark If flags contains APR_POLLSET_WAKEABLE, then a pollcb is + * created with an additional internal pipe object used for the + * apr_pollcb_wakeup() call. The actual size of pollcb is + * in that case @a size + 1. + * @remark Pollcb is only supported on some platforms; the apr_pollcb_create_ex() + * call will fail with APR_ENOTIMPL on platforms where it is not supported. + */ +APR_DECLARE(apr_status_t) apr_pollcb_create_ex(apr_pollcb_t **pollcb, + apr_uint32_t size, + apr_pool_t *p, + apr_uint32_t flags, + apr_pollset_method_e method); + +/** + * Add a socket or file descriptor to a pollcb + * @param pollcb The pollcb to which to add the descriptor + * @param descriptor The descriptor to add + * @remark If you set client_data in the descriptor, that value will be + * returned in the client_data field whenever this descriptor is + * signalled in apr_pollcb_poll(). + * @remark Unlike the apr_pollset API, the descriptor is not copied, and users + * must retain the memory used by descriptor, as the same pointer will + * be returned to them from apr_pollcb_poll. + * @remark Do not add the same socket or file descriptor to the same pollcb + * multiple times, even if the requested events differ for the + * different calls to apr_pollcb_add(). If the events of interest + * for a descriptor change, you must first remove the descriptor + * from the pollcb with apr_pollcb_remove(), then add it again + * specifying all requested events. + */ +APR_DECLARE(apr_status_t) apr_pollcb_add(apr_pollcb_t *pollcb, + apr_pollfd_t *descriptor); +/** + * Remove a descriptor from a pollcb + * @param pollcb The pollcb from which to remove the descriptor + * @param descriptor The descriptor to remove + * @remark If the descriptor is not found, APR_NOTFOUND is returned. + * @remark apr_pollcb_remove() cannot be used to remove a subset of requested + * events for a descriptor. The reqevents field in the apr_pollfd_t + * parameter must contain the same value when removing as when adding. + */ +APR_DECLARE(apr_status_t) apr_pollcb_remove(apr_pollcb_t *pollcb, + apr_pollfd_t *descriptor); + +/** + * Function prototype for pollcb handlers + * @param baton Opaque baton passed into apr_pollcb_poll() + * @param descriptor Contains the notification for an active descriptor. + * The @a rtnevents member describes which events were triggered + * for this descriptor. + * @remark If the pollcb handler does not return APR_SUCCESS, the apr_pollcb_poll() + * call returns with the handler's return value. + */ +typedef apr_status_t (*apr_pollcb_cb_t)(void *baton, apr_pollfd_t *descriptor); + +/** + * Block for activity on the descriptor(s) in a pollcb + * @param pollcb The pollcb to use + * @param timeout The amount of time in microseconds to wait. This is a + * maximum, not a minimum. If a descriptor is signalled, the + * function will return before this time. If timeout is + * negative, the function will block until a descriptor is + * signalled or until apr_pollcb_wakeup() has been called. + * @param func Callback function to call for each active descriptor. + * @param baton Opaque baton passed to the callback function. + * @remark Multiple signalled conditions for the same descriptor may be reported + * in one or more calls to the callback function, depending on the + * implementation. + * @remark APR_EINTR will be returned if the pollset has been created with + * APR_POLLSET_WAKEABLE and apr_pollcb_wakeup() has been called while + * waiting for activity. + */ +APR_DECLARE(apr_status_t) apr_pollcb_poll(apr_pollcb_t *pollcb, + apr_interval_time_t timeout, + apr_pollcb_cb_t func, + void *baton); + +/** + * Interrupt the blocked apr_pollcb_poll() call. + * @param pollcb The pollcb to use + * @remark If the pollcb was not created with APR_POLLSET_WAKEABLE the + * return value is APR_EINIT. + */ +APR_DECLARE(apr_status_t) apr_pollcb_wakeup(apr_pollcb_t *pollcb); + +/** + * Return a printable representation of the pollcb method. + * @param pollcb The pollcb to use + */ +APR_DECLARE(const char *) apr_pollcb_method_name(apr_pollcb_t *pollcb); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_POLL_H */ + diff --git a/c/dependencies/linux/apr/include/apr_pools.h b/c/dependencies/linux/apr/include/apr_pools.h new file mode 100644 index 00000000..783c9c42 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_pools.h @@ -0,0 +1,815 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_POOLS_H +#define APR_POOLS_H + +/** + * @file apr_pools.h + * @brief APR memory allocation + * + * Resource allocation routines... + * + * designed so that we don't have to keep track of EVERYTHING so that + * it can be explicitly freed later (a fundamentally unsound strategy --- + * particularly in the presence of die()). + * + * Instead, we maintain pools, and allocate items (both memory and I/O + * handlers) from the pools --- currently there are two, one for + * per-transaction info, and one for config info. When a transaction is + * over, we can delete everything in the per-transaction apr_pool_t without + * fear, and without thinking too hard about it either. + * + * Note that most operations on pools are not thread-safe: a single pool + * should only be accessed by a single thread at any given time. The one + * exception to this rule is creating a subpool of a given pool: one or more + * threads can safely create subpools at the same time that another thread + * accesses the parent pool. + */ + +#include "apr.h" +#include "apr_errno.h" +#include "apr_general.h" /* for APR_STRINGIFY */ +#define APR_WANT_MEMFUNC /**< for no good reason? */ +#include "apr_want.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_pools Memory Pool Functions + * @ingroup APR + * @{ + */ + +/** The fundamental pool type */ +typedef struct apr_pool_t apr_pool_t; + + +/** + * Declaration helper macro to construct apr_foo_pool_get()s. + * + * This standardized macro is used by opaque (APR) data types to return + * the apr_pool_t that is associated with the data type. + * + * APR_POOL_DECLARE_ACCESSOR() is used in a header file to declare the + * accessor function. A typical usage and result would be: + *
+ *    APR_POOL_DECLARE_ACCESSOR(file);
+ * becomes:
+ *    APR_DECLARE(apr_pool_t *) apr_file_pool_get(const apr_file_t *thefile);
+ * 
+ * @remark Doxygen unwraps this macro (via doxygen.conf) to provide + * actual help for each specific occurrence of apr_foo_pool_get. + * @remark the linkage is specified for APR. It would be possible to expand + * the macros to support other linkages. + */ +#define APR_POOL_DECLARE_ACCESSOR(type) \ + APR_DECLARE(apr_pool_t *) apr_##type##_pool_get \ + (const apr_##type##_t *the##type) + +/** + * Implementation helper macro to provide apr_foo_pool_get()s. + * + * In the implementation, the APR_POOL_IMPLEMENT_ACCESSOR() is used to + * actually define the function. It assumes the field is named "pool". + */ +#define APR_POOL_IMPLEMENT_ACCESSOR(type) \ + APR_DECLARE(apr_pool_t *) apr_##type##_pool_get \ + (const apr_##type##_t *the##type) \ + { return the##type->pool; } + + +/** + * Pool debug levels + * + *
+ * | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
+ * ---------------------------------
+ * |   |   |   |   |   |   |   | x |  General debug code enabled (useful in
+ *                                    combination with --with-efence).
+ *
+ * |   |   |   |   |   |   | x |   |  Verbose output on stderr (report
+ *                                    CREATE, CLEAR, DESTROY).
+ *
+ * |   |   |   | x |   |   |   |   |  Verbose output on stderr (report
+ *                                    PALLOC, PCALLOC).
+ *
+ * |   |   |   |   |   | x |   |   |  Lifetime checking. On each use of a
+ *                                    pool, check its lifetime.  If the pool
+ *                                    is out of scope, abort().
+ *                                    In combination with the verbose flag
+ *                                    above, it will output LIFE in such an
+ *                                    event prior to aborting.
+ *
+ * |   |   |   |   | x |   |   |   |  Pool owner checking.  On each use of a
+ *                                    pool, check if the current thread is the
+ *                                    pool's owner.  If not, abort().  In
+ *                                    combination with the verbose flag above,
+ *                                    it will output OWNER in such an event
+ *                                    prior to aborting.  Use the debug
+ *                                    function apr_pool_owner_set() to switch
+ *                                    a pool's ownership.
+ *
+ * When no debug level was specified, assume general debug mode.
+ * If level 0 was specified, debugging is switched off.
+ * 
+ */ +#if defined(APR_POOL_DEBUG) +/* If APR_POOL_DEBUG is blank, we get 1; if it is a number, we get -1. */ +#if (APR_POOL_DEBUG - APR_POOL_DEBUG -1 == 1) +#undef APR_POOL_DEBUG +#define APR_POOL_DEBUG 1 +#endif +#else +#define APR_POOL_DEBUG 0 +#endif + +/** the place in the code where the particular function was called */ +#define APR_POOL__FILE_LINE__ __FILE__ ":" APR_STRINGIFY(__LINE__) + + + +/** A function that is called when allocation fails. */ +typedef int (*apr_abortfunc_t)(int retcode); + +/* + * APR memory structure manipulators (pools, tables, and arrays). + */ + +/* + * Initialization + */ + +/** + * Setup all of the internal structures required to use pools + * @remark Programs do NOT need to call this directly. APR will call this + * automatically from apr_initialize. + * @internal + */ +APR_DECLARE(apr_status_t) apr_pool_initialize(void); + +/** + * Tear down all of the internal structures required to use pools + * @remark Programs do NOT need to call this directly. APR will call this + * automatically from apr_terminate. + * @internal + */ +APR_DECLARE(void) apr_pool_terminate(void); + + +/* + * Pool creation/destruction + */ + +#include "apr_allocator.h" + +/** + * Create a new pool. + * @param newpool The pool we have just created. + * @param parent The parent pool. If this is NULL, the new pool is a root + * pool. If it is non-NULL, the new pool will inherit all + * of its parent pool's attributes, except the apr_pool_t will + * be a sub-pool. + * @param abort_fn A function to use if the pool cannot allocate more memory. + * @param allocator The allocator to use with the new pool. If NULL the + * allocator of the parent pool will be used. + * @remark This function is thread-safe, in the sense that multiple threads + * can safely create subpools of the same parent pool concurrently. + * Similarly, a subpool can be created by one thread at the same + * time that another thread accesses the parent pool. + */ +APR_DECLARE(apr_status_t) apr_pool_create_ex(apr_pool_t **newpool, + apr_pool_t *parent, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +/** + * Create a new pool. + * @deprecated @see apr_pool_create_unmanaged_ex. + */ +APR_DECLARE(apr_status_t) apr_pool_create_core_ex(apr_pool_t **newpool, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator); + +/** + * Create a new unmanaged pool. + * @param newpool The pool we have just created. + * @param abort_fn A function to use if the pool cannot allocate more memory. + * @param allocator The allocator to use with the new pool. If NULL a + * new allocator will be created with the new pool as owner. + * @remark An unmanaged pool is a special pool without a parent; it will + * NOT be destroyed upon apr_terminate. It must be explicitly + * destroyed by calling apr_pool_destroy, to prevent memory leaks. + * Use of this function is discouraged, think twice about whether + * you really really need it. + * @warning Any child cleanups registered against the new pool, or + * against sub-pools thereof, will not be executed during an + * invocation of apr_proc_create(), so resources created in an + * "unmanaged" pool hierarchy will leak to child processes. + */ +APR_DECLARE(apr_status_t) apr_pool_create_unmanaged_ex(apr_pool_t **newpool, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +/** + * Debug version of apr_pool_create_ex. + * @param newpool @see apr_pool_create. + * @param parent @see apr_pool_create. + * @param abort_fn @see apr_pool_create. + * @param allocator @see apr_pool_create. + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @remark Only available when APR_POOL_DEBUG is defined. + * Call this directly if you have your apr_pool_create_ex + * calls in a wrapper function and wish to override + * the file_line argument to reflect the caller of + * your wrapper function. If you do not have + * apr_pool_create_ex in a wrapper, trust the macro + * and don't call apr_pool_create_ex_debug directly. + */ +APR_DECLARE(apr_status_t) apr_pool_create_ex_debug(apr_pool_t **newpool, + apr_pool_t *parent, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pool_create_ex(newpool, parent, abort_fn, allocator) \ + apr_pool_create_ex_debug(newpool, parent, abort_fn, allocator, \ + APR_POOL__FILE_LINE__) +#endif + +/** + * Debug version of apr_pool_create_core_ex. + * @deprecated @see apr_pool_create_unmanaged_ex_debug. + */ +APR_DECLARE(apr_status_t) apr_pool_create_core_ex_debug(apr_pool_t **newpool, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator, + const char *file_line); + +/** + * Debug version of apr_pool_create_unmanaged_ex. + * @param newpool @see apr_pool_create_unmanaged. + * @param abort_fn @see apr_pool_create_unmanaged. + * @param allocator @see apr_pool_create_unmanaged. + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @remark Only available when APR_POOL_DEBUG is defined. + * Call this directly if you have your apr_pool_create_unmanaged_ex + * calls in a wrapper function and wish to override + * the file_line argument to reflect the caller of + * your wrapper function. If you do not have + * apr_pool_create_core_ex in a wrapper, trust the macro + * and don't call apr_pool_create_core_ex_debug directly. + */ +APR_DECLARE(apr_status_t) apr_pool_create_unmanaged_ex_debug(apr_pool_t **newpool, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pool_create_core_ex(newpool, abort_fn, allocator) \ + apr_pool_create_unmanaged_ex_debug(newpool, abort_fn, allocator, \ + APR_POOL__FILE_LINE__) + +#define apr_pool_create_unmanaged_ex(newpool, abort_fn, allocator) \ + apr_pool_create_unmanaged_ex_debug(newpool, abort_fn, allocator, \ + APR_POOL__FILE_LINE__) + +#endif + +/** + * Create a new pool. + * @param newpool The pool we have just created. + * @param parent The parent pool. If this is NULL, the new pool is a root + * pool. If it is non-NULL, the new pool will inherit all + * of its parent pool's attributes, except the apr_pool_t will + * be a sub-pool. + * @remark This function is thread-safe, in the sense that multiple threads + * can safely create subpools of the same parent pool concurrently. + * Similarly, a subpool can be created by one thread at the same + * time that another thread accesses the parent pool. + */ +#if defined(DOXYGEN) +APR_DECLARE(apr_status_t) apr_pool_create(apr_pool_t **newpool, + apr_pool_t *parent); +#else +#if APR_POOL_DEBUG +#define apr_pool_create(newpool, parent) \ + apr_pool_create_ex_debug(newpool, parent, NULL, NULL, \ + APR_POOL__FILE_LINE__) +#else +#define apr_pool_create(newpool, parent) \ + apr_pool_create_ex(newpool, parent, NULL, NULL) +#endif +#endif + +/** + * Create a new unmanaged pool. + * @param newpool The pool we have just created. + */ +#if defined(DOXYGEN) +APR_DECLARE(apr_status_t) apr_pool_create_core(apr_pool_t **newpool); +APR_DECLARE(apr_status_t) apr_pool_create_unmanaged(apr_pool_t **newpool); +#else +#if APR_POOL_DEBUG +#define apr_pool_create_core(newpool) \ + apr_pool_create_unmanaged_ex_debug(newpool, NULL, NULL, \ + APR_POOL__FILE_LINE__) +#define apr_pool_create_unmanaged(newpool) \ + apr_pool_create_unmanaged_ex_debug(newpool, NULL, NULL, \ + APR_POOL__FILE_LINE__) +#else +#define apr_pool_create_core(newpool) \ + apr_pool_create_unmanaged_ex(newpool, NULL, NULL) +#define apr_pool_create_unmanaged(newpool) \ + apr_pool_create_unmanaged_ex(newpool, NULL, NULL) +#endif +#endif + +/** + * Find the pool's allocator + * @param pool The pool to get the allocator from. + */ +APR_DECLARE(apr_allocator_t *) apr_pool_allocator_get(apr_pool_t *pool) + __attribute__((nonnull(1))); + +/** + * Clear all memory in the pool and run all the cleanups. This also destroys all + * subpools. + * @param p The pool to clear + * @remark This does not actually free the memory, it just allows the pool + * to re-use this memory for the next allocation. + * @see apr_pool_destroy() + */ +APR_DECLARE(void) apr_pool_clear(apr_pool_t *p) __attribute__((nonnull(1))); + +/** + * Debug version of apr_pool_clear. + * @param p See: apr_pool_clear. + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @remark Only available when APR_POOL_DEBUG is defined. + * Call this directly if you have your apr_pool_clear + * calls in a wrapper function and wish to override + * the file_line argument to reflect the caller of + * your wrapper function. If you do not have + * apr_pool_clear in a wrapper, trust the macro + * and don't call apr_pool_destroy_clear directly. + */ +APR_DECLARE(void) apr_pool_clear_debug(apr_pool_t *p, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pool_clear(p) \ + apr_pool_clear_debug(p, APR_POOL__FILE_LINE__) +#endif + +/** + * Destroy the pool. This takes similar action as apr_pool_clear() and then + * frees all the memory. + * @param p The pool to destroy + * @remark This will actually free the memory + */ +APR_DECLARE(void) apr_pool_destroy(apr_pool_t *p) __attribute__((nonnull(1))); + +/** + * Debug version of apr_pool_destroy. + * @param p See: apr_pool_destroy. + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @remark Only available when APR_POOL_DEBUG is defined. + * Call this directly if you have your apr_pool_destroy + * calls in a wrapper function and wish to override + * the file_line argument to reflect the caller of + * your wrapper function. If you do not have + * apr_pool_destroy in a wrapper, trust the macro + * and don't call apr_pool_destroy_debug directly. + */ +APR_DECLARE(void) apr_pool_destroy_debug(apr_pool_t *p, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pool_destroy(p) \ + apr_pool_destroy_debug(p, APR_POOL__FILE_LINE__) +#endif + + +/* + * Memory allocation + */ + +/** + * Allocate a block of memory from a pool + * @param p The pool to allocate from + * @param size The amount of memory to allocate + * @return The allocated memory + */ +APR_DECLARE(void *) apr_palloc(apr_pool_t *p, apr_size_t size) +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) + __attribute__((alloc_size(2))) +#endif + __attribute__((nonnull(1))); + +/** + * Debug version of apr_palloc + * @param p See: apr_palloc + * @param size See: apr_palloc + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @return See: apr_palloc + */ +APR_DECLARE(void *) apr_palloc_debug(apr_pool_t *p, apr_size_t size, + const char *file_line) +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) + __attribute__((alloc_size(2))) +#endif + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_palloc(p, size) \ + apr_palloc_debug(p, size, APR_POOL__FILE_LINE__) +#endif + +/** + * Allocate a block of memory from a pool and set all of the memory to 0 + * @param p The pool to allocate from + * @param size The amount of memory to allocate + * @return The allocated memory + */ +#if defined(DOXYGEN) +APR_DECLARE(void *) apr_pcalloc(apr_pool_t *p, apr_size_t size); +#elif !APR_POOL_DEBUG +#define apr_pcalloc(p, size) memset(apr_palloc(p, size), 0, size) +#endif + +/** + * Debug version of apr_pcalloc + * @param p See: apr_pcalloc + * @param size See: apr_pcalloc + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @return See: apr_pcalloc + */ +APR_DECLARE(void *) apr_pcalloc_debug(apr_pool_t *p, apr_size_t size, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pcalloc(p, size) \ + apr_pcalloc_debug(p, size, APR_POOL__FILE_LINE__) +#endif + + +/* + * Pool Properties + */ + +/** + * Set the function to be called when an allocation failure occurs. + * @remark If the program wants APR to exit on a memory allocation error, + * then this function can be called to set the callback to use (for + * performing cleanup and then exiting). If this function is not called, + * then APR will return an error and expect the calling program to + * deal with the error accordingly. + */ +APR_DECLARE(void) apr_pool_abort_set(apr_abortfunc_t abortfunc, + apr_pool_t *pool) + __attribute__((nonnull(2))); + +/** + * Get the abort function associated with the specified pool. + * @param pool The pool for retrieving the abort function. + * @return The abort function for the given pool. + */ +APR_DECLARE(apr_abortfunc_t) apr_pool_abort_get(apr_pool_t *pool) + __attribute__((nonnull(1))); + +/** + * Get the parent pool of the specified pool. + * @param pool The pool for retrieving the parent pool. + * @return The parent of the given pool. + */ +APR_DECLARE(apr_pool_t *) apr_pool_parent_get(apr_pool_t *pool) + __attribute__((nonnull(1))); + +/** + * Determine if pool a is an ancestor of pool b. + * @param a The pool to search + * @param b The pool to search for + * @return True if a is an ancestor of b, NULL is considered an ancestor + * of all pools. + * @remark if compiled with APR_POOL_DEBUG, this function will also + * return true if A is a pool which has been guaranteed by the caller + * (using apr_pool_join) to have a lifetime at least as long as some + * ancestor of pool B. + */ +APR_DECLARE(int) apr_pool_is_ancestor(apr_pool_t *a, apr_pool_t *b); + +/** + * Tag a pool (give it a name) + * @param pool The pool to tag + * @param tag The tag + */ +APR_DECLARE(void) apr_pool_tag(apr_pool_t *pool, const char *tag) + __attribute__((nonnull(1))); + + +/* + * User data management + */ + +/** + * Set the data associated with the current pool + * @param data The user data associated with the pool. + * @param key The key to use for association + * @param cleanup The cleanup program to use to cleanup the data (NULL if none) + * @param pool The current pool + * @warning The data to be attached to the pool should have a life span + * at least as long as the pool it is being attached to. + * + * Users of APR must take EXTREME care when choosing a key to + * use for their data. It is possible to accidentally overwrite + * data by choosing a key that another part of the program is using. + * Therefore it is advised that steps are taken to ensure that unique + * keys are used for all of the userdata objects in a particular pool + * (the same key in two different pools or a pool and one of its + * subpools is okay) at all times. Careful namespace prefixing of + * key names is a typical way to help ensure this uniqueness. + * + */ +APR_DECLARE(apr_status_t) apr_pool_userdata_set(const void *data, + const char *key, + apr_status_t (*cleanup)(void *), + apr_pool_t *pool) + __attribute__((nonnull(2,4))); + +/** + * Set the data associated with the current pool + * @param data The user data associated with the pool. + * @param key The key to use for association + * @param cleanup The cleanup program to use to cleanup the data (NULL if none) + * @param pool The current pool + * @note same as apr_pool_userdata_set(), except that this version doesn't + * make a copy of the key (this function is useful, for example, when + * the key is a string literal) + * @warning This should NOT be used if the key could change addresses by + * any means between the apr_pool_userdata_setn() call and a + * subsequent apr_pool_userdata_get() on that key, such as if a + * static string is used as a userdata key in a DSO and the DSO could + * be unloaded and reloaded between the _setn() and the _get(). You + * MUST use apr_pool_userdata_set() in such cases. + * @warning More generally, the key and the data to be attached to the + * pool should have a life span at least as long as the pool itself. + * + */ +APR_DECLARE(apr_status_t) apr_pool_userdata_setn( + const void *data, const char *key, + apr_status_t (*cleanup)(void *), + apr_pool_t *pool) + __attribute__((nonnull(2,4))); + +/** + * Return the data associated with the current pool. + * @param data The user data associated with the pool. + * @param key The key for the data to retrieve + * @param pool The current pool. + */ +APR_DECLARE(apr_status_t) apr_pool_userdata_get(void **data, const char *key, + apr_pool_t *pool) + __attribute__((nonnull(1,2,3))); + + +/** + * @defgroup PoolCleanup Pool Cleanup Functions + * + * Cleanups are performed in the reverse order they were registered. That is: + * Last In, First Out. A cleanup function can safely allocate memory from + * the pool that is being cleaned up. It can also safely register additional + * cleanups which will be run LIFO, directly after the current cleanup + * terminates. Cleanups have to take caution in calling functions that + * create subpools. Subpools, created during cleanup will NOT automatically + * be cleaned up. In other words, cleanups are to clean up after themselves. + * + * @{ + */ + +/** + * Register a function to be called when a pool is cleared or destroyed + * @param p The pool to register the cleanup with + * @param data The data to pass to the cleanup function. + * @param plain_cleanup The function to call when the pool is cleared + * or destroyed + * @param child_cleanup The function to call when a child process is about + * to exec - this function is called in the child, obviously! + */ +APR_DECLARE(void) apr_pool_cleanup_register( + apr_pool_t *p, const void *data, + apr_status_t (*plain_cleanup)(void *), + apr_status_t (*child_cleanup)(void *)) + __attribute__((nonnull(3,4))); + +/** + * Register a function to be called when a pool is cleared or destroyed. + * + * Unlike apr_pool_cleanup_register which registers a cleanup + * that is called AFTER all subpools are destroyed, this function registers + * a function that will be called before any of the subpools are destroyed. + * + * @param p The pool to register the cleanup with + * @param data The data to pass to the cleanup function. + * @param plain_cleanup The function to call when the pool is cleared + * or destroyed + */ +APR_DECLARE(void) apr_pool_pre_cleanup_register( + apr_pool_t *p, const void *data, + apr_status_t (*plain_cleanup)(void *)) + __attribute__((nonnull(3))); + +/** + * Remove a previously registered cleanup function. + * + * The cleanup most recently registered with @a p having the same values of + * @a data and @a cleanup will be removed. + * + * @param p The pool to remove the cleanup from + * @param data The data of the registered cleanup + * @param cleanup The function to remove from cleanup + * @remarks For some strange reason only the plain_cleanup is handled by this + * function + */ +APR_DECLARE(void) apr_pool_cleanup_kill(apr_pool_t *p, const void *data, + apr_status_t (*cleanup)(void *)) + __attribute__((nonnull(3))); + +/** + * Replace the child cleanup function of a previously registered cleanup. + * + * The cleanup most recently registered with @a p having the same values of + * @a data and @a plain_cleanup will have the registered child cleanup + * function replaced with @a child_cleanup. + * + * @param p The pool of the registered cleanup + * @param data The data of the registered cleanup + * @param plain_cleanup The plain cleanup function of the registered cleanup + * @param child_cleanup The function to register as the child cleanup + */ +APR_DECLARE(void) apr_pool_child_cleanup_set( + apr_pool_t *p, const void *data, + apr_status_t (*plain_cleanup)(void *), + apr_status_t (*child_cleanup)(void *)) + __attribute__((nonnull(3,4))); + +/** + * Run the specified cleanup function immediately and unregister it. + * + * The cleanup most recently registered with @a p having the same values of + * @a data and @a cleanup will be removed and @a cleanup will be called + * with @a data as the argument. + * + * @param p The pool to remove the cleanup from + * @param data The data to remove from cleanup + * @param cleanup The function to remove from cleanup + */ +APR_DECLARE(apr_status_t) apr_pool_cleanup_run(apr_pool_t *p, void *data, + apr_status_t (*cleanup)(void *)) + __attribute__((nonnull(3))); + +/** + * An empty cleanup function. + * + * Passed to apr_pool_cleanup_register() when no cleanup is required. + * + * @param data The data to cleanup, will not be used by this function. + */ +APR_DECLARE_NONSTD(apr_status_t) apr_pool_cleanup_null(void *data); + +/** + * Run all registered child cleanups, in preparation for an exec() + * call in a forked child -- close files, etc., but *don't* flush I/O + * buffers, *don't* wait for subprocesses, and *don't* free any + * memory. + */ +APR_DECLARE(void) apr_pool_cleanup_for_exec(void); + +/** @} */ + +/** + * @defgroup PoolDebug Pool Debugging functions. + * + * pools have nested lifetimes -- sub_pools are destroyed when the + * parent pool is cleared. We allow certain liberties with operations + * on things such as tables (and on other structures in a more general + * sense) where we allow the caller to insert values into a table which + * were not allocated from the table's pool. The table's data will + * remain valid as long as all the pools from which its values are + * allocated remain valid. + * + * For example, if B is a sub pool of A, and you build a table T in + * pool B, then it's safe to insert data allocated in A or B into T + * (because B lives at most as long as A does, and T is destroyed when + * B is cleared/destroyed). On the other hand, if S is a table in + * pool A, it is safe to insert data allocated in A into S, but it + * is *not safe* to insert data allocated from B into S... because + * B can be cleared/destroyed before A is (which would leave dangling + * pointers in T's data structures). + * + * In general we say that it is safe to insert data into a table T + * if the data is allocated in any ancestor of T's pool. This is the + * basis on which the APR_POOL_DEBUG code works -- it tests these ancestor + * relationships for all data inserted into tables. APR_POOL_DEBUG also + * provides tools (apr_pool_find, and apr_pool_is_ancestor) for other + * folks to implement similar restrictions for their own data + * structures. + * + * However, sometimes this ancestor requirement is inconvenient -- + * sometimes it's necessary to create a sub pool where the sub pool is + * guaranteed to have the same lifetime as the parent pool. This is a + * guarantee implemented by the *caller*, not by the pool code. That + * is, the caller guarantees they won't destroy the sub pool + * individually prior to destroying the parent pool. + * + * In this case the caller must call apr_pool_join() to indicate this + * guarantee to the APR_POOL_DEBUG code. + * + * These functions are only implemented when #APR_POOL_DEBUG is set. + * + * @{ + */ +#if APR_POOL_DEBUG || defined(DOXYGEN) +/** + * Guarantee that a subpool has the same lifetime as the parent. + * @param p The parent pool + * @param sub The subpool + */ +APR_DECLARE(void) apr_pool_join(apr_pool_t *p, apr_pool_t *sub) + __attribute__((nonnull(2))); + +/** + * Find a pool from something allocated in it. + * @param mem The thing allocated in the pool + * @return The pool it is allocated in + */ +APR_DECLARE(apr_pool_t *) apr_pool_find(const void *mem); + +/** + * Report the number of bytes currently in the pool + * @param p The pool to inspect + * @param recurse Recurse/include the subpools' sizes + * @return The number of bytes + */ +APR_DECLARE(apr_size_t) apr_pool_num_bytes(apr_pool_t *p, int recurse) + __attribute__((nonnull(1))); + +/** + * Lock a pool + * @param pool The pool to lock + * @param flag The flag + */ +APR_DECLARE(void) apr_pool_lock(apr_pool_t *pool, int flag); + +/* @} */ + +#else /* APR_POOL_DEBUG or DOXYGEN */ + +#ifdef apr_pool_join +#undef apr_pool_join +#endif +#define apr_pool_join(a,b) + +#ifdef apr_pool_lock +#undef apr_pool_lock +#endif +#define apr_pool_lock(pool, lock) + +#endif /* APR_POOL_DEBUG or DOXYGEN */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_POOLS_H */ diff --git a/c/dependencies/linux/apr/include/apr_portable.h b/c/dependencies/linux/apr/include/apr_portable.h new file mode 100644 index 00000000..f56997e4 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_portable.h @@ -0,0 +1,549 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* This header file is where you should put ANY platform specific information. + * This should be the only header file that programs need to include that + * actually has platform dependent code which refers to the . + */ +#ifndef APR_PORTABLE_H +#define APR_PORTABLE_H +/** + * @file apr_portable.h + * @brief APR Portability Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" +#include "apr_network_io.h" +#include "apr_errno.h" +#include "apr_global_mutex.h" +#include "apr_proc_mutex.h" +#include "apr_time.h" +#include "apr_dso.h" +#include "apr_shm.h" + +#if APR_HAVE_DIRENT_H +#include +#endif +#if APR_HAVE_FCNTL_H +#include +#endif +#if APR_HAVE_PTHREAD_H +#include +#endif +#if APR_HAVE_SEMAPHORE_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_portabile Portability Routines + * @ingroup APR + * @{ + */ + +#ifdef WIN32 +/* The primitives for Windows types */ +typedef HANDLE apr_os_file_t; +typedef HANDLE apr_os_dir_t; +typedef SOCKET apr_os_sock_t; +typedef HANDLE apr_os_proc_mutex_t; +typedef HANDLE apr_os_thread_t; +typedef HANDLE apr_os_proc_t; +typedef DWORD apr_os_threadkey_t; +typedef FILETIME apr_os_imp_time_t; +typedef SYSTEMTIME apr_os_exp_time_t; +typedef HANDLE apr_os_dso_handle_t; +typedef HANDLE apr_os_shm_t; + +#elif defined(OS2) +typedef HFILE apr_os_file_t; +typedef HDIR apr_os_dir_t; +typedef int apr_os_sock_t; +typedef HMTX apr_os_proc_mutex_t; +typedef TID apr_os_thread_t; +typedef PID apr_os_proc_t; +typedef PULONG apr_os_threadkey_t; +typedef struct timeval apr_os_imp_time_t; +typedef struct tm apr_os_exp_time_t; +typedef HMODULE apr_os_dso_handle_t; +typedef void* apr_os_shm_t; + +#elif defined(__BEOS__) +#include +#include + +struct apr_os_proc_mutex_t { + sem_id sem; + int32 ben; +}; + +typedef int apr_os_file_t; +typedef DIR apr_os_dir_t; +typedef int apr_os_sock_t; +typedef struct apr_os_proc_mutex_t apr_os_proc_mutex_t; +typedef thread_id apr_os_thread_t; +typedef thread_id apr_os_proc_t; +typedef int apr_os_threadkey_t; +typedef struct timeval apr_os_imp_time_t; +typedef struct tm apr_os_exp_time_t; +typedef image_id apr_os_dso_handle_t; +typedef void* apr_os_shm_t; + +#elif defined(NETWARE) +typedef int apr_os_file_t; +typedef DIR apr_os_dir_t; +typedef int apr_os_sock_t; +typedef NXMutex_t apr_os_proc_mutex_t; +typedef NXThreadId_t apr_os_thread_t; +typedef long apr_os_proc_t; +typedef NXKey_t apr_os_threadkey_t; +typedef struct timeval apr_os_imp_time_t; +typedef struct tm apr_os_exp_time_t; +typedef void * apr_os_dso_handle_t; +typedef void* apr_os_shm_t; + +#else +/* Any other OS should go above this one. This is the lowest common + * denominator typedefs for all UNIX-like systems. :) + */ + +/** Basic OS process mutex structure. */ +struct apr_os_proc_mutex_t { +#if APR_HAS_SYSVSEM_SERIALIZE || APR_HAS_FCNTL_SERIALIZE || APR_HAS_FLOCK_SERIALIZE + /** Value used for SYS V Semaphore, FCNTL and FLOCK serialization */ + int crossproc; +#endif +#if APR_HAS_PROC_PTHREAD_SERIALIZE + /** Value used for PTHREAD serialization */ + pthread_mutex_t *pthread_interproc; +#endif +#if APR_HAS_THREADS + /* If no threads, no need for thread locks */ +#if APR_USE_PTHREAD_SERIALIZE + /** This value is currently unused within APR and Apache */ + pthread_mutex_t *intraproc; +#endif +#endif +#if APR_HAS_POSIXSEM_SERIALIZE + /** Value used for POSIX semaphores serialization */ + sem_t *psem_interproc; +#endif +}; + +typedef int apr_os_file_t; /**< native file */ +typedef DIR apr_os_dir_t; /**< native dir */ +typedef int apr_os_sock_t; /**< native dir */ +typedef struct apr_os_proc_mutex_t apr_os_proc_mutex_t; /**< native process + * mutex + */ +#if APR_HAS_THREADS && APR_HAVE_PTHREAD_H +typedef pthread_t apr_os_thread_t; /**< native thread */ +typedef pthread_key_t apr_os_threadkey_t; /**< native thread address + * space */ +#endif +typedef pid_t apr_os_proc_t; /**< native pid */ +typedef struct timeval apr_os_imp_time_t; /**< native timeval */ +typedef struct tm apr_os_exp_time_t; /**< native tm */ +/** @var apr_os_dso_handle_t + * native dso types + */ +#if defined(HPUX) || defined(HPUX10) || defined(HPUX11) +#include +typedef shl_t apr_os_dso_handle_t; +#elif defined(DARWIN) +#include +typedef NSModule apr_os_dso_handle_t; +#else +typedef void * apr_os_dso_handle_t; +#endif +typedef void* apr_os_shm_t; /**< native SHM */ + +#endif + +/** + * @typedef apr_os_sock_info_t + * @brief alias for local OS socket + */ +/** + * everything APR needs to know about an active socket to construct + * an APR socket from it; currently, this is platform-independent + */ +struct apr_os_sock_info_t { + apr_os_sock_t *os_sock; /**< always required */ + struct sockaddr *local; /**< NULL if not yet bound */ + struct sockaddr *remote; /**< NULL if not connected */ + int family; /**< always required (APR_INET, APR_INET6, etc.) */ + int type; /**< always required (SOCK_STREAM, SOCK_DGRAM, etc.) */ + int protocol; /**< 0 or actual protocol (APR_PROTO_SCTP, APR_PROTO_TCP, etc.) */ +}; + +typedef struct apr_os_sock_info_t apr_os_sock_info_t; + +#if APR_PROC_MUTEX_IS_GLOBAL || defined(DOXYGEN) +/** Opaque global mutex type */ +#define apr_os_global_mutex_t apr_os_proc_mutex_t +/** @return apr_os_global_mutex */ +#define apr_os_global_mutex_get apr_os_proc_mutex_get +#else + /** Thread and process mutex for those platforms where process mutexes + * are not held in threads. + */ + struct apr_os_global_mutex_t { + apr_pool_t *pool; + apr_proc_mutex_t *proc_mutex; +#if APR_HAS_THREADS + apr_thread_mutex_t *thread_mutex; +#endif /* APR_HAS_THREADS */ + }; + typedef struct apr_os_global_mutex_t apr_os_global_mutex_t; + +APR_DECLARE(apr_status_t) apr_os_global_mutex_get(apr_os_global_mutex_t *ospmutex, + apr_global_mutex_t *pmutex); +#endif + + +/** + * convert the file from apr type to os specific type. + * @param thefile The os specific file we are converting to + * @param file The apr file to convert. + * @remark On Unix, it is only possible to get a file descriptor from + * an apr file type. + */ +APR_DECLARE(apr_status_t) apr_os_file_get(apr_os_file_t *thefile, + apr_file_t *file); + +/** + * convert the dir from apr type to os specific type. + * @param thedir The os specific dir we are converting to + * @param dir The apr dir to convert. + */ +APR_DECLARE(apr_status_t) apr_os_dir_get(apr_os_dir_t **thedir, + apr_dir_t *dir); + +/** + * Convert the socket from an apr type to an OS specific socket + * @param thesock The socket to convert. + * @param sock The os specific equivalent of the apr socket.. + */ +APR_DECLARE(apr_status_t) apr_os_sock_get(apr_os_sock_t *thesock, + apr_socket_t *sock); + +/** + * Convert the proc mutex from apr type to os specific type + * @param ospmutex The os specific proc mutex we are converting to. + * @param pmutex The apr proc mutex to convert. + */ +APR_DECLARE(apr_status_t) apr_os_proc_mutex_get(apr_os_proc_mutex_t *ospmutex, + apr_proc_mutex_t *pmutex); + +/** + * Convert the proc mutex from apr type to os specific type, also + * providing the mechanism used by the apr mutex. + * @param ospmutex The os specific proc mutex we are converting to. + * @param pmutex The apr proc mutex to convert. + * @param mech The mechanism used by the apr proc mutex (if not NULL). + * @remark Allows for disambiguation for platforms with multiple mechanisms + * available. + */ +APR_DECLARE(apr_status_t) apr_os_proc_mutex_get_ex(apr_os_proc_mutex_t *ospmutex, + apr_proc_mutex_t *pmutex, + apr_lockmech_e *mech); + +/** + * Get the exploded time in the platforms native format. + * @param ostime the native time format + * @param aprtime the time to convert + */ +APR_DECLARE(apr_status_t) apr_os_exp_time_get(apr_os_exp_time_t **ostime, + apr_time_exp_t *aprtime); + +/** + * Get the imploded time in the platforms native format. + * @param ostime the native time format + * @param aprtime the time to convert + */ +APR_DECLARE(apr_status_t) apr_os_imp_time_get(apr_os_imp_time_t **ostime, + apr_time_t *aprtime); + +/** + * convert the shm from apr type to os specific type. + * @param osshm The os specific shm representation + * @param shm The apr shm to convert. + */ +APR_DECLARE(apr_status_t) apr_os_shm_get(apr_os_shm_t *osshm, + apr_shm_t *shm); + +#if APR_HAS_THREADS || defined(DOXYGEN) +/** + * @defgroup apr_os_thread Thread portability Routines + * @{ + */ +/** + * convert the thread to os specific type from apr type. + * @param thethd The apr thread to convert + * @param thd The os specific thread we are converting to + */ +APR_DECLARE(apr_status_t) apr_os_thread_get(apr_os_thread_t **thethd, + apr_thread_t *thd); + +/** + * convert the thread private memory key to os specific type from an apr type. + * @param thekey The apr handle we are converting from. + * @param key The os specific handle we are converting to. + */ +APR_DECLARE(apr_status_t) apr_os_threadkey_get(apr_os_threadkey_t *thekey, + apr_threadkey_t *key); + +/** + * convert the thread from os specific type to apr type. + * @param thd The apr thread we are converting to. + * @param thethd The os specific thread to convert + * @param cont The pool to use if it is needed. + */ +APR_DECLARE(apr_status_t) apr_os_thread_put(apr_thread_t **thd, + apr_os_thread_t *thethd, + apr_pool_t *cont); + +/** + * convert the thread private memory key from os specific type to apr type. + * @param key The apr handle we are converting to. + * @param thekey The os specific handle to convert + * @param cont The pool to use if it is needed. + */ +APR_DECLARE(apr_status_t) apr_os_threadkey_put(apr_threadkey_t **key, + apr_os_threadkey_t *thekey, + apr_pool_t *cont); +/** + * Get the thread ID + */ +APR_DECLARE(apr_os_thread_t) apr_os_thread_current(void); + +/** + * Compare two thread id's + * @param tid1 1st Thread ID to compare + * @param tid2 2nd Thread ID to compare + * @return non-zero if the two threads are equal, zero otherwise + */ +APR_DECLARE(int) apr_os_thread_equal(apr_os_thread_t tid1, + apr_os_thread_t tid2); + +/** @} */ +#endif /* APR_HAS_THREADS */ + +/** + * convert the file from os specific type to apr type. + * @param file The apr file we are converting to. + * @param thefile The os specific file to convert + * @param flags The flags that were used to open this file. + * @param cont The pool to use if it is needed. + * @remark On Unix, it is only possible to put a file descriptor into + * an apr file type. + */ +APR_DECLARE(apr_status_t) apr_os_file_put(apr_file_t **file, + apr_os_file_t *thefile, + apr_int32_t flags, apr_pool_t *cont); + +/** + * convert the file from os specific type to apr type. + * @param file The apr file we are converting to. + * @param thefile The os specific pipe to convert + * @param cont The pool to use if it is needed. + * @remark On Unix, it is only possible to put a file descriptor into + * an apr file type. + */ +APR_DECLARE(apr_status_t) apr_os_pipe_put(apr_file_t **file, + apr_os_file_t *thefile, + apr_pool_t *cont); + +/** + * convert the file from os specific type to apr type. + * @param file The apr file we are converting to. + * @param thefile The os specific pipe to convert + * @param register_cleanup A cleanup will be registered on the apr_file_t + * to issue apr_file_close(). + * @param cont The pool to use if it is needed. + * @remark On Unix, it is only possible to put a file descriptor into + * an apr file type. + */ +APR_DECLARE(apr_status_t) apr_os_pipe_put_ex(apr_file_t **file, + apr_os_file_t *thefile, + int register_cleanup, + apr_pool_t *cont); + +/** + * convert the dir from os specific type to apr type. + * @param dir The apr dir we are converting to. + * @param thedir The os specific dir to convert + * @param cont The pool to use when creating to apr directory. + */ +APR_DECLARE(apr_status_t) apr_os_dir_put(apr_dir_t **dir, + apr_os_dir_t *thedir, + apr_pool_t *cont); + +/** + * Convert a socket from the os specific type to the APR type. If + * sock points to NULL, a socket will be created from the pool + * provided. If **sock does not point to NULL, the structure pointed + * to by sock will be reused and updated with the given socket. + * @param sock The pool to use. + * @param thesock The socket to convert to. + * @param cont The socket we are converting to an apr type. + * @remark If it is a true socket, it is best to call apr_os_sock_make() + * and provide APR with more information about the socket. + */ +APR_DECLARE(apr_status_t) apr_os_sock_put(apr_socket_t **sock, + apr_os_sock_t *thesock, + apr_pool_t *cont); + +/** + * Create a socket from an existing descriptor and local and remote + * socket addresses. + * @param apr_sock The new socket that has been set up + * @param os_sock_info The os representation of the socket handle and + * other characteristics of the socket + * @param cont The pool to use + * @remark If you only know the descriptor/handle or if it isn't really + * a true socket, use apr_os_sock_put() instead. + */ +APR_DECLARE(apr_status_t) apr_os_sock_make(apr_socket_t **apr_sock, + apr_os_sock_info_t *os_sock_info, + apr_pool_t *cont); + +/** + * Convert the proc mutex from os specific type to apr type + * @param pmutex The apr proc mutex we are converting to. + * @param ospmutex The os specific proc mutex to convert. + * @param cont The pool to use if it is needed. + */ +APR_DECLARE(apr_status_t) apr_os_proc_mutex_put(apr_proc_mutex_t **pmutex, + apr_os_proc_mutex_t *ospmutex, + apr_pool_t *cont); + +/** + * Convert the proc mutex from os specific type to apr type, using the + * specified mechanism. + * @param pmutex The apr proc mutex we are converting to. + * @param ospmutex The os specific proc mutex to convert. + * @param mech The apr mutex locking mechanism + * @param register_cleanup Whether to destroy the os mutex with the apr + * one (either on explicit destroy or pool cleanup). + * @param cont The pool to use if it is needed. + * @remark Allows for disambiguation for platforms with multiple mechanisms + * available. + */ +APR_DECLARE(apr_status_t) apr_os_proc_mutex_put_ex(apr_proc_mutex_t **pmutex, + apr_os_proc_mutex_t *ospmutex, + apr_lockmech_e mech, + int register_cleanup, + apr_pool_t *cont); + +/** + * Put the imploded time in the APR format. + * @param aprtime the APR time format + * @param ostime the time to convert + * @param cont the pool to use if necessary + */ +APR_DECLARE(apr_status_t) apr_os_imp_time_put(apr_time_t *aprtime, + apr_os_imp_time_t **ostime, + apr_pool_t *cont); + +/** + * Put the exploded time in the APR format. + * @param aprtime the APR time format + * @param ostime the time to convert + * @param cont the pool to use if necessary + */ +APR_DECLARE(apr_status_t) apr_os_exp_time_put(apr_time_exp_t *aprtime, + apr_os_exp_time_t **ostime, + apr_pool_t *cont); + +/** + * convert the shared memory from os specific type to apr type. + * @param shm The apr shm representation of osshm + * @param osshm The os specific shm identity + * @param cont The pool to use if it is needed. + * @remark On fork()ed architectures, this is typically nothing more than + * the memory block mapped. On non-fork architectures, this is typically + * some internal handle to pass the mapping from process to process. + */ +APR_DECLARE(apr_status_t) apr_os_shm_put(apr_shm_t **shm, + apr_os_shm_t *osshm, + apr_pool_t *cont); + + +#if APR_HAS_DSO || defined(DOXYGEN) +/** + * @defgroup apr_os_dso DSO (Dynamic Loading) Portability Routines + * @{ + */ +/** + * convert the dso handle from os specific to apr + * @param dso The apr handle we are converting to + * @param thedso the os specific handle to convert + * @param pool the pool to use if it is needed + */ +APR_DECLARE(apr_status_t) apr_os_dso_handle_put(apr_dso_handle_t **dso, + apr_os_dso_handle_t thedso, + apr_pool_t *pool); + +/** + * convert the apr dso handle into an os specific one + * @param aprdso The apr dso handle to convert + * @param dso The os specific dso to return + */ +APR_DECLARE(apr_status_t) apr_os_dso_handle_get(apr_os_dso_handle_t *dso, + apr_dso_handle_t *aprdso); + +/** @} */ +#endif /* APR_HAS_DSO */ + + +#if APR_HAS_OS_UUID +/** + * Private: apr-util's apr_uuid module when supported by the platform + */ +APR_DECLARE(apr_status_t) apr_os_uuid_get(unsigned char *uuid_data); +#endif + + +/** + * Get the name of the system default character set. + * @param pool the pool to allocate the name from, if needed + */ +APR_DECLARE(const char*) apr_os_default_encoding(apr_pool_t *pool); + + +/** + * Get the name of the current locale character set. + * @param pool the pool to allocate the name from, if needed + * @remark Defers to apr_os_default_encoding() if the current locale's + * data can't be retrieved on this system. + */ +APR_DECLARE(const char*) apr_os_locale_encoding(apr_pool_t *pool); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_PORTABLE_H */ diff --git a/c/dependencies/linux/apr/include/apr_proc_mutex.h b/c/dependencies/linux/apr/include/apr_proc_mutex.h new file mode 100644 index 00000000..418c9504 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_proc_mutex.h @@ -0,0 +1,192 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_PROC_MUTEX_H +#define APR_PROC_MUTEX_H + +/** + * @file apr_proc_mutex.h + * @brief APR Process Locking Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_perms_set.h" +#include "apr_time.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_proc_mutex Process Locking Routines + * @ingroup APR + * @{ + */ + +/** + * Enumerated potential types for APR process locking methods + * @warning Check APR_HAS_foo_SERIALIZE defines to see if the platform supports + * APR_LOCK_foo. Only APR_LOCK_DEFAULT is portable. + */ +typedef enum { + APR_LOCK_FCNTL, /**< fcntl() */ + APR_LOCK_FLOCK, /**< flock() */ + APR_LOCK_SYSVSEM, /**< System V Semaphores */ + APR_LOCK_PROC_PTHREAD, /**< POSIX pthread process-based locking */ + APR_LOCK_POSIXSEM, /**< POSIX semaphore process-based locking */ + APR_LOCK_DEFAULT, /**< Use the default process lock */ + APR_LOCK_DEFAULT_TIMED /**< Use the default process timed lock */ +} apr_lockmech_e; + +/** Opaque structure representing a process mutex. */ +typedef struct apr_proc_mutex_t apr_proc_mutex_t; + +/* Function definitions */ + +/** + * Create and initialize a mutex that can be used to synchronize processes. + * @param mutex the memory address where the newly created mutex will be + * stored. + * @param fname A file name to use if the lock mechanism requires one. This + * argument should always be provided. The lock code itself will + * determine if it should be used. + * @param mech The mechanism to use for the interprocess lock, if any; one of + *
+ *            APR_LOCK_FCNTL
+ *            APR_LOCK_FLOCK
+ *            APR_LOCK_SYSVSEM
+ *            APR_LOCK_POSIXSEM
+ *            APR_LOCK_PROC_PTHREAD
+ *            APR_LOCK_DEFAULT     pick the default mechanism for the platform
+ * 
+ * @param pool the pool from which to allocate the mutex. + * @see apr_lockmech_e + * @warning Check APR_HAS_foo_SERIALIZE defines to see if the platform supports + * APR_LOCK_foo. Only APR_LOCK_DEFAULT is portable. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_create(apr_proc_mutex_t **mutex, + const char *fname, + apr_lockmech_e mech, + apr_pool_t *pool); + +/** + * Re-open a mutex in a child process. + * @param mutex The newly re-opened mutex structure. + * @param fname A file name to use if the mutex mechanism requires one. This + * argument should always be provided. The mutex code itself will + * determine if it should be used. This filename should be the + * same one that was passed to apr_proc_mutex_create(). + * @param pool The pool to operate on. + * @remark This function must be called to maintain portability, even + * if the underlying lock mechanism does not require it. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_child_init(apr_proc_mutex_t **mutex, + const char *fname, + apr_pool_t *pool); + +/** + * Acquire the lock for the given mutex. If the mutex is already locked, + * the current thread will be put to sleep until the lock becomes available. + * @param mutex the mutex on which to acquire the lock. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_lock(apr_proc_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex. If the mutex has already + * been acquired, the call returns immediately with APR_EBUSY. Note: it + * is important that the APR_STATUS_IS_EBUSY(s) macro be used to determine + * if the return value was APR_EBUSY, for portability reasons. + * @param mutex the mutex on which to attempt the lock acquiring. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_trylock(apr_proc_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex until timeout expires. + * If the acquisition time outs, the call returns with APR_TIMEUP. + * @param mutex the mutex on which to attempt the lock acquiring. + * @param timeout the relative timeout (microseconds). + * @note A negative or nul timeout means immediate attempt, returning + * APR_TIMEUP without blocking if it the lock is already acquired. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_timedlock(apr_proc_mutex_t *mutex, + apr_interval_time_t timeout); + +/** + * Release the lock for the given mutex. + * @param mutex the mutex from which to release the lock. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_unlock(apr_proc_mutex_t *mutex); + +/** + * Destroy the mutex and free the memory associated with the lock. + * @param mutex the mutex to destroy. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_destroy(apr_proc_mutex_t *mutex); + +/** + * Destroy the mutex and free the memory associated with the lock. + * @param mutex the mutex to destroy. + * @note This function is generally used to kill a cleanup on an already + * created mutex + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_cleanup(void *mutex); + +/** + * Return the name of the lockfile for the mutex, or NULL + * if the mutex doesn't use a lock file + */ + +APR_DECLARE(const char *) apr_proc_mutex_lockfile(apr_proc_mutex_t *mutex); + +/** + * Get the mechanism of the mutex, as it relates to the actual method + * used for the underlying apr_proc_mutex_t. + * @param mutex the mutex to get the mechanism from. + */ +APR_DECLARE(apr_lockmech_e) apr_proc_mutex_mech(apr_proc_mutex_t *mutex); + +/** + * Get the mechanism's name of the mutex, as it relates to the actual method + * used for the underlying apr_proc_mutex_t. + * @param mutex the mutex to get the mechanism's name from. + */ +APR_DECLARE(const char *) apr_proc_mutex_name(apr_proc_mutex_t *mutex); + +/** + * Display the name of the default mutex: APR_LOCK_DEFAULT + */ +APR_DECLARE(const char *) apr_proc_mutex_defname(void); + +/** + * Set mutex permissions. + */ +APR_PERMS_SET_IMPLEMENT(proc_mutex); + +/** + * Get the pool used by this proc_mutex. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(proc_mutex); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_PROC_MUTEX_H */ diff --git a/c/dependencies/linux/apr/include/apr_queue.h b/c/dependencies/linux/apr/include/apr_queue.h new file mode 100644 index 00000000..a3a41704 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_queue.h @@ -0,0 +1,138 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_QUEUE_H +#define APR_QUEUE_H + +/** + * @file apr_queue.h + * @brief Thread Safe FIFO bounded queue + * @note Since most implementations of the queue are backed by a condition + * variable implementation, it isn't available on systems without threads. + * Although condition variables are sometimes available without threads. + */ + +#include "apu.h" +#include "apr_errno.h" +#include "apr_pools.h" + +#if APR_HAS_THREADS + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_Util_FIFO Thread Safe FIFO bounded queue + * @ingroup APR_Util + * @{ + */ + +/** + * opaque structure + */ +typedef struct apr_queue_t apr_queue_t; + +/** + * create a FIFO queue + * @param queue The new queue + * @param queue_capacity maximum size of the queue + * @param a pool to allocate queue from + */ +APU_DECLARE(apr_status_t) apr_queue_create(apr_queue_t **queue, + unsigned int queue_capacity, + apr_pool_t *a); + +/** + * push/add an object to the queue, blocking if the queue is already full + * + * @param queue the queue + * @param data the data + * @returns APR_EINTR the blocking was interrupted (try again) + * @returns APR_EOF the queue has been terminated + * @returns APR_SUCCESS on a successful push + */ +APU_DECLARE(apr_status_t) apr_queue_push(apr_queue_t *queue, void *data); + +/** + * pop/get an object from the queue, blocking if the queue is already empty + * + * @param queue the queue + * @param data the data + * @returns APR_EINTR the blocking was interrupted (try again) + * @returns APR_EOF if the queue has been terminated + * @returns APR_SUCCESS on a successful pop + */ +APU_DECLARE(apr_status_t) apr_queue_pop(apr_queue_t *queue, void **data); + +/** + * push/add an object to the queue, returning immediately if the queue is full + * + * @param queue the queue + * @param data the data + * @returns APR_EINTR the blocking operation was interrupted (try again) + * @returns APR_EAGAIN the queue is full + * @returns APR_EOF the queue has been terminated + * @returns APR_SUCCESS on a successful push + */ +APU_DECLARE(apr_status_t) apr_queue_trypush(apr_queue_t *queue, void *data); + +/** + * pop/get an object to the queue, returning immediately if the queue is empty + * + * @param queue the queue + * @param data the data + * @returns APR_EINTR the blocking operation was interrupted (try again) + * @returns APR_EAGAIN the queue is empty + * @returns APR_EOF the queue has been terminated + * @returns APR_SUCCESS on a successful pop + */ +APU_DECLARE(apr_status_t) apr_queue_trypop(apr_queue_t *queue, void **data); + +/** + * returns the size of the queue. + * + * @warning this is not threadsafe, and is intended for reporting/monitoring + * of the queue. + * @param queue the queue + * @returns the size of the queue + */ +APU_DECLARE(unsigned int) apr_queue_size(apr_queue_t *queue); + +/** + * interrupt all the threads blocking on this queue. + * + * @param queue the queue + */ +APU_DECLARE(apr_status_t) apr_queue_interrupt_all(apr_queue_t *queue); + +/** + * terminate the queue, sending an interrupt to all the + * blocking threads + * + * @param queue the queue + */ +APU_DECLARE(apr_status_t) apr_queue_term(apr_queue_t *queue); + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif /* APR_HAS_THREADS */ + +#endif /* APRQUEUE_H */ diff --git a/c/dependencies/linux/apr/include/apr_random.h b/c/dependencies/linux/apr/include/apr_random.h new file mode 100644 index 00000000..29154358 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_random.h @@ -0,0 +1,153 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_RANDOM_H +#define APR_RANDOM_H + +/** + * @file apr_random.h + * @brief APR PRNG routines + */ + +#include "apr_pools.h" +#include "apr_thread_proc.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_random PRNG Routines + * @ingroup APR + * @{ + */ + +typedef struct apr_crypto_hash_t apr_crypto_hash_t; + +typedef void apr_crypto_hash_init_t(apr_crypto_hash_t *hash); +typedef void apr_crypto_hash_add_t(apr_crypto_hash_t *hash, const void *data, + apr_size_t bytes); +typedef void apr_crypto_hash_finish_t(apr_crypto_hash_t *hash, + unsigned char *result); + + +/* FIXME: make this opaque */ +struct apr_crypto_hash_t { + apr_crypto_hash_init_t *init; + apr_crypto_hash_add_t *add; + apr_crypto_hash_finish_t *finish; + apr_size_t size; + void *data; +}; + +/** + * Allocate and initialize the SHA-256 context + * @param p The pool to allocate from + */ +APR_DECLARE(apr_crypto_hash_t *) apr_crypto_sha256_new(apr_pool_t *p); + +/** Opaque PRNG structure. */ +typedef struct apr_random_t apr_random_t; + +/** + * Initialize a PRNG state + * @param g The PRNG state + * @param p The pool to allocate from + * @param pool_hash Pool hash functions + * @param key_hash Key hash functions + * @param prng_hash PRNG hash functions + */ +APR_DECLARE(void) apr_random_init(apr_random_t *g, apr_pool_t *p, + apr_crypto_hash_t *pool_hash, + apr_crypto_hash_t *key_hash, + apr_crypto_hash_t *prng_hash); +/** + * Allocate and initialize (apr_crypto_sha256_new) a new PRNG state. + * @param p The pool to allocate from + */ +APR_DECLARE(apr_random_t *) apr_random_standard_new(apr_pool_t *p); + +/** + * Mix the randomness pools. + * @param g The PRNG state + * @param entropy_ Entropy buffer + * @param bytes Length of entropy_ in bytes + */ +APR_DECLARE(void) apr_random_add_entropy(apr_random_t *g, + const void *entropy_, + apr_size_t bytes); +/** + * Generate cryptographically insecure random bytes. + * @param g The RNG state + * @param random Buffer to fill with random bytes + * @param bytes Length of buffer in bytes + */ +APR_DECLARE(apr_status_t) apr_random_insecure_bytes(apr_random_t *g, + void *random, + apr_size_t bytes); + +/** + * Generate cryptographically secure random bytes. + * @param g The RNG state + * @param random Buffer to fill with random bytes + * @param bytes Length of buffer in bytes + */ +APR_DECLARE(apr_status_t) apr_random_secure_bytes(apr_random_t *g, + void *random, + apr_size_t bytes); +/** + * Ensures that E bits of conditional entropy are mixed into the PRNG + * before any further randomness is extracted. + * @param g The RNG state + */ +APR_DECLARE(void) apr_random_barrier(apr_random_t *g); + +/** + * Return APR_SUCCESS if the cryptographic PRNG has been seeded with + * enough data, APR_ENOTENOUGHENTROPY otherwise. + * @param r The RNG state + */ +APR_DECLARE(apr_status_t) apr_random_secure_ready(apr_random_t *r); + +/** + * Return APR_SUCCESS if the PRNG has been seeded with enough data, + * APR_ENOTENOUGHENTROPY otherwise. + * @param r The PRNG state + */ +APR_DECLARE(apr_status_t) apr_random_insecure_ready(apr_random_t *r); + +/** + * Mix the randomness pools after forking. + * @param proc The resulting process handle from apr_proc_fork() + * @remark Call this in the child after forking to mix the randomness + * pools. Note that its generally a bad idea to fork a process with a + * real PRNG in it - better to have the PRNG externally and get the + * randomness from there. However, if you really must do it, then you + * should supply all your entropy to all the PRNGs - don't worry, they + * won't produce the same output. + * @remark Note that apr_proc_fork() calls this for you, so only weird + * applications need ever call it themselves. + * @internal + */ +APR_DECLARE(void) apr_random_after_fork(apr_proc_t *proc); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_RANDOM_H */ diff --git a/c/dependencies/linux/apr/include/apr_redis.h b/c/dependencies/linux/apr/include/apr_redis.h new file mode 100644 index 00000000..66a828b0 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_redis.h @@ -0,0 +1,459 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_redis.h + * @brief Client interface for redis + * @remark To use this interface you must have a separate redis + * for more information. + */ + +#ifndef APR_REDIS_H +#define APR_REDIS_H + +#include "apr.h" +#include "apr_pools.h" +#include "apr_time.h" +#include "apr_strings.h" +#include "apr_network_io.h" +#include "apr_ring.h" +#include "apr_buckets.h" +#include "apr_reslist.h" +#include "apr_hash.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#ifndef RC_DEFAULT_SERVER_PORT +#define RC_DEFAULT_SERVER_PORT 6379 +#endif + +#ifndef RC_DEFAULT_SERVER_MIN +#define RC_DEFAULT_SERVER_MIN 0 +#endif + +#ifndef RC_DEFAULT_SERVER_SMAX +#define RC_DEFAULT_SERVER_SMAX 1 +#endif + +#ifndef RC_DEFAULT_SERVER_TTL +#define RC_DEFAULT_SERVER_TTL 600 +#endif + +/** + * @defgroup APR_Util_RC Redis Client Routines + * @ingroup APR_Util + * @{ + */ + +/** Specifies the status of a redis server */ +typedef enum +{ + APR_RC_SERVER_LIVE, /**< Server is alive and responding to requests */ + APR_RC_SERVER_DEAD /**< Server is not responding to requests */ +} apr_redis_server_status_t; + +/** Opaque redis client connection object */ +typedef struct apr_redis_conn_t apr_redis_conn_t; + +/** Redis Server Info Object */ +typedef struct apr_redis_server_t apr_redis_server_t; +struct apr_redis_server_t +{ + const char *host; /**< Hostname of this Server */ + apr_port_t port; /**< Port of this Server */ + apr_redis_server_status_t status; /**< @see apr_redis_server_status_t */ +#if APR_HAS_THREADS || defined(DOXYGEN) + apr_reslist_t *conns; /**< Resource list of actual client connections */ +#else + apr_redis_conn_t *conn; +#endif + apr_pool_t *p; /** Pool to use for private allocations */ +#if APR_HAS_THREADS + apr_thread_mutex_t *lock; +#endif + apr_time_t btime; + apr_uint32_t rwto; + struct + { + int major; + int minor; + int patch; + char *number; + } version; +}; + +typedef struct apr_redis_t apr_redis_t; + +/* Custom hash callback function prototype, user for server selection. +* @param baton user selected baton +* @param data data to hash +* @param data_len length of data +*/ +typedef apr_uint32_t (*apr_redis_hash_func)(void *baton, + const char *data, + const apr_size_t data_len); +/* Custom Server Select callback function prototype. +* @param baton user selected baton +* @param rc redis instance, use rc->live_servers to select a node +* @param hash hash of the selected key. +*/ +typedef apr_redis_server_t* (*apr_redis_server_func)(void *baton, + apr_redis_t *rc, + const apr_uint32_t hash); + +/** Container for a set of redis servers */ +struct apr_redis_t +{ + apr_uint32_t flags; /**< Flags, Not currently used */ + apr_uint16_t nalloc; /**< Number of Servers Allocated */ + apr_uint16_t ntotal; /**< Number of Servers Added */ + apr_redis_server_t **live_servers; /**< Array of Servers */ + apr_pool_t *p; /** Pool to use for allocations */ + void *hash_baton; + apr_redis_hash_func hash_func; + void *server_baton; + apr_redis_server_func server_func; +}; + +/** + * Creates a crc32 hash used to split keys between servers + * @param rc The redis client object to use + * @param data Data to be hashed + * @param data_len Length of the data to use + * @return crc32 hash of data + * @remark The crc32 hash is not compatible with old redisd clients. + */ +APU_DECLARE(apr_uint32_t) apr_redis_hash(apr_redis_t *rc, + const char *data, + const apr_size_t data_len); + +/** + * Pure CRC32 Hash. Used by some clients. + */ +APU_DECLARE(apr_uint32_t) apr_redis_hash_crc32(void *baton, + const char *data, + const apr_size_t data_len); + +/** + * hash compatible with the standard Perl Client. + */ +APU_DECLARE(apr_uint32_t) apr_redis_hash_default(void *baton, + const char *data, + const apr_size_t data_len); + +/** + * Picks a server based on a hash + * @param rc The redis client object to use + * @param hash Hashed value of a Key + * @return server that controls specified hash + * @see apr_redis_hash + */ +APU_DECLARE(apr_redis_server_t *) apr_redis_find_server_hash(apr_redis_t *rc, + const apr_uint32_t hash); + +/** + * server selection compatible with the standard Perl Client. + */ +APU_DECLARE(apr_redis_server_t *) apr_redis_find_server_hash_default(void *baton, + apr_redis_t *rc, + const apr_uint32_t hash); + +/** + * Adds a server to a client object + * @param rc The redis client object to use + * @param server Server to add + * @remark Adding servers is not thread safe, and should be done once at startup. + * @warning Changing servers after startup may cause keys to go to + * different servers. + */ +APU_DECLARE(apr_status_t) apr_redis_add_server(apr_redis_t *rc, + apr_redis_server_t *server); + + +/** + * Finds a Server object based on a hostname/port pair + * @param rc The redis client object to use + * @param host Hostname of the server + * @param port Port of the server + * @return Server with matching Hostname and Port, or NULL if none was found. + */ +APU_DECLARE(apr_redis_server_t *) apr_redis_find_server(apr_redis_t *rc, + const char *host, + apr_port_t port); + +/** + * Enables a Server for use again + * @param rc The redis client object to use + * @param rs Server to Activate + */ +APU_DECLARE(apr_status_t) apr_redis_enable_server(apr_redis_t *rc, + apr_redis_server_t *rs); + + +/** + * Disable a Server + * @param rc The redis client object to use + * @param rs Server to Disable + */ +APU_DECLARE(apr_status_t) apr_redis_disable_server(apr_redis_t *rc, + apr_redis_server_t *rs); + +/** + * Creates a new Server Object + * @param p Pool to use + * @param host hostname of the server + * @param port port of the server + * @param min minimum number of client sockets to open + * @param smax soft maximum number of client connections to open + * @param max hard maximum number of client connections + * @param ttl time to live in microseconds of a client connection + * @param rwto r/w timeout value in seconds of a client connection + * @param ns location of the new server object + * @see apr_reslist_create + * @remark min, smax, and max are only used when APR_HAS_THREADS + */ +APU_DECLARE(apr_status_t) apr_redis_server_create(apr_pool_t *p, + const char *host, + apr_port_t port, + apr_uint32_t min, + apr_uint32_t smax, + apr_uint32_t max, + apr_uint32_t ttl, + apr_uint32_t rwto, + apr_redis_server_t **ns); +/** + * Creates a new redisd client object + * @param p Pool to use + * @param max_servers maximum number of servers + * @param flags Not currently used + * @param rc location of the new redis client object + */ +APU_DECLARE(apr_status_t) apr_redis_create(apr_pool_t *p, + apr_uint16_t max_servers, + apr_uint32_t flags, + apr_redis_t **rc); + +/** + * Gets a value from the server, allocating the value out of p + * @param rc client to use + * @param p Pool to use + * @param key null terminated string containing the key + * @param baton location of the allocated value + * @param len length of data at baton + * @param flags any flags set by the client for this key + * @return + */ +APU_DECLARE(apr_status_t) apr_redis_getp(apr_redis_t *rc, + apr_pool_t *p, + const char* key, + char **baton, + apr_size_t *len, + apr_uint16_t *flags); + +/** + * Sets a value by key on the server + * @param rc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param flags any flags set by the client for this key + */ +APU_DECLARE(apr_status_t) apr_redis_set(apr_redis_t *rc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint16_t flags); + +/** + * Sets a value by key on the server + * @param rc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param timeout time in seconds for the data to live on the server + * @param flags any flags set by the client for this key + */ +APU_DECLARE(apr_status_t) apr_redis_setex(apr_redis_t *rc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint32_t timeout, + apr_uint16_t flags); + +/** + * Deletes a key from a server + * @param rc client to use + * @param key null terminated string containing the key + * @param timeout time for the delete to stop other clients from adding + */ +APU_DECLARE(apr_status_t) apr_redis_delete(apr_redis_t *rc, + const char *key, + apr_uint32_t timeout); + +/** + * Query a server's version + * @param rs server to query + * @param p Pool to allocate answer from + * @param baton location to store server version string + */ +APU_DECLARE(apr_status_t) apr_redis_version(apr_redis_server_t *rs, + apr_pool_t *p, + char **baton); + +/** + * Query a server's INFO + * @param rs server to query + * @param p Pool to allocate answer from + * @param baton location to store server INFO response string + */ +APU_DECLARE(apr_status_t) apr_redis_info(apr_redis_server_t *rs, + apr_pool_t *p, + char **baton); + +/** + * Increments a value + * @param rc client to use + * @param key null terminated string containing the key + * @param inc number to increment by + * @param new_value new value after incrementing + */ +APU_DECLARE(apr_status_t) apr_redis_incr(apr_redis_t *rc, + const char *key, + apr_int32_t inc, + apr_uint32_t *new_value); +/** + * Decrements a value + * @param rc client to use + * @param key null terminated string containing the key + * @param inc number to decrement by + * @param new_value new value after decrementing + */ +APU_DECLARE(apr_status_t) apr_redis_decr(apr_redis_t *rc, + const char *key, + apr_int32_t inc, + apr_uint32_t *new_value); + + +/** + * Pings the server + * @param rs Server to ping + */ +APU_DECLARE(apr_status_t) apr_redis_ping(apr_redis_server_t *rs); + +/** + * Gets multiple values from the server, allocating the values out of p + * @param rc client to use + * @param temp_pool Pool used for temporary allocations. May be cleared inside this + * call. + * @param data_pool Pool used to allocate data for the returned values. + * @param values hash of apr_redis_value_t keyed by strings, contains the + * result of the multiget call. + * @return + */ +APU_DECLARE(apr_status_t) apr_redis_multgetp(apr_redis_t *rc, + apr_pool_t *temp_pool, + apr_pool_t *data_pool, + apr_hash_t *values); + +typedef enum +{ + APR_RS_SERVER_MASTER, /**< Server is a master */ + APR_RS_SERVER_SLAVE, /**< Server is a slave */ + APR_RS_SERVER_UNKNOWN /**< Server role is unknown */ +} apr_redis_server_role_t; + +typedef struct +{ +/* # Server */ + /** Major version number of this server */ + apr_uint32_t major; + /** Minor version number of this server */ + apr_uint32_t minor; + /** Patch version number of this server */ + apr_uint32_t patch; + /** Process id of this server process */ + apr_uint32_t process_id; + /** Number of seconds this server has been running */ + apr_uint32_t uptime_in_seconds; + /** Bitsize of the arch on the current machine */ + apr_uint32_t arch_bits; + +/* # Clients */ + /** Number of connected clients */ + apr_uint32_t connected_clients; + /** Number of blocked clients */ + apr_uint32_t blocked_clients; + +/* # Memory */ + /** Max memory of this server */ + apr_uint64_t maxmemory; + /** Amount of used memory */ + apr_uint64_t used_memory; + /** Total memory available on this server */ + apr_uint64_t total_system_memory; + +/* # Stats */ + /** Total connections received */ + apr_uint64_t total_connections_received; + /** Total commands processed */ + apr_uint64_t total_commands_processed; + /** Total commands rejected */ + apr_uint64_t rejected_connections; + /** Total net input bytes */ + apr_uint64_t total_net_input_bytes; + /** Total net output bytes */ + apr_uint64_t total_net_output_bytes; + /** Keyspace hits */ + apr_uint64_t keyspace_hits; + /** Keyspace misses */ + apr_uint64_t keyspace_misses; + +/* # Replication */ + /** Role */ + apr_redis_server_role_t role; + /** Number of connected slave */ + apr_uint32_t connected_slaves; + +/* # CPU */ + /** Accumulated CPU user time for this process */ + apr_uint32_t used_cpu_sys; + /** Accumulated CPU system time for this process */ + apr_uint32_t used_cpu_user; + +/* # Cluster */ + /** Is cluster enabled */ + apr_uint32_t cluster_enabled; +} apr_redis_stats_t; + +/** + * Query a server for statistics + * @param rs server to query + * @param p Pool to allocate answer from + * @param stats location of the new statistics structure + */ +APU_DECLARE(apr_status_t) apr_redis_stats(apr_redis_server_t *rs, + apr_pool_t *p, + apr_redis_stats_t **stats); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_REDIS_H */ diff --git a/c/dependencies/linux/apr/include/apr_reslist.h b/c/dependencies/linux/apr/include/apr_reslist.h new file mode 100644 index 00000000..02a8192b --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_reslist.h @@ -0,0 +1,183 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_RESLIST_H +#define APR_RESLIST_H + +/** + * @file apr_reslist.h + * @brief APR-UTIL Resource List Routines + */ + +#include "apr.h" +#include "apu.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_time.h" + +/** + * @defgroup APR_Util_RL Resource List Routines + * @ingroup APR_Util + * @{ + */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** Opaque resource list object */ +typedef struct apr_reslist_t apr_reslist_t; + +/* Generic constructor called by resource list when it needs to create a + * resource. + * @param resource opaque resource + * @param params flags + * @param pool Pool + */ +typedef apr_status_t (*apr_reslist_constructor)(void **resource, void *params, + apr_pool_t *pool); + +/* Generic destructor called by resource list when it needs to destroy a + * resource. + * @param resource opaque resource + * @param params flags + * @param pool Pool + */ +typedef apr_status_t (*apr_reslist_destructor)(void *resource, void *params, + apr_pool_t *pool); + +/* Cleanup order modes */ +#define APR_RESLIST_CLEANUP_DEFAULT 0 /**< default pool cleanup */ +#define APR_RESLIST_CLEANUP_FIRST 1 /**< use pool pre cleanup */ + +/** + * Create a new resource list with the following parameters: + * @param reslist An address where the pointer to the new resource + * list will be stored. + * @param min Allowed minimum number of available resources. Zero + * creates new resources only when needed. + * @param smax Resources will be destroyed during reslist maintenance to + * meet this maximum restriction as they expire (reach their ttl). + * @param hmax Absolute maximum limit on the number of total resources. + * @param ttl If non-zero, sets the maximum amount of time in microseconds an + * unused resource is valid. Any resource which has exceeded this + * time will be destroyed, either when encountered by + * apr_reslist_acquire() or during reslist maintenance. + * @param con Constructor routine that is called to create a new resource. + * @param de Destructor routine that is called to destroy an expired resource. + * @param params Passed to constructor and deconstructor + * @param pool The pool from which to create this resource list. Also the + * same pool that is passed to the constructor and destructor + * routines. + * @remark If APR has been compiled without thread support, hmax will be + * automatically set to 1 and values of min and smax will be forced to + * 1 for any non-zero value. + */ +APU_DECLARE(apr_status_t) apr_reslist_create(apr_reslist_t **reslist, + int min, int smax, int hmax, + apr_interval_time_t ttl, + apr_reslist_constructor con, + apr_reslist_destructor de, + void *params, + apr_pool_t *pool); + +/** + * Destroy the given resource list and all resources controlled by + * this list. + * FIXME: Should this block until all resources become available, + * or maybe just destroy all the free ones, or maybe destroy + * them even though they might be in use by something else? + * Currently it will abort if there are resources that haven't + * been released, so there is an assumption that all resources + * have been released to the list before calling this function. + * @param reslist The reslist to destroy + */ +APU_DECLARE(apr_status_t) apr_reslist_destroy(apr_reslist_t *reslist); + +/** + * Retrieve a resource from the list, creating a new one if necessary. + * If we have met our maximum number of resources, we will block + * until one becomes available. + * @param reslist The resource list. + * @param resource An address where the pointer to the resource + * will be stored. + */ +APU_DECLARE(apr_status_t) apr_reslist_acquire(apr_reslist_t *reslist, + void **resource); + +/** + * Return a resource back to the list of available resources. + * @param reslist The resource list. + * @param resource The resource to return to the list. + */ +APU_DECLARE(apr_status_t) apr_reslist_release(apr_reslist_t *reslist, + void *resource); + +/** + * Set the timeout the acquire will wait for a free resource + * when the maximum number of resources is exceeded. + * @param reslist The resource list. + * @param timeout Timeout to wait. The zero waits forever. + */ +APU_DECLARE(void) apr_reslist_timeout_set(apr_reslist_t *reslist, + apr_interval_time_t timeout); + +/** + * Return the number of outstanding resources. + * @param reslist The resource list. + */ +APU_DECLARE(apr_uint32_t) apr_reslist_acquired_count(apr_reslist_t *reslist); + +/** + * Invalidate a resource in the pool - e.g. a database connection + * that returns a "lost connection" error and can't be restored. + * Use this instead of apr_reslist_release if the resource is bad. + * @param reslist The resource list. + * @param resource The resource to invalidate. + */ +APU_DECLARE(apr_status_t) apr_reslist_invalidate(apr_reslist_t *reslist, + void *resource); + +/** + * Perform routine maintenance on the resource list. This call + * may instantiate new resources or expire old resources. + * @param reslist The resource list. + */ +APU_DECLARE(apr_status_t) apr_reslist_maintain(apr_reslist_t *reslist); + +/** + * Set reslist cleanup order. + * @param reslist The resource list. + * @param mode Cleanup order mode + *
+ *           APR_RESLIST_CLEANUP_DEFAULT  default pool cleanup order
+ *           APR_RESLIST_CLEANUP_FIRST    use pool pre cleanup
+ * 
+ * @remark If APR_RESLIST_CLEANUP_FIRST is used the destructors will + * be called before child pools of the pool used to create the reslist + * are destroyed. This allows to explicitly destroy the child pools + * inside reslist destructors. + */ +APU_DECLARE(void) apr_reslist_cleanup_order_set(apr_reslist_t *reslist, + apr_uint32_t mode); + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif /* ! APR_RESLIST_H */ diff --git a/c/dependencies/linux/apr/include/apr_ring.h b/c/dependencies/linux/apr/include/apr_ring.h new file mode 100644 index 00000000..eec735fc --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_ring.h @@ -0,0 +1,513 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * This code draws heavily from the 4.4BSD macros + * and Dean Gaudet's "splim/ring.h". + * + * + * + * We'd use Dean's code directly if we could guarantee the + * availability of inline functions. + */ + +#ifndef APR_RING_H +#define APR_RING_H + +/** + * @file apr_ring.h + * @brief APR Rings + */ + +/* + * for offsetof() + */ +#include "apr_general.h" + +/** + * @defgroup apr_ring Ring Macro Implementations + * @ingroup APR + * A ring is a kind of doubly-linked list that can be manipulated + * without knowing where its head is. + * @{ + */ + +/** + * The Ring Element + * + * A ring element struct is linked to the other elements in the ring + * through its ring entry field, e.g. + *
+ *      struct my_element_t {
+ *          APR_RING_ENTRY(my_element_t) link;
+ *          int foo;
+ *          char *bar;
+ *      };
+ * 
+ * + * An element struct may be put on more than one ring if it has more + * than one APR_RING_ENTRY field. Each APR_RING_ENTRY has a corresponding + * APR_RING_HEAD declaration. + * + * @warning For strict C standards compliance you should put the APR_RING_ENTRY + * first in the element struct unless the head is always part of a larger + * object with enough earlier fields to accommodate the offsetof() used + * to compute the ring sentinel below. You can usually ignore this caveat. + */ +#define APR_RING_ENTRY(elem) \ + struct { \ + struct elem * volatile next; \ + struct elem * volatile prev; \ + } + +/** + * The Ring Head + * + * Each ring is managed via its head, which is a struct declared like this: + *
+ *      APR_RING_HEAD(my_ring_t, my_element_t);
+ *      struct my_ring_t ring, *ringp;
+ * 
+ * + * This struct looks just like the element link struct so that we can + * be sure that the typecasting games will work as expected. + * + * The first element in the ring is next after the head, and the last + * element is just before the head. + */ +#define APR_RING_HEAD(head, elem) \ + struct head { \ + struct elem * volatile next; \ + struct elem * volatile prev; \ + } + +/** + * The Ring Sentinel + * + * This is the magic pointer value that occurs before the first and + * after the last elements in the ring, computed from the address of + * the ring's head. The head itself isn't an element, but in order to + * get rid of all the special cases when dealing with the ends of the + * ring, we play typecasting games to make it look like one. + * + * Here is a diagram to illustrate the arrangements of the next and + * prev pointers of each element in a single ring. Note that they point + * to the start of each element, not to the APR_RING_ENTRY structure. + * + *
+ *     +->+------+<-+  +->+------+<-+  +->+------+<-+
+ *     |  |struct|  |  |  |struct|  |  |  |struct|  |
+ *    /   | elem |   \/   | elem |   \/   | elem |  \
+ * ...    |      |   /\   |      |   /\   |      |   ...
+ *        +------+  |  |  +------+  |  |  +------+
+ *   ...--|prev  |  |  +--|ring  |  |  +--|prev  |
+ *        |  next|--+     | entry|--+     |  next|--...
+ *        +------+        +------+        +------+
+ *        | etc. |        | etc. |        | etc. |
+ *        :      :        :      :        :      :
+ * 
+ * + * The APR_RING_HEAD is nothing but a bare APR_RING_ENTRY. The prev + * and next pointers in the first and last elements don't actually + * point to the head, they point to a phantom place called the + * sentinel. Its value is such that last->next->next == first because + * the offset from the sentinel to the head's next pointer is the same + * as the offset from the start of an element to its next pointer. + * This also works in the opposite direction. + * + *
+ *        last                            first
+ *     +->+------+<-+  +->sentinel<-+  +->+------+<-+
+ *     |  |struct|  |  |            |  |  |struct|  |
+ *    /   | elem |   \/              \/   | elem |  \
+ * ...    |      |   /\              /\   |      |   ...
+ *        +------+  |  |  +------+  |  |  +------+
+ *   ...--|prev  |  |  +--|ring  |  |  +--|prev  |
+ *        |  next|--+     |  head|--+     |  next|--...
+ *        +------+        +------+        +------+
+ *        | etc. |                        | etc. |
+ *        :      :                        :      :
+ * 
+ * + * Note that the offset mentioned above is different for each kind of + * ring that the element may be on, and each kind of ring has a unique + * name for its APR_RING_ENTRY in each element, and has its own type + * for its APR_RING_HEAD. + * + * Note also that if the offset is non-zero (which is required if an + * element has more than one APR_RING_ENTRY), the unreality of the + * sentinel may have bad implications on very perverse implementations + * of C -- see the warning in APR_RING_ENTRY. + * + * @param hp The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SENTINEL(hp, elem, link) \ + (struct elem *)((char *)(&(hp)->next) - APR_OFFSETOF(struct elem, link)) + +/** + * The first element of the ring + * @param hp The head of the ring + */ +#define APR_RING_FIRST(hp) (hp)->next +/** + * The last element of the ring + * @param hp The head of the ring + */ +#define APR_RING_LAST(hp) (hp)->prev +/** + * The next element in the ring + * @param ep The current element + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_NEXT(ep, link) (ep)->link.next +/** + * The previous element in the ring + * @param ep The current element + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_PREV(ep, link) (ep)->link.prev + + +/** + * Initialize a ring + * @param hp The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INIT(hp, elem, link) do { \ + APR_RING_FIRST((hp)) = APR_RING_SENTINEL((hp), elem, link); \ + APR_RING_LAST((hp)) = APR_RING_SENTINEL((hp), elem, link); \ + } while (0) + +/** + * Determine if a ring is empty + * @param hp The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + * @return true or false + */ +#define APR_RING_EMPTY(hp, elem, link) \ + (APR_RING_FIRST((hp)) == APR_RING_SENTINEL((hp), elem, link)) + +/** + * Initialize a singleton element + * @param ep The element + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_ELEM_INIT(ep, link) do { \ + APR_RING_NEXT((ep), link) = (ep); \ + APR_RING_PREV((ep), link) = (ep); \ + } while (0) + + +/** + * Splice the sequence ep1..epN into the ring before element lep + * (..lep.. becomes ..ep1..epN..lep..) + * @warning This doesn't work for splicing before the first element or on + * empty rings... see APR_RING_SPLICE_HEAD for one that does + * @param lep Element in the ring to splice before + * @param ep1 First element in the sequence to splice in + * @param epN Last element in the sequence to splice in + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SPLICE_BEFORE(lep, ep1, epN, link) do { \ + APR_RING_NEXT((epN), link) = (lep); \ + APR_RING_PREV((ep1), link) = APR_RING_PREV((lep), link); \ + APR_RING_NEXT(APR_RING_PREV((lep), link), link) = (ep1); \ + APR_RING_PREV((lep), link) = (epN); \ + } while (0) + +/** + * Splice the sequence ep1..epN into the ring after element lep + * (..lep.. becomes ..lep..ep1..epN..) + * @warning This doesn't work for splicing after the last element or on + * empty rings... see APR_RING_SPLICE_TAIL for one that does + * @param lep Element in the ring to splice after + * @param ep1 First element in the sequence to splice in + * @param epN Last element in the sequence to splice in + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SPLICE_AFTER(lep, ep1, epN, link) do { \ + APR_RING_PREV((ep1), link) = (lep); \ + APR_RING_NEXT((epN), link) = APR_RING_NEXT((lep), link); \ + APR_RING_PREV(APR_RING_NEXT((lep), link), link) = (epN); \ + APR_RING_NEXT((lep), link) = (ep1); \ + } while (0) + +/** + * Insert the element nep into the ring before element lep + * (..lep.. becomes ..nep..lep..) + * @warning This doesn't work for inserting before the first element or on + * empty rings... see APR_RING_INSERT_HEAD for one that does + * @param lep Element in the ring to insert before + * @param nep Element to insert + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INSERT_BEFORE(lep, nep, link) \ + APR_RING_SPLICE_BEFORE((lep), (nep), (nep), link) + +/** + * Insert the element nep into the ring after element lep + * (..lep.. becomes ..lep..nep..) + * @warning This doesn't work for inserting after the last element or on + * empty rings... see APR_RING_INSERT_TAIL for one that does + * @param lep Element in the ring to insert after + * @param nep Element to insert + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INSERT_AFTER(lep, nep, link) \ + APR_RING_SPLICE_AFTER((lep), (nep), (nep), link) + + +/** + * Splice the sequence ep1..epN into the ring before the first element + * (..hp.. becomes ..hp..ep1..epN..) + * @param hp Head of the ring + * @param ep1 First element in the sequence to splice in + * @param epN Last element in the sequence to splice in + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SPLICE_HEAD(hp, ep1, epN, elem, link) \ + APR_RING_SPLICE_AFTER(APR_RING_SENTINEL((hp), elem, link), \ + (ep1), (epN), link) + +/** + * Splice the sequence ep1..epN into the ring after the last element + * (..hp.. becomes ..ep1..epN..hp..) + * @param hp Head of the ring + * @param ep1 First element in the sequence to splice in + * @param epN Last element in the sequence to splice in + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SPLICE_TAIL(hp, ep1, epN, elem, link) \ + APR_RING_SPLICE_BEFORE(APR_RING_SENTINEL((hp), elem, link), \ + (ep1), (epN), link) + +/** + * Insert the element nep into the ring before the first element + * (..hp.. becomes ..hp..nep..) + * @param hp Head of the ring + * @param nep Element to insert + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INSERT_HEAD(hp, nep, elem, link) \ + APR_RING_SPLICE_HEAD((hp), (nep), (nep), elem, link) + +/** + * Insert the element nep into the ring after the last element + * (..hp.. becomes ..nep..hp..) + * @param hp Head of the ring + * @param nep Element to insert + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INSERT_TAIL(hp, nep, elem, link) \ + APR_RING_SPLICE_TAIL((hp), (nep), (nep), elem, link) + +/** + * Concatenate ring h2 onto the end of ring h1, leaving h2 empty. + * @param h1 Head of the ring to concatenate onto + * @param h2 Head of the ring to concatenate + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_CONCAT(h1, h2, elem, link) do { \ + if (!APR_RING_EMPTY((h2), elem, link)) { \ + APR_RING_SPLICE_BEFORE(APR_RING_SENTINEL((h1), elem, link), \ + APR_RING_FIRST((h2)), \ + APR_RING_LAST((h2)), link); \ + APR_RING_INIT((h2), elem, link); \ + } \ + } while (0) + +/** + * Prepend ring h2 onto the beginning of ring h1, leaving h2 empty. + * @param h1 Head of the ring to prepend onto + * @param h2 Head of the ring to prepend + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_PREPEND(h1, h2, elem, link) do { \ + if (!APR_RING_EMPTY((h2), elem, link)) { \ + APR_RING_SPLICE_AFTER(APR_RING_SENTINEL((h1), elem, link), \ + APR_RING_FIRST((h2)), \ + APR_RING_LAST((h2)), link); \ + APR_RING_INIT((h2), elem, link); \ + } \ + } while (0) + +/** + * Unsplice a sequence of elements from a ring + * @warning The unspliced sequence is left with dangling pointers at either end + * @param ep1 First element in the sequence to unsplice + * @param epN Last element in the sequence to unsplice + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_UNSPLICE(ep1, epN, link) do { \ + APR_RING_NEXT(APR_RING_PREV((ep1), link), link) = \ + APR_RING_NEXT((epN), link); \ + APR_RING_PREV(APR_RING_NEXT((epN), link), link) = \ + APR_RING_PREV((ep1), link); \ + } while (0) + +/** + * Remove a single element from a ring + * @warning The unspliced element is left with dangling pointers at either end + * @param ep Element to remove + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_REMOVE(ep, link) \ + APR_RING_UNSPLICE((ep), (ep), link) + +/** + * Iterate over a ring + * @param ep The current element + * @param head The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_FOREACH(ep, head, elem, link) \ + for (ep = APR_RING_FIRST(head); \ + ep != APR_RING_SENTINEL(head, elem, link); \ + ep = APR_RING_NEXT(ep, link)) + +/** + * Iterate over a ring safe against removal of the current element + * @param ep1 The current element + * @param ep2 Iteration cursor + * @param head The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_FOREACH_SAFE(ep1, ep2, head, elem, link) \ + for (ep1 = APR_RING_FIRST(head), ep2 = APR_RING_NEXT(ep1, link); \ + ep1 != APR_RING_SENTINEL(head, elem, link); \ + ep1 = ep2, ep2 = APR_RING_NEXT(ep1, link)) + +/* Debugging tools: */ + +#ifdef APR_RING_DEBUG +#include +#include + +#define APR_RING_CHECK_ONE(msg, ptr) \ + fprintf(stderr, "*** %s %p\n", msg, ptr) + +#define APR_RING_CHECK(hp, elem, link, msg) \ + APR_RING_CHECK_ELEM(APR_RING_SENTINEL(hp, elem, link), elem, link, msg) + +#define APR_RING_CHECK_ELEM(ep, elem, link, msg) do { \ + struct elem *start = (ep); \ + struct elem *here = start; \ + fprintf(stderr, "*** ring check start -- %s\n", msg); \ + do { \ + fprintf(stderr, "\telem %p\n", here); \ + fprintf(stderr, "\telem->next %p\n", \ + APR_RING_NEXT(here, link)); \ + fprintf(stderr, "\telem->prev %p\n", \ + APR_RING_PREV(here, link)); \ + fprintf(stderr, "\telem->next->prev %p\n", \ + APR_RING_PREV(APR_RING_NEXT(here, link), link)); \ + fprintf(stderr, "\telem->prev->next %p\n", \ + APR_RING_NEXT(APR_RING_PREV(here, link), link)); \ + if (APR_RING_PREV(APR_RING_NEXT(here, link), link) != here) { \ + fprintf(stderr, "\t*** elem->next->prev != elem\n"); \ + break; \ + } \ + if (APR_RING_NEXT(APR_RING_PREV(here, link), link) != here) { \ + fprintf(stderr, "\t*** elem->prev->next != elem\n"); \ + break; \ + } \ + here = APR_RING_NEXT(here, link); \ + } while (here != start); \ + fprintf(stderr, "*** ring check end\n"); \ + } while (0) + +#define APR_RING_CHECK_CONSISTENCY(hp, elem, link) \ + APR_RING_CHECK_ELEM_CONSISTENCY(APR_RING_SENTINEL(hp, elem, link),\ + elem, link) + +#define APR_RING_CHECK_ELEM_CONSISTENCY(ep, elem, link) do { \ + struct elem *start = (ep); \ + struct elem *here = start; \ + do { \ + assert(APR_RING_PREV(APR_RING_NEXT(here, link), link) == here); \ + assert(APR_RING_NEXT(APR_RING_PREV(here, link), link) == here); \ + here = APR_RING_NEXT(here, link); \ + } while (here != start); \ + } while (0) + +#else +/** + * Print a single pointer value to STDERR + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param msg Descriptive message + * @param ptr Pointer value to print + */ +#define APR_RING_CHECK_ONE(msg, ptr) +/** + * Dump all ring pointers to STDERR, starting with the head and looping all + * the way around the ring back to the head. Aborts if an inconsistency + * is found. + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param hp Head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + * @param msg Descriptive message + */ +#define APR_RING_CHECK(hp, elem, link, msg) +/** + * Loops around a ring and checks all the pointers for consistency. Pops + * an assertion if any inconsistency is found. Same idea as APR_RING_CHECK() + * except that it's silent if all is well. + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param hp Head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_CHECK_CONSISTENCY(hp, elem, link) +/** + * Dump all ring pointers to STDERR, starting with the given element and + * looping all the way around the ring back to that element. Aborts if + * an inconsistency is found. + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param ep The element + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + * @param msg Descriptive message + */ +#define APR_RING_CHECK_ELEM(ep, elem, link, msg) +/** + * Loops around a ring, starting with the given element, and checks all + * the pointers for consistency. Pops an assertion if any inconsistency + * is found. Same idea as APR_RING_CHECK_ELEM() except that it's silent + * if all is well. + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param ep The element + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_CHECK_ELEM_CONSISTENCY(ep, elem, link) +#endif + +/** @} */ + +#endif /* !APR_RING_H */ diff --git a/c/dependencies/linux/apr/include/apr_rmm.h b/c/dependencies/linux/apr/include/apr_rmm.h new file mode 100644 index 00000000..976fe9c5 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_rmm.h @@ -0,0 +1,137 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_RMM_H +#define APR_RMM_H +/** + * @file apr_rmm.h + * @brief APR-UTIL Relocatable Memory Management Routines + */ +/** + * @defgroup APR_Util_RMM Relocatable Memory Management Routines + * @ingroup APR_Util + * @{ + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apu.h" +#include "apr_anylock.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** Structure to access Relocatable, Managed Memory */ +typedef struct apr_rmm_t apr_rmm_t; + +/** Fundamental allocation unit, within a specific apr_rmm_t */ +typedef apr_size_t apr_rmm_off_t; + +/** + * Initialize a relocatable memory block to be managed by the apr_rmm API. + * @param rmm The relocatable memory block + * @param lock An apr_anylock_t of the appropriate type of lock, or NULL + * if no locking is required. + * @param membuf The block of relocatable memory to be managed + * @param memsize The size of relocatable memory block to be managed + * @param cont The pool to use for local storage and management + * @remark Both @param membuf and @param memsize must be aligned + * (for instance using APR_ALIGN_DEFAULT). + */ +APU_DECLARE(apr_status_t) apr_rmm_init(apr_rmm_t **rmm, apr_anylock_t *lock, + void *membuf, apr_size_t memsize, + apr_pool_t *cont); + +/** + * Destroy a managed memory block. + * @param rmm The relocatable memory block to destroy + */ +APU_DECLARE(apr_status_t) apr_rmm_destroy(apr_rmm_t *rmm); + +/** + * Attach to a relocatable memory block already managed by the apr_rmm API. + * @param rmm The relocatable memory block + * @param lock An apr_anylock_t of the appropriate type of lock + * @param membuf The block of relocatable memory already under management + * @param cont The pool to use for local storage and management + */ +APU_DECLARE(apr_status_t) apr_rmm_attach(apr_rmm_t **rmm, apr_anylock_t *lock, + void *membuf, apr_pool_t *cont); + +/** + * Detach from the managed block of memory. + * @param rmm The relocatable memory block to detach from + */ +APU_DECLARE(apr_status_t) apr_rmm_detach(apr_rmm_t *rmm); + +/** + * Allocate memory from the block of relocatable memory. + * @param rmm The relocatable memory block + * @param reqsize How much memory to allocate + */ +APU_DECLARE(apr_rmm_off_t) apr_rmm_malloc(apr_rmm_t *rmm, apr_size_t reqsize); + +/** + * Realloc memory from the block of relocatable memory. + * @param rmm The relocatable memory block + * @param entity The memory allocation to realloc + * @param reqsize The new size + */ +APU_DECLARE(apr_rmm_off_t) apr_rmm_realloc(apr_rmm_t *rmm, void *entity, apr_size_t reqsize); + +/** + * Allocate memory from the block of relocatable memory and initialize it to zero. + * @param rmm The relocatable memory block + * @param reqsize How much memory to allocate + */ +APU_DECLARE(apr_rmm_off_t) apr_rmm_calloc(apr_rmm_t *rmm, apr_size_t reqsize); + +/** + * Free allocation returned by apr_rmm_malloc or apr_rmm_calloc. + * @param rmm The relocatable memory block + * @param entity The memory allocation to free + */ +APU_DECLARE(apr_status_t) apr_rmm_free(apr_rmm_t *rmm, apr_rmm_off_t entity); + +/** + * Retrieve the physical address of a relocatable allocation of memory + * @param rmm The relocatable memory block + * @param entity The memory allocation to free + * @return address The address, aligned with APR_ALIGN_DEFAULT. + */ +APU_DECLARE(void *) apr_rmm_addr_get(apr_rmm_t *rmm, apr_rmm_off_t entity); + +/** + * Compute the offset of a relocatable allocation of memory + * @param rmm The relocatable memory block + * @param entity The physical address to convert to an offset + */ +APU_DECLARE(apr_rmm_off_t) apr_rmm_offset_get(apr_rmm_t *rmm, void *entity); + +/** + * Compute the required overallocation of memory needed to fit n allocs + * @param n The number of alloc/calloc regions desired + */ +APU_DECLARE(apr_size_t) apr_rmm_overhead_get(int n); + +#ifdef __cplusplus +} +#endif +/** @} */ +#endif /* ! APR_RMM_H */ + diff --git a/c/dependencies/linux/apr/include/apr_sdbm.h b/c/dependencies/linux/apr/include/apr_sdbm.h new file mode 100644 index 00000000..5759508b --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_sdbm.h @@ -0,0 +1,176 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * sdbm - ndbm work-alike hashed database library + * based on Per-Ake Larson's Dynamic Hashing algorithms. BIT 18 (1978). + * author: oz@nexus.yorku.ca + * status: ex-public domain + */ + +#ifndef APR_SDBM_H +#define APR_SDBM_H + +#include "apu.h" +#include "apr_errno.h" +#include "apr_file_io.h" /* for apr_fileperms_t */ + +/** + * @file apr_sdbm.h + * @brief apr-util SDBM library + */ +/** + * @defgroup APR_Util_DBM_SDBM SDBM library + * @ingroup APR_Util_DBM + * @{ + */ + +/** + * Structure for referencing an sdbm + */ +typedef struct apr_sdbm_t apr_sdbm_t; + +/** + * Structure for referencing the datum record within an sdbm + */ +typedef struct { + /** pointer to the data stored/retrieved */ + char *dptr; + /** size of data */ + /* apr_ssize_t for release 2.0??? */ + int dsize; +} apr_sdbm_datum_t; + +/* The extensions used for the database files */ +/** SDBM Directory file extension */ +#define APR_SDBM_DIRFEXT ".dir" +/** SDBM page file extension */ +#define APR_SDBM_PAGFEXT ".pag" + +/* flags to sdbm_store */ +#define APR_SDBM_INSERT 0 /**< Insert */ +#define APR_SDBM_REPLACE 1 /**< Replace */ +#define APR_SDBM_INSERTDUP 2 /**< Insert with duplicates */ + +/** + * Open an sdbm database by file name + * @param db The newly opened database + * @param name The sdbm file to open + * @param mode The flag values (APR_READ and APR_BINARY flags are implicit) + *
+ *           APR_WRITE          open for read-write access
+ *           APR_CREATE         create the sdbm if it does not exist
+ *           APR_TRUNCATE       empty the contents of the sdbm
+ *           APR_EXCL           fail for APR_CREATE if the file exists
+ *           APR_DELONCLOSE     delete the sdbm when closed
+ *           APR_SHARELOCK      support locking across process/machines
+ * 
+ * @param perms Permissions to apply to if created + * @param p The pool to use when creating the sdbm + * @remark The sdbm name is not a true file name, as sdbm appends suffixes + * for seperate data and index files. + */ +APU_DECLARE(apr_status_t) apr_sdbm_open(apr_sdbm_t **db, const char *name, + apr_int32_t mode, + apr_fileperms_t perms, apr_pool_t *p); + +/** + * Close an sdbm file previously opened by apr_sdbm_open + * @param db The database to close + */ +APU_DECLARE(apr_status_t) apr_sdbm_close(apr_sdbm_t *db); + +/** + * Lock an sdbm database for concurency of multiple operations + * @param db The database to lock + * @param type The lock type + *
+ *           APR_FLOCK_SHARED
+ *           APR_FLOCK_EXCLUSIVE
+ * 
+ * @remark Calls to apr_sdbm_lock may be nested. All apr_sdbm functions + * perform implicit locking. Since an APR_FLOCK_SHARED lock cannot be + * portably promoted to an APR_FLOCK_EXCLUSIVE lock, apr_sdbm_store and + * apr_sdbm_delete calls will fail if an APR_FLOCK_SHARED lock is held. + * The apr_sdbm_lock call requires the database to be opened with the + * APR_SHARELOCK mode value. + */ +APU_DECLARE(apr_status_t) apr_sdbm_lock(apr_sdbm_t *db, int type); + +/** + * Release an sdbm lock previously aquired by apr_sdbm_lock + * @param db The database to unlock + */ +APU_DECLARE(apr_status_t) apr_sdbm_unlock(apr_sdbm_t *db); + +/** + * Fetch an sdbm record value by key + * @param db The database + * @param value The value datum retrieved for this record + * @param key The key datum to find this record + */ +APU_DECLARE(apr_status_t) apr_sdbm_fetch(apr_sdbm_t *db, + apr_sdbm_datum_t *value, + apr_sdbm_datum_t key); + +/** + * Store an sdbm record value by key + * @param db The database + * @param key The key datum to store this record by + * @param value The value datum to store in this record + * @param opt The method used to store the record + *
+ *           APR_SDBM_INSERT     return an error if the record exists
+ *           APR_SDBM_REPLACE    overwrite any existing record for key
+ * 
+ */ +APU_DECLARE(apr_status_t) apr_sdbm_store(apr_sdbm_t *db, apr_sdbm_datum_t key, + apr_sdbm_datum_t value, int opt); + +/** + * Delete an sdbm record value by key + * @param db The database + * @param key The key datum of the record to delete + * @remark It is not an error to delete a non-existent record. + */ +APU_DECLARE(apr_status_t) apr_sdbm_delete(apr_sdbm_t *db, + const apr_sdbm_datum_t key); + +/** + * Retrieve the first record key from a dbm + * @param db The database + * @param key The key datum of the first record + * @remark The keys returned are not ordered. To traverse the list of keys + * for an sdbm opened with APR_SHARELOCK, the caller must use apr_sdbm_lock + * prior to retrieving the first record, and hold the lock until after the + * last call to apr_sdbm_nextkey. + */ +APU_DECLARE(apr_status_t) apr_sdbm_firstkey(apr_sdbm_t *db, apr_sdbm_datum_t *key); + +/** + * Retrieve the next record key from an sdbm + * @param db The database + * @param key The key datum of the next record + */ +APU_DECLARE(apr_status_t) apr_sdbm_nextkey(apr_sdbm_t *db, apr_sdbm_datum_t *key); + +/** + * Returns true if the sdbm database opened for read-only access + * @param db The database to test + */ +APU_DECLARE(int) apr_sdbm_rdonly(apr_sdbm_t *db); +/** @} */ +#endif /* APR_SDBM_H */ diff --git a/c/dependencies/linux/apr/include/apr_sha1.h b/c/dependencies/linux/apr/include/apr_sha1.h new file mode 100644 index 00000000..2a4edf36 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_sha1.h @@ -0,0 +1,121 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* NIST Secure Hash Algorithm + * heavily modified by Uwe Hollerbach uh@alumni.caltech edu + * from Peter C. Gutmann's implementation as found in + * Applied Cryptography by Bruce Schneier + * This code is hereby placed in the public domain + */ + +#ifndef APR_SHA1_H +#define APR_SHA1_H + +#include "apu.h" +#include "apr_general.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_sha1.h + * @brief APR-UTIL SHA1 library + */ + +/** size of the SHA1 DIGEST */ +#define APR_SHA1_DIGESTSIZE 20 + +/** + * Define the Magic String prefix that identifies a password as being + * hashed using our algorithm. + */ +#define APR_SHA1PW_ID "{SHA}" + +/** length of the SHA Password */ +#define APR_SHA1PW_IDLEN 5 + +/** @see apr_sha1_ctx_t */ +typedef struct apr_sha1_ctx_t apr_sha1_ctx_t; + +/** + * SHA1 context structure + */ +struct apr_sha1_ctx_t { + /** message digest */ + apr_uint32_t digest[5]; + /** 64-bit bit counts */ + apr_uint32_t count_lo, count_hi; + /** SHA data buffer */ + apr_uint32_t data[16]; + /** unprocessed amount in data */ + int local; +}; + +/** + * Provide a means to SHA1 crypt/encode a plaintext password in a way which + * makes password file compatible with those commonly use in netscape web + * and ldap installations. + * @param clear The plaintext password + * @param len The length of the plaintext password + * @param out The encrypted/encoded password + * @note SHA1 support is useful for migration purposes, but is less + * secure than Apache's password format, since Apache's (MD5) + * password format uses a random eight character salt to generate + * one of many possible hashes for the same password. Netscape + * uses plain SHA1 without a salt, so the same password + * will always generate the same hash, making it easier + * to break since the search space is smaller. + */ +APU_DECLARE(void) apr_sha1_base64(const char *clear, int len, char *out); + +/** + * Initialize the SHA digest + * @param context The SHA context to initialize + */ +APU_DECLARE(void) apr_sha1_init(apr_sha1_ctx_t *context); + +/** + * Update the SHA digest + * @param context The SHA1 context to update + * @param input The buffer to add to the SHA digest + * @param inputLen The length of the input buffer + */ +APU_DECLARE(void) apr_sha1_update(apr_sha1_ctx_t *context, const char *input, + unsigned int inputLen); + +/** + * Update the SHA digest with binary data + * @param context The SHA1 context to update + * @param input The buffer to add to the SHA digest + * @param inputLen The length of the input buffer + */ +APU_DECLARE(void) apr_sha1_update_binary(apr_sha1_ctx_t *context, + const unsigned char *input, + unsigned int inputLen); + +/** + * Finish computing the SHA digest + * @param digest the output buffer in which to store the digest + * @param context The context to finalize + */ +APU_DECLARE(void) apr_sha1_final(unsigned char digest[APR_SHA1_DIGESTSIZE], + apr_sha1_ctx_t *context); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_SHA1_H */ diff --git a/c/dependencies/linux/apr/include/apr_shm.h b/c/dependencies/linux/apr/include/apr_shm.h new file mode 100644 index 00000000..635c654b --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_shm.h @@ -0,0 +1,229 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_SHM_H +#define APR_SHM_H + +/** + * @file apr_shm.h + * @brief APR Shared Memory Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_perms_set.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_shm Shared Memory Routines + * @ingroup APR + * @{ + */ + +/** + * Private, platform-specific data struture representing a shared memory + * segment. + */ +typedef struct apr_shm_t apr_shm_t; + +/** + * Create and make accessible a shared memory segment with default + * properties. + * @param m The shared memory structure to create. + * @param reqsize The desired size of the segment. + * @param filename The file to use for shared memory on platforms that + * require it. + * @param pool the pool from which to allocate the shared memory + * structure. + * @remark A note about Anonymous vs. Named shared memory segments: + * Not all plaforms support anonymous shared memory segments, but in + * some cases it is prefered over other types of shared memory + * implementations. Passing a NULL 'file' parameter to this function + * will cause the subsystem to use anonymous shared memory segments. + * If such a system is not available, APR_ENOTIMPL is returned. + * @remark A note about allocation sizes: + * On some platforms it is necessary to store some metainformation + * about the segment within the actual segment. In order to supply + * the caller with the requested size it may be necessary for the + * implementation to request a slightly greater segment length + * from the subsystem. In all cases, the apr_shm_baseaddr_get() + * function will return the first usable byte of memory. + * + */ +APR_DECLARE(apr_status_t) apr_shm_create(apr_shm_t **m, + apr_size_t reqsize, + const char *filename, + apr_pool_t *pool); + +/** + * Special processing flags for apr_shm_create_ex() and apr_shm_attach_ex(). + */ +#define APR_SHM_NS_LOCAL 1 /* Create or attach to named shared memory + * segment in the "Local" namespace on + * Windows. (Ignored on other platforms.) + * By default, the "Global" namespace is + * used for privileged processes and the + * "Local" namespace is used otherwise. + */ +#define APR_SHM_NS_GLOBAL 2 /* Create or attach to named shared memory + * segment in the "Global" namespace on + * Windows. (Ignored on other platforms.) + */ + +/** + * Create and make accessible a shared memory segment with platform- + * specific processing. + * @param m The shared memory structure to create. + * @param reqsize The desired size of the segment. + * @param filename The file to use for shared memory on platforms that + * require it. + * @param pool the pool from which to allocate the shared memory + * structure. + * @param flags mask of APR_SHM_* (defined above) + * @remark A note about Anonymous vs. Named shared memory segments: + * Not all plaforms support anonymous shared memory segments, but in + * some cases it is prefered over other types of shared memory + * implementations. Passing a NULL 'file' parameter to this function + * will cause the subsystem to use anonymous shared memory segments. + * If such a system is not available, APR_ENOTIMPL is returned. + * @remark A note about allocation sizes: + * On some platforms it is necessary to store some metainformation + * about the segment within the actual segment. In order to supply + * the caller with the requested size it may be necessary for the + * implementation to request a slightly greater segment length + * from the subsystem. In all cases, the apr_shm_baseaddr_get() + * function will return the first usable byte of memory. + * + */ +APR_DECLARE(apr_status_t) apr_shm_create_ex(apr_shm_t **m, + apr_size_t reqsize, + const char *filename, + apr_pool_t *pool, + apr_int32_t flags); + +/** + * Remove named resource associated with a shared memory segment, + * preventing attachments to the resource, but not destroying it. + * @param filename The filename associated with shared-memory segment which + * needs to be removed + * @param pool The pool used for file operations + * @remark This function is only supported on platforms which support + * name-based shared memory segments, and will return APR_ENOTIMPL on + * platforms without such support. Removing the file while the shm + * is in use is not entirely portable, caller may use this to enhance + * obscurity of the resource, but be prepared for the call to fail, + * and for concurrent attempts to create a resource of the same name + * to also fail. The pool cleanup of apr_shm_create (apr_shm_destroy) + * also removes the named resource. + */ +APR_DECLARE(apr_status_t) apr_shm_remove(const char *filename, + apr_pool_t *pool); + +/** + * Delete named resource associated with a shared memory segment, + * preventing attachments to the resource. + * @param m The shared memory segment structure to delete. + * @remark This function is only supported on platforms which support + * name-based shared memory segments, and will return APR_ENOTIMPL on + * platforms without such support. Removing the file while the shm + * is in use is not entirely portable, caller may use this to enhance + * obscurity of the resource, but be prepared for the call to fail, + * and for concurrent attempts to create a resource of the same name + * to also fail. The pool cleanup of apr_shm_create (apr_shm_destroy) + * also removes the named resource. + */ +APR_DECLARE(apr_status_t) apr_shm_delete(apr_shm_t *m); + +/** + * Destroy a shared memory segment and associated memory. + * @param m The shared memory segment structure to destroy. + */ +APR_DECLARE(apr_status_t) apr_shm_destroy(apr_shm_t *m); + +/** + * Attach to a shared memory segment that was created + * by another process. + * @param m The shared memory structure to create. + * @param filename The file used to create the original segment. + * (This MUST match the original filename.) + * @param pool the pool from which to allocate the shared memory + * structure for this process. + */ +APR_DECLARE(apr_status_t) apr_shm_attach(apr_shm_t **m, + const char *filename, + apr_pool_t *pool); + +/** + * Attach to a shared memory segment that was created + * by another process, with platform-specific processing. + * @param m The shared memory structure to create. + * @param filename The file used to create the original segment. + * (This MUST match the original filename.) + * @param pool the pool from which to allocate the shared memory + * structure for this process. + * @param flags mask of APR_SHM_* (defined above) + */ +APR_DECLARE(apr_status_t) apr_shm_attach_ex(apr_shm_t **m, + const char *filename, + apr_pool_t *pool, + apr_int32_t flags); + +/** + * Detach from a shared memory segment without destroying it. + * @param m The shared memory structure representing the segment + * to detach from. + */ +APR_DECLARE(apr_status_t) apr_shm_detach(apr_shm_t *m); + +/** + * Retrieve the base address of the shared memory segment. + * NOTE: This address is only usable within the callers address + * space, since this API does not guarantee that other attaching + * processes will maintain the same address mapping. + * @param m The shared memory segment from which to retrieve + * the base address. + * @return address, aligned by APR_ALIGN_DEFAULT. + */ +APR_DECLARE(void *) apr_shm_baseaddr_get(const apr_shm_t *m); + +/** + * Retrieve the length of a shared memory segment in bytes. + * @param m The shared memory segment from which to retrieve + * the segment length. + */ +APR_DECLARE(apr_size_t) apr_shm_size_get(const apr_shm_t *m); + +/** + * Set shared memory permissions. + */ +APR_PERMS_SET_IMPLEMENT(shm); + +/** + * Get the pool used by this shared memory segment. + */ +APR_POOL_DECLARE_ACCESSOR(shm); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_SHM_T */ diff --git a/c/dependencies/linux/apr/include/apr_signal.h b/c/dependencies/linux/apr/include/apr_signal.h new file mode 100644 index 00000000..20631333 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_signal.h @@ -0,0 +1,109 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_SIGNAL_H +#define APR_SIGNAL_H + +/** + * @file apr_signal.h + * @brief APR Signal Handling + */ + +#include "apr.h" +#include "apr_pools.h" + +#if APR_HAVE_SIGNAL_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_signal Signal Handling + * @ingroup APR + * @{ + */ + +#if APR_HAVE_SIGACTION || defined(DOXYGEN) + +#if defined(DARWIN) && !defined(__cplusplus) && !defined(_ANSI_SOURCE) +/* work around Darwin header file bugs + * http://www.opensource.apple.com/bugs/X/BSD%20Kernel/2657228.html + */ +#undef SIG_DFL +#undef SIG_IGN +#undef SIG_ERR +#define SIG_DFL (void (*)(int))0 +#define SIG_IGN (void (*)(int))1 +#define SIG_ERR (void (*)(int))-1 +#endif + +/** Function prototype for signal handlers */ +typedef void apr_sigfunc_t(int); + +/** + * Set the signal handler function for a given signal + * @param signo The signal (eg... SIGWINCH) + * @param func the function to get called + */ +APR_DECLARE(apr_sigfunc_t *) apr_signal(int signo, apr_sigfunc_t * func); + +#if defined(SIG_IGN) && !defined(SIG_ERR) +#define SIG_ERR ((apr_sigfunc_t *) -1) +#endif + +#else /* !APR_HAVE_SIGACTION */ +#define apr_signal(a, b) signal(a, b) +#endif + + +/** + * Get the description for a specific signal number + * @param signum The signal number + * @return The description of the signal + */ +APR_DECLARE(const char *) apr_signal_description_get(int signum); + +/** + * APR-private function for initializing the signal package + * @internal + * @param pglobal The internal, global pool + */ +void apr_signal_init(apr_pool_t *pglobal); + +/** + * Block the delivery of a particular signal + * @param signum The signal number + * @return status + */ +APR_DECLARE(apr_status_t) apr_signal_block(int signum); + +/** + * Enable the delivery of a particular signal + * @param signum The signal number + * @return status + */ +APR_DECLARE(apr_status_t) apr_signal_unblock(int signum); + +/** @} */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* APR_SIGNAL_H */ diff --git a/c/dependencies/linux/apr/include/apr_siphash.h b/c/dependencies/linux/apr/include/apr_siphash.h new file mode 100644 index 00000000..42aa8874 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_siphash.h @@ -0,0 +1,148 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + SipHash reference C implementation + Copyright (c) 2012-2014 Jean-Philippe Aumasson + + Copyright (c) 2012-2014 Daniel J. Bernstein + To the extent possible under law, the author(s) have dedicated all copyright + and related and neighboring rights to this software to the public domain + worldwide. This software is distributed without any warranty. + You should have received a copy of the CC0 Public Domain Dedication along + with this software. If not, see + . + */ + +#ifndef APR_SIPHASH_H +#define APR_SIPHASH_H + +#include "apr.h" +#include "apu.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_siphash.h + * @brief APR-UTIL siphash library + * "SipHash-c-d is a family of pseudorandom functions (a.k.a. keyed + * hash functions) optimized for speed on short messages", designed by + * Jean-Philippe Aumasson and Daniel J. Bernstein. It generates a 64bit + * hash (or MAC) from the message and a 128bit key. + * See http://cr.yp.to/siphash/siphash-20120620.pdf for the details, + * c is the number of compression rounds, d the number of finalization + * rounds; we also define fast implementations for c = 2 with d = 4 (aka + * siphash-2-4), and c = 4 with d = 8 (aka siphash-4-8), as recommended + * parameters per the authors. + */ + +/** size of the siphash digest */ +#define APR_SIPHASH_DSIZE 8 + +/** size of the siphash key */ +#define APR_SIPHASH_KSIZE 16 + + +/** + * @brief Computes SipHash-c-d, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key. + * @param src The message + * @param len The length of the message + * @param key The secret key + * @param c The number of compression rounds + * @param d The number of finalization rounds + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(apr_uint64_t) apr_siphash(const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE], + unsigned int c, unsigned int d); + +/** + * @brief Computes SipHash-c-d, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key, into a possibly + * unaligned buffer (using the little endian representation as defined by the + * authors for interoperabilty) usable as a MAC. + * @param out The output buffer (or MAC) + * @param src The message + * @param len The length of the message + * @param key The secret key + * @param c The number of compression rounds + * @param d The number of finalization rounds + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(void) apr_siphash_auth(unsigned char out[APR_SIPHASH_DSIZE], + const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE], + unsigned int c, unsigned int d); + +/** + * @brief Computes SipHash-2-4, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key. + * @param src The message to hash + * @param len The length of the message + * @param key The secret key + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(apr_uint64_t) apr_siphash24(const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE]); + +/** + * @brief Computes SipHash-2-4, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key, into a possibly + * unaligned buffer (using the little endian representation as defined by the + * authors for interoperabilty) usable as a MAC. + * @param out The output buffer (or MAC) + * @param src The message + * @param len The length of the message + * @param key The secret key + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(void) apr_siphash24_auth(unsigned char out[APR_SIPHASH_DSIZE], + const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE]); + +/** + * @brief Computes SipHash-4-8, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key. + * @param src The message + * @param len The length of the message + * @param key The secret key + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(apr_uint64_t) apr_siphash48(const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE]); + +/** + * @brief Computes SipHash-4-8, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key, into a possibly + * unaligned buffer (using the little endian representation as defined by the + * authors for interoperabilty) usable as a MAC. + * @param out The output buffer (or MAC) + * @param src The message + * @param len The length of the message + * @param key The secret key + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(void) apr_siphash48_auth(unsigned char out[APR_SIPHASH_DSIZE], + const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE]); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_SIPHASH_H */ diff --git a/c/dependencies/linux/apr/include/apr_skiplist.h b/c/dependencies/linux/apr/include/apr_skiplist.h new file mode 100644 index 00000000..eeab10bf --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_skiplist.h @@ -0,0 +1,381 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_SKIPLIST_H +#define APR_SKIPLIST_H +/** + * @file apr_skiplist.h + * @brief APR skip list implementation + */ + +#include "apr.h" +#include "apr_portable.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_skiplist Skip list implementation + * Refer to http://en.wikipedia.org/wiki/Skip_list for information + * about the purpose of and ideas behind skip lists. + * @ingroup APR + * @{ + */ + +/** + * apr_skiplist_compare is the function type that must be implemented + * per object type that is used in a skip list for comparisons to maintain + * order + * */ +typedef int (*apr_skiplist_compare) (void *, void *); + +/** + * apr_skiplist_freefunc is the function type that must be implemented + * to handle elements as they are removed from a skip list. + */ +typedef void (*apr_skiplist_freefunc) (void *); + +/** Opaque structure used to represent the skip list */ +struct apr_skiplist; +/** Opaque structure used to represent the skip list */ +typedef struct apr_skiplist apr_skiplist; + +/** + * Opaque structure used to represent abstract nodes in the skip list + * (an abstraction above the raw elements which are collected in the + * skip list). + */ +struct apr_skiplistnode; +/** Opaque structure */ +typedef struct apr_skiplistnode apr_skiplistnode; + +/** + * Allocate memory using the same mechanism as the skip list. + * @param sl The skip list + * @param size The amount to allocate + * @remark If a pool was provided to apr_skiplist_init(), memory will + * be allocated from the pool or from a free list maintained with + * the skip list. Otherwise, memory will be allocated using the + * C standard library heap functions. + */ +APR_DECLARE(void *) apr_skiplist_alloc(apr_skiplist *sl, size_t size); + +/** + * Free memory using the same mechanism as the skip list. + * @param sl The skip list + * @param mem The object to free + * @remark If a pool was provided to apr_skiplist_init(), memory will + * be added to a free list maintained with the skip list and be available + * to operations on the skip list or to other calls to apr_skiplist_alloc(). + * Otherwise, memory will be freed using the C standard library heap + * functions. + */ +APR_DECLARE(void) apr_skiplist_free(apr_skiplist *sl, void *mem); + +/** + * Allocate a new skip list + * @param sl The pointer in which to return the newly created skip list + * @param p The pool from which to allocate the skip list (optional). + * @remark Unlike most APR functions, a pool is optional. If no pool + * is provided, the C standard library heap functions will be used instead. + */ +APR_DECLARE(apr_status_t) apr_skiplist_init(apr_skiplist **sl, apr_pool_t *p); + +/** + * Set the comparison functions to be used for searching the skip list. + * @param sl The skip list + * @param XXX1 FIXME + * @param XXX2 FIXME + * + * @remark If existing comparison functions are being replaced, the index + * will be replaced during this call. That is a potentially expensive + * operation. + */ +APR_DECLARE(void) apr_skiplist_set_compare(apr_skiplist *sl, apr_skiplist_compare XXX1, + apr_skiplist_compare XXX2); + +/** + * Set the indexing functions to the specified comparison functions and + * rebuild the index. + * @param sl The skip list + * @param XXX1 FIXME + * @param XXX2 FIXME + * + * @remark If an index already exists, it will not be replaced and the + * comparison functions will not be changed. + */ +APR_DECLARE(void) apr_skiplist_add_index(apr_skiplist *sl, apr_skiplist_compare XXX1, + apr_skiplist_compare XXX2); + +/** + * Return the list maintained by the skip list abstraction. + * @param sl The skip list + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_getlist(apr_skiplist *sl); + +/** + * Return the next matching element in the skip list using the specified + * comparison function. + * @param sl The skip list + * @param data The value to search for + * @param iter A pointer to the returned skip list node representing the element + * found + * @param func The comparison function to use + */ +APR_DECLARE(void *) apr_skiplist_find_compare(apr_skiplist *sl, + void *data, + apr_skiplistnode **iter, + apr_skiplist_compare func); + +/** + * Return the next matching element in the skip list using the current comparison + * function. + * @param sl The skip list + * @param data The value to search for + * @param iter A pointer to the returned skip list node representing the element + * found + */ +APR_DECLARE(void *) apr_skiplist_find(apr_skiplist *sl, void *data, apr_skiplistnode **iter); + +/** + * Return the last matching element in the skip list using the specified + * comparison function. + * @param sl The skip list + * @param data The value to search for + * @param iter A pointer to the returned skip list node representing the element + * found + * @param comp The comparison function to use + */ +APR_DECLARE(void *) apr_skiplist_last_compare(apr_skiplist *sl, void *data, + apr_skiplistnode **iter, + apr_skiplist_compare comp); + +/** + * Return the last matching element in the skip list using the current comparison + * function. + * @param sl The skip list + * @param data The value to search for + * @param iter A pointer to the returned skip list node representing the element + * found + */ +APR_DECLARE(void *) apr_skiplist_last(apr_skiplist *sl, void *data, + apr_skiplistnode **iter); + +/** + * Return the next element in the skip list. + * @param sl The skip list + * @param iter On entry, a pointer to the skip list node to start with; on return, + * a pointer to the skip list node representing the element returned + * @remark If iter points to a NULL value on entry, NULL will be returned. + */ +APR_DECLARE(void *) apr_skiplist_next(apr_skiplist *sl, apr_skiplistnode **iter); + +/** + * Return the previous element in the skip list. + * @param sl The skip list + * @param iter On entry, a pointer to the skip list node to start with; on return, + * a pointer to the skip list node representing the element returned + * @remark If iter points to a NULL value on entry, NULL will be returned. + */ +APR_DECLARE(void *) apr_skiplist_previous(apr_skiplist *sl, apr_skiplistnode **iter); + +/** + * Return the element of the skip list node + * @param iter The skip list node + */ +APR_DECLARE(void *) apr_skiplist_element(apr_skiplistnode *iter); + +/** + * Insert an element into the skip list using the specified comparison function + * if it does not already exist. + * @param sl The skip list + * @param data The element to insert + * @param comp The comparison function to use for placement into the skip list + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_insert_compare(apr_skiplist *sl, + void *data, apr_skiplist_compare comp); + +/** + * Insert an element into the skip list using the existing comparison function + * if it does not already exist. + * @param sl The skip list + * @param data The element to insert + * @remark If no comparison function has been set for the skip list, the element + * will not be inserted and NULL will be returned. + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_insert(apr_skiplist* sl, void *data); + +/** + * Add an element into the skip list using the specified comparison function + * allowing for duplicates. + * @param sl The skip list + * @param data The element to add + * @param comp The comparison function to use for placement into the skip list + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_add_compare(apr_skiplist *sl, + void *data, apr_skiplist_compare comp); + +/** + * Add an element into the skip list using the existing comparison function + * allowing for duplicates. + * @param sl The skip list + * @param data The element to insert + * @remark If no comparison function has been set for the skip list, the element + * will not be inserted and NULL will be returned. + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_add(apr_skiplist* sl, void *data); + +/** + * Add an element into the skip list using the specified comparison function + * removing the existing duplicates. + * @param sl The skip list + * @param data The element to insert + * @param comp The comparison function to use for placement into the skip list + * @param myfree A function to be called for each removed duplicate + * @remark If no comparison function has been set for the skip list, the element + * will not be inserted, none will be replaced, and NULL will be returned. + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_replace_compare(apr_skiplist *sl, + void *data, apr_skiplist_freefunc myfree, + apr_skiplist_compare comp); + +/** + * Add an element into the skip list using the existing comparison function + * removing the existing duplicates. + * @param sl The skip list + * @param data The element to insert + * @param myfree A function to be called for each removed duplicate + * @remark If no comparison function has been set for the skip list, the element + * will not be inserted, none will be replaced, and NULL will be returned. + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_replace(apr_skiplist *sl, + void *data, apr_skiplist_freefunc myfree); + +/** + * Remove a node from the skip list. + * @param sl The skip list + * @param iter The skip list node to remove + * @param myfree A function to be called for the removed element + */ +APR_DECLARE(int) apr_skiplist_remove_node(apr_skiplist *sl, + apr_skiplistnode *iter, + apr_skiplist_freefunc myfree); + +/** + * Remove an element from the skip list using the specified comparison function for + * locating the element. In the case of duplicates, the 1st entry will be removed. + * @param sl The skip list + * @param data The element to remove + * @param myfree A function to be called for each removed element + * @param comp The comparison function to use for placement into the skip list + * @remark If the element is not found, 0 will be returned. Otherwise, the heightXXX + * will be returned. + */ +APR_DECLARE(int) apr_skiplist_remove_compare(apr_skiplist *sl, void *data, + apr_skiplist_freefunc myfree, apr_skiplist_compare comp); + +/** + * Remove an element from the skip list using the existing comparison function for + * locating the element. In the case of duplicates, the 1st entry will be removed. + * @param sl The skip list + * @param data The element to remove + * @param myfree A function to be called for each removed element + * @remark If the element is not found, 0 will be returned. Otherwise, the heightXXX + * will be returned. + * @remark If no comparison function has been set for the skip list, the element + * will not be removed and 0 will be returned. + */ +APR_DECLARE(int) apr_skiplist_remove(apr_skiplist *sl, void *data, apr_skiplist_freefunc myfree); + +/** + * Remove all elements from the skip list. + * @param sl The skip list + * @param myfree A function to be called for each removed element + */ +APR_DECLARE(void) apr_skiplist_remove_all(apr_skiplist *sl, apr_skiplist_freefunc myfree); + +/** + * Remove each element from the skip list. + * @param sl The skip list + * @param myfree A function to be called for each removed element + */ +APR_DECLARE(void) apr_skiplist_destroy(apr_skiplist *sl, apr_skiplist_freefunc myfree); + +/** + * Return the first element in the skip list, removing the element from the skip list. + * @param sl The skip list + * @param myfree A function to be called for the removed element + * @remark NULL will be returned if there are no elements + */ +APR_DECLARE(void *) apr_skiplist_pop(apr_skiplist *sl, apr_skiplist_freefunc myfree); + +/** + * Return the first element in the skip list, leaving the element in the skip list. + * @param sl The skip list + * @remark NULL will be returned if there are no elements + */ +APR_DECLARE(void *) apr_skiplist_peek(apr_skiplist *sl); + +/** + * Return the size of the list (number of elements), in O(1). + * @param sl The skip list + */ +APR_DECLARE(size_t) apr_skiplist_size(const apr_skiplist *sl); + +/** + * Return the height of the list (number of skip paths), in O(1). + * @param sl The skip list + */ +APR_DECLARE(int) apr_skiplist_height(const apr_skiplist *sl); + +/** + * Return the predefined maximum height of the skip list. + * @param sl The skip list + */ +APR_DECLARE(int) apr_skiplist_preheight(const apr_skiplist *sl); + +/** + * Set a predefined maximum height for the skip list. + * @param sl The skip list + * @param to The preheight to set, or a nul/negative value to disable. + * @remark When a preheight is used, the height of each inserted element is + * computed randomly up to this preheight instead of the current skip list's + * height plus one used by the default implementation. Using a preheight can + * probably ensure more fairness with long living elements (since with an + * adaptative height, former elements may have been created with a low height, + * hence a longest path to reach them while the skip list grows). On the other + * hand, the default behaviour (preheight <= 0) with a growing and decreasing + * maximum height is more adaptative/suitable for short living values. + * @note Should be called before any insertion/add. + */ +APR_DECLARE(void) apr_skiplist_set_preheight(apr_skiplist *sl, int to); + +/** + * Merge two skip lists. XXX SEMANTICS + * @param sl1 One of two skip lists to be merged + * @param sl2 The other of two skip lists to be merged + */ +APR_DECLARE(apr_skiplist *) apr_skiplist_merge(apr_skiplist *sl1, apr_skiplist *sl2); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_SKIPLIST_H */ diff --git a/c/dependencies/linux/apr/include/apr_strings.h b/c/dependencies/linux/apr/include/apr_strings.h new file mode 100644 index 00000000..d5f8719d --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_strings.h @@ -0,0 +1,380 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* Portions of this file are covered by */ +/* -*- mode: c; c-file-style: "k&r" -*- + + strnatcmp.c -- Perform 'natural order' comparisons of strings in C. + Copyright (C) 2000 by Martin Pool + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef APR_STRINGS_H +#define APR_STRINGS_H + +/** + * @file apr_strings.h + * @brief APR Strings library + */ + +#include "apr.h" +#include "apr_errno.h" +#include "apr_pools.h" +#define APR_WANT_IOVEC +#include "apr_want.h" + +#if APR_HAVE_STDARG_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_strings String routines + * @ingroup APR + * @{ + */ + +/** + * Do a natural order comparison of two strings. + * @param a The first string to compare + * @param b The second string to compare + * @return Either <0, 0, or >0. If the first string is less than the second + * this returns <0, if they are equivalent it returns 0, and if the + * first string is greater than second string it retuns >0. + */ +APR_DECLARE(int) apr_strnatcmp(char const *a, char const *b); + +/** + * Do a natural order comparison of two strings ignoring the case of the + * strings. + * @param a The first string to compare + * @param b The second string to compare + * @return Either <0, 0, or >0. If the first string is less than the second + * this returns <0, if they are equivalent it returns 0, and if the + * first string is greater than second string it retuns >0. + */ +APR_DECLARE(int) apr_strnatcasecmp(char const *a, char const *b); + +/** + * duplicate a string into memory allocated out of a pool + * @param p The pool to allocate out of + * @param s The string to duplicate + * @return The new string or NULL if s == NULL + */ +APR_DECLARE(char *) apr_pstrdup(apr_pool_t *p, const char *s); + +/** + * Create a null-terminated string by making a copy of a sequence + * of characters and appending a null byte + * @param p The pool to allocate out of + * @param s The block of characters to duplicate + * @param n The number of characters to duplicate + * @return The new string or NULL if s == NULL + * @remark This is a faster alternative to apr_pstrndup(), for use + * when you know that the string being duplicated really + * has 'n' or more characters. If the string might contain + * fewer characters, use apr_pstrndup(). + */ +APR_DECLARE(char *) apr_pstrmemdup(apr_pool_t *p, const char *s, apr_size_t n) +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) + __attribute__((alloc_size(3))) +#endif + ; + +/** + * Duplicate at most n characters of a string into memory allocated + * out of a pool; the new string will be NUL-terminated + * @param p The pool to allocate out of + * @param s The string to duplicate + * @param n The maximum number of characters to duplicate + * @return The new string or NULL if s == NULL + * @remark The amount of memory allocated from the pool is the length + * of the returned string including the NUL terminator + */ +APR_DECLARE(char *) apr_pstrndup(apr_pool_t *p, const char *s, apr_size_t n); + +/** + * Duplicate a block of memory. + * + * @param p The pool to allocate from + * @param m The memory to duplicate + * @param n The number of bytes to duplicate + * @return The new block of memory or NULL if m == NULL + */ +APR_DECLARE(void *) apr_pmemdup(apr_pool_t *p, const void *m, apr_size_t n) +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) + __attribute__((alloc_size(3))) +#endif + ; + +/** + * Concatenate multiple strings, allocating memory out a pool + * @param p The pool to allocate out of + * @param ... The strings to concatenate. The final string must be NULL + * @return The new string + */ +APR_DECLARE_NONSTD(char *) apr_pstrcat(apr_pool_t *p, ...) +#if defined(__GNUC__) && __GNUC__ >= 4 + __attribute__((sentinel)) +#endif + ; + +/** + * Concatenate multiple strings specified in a writev-style vector + * @param p The pool from which to allocate + * @param vec The strings to concatenate + * @param nvec The number of strings to concatenate + * @param nbytes (output) strlen of new string (pass in NULL to omit) + * @return The new string + */ +APR_DECLARE(char *) apr_pstrcatv(apr_pool_t *p, const struct iovec *vec, + apr_size_t nvec, apr_size_t *nbytes); + +/** + * printf-style style printing routine. The data is output to a string + * allocated from a pool + * @param p The pool to allocate out of + * @param fmt The format of the string + * @param ap The arguments to use while printing the data + * @return The new string + */ +APR_DECLARE(char *) apr_pvsprintf(apr_pool_t *p, const char *fmt, va_list ap); + +/** + * printf-style style printing routine. The data is output to a string + * allocated from a pool + * @param p The pool to allocate out of + * @param fmt The format of the string + * @param ... The arguments to use while printing the data + * @return The new string + */ +APR_DECLARE_NONSTD(char *) apr_psprintf(apr_pool_t *p, const char *fmt, ...) + __attribute__((format(printf,2,3))); + +/** + * Copy up to dst_size characters from src to dst; does not copy + * past a NUL terminator in src, but always terminates dst with a NUL + * regardless. + * @param dst The destination string + * @param src The source string + * @param dst_size The space available in dst; dst always receives + * NUL termination, so if src is longer than + * dst_size, the actual number of characters copied is + * dst_size - 1. + * @return Pointer to the NUL terminator of the destination string, dst + * @remark + *
+ * Note the differences between this function and strncpy():
+ *  1) strncpy() doesn't always NUL terminate; apr_cpystrn() does.
+ *  2) strncpy() pads the destination string with NULs, which is often 
+ *     unnecessary; apr_cpystrn() does not.
+ *  3) strncpy() returns a pointer to the beginning of the dst string;
+ *     apr_cpystrn() returns a pointer to the NUL terminator of dst, 
+ *     to allow a check for truncation.
+ * 
+ */ +APR_DECLARE(char *) apr_cpystrn(char *dst, const char *src, + apr_size_t dst_size); + +/** + * Remove all whitespace from a string + * @param dest The destination string. It is okay to modify the string + * in place. Namely dest == src + * @param src The string to rid the spaces from. + * @return A pointer to the destination string's null terminator. + */ +APR_DECLARE(char *) apr_collapse_spaces(char *dest, const char *src); + +/** + * Convert the arguments to a program from one string to an array of + * strings terminated by a NULL pointer + * @param arg_str The arguments to convert + * @param argv_out Output location. This is a pointer to an array of strings. + * @param token_context Pool to use. + */ +APR_DECLARE(apr_status_t) apr_tokenize_to_argv(const char *arg_str, + char ***argv_out, + apr_pool_t *token_context); + +/** + * Split a string into separate null-terminated tokens. The tokens are + * delimited in the string by one or more characters from the sep + * argument. + * @param str The string to separate; this should be specified on the + * first call to apr_strtok() for a given string, and NULL + * on subsequent calls. + * @param sep The set of delimiters + * @param last State saved by apr_strtok() between calls. + * @return The next token from the string + * @note the 'last' state points to the trailing NUL char of the final + * token, otherwise it points to the character following the current + * token (all successive or empty occurances of sep are skiped on the + * subsequent call to apr_strtok). Therefore it is possible to avoid + * a strlen() determination, with the following logic; + * toklen = last - retval; if (*last) --toklen; + */ +APR_DECLARE(char *) apr_strtok(char *str, const char *sep, char **last); + +/** + * @defgroup APR_Strings_Snprintf snprintf implementations + * @warning + * These are snprintf implementations based on apr_vformatter(). + * + * Note that various standards and implementations disagree on the return + * value of snprintf, and side-effects due to %n in the formatting string. + * apr_snprintf (and apr_vsnprintf) behaves as follows: + * + * Process the format string until the entire string is exhausted, or + * the buffer fills. If the buffer fills then stop processing immediately + * (so no further %n arguments are processed), and return the buffer + * length. In all cases the buffer is NUL terminated. It will return the + * number of characters inserted into the buffer, not including the + * terminating NUL. As a special case, if len is 0, apr_snprintf will + * return the number of characters that would have been inserted if + * the buffer had been infinite (in this case, *buffer can be NULL) + * + * In no event does apr_snprintf return a negative number. + * @{ + */ + +/** + * snprintf routine based on apr_vformatter. This means it understands the + * same extensions. + * @param buf The buffer to write to + * @param len The size of the buffer + * @param format The format string + * @param ... The arguments to use to fill out the format string. + */ +APR_DECLARE_NONSTD(int) apr_snprintf(char *buf, apr_size_t len, + const char *format, ...) + __attribute__((format(printf,3,4))); + +/** + * vsnprintf routine based on apr_vformatter. This means it understands the + * same extensions. + * @param buf The buffer to write to + * @param len The size of the buffer + * @param format The format string + * @param ap The arguments to use to fill out the format string. + */ +APR_DECLARE(int) apr_vsnprintf(char *buf, apr_size_t len, const char *format, + va_list ap); +/** @} */ + +/** + * create a string representation of an int, allocated from a pool + * @param p The pool from which to allocate + * @param n The number to format + * @return The string representation of the number + */ +APR_DECLARE(char *) apr_itoa(apr_pool_t *p, int n); + +/** + * create a string representation of a long, allocated from a pool + * @param p The pool from which to allocate + * @param n The number to format + * @return The string representation of the number + */ +APR_DECLARE(char *) apr_ltoa(apr_pool_t *p, long n); + +/** + * create a string representation of an apr_off_t, allocated from a pool + * @param p The pool from which to allocate + * @param n The number to format + * @return The string representation of the number + */ +APR_DECLARE(char *) apr_off_t_toa(apr_pool_t *p, apr_off_t n); + +/** + * Convert a numeric string into an apr_off_t numeric value. + * @param offset The value of the parsed string. + * @param buf The string to parse. It may contain optional whitespace, + * followed by an optional '+' (positive, default) or '-' (negative) + * character, followed by an optional '0x' prefix if base is 0 or 16, + * followed by numeric digits appropriate for base. + * @param end A pointer to the end of the valid character in buf. If + * not NULL, it is set to the first invalid character in buf. + * @param base A numeric base in the range between 2 and 36 inclusive, + * or 0. If base is zero, buf will be treated as base ten unless its + * digits are prefixed with '0x', in which case it will be treated as + * base 16. + * @bug *end breaks type safety; where *buf is const, *end needs to be + * declared as const in APR 2.0 + */ +APR_DECLARE(apr_status_t) apr_strtoff(apr_off_t *offset, const char *buf, + char **end, int base); + +/** + * parse a numeric string into a 64-bit numeric value + * @param buf The string to parse. It may contain optional whitespace, + * followed by an optional '+' (positive, default) or '-' (negative) + * character, followed by an optional '0x' prefix if base is 0 or 16, + * followed by numeric digits appropriate for base. + * @param end A pointer to the end of the valid character in buf. If + * not NULL, it is set to the first invalid character in buf. + * @param base A numeric base in the range between 2 and 36 inclusive, + * or 0. If base is zero, buf will be treated as base ten unless its + * digits are prefixed with '0x', in which case it will be treated as + * base 16. + * @return The numeric value of the string. On overflow, errno is set + * to ERANGE. On success, errno is set to 0. + */ +APR_DECLARE(apr_int64_t) apr_strtoi64(const char *buf, char **end, int base); + +/** + * parse a base-10 numeric string into a 64-bit numeric value. + * Equivalent to apr_strtoi64(buf, (char**)NULL, 10). + * @param buf The string to parse + * @return The numeric value of the string. On overflow, errno is set + * to ERANGE. On success, errno is set to 0. + */ +APR_DECLARE(apr_int64_t) apr_atoi64(const char *buf); + +/** + * Format a binary size (magnitiudes are 2^10 rather than 10^3) from an apr_off_t, + * as bytes, K, M, T, etc, to a four character compacted human readable string. + * @param size The size to format + * @param buf The 5 byte text buffer (counting the trailing null) + * @return The buf passed to apr_strfsize() + * @remark All negative sizes report ' - ', apr_strfsize only formats positive values. + */ +APR_DECLARE(char *) apr_strfsize(apr_off_t size, char *buf); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_STRINGS_H */ diff --git a/c/dependencies/linux/apr/include/apr_strmatch.h b/c/dependencies/linux/apr/include/apr_strmatch.h new file mode 100644 index 00000000..53fadad5 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_strmatch.h @@ -0,0 +1,81 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_STRMATCH_H +#define APR_STRMATCH_H +/** + * @file apr_strmatch.h + * @brief APR-UTIL string matching routines + */ + +#include "apu.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_StrMatch String matching routines + * @ingroup APR_Util + * @{ + */ + +/** @see apr_strmatch_pattern */ +typedef struct apr_strmatch_pattern apr_strmatch_pattern; + +/** + * Precompiled search pattern + */ +struct apr_strmatch_pattern { + /** Function called to compare */ + const char *(*compare)(const apr_strmatch_pattern *this_pattern, + const char *s, apr_size_t slen); + const char *pattern; /**< Current pattern */ + apr_size_t length; /**< Current length */ + void *context; /**< hook to add precomputed metadata */ +}; + +#if defined(DOXYGEN) +/** + * Search for a precompiled pattern within a string + * @param pattern The pattern + * @param s The string in which to search for the pattern + * @param slen The length of s (excluding null terminator) + * @return A pointer to the first instance of the pattern in s, or + * NULL if not found + */ +APU_DECLARE(const char *) apr_strmatch(const apr_strmatch_pattern *pattern, + const char *s, apr_size_t slen); +#else +#define apr_strmatch(pattern, s, slen) (*((pattern)->compare))((pattern), (s), (slen)) +#endif + +/** + * Precompile a pattern for matching using the Boyer-Moore-Horspool algorithm + * @param p The pool from which to allocate the pattern + * @param s The pattern string + * @param case_sensitive Whether the matching should be case-sensitive + * @return a pointer to the compiled pattern, or NULL if compilation fails + */ +APU_DECLARE(const apr_strmatch_pattern *) apr_strmatch_precompile(apr_pool_t *p, const char *s, int case_sensitive); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_STRMATCH_H */ diff --git a/c/dependencies/linux/apr/include/apr_support.h b/c/dependencies/linux/apr/include/apr_support.h new file mode 100644 index 00000000..79c8cb47 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_support.h @@ -0,0 +1,57 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_SUPPORT_H +#define APR_SUPPORT_H + +/** + * @file apr_support.h + * @brief APR Support functions + */ + +#include "apr.h" +#include "apr_network_io.h" +#include "apr_file_io.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_support Internal APR support functions + * @ingroup APR + * @{ + */ + +/** + * Wait for IO to occur or timeout. + * + * @param f The file to wait on. + * @param s The socket to wait on if @a f is @c NULL. + * @param for_read If non-zero wait for data to be available to read, + * otherwise wait for data to be able to be written. + * @return APR_TIMEUP if we run out of time. + */ +apr_status_t apr_wait_for_io_or_timeout(apr_file_t *f, apr_socket_t *s, + int for_read); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_SUPPORT_H */ diff --git a/c/dependencies/linux/apr/include/apr_tables.h b/c/dependencies/linux/apr/include/apr_tables.h new file mode 100644 index 00000000..27974c0e --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_tables.h @@ -0,0 +1,507 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_TABLES_H +#define APR_TABLES_H + +/** + * @file apr_tables.h + * @brief APR Table library + */ + +#include "apr.h" +#include "apr_pools.h" + +#if APR_HAVE_STDARG_H +#include /* for va_list */ +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_tables Table and Array Functions + * @ingroup APR + * Arrays are used to store data which is referenced sequentially or + * as a stack. Functions are provided to push and pop individual + * elements as well as to operate on the entire array. + * + * Tables are used to store data which can be referenced by key. + * Limited capabilities are provided for tables with multiple elements + * which share a key; while key lookup will return only a single + * element, iteration is available. Additionally, a table can be + * compressed to resolve duplicates. + * + * Both arrays and tables may store string or binary data; some features, + * such as concatenation or merging of elements, work only for string + * data. + * @{ + */ + +/** the table abstract data type */ +typedef struct apr_table_t apr_table_t; + +/** @see apr_array_header_t */ +typedef struct apr_array_header_t apr_array_header_t; + +/** An opaque array type */ +struct apr_array_header_t { + /** The pool the array is allocated out of */ + apr_pool_t *pool; + /** The amount of memory allocated for each element of the array */ + int elt_size; + /** The number of active elements in the array */ + int nelts; + /** The number of elements allocated in the array */ + int nalloc; + /** The elements in the array */ + char *elts; +}; + +/** + * The (opaque) structure for string-content tables. + */ +typedef struct apr_table_entry_t apr_table_entry_t; + +/** The type for each entry in a string-content table */ +struct apr_table_entry_t { + /** The key for the current table entry */ + char *key; /* maybe NULL in future; + * check when iterating thru table_elts + */ + /** The value for the current table entry */ + char *val; + + /** A checksum for the key, for use by the apr_table internals */ + apr_uint32_t key_checksum; +}; + +/** + * Get the elements from a table. + * @param t The table + * @return An array containing the contents of the table + */ +APR_DECLARE(const apr_array_header_t *) apr_table_elts(const apr_table_t *t); + +/** + * Determine if the table is empty (either NULL or having no elements). + * @param t The table to check + * @return True if empty, False otherwise + */ +APR_DECLARE(int) apr_is_empty_table(const apr_table_t *t); + +/** + * Determine if the array is empty (either NULL or having no elements). + * @param a The array to check + * @return True if empty, False otherwise + */ +APR_DECLARE(int) apr_is_empty_array(const apr_array_header_t *a); + +/** + * Create an array. + * @param p The pool to allocate the memory out of + * @param nelts the number of elements in the initial array + * @param elt_size The size of each element in the array. + * @return The new array + */ +APR_DECLARE(apr_array_header_t *) apr_array_make(apr_pool_t *p, + int nelts, int elt_size); + +/** + * Add a new element to an array (as a first-in, last-out stack). + * @param arr The array to add an element to. + * @return Location for the new element in the array. + * @remark If there are no free spots in the array, then this function will + * allocate new space for the new element. + */ +APR_DECLARE(void *) apr_array_push(apr_array_header_t *arr); + +/** A helper macro for accessing a member of an APR array. + * + * @param ary the array + * @param i the index into the array to return + * @param type the type of the objects stored in the array + * + * @return the item at index i + */ +#define APR_ARRAY_IDX(ary,i,type) (((type *)(ary)->elts)[i]) + +/** A helper macro for pushing elements into an APR array. + * + * @param ary the array + * @param type the type of the objects stored in the array + * + * @return the location where the new object should be placed + */ +#define APR_ARRAY_PUSH(ary,type) (*((type *)apr_array_push(ary))) + +/** + * Remove an element from an array (as a first-in, last-out stack). + * @param arr The array to remove an element from. + * @return Location of the element in the array. + * @remark If there are no elements in the array, NULL is returned. + */ +APR_DECLARE(void *) apr_array_pop(apr_array_header_t *arr); + +/** + * Remove all elements from an array. + * @param arr The array to remove all elements from. + * @remark As the underlying storage is allocated from a pool, no + * memory is freed by this operation, but is available for reuse. + */ +APR_DECLARE(void) apr_array_clear(apr_array_header_t *arr); + +/** + * Concatenate two arrays together. + * @param dst The destination array, and the one to go first in the combined + * array + * @param src The source array to add to the destination array + */ +APR_DECLARE(void) apr_array_cat(apr_array_header_t *dst, + const apr_array_header_t *src); + +/** + * Copy the entire array. + * @param p The pool to allocate the copy of the array out of + * @param arr The array to copy + * @return An exact copy of the array passed in + * @remark The alternate apr_array_copy_hdr() copies only the header, and arranges + * for the elements to be copied if (and only if) the code subsequently + * does a push or arraycat. + */ +APR_DECLARE(apr_array_header_t *) apr_array_copy(apr_pool_t *p, + const apr_array_header_t *arr); +/** + * Copy the headers of the array, and arrange for the elements to be copied if + * and only if the code subsequently does a push or arraycat. + * @param p The pool to allocate the copy of the array out of + * @param arr The array to copy + * @return An exact copy of the array passed in + * @remark The alternate apr_array_copy() copies the *entire* array. + */ +APR_DECLARE(apr_array_header_t *) apr_array_copy_hdr(apr_pool_t *p, + const apr_array_header_t *arr); + +/** + * Append one array to the end of another, creating a new array in the process. + * @param p The pool to allocate the new array out of + * @param first The array to put first in the new array. + * @param second The array to put second in the new array. + * @return A new array containing the data from the two arrays passed in. +*/ +APR_DECLARE(apr_array_header_t *) apr_array_append(apr_pool_t *p, + const apr_array_header_t *first, + const apr_array_header_t *second); + +/** + * Generate a new string from the apr_pool_t containing the concatenated + * sequence of substrings referenced as elements within the array. The string + * will be empty if all substrings are empty or null, or if there are no + * elements in the array. If sep is non-NUL, it will be inserted between + * elements as a separator. + * @param p The pool to allocate the string out of + * @param arr The array to generate the string from + * @param sep The separator to use + * @return A string containing all of the data in the array. + */ +APR_DECLARE(char *) apr_array_pstrcat(apr_pool_t *p, + const apr_array_header_t *arr, + const char sep); + +/** + * Make a new table. + * @param p The pool to allocate the pool out of + * @param nelts The number of elements in the initial table. + * @return The new table. + * @warning This table can only store text data + */ +APR_DECLARE(apr_table_t *) apr_table_make(apr_pool_t *p, int nelts); + +/** + * Create a new table and copy another table into it. + * @param p The pool to allocate the new table out of + * @param t The table to copy + * @return A copy of the table passed in + * @warning The table keys and respective values are not copied + */ +APR_DECLARE(apr_table_t *) apr_table_copy(apr_pool_t *p, + const apr_table_t *t); + +/** + * Create a new table whose contents are deep copied from the given + * table. A deep copy operation copies all fields, and makes copies + * of dynamically allocated memory pointed to by the fields. + * @param p The pool to allocate the new table out of + * @param t The table to clone + * @return A deep copy of the table passed in + */ +APR_DECLARE(apr_table_t *) apr_table_clone(apr_pool_t *p, + const apr_table_t *t); + +/** + * Delete all of the elements from a table. + * @param t The table to clear + */ +APR_DECLARE(void) apr_table_clear(apr_table_t *t); + +/** + * Get the value associated with a given key from the table. After this call, + * the data is still in the table. + * @param t The table to search for the key + * @param key The key to search for (case does not matter) + * @return The value associated with the key, or NULL if the key does not exist. + */ +APR_DECLARE(const char *) apr_table_get(const apr_table_t *t, const char *key); + +/** + * Get values associated with a given key from the table. If more than one + * value exists, return a comma separated list of values. After this call, the + * data is still in the table. + * @param p The pool to allocate the combined value from, if necessary + * @param t The table to search for the key + * @param key The key to search for (case does not matter) + * @return The value associated with the key, or NULL if the key does not exist. + */ +APR_DECLARE(const char *) apr_table_getm(apr_pool_t *p, const apr_table_t *t, + const char *key); + +/** + * Add a key/value pair to a table. If another element already exists with the + * same key, this will overwrite the old data. + * @param t The table to add the data to. + * @param key The key to use (case does not matter) + * @param val The value to add + * @remark When adding data, this function makes a copy of both the key and the + * value. + */ +APR_DECLARE(void) apr_table_set(apr_table_t *t, const char *key, + const char *val); + +/** + * Add a key/value pair to a table. If another element already exists with the + * same key, this will overwrite the old data. + * @param t The table to add the data to. + * @param key The key to use (case does not matter) + * @param val The value to add + * @warning When adding data, this function does not make a copy of the key or + * the value, so care should be taken to ensure that the values will + * not change after they have been added.. + */ +APR_DECLARE(void) apr_table_setn(apr_table_t *t, const char *key, + const char *val); + +/** + * Remove data from the table. + * @param t The table to remove data from + * @param key The key of the data being removed (case does not matter) + */ +APR_DECLARE(void) apr_table_unset(apr_table_t *t, const char *key); + +/** + * Add data to a table by merging the value with data that has already been + * stored. The merging is done by concatenating the two values, separated + * by the string ", ". + * @param t The table to search for the data + * @param key The key to merge data for (case does not matter) + * @param val The data to add + * @remark If the key is not found, then this function acts like apr_table_add() + */ +APR_DECLARE(void) apr_table_merge(apr_table_t *t, const char *key, + const char *val); + +/** + * Add data to a table by merging the value with data that has already been + * stored. The merging is done by concatenating the two values, separated + * by the string ", ". + * @param t The table to search for the data + * @param key The key to merge data for (case does not matter) + * @param val The data to add + * @remark If the key is not found, then this function acts like apr_table_addn() + */ +APR_DECLARE(void) apr_table_mergen(apr_table_t *t, const char *key, + const char *val); + +/** + * Add data to a table, regardless of whether there is another element with the + * same key. + * @param t The table to add to + * @param key The key to use + * @param val The value to add. + * @remark When adding data, this function makes a copy of both the key and the + * value. + */ +APR_DECLARE(void) apr_table_add(apr_table_t *t, const char *key, + const char *val); + +/** + * Add data to a table, regardless of whether there is another element with the + * same key. + * @param t The table to add to + * @param key The key to use + * @param val The value to add. + * @remark When adding data, this function does not make a copy of the key or the + * value, so care should be taken to ensure that the values will not + * change after they have been added. + */ +APR_DECLARE(void) apr_table_addn(apr_table_t *t, const char *key, + const char *val); + +/** + * Merge two tables into one new table. + * @param p The pool to use for the new table + * @param overlay The first table to put in the new table + * @param base The table to add at the end of the new table + * @return A new table containing all of the data from the two passed in + */ +APR_DECLARE(apr_table_t *) apr_table_overlay(apr_pool_t *p, + const apr_table_t *overlay, + const apr_table_t *base); + +/** + * Declaration prototype for the iterator callback function of apr_table_do() + * and apr_table_vdo(). + * @param rec The data passed as the first argument to apr_table_[v]do() + * @param key The key from this iteration of the table + * @param value The value from this iteration of the table + * @remark Iteration continues while this callback function returns non-zero. + * To export the callback function for apr_table_[v]do() it must be declared + * in the _NONSTD convention. + * @see apr_table_do @see apr_table_vdo + */ +typedef int (apr_table_do_callback_fn_t)(void *rec, const char *key, + const char *value); + +/** + * Iterate over a table running the provided function once for every + * element in the table. The varargs array must be a list of zero or + * more (char *) keys followed by a NULL pointer. If zero keys are + * given, the @param comp function will be invoked for every element + * in the table. Otherwise, the function is invoked only for those + * elements matching the keys specified. + * + * If an invocation of the comp function returns zero, + * iteration will continue using the next specified key, if any. + * + * @param comp The function to run + * @param rec The data to pass as the first argument to the function + * @param t The table to iterate over + * @param ... A varargs array of zero or more (char *) keys followed by NULL + * @return FALSE if one of the comp() iterations returned zero; TRUE if all + * iterations returned non-zero + * @see apr_table_do_callback_fn_t @see apr_table_vdo + */ +APR_DECLARE_NONSTD(int) apr_table_do(apr_table_do_callback_fn_t *comp, + void *rec, const apr_table_t *t, ...) +#if defined(__GNUC__) && __GNUC__ >= 4 + __attribute__((sentinel)) +#endif + ; + +/** + * Iterate over a table running the provided function once for every + * element in the table. The vp varargs parameter must be a + * list of zero or more (char *) keys followed by a NULL pointer. If + * zero keys are given, the @param comp function will be invoked for + * every element in the table. Otherwise, the function is invoked + * only for those elements matching the keys specified. + * + * If an invocation of the comp function returns zero, + * iteration will continue using the next specified key, if any. + * + * @param comp The function to run + * @param rec The data to pass as the first argument to the function + * @param t The table to iterate over + * @param vp List of zero or more (char *) keys followed by NULL + * @return FALSE if one of the comp() iterations returned zero; TRUE if all + * iterations returned non-zero + * @see apr_table_do_callback_fn_t @see apr_table_do + */ +APR_DECLARE(int) apr_table_vdo(apr_table_do_callback_fn_t *comp, + void *rec, const apr_table_t *t, va_list vp); + +/** flag for overlap to use apr_table_setn */ +#define APR_OVERLAP_TABLES_SET (0) +/** flag for overlap to use apr_table_mergen */ +#define APR_OVERLAP_TABLES_MERGE (1) +/** flag for overlap to use apr_table_addn */ +#define APR_OVERLAP_TABLES_ADD (2) +/** + * For each element in table b, either use setn or mergen to add the data + * to table a. Which method is used is determined by the flags passed in. + * @param a The table to add the data to. + * @param b The table to iterate over, adding its data to table a + * @param flags How to add the table to table a. One of: + * APR_OVERLAP_TABLES_SET Use apr_table_setn + * APR_OVERLAP_TABLES_MERGE Use apr_table_mergen + * APR_OVERLAP_TABLES_ADD Use apr_table_addn + * @remark When merging duplicates, the two values are concatenated, + * separated by the string ", ". + * @remark This function is highly optimized, and uses less memory and CPU cycles + * than a function that just loops through table b calling other functions. + */ +/** + * Conceptually, apr_table_overlap does this: + * + *
+ *  apr_array_header_t *barr = apr_table_elts(b);
+ *  apr_table_entry_t *belt = (apr_table_entry_t *)barr->elts;
+ *  int i;
+ *
+ *  for (i = 0; i < barr->nelts; ++i) {
+ *      if (flags & APR_OVERLAP_TABLES_MERGE) {
+ *          apr_table_mergen(a, belt[i].key, belt[i].val);
+ *      }
+ *      else if (flags & APR_OVERLAP_TABLES_ADD) {
+ *          apr_table_addn(a, belt[i].key, belt[i].val);
+ *      }
+ *      else {
+ *          apr_table_setn(a, belt[i].key, belt[i].val);
+ *      }
+ *  }
+ * 
+ * + * Except that it is more efficient (less space and cpu-time) especially + * when b has many elements. + * + * Notice the assumptions on the keys and values in b -- they must be + * in an ancestor of a's pool. In practice b and a are usually from + * the same pool. + */ + +APR_DECLARE(void) apr_table_overlap(apr_table_t *a, const apr_table_t *b, + unsigned flags); + +/** + * Eliminate redundant entries in a table by either overwriting + * or merging duplicates. + * + * @param t Table. + * @param flags APR_OVERLAP_TABLES_MERGE to merge, or + * APR_OVERLAP_TABLES_SET to overwrite, or + * APR_OVERLAP_TABLES_ADD to add + * @remark When merging duplicates, the two values are concatenated, + * separated by the string ", ". + */ +APR_DECLARE(void) apr_table_compress(apr_table_t *t, unsigned flags); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_TABLES_H */ diff --git a/c/dependencies/linux/apr/include/apr_thread_cond.h b/c/dependencies/linux/apr/include/apr_thread_cond.h new file mode 100644 index 00000000..199f1ded --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_thread_cond.h @@ -0,0 +1,139 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_THREAD_COND_H +#define APR_THREAD_COND_H + +/** + * @file apr_thread_cond.h + * @brief APR Condition Variable Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_time.h" +#include "apr_thread_mutex.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#if APR_HAS_THREADS || defined(DOXYGEN) + +/** + * @defgroup apr_thread_cond Condition Variable Routines + * @ingroup APR + * @{ + */ + +/** Opaque structure for thread condition variables */ +typedef struct apr_thread_cond_t apr_thread_cond_t; + +/** + * Note: destroying a condition variable (or likewise, destroying or + * clearing the pool from which a condition variable was allocated) if + * any threads are blocked waiting on it gives undefined results. + */ + +/** + * Create and initialize a condition variable that can be used to signal + * and schedule threads in a single process. + * @param cond the memory address where the newly created condition variable + * will be stored. + * @param pool the pool from which to allocate the condition. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_create(apr_thread_cond_t **cond, + apr_pool_t *pool); + +/** + * Put the active calling thread to sleep until signaled to wake up. Each + * condition variable must be associated with a mutex, and that mutex must + * be locked before calling this function, or the behavior will be + * undefined. As the calling thread is put to sleep, the given mutex + * will be simultaneously released; and as this thread wakes up the lock + * is again simultaneously acquired. + * @param cond the condition variable on which to block. + * @param mutex the mutex that must be locked upon entering this function, + * is released while the thread is asleep, and is again acquired before + * returning from this function. + * @remark Spurious wakeups may occur. Before and after every call to wait on + * a condition variable, the caller should test whether the condition is already + * met. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_wait(apr_thread_cond_t *cond, + apr_thread_mutex_t *mutex); + +/** + * Put the active calling thread to sleep until signaled to wake up or + * the timeout is reached. Each condition variable must be associated + * with a mutex, and that mutex must be locked before calling this + * function, or the behavior will be undefined. As the calling thread + * is put to sleep, the given mutex will be simultaneously released; + * and as this thread wakes up the lock is again simultaneously acquired. + * @param cond the condition variable on which to block. + * @param mutex the mutex that must be locked upon entering this function, + * is released while the thread is asleep, and is again acquired before + * returning from this function. + * @param timeout The amount of time in microseconds to wait. This is + * a maximum, not a minimum. If the condition is signaled, we + * will wake up before this time, otherwise the error APR_TIMEUP + * is returned. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_timedwait(apr_thread_cond_t *cond, + apr_thread_mutex_t *mutex, + apr_interval_time_t timeout); + +/** + * Signals a single thread, if one exists, that is blocking on the given + * condition variable. That thread is then scheduled to wake up and acquire + * the associated mutex. Although it is not required, if predictable scheduling + * is desired, that mutex must be locked while calling this function. + * @param cond the condition variable on which to produce the signal. + * @remark If no threads are waiting on the condition variable, nothing happens. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_signal(apr_thread_cond_t *cond); + +/** + * Signals all threads blocking on the given condition variable. + * Each thread that was signaled is then scheduled to wake up and acquire + * the associated mutex. This will happen in a serialized manner. + * @param cond the condition variable on which to produce the broadcast. + * @remark If no threads are waiting on the condition variable, nothing happens. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_broadcast(apr_thread_cond_t *cond); + +/** + * Destroy the condition variable and free the associated memory. + * @param cond the condition variable to destroy. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_destroy(apr_thread_cond_t *cond); + +/** + * Get the pool used by this thread_cond. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(thread_cond); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_THREAD_COND_H */ diff --git a/c/dependencies/linux/apr/include/apr_thread_mutex.h b/c/dependencies/linux/apr/include/apr_thread_mutex.h new file mode 100644 index 00000000..8eb61729 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_thread_mutex.h @@ -0,0 +1,123 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_THREAD_MUTEX_H +#define APR_THREAD_MUTEX_H + +/** + * @file apr_thread_mutex.h + * @brief APR Thread Mutex Routines + */ + +#include "apr.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#if APR_HAS_THREADS || defined(DOXYGEN) + +/** + * @defgroup apr_thread_mutex Thread Mutex Routines + * @ingroup APR + * @{ + */ + +/** Opaque thread-local mutex structure */ +typedef struct apr_thread_mutex_t apr_thread_mutex_t; + +#define APR_THREAD_MUTEX_DEFAULT 0x0 /**< platform-optimal lock behavior */ +#define APR_THREAD_MUTEX_NESTED 0x1 /**< enable nested (recursive) locks */ +#define APR_THREAD_MUTEX_UNNESTED 0x2 /**< disable nested locks */ +#define APR_THREAD_MUTEX_TIMED 0x4 /**< enable timed locks */ + +/* Delayed the include to avoid a circular reference */ +#include "apr_pools.h" +#include "apr_time.h" + +/** + * Create and initialize a mutex that can be used to synchronize threads. + * @param mutex the memory address where the newly created mutex will be + * stored. + * @param flags Or'ed value of: + *
+ *           APR_THREAD_MUTEX_DEFAULT   platform-optimal lock behavior.
+ *           APR_THREAD_MUTEX_NESTED    enable nested (recursive) locks.
+ *           APR_THREAD_MUTEX_UNNESTED  disable nested locks (non-recursive).
+ * 
+ * @param pool the pool from which to allocate the mutex. + * @warning Be cautious in using APR_THREAD_MUTEX_DEFAULT. While this is the + * most optimal mutex based on a given platform's performance characteristics, + * it will behave as either a nested or an unnested lock. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_create(apr_thread_mutex_t **mutex, + unsigned int flags, + apr_pool_t *pool); +/** + * Acquire the lock for the given mutex. If the mutex is already locked, + * the current thread will be put to sleep until the lock becomes available. + * @param mutex the mutex on which to acquire the lock. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_lock(apr_thread_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex. If the mutex has already + * been acquired, the call returns immediately with APR_EBUSY. Note: it + * is important that the APR_STATUS_IS_EBUSY(s) macro be used to determine + * if the return value was APR_EBUSY, for portability reasons. + * @param mutex the mutex on which to attempt the lock acquiring. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_trylock(apr_thread_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex until timeout expires. + * If the acquisition time outs, the call returns with APR_TIMEUP. + * @param mutex the mutex on which to attempt the lock acquiring. + * @param timeout the relative timeout (microseconds). + * @note A timeout negative or nul means immediate attempt, returning + * APR_TIMEUP without blocking if it the lock is already acquired. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_timedlock(apr_thread_mutex_t *mutex, + apr_interval_time_t timeout); + +/** + * Release the lock for the given mutex. + * @param mutex the mutex from which to release the lock. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_unlock(apr_thread_mutex_t *mutex); + +/** + * Destroy the mutex and free the memory associated with the lock. + * @param mutex the mutex to destroy. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_destroy(apr_thread_mutex_t *mutex); + +/** + * Get the pool used by this thread_mutex. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(thread_mutex); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_THREAD_MUTEX_H */ diff --git a/c/dependencies/linux/apr/include/apr_thread_pool.h b/c/dependencies/linux/apr/include/apr_thread_pool.h new file mode 100644 index 00000000..cbf382b3 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_thread_pool.h @@ -0,0 +1,299 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +#ifndef APU_THREAD_POOL_H +#define APU_THREAD_POOL_H + +#include "apu.h" +#include "apr_thread_proc.h" + +/** + * @file apr_thread_pool.h + * @brief APR Thread Pool Library + + * @remarks This library implements a thread pool using apr_thread_t. A thread + * pool is a set of threads that can be created in advance or on demand until a + * maximum number. When a task is scheduled, the thread pool will find an idle + * thread to handle the task. In case all existing threads are busy and the + * number of tasks in the queue is higher than the adjustable threshold, the + * pool will try to create a new thread to serve the task if the maximum number + * has not been reached. Otherwise, the task will be put into a queue based on + * priority, which can be valued from 0 to 255, with higher values being served + * first. If there are tasks with the same priority, the new task might be put at + * the top or at the bottom - it depends on which function is used to put the task. + * + * @remarks There may be the case where the thread pool can use up to the maximum + * number of threads at peak load, but having those threads idle afterwards. A + * maximum number of idle threads can be set so that the extra idling threads will + * be terminated to save system resources. + */ +#if APR_HAS_THREADS + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_Util_TP Thread Pool routines + * @ingroup APR_Util + * @{ + */ + +/** Opaque Thread Pool structure. */ +typedef struct apr_thread_pool apr_thread_pool_t; + +#define APR_THREAD_TASK_PRIORITY_LOWEST 0 +#define APR_THREAD_TASK_PRIORITY_LOW 63 +#define APR_THREAD_TASK_PRIORITY_NORMAL 127 +#define APR_THREAD_TASK_PRIORITY_HIGH 191 +#define APR_THREAD_TASK_PRIORITY_HIGHEST 255 + +/** + * Create a thread pool + * @param me The pointer in which to return the newly created apr_thread_pool + * object, or NULL if thread pool creation fails. + * @param init_threads The number of threads to be created initially, this number + * will also be used as the initial value for the maximum number of idle threads. + * @param max_threads The maximum number of threads that can be created + * @param pool The pool to use + * @return APR_SUCCESS if the thread pool was created successfully. Otherwise, + * the error code. + */ +APU_DECLARE(apr_status_t) apr_thread_pool_create(apr_thread_pool_t **me, + apr_size_t init_threads, + apr_size_t max_threads, + apr_pool_t *pool); + +/** + * Destroy the thread pool and stop all the threads + * @return APR_SUCCESS if all threads are stopped. + */ +APU_DECLARE(apr_status_t) apr_thread_pool_destroy(apr_thread_pool_t *me); + +/** + * Schedule a task to the bottom of the tasks of same priority. + * @param me The thread pool + * @param func The task function + * @param param The parameter for the task function + * @param priority The priority of the task. + * @param owner Owner of this task. + * @return APR_SUCCESS if the task had been scheduled successfully + */ +APU_DECLARE(apr_status_t) apr_thread_pool_push(apr_thread_pool_t *me, + apr_thread_start_t func, + void *param, + apr_byte_t priority, + void *owner); +/** + * Schedule a task to be run after a delay + * @param me The thread pool + * @param func The task function + * @param param The parameter for the task function + * @param time Time in microseconds + * @param owner Owner of this task. + * @return APR_SUCCESS if the task had been scheduled successfully + */ +APU_DECLARE(apr_status_t) apr_thread_pool_schedule(apr_thread_pool_t *me, + apr_thread_start_t func, + void *param, + apr_interval_time_t time, + void *owner); + +/** + * Schedule a task to the top of the tasks of same priority. + * @param me The thread pool + * @param func The task function + * @param param The parameter for the task function + * @param priority The priority of the task. + * @param owner Owner of this task. + * @return APR_SUCCESS if the task had been scheduled successfully + */ +APU_DECLARE(apr_status_t) apr_thread_pool_top(apr_thread_pool_t *me, + apr_thread_start_t func, + void *param, + apr_byte_t priority, + void *owner); + +/** + * Cancel tasks submitted by the owner. If there is any task from the owner that + * is currently running, the function will spin until the task finished. + * @param me The thread pool + * @param owner Owner of the task + * @return APR_SUCCESS if the task has been cancelled successfully + * @note The task function should not be calling cancel, otherwise the function + * may get stuck forever. The function assert if it detect such a case. + */ +APU_DECLARE(apr_status_t) apr_thread_pool_tasks_cancel(apr_thread_pool_t *me, + void *owner); + +/** + * Get the current number of tasks waiting in the queue + * @param me The thread pool + * @return Number of tasks in the queue + */ +APU_DECLARE(apr_size_t) apr_thread_pool_tasks_count(apr_thread_pool_t *me); + +/** + * Get the current number of scheduled tasks waiting in the queue + * @param me The thread pool + * @return Number of scheduled tasks in the queue + */ +APU_DECLARE(apr_size_t) apr_thread_pool_scheduled_tasks_count(apr_thread_pool_t *me); + +/** + * Get the current number of threads + * @param me The thread pool + * @return Total number of threads + */ +APU_DECLARE(apr_size_t) apr_thread_pool_threads_count(apr_thread_pool_t *me); + +/** + * Get the current number of busy threads + * @param me The thread pool + * @return Number of busy threads + */ +APU_DECLARE(apr_size_t) apr_thread_pool_busy_count(apr_thread_pool_t *me); + +/** + * Get the current number of idle threads + * @param me The thread pool + * @return Number of idle threads + */ +APU_DECLARE(apr_size_t) apr_thread_pool_idle_count(apr_thread_pool_t *me); + +/** + * Access function for the maximum number of idle threads. Number of current + * idle threads will be reduced to the new limit. + * @param me The thread pool + * @param cnt The number + * @return The number of threads that were stopped. + */ +APU_DECLARE(apr_size_t) apr_thread_pool_idle_max_set(apr_thread_pool_t *me, + apr_size_t cnt); + +/** + * Get number of tasks that have run + * @param me The thread pool + * @return Number of tasks that have run + */ +APU_DECLARE(apr_size_t) + apr_thread_pool_tasks_run_count(apr_thread_pool_t * me); + +/** + * Get high water mark of the number of tasks waiting to run + * @param me The thread pool + * @return High water mark of tasks waiting to run + */ +APU_DECLARE(apr_size_t) + apr_thread_pool_tasks_high_count(apr_thread_pool_t * me); + +/** + * Get high water mark of the number of threads + * @param me The thread pool + * @return High water mark of threads in thread pool + */ +APU_DECLARE(apr_size_t) + apr_thread_pool_threads_high_count(apr_thread_pool_t * me); + +/** + * Get the number of idle threads that were destroyed after timing out + * @param me The thread pool + * @return Number of idle threads that timed out + */ +APU_DECLARE(apr_size_t) + apr_thread_pool_threads_idle_timeout_count(apr_thread_pool_t * me); + +/** + * Access function for the maximum number of idle threads + * @param me The thread pool + * @return The current maximum number + */ +APU_DECLARE(apr_size_t) apr_thread_pool_idle_max_get(apr_thread_pool_t *me); + +/** + * Access function for the maximum number of threads. + * @param me The thread pool + * @param cnt Number of threads + * @return The original maximum number of threads + */ +APU_DECLARE(apr_size_t) apr_thread_pool_thread_max_set(apr_thread_pool_t *me, + apr_size_t cnt); + +/** + * Access function for the maximum wait time (in microseconds) of an + * idling thread that exceeds the maximum number of idling threads. + * A non-zero value allows for the reaping of idling threads to shrink + * over time. Which helps reduce thrashing. + * @param me The thread pool + * @param timeout The number of microseconds an idle thread should wait + * till it reaps itself + * @return The original maximum wait time + */ +APU_DECLARE(apr_interval_time_t) + apr_thread_pool_idle_wait_set(apr_thread_pool_t * me, + apr_interval_time_t timeout); + +/** + * Access function for the maximum wait time (in microseconds) of an + * idling thread that exceeds the maximum number of idling threads + * @param me The thread pool + * @return The current maximum wait time + */ +APU_DECLARE(apr_interval_time_t) + apr_thread_pool_idle_wait_get(apr_thread_pool_t * me); + +/** + * Access function for the maximum number of threads + * @param me The thread pool + * @return The current maximum number + */ +APU_DECLARE(apr_size_t) apr_thread_pool_thread_max_get(apr_thread_pool_t *me); + +/** + * Access function for the threshold of tasks in queue to trigger a new thread. + * @param me The thread pool + * @param cnt The new threshold + * @return The original threshold + */ +APU_DECLARE(apr_size_t) apr_thread_pool_threshold_set(apr_thread_pool_t *me, + apr_size_t val); + +/** + * Access function for the threshold of tasks in queue to trigger a new thread. + * @param me The thread pool + * @return The current threshold + */ +APU_DECLARE(apr_size_t) apr_thread_pool_threshold_get(apr_thread_pool_t * me); + +/** + * Get owner of the task currently been executed by the thread. + * @param thd The thread is executing a task + * @param owner Pointer to receive owner of the task. + * @return APR_SUCCESS if the owner is retrieved successfully + */ +APU_DECLARE(apr_status_t) apr_thread_pool_task_owner_get(apr_thread_t *thd, + void **owner); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_HAS_THREADS */ +#endif /* !APR_THREAD_POOL_H */ diff --git a/c/dependencies/linux/apr/include/apr_thread_proc.h b/c/dependencies/linux/apr/include/apr_thread_proc.h new file mode 100644 index 00000000..ea3c43f9 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_thread_proc.h @@ -0,0 +1,846 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_THREAD_PROC_H +#define APR_THREAD_PROC_H + +/** + * @file apr_thread_proc.h + * @brief APR Thread and Process Library + */ + +#include "apr.h" +#include "apr_file_io.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_perms_set.h" + +#if APR_HAVE_STRUCT_RLIMIT +#include +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_thread_proc Threads and Process Functions + * @ingroup APR + * @{ + */ + +typedef enum { + APR_SHELLCMD, /**< use the shell to invoke the program */ + APR_PROGRAM, /**< invoke the program directly, no copied env */ + APR_PROGRAM_ENV, /**< invoke the program, replicating our environment */ + APR_PROGRAM_PATH, /**< find program on PATH, use our environment */ + APR_SHELLCMD_ENV /**< use the shell to invoke the program, + * replicating our environment + */ +} apr_cmdtype_e; + +typedef enum { + APR_WAIT, /**< wait for the specified process to finish */ + APR_NOWAIT /**< do not wait -- just see if it has finished */ +} apr_wait_how_e; + +/* I am specifically calling out the values so that the macros below make + * more sense. Yes, I know I don't need to, but I am hoping this makes what + * I am doing more clear. If you want to add more reasons to exit, continue + * to use bitmasks. + */ +typedef enum { + APR_PROC_EXIT = 1, /**< process exited normally */ + APR_PROC_SIGNAL = 2, /**< process exited due to a signal */ + APR_PROC_SIGNAL_CORE = 4 /**< process exited and dumped a core file */ +} apr_exit_why_e; + +/** did we exit the process */ +#define APR_PROC_CHECK_EXIT(x) (x & APR_PROC_EXIT) +/** did we get a signal */ +#define APR_PROC_CHECK_SIGNALED(x) (x & APR_PROC_SIGNAL) +/** did we get core */ +#define APR_PROC_CHECK_CORE_DUMP(x) (x & APR_PROC_SIGNAL_CORE) + +/** @see apr_procattr_io_set */ +#define APR_NO_PIPE 0 +/** @see apr_procattr_io_set and apr_file_pipe_create_ex */ +#define APR_FULL_BLOCK 1 +/** @see apr_procattr_io_set and apr_file_pipe_create_ex */ +#define APR_FULL_NONBLOCK 2 +/** @see apr_procattr_io_set */ +#define APR_PARENT_BLOCK 3 +/** @see apr_procattr_io_set */ +#define APR_CHILD_BLOCK 4 +/** @see apr_procattr_io_set */ +#define APR_NO_FILE 8 + +/** @see apr_file_pipe_create_ex */ +#define APR_READ_BLOCK 3 +/** @see apr_file_pipe_create_ex */ +#define APR_WRITE_BLOCK 4 + +/** @see apr_procattr_io_set + * @note Win32 only effective with version 1.2.12, portably introduced in 1.3.0 + */ +#define APR_NO_FILE 8 + +/** @see apr_procattr_limit_set */ +#define APR_LIMIT_CPU 0 +/** @see apr_procattr_limit_set */ +#define APR_LIMIT_MEM 1 +/** @see apr_procattr_limit_set */ +#define APR_LIMIT_NPROC 2 +/** @see apr_procattr_limit_set */ +#define APR_LIMIT_NOFILE 3 + +/** + * @defgroup APR_OC Other Child Flags + * @{ + */ +#define APR_OC_REASON_DEATH 0 /**< child has died, caller must call + * unregister still */ +#define APR_OC_REASON_UNWRITABLE 1 /**< write_fd is unwritable */ +#define APR_OC_REASON_RESTART 2 /**< a restart is occurring, perform + * any necessary cleanup (including + * sending a special signal to child) + */ +#define APR_OC_REASON_UNREGISTER 3 /**< unregister has been called, do + * whatever is necessary (including + * kill the child) */ +#define APR_OC_REASON_LOST 4 /**< somehow the child exited without + * us knowing ... buggy os? */ +#define APR_OC_REASON_RUNNING 5 /**< a health check is occurring, + * for most maintainence functions + * this is a no-op. + */ +/** @} */ + +/** The APR process type */ +typedef struct apr_proc_t { + /** The process ID */ + pid_t pid; + /** Parent's side of pipe to child's stdin */ + apr_file_t *in; + /** Parent's side of pipe to child's stdout */ + apr_file_t *out; + /** Parent's side of pipe to child's stdouterr */ + apr_file_t *err; +#if APR_HAS_PROC_INVOKED || defined(DOXYGEN) + /** Diagnositics/debugging string of the command invoked for + * this process [only present if APR_HAS_PROC_INVOKED is true] + * @remark Only enabled on Win32 by default. + * @bug This should either always or never be present in release + * builds - since it breaks binary compatibility. We may enable + * it always in APR 1.0 yet leave it undefined in most cases. + */ + char *invoked; +#endif +#if defined(WIN32) || defined(DOXYGEN) + /** (Win32 only) Creator's handle granting access to the process + * @remark This handle is closed and reset to NULL in every case + * corresponding to a waitpid() on Unix which returns the exit status. + * Therefore Win32 correspond's to Unix's zombie reaping characteristics + * and avoids potential handle leaks. + */ + HANDLE hproc; +#endif +} apr_proc_t; + +/** + * The prototype for APR child errfn functions. (See the description + * of apr_procattr_child_errfn_set() for more information.) + * It is passed the following parameters: + * @param pool Pool associated with the apr_proc_t. If your child + * error function needs user data, associate it with this + * pool. + * @param err APR error code describing the error + * @param description Text description of type of processing which failed + */ +typedef void (apr_child_errfn_t)(apr_pool_t *proc, apr_status_t err, + const char *description); + +/** Opaque Thread structure. */ +typedef struct apr_thread_t apr_thread_t; + +/** Opaque Thread attributes structure. */ +typedef struct apr_threadattr_t apr_threadattr_t; + +/** Opaque Process attributes structure. */ +typedef struct apr_procattr_t apr_procattr_t; + +/** Opaque control variable for one-time atomic variables. */ +typedef struct apr_thread_once_t apr_thread_once_t; + +/** Opaque thread private address space. */ +typedef struct apr_threadkey_t apr_threadkey_t; + +/** Opaque record of child process. */ +typedef struct apr_other_child_rec_t apr_other_child_rec_t; + +/** + * The prototype for any APR thread worker functions. + */ +typedef void *(APR_THREAD_FUNC *apr_thread_start_t)(apr_thread_t*, void*); + +typedef enum { + APR_KILL_NEVER, /**< process is never killed (i.e., never sent + * any signals), but it will be reaped if it exits + * before the pool is cleaned up */ + APR_KILL_ALWAYS, /**< process is sent SIGKILL on apr_pool_t cleanup */ + APR_KILL_AFTER_TIMEOUT, /**< SIGTERM, wait 3 seconds, SIGKILL */ + APR_JUST_WAIT, /**< wait forever for the process to complete */ + APR_KILL_ONLY_ONCE /**< send SIGTERM and then wait */ +} apr_kill_conditions_e; + +/* Thread Function definitions */ + +#if APR_HAS_THREADS + +/** + * Create and initialize a new threadattr variable + * @param new_attr The newly created threadattr. + * @param cont The pool to use + */ +APR_DECLARE(apr_status_t) apr_threadattr_create(apr_threadattr_t **new_attr, + apr_pool_t *cont); + +/** + * Set if newly created threads should be created in detached state. + * @param attr The threadattr to affect + * @param on Non-zero if detached threads should be created. + */ +APR_DECLARE(apr_status_t) apr_threadattr_detach_set(apr_threadattr_t *attr, + apr_int32_t on); + +/** + * Get the detach state for this threadattr. + * @param attr The threadattr to reference + * @return APR_DETACH if threads are to be detached, or APR_NOTDETACH + * if threads are to be joinable. + */ +APR_DECLARE(apr_status_t) apr_threadattr_detach_get(apr_threadattr_t *attr); + +/** + * Set the stack size of newly created threads. + * @param attr The threadattr to affect + * @param stacksize The stack size in bytes + */ +APR_DECLARE(apr_status_t) apr_threadattr_stacksize_set(apr_threadattr_t *attr, + apr_size_t stacksize); + +/** + * Set the stack guard area size of newly created threads. + * @param attr The threadattr to affect + * @param guardsize The stack guard area size in bytes + * @note Thread library implementations commonly use a "guard area" + * after each thread's stack which is not readable or writable such that + * stack overflows cause a segfault; this consumes e.g. 4K of memory + * and increases memory management overhead. Setting the guard area + * size to zero hence trades off reliable behaviour on stack overflow + * for performance. */ +APR_DECLARE(apr_status_t) apr_threadattr_guardsize_set(apr_threadattr_t *attr, + apr_size_t guardsize); + +/** + * Create a new thread of execution + * @param new_thread The newly created thread handle. + * @param attr The threadattr to use to determine how to create the thread + * @param func The function to start the new thread in + * @param data Any data to be passed to the starting function + * @param cont The pool to use + */ +APR_DECLARE(apr_status_t) apr_thread_create(apr_thread_t **new_thread, + apr_threadattr_t *attr, + apr_thread_start_t func, + void *data, apr_pool_t *cont); + +/** + * stop the current thread + * @param thd The thread to stop + * @param retval The return value to pass back to any thread that cares + */ +APR_DECLARE(apr_status_t) apr_thread_exit(apr_thread_t *thd, + apr_status_t retval); + +/** + * block until the desired thread stops executing. + * @param retval The return value from the dead thread. + * @param thd The thread to join + */ +APR_DECLARE(apr_status_t) apr_thread_join(apr_status_t *retval, + apr_thread_t *thd); + +/** + * force the current thread to yield the processor + */ +APR_DECLARE(void) apr_thread_yield(void); + +/** + * Initialize the control variable for apr_thread_once. If this isn't + * called, apr_initialize won't work. + * @param control The control variable to initialize + * @param p The pool to allocate data from. + */ +APR_DECLARE(apr_status_t) apr_thread_once_init(apr_thread_once_t **control, + apr_pool_t *p); + +/** + * Run the specified function one time, regardless of how many threads + * call it. + * @param control The control variable. The same variable should + * be passed in each time the function is tried to be + * called. This is how the underlying functions determine + * if the function has ever been called before. + * @param func The function to call. + */ +APR_DECLARE(apr_status_t) apr_thread_once(apr_thread_once_t *control, + void (*func)(void)); + +/** + * detach a thread + * @param thd The thread to detach + */ +APR_DECLARE(apr_status_t) apr_thread_detach(apr_thread_t *thd); + +/** + * Return user data associated with the current thread. + * @param data The user data associated with the thread. + * @param key The key to associate with the data + * @param thread The currently open thread. + */ +APR_DECLARE(apr_status_t) apr_thread_data_get(void **data, const char *key, + apr_thread_t *thread); + +/** + * Set user data associated with the current thread. + * @param data The user data to associate with the thread. + * @param key The key to use for associating the data with the thread + * @param cleanup The cleanup routine to use when the thread is destroyed. + * @param thread The currently open thread. + */ +APR_DECLARE(apr_status_t) apr_thread_data_set(void *data, const char *key, + apr_status_t (*cleanup) (void *), + apr_thread_t *thread); + +/** + * Create and initialize a new thread private address space + * @param key The thread private handle. + * @param dest The destructor to use when freeing the private memory. + * @param cont The pool to use + */ +APR_DECLARE(apr_status_t) apr_threadkey_private_create(apr_threadkey_t **key, + void (*dest)(void *), + apr_pool_t *cont); + +/** + * Get a pointer to the thread private memory + * @param new_mem The data stored in private memory + * @param key The handle for the desired thread private memory + */ +APR_DECLARE(apr_status_t) apr_threadkey_private_get(void **new_mem, + apr_threadkey_t *key); + +/** + * Set the data to be stored in thread private memory + * @param priv The data to be stored in private memory + * @param key The handle for the desired thread private memory + */ +APR_DECLARE(apr_status_t) apr_threadkey_private_set(void *priv, + apr_threadkey_t *key); + +/** + * Free the thread private memory + * @param key The handle for the desired thread private memory + */ +APR_DECLARE(apr_status_t) apr_threadkey_private_delete(apr_threadkey_t *key); + +/** + * Return the pool associated with the current threadkey. + * @param data The user data associated with the threadkey. + * @param key The key associated with the data + * @param threadkey The currently open threadkey. + */ +APR_DECLARE(apr_status_t) apr_threadkey_data_get(void **data, const char *key, + apr_threadkey_t *threadkey); + +/** + * Return the pool associated with the current threadkey. + * @param data The data to set. + * @param key The key to associate with the data. + * @param cleanup The cleanup routine to use when the file is destroyed. + * @param threadkey The currently open threadkey. + */ +APR_DECLARE(apr_status_t) apr_threadkey_data_set(void *data, const char *key, + apr_status_t (*cleanup) (void *), + apr_threadkey_t *threadkey); + +#endif + +/** + * Create and initialize a new procattr variable + * @param new_attr The newly created procattr. + * @param cont The pool to use + */ +APR_DECLARE(apr_status_t) apr_procattr_create(apr_procattr_t **new_attr, + apr_pool_t *cont); + +/** + * Determine if any of stdin, stdout, or stderr should be linked to pipes + * when starting a child process. + * @param attr The procattr we care about. + * @param in Should stdin be a pipe back to the parent? + * @param out Should stdout be a pipe back to the parent? + * @param err Should stderr be a pipe back to the parent? + * @note If APR_NO_PIPE, there will be no special channel, the child + * inherits the parent's corresponding stdio stream. If APR_NO_FILE is + * specified, that corresponding stream is closed in the child (and will + * be INVALID_HANDLE_VALUE when inspected on Win32). This can have ugly + * side effects, as the next file opened in the child on Unix will fall + * into the stdio stream fd slot! + */ +APR_DECLARE(apr_status_t) apr_procattr_io_set(apr_procattr_t *attr, + apr_int32_t in, apr_int32_t out, + apr_int32_t err); + +/** + * Set the child_in and/or parent_in values to existing apr_file_t values. + * @param attr The procattr we care about. + * @param child_in apr_file_t value to use as child_in. Must be a valid file. + * @param parent_in apr_file_t value to use as parent_in. Must be a valid file. + * @remark This is NOT a required initializer function. This is + * useful if you have already opened a pipe (or multiple files) + * that you wish to use, perhaps persistently across multiple + * process invocations - such as a log file. You can save some + * extra function calls by not creating your own pipe since this + * creates one in the process space for you. + * @bug Note that calling this function with two NULL files on some platforms + * creates an APR_FULL_BLOCK pipe, but this behavior is neither portable nor + * is it supported. @see apr_procattr_io_set instead for simple pipes. + */ +APR_DECLARE(apr_status_t) apr_procattr_child_in_set(struct apr_procattr_t *attr, + apr_file_t *child_in, + apr_file_t *parent_in); + +/** + * Set the child_out and parent_out values to existing apr_file_t values. + * @param attr The procattr we care about. + * @param child_out apr_file_t value to use as child_out. Must be a valid file. + * @param parent_out apr_file_t value to use as parent_out. Must be a valid file. + * @remark This is NOT a required initializer function. This is + * useful if you have already opened a pipe (or multiple files) + * that you wish to use, perhaps persistently across multiple + * process invocations - such as a log file. + * @bug Note that calling this function with two NULL files on some platforms + * creates an APR_FULL_BLOCK pipe, but this behavior is neither portable nor + * is it supported. @see apr_procattr_io_set instead for simple pipes. + */ +APR_DECLARE(apr_status_t) apr_procattr_child_out_set(struct apr_procattr_t *attr, + apr_file_t *child_out, + apr_file_t *parent_out); + +/** + * Set the child_err and parent_err values to existing apr_file_t values. + * @param attr The procattr we care about. + * @param child_err apr_file_t value to use as child_err. Must be a valid file. + * @param parent_err apr_file_t value to use as parent_err. Must be a valid file. + * @remark This is NOT a required initializer function. This is + * useful if you have already opened a pipe (or multiple files) + * that you wish to use, perhaps persistently across multiple + * process invocations - such as a log file. + * @bug Note that calling this function with two NULL files on some platforms + * creates an APR_FULL_BLOCK pipe, but this behavior is neither portable nor + * is it supported. @see apr_procattr_io_set instead for simple pipes. + */ +APR_DECLARE(apr_status_t) apr_procattr_child_err_set(struct apr_procattr_t *attr, + apr_file_t *child_err, + apr_file_t *parent_err); + +/** + * Set which directory the child process should start executing in. + * @param attr The procattr we care about. + * @param dir Which dir to start in. By default, this is the same dir as + * the parent currently resides in, when the createprocess call + * is made. + */ +APR_DECLARE(apr_status_t) apr_procattr_dir_set(apr_procattr_t *attr, + const char *dir); + +/** + * Set what type of command the child process will call. + * @param attr The procattr we care about. + * @param cmd The type of command. One of: + *
+ *            APR_SHELLCMD     --  Anything that the shell can handle
+ *            APR_PROGRAM      --  Executable program   (default) 
+ *            APR_PROGRAM_ENV  --  Executable program, copy environment
+ *            APR_PROGRAM_PATH --  Executable program on PATH, copy env
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_procattr_cmdtype_set(apr_procattr_t *attr, + apr_cmdtype_e cmd); + +/** + * Determine if the child should start in detached state. + * @param attr The procattr we care about. + * @param detach Should the child start in detached state? Default is no. + */ +APR_DECLARE(apr_status_t) apr_procattr_detach_set(apr_procattr_t *attr, + apr_int32_t detach); + +#if APR_HAVE_STRUCT_RLIMIT +/** + * Set the Resource Utilization limits when starting a new process. + * @param attr The procattr we care about. + * @param what Which limit to set, one of: + *
+ *                 APR_LIMIT_CPU
+ *                 APR_LIMIT_MEM
+ *                 APR_LIMIT_NPROC
+ *                 APR_LIMIT_NOFILE
+ * 
+ * @param limit Value to set the limit to. + */ +APR_DECLARE(apr_status_t) apr_procattr_limit_set(apr_procattr_t *attr, + apr_int32_t what, + struct rlimit *limit); +#endif + +/** + * Specify an error function to be called in the child process if APR + * encounters an error in the child prior to running the specified program. + * @param attr The procattr describing the child process to be created. + * @param errfn The function to call in the child process. + * @remark At the present time, it will only be called from apr_proc_create() + * on platforms where fork() is used. It will never be called on other + * platforms, on those platforms apr_proc_create() will return the error + * in the parent process rather than invoke the callback in the now-forked + * child process. + */ +APR_DECLARE(apr_status_t) apr_procattr_child_errfn_set(apr_procattr_t *attr, + apr_child_errfn_t *errfn); + +/** + * Specify that apr_proc_create() should do whatever it can to report + * failures to the caller of apr_proc_create(), rather than find out in + * the child. + * @param attr The procattr describing the child process to be created. + * @param chk Flag to indicate whether or not extra work should be done + * to try to report failures to the caller. + * @remark This flag only affects apr_proc_create() on platforms where + * fork() is used. This leads to extra overhead in the calling + * process, but that may help the application handle such + * errors more gracefully. + */ +APR_DECLARE(apr_status_t) apr_procattr_error_check_set(apr_procattr_t *attr, + apr_int32_t chk); + +/** + * Determine if the child should start in its own address space or using the + * current one from its parent + * @param attr The procattr we care about. + * @param addrspace Should the child start in its own address space? Default + * is no on NetWare and yes on other platforms. + */ +APR_DECLARE(apr_status_t) apr_procattr_addrspace_set(apr_procattr_t *attr, + apr_int32_t addrspace); + +/** + * Set the username used for running process + * @param attr The procattr we care about. + * @param username The username used + * @param password User password if needed. Password is needed on WIN32 + * or any other platform having + * APR_PROCATTR_USER_SET_REQUIRES_PASSWORD set. + */ +APR_DECLARE(apr_status_t) apr_procattr_user_set(apr_procattr_t *attr, + const char *username, + const char *password); + +/** + * Set the group used for running process + * @param attr The procattr we care about. + * @param groupname The group name used + */ +APR_DECLARE(apr_status_t) apr_procattr_group_set(apr_procattr_t *attr, + const char *groupname); + + +/** + * Register permission set function + * @param attr The procattr we care about. + * @param perms_set_fn Permission set callback + * @param data Data to pass to permission callback function + * @param perms Permissions to set + */ +APR_DECLARE(apr_status_t) apr_procattr_perms_set_register(apr_procattr_t *attr, + apr_perms_setfn_t *perms_set_fn, + void *data, + apr_fileperms_t perms); + +#if APR_HAS_FORK +/** + * This is currently the only non-portable call in APR. This executes + * a standard unix fork. + * @param proc The resulting process handle. + * @param cont The pool to use. + * @remark returns APR_INCHILD for the child, and APR_INPARENT for the parent + * or an error. + */ +APR_DECLARE(apr_status_t) apr_proc_fork(apr_proc_t *proc, apr_pool_t *cont); +#endif + +/** + * Create a new process and execute a new program within that process. + * @param new_proc The resulting process handle. + * @param progname The program to run + * @param args the arguments to pass to the new program. The first + * one should be the program name. + * @param env The new environment table for the new process. This + * should be a list of NULL-terminated strings. This argument + * is ignored for APR_PROGRAM_ENV, APR_PROGRAM_PATH, and + * APR_SHELLCMD_ENV types of commands. + * @param attr the procattr we should use to determine how to create the new + * process + * @param pool The pool to use. + * @note This function returns without waiting for the new process to terminate; + * use apr_proc_wait for that. + */ +APR_DECLARE(apr_status_t) apr_proc_create(apr_proc_t *new_proc, + const char *progname, + const char * const *args, + const char * const *env, + apr_procattr_t *attr, + apr_pool_t *pool); + +/** + * Wait for a child process to die + * @param proc The process handle that corresponds to the desired child process + * @param exitcode The returned exit status of the child, if a child process + * dies, or the signal that caused the child to die. + * On platforms that don't support obtaining this information, + * the status parameter will be returned as APR_ENOTIMPL. + * @param exitwhy Why the child died, the bitwise or of: + *
+ *            APR_PROC_EXIT         -- process terminated normally
+ *            APR_PROC_SIGNAL       -- process was killed by a signal
+ *            APR_PROC_SIGNAL_CORE  -- process was killed by a signal, and
+ *                                     generated a core dump.
+ * 
+ * @param waithow How should we wait. One of: + *
+ *            APR_WAIT   -- block until the child process dies.
+ *            APR_NOWAIT -- return immediately regardless of if the 
+ *                          child is dead or not.
+ * 
+ * @remark The child's status is in the return code to this process. It is one of: + *
+ *            APR_CHILD_DONE     -- child is no longer running.
+ *            APR_CHILD_NOTDONE  -- child is still running.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_proc_wait(apr_proc_t *proc, + int *exitcode, apr_exit_why_e *exitwhy, + apr_wait_how_e waithow); + +/** + * Wait for any current child process to die and return information + * about that child. + * @param proc Pointer to NULL on entry, will be filled out with child's + * information + * @param exitcode The returned exit status of the child, if a child process + * dies, or the signal that caused the child to die. + * On platforms that don't support obtaining this information, + * the status parameter will be returned as APR_ENOTIMPL. + * @param exitwhy Why the child died, the bitwise or of: + *
+ *            APR_PROC_EXIT         -- process terminated normally
+ *            APR_PROC_SIGNAL       -- process was killed by a signal
+ *            APR_PROC_SIGNAL_CORE  -- process was killed by a signal, and
+ *                                     generated a core dump.
+ * 
+ * @param waithow How should we wait. One of: + *
+ *            APR_WAIT   -- block until the child process dies.
+ *            APR_NOWAIT -- return immediately regardless of if the 
+ *                          child is dead or not.
+ * 
+ * @param p Pool to allocate child information out of. + * @bug Passing proc as a *proc rather than **proc was an odd choice + * for some platforms... this should be revisited in 1.0 + */ +APR_DECLARE(apr_status_t) apr_proc_wait_all_procs(apr_proc_t *proc, + int *exitcode, + apr_exit_why_e *exitwhy, + apr_wait_how_e waithow, + apr_pool_t *p); + +#define APR_PROC_DETACH_FOREGROUND 0 /**< Do not detach */ +#define APR_PROC_DETACH_DAEMONIZE 1 /**< Detach */ + +/** + * Detach the process from the controlling terminal. + * @param daemonize set to non-zero if the process should daemonize + * and become a background process, else it will + * stay in the foreground. + */ +APR_DECLARE(apr_status_t) apr_proc_detach(int daemonize); + +/** + * Register an other_child -- a child associated to its registered + * maintence callback. This callback is invoked when the process + * dies, is disconnected or disappears. + * @param proc The child process to register. + * @param maintenance maintenance is a function that is invoked with a + * reason and the data pointer passed here. + * @param data Opaque context data passed to the maintenance function. + * @param write_fd An fd that is probed for writing. If it is ever unwritable + * then the maintenance is invoked with reason + * OC_REASON_UNWRITABLE. + * @param p The pool to use for allocating memory. + * @bug write_fd duplicates the proc->out stream, it's really redundant + * and should be replaced in the APR 1.0 API with a bitflag of which + * proc->in/out/err handles should be health checked. + * @bug no platform currently tests the pipes health. + */ +APR_DECLARE(void) apr_proc_other_child_register(apr_proc_t *proc, + void (*maintenance) (int reason, + void *, + int status), + void *data, apr_file_t *write_fd, + apr_pool_t *p); + +/** + * Stop watching the specified other child. + * @param data The data to pass to the maintenance function. This is + * used to find the process to unregister. + * @warning Since this can be called by a maintenance function while we're + * scanning the other_children list, all scanners should protect + * themself by loading ocr->next before calling any maintenance + * function. + */ +APR_DECLARE(void) apr_proc_other_child_unregister(void *data); + +/** + * Notify the maintenance callback of a registered other child process + * that application has detected an event, such as death. + * @param proc The process to check + * @param reason The reason code to pass to the maintenance function + * @param status The status to pass to the maintenance function + * @remark An example of code using this behavior; + *
+ * rv = apr_proc_wait_all_procs(&proc, &exitcode, &status, APR_WAIT, p);
+ * if (APR_STATUS_IS_CHILD_DONE(rv)) {
+ * \#if APR_HAS_OTHER_CHILD
+ *     if (apr_proc_other_child_alert(&proc, APR_OC_REASON_DEATH, status)
+ *             == APR_SUCCESS) {
+ *         ;  (already handled)
+ *     }
+ *     else
+ * \#endif
+ *         [... handling non-otherchild processes death ...]
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_proc_other_child_alert(apr_proc_t *proc, + int reason, + int status); + +/** + * Test one specific other child processes and invoke the maintenance callback + * with the appropriate reason code, if still running, or the appropriate reason + * code if the process is no longer healthy. + * @param ocr The registered other child + * @param reason The reason code (e.g. APR_OC_REASON_RESTART) if still running + */ +APR_DECLARE(void) apr_proc_other_child_refresh(apr_other_child_rec_t *ocr, + int reason); + +/** + * Test all registered other child processes and invoke the maintenance callback + * with the appropriate reason code, if still running, or the appropriate reason + * code if the process is no longer healthy. + * @param reason The reason code (e.g. APR_OC_REASON_RESTART) to running processes + */ +APR_DECLARE(void) apr_proc_other_child_refresh_all(int reason); + +/** + * Terminate a process. + * @param proc The process to terminate. + * @param sig How to kill the process. + */ +APR_DECLARE(apr_status_t) apr_proc_kill(apr_proc_t *proc, int sig); + +/** + * Register a process to be killed when a pool dies. + * @param a The pool to use to define the processes lifetime + * @param proc The process to register + * @param how How to kill the process, one of: + *
+ *         APR_KILL_NEVER         -- process is never sent any signals
+ *         APR_KILL_ALWAYS        -- process is sent SIGKILL on apr_pool_t cleanup
+ *         APR_KILL_AFTER_TIMEOUT -- SIGTERM, wait 3 seconds, SIGKILL
+ *         APR_JUST_WAIT          -- wait forever for the process to complete
+ *         APR_KILL_ONLY_ONCE     -- send SIGTERM and then wait
+ * 
+ */ +APR_DECLARE(void) apr_pool_note_subprocess(apr_pool_t *a, apr_proc_t *proc, + apr_kill_conditions_e how); + +#if APR_HAS_THREADS + +#if (APR_HAVE_SIGWAIT || APR_HAVE_SIGSUSPEND) && !defined(OS2) + +/** + * Setup the process for a single thread to be used for all signal handling. + * @warning This must be called before any threads are created + */ +APR_DECLARE(apr_status_t) apr_setup_signal_thread(void); + +/** + * Make the current thread listen for signals. This thread will loop + * forever, calling a provided function whenever it receives a signal. That + * functions should return 1 if the signal has been handled, 0 otherwise. + * @param signal_handler The function to call when a signal is received + * apr_status_t apr_signal_thread((int)(*signal_handler)(int signum)) + * @note Synchronous signals like SIGABRT/SIGSEGV/SIGBUS/... are ignored by + * apr_signal_thread() and thus can't be waited by this function (they remain + * handled by the operating system or its native signals interface). + * @remark In APR version 1.6 and ealier, SIGUSR2 was part of these ignored + * signals and thus was never passed in to the signal_handler. From APR 1.7 + * this is no more the case so SIGUSR2 can be handled in signal_handler and + * acted upon like the other asynchronous signals. + */ +APR_DECLARE(apr_status_t) apr_signal_thread(int(*signal_handler)(int signum)); + +#endif /* (APR_HAVE_SIGWAIT || APR_HAVE_SIGSUSPEND) && !defined(OS2) */ + +/** + * Get the child-pool used by the thread from the thread info. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(thread); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_THREAD_PROC_H */ + diff --git a/c/dependencies/linux/apr/include/apr_thread_rwlock.h b/c/dependencies/linux/apr/include/apr_thread_rwlock.h new file mode 100644 index 00000000..0bd958fb --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_thread_rwlock.h @@ -0,0 +1,129 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_THREAD_RWLOCK_H +#define APR_THREAD_RWLOCK_H + +/** + * @file apr_thread_rwlock.h + * @brief APR Reader/Writer Lock Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#if APR_HAS_THREADS + +/** + * @defgroup apr_thread_rwlock Reader/Writer Lock Routines + * @ingroup APR + * @{ + */ + +/** Opaque read-write thread-safe lock. */ +typedef struct apr_thread_rwlock_t apr_thread_rwlock_t; + +/** + * Note: The following operations have undefined results: unlocking a + * read-write lock which is not locked in the calling thread; write + * locking a read-write lock which is already locked by the calling + * thread; destroying a read-write lock more than once; clearing or + * destroying the pool from which a locked read-write lock is + * allocated. + */ + +/** + * Create and initialize a read-write lock that can be used to synchronize + * threads. + * @param rwlock the memory address where the newly created readwrite lock + * will be stored. + * @param pool the pool from which to allocate the mutex. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_create(apr_thread_rwlock_t **rwlock, + apr_pool_t *pool); +/** + * Acquire a shared-read lock on the given read-write lock. This will allow + * multiple threads to enter the same critical section while they have acquired + * the read lock. + * @param rwlock the read-write lock on which to acquire the shared read. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_rdlock(apr_thread_rwlock_t *rwlock); + +/** + * Attempt to acquire the shared-read lock on the given read-write lock. This + * is the same as apr_thread_rwlock_rdlock(), only that the function fails + * if there is another thread holding the write lock, or if there are any + * write threads blocking on the lock. If the function fails for this case, + * APR_EBUSY will be returned. Note: it is important that the + * APR_STATUS_IS_EBUSY(s) macro be used to determine if the return value was + * APR_EBUSY, for portability reasons. + * @param rwlock the rwlock on which to attempt the shared read. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_tryrdlock(apr_thread_rwlock_t *rwlock); + +/** + * Acquire an exclusive-write lock on the given read-write lock. This will + * allow only one single thread to enter the critical sections. If there + * are any threads currently holding the read-lock, this thread is put to + * sleep until it can have exclusive access to the lock. + * @param rwlock the read-write lock on which to acquire the exclusive write. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_wrlock(apr_thread_rwlock_t *rwlock); + +/** + * Attempt to acquire the exclusive-write lock on the given read-write lock. + * This is the same as apr_thread_rwlock_wrlock(), only that the function fails + * if there is any other thread holding the lock (for reading or writing), + * in which case the function will return APR_EBUSY. Note: it is important + * that the APR_STATUS_IS_EBUSY(s) macro be used to determine if the return + * value was APR_EBUSY, for portability reasons. + * @param rwlock the rwlock on which to attempt the exclusive write. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_trywrlock(apr_thread_rwlock_t *rwlock); + +/** + * Release either the read or write lock currently held by the calling thread + * associated with the given read-write lock. + * @param rwlock the read-write lock to be released (unlocked). + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_unlock(apr_thread_rwlock_t *rwlock); + +/** + * Destroy the read-write lock and free the associated memory. + * @param rwlock the rwlock to destroy. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_destroy(apr_thread_rwlock_t *rwlock); + +/** + * Get the pool used by this thread_rwlock. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(thread_rwlock); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_THREAD_RWLOCK_H */ diff --git a/c/dependencies/linux/apr/include/apr_time.h b/c/dependencies/linux/apr/include/apr_time.h new file mode 100644 index 00000000..b0efd791 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_time.h @@ -0,0 +1,237 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_TIME_H +#define APR_TIME_H + +/** + * @file apr_time.h + * @brief APR Time Library + */ + +#include "apr.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_time Time Routines + * @ingroup APR + * @{ + */ + +/** month names */ +APR_DECLARE_DATA extern const char apr_month_snames[12][4]; +/** day names */ +APR_DECLARE_DATA extern const char apr_day_snames[7][4]; + + +/** number of microseconds since 00:00:00 January 1, 1970 UTC */ +typedef apr_int64_t apr_time_t; + + +/** mechanism to properly type apr_time_t literals */ +#define APR_TIME_C(val) APR_INT64_C(val) + +/** mechanism to properly print apr_time_t values */ +#define APR_TIME_T_FMT APR_INT64_T_FMT + +/** intervals for I/O timeouts, in microseconds */ +typedef apr_int64_t apr_interval_time_t; +/** short interval for I/O timeouts, in microseconds */ +typedef apr_int32_t apr_short_interval_time_t; + +/** number of microseconds per second */ +#define APR_USEC_PER_SEC APR_TIME_C(1000000) + +/** @return apr_time_t as a second */ +#define apr_time_sec(time) ((time) / APR_USEC_PER_SEC) + +/** @return apr_time_t as a usec */ +#define apr_time_usec(time) ((time) % APR_USEC_PER_SEC) + +/** @return apr_time_t as a msec */ +#define apr_time_msec(time) (((time) / 1000) % 1000) + +/** @return apr_time_t as a msec */ +#define apr_time_as_msec(time) ((time) / 1000) + +/** @return milliseconds as an apr_time_t */ +#define apr_time_from_msec(msec) ((apr_time_t)(msec) * 1000) + +/** @return seconds as an apr_time_t */ +#define apr_time_from_sec(sec) ((apr_time_t)(sec) * APR_USEC_PER_SEC) + +/** @return a second and usec combination as an apr_time_t */ +#define apr_time_make(sec, usec) ((apr_time_t)(sec) * APR_USEC_PER_SEC \ + + (apr_time_t)(usec)) + +/** + * @return the current time + */ +APR_DECLARE(apr_time_t) apr_time_now(void); + +/** @see apr_time_exp_t */ +typedef struct apr_time_exp_t apr_time_exp_t; + +/** + * a structure similar to ANSI struct tm with the following differences: + * - tm_usec isn't an ANSI field + * - tm_gmtoff isn't an ANSI field (it's a BSDism) + */ +struct apr_time_exp_t { + /** microseconds past tm_sec */ + apr_int32_t tm_usec; + /** (0-61) seconds past tm_min */ + apr_int32_t tm_sec; + /** (0-59) minutes past tm_hour */ + apr_int32_t tm_min; + /** (0-23) hours past midnight */ + apr_int32_t tm_hour; + /** (1-31) day of the month */ + apr_int32_t tm_mday; + /** (0-11) month of the year */ + apr_int32_t tm_mon; + /** year since 1900 */ + apr_int32_t tm_year; + /** (0-6) days since Sunday */ + apr_int32_t tm_wday; + /** (0-365) days since January 1 */ + apr_int32_t tm_yday; + /** daylight saving time */ + apr_int32_t tm_isdst; + /** seconds east of UTC */ + apr_int32_t tm_gmtoff; +}; + +/* Delayed the include to avoid a circular reference */ +#include "apr_pools.h" + +/** + * Convert an ansi time_t to an apr_time_t + * @param result the resulting apr_time_t + * @param input the time_t to convert + */ +APR_DECLARE(apr_status_t) apr_time_ansi_put(apr_time_t *result, + time_t input); + +/** + * Convert a time to its human readable components using an offset + * from GMT. + * @param result the exploded time + * @param input the time to explode + * @param offs the number of seconds offset to apply + */ +APR_DECLARE(apr_status_t) apr_time_exp_tz(apr_time_exp_t *result, + apr_time_t input, + apr_int32_t offs); + +/** + * Convert a time to its human readable components (GMT). + * @param result the exploded time + * @param input the time to explode + */ +APR_DECLARE(apr_status_t) apr_time_exp_gmt(apr_time_exp_t *result, + apr_time_t input); + +/** + * Convert a time to its human readable components in the local timezone. + * @param result the exploded time + * @param input the time to explode + */ +APR_DECLARE(apr_status_t) apr_time_exp_lt(apr_time_exp_t *result, + apr_time_t input); + +/** + * Convert time value from human readable format to a numeric apr_time_t + * (elapsed microseconds since the epoch). + * @param result the resulting imploded time + * @param input the input exploded time + */ +APR_DECLARE(apr_status_t) apr_time_exp_get(apr_time_t *result, + apr_time_exp_t *input); + +/** + * Convert time value from human readable format to a numeric apr_time_t that + * always represents GMT. + * @param result the resulting imploded time + * @param input the input exploded time + */ +APR_DECLARE(apr_status_t) apr_time_exp_gmt_get(apr_time_t *result, + apr_time_exp_t *input); + +/** + * Sleep for the specified number of micro-seconds. + * @param t desired amount of time to sleep. + * @warning May sleep for longer than the specified time. + */ +APR_DECLARE(void) apr_sleep(apr_interval_time_t t); + +/** length of a RFC822 Date */ +#define APR_RFC822_DATE_LEN (30) +/** + * apr_rfc822_date formats dates in the RFC822 + * format in an efficient manner. It is a fixed length + * format which requires APR_RFC822_DATA_LEN bytes of storage, + * including the trailing NUL terminator. + * @param date_str String to write to. + * @param t the time to convert + */ +APR_DECLARE(apr_status_t) apr_rfc822_date(char *date_str, apr_time_t t); + +/** length of a CTIME date */ +#define APR_CTIME_LEN (25) +/** + * apr_ctime formats dates in the ctime() format + * in an efficient manner. It is a fixed length format + * and requires APR_CTIME_LEN bytes of storage including + * the trailing NUL terminator. + * Unlike ANSI/ISO C ctime(), apr_ctime() does not include + * a \\n at the end of the string. + * @param date_str String to write to. + * @param t the time to convert + */ +APR_DECLARE(apr_status_t) apr_ctime(char *date_str, apr_time_t t); + +/** + * Formats the exploded time according to the format specified + * @param s string to write to + * @param retsize The length of the returned string + * @param max The maximum length of the string + * @param format The format for the time string + * @param tm The time to convert + */ +APR_DECLARE(apr_status_t) apr_strftime(char *s, apr_size_t *retsize, + apr_size_t max, const char *format, + apr_time_exp_t *tm); + +/** + * Improve the clock resolution for the lifetime of the given pool. + * Generally this is only desirable on benchmarking and other very + * time-sensitive applications, and has no impact on most platforms. + * @param p The pool to associate the finer clock resolution + */ +APR_DECLARE(void) apr_time_clock_hires(apr_pool_t *p); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_TIME_H */ diff --git a/c/dependencies/linux/apr/include/apr_uri.h b/c/dependencies/linux/apr/include/apr_uri.h new file mode 100644 index 00000000..02908a9d --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_uri.h @@ -0,0 +1,178 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_uri.h: External Interface of apr_uri.c + */ + +/** + * @file apr_uri.h + * @brief APR-UTIL URI Routines + */ + +#ifndef APR_URI_H +#define APR_URI_H + +#include "apu.h" + +#include "apr_network_io.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_URI URI + * @ingroup APR_Util + * @{ + */ + +#define APR_URI_FTP_DEFAULT_PORT 21 /**< default FTP port */ +#define APR_URI_SSH_DEFAULT_PORT 22 /**< default SSH port */ +#define APR_URI_TELNET_DEFAULT_PORT 23 /**< default telnet port */ +#define APR_URI_GOPHER_DEFAULT_PORT 70 /**< default Gopher port */ +#define APR_URI_HTTP_DEFAULT_PORT 80 /**< default HTTP port */ +#define APR_URI_POP_DEFAULT_PORT 110 /**< default POP port */ +#define APR_URI_NNTP_DEFAULT_PORT 119 /**< default NNTP port */ +#define APR_URI_IMAP_DEFAULT_PORT 143 /**< default IMAP port */ +#define APR_URI_PROSPERO_DEFAULT_PORT 191 /**< default Prospero port */ +#define APR_URI_WAIS_DEFAULT_PORT 210 /**< default WAIS port */ +#define APR_URI_LDAP_DEFAULT_PORT 389 /**< default LDAP port */ +#define APR_URI_HTTPS_DEFAULT_PORT 443 /**< default HTTPS port */ +#define APR_URI_RTSP_DEFAULT_PORT 554 /**< default RTSP port */ +#define APR_URI_SNEWS_DEFAULT_PORT 563 /**< default SNEWS port */ +#define APR_URI_ACAP_DEFAULT_PORT 674 /**< default ACAP port */ +#define APR_URI_NFS_DEFAULT_PORT 2049 /**< default NFS port */ +#define APR_URI_TIP_DEFAULT_PORT 3372 /**< default TIP port */ +#define APR_URI_SIP_DEFAULT_PORT 5060 /**< default SIP port */ + +/** Flags passed to unparse_uri_components(): */ +/** suppress "scheme://user\@site:port" */ +#define APR_URI_UNP_OMITSITEPART (1U<<0) +/** Just omit user */ +#define APR_URI_UNP_OMITUSER (1U<<1) +/** Just omit password */ +#define APR_URI_UNP_OMITPASSWORD (1U<<2) +/** omit "user:password\@" part */ +#define APR_URI_UNP_OMITUSERINFO (APR_URI_UNP_OMITUSER | \ + APR_URI_UNP_OMITPASSWORD) +/** Show plain text password (default: show XXXXXXXX) */ +#define APR_URI_UNP_REVEALPASSWORD (1U<<3) +/** Show "scheme://user\@site:port" only */ +#define APR_URI_UNP_OMITPATHINFO (1U<<4) +/** Omit the "?queryarg" from the path */ +#define APR_URI_UNP_OMITQUERY (1U<<5) + +/** @see apr_uri_t */ +typedef struct apr_uri_t apr_uri_t; + +/** + * A structure to encompass all of the fields in a uri + */ +struct apr_uri_t { + /** scheme ("http"/"ftp"/...) */ + char *scheme; + /** combined [user[:password]\@]host[:port] */ + char *hostinfo; + /** user name, as in http://user:passwd\@host:port/ */ + char *user; + /** password, as in http://user:passwd\@host:port/ */ + char *password; + /** hostname from URI (or from Host: header) */ + char *hostname; + /** port string (integer representation is in "port") */ + char *port_str; + /** the request path (or NULL if only scheme://host was given) */ + char *path; + /** Everything after a '?' in the path, if present */ + char *query; + /** Trailing "#fragment" string, if present */ + char *fragment; + + /** structure returned from gethostbyname() */ + struct hostent *hostent; + + /** The port number, numeric, valid only if port_str != NULL */ + apr_port_t port; + + /** has the structure been initialized */ + unsigned is_initialized:1; + + /** has the DNS been looked up yet */ + unsigned dns_looked_up:1; + /** has the dns been resolved yet */ + unsigned dns_resolved:1; +}; + +/* apr_uri.c */ +/** + * Return the default port for a given scheme. The schemes recognized are + * http, ftp, https, gopher, wais, nntp, snews, and prospero + * @param scheme_str The string that contains the current scheme + * @return The default port for this scheme + */ +APU_DECLARE(apr_port_t) apr_uri_port_of_scheme(const char *scheme_str); + +/** + * Unparse a apr_uri_t structure to an URI string. Optionally + * suppress the password for security reasons. + * @param p The pool to allocate out of + * @param uptr All of the parts of the uri + * @param flags How to unparse the uri. One of: + *
+ *    APR_URI_UNP_OMITSITEPART        Suppress "scheme://user\@site:port" 
+ *    APR_URI_UNP_OMITUSER            Just omit user 
+ *    APR_URI_UNP_OMITPASSWORD        Just omit password 
+ *    APR_URI_UNP_OMITUSERINFO        Omit "user:password\@" part
+ *    APR_URI_UNP_REVEALPASSWORD      Show plain text password (default: show XXXXXXXX)
+ *    APR_URI_UNP_OMITPATHINFO        Show "scheme://user\@site:port" only 
+ *    APR_URI_UNP_OMITQUERY           Omit "?queryarg" or "#fragment" 
+ * 
+ * @return The uri as a string + */ +APU_DECLARE(char *) apr_uri_unparse(apr_pool_t *p, + const apr_uri_t *uptr, + unsigned flags); + +/** + * Parse a given URI, fill in all supplied fields of a apr_uri_t + * structure. This eliminates the necessity of extracting host, port, + * path, query info repeatedly in the modules. + * @param p The pool to allocate out of + * @param uri The uri to parse + * @param uptr The apr_uri_t to fill out + * @return APR_SUCCESS for success or error code + */ +APU_DECLARE(apr_status_t) apr_uri_parse(apr_pool_t *p, const char *uri, + apr_uri_t *uptr); + +/** + * Special case for CONNECT parsing: it comes with the hostinfo part only + * @param p The pool to allocate out of + * @param hostinfo The hostinfo string to parse + * @param uptr The apr_uri_t to fill out + * @return APR_SUCCESS for success or error code + */ +APU_DECLARE(apr_status_t) apr_uri_parse_hostinfo(apr_pool_t *p, + const char *hostinfo, + apr_uri_t *uptr); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_URI_H */ diff --git a/c/dependencies/linux/apr/include/apr_user.h b/c/dependencies/linux/apr/include/apr_user.h new file mode 100644 index 00000000..0e0a3ac5 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_user.h @@ -0,0 +1,158 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_USER_H +#define APR_USER_H + +/** + * @file apr_user.h + * @brief APR User ID Services + */ + +#include "apr.h" +#include "apr_errno.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_user User and Group ID Services + * @ingroup APR + * @{ + */ + +/** + * Structure for determining user ownership. + */ +#ifdef WIN32 +typedef PSID apr_uid_t; +#else +typedef uid_t apr_uid_t; +#endif + +/** + * Structure for determining group ownership. + */ +#ifdef WIN32 +typedef PSID apr_gid_t; +#else +typedef gid_t apr_gid_t; +#endif + +#if APR_HAS_USER + +/** + * Get the userid (and groupid) of the calling process + * @param userid Returns the user id + * @param groupid Returns the user's group id + * @param p The pool from which to allocate working space + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_uid_current(apr_uid_t *userid, + apr_gid_t *groupid, + apr_pool_t *p); + +/** + * Get the user name for a specified userid + * @param username Pointer to new string containing user name (on output) + * @param userid The userid + * @param p The pool from which to allocate the string + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_uid_name_get(char **username, apr_uid_t userid, + apr_pool_t *p); + +/** + * Get the userid (and groupid) for the specified username + * @param userid Returns the user id + * @param groupid Returns the user's group id + * @param username The username to look up + * @param p The pool from which to allocate working space + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_uid_get(apr_uid_t *userid, apr_gid_t *groupid, + const char *username, apr_pool_t *p); + +/** + * Get the home directory for the named user + * @param dirname Pointer to new string containing directory name (on output) + * @param username The named user + * @param p The pool from which to allocate the string + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_uid_homepath_get(char **dirname, + const char *username, + apr_pool_t *p); + +/** + * Compare two user identifiers for equality. + * @param left One uid to test + * @param right Another uid to test + * @return APR_SUCCESS if the apr_uid_t structures identify the same user, + * APR_EMISMATCH if not, APR_BADARG if an apr_uid_t is invalid. + * @remark This function is available only if APR_HAS_USER is defined. + */ +#if defined(WIN32) +APR_DECLARE(apr_status_t) apr_uid_compare(apr_uid_t left, apr_uid_t right); +#else +#define apr_uid_compare(left,right) (((left) == (right)) ? APR_SUCCESS : APR_EMISMATCH) +#endif + +/** + * Get the group name for a specified groupid + * @param groupname Pointer to new string containing group name (on output) + * @param groupid The groupid + * @param p The pool from which to allocate the string + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_gid_name_get(char **groupname, + apr_gid_t groupid, apr_pool_t *p); + +/** + * Get the groupid for a specified group name + * @param groupid Pointer to the group id (on output) + * @param groupname The group name to look up + * @param p The pool from which to allocate the string + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_gid_get(apr_gid_t *groupid, + const char *groupname, apr_pool_t *p); + +/** + * Compare two group identifiers for equality. + * @param left One gid to test + * @param right Another gid to test + * @return APR_SUCCESS if the apr_gid_t structures identify the same group, + * APR_EMISMATCH if not, APR_BADARG if an apr_gid_t is invalid. + * @remark This function is available only if APR_HAS_USER is defined. + */ +#if defined(WIN32) +APR_DECLARE(apr_status_t) apr_gid_compare(apr_gid_t left, apr_gid_t right); +#else +#define apr_gid_compare(left,right) (((left) == (right)) ? APR_SUCCESS : APR_EMISMATCH) +#endif + +#endif /* ! APR_HAS_USER */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_USER_H */ diff --git a/c/dependencies/linux/apr/include/apr_uuid.h b/c/dependencies/linux/apr/include/apr_uuid.h new file mode 100644 index 00000000..5312a9f6 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_uuid.h @@ -0,0 +1,76 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_uuid.h + * @brief APR UUID library + */ +#ifndef APR_UUID_H +#define APR_UUID_H + +#include "apu.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_UUID UUID Handling + * @ingroup APR + * @{ + */ + +/** + * we represent a UUID as a block of 16 bytes. + */ + +typedef struct { + unsigned char data[16]; /**< the actual UUID */ +} apr_uuid_t; + +/** UUIDs are formatted as: 00112233-4455-6677-8899-AABBCCDDEEFF */ +#define APR_UUID_FORMATTED_LENGTH 36 + + +/** + * Generate and return a (new) UUID + * @param uuid The resulting UUID + */ +APU_DECLARE(void) apr_uuid_get(apr_uuid_t *uuid); + +/** + * Format a UUID into a string, following the standard format + * @param buffer The buffer to place the formatted UUID string into. It must + * be at least APR_UUID_FORMATTED_LENGTH + 1 bytes long to hold + * the formatted UUID and a null terminator + * @param uuid The UUID to format + */ +APU_DECLARE(void) apr_uuid_format(char *buffer, const apr_uuid_t *uuid); + +/** + * Parse a standard-format string into a UUID + * @param uuid The resulting UUID + * @param uuid_str The formatted UUID + */ +APU_DECLARE(apr_status_t) apr_uuid_parse(apr_uuid_t *uuid, const char *uuid_str); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_UUID_H */ diff --git a/c/dependencies/linux/apr/include/apr_version.h b/c/dependencies/linux/apr/include/apr_version.h new file mode 100644 index 00000000..e96de383 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_version.h @@ -0,0 +1,164 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_VERSION_H +#define APR_VERSION_H + +/** + * @file apr_version.h + * @brief APR Versioning Interface + * + * APR's Version + * + * There are several different mechanisms for accessing the version. There + * is a string form, and a set of numbers; in addition, there are constants + * which can be compiled into your application, and you can query the library + * being used for its actual version. + * + * Note that it is possible for an application to detect that it has been + * compiled against a different version of APR by use of the compile-time + * constants and the use of the run-time query function. + * + * APR version numbering follows the guidelines specified in: + * + * http://apr.apache.org/versioning.html + */ + + +#define APR_COPYRIGHT "Copyright (c) 2000-2019 The Apache Software " \ + "Foundation or its licensors, as applicable." + +/* The numeric compile-time version constants. These constants are the + * authoritative version numbers for APR. + */ + +/** major version + * Major API changes that could cause compatibility problems for older + * programs such as structure size changes. No binary compatibility is + * possible across a change in the major version. + */ +#define APR_MAJOR_VERSION 1 + +/** minor version + * Minor API changes that do not cause binary compatibility problems. + * Reset to 0 when upgrading APR_MAJOR_VERSION + */ +#define APR_MINOR_VERSION 7 + +/** patch level + * The Patch Level never includes API changes, simply bug fixes. + * Reset to 0 when upgrading APR_MINOR_VERSION + */ +#define APR_PATCH_VERSION 0 + +/** + * The symbol APR_IS_DEV_VERSION is only defined for internal, + * "development" copies of APR. It is undefined for released versions + * of APR. + */ +/* #undef APR_IS_DEV_VERSION */ + +/** + * Check at compile time if the APR version is at least a certain + * level. + * @param major The major version component of the version checked + * for (e.g., the "1" of "1.3.0"). + * @param minor The minor version component of the version checked + * for (e.g., the "3" of "1.3.0"). + * @param patch The patch level component of the version checked + * for (e.g., the "0" of "1.3.0"). + * @remark This macro is available with APR versions starting with + * 1.3.0. + */ +#define APR_VERSION_AT_LEAST(major,minor,patch) \ +(((major) < APR_MAJOR_VERSION) \ + || ((major) == APR_MAJOR_VERSION && (minor) < APR_MINOR_VERSION) \ + || ((major) == APR_MAJOR_VERSION && (minor) == APR_MINOR_VERSION && (patch) <= APR_PATCH_VERSION)) + +#if defined(APR_IS_DEV_VERSION) || defined(DOXYGEN) +/** Internal: string form of the "is dev" flag */ +#ifndef APR_IS_DEV_STRING +#define APR_IS_DEV_STRING "-dev" +#endif +#else +#define APR_IS_DEV_STRING "" +#endif + +/* APR_STRINGIFY is defined here, and also in apr_general.h, so wrap it */ +#ifndef APR_STRINGIFY +/** Properly quote a value as a string in the C preprocessor */ +#define APR_STRINGIFY(n) APR_STRINGIFY_HELPER(n) +/** Helper macro for APR_STRINGIFY */ +#define APR_STRINGIFY_HELPER(n) #n +#endif + +/** The formatted string of APR's version */ +#define APR_VERSION_STRING \ + APR_STRINGIFY(APR_MAJOR_VERSION) "." \ + APR_STRINGIFY(APR_MINOR_VERSION) "." \ + APR_STRINGIFY(APR_PATCH_VERSION) \ + APR_IS_DEV_STRING + +/** An alternative formatted string of APR's version */ +/* macro for Win32 .rc files using numeric csv representation */ +#define APR_VERSION_STRING_CSV APR_MAJOR_VERSION ##, \ + ##APR_MINOR_VERSION ##, \ + ##APR_PATCH_VERSION + + +#ifndef APR_VERSION_ONLY + +/* The C language API to access the version at run time, + * as opposed to compile time. APR_VERSION_ONLY may be defined + * externally when preprocessing apr_version.h to obtain strictly + * the C Preprocessor macro declarations. + */ + +#include "apr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The numeric version information is broken out into fields within this + * structure. + */ +typedef struct { + int major; /**< major number */ + int minor; /**< minor number */ + int patch; /**< patch number */ + int is_dev; /**< is development (1 or 0) */ +} apr_version_t; + +/** + * Return APR's version information information in a numeric form. + * + * @param pvsn Pointer to a version structure for returning the version + * information. + */ +APR_DECLARE(void) apr_version(apr_version_t *pvsn); + +/** Return APR's version information as a string. */ +APR_DECLARE(const char *) apr_version_string(void); + +#ifdef __cplusplus +} +#endif + +#endif /* ndef APR_VERSION_ONLY */ + +#endif /* ndef APR_VERSION_H */ diff --git a/c/dependencies/linux/apr/include/apr_want.h b/c/dependencies/linux/apr/include/apr_want.h new file mode 100644 index 00000000..2863b001 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_want.h @@ -0,0 +1,124 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr.h" /* configuration data */ +/** + * @file apr_want.h + * @brief APR Standard Headers Support + * + *
+ * Features:
+ *
+ *   APR_WANT_STRFUNC:  strcmp, strcat, strcpy, etc
+ *   APR_WANT_MEMFUNC:  memcmp, memcpy, etc
+ *   APR_WANT_STDIO:     and related bits
+ *   APR_WANT_IOVEC:    struct iovec
+ *   APR_WANT_BYTEFUNC: htons, htonl, ntohl, ntohs
+ *
+ * Typical usage:
+ *
+ *   \#define APR_WANT_STRFUNC
+ *   \#define APR_WANT_MEMFUNC
+ *   \#include "apr_want.h"
+ *
+ * The appropriate headers will be included.
+ *
+ * Note: it is safe to use this in a header (it won't interfere with other
+ *       headers' or source files' use of apr_want.h)
+ * 
+ */ + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_STRFUNC + +#if APR_HAVE_STRING_H +#include +#endif +#if APR_HAVE_STRINGS_H +#include +#endif + +#undef APR_WANT_STRFUNC +#endif + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_MEMFUNC + +#if APR_HAVE_STRING_H +#include +#endif + +#undef APR_WANT_MEMFUNC +#endif + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_STDIO + +#if APR_HAVE_STDIO_H +#include +#endif + +#undef APR_WANT_STDIO +#endif + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_IOVEC + +#if APR_HAVE_IOVEC + +#if APR_HAVE_SYS_UIO_H +#include +#endif + +#else + +#ifndef APR_IOVEC_DEFINED +#define APR_IOVEC_DEFINED +struct iovec +{ + void *iov_base; + size_t iov_len; +}; +#endif /* !APR_IOVEC_DEFINED */ + +#endif /* APR_HAVE_IOVEC */ + +#undef APR_WANT_IOVEC +#endif + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_BYTEFUNC + +/* Single Unix says they are in arpa/inet.h. Linux has them in + * netinet/in.h. FreeBSD has them in arpa/inet.h but requires that + * netinet/in.h be included first. + */ +#if APR_HAVE_NETINET_IN_H +#include +#endif +#if APR_HAVE_ARPA_INET_H +#include +#endif + +#undef APR_WANT_BYTEFUNC +#endif + +/* --------------------------------------------------------------------- */ diff --git a/c/dependencies/linux/apr/include/apr_xlate.h b/c/dependencies/linux/apr/include/apr_xlate.h new file mode 100644 index 00000000..32636685 --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_xlate.h @@ -0,0 +1,163 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_XLATE_H +#define APR_XLATE_H + +#include "apu.h" +#include "apr_pools.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @file apr_xlate.h + * @brief APR I18N translation library + */ + +/** + * @defgroup APR_XLATE I18N translation library + * @ingroup APR + * @{ + */ +/** Opaque translation buffer */ +typedef struct apr_xlate_t apr_xlate_t; + +/** + * Set up for converting text from one charset to another. + * @param convset The handle to be filled in by this function + * @param topage The name of the target charset + * @param frompage The name of the source charset + * @param pool The pool to use + * @remark + * Specify APR_DEFAULT_CHARSET for one of the charset + * names to indicate the charset of the source code at + * compile time. This is useful if there are literal + * strings in the source code which must be translated + * according to the charset of the source code. + * APR_DEFAULT_CHARSET is not useful if the source code + * of the caller was not encoded in the same charset as + * APR at compile time. + * + * @remark + * Specify APR_LOCALE_CHARSET for one of the charset + * names to indicate the charset of the current locale. + * + * @remark + * Return APR_EINVAL if unable to procure a convset, or APR_ENOTIMPL + * if charset transcoding is not available in this instance of + * apr-util at all (i.e., APR_HAS_XLATE is undefined). + */ +APU_DECLARE(apr_status_t) apr_xlate_open(apr_xlate_t **convset, + const char *topage, + const char *frompage, + apr_pool_t *pool); + +/** + * This is to indicate the charset of the sourcecode at compile time + * names to indicate the charset of the source code at + * compile time. This is useful if there are literal + * strings in the source code which must be translated + * according to the charset of the source code. + */ +#define APR_DEFAULT_CHARSET (const char *)0 +/** + * To indicate charset names of the current locale + */ +#define APR_LOCALE_CHARSET (const char *)1 + +/** + * Find out whether or not the specified conversion is single-byte-only. + * @param convset The handle allocated by apr_xlate_open, specifying the + * parameters of conversion + * @param onoff Output: whether or not the conversion is single-byte-only + * @remark + * Return APR_ENOTIMPL if charset transcoding is not available + * in this instance of apr-util (i.e., APR_HAS_XLATE is undefined). + */ +APU_DECLARE(apr_status_t) apr_xlate_sb_get(apr_xlate_t *convset, int *onoff); + +/** + * Convert a buffer of text from one codepage to another. + * @param convset The handle allocated by apr_xlate_open, specifying + * the parameters of conversion + * @param inbuf The address of the source buffer + * @param inbytes_left Input: the amount of input data to be translated + * Output: the amount of input data not yet translated + * @param outbuf The address of the destination buffer + * @param outbytes_left Input: the size of the output buffer + * Output: the amount of the output buffer not yet used + * @remark + * Returns APR_ENOTIMPL if charset transcoding is not available + * in this instance of apr-util (i.e., APR_HAS_XLATE is undefined). + * Returns APR_INCOMPLETE if the input buffer ends in an incomplete + * multi-byte character. + * + * To correctly terminate the output buffer for some multi-byte + * character set encodings, a final call must be made to this function + * after the complete input string has been converted, passing + * the inbuf and inbytes_left parameters as NULL. (Note that this + * mode only works from version 1.1.0 onwards) + */ +APU_DECLARE(apr_status_t) apr_xlate_conv_buffer(apr_xlate_t *convset, + const char *inbuf, + apr_size_t *inbytes_left, + char *outbuf, + apr_size_t *outbytes_left); + +/* @see apr_file_io.h the comment in apr_file_io.h about this hack */ +#ifdef APR_NOT_DONE_YET +/** + * The purpose of apr_xlate_conv_char is to translate one character + * at a time. This needs to be written carefully so that it works + * with double-byte character sets. + * @param convset The handle allocated by apr_xlate_open, specifying the + * parameters of conversion + * @param inchar The character to convert + * @param outchar The converted character + */ +APU_DECLARE(apr_status_t) apr_xlate_conv_char(apr_xlate_t *convset, + char inchar, char outchar); +#endif + +/** + * Convert a single-byte character from one charset to another. + * @param convset The handle allocated by apr_xlate_open, specifying the + * parameters of conversion + * @param inchar The single-byte character to convert. + * @warning This only works when converting between single-byte character sets. + * -1 will be returned if the conversion can't be performed. + */ +APU_DECLARE(apr_int32_t) apr_xlate_conv_byte(apr_xlate_t *convset, + unsigned char inchar); + +/** + * Close a codepage translation handle. + * @param convset The codepage translation handle to close + * @remark + * Return APR_ENOTIMPL if charset transcoding is not available + * in this instance of apr-util (i.e., APR_HAS_XLATE is undefined). + */ +APU_DECLARE(apr_status_t) apr_xlate_close(apr_xlate_t *convset); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_XLATE_H */ diff --git a/c/dependencies/linux/apr/include/apr_xml.h b/c/dependencies/linux/apr/include/apr_xml.h new file mode 100644 index 00000000..87a696cc --- /dev/null +++ b/c/dependencies/linux/apr/include/apr_xml.h @@ -0,0 +1,358 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file apr_xml.h + * @brief APR-UTIL XML Library + */ +#ifndef APR_XML_H +#define APR_XML_H + +/** + * @defgroup APR_Util_XML XML + * @ingroup APR_Util + * @{ + */ +#include "apr_pools.h" +#include "apr_tables.h" +#include "apr_file_io.h" + +#include "apu.h" +#if APR_CHARSET_EBCDIC +#include "apr_xlate.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @package Apache XML library + */ + +/* -------------------------------------------------------------------- */ + +/* ### these will need to move at some point to a more logical spot */ + +/** @see apr_text */ +typedef struct apr_text apr_text; + +/** Structure to keep a linked list of pieces of text */ +struct apr_text { + /** The current piece of text */ + const char *text; + /** a pointer to the next piece of text */ + struct apr_text *next; +}; + +/** @see apr_text_header */ +typedef struct apr_text_header apr_text_header; + +/** A list of pieces of text */ +struct apr_text_header { + /** The first piece of text in the list */ + apr_text *first; + /** The last piece of text in the list */ + apr_text *last; +}; + +/** + * Append a piece of text to the end of a list + * @param p The pool to allocate out of + * @param hdr The text header to append to + * @param text The new text to append + */ +APU_DECLARE(void) apr_text_append(apr_pool_t *p, apr_text_header *hdr, + const char *text); + + +/* -------------------------------------------------------------------- +** +** XML PARSING +*/ + +/* +** Qualified namespace values +** +** APR_XML_NS_DAV_ID +** We always insert the "DAV:" namespace URI at the head of the +** namespace array. This means that it will always be at ID==0, +** making it much easier to test for. +** +** APR_XML_NS_NONE +** This special ID is used for two situations: +** +** 1) The namespace prefix begins with "xml" (and we do not know +** what it means). Namespace prefixes with "xml" (any case) as +** their first three characters are reserved by the XML Namespaces +** specification for future use. mod_dav will pass these through +** unchanged. When this identifier is used, the prefix is LEFT in +** the element/attribute name. Downstream processing should not +** prepend another prefix. +** +** 2) The element/attribute does not have a namespace. +** +** a) No prefix was used, and a default namespace has not been +** defined. +** b) No prefix was used, and the default namespace was specified +** to mean "no namespace". This is done with a namespace +** declaration of: xmlns="" +** (this declaration is typically used to override a previous +** specification for the default namespace) +** +** In these cases, we need to record that the elem/attr has no +** namespace so that we will not attempt to prepend a prefix. +** All namespaces that are used will have a prefix assigned to +** them -- mod_dav will never set or use the default namespace +** when generating XML. This means that "no prefix" will always +** mean "no namespace". +** +** In both cases, the XML generation will avoid prepending a prefix. +** For the first case, this means the original prefix/name will be +** inserted into the output stream. For the latter case, it means +** the name will have no prefix, and since we never define a default +** namespace, this means it will have no namespace. +** +** Note: currently, mod_dav understands the "xmlns" prefix and the +** "xml:lang" attribute. These are handled specially (they aren't +** left within the XML tree), so the APR_XML_NS_NONE value won't ever +** really apply to these values. +*/ +#define APR_XML_NS_DAV_ID 0 /**< namespace ID for "DAV:" */ +#define APR_XML_NS_NONE -10 /**< no namespace for this elem/attr */ + +#define APR_XML_NS_ERROR_BASE -100 /**< used only during processing */ +/** Is this namespace an error? */ +#define APR_XML_NS_IS_ERROR(e) ((e) <= APR_XML_NS_ERROR_BASE) + +/** @see apr_xml_attr */ +typedef struct apr_xml_attr apr_xml_attr; +/** @see apr_xml_elem */ +typedef struct apr_xml_elem apr_xml_elem; +/** @see apr_xml_doc */ +typedef struct apr_xml_doc apr_xml_doc; + +/** apr_xml_attr: holds a parsed XML attribute */ +struct apr_xml_attr { + /** attribute name */ + const char *name; + /** index into namespace array */ + int ns; + + /** attribute value */ + const char *value; + + /** next attribute */ + struct apr_xml_attr *next; +}; + +/** apr_xml_elem: holds a parsed XML element */ +struct apr_xml_elem { + /** element name */ + const char *name; + /** index into namespace array */ + int ns; + /** xml:lang for attrs/contents */ + const char *lang; + + /** cdata right after start tag */ + apr_text_header first_cdata; + /** cdata after MY end tag */ + apr_text_header following_cdata; + + /** parent element */ + struct apr_xml_elem *parent; + /** next (sibling) element */ + struct apr_xml_elem *next; + /** first child element */ + struct apr_xml_elem *first_child; + /** first attribute */ + struct apr_xml_attr *attr; + + /* used only during parsing */ + /** last child element */ + struct apr_xml_elem *last_child; + /** namespaces scoped by this elem */ + struct apr_xml_ns_scope *ns_scope; + + /* used by modules during request processing */ + /** Place for modules to store private data */ + void *priv; +}; + +/** Is this XML element empty? */ +#define APR_XML_ELEM_IS_EMPTY(e) ((e)->first_child == NULL && \ + (e)->first_cdata.first == NULL) + +/** apr_xml_doc: holds a parsed XML document */ +struct apr_xml_doc { + /** root element */ + apr_xml_elem *root; + /** array of namespaces used */ + apr_array_header_t *namespaces; +}; + +/** Opaque XML parser structure */ +typedef struct apr_xml_parser apr_xml_parser; + +/** + * Create an XML parser + * @param pool The pool for allocating the parser and the parse results. + * @return The new parser. + */ +APU_DECLARE(apr_xml_parser *) apr_xml_parser_create(apr_pool_t *pool); + +/** + * Parse a File, producing a xml_doc + * @param p The pool for allocating the parse results. + * @param parser A pointer to *parser (needed so calling function can get + * errors), will be set to NULL on successful completion. + * @param ppdoc A pointer to *apr_xml_doc (which has the parsed results in it) + * @param xmlfd A file to read from. + * @param buffer_length Buffer length which would be suitable + * @return Any errors found during parsing. + */ +APU_DECLARE(apr_status_t) apr_xml_parse_file(apr_pool_t *p, + apr_xml_parser **parser, + apr_xml_doc **ppdoc, + apr_file_t *xmlfd, + apr_size_t buffer_length); + + +/** + * Feed input into the parser + * @param parser The XML parser for parsing this data. + * @param data The data to parse. + * @param len The length of the data. + * @return Any errors found during parsing. + * @remark Use apr_xml_parser_geterror() to get more error information. + */ +APU_DECLARE(apr_status_t) apr_xml_parser_feed(apr_xml_parser *parser, + const char *data, + apr_size_t len); + +/** + * Terminate the parsing and return the result + * @param parser The XML parser for parsing this data. + * @param pdoc The resulting parse information. May be NULL to simply + * terminate the parsing without fetching the info. + * @return Any errors found during the final stage of parsing. + * @remark Use apr_xml_parser_geterror() to get more error information. + */ +APU_DECLARE(apr_status_t) apr_xml_parser_done(apr_xml_parser *parser, + apr_xml_doc **pdoc); + +/** + * Fetch additional error information from the parser. + * @param parser The XML parser to query for errors. + * @param errbuf A buffer for storing error text. + * @param errbufsize The length of the error text buffer. + * @return The error buffer + */ +APU_DECLARE(char *) apr_xml_parser_geterror(apr_xml_parser *parser, + char *errbuf, + apr_size_t errbufsize); + + +/** + * Converts an XML element tree to flat text + * @param p The pool to allocate out of + * @param elem The XML element to convert + * @param style How to covert the XML. One of: + *
+ *     APR_XML_X2T_FULL                start tag, contents, end tag 
+ *     APR_XML_X2T_INNER               contents only 
+ *     APR_XML_X2T_LANG_INNER          xml:lang + inner contents 
+ *     APR_XML_X2T_FULL_NS_LANG        FULL + ns defns + xml:lang 
+ *     APR_XML_X2T_PARSED              original prefixes
+ * 
+ * @param namespaces The namespace of the current XML element + * @param ns_map Namespace mapping + * @param pbuf Buffer to put the converted text into + * @param psize Size of the converted text + */ +APU_DECLARE(void) apr_xml_to_text(apr_pool_t *p, const apr_xml_elem *elem, + int style, apr_array_header_t *namespaces, + int *ns_map, const char **pbuf, + apr_size_t *psize); + +/* style argument values: */ +#define APR_XML_X2T_FULL 0 /**< start tag, contents, end tag */ +#define APR_XML_X2T_INNER 1 /**< contents only */ +#define APR_XML_X2T_LANG_INNER 2 /**< xml:lang + inner contents */ +#define APR_XML_X2T_FULL_NS_LANG 3 /**< FULL + ns defns + xml:lang */ +#define APR_XML_X2T_PARSED 4 /**< original prefixes */ + +/** + * empty XML element + * @param p The pool to allocate out of + * @param elem The XML element to empty + * @return the string that was stored in the XML element + */ +APU_DECLARE(const char *) apr_xml_empty_elem(apr_pool_t *p, + const apr_xml_elem *elem); + +/** + * quote an XML string + * Replace '\<', '\>', and '\&' with '\<', '\>', and '\&'. + * @param p The pool to allocate out of + * @param s The string to quote + * @param quotes If quotes is true, then replace '"' with '\"'. + * @return The quoted string + * @note If the string does not contain special characters, it is not + * duplicated into the pool and the original string is returned. + */ +APU_DECLARE(const char *) apr_xml_quote_string(apr_pool_t *p, const char *s, + int quotes); + +/** + * Quote an XML element + * @param p The pool to allocate out of + * @param elem The element to quote + */ +APU_DECLARE(void) apr_xml_quote_elem(apr_pool_t *p, apr_xml_elem *elem); + +/* manage an array of unique URIs: apr_xml_insert_uri() and APR_XML_URI_ITEM() */ + +/** + * return the URI's (existing) index, or insert it and return a new index + * @param uri_array array to insert into + * @param uri The uri to insert + * @return int The uri's index + */ +APU_DECLARE(int) apr_xml_insert_uri(apr_array_header_t *uri_array, + const char *uri); + +/** Get the URI item for this XML element */ +#define APR_XML_GET_URI_ITEM(ary, i) (((const char * const *)(ary)->elts)[i]) + +#if APR_CHARSET_EBCDIC +/** + * Convert parsed tree in EBCDIC + * @param p The pool to allocate out of + * @param pdoc The apr_xml_doc to convert. + * @param xlate The translation handle to use. + * @return Any errors found during conversion. + */ +APU_DECLARE(apr_status_t) apr_xml_parser_convert_doc(apr_pool_t *p, + apr_xml_doc *pdoc, + apr_xlate_t *convset); +#endif + +#ifdef __cplusplus +} +#endif +/** @} */ +#endif /* APR_XML_H */ diff --git a/c/dependencies/linux/apr/include/apu.h b/c/dependencies/linux/apr/include/apu.h new file mode 100644 index 00000000..5b5d59b1 --- /dev/null +++ b/c/dependencies/linux/apr/include/apu.h @@ -0,0 +1,128 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apu.h is generated from apu.h.in by configure -- do not edit apu.h + */ +/* @file apu.h + * @brief APR-Utility main file + */ +/** + * @defgroup APR_Util APR Utility Functions + * @{ + */ + + +#ifndef APU_H +#define APU_H + +/** + * APU_DECLARE_EXPORT is defined when building the APR-UTIL dynamic library, + * so that all public symbols are exported. + * + * APU_DECLARE_STATIC is defined when including the APR-UTIL public headers, + * to provide static linkage when the dynamic library may be unavailable. + * + * APU_DECLARE_STATIC and APU_DECLARE_EXPORT are left undefined when + * including the APR-UTIL public headers, to import and link the symbols from + * the dynamic APR-UTIL library and assure appropriate indirection and calling + * conventions at compile time. + */ + +#if defined(DOXYGEN) || !defined(WIN32) +/** + * The public APR-UTIL functions are declared with APU_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APU_DECLARE_NONSTD(). + * + * @fn APU_DECLARE(rettype) apr_func(args); + */ +#define APU_DECLARE(type) type +/** + * The public APR-UTIL functions using variable arguments are declared with + * APU_DECLARE_NONSTD(), as they must use the C language calling convention. + * + * @fn APU_DECLARE_NONSTD(rettype) apr_func(args, ...); + */ +#define APU_DECLARE_NONSTD(type) type +/** + * The public APR-UTIL variables are declared with APU_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * + * @fn APU_DECLARE_DATA type apr_variable; + * @note APU_DECLARE_DATA extern type apr_variable; syntax is required for + * declarations within headers to properly import the variable. + */ +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_STATIC) +#define APU_DECLARE(type) type __stdcall +#define APU_DECLARE_NONSTD(type) type __cdecl +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_EXPORT) +#define APU_DECLARE(type) __declspec(dllexport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllexport) +#else +#define APU_DECLARE(type) __declspec(dllimport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllimport) +#endif + +#if !defined(WIN32) || defined(APU_MODULE_DECLARE_STATIC) +/** + * Declare a dso module's exported module structure as APU_MODULE_DECLARE_DATA. + * + * Unless APU_MODULE_DECLARE_STATIC is defined at compile time, symbols + * declared with APU_MODULE_DECLARE_DATA are always exported. + * @code + * module APU_MODULE_DECLARE_DATA mod_tag + * @endcode + */ +#define APU_MODULE_DECLARE_DATA +#else +#define APU_MODULE_DECLARE_DATA __declspec(dllexport) +#endif + +/* + * we always have SDBM (it's in our codebase) + */ +#define APU_HAVE_SDBM 1 +#define APU_HAVE_GDBM 0 +#define APU_HAVE_NDBM 0 +#define APU_HAVE_DB 0 + +#if APU_HAVE_DB +#define APU_HAVE_DB_VERSION 0 +#endif + +#define APU_HAVE_PGSQL 0 +#define APU_HAVE_MYSQL 0 +#define APU_HAVE_SQLITE3 1 +#define APU_HAVE_SQLITE2 0 +#define APU_HAVE_ORACLE 0 +#define APU_HAVE_ODBC 0 + +#define APU_HAVE_CRYPTO 0 +#define APU_HAVE_OPENSSL 0 +#define APU_HAVE_NSS 0 +#define APU_HAVE_COMMONCRYPTO 0 + +#define APU_HAVE_APR_ICONV 0 +#define APU_HAVE_ICONV 1 +#define APR_HAS_XLATE (APU_HAVE_APR_ICONV || APU_HAVE_ICONV) + +#endif /* APU_H */ +/** @} */ diff --git a/c/dependencies/linux/apr/include/apu_errno.h b/c/dependencies/linux/apr/include/apu_errno.h new file mode 100644 index 00000000..c0a8ec7d --- /dev/null +++ b/c/dependencies/linux/apr/include/apu_errno.h @@ -0,0 +1,173 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APU_ERRNO_H +#define APU_ERRNO_H + +/** + * @file apu_errno.h + * @brief APR-Util Error Codes + */ + +#include "apr.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apu_errno Error Codes + * @ingroup APR_Util + * @{ + */ + +/** + * @defgroup APR_Util_Error APR_Util Error Values + *
+ * APU ERROR VALUES
+ * APR_ENOKEY         The key provided was empty or NULL
+ * APR_ENOIV          The initialisation vector provided was NULL
+ * APR_EKEYTYPE       The key type was not recognised
+ * APR_ENOSPACE       The buffer supplied was not big enough
+ * APR_ECRYPT         An error occurred while encrypting or decrypting
+ * APR_EPADDING       Padding was not supported
+ * APR_EKEYLENGTH     The key length was incorrect
+ * APR_ENOCIPHER      The cipher provided was not recognised
+ * APR_ENODIGEST      The digest provided was not recognised
+ * APR_ENOENGINE      The engine provided was not recognised
+ * APR_EINITENGINE    The engine could not be initialised
+ * APR_EREINIT        Underlying crypto has already been initialised
+ * 
+ * + *
+ * APR STATUS VALUES
+ * APR_INCHILD        Program is currently executing in the child
+ * 
+ * @{ + */ +/** @see APR_STATUS_IS_ENOKEY */ +#define APR_ENOKEY (APR_UTIL_START_STATUS + 1) +/** @see APR_STATUS_IS_ENOIV */ +#define APR_ENOIV (APR_UTIL_START_STATUS + 2) +/** @see APR_STATUS_IS_EKEYTYPE */ +#define APR_EKEYTYPE (APR_UTIL_START_STATUS + 3) +/** @see APR_STATUS_IS_ENOSPACE */ +#define APR_ENOSPACE (APR_UTIL_START_STATUS + 4) +/** @see APR_STATUS_IS_ECRYPT */ +#define APR_ECRYPT (APR_UTIL_START_STATUS + 5) +/** @see APR_STATUS_IS_EPADDING */ +#define APR_EPADDING (APR_UTIL_START_STATUS + 6) +/** @see APR_STATUS_IS_EKEYLENGTH */ +#define APR_EKEYLENGTH (APR_UTIL_START_STATUS + 7) +/** @see APR_STATUS_IS_ENOCIPHER */ +#define APR_ENOCIPHER (APR_UTIL_START_STATUS + 8) +/** @see APR_STATUS_IS_ENODIGEST */ +#define APR_ENODIGEST (APR_UTIL_START_STATUS + 9) +/** @see APR_STATUS_IS_ENOENGINE */ +#define APR_ENOENGINE (APR_UTIL_START_STATUS + 10) +/** @see APR_STATUS_IS_EINITENGINE */ +#define APR_EINITENGINE (APR_UTIL_START_STATUS + 11) +/** @see APR_STATUS_IS_EREINIT */ +#define APR_EREINIT (APR_UTIL_START_STATUS + 12) +/** @} */ + +/** + * @defgroup APU_STATUS_IS Status Value Tests + * @warning For any particular error condition, more than one of these tests + * may match. This is because platform-specific error codes may not + * always match the semantics of the POSIX codes these tests (and the + * corresponding APR error codes) are named after. A notable example + * are the APR_STATUS_IS_ENOENT and APR_STATUS_IS_ENOTDIR tests on + * Win32 platforms. The programmer should always be aware of this and + * adjust the order of the tests accordingly. + * @{ + */ + +/** @} */ + +/** + * @addtogroup APR_Util_Error + * @{ + */ +/** + * The key was empty or not provided + */ +#define APR_STATUS_IS_ENOKEY(s) ((s) == APR_ENOKEY) +/** + * The initialisation vector was not provided + */ +#define APR_STATUS_IS_ENOIV(s) ((s) == APR_ENOIV) +/** + * The key type was not recognised + */ +#define APR_STATUS_IS_EKEYTYPE(s) ((s) == APR_EKEYTYPE) +/** + * The buffer provided was not big enough + */ +#define APR_STATUS_IS_ENOSPACE(s) ((s) == APR_ENOSPACE) +/** + * An error occurred while encrypting or decrypting + */ +#define APR_STATUS_IS_ECRYPT(s) ((s) == APR_ECRYPT) +/** + * An error occurred while padding + */ +#define APR_STATUS_IS_EPADDING(s) ((s) == APR_EPADDING) +/** + * An error occurred with the key length + */ +#define APR_STATUS_IS_EKEYLENGTH(s) ((s) == APR_EKEYLENGTH) +/** + * The cipher provided was not recognised + */ +#define APR_STATUS_IS_ENOCIPHER(s) ((s) == APR_ENOCIPHER) +/** + * The digest provided was not recognised + */ +#define APR_STATUS_IS_ENODIGEST(s) ((s) == APR_ENODIGEST) +/** + * The engine provided was not recognised + */ +#define APR_STATUS_IS_ENOENGINE(s) ((s) == APR_ENOENGINE) +/** + * The engine could not be initialised + */ +#define APR_STATUS_IS_EINITENGINE(s) ((s) == APR_EINITENGINE) +/** + * Crypto has already been initialised + */ +#define APR_STATUS_IS_EREINIT(s) ((s) == APR_EREINIT) +/** @} */ + +/** + * This structure allows the underlying API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apu_err_t { + const char *reason; + const char *msg; + int rc; +} apu_err_t; + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APU_ERRNO_H */ diff --git a/c/dependencies/linux/apr/include/apu_version.h b/c/dependencies/linux/apr/include/apu_version.h new file mode 100644 index 00000000..e4fb2e64 --- /dev/null +++ b/c/dependencies/linux/apr/include/apu_version.h @@ -0,0 +1,139 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APU_VERSION_H +#define APU_VERSION_H + +/** + * @file apu_version.h + * @brief APR-util Versioning Interface + * + * APR-util's Version + * + * There are several different mechanisms for accessing the version. There + * is a string form, and a set of numbers; in addition, there are constants + * which can be compiled into your application, and you can query the library + * being used for its actual version. + * + * Note that it is possible for an application to detect that it has been + * compiled against a different version of APU by use of the compile-time + * constants and the use of the run-time query function. + * + * APU version numbering follows the guidelines specified in: + * + * http://apr.apache.org/versioning.html + */ + + +#define APU_COPYRIGHT "Copyright (c) 2000-2016 The Apache Software " \ + "Foundation or its licensors, as applicable." + +/* The numeric compile-time version constants. These constants are the + * authoritative version numbers for APU. + */ + +/** major version + * Major API changes that could cause compatibility problems for older + * programs such as structure size changes. No binary compatibility is + * possible across a change in the major version. + */ +#define APU_MAJOR_VERSION 1 + +/** minor version + * Minor API changes that do not cause binary compatibility problems. + * Reset to 0 when upgrading APU_MAJOR_VERSION + */ +#define APU_MINOR_VERSION 6 + +/** patch level + * The Patch Level never includes API changes, simply bug fixes. + * Reset to 0 when upgrading APR_MINOR_VERSION + */ +#define APU_PATCH_VERSION 1 + +/** + * The symbol APU_IS_DEV_VERSION is only defined for internal, + * "development" copies of APU. It is undefined for released versions + * of APU. + */ +/* #undef APU_IS_DEV_VERSION */ + + +#if defined(APU_IS_DEV_VERSION) || defined(DOXYGEN) +/** Internal: string form of the "is dev" flag */ +#ifndef APU_IS_DEV_STRING +#define APU_IS_DEV_STRING "-dev" +#endif +#else +#define APU_IS_DEV_STRING "" +#endif + + +#ifndef APU_STRINGIFY +/** Properly quote a value as a string in the C preprocessor */ +#define APU_STRINGIFY(n) APU_STRINGIFY_HELPER(n) +/** Helper macro for APU_STRINGIFY */ +#define APU_STRINGIFY_HELPER(n) #n +#endif + +/** The formatted string of APU's version */ +#define APU_VERSION_STRING \ + APU_STRINGIFY(APU_MAJOR_VERSION) "." \ + APU_STRINGIFY(APU_MINOR_VERSION) "." \ + APU_STRINGIFY(APU_PATCH_VERSION) \ + APU_IS_DEV_STRING + +/** An alternative formatted string of APR's version */ +/* macro for Win32 .rc files using numeric csv representation */ +#define APU_VERSION_STRING_CSV APU_MAJOR_VERSION ##, \ + ##APU_MINOR_VERSION ##, \ + ##APU_PATCH_VERSION + + +#ifndef APU_VERSION_ONLY + +/* The C language API to access the version at run time, + * as opposed to compile time. APU_VERSION_ONLY may be defined + * externally when preprocessing apr_version.h to obtain strictly + * the C Preprocessor macro declarations. + */ + +#include "apr_version.h" + +#include "apu.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Return APR-util's version information information in a numeric form. + * + * @param pvsn Pointer to a version structure for returning the version + * information. + */ +APU_DECLARE(void) apu_version(apr_version_t *pvsn); + +/** Return APU's version information as a string. */ +APU_DECLARE(const char *) apu_version_string(void); + +#ifdef __cplusplus +} +#endif + +#endif /* ndef APU_VERSION_ONLY */ + +#endif /* ndef APU_VERSION_H */ diff --git a/c/dependencies/linux/apr/include/apu_want.h b/c/dependencies/linux/apr/include/apu_want.h new file mode 100644 index 00000000..25f1100d --- /dev/null +++ b/c/dependencies/linux/apr/include/apu_want.h @@ -0,0 +1,51 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apu.h" /* configuration data */ + +/** + * @file apu_want.h + * @brief APR Standard Headers Support + * + *
+ * Features:
+ *
+ *   APU_WANT_DB:       
+ *
+ * Typical usage:
+ *
+ *   #define APU_WANT_DB
+ *   #include "apu_want.h"
+ *
+ * The appropriate headers will be included.
+ *
+ * Note: it is safe to use this in a header (it won't interfere with other
+ *       headers' or source files' use of apu_want.h)
+ * 
+ */ + +/* --------------------------------------------------------------------- */ + +#ifdef APU_WANT_DB + +#if APU_HAVE_DB +#include +#endif + +#undef APU_WANT_DB +#endif + +/* --------------------------------------------------------------------- */ diff --git a/c/dependencies/linux/apr/lib/x86_64/libapr.a b/c/dependencies/linux/apr/lib/x86_64/libapr.a new file mode 100644 index 00000000..796fb93a Binary files /dev/null and b/c/dependencies/linux/apr/lib/x86_64/libapr.a differ diff --git a/c/dependencies/linux/apr/lib/x86_64/libaprutil.a b/c/dependencies/linux/apr/lib/x86_64/libaprutil.a new file mode 100644 index 00000000..4ff71c19 Binary files /dev/null and b/c/dependencies/linux/apr/lib/x86_64/libaprutil.a differ diff --git a/c/dependencies/macos/apr/include/apr.h b/c/dependencies/macos/apr/include/apr.h new file mode 100644 index 00000000..a4d3e26a --- /dev/null +++ b/c/dependencies/macos/apr/include/apr.h @@ -0,0 +1,656 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef APR_H +#define APR_H + +/* GENERATED FILE WARNING! DO NOT EDIT apr.h + * + * You must modify apr.h.in instead. + * + * And please, make an effort to stub apr.hw and apr.hnw in the process. + */ + +/** + * @file apr.h + * @brief APR Platform Definitions + * @remark This is a generated header generated from include/apr.h.in by + * ./configure, or copied from include/apr.hw or include/apr.hnw + * for Win32 or Netware by those build environments, respectively. + */ + +/** + * @defgroup APR Apache Portability Runtime library + * @{ + */ +/** + * @defgroup apr_platform Platform Definitions + * @{ + * @warning + * The actual values of macros and typedefs on this page
+ * are platform specific and should NOT be relied upon!
+ */ + +/* So that we can use inline on some critical functions, and use + * GNUC attributes (such as to get -Wall warnings for printf-like + * functions). Only do this in gcc 2.7 or later ... it may work + * on earlier stuff, but why chance it. + * + * We've since discovered that the gcc shipped with NeXT systems + * as "cc" is completely broken. It claims to be __GNUC__ and so + * on, but it doesn't implement half of the things that __GNUC__ + * means. In particular it's missing inline and the __attribute__ + * stuff. So we hack around it. PR#1613. -djg + */ +#if !defined(__GNUC__) || __GNUC__ < 2 || \ + (__GNUC__ == 2 && __GNUC_MINOR__ < 7) ||\ + defined(NEXT) +#ifndef __attribute__ +#define __attribute__(__x) +#endif +#define APR_INLINE +#define APR_HAS_INLINE 0 +#else +#define APR_INLINE __inline__ +#define APR_HAS_INLINE 1 +#endif + +#define APR_HAVE_ARPA_INET_H 1 +#define APR_HAVE_CONIO_H 0 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 1 +#define APR_HAVE_DIRENT_H 1 +#define APR_HAVE_ERRNO_H 1 +#define APR_HAVE_FCNTL_H 1 +#define APR_HAVE_IO_H 0 +#define APR_HAVE_LIMITS_H 1 +#define APR_HAVE_NETDB_H 1 +#define APR_HAVE_NETINET_IN_H 1 +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 1 +#define APR_HAVE_PROCESS_H 0 +#define APR_HAVE_PTHREAD_H 1 +#define APR_HAVE_SEMAPHORE_H 1 +#define APR_HAVE_SIGNAL_H 1 +#define APR_HAVE_STDARG_H 1 +#define APR_HAVE_STDINT_H 1 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 1 +#define APR_HAVE_INTTYPES_H 1 +#define APR_HAVE_SYS_IOCTL_H 1 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SIGNAL_H 1 +#define APR_HAVE_SYS_SOCKET_H 1 +#define APR_HAVE_SYS_SOCKIO_H 1 +#define APR_HAVE_SYS_SYSLIMITS_H 1 +#define APR_HAVE_SYS_TIME_H 1 +#define APR_HAVE_SYS_TYPES_H 1 +#define APR_HAVE_SYS_UIO_H 1 +#define APR_HAVE_SYS_UN_H 1 +#define APR_HAVE_SYS_WAIT_H 1 +#define APR_HAVE_TIME_H 1 +#define APR_HAVE_UNISTD_H 1 +#define APR_HAVE_WINDOWS_H 0 +#define APR_HAVE_WINSOCK2_H 0 + +/** @} */ +/** @} */ + +/* We don't include our conditional headers within the doxyblocks + * or the extern "C" namespace + */ + +#if APR_HAVE_WINDOWS_H && defined(WIN32) +/* If windows.h was already included, our preferences don't matter. + * If not, include a restricted set of windows headers to our tastes. + */ +#ifndef _WINDOWS_ + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif + +#ifndef _WIN32_WINNT +/* Restrict the server to a subset of Windows XP header files by default + */ +#define _WIN32_WINNT 0x0501 +#endif + +#ifndef NOUSER +#define NOUSER +#endif +#ifndef NOMCX +#define NOMCX +#endif +#ifndef NOIME +#define NOIME +#endif + +#include +/* + * Add a _very_few_ declarations missing from the restricted set of headers + * (If this list becomes extensive, re-enable the required headers above!) + * winsock headers were excluded by WIN32_LEAN_AND_MEAN, so include them now + */ +#define SW_HIDE 0 +#ifndef _WIN32_WCE +#include +#include +#include +#else +#include +#endif + +#endif /* ndef _WINDOWS_ */ +#endif /* APR_HAVE_WINDOWS_H */ + +#if APR_HAVE_SYS_TYPES_H +#include +#endif + +#if APR_HAVE_SYS_SOCKET_H +#include +#endif + +#if APR_HAVE_STDINT_H +#ifdef __cplusplus +/* C99 7.18.4 requires that stdint.h only exposes INT64_C + * and UINT64_C for C++ implementations if this is defined: */ +#ifndef __STDC_CONSTANT_MACROS +#define __STDC_CONSTANT_MACROS +#endif +/* C++ needs this too for PRI*NN formats: */ +#ifndef __STDC_FORMAT_MACROS +#define __STDC_FORMAT_MACROS +#endif +#endif /* __cplusplus */ +#include +#endif + +#if APR_HAVE_INTTYPES_H +#include +#endif + +#if APR_HAVE_SYS_WAIT_H +#include +#endif + +#ifdef OS2 +#define INCL_DOS +#define INCL_DOSERRORS +#include +#endif + +/* header files for PATH_MAX, _POSIX_PATH_MAX */ +#if APR_HAVE_LIMITS_H +#include +#else +#if APR_HAVE_SYS_SYSLIMITS_H +#include +#endif +#endif + +/* __APPLE__ is now the official pre-defined macro for macOS */ +#ifdef __APPLE__ +#undef DARWIN +#undef DARWIN_10 +#define DARWIN +#define DARWIN_10 +#endif /* __APPLE__ */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @addtogroup apr_platform + * @ingroup APR + * @{ + */ + +#define APR_HAVE_SHMEM_MMAP_TMP 1 +#define APR_HAVE_SHMEM_MMAP_SHM 1 +#define APR_HAVE_SHMEM_MMAP_ZERO 0 +#define APR_HAVE_SHMEM_SHMGET_ANON 1 +#define APR_HAVE_SHMEM_SHMGET 1 +#define APR_HAVE_SHMEM_MMAP_ANON 1 +#define APR_HAVE_SHMEM_BEOS 0 + +#define APR_USE_SHMEM_MMAP_TMP 0 +#define APR_USE_SHMEM_MMAP_SHM 1 +#define APR_USE_SHMEM_MMAP_ZERO 0 +#define APR_USE_SHMEM_SHMGET_ANON 0 +#define APR_USE_SHMEM_SHMGET 0 +#define APR_USE_SHMEM_MMAP_ANON 1 +#define APR_USE_SHMEM_BEOS 0 + +#define APR_USE_FLOCK_SERIALIZE 0 +#define APR_USE_SYSVSEM_SERIALIZE 1 +#define APR_USE_POSIXSEM_SERIALIZE 0 +#define APR_USE_FCNTL_SERIALIZE 0 +#define APR_USE_PROC_PTHREAD_SERIALIZE 0 +#define APR_USE_PTHREAD_SERIALIZE 1 + +#define APR_HAS_FLOCK_SERIALIZE 1 +#define APR_HAS_SYSVSEM_SERIALIZE 1 +#define APR_HAS_POSIXSEM_SERIALIZE 1 +#define APR_HAS_FCNTL_SERIALIZE 1 +#define APR_HAS_PROC_PTHREAD_SERIALIZE 0 + +#define APR_PROCESS_LOCK_IS_GLOBAL 0 + +#define APR_HAVE_CORKABLE_TCP 1 +#define APR_HAVE_GETRLIMIT 1 +#define APR_HAVE_IN_ADDR 1 +#define APR_HAVE_INET_ADDR 1 +#define APR_HAVE_INET_NETWORK 1 +#define APR_HAVE_IPV6 1 +#define APR_HAVE_SOCKADDR_UN 1 +#define APR_HAVE_MEMMOVE 1 +#define APR_HAVE_SETRLIMIT 1 +#define APR_HAVE_SIGACTION 1 +#define APR_HAVE_SIGSUSPEND 1 +#define APR_HAVE_SIGWAIT 1 +#define APR_HAVE_SA_STORAGE 1 +#define APR_HAVE_STRCASECMP 1 +#define APR_HAVE_STRDUP 1 +#define APR_HAVE_STRICMP 0 +#define APR_HAVE_STRNCASECMP 1 +#define APR_HAVE_STRNICMP 0 +#define APR_HAVE_STRSTR 1 +#define APR_HAVE_MEMCHR 1 +#define APR_HAVE_STRUCT_RLIMIT 1 +#define APR_HAVE_UNION_SEMUN 1 +#define APR_HAVE_SCTP 0 +#define APR_HAVE_IOVEC 1 + +/* APR Feature Macros */ +#define APR_HAS_SHARED_MEMORY 1 +#define APR_HAS_THREADS 1 +#define APR_HAS_SENDFILE 1 +#define APR_HAS_MMAP 1 +#define APR_HAS_FORK 1 +#define APR_HAS_RANDOM 1 +#define APR_HAS_OTHER_CHILD 1 +#define APR_HAS_DSO 1 +#define APR_HAS_SO_ACCEPTFILTER 0 +#define APR_HAS_UNICODE_FS 0 +#define APR_HAS_PROC_INVOKED 0 +#define APR_HAS_USER 1 +#define APR_HAS_LARGE_FILES 0 +#define APR_HAS_XTHREAD_FILES 0 +#define APR_HAS_OS_UUID 1 +#define APR_HAS_TIMEDLOCKS 1 + +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 0 + +/* APR sets APR_FILES_AS_SOCKETS to 1 on systems where it is possible + * to poll on files/pipes. + */ +#define APR_FILES_AS_SOCKETS 1 + +/* This macro indicates whether or not EBCDIC is the native character set. + */ +#define APR_CHARSET_EBCDIC 0 + +/* If we have a TCP implementation that can be "corked", what flag + * do we use? + */ +#define APR_TCP_NOPUSH_FLAG TCP_NOPUSH + +/* Is the TCP_NODELAY socket option inherited from listening sockets? +*/ +#define APR_TCP_NODELAY_INHERITED 1 + +/* Is the O_NONBLOCK flag inherited from listening sockets? +*/ +#define APR_O_NONBLOCK_INHERITED 1 + +/* Typedefs that APR needs. */ + +typedef unsigned char apr_byte_t; + +typedef short apr_int16_t; +typedef unsigned short apr_uint16_t; + +typedef int apr_int32_t; +typedef unsigned int apr_uint32_t; + +#define APR_SIZEOF_VOIDP 8 + +/* + * Darwin 10's default compiler (gcc42) builds for both 64 and + * 32 bit architectures unless specifically told not to. + * In those cases, we need to override types depending on how + * we're being built at compile time. + * NOTE: This is an ugly work-around for Darwin's + * concept of universal binaries, a single package + * (executable, lib, etc...) which contains both 32 + * and 64 bit versions. The issue is that if APR is + * built universally, if something else is compiled + * against it, some bit sizes will depend on whether + * it is 32 or 64 bit. This is determined by the __LP64__ + * flag. Since we need to support both, we have to + * handle OS X unqiuely. + */ +#ifdef DARWIN_10 +#undef APR_SIZEOF_VOIDP +#undef APR_INT64_C +#undef APR_UINT64_C +#ifdef __LP64__ + typedef long apr_int64_t; + typedef unsigned long apr_uint64_t; + #define APR_SIZEOF_VOIDP 8 + #define APR_INT64_C(v) (v ## L) + #define APR_UINT64_C(v) (v ## UL) +#else + typedef long long apr_int64_t; + typedef unsigned long long apr_uint64_t; + #define APR_SIZEOF_VOIDP 4 + #define APR_INT64_C(v) (v ## LL) + #define APR_UINT64_C(v) (v ## ULL) +#endif +#else + typedef int64_t apr_int64_t; + typedef uint64_t apr_uint64_t; + + /* Mechanisms to properly type numeric literals */ + #define APR_INT64_C(val) INT64_C(val) + #define APR_UINT64_C(val) UINT64_C(val) +#endif + +typedef size_t apr_size_t; +typedef ssize_t apr_ssize_t; +typedef off_t apr_off_t; +typedef socklen_t apr_socklen_t; +typedef ino_t apr_ino_t; + +#if APR_SIZEOF_VOIDP == 8 +typedef apr_uint64_t apr_uintptr_t; +#else +typedef apr_uint32_t apr_uintptr_t; +#endif + +/* Are we big endian? */ +#define APR_IS_BIGENDIAN 0 + +#ifdef INT16_MIN +#define APR_INT16_MIN INT16_MIN +#else +#define APR_INT16_MIN (-0x7fff - 1) +#endif + +#ifdef INT16_MAX +#define APR_INT16_MAX INT16_MAX +#else +#define APR_INT16_MAX (0x7fff) +#endif + +#ifdef UINT16_MAX +#define APR_UINT16_MAX UINT16_MAX +#else +#define APR_UINT16_MAX (0xffff) +#endif + +#ifdef INT32_MIN +#define APR_INT32_MIN INT32_MIN +#else +#define APR_INT32_MIN (-0x7fffffff - 1) +#endif + +#ifdef INT32_MAX +#define APR_INT32_MAX INT32_MAX +#else +#define APR_INT32_MAX 0x7fffffff +#endif + +#ifdef UINT32_MAX +#define APR_UINT32_MAX UINT32_MAX +#else +#define APR_UINT32_MAX (0xffffffffU) +#endif + +#ifdef INT64_MIN +#define APR_INT64_MIN INT64_MIN +#else +#define APR_INT64_MIN (APR_INT64_C(-0x7fffffffffffffff) - 1) +#endif + +#ifdef INT64_MAX +#define APR_INT64_MAX INT64_MAX +#else +#define APR_INT64_MAX APR_INT64_C(0x7fffffffffffffff) +#endif + +#ifdef UINT64_MAX +#define APR_UINT64_MAX UINT64_MAX +#else +#define APR_UINT64_MAX APR_UINT64_C(0xffffffffffffffff) +#endif + +#define APR_SIZE_MAX (~((apr_size_t)0)) + + +/* Definitions that APR programs need to work properly. */ + +/** + * APR public API wrap for C++ compilers. + */ +#ifdef __cplusplus +#define APR_BEGIN_DECLS extern "C" { +#define APR_END_DECLS } +#else +#define APR_BEGIN_DECLS +#define APR_END_DECLS +#endif + +/** + * Thread callbacks from APR functions must be declared with APR_THREAD_FUNC, + * so that they follow the platform's calling convention. + *
+ *
+ * void* APR_THREAD_FUNC my_thread_entry_fn(apr_thread_t *thd, void *data);
+ *
+ * 
+ */ +#define APR_THREAD_FUNC + +#if defined(DOXYGEN) || !defined(WIN32) + +/** + * The public APR functions are declared with APR_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APR_DECLARE_NONSTD(). + * + * @remark Both the declaration and implementations must use the same macro. + * + *
+ * APR_DECLARE(rettype) apr_func(args)
+ * 
+ * @see APR_DECLARE_NONSTD @see APR_DECLARE_DATA + * @remark Note that when APR compiles the library itself, it passes the + * symbol -DAPR_DECLARE_EXPORT to the compiler on some platforms (e.g. Win32) + * to export public symbols from the dynamic library build.\n + * The user must define the APR_DECLARE_STATIC when compiling to target + * the static APR library on some platforms (e.g. Win32.) The public symbols + * are neither exported nor imported when APR_DECLARE_STATIC is defined.\n + * By default, compiling an application and including the APR public + * headers, without defining APR_DECLARE_STATIC, will prepare the code to be + * linked to the dynamic library. + */ +#define APR_DECLARE(type) type + +/** + * The public APR functions using variable arguments are declared with + * APR_DECLARE_NONSTD(), as they must follow the C language calling convention. + * @see APR_DECLARE @see APR_DECLARE_DATA + * @remark Both the declaration and implementations must use the same macro. + *
+ *
+ * APR_DECLARE_NONSTD(rettype) apr_func(args, ...);
+ *
+ * 
+ */ +#define APR_DECLARE_NONSTD(type) type + +/** + * The public APR variables are declared with AP_MODULE_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * @see APR_DECLARE @see APR_DECLARE_NONSTD + * @remark Note that the declaration and implementations use different forms, + * but both must include the macro. + * + *
+ *
+ * extern APR_DECLARE_DATA type apr_variable;\n
+ * APR_DECLARE_DATA type apr_variable = value;
+ *
+ * 
+ */ +#define APR_DECLARE_DATA + +#elif defined(APR_DECLARE_STATIC) +#define APR_DECLARE(type) type __stdcall +#define APR_DECLARE_NONSTD(type) type __cdecl +#define APR_DECLARE_DATA +#elif defined(APR_DECLARE_EXPORT) +#define APR_DECLARE(type) __declspec(dllexport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllexport) +#else +#define APR_DECLARE(type) __declspec(dllimport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllimport) +#endif + +/* Define APR_SSIZE_T_FMT. + * If ssize_t is an integer we define it to be "d", + * if ssize_t is a long int we define it to be "ld", + * if ssize_t is neither we declare an error here. + * I looked for a better way to define this here, but couldn't find one, so + * to find the logic for this definition search for "ssize_t_fmt" in + * configure.in. + */ + +#define APR_SSIZE_T_FMT "ld" + +/* And APR_SIZE_T_FMT */ +#define APR_SIZE_T_FMT "lu" + +/* And APR_OFF_T_FMT */ +#define APR_OFF_T_FMT "lld" + +/* And APR_PID_T_FMT */ +#define APR_PID_T_FMT "d" + +/* And APR_INT64_T_FMT */ +#define APR_INT64_T_FMT PRId64 + +/* And APR_UINT64_T_FMT */ +#define APR_UINT64_T_FMT PRIu64 + +/* And APR_UINT64_T_HEX_FMT */ +#define APR_UINT64_T_HEX_FMT PRIx64 + +/* + * Ensure we work with universal binaries on Darwin + */ +#ifdef DARWIN_10 + +#undef APR_HAS_LARGE_FILES +#undef APR_SIZEOF_VOIDP +#undef APR_INT64_T_FMT +#undef APR_UINT64_T_FMT +#undef APR_UINT64_T_HEX_FMT + +#ifdef __LP64__ + #define APR_HAS_LARGE_FILES 0 + #define APR_SIZEOF_VOIDP 8 + #define APR_INT64_T_FMT "ld" + #define APR_UINT64_T_FMT "lu" + #define APR_UINT64_T_HEX_FMT "lx" +#else + #define APR_HAS_LARGE_FILES 1 + #define APR_SIZEOF_VOIDP 4 + #define APR_INT64_T_FMT "lld" + #define APR_UINT64_T_FMT "llu" + #define APR_UINT64_T_HEX_FMT "llx" +#endif + +#undef APR_IS_BIGENDIAN +#ifdef __BIG_ENDIAN__ + #define APR_IS_BIGENDIAN 1 +#else + #define APR_IS_BIGENDIAN 0 +#endif + +#undef APR_OFF_T_FMT +#define APR_OFF_T_FMT "lld" + +#endif /* DARWIN_10 */ + +/* Does the proc mutex lock threads too */ +#define APR_PROC_MUTEX_IS_GLOBAL 0 + +/* Local machine definition for console and log output. */ +#define APR_EOL_STR "\n" + +#if APR_HAVE_SYS_WAIT_H +#ifdef WEXITSTATUS +#define apr_wait_t int +#else +#define apr_wait_t union wait +#define WEXITSTATUS(status) (int)((status).w_retcode) +#define WTERMSIG(status) (int)((status).w_termsig) +#endif /* !WEXITSTATUS */ +#elif defined(__MINGW32__) +typedef int apr_wait_t; +#endif /* HAVE_SYS_WAIT_H */ + +#if defined(PATH_MAX) +#define APR_PATH_MAX PATH_MAX +#elif defined(_POSIX_PATH_MAX) +#define APR_PATH_MAX _POSIX_PATH_MAX +#else +#error no decision has been made on APR_PATH_MAX for your platform +#endif + +#define APR_DSOPATH "DYLD_LIBRARY_PATH" + +/** @} */ + +/* Definitions that only Win32 programs need to compile properly. */ + +/* XXX These simply don't belong here, perhaps in apr_portable.h + * based on some APR_HAVE_PID/GID/UID? + */ +#ifdef __MINGW32__ +#ifndef __GNUC__ +typedef int pid_t; +#endif +typedef int uid_t; +typedef int gid_t; +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* APR_H */ diff --git a/c/dependencies/macos/apr/include/apr_allocator.h b/c/dependencies/macos/apr/include/apr_allocator.h new file mode 100644 index 00000000..be05d0e4 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_allocator.h @@ -0,0 +1,179 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ALLOCATOR_H +#define APR_ALLOCATOR_H + +/** + * @file apr_allocator.h + * @brief APR Internal Memory Allocation + */ + +#include "apr.h" +#include "apr_errno.h" +#define APR_WANT_MEMFUNC /**< For no good reason? */ +#include "apr_want.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_allocator Internal Memory Allocation + * @ingroup APR + * @{ + */ + +/** the allocator structure */ +typedef struct apr_allocator_t apr_allocator_t; +/** the structure which holds information about the allocation */ +typedef struct apr_memnode_t apr_memnode_t; + +/** basic memory node structure + * @note The next, ref and first_avail fields are available for use by the + * caller of apr_allocator_alloc(), the remaining fields are read-only. + * The next field has to be used with caution and sensibly set when the + * memnode is passed back to apr_allocator_free(). See apr_allocator_free() + * for details. + * The ref and first_avail fields will be properly restored by + * apr_allocator_free(). + */ +struct apr_memnode_t { + apr_memnode_t *next; /**< next memnode */ + apr_memnode_t **ref; /**< reference to self */ + apr_uint32_t index; /**< size */ + apr_uint32_t free_index; /**< how much free */ + char *first_avail; /**< pointer to first free memory */ + char *endp; /**< pointer to end of free memory */ +}; + +/** The base size of a memory node - aligned. */ +#define APR_MEMNODE_T_SIZE APR_ALIGN_DEFAULT(sizeof(apr_memnode_t)) + +/** Symbolic constants */ +#define APR_ALLOCATOR_MAX_FREE_UNLIMITED 0 + +/** + * Create a new allocator + * @param allocator The allocator we have just created. + * + */ +APR_DECLARE(apr_status_t) apr_allocator_create(apr_allocator_t **allocator) + __attribute__((nonnull(1))); + +/** + * Destroy an allocator + * @param allocator The allocator to be destroyed + * @remark Any memnodes not given back to the allocator prior to destroying + * will _not_ be free()d. + */ +APR_DECLARE(void) apr_allocator_destroy(apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +/** + * Allocate a block of mem from the allocator + * @param allocator The allocator to allocate from + * @param size The size of the mem to allocate (excluding the + * memnode structure) + */ +APR_DECLARE(apr_memnode_t *) apr_allocator_alloc(apr_allocator_t *allocator, + apr_size_t size) + __attribute__((nonnull(1))); + +/** + * Free a list of blocks of mem, giving them back to the allocator. + * The list is typically terminated by a memnode with its next field + * set to NULL. + * @param allocator The allocator to give the mem back to + * @param memnode The memory node to return + */ +APR_DECLARE(void) apr_allocator_free(apr_allocator_t *allocator, + apr_memnode_t *memnode) + __attribute__((nonnull(1,2))); + +/** + * Get the true size that would be allocated for the given size (including + * the header and alignment). + * @param allocator The allocator from which to the memory would be allocated + * @param size The size to align + * @return The aligned size (or zero on apr_size_t overflow) + */ +APR_DECLARE(apr_size_t) apr_allocator_align(apr_allocator_t *allocator, + apr_size_t size); + +#include "apr_pools.h" + +/** + * Set the owner of the allocator + * @param allocator The allocator to set the owner for + * @param pool The pool that is to own the allocator + * @remark Typically pool is the highest level pool using the allocator + */ +/* + * XXX: see if we can come up with something a bit better. Currently + * you can make a pool an owner, but if the pool doesn't use the allocator + * the allocator will never be destroyed. + */ +APR_DECLARE(void) apr_allocator_owner_set(apr_allocator_t *allocator, + apr_pool_t *pool) + __attribute__((nonnull(1))); + +/** + * Get the current owner of the allocator + * @param allocator The allocator to get the owner from + */ +APR_DECLARE(apr_pool_t *) apr_allocator_owner_get(apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +/** + * Set the current threshold at which the allocator should start + * giving blocks back to the system. + * @param allocator The allocator to set the threshold on + * @param size The threshold. 0 == unlimited. + */ +APR_DECLARE(void) apr_allocator_max_free_set(apr_allocator_t *allocator, + apr_size_t size) + __attribute__((nonnull(1))); + +#include "apr_thread_mutex.h" + +#if APR_HAS_THREADS +/** + * Set a mutex for the allocator to use + * @param allocator The allocator to set the mutex for + * @param mutex The mutex + */ +APR_DECLARE(void) apr_allocator_mutex_set(apr_allocator_t *allocator, + apr_thread_mutex_t *mutex) + __attribute__((nonnull(1))); + +/** + * Get the mutex currently set for the allocator + * @param allocator The allocator + */ +APR_DECLARE(apr_thread_mutex_t *) apr_allocator_mutex_get( + apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ALLOCATOR_H */ diff --git a/c/dependencies/macos/apr/include/apr_anylock.h b/c/dependencies/macos/apr/include/apr_anylock.h new file mode 100644 index 00000000..51e97ff3 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_anylock.h @@ -0,0 +1,128 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_anylock.h + * @brief APR-Util transparent any lock flavor wrapper + */ +#ifndef APR_ANYLOCK_H +#define APR_ANYLOCK_H + +#include "apr_proc_mutex.h" +#include "apr_thread_mutex.h" +#include "apr_thread_rwlock.h" + +/** Structure that may contain any APR lock type */ +typedef struct apr_anylock_t { + /** Indicates what type of lock is in lock */ + enum tm_lock { + apr_anylock_none, /**< None */ + apr_anylock_procmutex, /**< Process-based */ + apr_anylock_threadmutex, /**< Thread-based */ + apr_anylock_readlock, /**< Read lock */ + apr_anylock_writelock /**< Write lock */ + } type; + /** Union of all possible APR locks */ + union apr_anylock_u_t { + apr_proc_mutex_t *pm; /**< Process mutex */ +#if APR_HAS_THREADS + apr_thread_mutex_t *tm; /**< Thread mutex */ + apr_thread_rwlock_t *rw; /**< Read-write lock */ +#endif + } lock; +} apr_anylock_t; + +#if APR_HAS_THREADS + +/** Lock an apr_anylock_t structure */ +#define APR_ANYLOCK_LOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_threadmutex) \ + ? apr_thread_mutex_lock((lck)->lock.tm) \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_lock((lck)->lock.pm) \ + : (((lck)->type == apr_anylock_readlock) \ + ? apr_thread_rwlock_rdlock((lck)->lock.rw) \ + : (((lck)->type == apr_anylock_writelock) \ + ? apr_thread_rwlock_wrlock((lck)->lock.rw) \ + : APR_EINVAL))))) + +#else /* APR_HAS_THREADS */ + +#define APR_ANYLOCK_LOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_lock((lck)->lock.pm) \ + : APR_EINVAL)) + +#endif /* APR_HAS_THREADS */ + +#if APR_HAS_THREADS + +/** Try to lock an apr_anylock_t structure */ +#define APR_ANYLOCK_TRYLOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_threadmutex) \ + ? apr_thread_mutex_trylock((lck)->lock.tm) \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_trylock((lck)->lock.pm) \ + : (((lck)->type == apr_anylock_readlock) \ + ? apr_thread_rwlock_tryrdlock((lck)->lock.rw) \ + : (((lck)->type == apr_anylock_writelock) \ + ? apr_thread_rwlock_trywrlock((lck)->lock.rw) \ + : APR_EINVAL))))) + +#else /* APR_HAS_THREADS */ + +#define APR_ANYLOCK_TRYLOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_trylock((lck)->lock.pm) \ + : APR_EINVAL)) + +#endif /* APR_HAS_THREADS */ + +#if APR_HAS_THREADS + +/** Unlock an apr_anylock_t structure */ +#define APR_ANYLOCK_UNLOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_threadmutex) \ + ? apr_thread_mutex_unlock((lck)->lock.tm) \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_unlock((lck)->lock.pm) \ + : ((((lck)->type == apr_anylock_readlock) || \ + ((lck)->type == apr_anylock_writelock)) \ + ? apr_thread_rwlock_unlock((lck)->lock.rw) \ + : APR_EINVAL)))) + +#else /* APR_HAS_THREADS */ + +#define APR_ANYLOCK_UNLOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_unlock((lck)->lock.pm) \ + : APR_EINVAL)) + +#endif /* APR_HAS_THREADS */ + +#endif /* !APR_ANYLOCK_H */ diff --git a/c/dependencies/macos/apr/include/apr_atomic.h b/c/dependencies/macos/apr/include/apr_atomic.h new file mode 100644 index 00000000..3d203edc --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_atomic.h @@ -0,0 +1,207 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ATOMIC_H +#define APR_ATOMIC_H + +/** + * @file apr_atomic.h + * @brief APR Atomic Operations + */ + +#include "apr.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_atomic Atomic Operations + * @ingroup APR + * @{ + */ + +/** + * this function is required on some platforms to initialize the + * atomic operation's internal structures + * @param p pool + * @return APR_SUCCESS on successful completion + * @remark Programs do NOT need to call this directly. APR will call this + * automatically from apr_initialize(). + * @internal + */ +APR_DECLARE(apr_status_t) apr_atomic_init(apr_pool_t *p); + +/* + * Atomic operations on 32-bit values + * Note: Each of these functions internally implements a memory barrier + * on platforms that require it + */ + +/** + * atomically read an apr_uint32_t from memory + * @param mem the pointer + */ +APR_DECLARE(apr_uint32_t) apr_atomic_read32(volatile apr_uint32_t *mem); + +/** + * atomically set an apr_uint32_t in memory + * @param mem pointer to the object + * @param val value that the object will assume + */ +APR_DECLARE(void) apr_atomic_set32(volatile apr_uint32_t *mem, apr_uint32_t val); + +/** + * atomically add 'val' to an apr_uint32_t + * @param mem pointer to the object + * @param val amount to add + * @return old value pointed to by mem + */ +APR_DECLARE(apr_uint32_t) apr_atomic_add32(volatile apr_uint32_t *mem, apr_uint32_t val); + +/** + * atomically subtract 'val' from an apr_uint32_t + * @param mem pointer to the object + * @param val amount to subtract + */ +APR_DECLARE(void) apr_atomic_sub32(volatile apr_uint32_t *mem, apr_uint32_t val); + +/** + * atomically increment an apr_uint32_t by 1 + * @param mem pointer to the object + * @return old value pointed to by mem + */ +APR_DECLARE(apr_uint32_t) apr_atomic_inc32(volatile apr_uint32_t *mem); + +/** + * atomically decrement an apr_uint32_t by 1 + * @param mem pointer to the atomic value + * @return zero if the value becomes zero on decrement, otherwise non-zero + */ +APR_DECLARE(int) apr_atomic_dec32(volatile apr_uint32_t *mem); + +/** + * compare an apr_uint32_t's value with 'cmp'. + * If they are the same swap the value with 'with' + * @param mem pointer to the value + * @param with what to swap it with + * @param cmp the value to compare it to + * @return the old value of *mem + */ +APR_DECLARE(apr_uint32_t) apr_atomic_cas32(volatile apr_uint32_t *mem, apr_uint32_t with, + apr_uint32_t cmp); + +/** + * exchange an apr_uint32_t's value with 'val'. + * @param mem pointer to the value + * @param val what to swap it with + * @return the old value of *mem + */ +APR_DECLARE(apr_uint32_t) apr_atomic_xchg32(volatile apr_uint32_t *mem, apr_uint32_t val); + +/* + * Atomic operations on 64-bit values + * Note: Each of these functions internally implements a memory barrier + * on platforms that require it + */ + +/** + * atomically read an apr_uint64_t from memory + * @param mem the pointer + */ +APR_DECLARE(apr_uint64_t) apr_atomic_read64(volatile apr_uint64_t *mem); + +/** + * atomically set an apr_uint64_t in memory + * @param mem pointer to the object + * @param val value that the object will assume + */ +APR_DECLARE(void) apr_atomic_set64(volatile apr_uint64_t *mem, apr_uint64_t val); + +/** + * atomically add 'val' to an apr_uint64_t + * @param mem pointer to the object + * @param val amount to add + * @return old value pointed to by mem + */ +APR_DECLARE(apr_uint64_t) apr_atomic_add64(volatile apr_uint64_t *mem, apr_uint64_t val); + +/** + * atomically subtract 'val' from an apr_uint64_t + * @param mem pointer to the object + * @param val amount to subtract + */ +APR_DECLARE(void) apr_atomic_sub64(volatile apr_uint64_t *mem, apr_uint64_t val); + +/** + * atomically increment an apr_uint64_t by 1 + * @param mem pointer to the object + * @return old value pointed to by mem + */ +APR_DECLARE(apr_uint64_t) apr_atomic_inc64(volatile apr_uint64_t *mem); + +/** + * atomically decrement an apr_uint64_t by 1 + * @param mem pointer to the atomic value + * @return zero if the value becomes zero on decrement, otherwise non-zero + */ +APR_DECLARE(int) apr_atomic_dec64(volatile apr_uint64_t *mem); + +/** + * compare an apr_uint64_t's value with 'cmp'. + * If they are the same swap the value with 'with' + * @param mem pointer to the value + * @param with what to swap it with + * @param cmp the value to compare it to + * @return the old value of *mem + */ +APR_DECLARE(apr_uint64_t) apr_atomic_cas64(volatile apr_uint64_t *mem, apr_uint64_t with, + apr_uint64_t cmp); + +/** + * exchange an apr_uint64_t's value with 'val'. + * @param mem pointer to the value + * @param val what to swap it with + * @return the old value of *mem + */ +APR_DECLARE(apr_uint64_t) apr_atomic_xchg64(volatile apr_uint64_t *mem, apr_uint64_t val); + +/** + * compare the pointer's value with cmp. + * If they are the same swap the value with 'with' + * @param mem pointer to the pointer + * @param with what to swap it with + * @param cmp the value to compare it to + * @return the old value of the pointer + */ +APR_DECLARE(void*) apr_atomic_casptr(volatile void **mem, void *with, const void *cmp); + +/** + * exchange a pair of pointer values + * @param mem pointer to the pointer + * @param with what to swap it with + * @return the old value of the pointer + */ +APR_DECLARE(void*) apr_atomic_xchgptr(volatile void **mem, void *with); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ATOMIC_H */ diff --git a/c/dependencies/macos/apr/include/apr_base64.h b/c/dependencies/macos/apr/include/apr_base64.h new file mode 100644 index 00000000..17de1c58 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_base64.h @@ -0,0 +1,113 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * The apr_vsnprintf/apr_snprintf functions are based on, and used with the + * permission of, the SIO stdio-replacement strx_* functions by Panos + * Tsirigotis for xinetd. + */ + +/** + * @file apr_base64.h + * @brief APR-UTIL Base64 Encoding + */ +#ifndef APR_BASE64_H +#define APR_BASE64_H + +#include "apu.h" +#include "apr_general.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Base64 Base64 Encoding + * @ingroup APR_Util + * @{ + */ + +/* Simple BASE64 encode/decode functions. + * + * As we might encode binary strings, hence we require the length of + * the incoming plain source. And return the length of what we decoded. + * + * The decoding function takes any non valid char (i.e. whitespace, \0 + * or anything non A-Z,0-9 etc as terminal. + * + * plain strings/binary sequences are not assumed '\0' terminated. Encoded + * strings are neither. But probably should. + * + */ + +/** + * Given the length of an un-encoded string, get the length of the + * encoded string. + * @param len the length of an unencoded string. + * @return the length of the string after it is encoded, including the + * trailing \0 + */ +APU_DECLARE(int) apr_base64_encode_len(int len); + +/** + * Encode a text string using base64encoding. + * @param coded_dst The destination string for the encoded string. + * @param plain_src The original string in plain text + * @param len_plain_src The length of the plain text string + * @return the length of the encoded string + */ +APU_DECLARE(int) apr_base64_encode(char * coded_dst, const char *plain_src, + int len_plain_src); + +/** + * Encode an EBCDIC string using base64encoding. + * @param coded_dst The destination string for the encoded string. + * @param plain_src The original string in plain text + * @param len_plain_src The length of the plain text string + * @return the length of the encoded string + */ +APU_DECLARE(int) apr_base64_encode_binary(char * coded_dst, + const unsigned char *plain_src, + int len_plain_src); + +/** + * Determine the maximum buffer length required to decode the plain text + * string given the encoded string. + * @param coded_src The encoded string + * @return the maximum required buffer length for the plain text string + */ +APU_DECLARE(int) apr_base64_decode_len(const char * coded_src); + +/** + * Decode a string to plain text + * @param plain_dst The destination string for the plain text + * @param coded_src The encoded string + * @return the length of the plain text string + */ +APU_DECLARE(int) apr_base64_decode(char * plain_dst, const char *coded_src); + +/** + * Decode an EBCDIC string to plain text + * @param plain_dst The destination string for the plain text + * @param coded_src The encoded string + * @return the length of the plain text string + */ +APU_DECLARE(int) apr_base64_decode_binary(unsigned char * plain_dst, + const char *coded_src); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_BASE64_H */ diff --git a/c/dependencies/macos/apr/include/apr_buckets.h b/c/dependencies/macos/apr/include/apr_buckets.h new file mode 100644 index 00000000..53633f53 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_buckets.h @@ -0,0 +1,1600 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file apr_buckets.h + * @brief APR-UTIL Buckets/Bucket Brigades + */ + +#ifndef APR_BUCKETS_H +#define APR_BUCKETS_H + +#if defined(APR_BUCKET_DEBUG) && !defined(APR_RING_DEBUG) +#define APR_RING_DEBUG +#endif + +#include "apu.h" +#include "apr_network_io.h" +#include "apr_file_io.h" +#include "apr_general.h" +#include "apr_mmap.h" +#include "apr_errno.h" +#include "apr_ring.h" +#include "apr.h" +#if APR_HAVE_SYS_UIO_H +#include /* for struct iovec */ +#endif +#if APR_HAVE_STDARG_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Bucket_Brigades Bucket Brigades + * @ingroup APR_Util + * @{ + */ + +/** default bucket buffer size - 8KB minus room for memory allocator headers */ +#define APR_BUCKET_BUFF_SIZE 8000 + +/** Determines how a bucket or brigade should be read */ +typedef enum { + APR_BLOCK_READ, /**< block until data becomes available */ + APR_NONBLOCK_READ /**< return immediately if no data is available */ +} apr_read_type_e; + +/** + * The one-sentence buzzword-laden overview: Bucket brigades represent + * a complex data stream that can be passed through a layered IO + * system without unnecessary copying. A longer overview follows... + * + * A bucket brigade is a doubly linked list (ring) of buckets, so we + * aren't limited to inserting at the front and removing at the end. + * Buckets are only passed around as members of a brigade, although + * singleton buckets can occur for short periods of time. + * + * Buckets are data stores of various types. They can refer to data in + * memory, or part of a file or mmap area, or the output of a process, + * etc. Buckets also have some type-dependent accessor functions: + * read, split, copy, setaside, and destroy. + * + * read returns the address and size of the data in the bucket. If the + * data isn't in memory then it is read in and the bucket changes type + * so that it can refer to the new location of the data. If all the + * data doesn't fit in the bucket then a new bucket is inserted into + * the brigade to hold the rest of it. + * + * split divides the data in a bucket into two regions. After a split + * the original bucket refers to the first part of the data and a new + * bucket inserted into the brigade after the original bucket refers + * to the second part of the data. Reference counts are maintained as + * necessary. + * + * setaside ensures that the data in the bucket has a long enough + * lifetime. Sometimes it is convenient to create a bucket referring + * to data on the stack in the expectation that it will be consumed + * (output to the network) before the stack is unwound. If that + * expectation turns out not to be valid, the setaside function is + * called to move the data somewhere safer. + * + * copy makes a duplicate of the bucket structure as long as it's + * possible to have multiple references to a single copy of the + * data itself. Not all bucket types can be copied. + * + * destroy maintains the reference counts on the resources used by a + * bucket and frees them if necessary. + * + * Note: all of the above functions have wrapper macros (apr_bucket_read(), + * apr_bucket_destroy(), etc), and those macros should be used rather + * than using the function pointers directly. + * + * To write a bucket brigade, they are first made into an iovec, so that we + * don't write too little data at one time. Currently we ignore compacting the + * buckets into as few buckets as possible, but if we really want good + * performance, then we need to compact the buckets before we convert to an + * iovec, or possibly while we are converting to an iovec. + */ + +/* + * Forward declaration of the main types. + */ + +/** @see apr_bucket_brigade */ +typedef struct apr_bucket_brigade apr_bucket_brigade; +/** @see apr_bucket */ +typedef struct apr_bucket apr_bucket; +/** @see apr_bucket_alloc_t */ +typedef struct apr_bucket_alloc_t apr_bucket_alloc_t; + +/** @see apr_bucket_type_t */ +typedef struct apr_bucket_type_t apr_bucket_type_t; + +/** + * Basic bucket type + */ +struct apr_bucket_type_t { + /** + * The name of the bucket type + */ + const char *name; + /** + * The number of functions this bucket understands. Can not be less than + * five. + */ + int num_func; + /** + * Whether the bucket contains metadata (ie, information that + * describes the regular contents of the brigade). The metadata + * is not returned by apr_bucket_read() and is not indicated by + * the ->length of the apr_bucket itself. In other words, an + * empty bucket is safe to arbitrarily remove if and only if it + * contains no metadata. In this sense, "data" is just raw bytes + * that are the "content" of the brigade and "metadata" describes + * that data but is not a proper part of it. + */ + enum { + /** This bucket type represents actual data to send to the client. */ + APR_BUCKET_DATA = 0, + /** This bucket type represents metadata. */ + APR_BUCKET_METADATA = 1 + } is_metadata; + /** + * Free the private data and any resources used by the bucket (if they + * aren't shared with another bucket). This function is required to be + * implemented for all bucket types, though it might be a no-op on some + * of them (namely ones that never allocate any private data structures). + * @param data The private data pointer from the bucket to be destroyed + */ + void (*destroy)(void *data); + + /** + * Read the data from the bucket. This is required to be implemented + * for all bucket types. + * @param b The bucket to read from + * @param str A place to store the data read. Allocation should only be + * done if absolutely necessary. + * @param len The amount of data read. + * @param block Should this read function block if there is more data that + * cannot be read immediately. + */ + apr_status_t (*read)(apr_bucket *b, const char **str, apr_size_t *len, + apr_read_type_e block); + + /** + * Make it possible to set aside the data for at least as long as the + * given pool. Buckets containing data that could potentially die before + * this pool (e.g. the data resides on the stack, in a child pool of + * the given pool, or in a disjoint pool) must somehow copy, shift, or + * transform the data to have the proper lifetime. + * @param e The bucket to convert + * @remark Some bucket types contain data that will always outlive the + * bucket itself. For example no data (EOS and FLUSH), or the data + * resides in global, constant memory (IMMORTAL), or the data is on + * the heap (HEAP). For these buckets, apr_bucket_setaside_noop can + * be used. + */ + apr_status_t (*setaside)(apr_bucket *e, apr_pool_t *pool); + + /** + * Split one bucket in two at the specified position by duplicating + * the bucket structure (not the data) and modifying any necessary + * start/end/offset information. If it's not possible to do this + * for the bucket type (perhaps the length of the data is indeterminate, + * as with pipe and socket buckets), then APR_ENOTIMPL is returned. + * @param e The bucket to split + * @param point The offset of the first byte in the new bucket + */ + apr_status_t (*split)(apr_bucket *e, apr_size_t point); + + /** + * Copy the bucket structure (not the data), assuming that this is + * possible for the bucket type. If it's not, APR_ENOTIMPL is returned. + * @param e The bucket to copy + * @param c Returns a pointer to the new bucket + */ + apr_status_t (*copy)(apr_bucket *e, apr_bucket **c); + +}; + +/** + * apr_bucket structures are allocated on the malloc() heap and + * their lifetime is controlled by the parent apr_bucket_brigade + * structure. Buckets can move from one brigade to another e.g. by + * calling APR_BRIGADE_CONCAT(). In general the data in a bucket has + * the same lifetime as the bucket and is freed when the bucket is + * destroyed; if the data is shared by more than one bucket (e.g. + * after a split) the data is freed when the last bucket goes away. + */ +struct apr_bucket { + /** Links to the rest of the brigade */ + APR_RING_ENTRY(apr_bucket) link; + /** The type of bucket. */ + const apr_bucket_type_t *type; + /** The length of the data in the bucket. This could have been implemented + * with a function, but this is an optimization, because the most + * common thing to do will be to get the length. If the length is unknown, + * the value of this field will be (apr_size_t)(-1). + */ + apr_size_t length; + /** The start of the data in the bucket relative to the private base + * pointer. The vast majority of bucket types allow a fixed block of + * data to be referenced by multiple buckets, each bucket pointing to + * a different segment of the data. That segment starts at base+start + * and ends at base+start+length. + * If the length == (apr_size_t)(-1), then start == -1. + */ + apr_off_t start; + /** type-dependent data hangs off this pointer */ + void *data; + /** + * Pointer to function used to free the bucket. This function should + * always be defined and it should be consistent with the memory + * function used to allocate the bucket. For example, if malloc() is + * used to allocate the bucket, this pointer should point to free(). + * @param e Pointer to the bucket being freed + */ + void (*free)(void *e); + /** The freelist from which this bucket was allocated */ + apr_bucket_alloc_t *list; +}; + +/** A list of buckets */ +struct apr_bucket_brigade { + /** The pool to associate the brigade with. The data is not allocated out + * of the pool, but a cleanup is registered with this pool. If the + * brigade is destroyed by some mechanism other than pool destruction, + * the destroying function is responsible for killing the cleanup. + */ + apr_pool_t *p; + /** The buckets in the brigade are on this list. */ + /* + * The apr_bucket_list structure doesn't actually need a name tag + * because it has no existence independent of struct apr_bucket_brigade; + * the ring macros are designed so that you can leave the name tag + * argument empty in this situation but apparently the Windows compiler + * doesn't like that. + */ + APR_RING_HEAD(apr_bucket_list, apr_bucket) list; + /** The freelist from which this bucket was allocated */ + apr_bucket_alloc_t *bucket_alloc; +}; + + +/** + * Function called when a brigade should be flushed + */ +typedef apr_status_t (*apr_brigade_flush)(apr_bucket_brigade *bb, void *ctx); + +/* + * define APR_BUCKET_DEBUG if you want your brigades to be checked for + * validity at every possible instant. this will slow your code down + * substantially but is a very useful debugging tool. + */ +#ifdef APR_BUCKET_DEBUG + +#define APR_BRIGADE_CHECK_CONSISTENCY(b) \ + APR_RING_CHECK_CONSISTENCY(&(b)->list, apr_bucket, link) + +#define APR_BUCKET_CHECK_CONSISTENCY(e) \ + APR_RING_CHECK_ELEM_CONSISTENCY((e), apr_bucket, link) + +#else +/** + * checks the ring pointers in a bucket brigade for consistency. an + * abort() will be triggered if any inconsistencies are found. + * note: this is a no-op unless APR_BUCKET_DEBUG is defined. + * @param b The brigade + */ +#define APR_BRIGADE_CHECK_CONSISTENCY(b) +/** + * checks the brigade a bucket is in for ring consistency. an + * abort() will be triggered if any inconsistencies are found. + * note: this is a no-op unless APR_BUCKET_DEBUG is defined. + * @param e The bucket + */ +#define APR_BUCKET_CHECK_CONSISTENCY(e) +#endif + + +/** + * Wrappers around the RING macros to reduce the verbosity of the code + * that handles bucket brigades. + */ +/** + * The magic pointer value that indicates the head of the brigade + * @remark This is used to find the beginning and end of the brigade, eg: + *
+ *      while (e != APR_BRIGADE_SENTINEL(b)) {
+ *          ...
+ *          e = APR_BUCKET_NEXT(e);
+ *      }
+ * 
+ * @param b The brigade + * @return The magic pointer value + */ +#define APR_BRIGADE_SENTINEL(b) APR_RING_SENTINEL(&(b)->list, apr_bucket, link) + +/** + * Determine if the bucket brigade is empty + * @param b The brigade to check + * @return true or false + */ +#define APR_BRIGADE_EMPTY(b) APR_RING_EMPTY(&(b)->list, apr_bucket, link) + +/** + * Return the first bucket in a brigade + * @param b The brigade to query + * @return The first bucket in the brigade + */ +#define APR_BRIGADE_FIRST(b) APR_RING_FIRST(&(b)->list) +/** + * Return the last bucket in a brigade + * @param b The brigade to query + * @return The last bucket in the brigade + */ +#define APR_BRIGADE_LAST(b) APR_RING_LAST(&(b)->list) + +/** + * Insert a single bucket at the front of a brigade + * @param b The brigade to add to + * @param e The bucket to insert + */ +#define APR_BRIGADE_INSERT_HEAD(b, e) do { \ + apr_bucket *ap__b = (e); \ + APR_RING_INSERT_HEAD(&(b)->list, ap__b, apr_bucket, link); \ + APR_BRIGADE_CHECK_CONSISTENCY((b)); \ + } while (0) + +/** + * Insert a single bucket at the end of a brigade + * @param b The brigade to add to + * @param e The bucket to insert + */ +#define APR_BRIGADE_INSERT_TAIL(b, e) do { \ + apr_bucket *ap__b = (e); \ + APR_RING_INSERT_TAIL(&(b)->list, ap__b, apr_bucket, link); \ + APR_BRIGADE_CHECK_CONSISTENCY((b)); \ + } while (0) + +/** + * Concatenate brigade b onto the end of brigade a, leaving brigade b empty + * @param a The first brigade + * @param b The second brigade + */ +#define APR_BRIGADE_CONCAT(a, b) do { \ + APR_RING_CONCAT(&(a)->list, &(b)->list, apr_bucket, link); \ + APR_BRIGADE_CHECK_CONSISTENCY((a)); \ + } while (0) + +/** + * Prepend brigade b onto the beginning of brigade a, leaving brigade b empty + * @param a The first brigade + * @param b The second brigade + */ +#define APR_BRIGADE_PREPEND(a, b) do { \ + APR_RING_PREPEND(&(a)->list, &(b)->list, apr_bucket, link); \ + APR_BRIGADE_CHECK_CONSISTENCY((a)); \ + } while (0) + +/** + * Insert a single bucket before a specified bucket + * @param a The bucket to insert before + * @param b The bucket to insert + */ +#define APR_BUCKET_INSERT_BEFORE(a, b) do { \ + apr_bucket *ap__a = (a), *ap__b = (b); \ + APR_RING_INSERT_BEFORE(ap__a, ap__b, link); \ + APR_BUCKET_CHECK_CONSISTENCY(ap__a); \ + } while (0) + +/** + * Insert a single bucket after a specified bucket + * @param a The bucket to insert after + * @param b The bucket to insert + */ +#define APR_BUCKET_INSERT_AFTER(a, b) do { \ + apr_bucket *ap__a = (a), *ap__b = (b); \ + APR_RING_INSERT_AFTER(ap__a, ap__b, link); \ + APR_BUCKET_CHECK_CONSISTENCY(ap__a); \ + } while (0) + +/** + * Get the next bucket in the list + * @param e The current bucket + * @return The next bucket + */ +#define APR_BUCKET_NEXT(e) APR_RING_NEXT((e), link) +/** + * Get the previous bucket in the list + * @param e The current bucket + * @return The previous bucket + */ +#define APR_BUCKET_PREV(e) APR_RING_PREV((e), link) + +/** + * Remove a bucket from its bucket brigade + * @param e The bucket to remove + */ +#define APR_BUCKET_REMOVE(e) APR_RING_REMOVE((e), link) + +/** + * Initialize a new bucket's prev/next pointers + * @param e The bucket to initialize + */ +#define APR_BUCKET_INIT(e) APR_RING_ELEM_INIT((e), link) + +/** + * Determine if a bucket contains metadata. An empty bucket is + * safe to arbitrarily remove if and only if this is false. + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_METADATA(e) ((e)->type->is_metadata) + +/** + * Determine if a bucket is a FLUSH bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_FLUSH(e) ((e)->type == &apr_bucket_type_flush) +/** + * Determine if a bucket is an EOS bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_EOS(e) ((e)->type == &apr_bucket_type_eos) +/** + * Determine if a bucket is a FILE bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_FILE(e) ((e)->type == &apr_bucket_type_file) +/** + * Determine if a bucket is a PIPE bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_PIPE(e) ((e)->type == &apr_bucket_type_pipe) +/** + * Determine if a bucket is a SOCKET bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_SOCKET(e) ((e)->type == &apr_bucket_type_socket) +/** + * Determine if a bucket is a HEAP bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_HEAP(e) ((e)->type == &apr_bucket_type_heap) +/** + * Determine if a bucket is a TRANSIENT bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_TRANSIENT(e) ((e)->type == &apr_bucket_type_transient) +/** + * Determine if a bucket is a IMMORTAL bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_IMMORTAL(e) ((e)->type == &apr_bucket_type_immortal) +#if APR_HAS_MMAP +/** + * Determine if a bucket is a MMAP bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_MMAP(e) ((e)->type == &apr_bucket_type_mmap) +#endif +/** + * Determine if a bucket is a POOL bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_POOL(e) ((e)->type == &apr_bucket_type_pool) + +/* + * General-purpose reference counting for the various bucket types. + * + * Any bucket type that keeps track of the resources it uses (i.e. + * most of them except for IMMORTAL, TRANSIENT, and EOS) needs to + * attach a reference count to the resource so that it can be freed + * when the last bucket that uses it goes away. Resource-sharing may + * occur because of bucket splits or buckets that refer to globally + * cached data. */ + +/** @see apr_bucket_refcount */ +typedef struct apr_bucket_refcount apr_bucket_refcount; +/** + * The structure used to manage the shared resource must start with an + * apr_bucket_refcount which is updated by the general-purpose refcount + * code. A pointer to the bucket-type-dependent private data structure + * can be cast to a pointer to an apr_bucket_refcount and vice versa. + */ +struct apr_bucket_refcount { + /** The number of references to this bucket */ + int refcount; +}; + +/* ***** Reference-counted bucket types ***** */ + +/** @see apr_bucket_heap */ +typedef struct apr_bucket_heap apr_bucket_heap; +/** + * A bucket referring to data allocated off the heap. + */ +struct apr_bucket_heap { + /** Number of buckets using this memory */ + apr_bucket_refcount refcount; + /** The start of the data actually allocated. This should never be + * modified, it is only used to free the bucket. + */ + char *base; + /** how much memory was allocated */ + apr_size_t alloc_len; + /** function to use to delete the data */ + void (*free_func)(void *data); +}; + +/** @see apr_bucket_pool */ +typedef struct apr_bucket_pool apr_bucket_pool; +/** + * A bucket referring to data allocated from a pool + */ +struct apr_bucket_pool { + /** The pool bucket must be able to be easily morphed to a heap + * bucket if the pool gets cleaned up before all references are + * destroyed. This apr_bucket_heap structure is populated automatically + * when the pool gets cleaned up, and subsequent calls to pool_read() + * will result in the apr_bucket in question being morphed into a + * regular heap bucket. (To avoid having to do many extra refcount + * manipulations and b->data manipulations, the apr_bucket_pool + * struct actually *contains* the apr_bucket_heap struct that it + * will become as its first element; the two share their + * apr_bucket_refcount members.) + */ + apr_bucket_heap heap; + /** The block of data actually allocated from the pool. + * Segments of this block are referenced by adjusting + * the start and length of the apr_bucket accordingly. + * This will be NULL after the pool gets cleaned up. + */ + const char *base; + /** The pool the data was allocated from. When the pool + * is cleaned up, this gets set to NULL as an indicator + * to pool_read() that the data is now on the heap and + * so it should morph the bucket into a regular heap + * bucket before continuing. + */ + apr_pool_t *pool; + /** The freelist this structure was allocated from, which is + * needed in the cleanup phase in order to allocate space on the heap + */ + apr_bucket_alloc_t *list; +}; + +#if APR_HAS_MMAP +/** @see apr_bucket_mmap */ +typedef struct apr_bucket_mmap apr_bucket_mmap; +/** + * A bucket referring to an mmap()ed file + */ +struct apr_bucket_mmap { + /** Number of buckets using this memory */ + apr_bucket_refcount refcount; + /** The mmap this sub_bucket refers to */ + apr_mmap_t *mmap; +}; +#endif + +/** @see apr_bucket_file */ +typedef struct apr_bucket_file apr_bucket_file; +/** + * A bucket referring to an file + */ +struct apr_bucket_file { + /** Number of buckets using this memory */ + apr_bucket_refcount refcount; + /** The file this bucket refers to */ + apr_file_t *fd; + /** The pool into which any needed structures should + * be created while reading from this file bucket */ + apr_pool_t *readpool; +#if APR_HAS_MMAP + /** Whether this bucket should be memory-mapped if + * a caller tries to read from it */ + int can_mmap; +#endif /* APR_HAS_MMAP */ + /** File read block size */ + apr_size_t read_size; +}; + +/** @see apr_bucket_structs */ +typedef union apr_bucket_structs apr_bucket_structs; +/** + * A union of all bucket structures so we know what + * the max size is. + */ +union apr_bucket_structs { + apr_bucket b; /**< Bucket */ + apr_bucket_heap heap; /**< Heap */ + apr_bucket_pool pool; /**< Pool */ +#if APR_HAS_MMAP + apr_bucket_mmap mmap; /**< MMap */ +#endif + apr_bucket_file file; /**< File */ +}; + +/** + * The amount that apr_bucket_alloc() should allocate in the common case. + * Note: this is twice as big as apr_bucket_structs to allow breathing + * room for third-party bucket types. + */ +#define APR_BUCKET_ALLOC_SIZE APR_ALIGN_DEFAULT(2*sizeof(apr_bucket_structs)) + +/* ***** Bucket Brigade Functions ***** */ +/** + * Create a new bucket brigade. The bucket brigade is originally empty. + * @param p The pool to associate with the brigade. Data is not allocated out + * of the pool, but a cleanup is registered. + * @param list The bucket allocator to use + * @return The empty bucket brigade + */ +APU_DECLARE(apr_bucket_brigade *) apr_brigade_create(apr_pool_t *p, + apr_bucket_alloc_t *list); + +/** + * destroy an entire bucket brigade. This includes destroying all of the + * buckets within the bucket brigade's bucket list. + * @param b The bucket brigade to destroy + */ +APU_DECLARE(apr_status_t) apr_brigade_destroy(apr_bucket_brigade *b); + +/** + * empty out an entire bucket brigade. This includes destroying all of the + * buckets within the bucket brigade's bucket list. This is similar to + * apr_brigade_destroy(), except that it does not deregister the brigade's + * pool cleanup function. + * @param data The bucket brigade to clean up + * @remark Generally, you should use apr_brigade_destroy(). This function + * can be useful in situations where you have a single brigade that + * you wish to reuse many times by destroying all of the buckets in + * the brigade and putting new buckets into it later. + */ +APU_DECLARE(apr_status_t) apr_brigade_cleanup(void *data); + +/** + * Move the buckets from the tail end of the existing brigade @a b into + * the brigade @a a. If @a a is NULL a new brigade is created. Buckets + * from @a e to the last bucket (inclusively) of brigade @a b are moved + * from @a b to the returned brigade @a a. + * + * @param b The brigade to split + * @param e The first bucket to move + * @param a The brigade which should be used for the result or NULL if + * a new brigade should be created. The brigade @a a will be + * cleared if it is not empty. + * @return The brigade supplied in @a a or a new one if @a a was NULL. + * @warning Note that this function allocates a new brigade if @a a is + * NULL so memory consumption should be carefully considered. + */ +APU_DECLARE(apr_bucket_brigade *) apr_brigade_split_ex(apr_bucket_brigade *b, + apr_bucket *e, + apr_bucket_brigade *a); + +/** + * Create a new bucket brigade and move the buckets from the tail end + * of an existing brigade into the new brigade. Buckets from + * @a e to the last bucket (inclusively) of brigade @a b + * are moved from @a b to the returned brigade. + * @param b The brigade to split + * @param e The first bucket to move + * @return The new brigade + * @warning Note that this function always allocates a new brigade + * so memory consumption should be carefully considered. + */ +APU_DECLARE(apr_bucket_brigade *) apr_brigade_split(apr_bucket_brigade *b, + apr_bucket *e); + +/** + * Partition a bucket brigade at a given offset (in bytes from the start of + * the brigade). This is useful whenever a filter wants to use known ranges + * of bytes from the brigade; the ranges can even overlap. + * @param b The brigade to partition + * @param point The offset at which to partition the brigade + * @param after_point Returns a pointer to the first bucket after the partition + * @return APR_SUCCESS on success, APR_INCOMPLETE if the contents of the + * brigade were shorter than @a point, or an error code. + * @remark if APR_INCOMPLETE is returned, @a after_point will be set to + * the brigade sentinel. + */ +APU_DECLARE(apr_status_t) apr_brigade_partition(apr_bucket_brigade *b, + apr_off_t point, + apr_bucket **after_point); + +/** + * Return the total length of the brigade. + * @param bb The brigade to compute the length of + * @param read_all Read unknown-length buckets to force a size + * @param length Returns the length of the brigade (up to the end, or up + * to a bucket read error), or -1 if the brigade has buckets + * of indeterminate length and read_all is 0. + */ +APU_DECLARE(apr_status_t) apr_brigade_length(apr_bucket_brigade *bb, + int read_all, + apr_off_t *length); + +/** + * Take a bucket brigade and store the data in a flat char* + * @param bb The bucket brigade to create the char* from + * @param c The char* to write into + * @param len The maximum length of the char array. On return, it is the + * actual length of the char array. + */ +APU_DECLARE(apr_status_t) apr_brigade_flatten(apr_bucket_brigade *bb, + char *c, + apr_size_t *len); + +/** + * Creates a pool-allocated string representing a flat bucket brigade + * @param bb The bucket brigade to create the char array from + * @param c On return, the allocated char array + * @param len On return, the length of the char array. + * @param pool The pool to allocate the string from. + */ +APU_DECLARE(apr_status_t) apr_brigade_pflatten(apr_bucket_brigade *bb, + char **c, + apr_size_t *len, + apr_pool_t *pool); + +/** + * Split a brigade to represent one LF line. + * @param bbOut The bucket brigade that will have the LF line appended to. + * @param bbIn The input bucket brigade to search for a LF-line. + * @param block The blocking mode to be used to split the line. + * @param maxbytes The maximum bytes to read. If this many bytes are seen + * without a LF, the brigade will contain a partial line. + */ +APU_DECLARE(apr_status_t) apr_brigade_split_line(apr_bucket_brigade *bbOut, + apr_bucket_brigade *bbIn, + apr_read_type_e block, + apr_off_t maxbytes); + +/** + * Create an iovec of the elements in a bucket_brigade... return number + * of elements used. This is useful for writing to a file or to the + * network efficiently. + * @param b The bucket brigade to create the iovec from + * @param vec The iovec to create + * @param nvec The number of elements in the iovec. On return, it is the + * number of iovec elements actually filled out. + */ +APU_DECLARE(apr_status_t) apr_brigade_to_iovec(apr_bucket_brigade *b, + struct iovec *vec, int *nvec); + +/** + * This function writes a list of strings into a bucket brigade. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param va A list of strings to add + * @return APR_SUCCESS or error code. + */ +APU_DECLARE(apr_status_t) apr_brigade_vputstrs(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, + va_list va); + +/** + * This function writes a string into a bucket brigade. + * + * The apr_brigade_write function attempts to be efficient with the + * handling of heap buckets. Regardless of the amount of data stored + * inside a heap bucket, heap buckets are a fixed size to promote their + * reuse. + * + * If an attempt is made to write a string to a brigade that already + * ends with a heap bucket, this function will attempt to pack the + * string into the remaining space in the previous heap bucket, before + * allocating a new heap bucket. + * + * This function always returns APR_SUCCESS, unless a flush function is + * passed, in which case the return value of the flush function will be + * returned if used. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param str The string to add + * @param nbyte The number of bytes to write + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_write(apr_bucket_brigade *b, + apr_brigade_flush flush, void *ctx, + const char *str, apr_size_t nbyte); + +/** + * This function writes multiple strings into a bucket brigade. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param vec The strings to add (address plus length for each) + * @param nvec The number of entries in iovec + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_writev(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, + const struct iovec *vec, + apr_size_t nvec); + +/** + * This function writes a string into a bucket brigade. + * @param bb The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param str The string to add + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_puts(apr_bucket_brigade *bb, + apr_brigade_flush flush, void *ctx, + const char *str); + +/** + * This function writes a character into a bucket brigade. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param c The character to add + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_putc(apr_bucket_brigade *b, + apr_brigade_flush flush, void *ctx, + const char c); + +/** + * This function writes an unspecified number of strings into a bucket brigade. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param ... The strings to add + * @return APR_SUCCESS or error code + */ +APU_DECLARE_NONSTD(apr_status_t) apr_brigade_putstrs(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, ...); + +/** + * Evaluate a printf and put the resulting string at the end + * of the bucket brigade. + * @param b The brigade to write to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param fmt The format of the string to write + * @param ... The arguments to fill out the format + * @return APR_SUCCESS or error code + */ +APU_DECLARE_NONSTD(apr_status_t) apr_brigade_printf(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, + const char *fmt, ...) + __attribute__((format(printf,4,5))); + +/** + * Evaluate a printf and put the resulting string at the end + * of the bucket brigade. + * @param b The brigade to write to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param fmt The format of the string to write + * @param va The arguments to fill out the format + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_vprintf(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, + const char *fmt, va_list va); + +/** + * Utility function to insert a file (or a segment of a file) onto the + * end of the brigade. The file is split into multiple buckets if it + * is larger than the maximum size which can be represented by a + * single bucket. + * @param bb the brigade to insert into + * @param f the file to insert + * @param start the offset of the start of the segment + * @param len the length of the segment of the file to insert + * @param p pool from which file buckets are allocated + * @return the last bucket inserted + */ +APU_DECLARE(apr_bucket *) apr_brigade_insert_file(apr_bucket_brigade *bb, + apr_file_t *f, + apr_off_t start, + apr_off_t len, + apr_pool_t *p); + + + +/* ***** Bucket freelist functions ***** */ +/** + * Create a bucket allocator. + * @param p This pool's underlying apr_allocator_t is used to allocate memory + * for the bucket allocator. When the pool is destroyed, the bucket + * allocator's cleanup routine will free all memory that has been + * allocated from it. + * @remark The reason the allocator gets its memory from the pool's + * apr_allocator_t rather than from the pool itself is because + * the bucket allocator will free large memory blocks back to the + * allocator when it's done with them, thereby preventing memory + * footprint growth that would occur if we allocated from the pool. + * @warning The allocator must never be used by more than one thread at a time. + */ +APU_DECLARE_NONSTD(apr_bucket_alloc_t *) apr_bucket_alloc_create(apr_pool_t *p); + +/** + * Create a bucket allocator. + * @param allocator This apr_allocator_t is used to allocate both the bucket + * allocator and all memory handed out by the bucket allocator. The + * caller is responsible for destroying the bucket allocator and the + * apr_allocator_t -- no automatic cleanups will happen. + * @warning The allocator must never be used by more than one thread at a time. + */ +APU_DECLARE_NONSTD(apr_bucket_alloc_t *) apr_bucket_alloc_create_ex(apr_allocator_t *allocator); + +/** + * Destroy a bucket allocator. + * @param list The allocator to be destroyed + */ +APU_DECLARE_NONSTD(void) apr_bucket_alloc_destroy(apr_bucket_alloc_t *list); + +/** + * Get the aligned size corresponding to the requested size, but minus the + * allocator(s) overhead such that the allocation would remain in the + * same boundary. + * @param list The allocator from which to the memory would be allocated. + * @param size The requested size. + * @return The corresponding aligned/floored size. + */ +APU_DECLARE_NONSTD(apr_size_t) apr_bucket_alloc_aligned_floor(apr_bucket_alloc_t *list, + apr_size_t size) + __attribute__((nonnull(1))); + +/** + * Allocate memory for use by the buckets. + * @param size The amount to allocate. + * @param list The allocator from which to allocate the memory. + */ +APU_DECLARE_NONSTD(void *) apr_bucket_alloc(apr_size_t size, apr_bucket_alloc_t *list); + +/** + * Free memory previously allocated with apr_bucket_alloc(). + * @param block The block of memory to be freed. + */ +APU_DECLARE_NONSTD(void) apr_bucket_free(void *block); + + +/* ***** Bucket Functions ***** */ +/** + * Free the resources used by a bucket. If multiple buckets refer to + * the same resource it is freed when the last one goes away. + * @see apr_bucket_delete() + * @param e The bucket to destroy + */ +#define apr_bucket_destroy(e) do { \ + apr_bucket *apr__d = (e); \ + apr__d->type->destroy(apr__d->data); \ + apr__d->free(apr__d); \ + } while (0) + +/** + * Delete a bucket by removing it from its brigade (if any) and then + * destroying it. + * @remark This mainly acts as an aid in avoiding code verbosity. It is + * the preferred exact equivalent to: + *
+ *      APR_BUCKET_REMOVE(e);
+ *      apr_bucket_destroy(e);
+ * 
+ * @param e The bucket to delete + */ +#define apr_bucket_delete(e) do { \ + apr_bucket *apr__b = (e); \ + APR_BUCKET_REMOVE(apr__b); \ + apr_bucket_destroy(apr__b); \ + } while (0) + +/** + * Read some data from the bucket. + * + * The apr_bucket_read function returns a convenient amount of data + * from the bucket provided, writing the address and length of the + * data to the pointers provided by the caller. The function tries + * as hard as possible to avoid a memory copy. + * + * Buckets are expected to be a member of a brigade at the time they + * are read. + * + * In typical application code, buckets are read in a loop, and after + * each bucket is read and processed, it is moved or deleted from the + * brigade and the next bucket read. + * + * The definition of "convenient" depends on the type of bucket that + * is being read, and is decided by APR. In the case of memory based + * buckets such as heap and immortal buckets, a pointer will be + * returned to the location of the buffer containing the complete + * contents of the bucket. + * + * Some buckets, such as the socket bucket, might have no concept + * of length. If an attempt is made to read such a bucket, the + * apr_bucket_read function will read a convenient amount of data + * from the socket. The socket bucket is magically morphed into a + * heap bucket containing the just-read data, and a new socket bucket + * is inserted just after this heap bucket. + * + * To understand why apr_bucket_read might do this, consider the loop + * described above to read and process buckets. The current bucket + * is magically morphed into a heap bucket and returned to the caller. + * The caller processes the data, and deletes the heap bucket, moving + * onto the next bucket, the new socket bucket. This process repeats, + * giving the illusion of a bucket brigade that contains potentially + * infinite amounts of data. It is up to the caller to decide at what + * point to stop reading buckets. + * + * Some buckets, such as the file bucket, might have a fixed size, + * but be significantly larger than is practical to store in RAM in + * one go. As with the socket bucket, if an attempt is made to read + * from a file bucket, the file bucket is magically morphed into a + * heap bucket containing a convenient amount of data read from the + * current offset in the file. During the read, the offset will be + * moved forward on the file, and a new file bucket will be inserted + * directly after the current bucket representing the remainder of the + * file. If the heap bucket was large enough to store the whole + * remainder of the file, no more file buckets are inserted, and the + * file bucket will disappear completely. + * + * The pattern for reading buckets described above does create the + * illusion that the code is willing to swallow buckets that might be + * too large for the system to handle in one go. This however is just + * an illusion: APR will always ensure that large (file) or infinite + * (socket) buckets are broken into convenient bite sized heap buckets + * before data is returned to the caller. + * + * There is a potential gotcha to watch for: if buckets are read in a + * loop, and aren't deleted after being processed, the potentially large + * bucket will slowly be converted into RAM resident heap buckets. If + * the file is larger than available RAM, an out of memory condition + * could be caused if the application is not careful to manage this. + * + * @param e The bucket to read from + * @param str The location to store a pointer to the data in + * @param len The location to store the amount of data read + * @param block Whether the read function blocks + */ +#define apr_bucket_read(e,str,len,block) (e)->type->read(e, str, len, block) + +/** + * Setaside data so that stack data is not destroyed on returning from + * the function + * @param e The bucket to setaside + * @param p The pool to setaside into + */ +#define apr_bucket_setaside(e,p) (e)->type->setaside(e,p) + +/** + * Split one bucket in two at the point provided. + * + * Once split, the original bucket becomes the first of the two new buckets. + * + * (It is assumed that the bucket is a member of a brigade when this + * function is called). + * @param e The bucket to split + * @param point The offset to split the bucket at + */ +#define apr_bucket_split(e,point) (e)->type->split(e, point) + +/** + * Copy a bucket. + * @param e The bucket to copy + * @param c Returns a pointer to the new bucket + */ +#define apr_bucket_copy(e,c) (e)->type->copy(e, c) + +/* Bucket type handling */ + +/** + * This function simply returns APR_SUCCESS to denote that the bucket does + * not require anything to happen for its setaside() function. This is + * appropriate for buckets that have "immortal" data -- the data will live + * at least as long as the bucket. + * @param data The bucket to setaside + * @param pool The pool defining the desired lifetime of the bucket data + * @return APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_setaside_noop(apr_bucket *data, + apr_pool_t *pool); + +/** + * A place holder function that signifies that the setaside function was not + * implemented for this bucket + * @param data The bucket to setaside + * @param pool The pool defining the desired lifetime of the bucket data + * @return APR_ENOTIMPL + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_setaside_notimpl(apr_bucket *data, + apr_pool_t *pool); + +/** + * A place holder function that signifies that the split function was not + * implemented for this bucket + * @param data The bucket to split + * @param point The location to split the bucket + * @return APR_ENOTIMPL + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_split_notimpl(apr_bucket *data, + apr_size_t point); + +/** + * A place holder function that signifies that the copy function was not + * implemented for this bucket + * @param e The bucket to copy + * @param c Returns a pointer to the new bucket + * @return APR_ENOTIMPL + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_copy_notimpl(apr_bucket *e, + apr_bucket **c); + +/** + * A place holder function that signifies that this bucket does not need + * to do anything special to be destroyed. That's only the case for buckets + * that either have no data (metadata buckets) or buckets whose data pointer + * points to something that's not a bucket-type-specific structure, as with + * simple buckets where data points to a string and pipe buckets where data + * points directly to the apr_file_t. + * @param data The bucket data to destroy + */ +APU_DECLARE_NONSTD(void) apr_bucket_destroy_noop(void *data); + +/** + * There is no apr_bucket_destroy_notimpl, because destruction is required + * to be implemented (it could be a noop, but only if that makes sense for + * the bucket type) + */ + +/* There is no apr_bucket_read_notimpl, because it is a required function + */ + + +/* All of the bucket types implemented by the core */ +/** + * The flush bucket type. This signifies that all data should be flushed to + * the next filter. The flush bucket should be sent with the other buckets. + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_flush; +/** + * The EOS bucket type. This signifies that there will be no more data, ever. + * All filters MUST send all data to the next filter when they receive a + * bucket of this type + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_eos; +/** + * The FILE bucket type. This bucket represents a file on disk + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_file; +/** + * The HEAP bucket type. This bucket represents a data allocated from the + * heap. + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_heap; +#if APR_HAS_MMAP +/** + * The MMAP bucket type. This bucket represents an MMAP'ed file + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_mmap; +#endif +/** + * The POOL bucket type. This bucket represents a data that was allocated + * from a pool. IF this bucket is still available when the pool is cleared, + * the data is copied on to the heap. + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_pool; +/** + * The PIPE bucket type. This bucket represents a pipe to another program. + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_pipe; +/** + * The IMMORTAL bucket type. This bucket represents a segment of data that + * the creator is willing to take responsibility for. The core will do + * nothing with the data in an immortal bucket + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_immortal; +/** + * The TRANSIENT bucket type. This bucket represents a data allocated off + * the stack. When the setaside function is called, this data is copied on + * to the heap + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_transient; +/** + * The SOCKET bucket type. This bucket represents a socket to another machine + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_socket; + + +/* ***** Simple buckets ***** */ + +/** + * Split a simple bucket into two at the given point. Most non-reference + * counting buckets that allow multiple references to the same block of + * data (eg transient and immortal) will use this as their split function + * without any additional type-specific handling. + * @param b The bucket to be split + * @param point The offset of the first byte in the new bucket + * @return APR_EINVAL if the point is not within the bucket; + * APR_ENOMEM if allocation failed; + * or APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_simple_split(apr_bucket *b, + apr_size_t point); + +/** + * Copy a simple bucket. Most non-reference-counting buckets that allow + * multiple references to the same block of data (eg transient and immortal) + * will use this as their copy function without any additional type-specific + * handling. + * @param a The bucket to copy + * @param b Returns a pointer to the new bucket + * @return APR_ENOMEM if allocation failed; + * or APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_simple_copy(apr_bucket *a, + apr_bucket **b); + + +/* ***** Shared, reference-counted buckets ***** */ + +/** + * Initialize a bucket containing reference-counted data that may be + * shared. The caller must allocate the bucket if necessary and + * initialize its type-dependent fields, and allocate and initialize + * its own private data structure. This function should only be called + * by type-specific bucket creation functions. + * @param b The bucket to initialize + * @param data A pointer to the private data structure + * with the reference count at the start + * @param start The start of the data in the bucket + * relative to the private base pointer + * @param length The length of the data in the bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_shared_make(apr_bucket *b, void *data, + apr_off_t start, + apr_size_t length); + +/** + * Decrement the refcount of the data in the bucket. This function + * should only be called by type-specific bucket destruction functions. + * @param data The private data pointer from the bucket to be destroyed + * @return TRUE or FALSE; TRUE if the reference count is now + * zero, indicating that the shared resource itself can + * be destroyed by the caller. + */ +APU_DECLARE(int) apr_bucket_shared_destroy(void *data); + +/** + * Split a bucket into two at the given point, and adjust the refcount + * to the underlying data. Most reference-counting bucket types will + * be able to use this function as their split function without any + * additional type-specific handling. + * @param b The bucket to be split + * @param point The offset of the first byte in the new bucket + * @return APR_EINVAL if the point is not within the bucket; + * APR_ENOMEM if allocation failed; + * or APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_shared_split(apr_bucket *b, + apr_size_t point); + +/** + * Copy a refcounted bucket, incrementing the reference count. Most + * reference-counting bucket types will be able to use this function + * as their copy function without any additional type-specific handling. + * @param a The bucket to copy + * @param b Returns a pointer to the new bucket + * @return APR_ENOMEM if allocation failed; + or APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_shared_copy(apr_bucket *a, + apr_bucket **b); + + +/* ***** Functions to Create Buckets of varying types ***** */ +/* + * Each bucket type foo has two initialization functions: + * apr_bucket_foo_make which sets up some already-allocated memory as a + * bucket of type foo; and apr_bucket_foo_create which allocates memory + * for the bucket, calls apr_bucket_make_foo, and initializes the + * bucket's list pointers. The apr_bucket_foo_make functions are used + * inside the bucket code to change the type of buckets in place; + * other code should call apr_bucket_foo_create. All the initialization + * functions change nothing if they fail. + */ + +/** + * Create an End of Stream bucket. This indicates that there is no more data + * coming from down the filter stack. All filters should flush at this point. + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_eos_create(apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in an EOS bucket. This indicates that there is no + * more data coming from down the filter stack. All filters should flush at + * this point. + * @param b The bucket to make into an EOS bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_eos_make(apr_bucket *b); + +/** + * Create a flush bucket. This indicates that filters should flush their + * data. There is no guarantee that they will flush it, but this is the + * best we can do. + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_flush_create(apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a FLUSH bucket. This indicates that filters + * should flush their data. There is no guarantee that they will flush it, + * but this is the best we can do. + * @param b The bucket to make into a FLUSH bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_flush_make(apr_bucket *b); + +/** + * Create a bucket referring to long-lived data. + * @param buf The data to insert into the bucket + * @param nbyte The size of the data to insert. + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_immortal_create(const char *buf, + apr_size_t nbyte, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to long-lived data + * @param b The bucket to make into a IMMORTAL bucket + * @param buf The data to insert into the bucket + * @param nbyte The size of the data to insert. + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_immortal_make(apr_bucket *b, + const char *buf, + apr_size_t nbyte); + +/** + * Create a bucket referring to data on the stack. + * @param buf The data to insert into the bucket + * @param nbyte The size of the data to insert. + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_transient_create(const char *buf, + apr_size_t nbyte, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to stack data + * @param b The bucket to make into a TRANSIENT bucket + * @param buf The data to insert into the bucket + * @param nbyte The size of the data to insert. + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_transient_make(apr_bucket *b, + const char *buf, + apr_size_t nbyte); + +/** + * Create a bucket referring to memory on the heap. If the caller asks + * for the data to be copied, this function always allocates 4K of + * memory so that more data can be added to the bucket without + * requiring another allocation. Therefore not all the data may be put + * into the bucket. If copying is not requested then the bucket takes + * over responsibility for free()ing the memory. + * @param buf The buffer to insert into the bucket + * @param nbyte The size of the buffer to insert. + * @param free_func Function to use to free the data; NULL indicates that the + * bucket should make a copy of the data + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_heap_create(const char *buf, + apr_size_t nbyte, + void (*free_func)(void *data), + apr_bucket_alloc_t *list); +/** + * Make the bucket passed in a bucket refer to heap data + * @param b The bucket to make into a HEAP bucket + * @param buf The buffer to insert into the bucket + * @param nbyte The size of the buffer to insert. + * @param free_func Function to use to free the data; NULL indicates that the + * bucket should make a copy of the data + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_heap_make(apr_bucket *b, const char *buf, + apr_size_t nbyte, + void (*free_func)(void *data)); + +/** + * Create a bucket referring to memory allocated from a pool. + * + * @param buf The buffer to insert into the bucket + * @param length The number of bytes referred to by this bucket + * @param pool The pool the memory was allocated from + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_pool_create(const char *buf, + apr_size_t length, + apr_pool_t *pool, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to pool data + * @param b The bucket to make into a pool bucket + * @param buf The buffer to insert into the bucket + * @param length The number of bytes referred to by this bucket + * @param pool The pool the memory was allocated from + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_pool_make(apr_bucket *b, const char *buf, + apr_size_t length, + apr_pool_t *pool); + +#if APR_HAS_MMAP +/** + * Create a bucket referring to mmap()ed memory. + * @param mm The mmap to insert into the bucket + * @param start The offset of the first byte in the mmap + * that this bucket refers to + * @param length The number of bytes referred to by this bucket + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_mmap_create(apr_mmap_t *mm, + apr_off_t start, + apr_size_t length, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to an MMAP'ed file + * @param b The bucket to make into a MMAP bucket + * @param mm The mmap to insert into the bucket + * @param start The offset of the first byte in the mmap + * that this bucket refers to + * @param length The number of bytes referred to by this bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_mmap_make(apr_bucket *b, apr_mmap_t *mm, + apr_off_t start, + apr_size_t length); +#endif + +/** + * Create a bucket referring to a socket. + * @param thissock The socket to put in the bucket + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_socket_create(apr_socket_t *thissock, + apr_bucket_alloc_t *list); +/** + * Make the bucket passed in a bucket refer to a socket + * @param b The bucket to make into a SOCKET bucket + * @param thissock The socket to put in the bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_socket_make(apr_bucket *b, + apr_socket_t *thissock); + +/** + * Create a bucket referring to a pipe. + * @param thispipe The pipe to put in the bucket + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_pipe_create(apr_file_t *thispipe, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to a pipe + * @param b The bucket to make into a PIPE bucket + * @param thispipe The pipe to put in the bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_pipe_make(apr_bucket *b, + apr_file_t *thispipe); + +/** + * Create a bucket referring to a file. + * @param fd The file to put in the bucket + * @param offset The offset where the data of interest begins in the file + * @param len The amount of data in the file we are interested in + * @param p The pool into which any needed structures should be created + * while reading from this file bucket + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + * @remark If the file is truncated such that the segment of the file + * referenced by the bucket no longer exists, an attempt to read + * from the bucket will fail with APR_EOF. + * @remark apr_brigade_insert_file() should generally be used to + * insert files into brigades, since that function can correctly + * handle large file issues. + */ +APU_DECLARE(apr_bucket *) apr_bucket_file_create(apr_file_t *fd, + apr_off_t offset, + apr_size_t len, + apr_pool_t *p, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to a file + * @param b The bucket to make into a FILE bucket + * @param fd The file to put in the bucket + * @param offset The offset where the data of interest begins in the file + * @param len The amount of data in the file we are interested in + * @param p The pool into which any needed structures should be created + * while reading from this file bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_file_make(apr_bucket *b, apr_file_t *fd, + apr_off_t offset, + apr_size_t len, apr_pool_t *p); + +/** + * Enable or disable memory-mapping for a FILE bucket (default is enabled) + * @param b The bucket + * @param enabled Whether memory-mapping should be enabled + * @return APR_SUCCESS normally, or an error code if the operation fails + */ +APU_DECLARE(apr_status_t) apr_bucket_file_enable_mmap(apr_bucket *b, + int enabled); + +/** + * Set the size of the read buffer allocated by a FILE bucket (default + * is @a APR_BUCKET_BUFF_SIZE) + * memory-mapping is disabled only) + * @param b The bucket + * @param size Size of the allocated buffers + * @return APR_SUCCESS normally, or an error code if the operation fails + * @remark Relevant/used only when memory-mapping is disabled (@see + * apr_bucket_file_enable_mmap) + */ +APU_DECLARE(apr_status_t) apr_bucket_file_set_buf_size(apr_bucket *b, + apr_size_t size); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_BUCKETS_H */ diff --git a/c/dependencies/macos/apr/include/apr_crypto.h b/c/dependencies/macos/apr/include/apr_crypto.h new file mode 100644 index 00000000..b90f3fec --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_crypto.h @@ -0,0 +1,507 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_CRYPTO_H +#define APR_CRYPTO_H + +#include "apu.h" +#include "apr_pools.h" +#include "apr_tables.h" +#include "apr_hash.h" +#include "apu_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_crypto.h + * @brief APR-UTIL Crypto library + */ +/** + * @defgroup APR_Util_Crypto Crypto routines + * @ingroup APR_Util + * @{ + */ + +#if APU_HAVE_CRYPTO + +#ifndef APU_CRYPTO_RECOMMENDED_DRIVER +#if APU_HAVE_COMMONCRYPTO +#define APU_CRYPTO_RECOMMENDED_DRIVER "commoncrypto" +#else +#if APU_HAVE_OPENSSL +#define APU_CRYPTO_RECOMMENDED_DRIVER "openssl" +#else +#if APU_HAVE_NSS +#define APU_CRYPTO_RECOMMENDED_DRIVER "nss" +#else +#if APU_HAVE_MSCNG +#define APU_CRYPTO_RECOMMENDED_DRIVER "mscng" +#else +#if APU_HAVE_MSCAPI +#define APU_CRYPTO_RECOMMENDED_DRIVER "mscapi" +#else +#endif +#endif +#endif +#endif +#endif +#endif + +/** + * Symmetric Key types understood by the library. + * + * NOTE: It is expected that this list will grow over time. + * + * Interoperability Matrix: + * + * The matrix is based on the testcrypto.c unit test, which attempts to + * test whether a simple encrypt/decrypt will succeed, as well as testing + * whether an encrypted string by one library can be decrypted by the + * others. + * + * Some libraries will successfully encrypt and decrypt their own data, + * but won't decrypt data from another library. It is hoped that over + * time these anomalies will be found and fixed, but until then it is + * recommended that ciphers are chosen that interoperate across platform. + * + * An X below means the test passes, it does not necessarily mean that + * encryption performed is correct or secure. Applications should stick + * to ciphers that pass the interoperablity tests on the right hand side + * of the table. + * + * Aligned data is data whose length is a multiple of the block size for + * the chosen cipher. Padded data is data that is not aligned by block + * size and must be padded by the crypto library. + * + * OpenSSL CommonCrypto NSS Interop + * Align Pad Align Pad Align Pad Align Pad + * 3DES_192/CBC X X X X X X X X + * 3DES_192/ECB X X X X + * AES_256/CBC X X X X X X X X + * AES_256/ECB X X X X X X + * AES_192/CBC X X X X X X + * AES_192/ECB X X X X X + * AES_128/CBC X X X X X X + * AES_128/ECB X X X X X + * + * Conclusion: for padded data, use 3DES_192/CBC or AES_256/CBC. For + * aligned data, use 3DES_192/CBC, AES_256/CBC or AES_256/ECB. + */ + +typedef enum +{ + APR_KEY_NONE, APR_KEY_3DES_192, /** 192 bit (3-Key) 3DES */ + APR_KEY_AES_128, /** 128 bit AES */ + APR_KEY_AES_192, /** 192 bit AES */ + APR_KEY_AES_256 +/** 256 bit AES */ +} apr_crypto_block_key_type_e; + +typedef enum +{ + APR_MODE_NONE, /** An error condition */ + APR_MODE_ECB, /** Electronic Code Book */ + APR_MODE_CBC +/** Cipher Block Chaining */ +} apr_crypto_block_key_mode_e; + +/* These are opaque structs. Instantiation is up to each backend */ +typedef struct apr_crypto_driver_t apr_crypto_driver_t; +typedef struct apr_crypto_t apr_crypto_t; +typedef struct apr_crypto_config_t apr_crypto_config_t; +typedef struct apr_crypto_key_t apr_crypto_key_t; +typedef struct apr_crypto_block_t apr_crypto_block_t; + +typedef struct apr_crypto_block_key_type_t { + apr_crypto_block_key_type_e type; + int keysize; + int blocksize; + int ivsize; +} apr_crypto_block_key_type_t; + +typedef struct apr_crypto_block_key_mode_t { + apr_crypto_block_key_mode_e mode; +} apr_crypto_block_key_mode_t; + +typedef struct apr_crypto_passphrase_t { + const char *pass; + apr_size_t passLen; + const unsigned char * salt; + apr_size_t saltLen; + int iterations; +} apr_crypto_passphrase_t; + +typedef struct apr_crypto_secret_t { + const unsigned char *secret; + apr_size_t secretLen; +} apr_crypto_secret_t; + +typedef enum { + /** Key is derived from a passphrase */ + APR_CRYPTO_KTYPE_PASSPHRASE = 1, + /** Key is derived from a raw key */ + APR_CRYPTO_KTYPE_SECRET = 2, +} apr_crypto_key_type; + +typedef struct apr_crypto_key_rec_t { + apr_crypto_key_type ktype; + apr_crypto_block_key_type_e type; + apr_crypto_block_key_mode_e mode; + int pad; + union { + apr_crypto_passphrase_t passphrase; + apr_crypto_secret_t secret; + } k; +} apr_crypto_key_rec_t; + +/** + * @brief Perform once-only initialisation. Call once only. + * + * @param pool - pool to register any shutdown cleanups, etc + * @return APR_NOTIMPL in case of no crypto support. + */ +APU_DECLARE(apr_status_t) apr_crypto_init(apr_pool_t *pool); + +/** + * @brief Zero out the buffer provided when the pool is cleaned up. + * + * @param pool - pool to register the cleanup + * @param buffer - buffer to zero out + * @param size - size of the buffer to zero out + */ +APU_DECLARE(apr_status_t) apr_crypto_clear(apr_pool_t *pool, void *buffer, + apr_size_t size); + +/** + * @brief Always zero out the buffer provided, without being optimized out by + * the compiler. + * + * @param buffer - buffer to zero out + * @param size - size of the buffer to zero out + */ +APU_DECLARE(apr_status_t) apr_crypto_memzero(void *buffer, apr_size_t size); + +/** + * @brief Timing attacks safe buffers comparison, where the executing time does + * not depend on the bytes compared but solely on the number of bytes. + * + * @param buf1 - first buffer to compare + * @param buf2 - second buffer to compare + * @param size - size of the buffers to compare + * @return 1 if the buffers are equals, 0 otherwise. + */ +APU_DECLARE(int) apr_crypto_equals(const void *buf1, const void *buf2, + apr_size_t size); + +/** + * @brief Get the driver struct for a name + * + * @param driver - pointer to driver struct. + * @param name - driver name + * @param params - array of initialisation parameters + * @param result - result and error message on failure + * @param pool - (process) pool to register cleanup + * @return APR_SUCCESS for success + * @return APR_ENOTIMPL for no driver (when DSO not enabled) + * @return APR_EDSOOPEN if DSO driver file can't be opened + * @return APR_ESYMNOTFOUND if the driver file doesn't contain a driver + * @remarks NSS: the params can have "dir", "key3", "cert7" and "secmod" + * keys, each followed by an equal sign and a value. Such key/value pairs can + * be delimited by space or tab. If the value contains a space, surround the + * whole key value pair in quotes: "dir=My Directory". + * @remarks OpenSSL: currently no params are supported. + */ +APU_DECLARE(apr_status_t) apr_crypto_get_driver( + const apr_crypto_driver_t **driver, + const char *name, const char *params, const apu_err_t **result, + apr_pool_t *pool); + +/** + * @brief Return the name of the driver. + * + * @param driver - The driver in use. + * @return The name of the driver. + */ +APU_DECLARE(const char *) apr_crypto_driver_name( + const apr_crypto_driver_t *driver); + +/** + * @brief Get the result of the last operation on a context. If the result + * is NULL, the operation was successful. + * @param result - the result structure + * @param f - context pointer + * @return APR_SUCCESS for success + */ +APU_DECLARE(apr_status_t) apr_crypto_error(const apu_err_t **result, + const apr_crypto_t *f); + +/** + * @brief Create a context for supporting encryption. Keys, certificates, + * algorithms and other parameters will be set per context. More than + * one context can be created at one time. A cleanup will be automatically + * registered with the given pool to guarantee a graceful shutdown. + * @param f - context pointer will be written here + * @param driver - driver to use + * @param params - array of key parameters + * @param pool - process pool + * @return APR_ENOENGINE when the engine specified does not exist. APR_EINITENGINE + * if the engine cannot be initialised. + * @remarks NSS: currently no params are supported. + * @remarks OpenSSL: the params can have "engine" as a key, followed by an equal + * sign and a value. + */ +APU_DECLARE(apr_status_t) apr_crypto_make(apr_crypto_t **f, + const apr_crypto_driver_t *driver, const char *params, + apr_pool_t *pool); + +/** + * @brief Get a hash table of key types, keyed by the name of the type against + * a pointer to apr_crypto_block_key_type_t, which in turn begins with an + * integer. + * + * @param types - hashtable of key types keyed to constants. + * @param f - encryption context + * @return APR_SUCCESS for success + */ +APU_DECLARE(apr_status_t) apr_crypto_get_block_key_types(apr_hash_t **types, + const apr_crypto_t *f); + +/** + * @brief Get a hash table of key modes, keyed by the name of the mode against + * a pointer to apr_crypto_block_key_mode_t, which in turn begins with an + * integer. + * + * @param modes - hashtable of key modes keyed to constants. + * @param f - encryption context + * @return APR_SUCCESS for success + */ +APU_DECLARE(apr_status_t) apr_crypto_get_block_key_modes(apr_hash_t **modes, + const apr_crypto_t *f); + +/** + * @brief Create a key from the provided secret or passphrase. The key is cleaned + * up when the context is cleaned, and may be reused with multiple encryption + * or decryption operations. + * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If + * *key is not NULL, *key must point at a previously created structure. + * @param key The key returned, see note. + * @param rec The key record, from which the key will be derived. + * @param f The context to use. + * @param p The pool to use. + * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend + * error occurred while generating the key. APR_ENOCIPHER if the type or mode + * is not supported by the particular backend. APR_EKEYTYPE if the key type is + * not known. APR_EPADDING if padding was requested but is not supported. + * APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_key(apr_crypto_key_t **key, + const apr_crypto_key_rec_t *rec, const apr_crypto_t *f, apr_pool_t *p); + +/** + * @brief Create a key from the given passphrase. By default, the PBKDF2 + * algorithm is used to generate the key from the passphrase. It is expected + * that the same pass phrase will generate the same key, regardless of the + * backend crypto platform used. The key is cleaned up when the context + * is cleaned, and may be reused with multiple encryption or decryption + * operations. + * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If + * *key is not NULL, *key must point at a previously created structure. + * @param key The key returned, see note. + * @param ivSize The size of the initialisation vector will be returned, based + * on whether an IV is relevant for this type of crypto. + * @param pass The passphrase to use. + * @param passLen The passphrase length in bytes + * @param salt The salt to use. + * @param saltLen The salt length in bytes + * @param type 3DES_192, AES_128, AES_192, AES_256. + * @param mode Electronic Code Book / Cipher Block Chaining. + * @param doPad Pad if necessary. + * @param iterations Number of iterations to use in algorithm + * @param f The context to use. + * @param p The pool to use. + * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend + * error occurred while generating the key. APR_ENOCIPHER if the type or mode + * is not supported by the particular backend. APR_EKEYTYPE if the key type is + * not known. APR_EPADDING if padding was requested but is not supported. + * APR_ENOTIMPL if not implemented. + * @deprecated Replaced by apr_crypto_key(). + */ +APU_DECLARE(apr_status_t) apr_crypto_passphrase(apr_crypto_key_t **key, + apr_size_t *ivSize, const char *pass, apr_size_t passLen, + const unsigned char * salt, apr_size_t saltLen, + const apr_crypto_block_key_type_e type, + const apr_crypto_block_key_mode_e mode, const int doPad, + const int iterations, const apr_crypto_t *f, apr_pool_t *p); + +/** + * @brief Initialise a context for encrypting arbitrary data using the given key. + * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If + * *ctx is not NULL, *ctx must point at a previously created structure. + * @param ctx The block context returned, see note. + * @param iv Optional initialisation vector. If the buffer pointed to is NULL, + * an IV will be created at random, in space allocated from the pool. + * If the buffer pointed to is not NULL, the IV in the buffer will be + * used. + * @param key The key structure to use. + * @param blockSize The block size of the cipher. + * @param p The pool to use. + * @return Returns APR_ENOIV if an initialisation vector is required but not specified. + * Returns APR_EINIT if the backend failed to initialise the context. Returns + * APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_encrypt_init( + apr_crypto_block_t **ctx, const unsigned char **iv, + const apr_crypto_key_t *key, apr_size_t *blockSize, apr_pool_t *p); + +/** + * @brief Encrypt data provided by in, write it to out. + * @note The number of bytes written will be written to outlen. If + * out is NULL, outlen will contain the maximum size of the + * buffer needed to hold the data, including any data + * generated by apr_crypto_block_encrypt_finish below. If *out points + * to NULL, a buffer sufficiently large will be created from + * the pool provided. If *out points to a not-NULL value, this + * value will be used as a buffer instead. + * @param out Address of a buffer to which data will be written, + * see note. + * @param outlen Length of the output will be written here. + * @param in Address of the buffer to read. + * @param inlen Length of the buffer to read. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if + * not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_encrypt(unsigned char **out, + apr_size_t *outlen, const unsigned char *in, apr_size_t inlen, + apr_crypto_block_t *ctx); + +/** + * @brief Encrypt final data block, write it to out. + * @note If necessary the final block will be written out after being + * padded. Typically the final block will be written to the + * same buffer used by apr_crypto_block_encrypt, offset by the + * number of bytes returned as actually written by the + * apr_crypto_block_encrypt() call. After this call, the context + * is cleaned and can be reused by apr_crypto_block_encrypt_init(). + * @param out Address of a buffer to which data will be written. This + * buffer must already exist, and is usually the same + * buffer used by apr_evp_crypt(). See note. + * @param outlen Length of the output will be written here. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. + * @return APR_EPADDING if padding was enabled and the block was incorrectly + * formatted. + * @return APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_encrypt_finish(unsigned char *out, + apr_size_t *outlen, apr_crypto_block_t *ctx); + +/** + * @brief Initialise a context for decrypting arbitrary data using the given key. + * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If + * *ctx is not NULL, *ctx must point at a previously created structure. + * @param ctx The block context returned, see note. + * @param blockSize The block size of the cipher. + * @param iv Optional initialisation vector. + * @param key The key structure to use. + * @param p The pool to use. + * @return Returns APR_ENOIV if an initialisation vector is required but not specified. + * Returns APR_EINIT if the backend failed to initialise the context. Returns + * APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_decrypt_init( + apr_crypto_block_t **ctx, apr_size_t *blockSize, + const unsigned char *iv, const apr_crypto_key_t *key, apr_pool_t *p); + +/** + * @brief Decrypt data provided by in, write it to out. + * @note The number of bytes written will be written to outlen. If + * out is NULL, outlen will contain the maximum size of the + * buffer needed to hold the data, including any data + * generated by apr_crypto_block_decrypt_finish below. If *out points + * to NULL, a buffer sufficiently large will be created from + * the pool provided. If *out points to a not-NULL value, this + * value will be used as a buffer instead. + * @param out Address of a buffer to which data will be written, + * see note. + * @param outlen Length of the output will be written here. + * @param in Address of the buffer to read. + * @param inlen Length of the buffer to read. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if + * not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_decrypt(unsigned char **out, + apr_size_t *outlen, const unsigned char *in, apr_size_t inlen, + apr_crypto_block_t *ctx); + +/** + * @brief Decrypt final data block, write it to out. + * @note If necessary the final block will be written out after being + * padded. Typically the final block will be written to the + * same buffer used by apr_crypto_block_decrypt, offset by the + * number of bytes returned as actually written by the + * apr_crypto_block_decrypt() call. After this call, the context + * is cleaned and can be reused by apr_crypto_block_decrypt_init(). + * @param out Address of a buffer to which data will be written. This + * buffer must already exist, and is usually the same + * buffer used by apr_evp_crypt(). See note. + * @param outlen Length of the output will be written here. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. + * @return APR_EPADDING if padding was enabled and the block was incorrectly + * formatted. + * @return APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_decrypt_finish(unsigned char *out, + apr_size_t *outlen, apr_crypto_block_t *ctx); + +/** + * @brief Clean encryption / decryption context. + * @note After cleanup, a context is free to be reused if necessary. + * @param ctx The block context to use. + * @return Returns APR_ENOTIMPL if not supported. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_cleanup(apr_crypto_block_t *ctx); + +/** + * @brief Clean encryption / decryption context. + * @note After cleanup, a context is free to be reused if necessary. + * @param f The context to use. + * @return Returns APR_ENOTIMPL if not supported. + */ +APU_DECLARE(apr_status_t) apr_crypto_cleanup(apr_crypto_t *f); + +/** + * @brief Shutdown the crypto library. + * @note After shutdown, it is expected that the init function can be called again. + * @param driver - driver to use + * @return Returns APR_ENOTIMPL if not supported. + */ +APU_DECLARE(apr_status_t) apr_crypto_shutdown( + const apr_crypto_driver_t *driver); + +#endif /* APU_HAVE_CRYPTO */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/c/dependencies/macos/apr/include/apr_cstr.h b/c/dependencies/macos/apr/include/apr_cstr.h new file mode 100644 index 00000000..3f1b1a09 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_cstr.h @@ -0,0 +1,292 @@ +/* ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * ==================================================================== + */ + +/** + * @file apr_cstr.h + * @brief C string goodies. + */ + +#ifndef APR_CSTR_H +#define APR_CSTR_H + +#include /* for apr_size_t */ +#include /* for apr_pool_t */ +#include /* for apr_array_header_t */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_cstr C (POSIX) locale string functions + * @ingroup apr_strings + * + * The apr_cstr_* functions provide traditional C char * string text handling, + * and notabilty they treat all text in the C (a.k.a. POSIX) locale using the + * minimal POSIX character set, represented in either ASCII or a corresponding + * EBCDIC subset. + * + * Character values outside of that set are treated as opaque bytes, and all + * multi-byte character sequences are handled as individual distinct octets. + * + * Multi-byte characters sequences whose octets fall in the ASCII range cause + * unexpected results, such as in the ISO-2022-JP code page where ASCII octets + * occur within both shift-state and multibyte sequences. + * + * In the case of the UTF-8 encoding, all multibyte characters all fall outside + * of the C/POSIX range of characters, so these functions are generally safe + * to use on UTF-8 strings. The programmer must be aware that each octet may + * not represent a distinct printable character in such encodings. + * + * The standard C99/POSIX string functions, rather than apr_cstr, should be + * used in all cases where the current locale and encoding of the text is + * significant. + * @{ + */ + + +/** Divide @a input into substrings, interpreting any char from @a sep + * as a token separator. + * + * Return an array of copies of those substrings (plain const char*), + * allocating both the array and the copies in @a pool. + * + * None of the elements added to the array contain any of the + * characters in @a sep_chars, and none of the new elements are empty + * (thus, it is possible that the returned array will have length + * zero). + * + * If @a chop_whitespace is TRUE, then remove leading and trailing + * whitespace from the returned strings. + * + * @since New in 1.6 + */ +APR_DECLARE(apr_array_header_t *) apr_cstr_split(const char *input, + const char *sep_chars, + int chop_whitespace, + apr_pool_t *pool); + +/** Like apr_cstr_split(), but append to existing @a array instead of + * creating a new one. Allocate the copied substrings in @a pool + * (i.e., caller decides whether or not to pass @a array->pool as @a pool). + * + * @since New in 1.6 + */ +APR_DECLARE(void) apr_cstr_split_append(apr_array_header_t *array, + const char *input, + const char *sep_chars, + int chop_whitespace, + apr_pool_t *pool); + + +/** Return @c TRUE iff @a str matches any of the elements of @a list, a list + * of zero or more glob patterns. + * + * @since New in 1.6 + */ +APR_DECLARE(int) apr_cstr_match_glob_list(const char *str, + const apr_array_header_t *list); + +/** Return @c TRUE iff @a str exactly matches any of the elements of @a list. + * + * @since New in 1.6 + */ +APR_DECLARE(int) apr_cstr_match_list(const char *str, + const apr_array_header_t *list); + +/** + * Get the next token from @a *str interpreting any char from @a sep as a + * token separator. Separators at the beginning of @a str will be skipped. + * Returns a pointer to the beginning of the first token in @a *str or NULL + * if no token is left. Modifies @a str such that the next call will return + * the next token. + * + * @note The content of @a *str may be modified by this function. + * + * @since New in 1.6. + */ +APR_DECLARE(char *) apr_cstr_tokenize(const char *sep, char **str); + +/** + * Return the number of line breaks in @a msg, allowing any kind of newline + * termination (CR, LF, CRLF, or LFCR), even inconsistent. + * + * @since New in 1.6. + */ +APR_DECLARE(int) apr_cstr_count_newlines(const char *msg); + +#if 0 /* XXX: stringbuf logic is not present in APR */ +/** + * Return a cstring which is the concatenation of @a strings (an array + * of char *) each followed by @a separator (that is, @a separator + * will also end the resulting string). Allocate the result in @a pool. + * If @a strings is empty, then return the empty string. + * + * @since New in 1.6. + */ +APR_DECLARE(char *) apr_cstr_join(const apr_array_header_t *strings, + const char *separator, + apr_pool_t *pool); +#endif + +/** + * Perform a case-insensitive comparison of two strings @a atr1 and @a atr2, + * treating upper and lower case values of the 26 standard C/POSIX alphabetic + * characters as equivalent. Extended latin characters outside of this set + * are treated as unique octets, irrespective of the current locale. + * + * Returns in integer greater than, equal to, or less than 0, + * according to whether @a str1 is considered greater than, equal to, + * or less than @a str2. + * + * @since New in 1.6. + */ +APR_DECLARE(int) apr_cstr_casecmp(const char *str1, const char *str2); + +/** + * Perform a case-insensitive comparison of two strings @a atr1 and @a atr2, + * treating upper and lower case values of the 26 standard C/POSIX alphabetic + * characters as equivalent. Extended latin characters outside of this set + * are treated as unique octets, irrespective of the current locale. + * + * Returns in integer greater than, equal to, or less than 0, + * according to whether @a str1 is considered greater than, equal to, + * or less than @a str2. + * + * @since New in 1.6. + */ +APR_DECLARE(int) apr_cstr_casecmpn(const char *str1, + const char *str2, + apr_size_t n); + +/** + * Parse the C string @a str into a 64 bit number, and return it in @a *n. + * Assume that the number is represented in base @a base. + * Raise an error if conversion fails (e.g. due to overflow), or if the + * converted number is smaller than @a minval or larger than @a maxval. + * + * Leading whitespace in @a str is skipped in a locale-dependent way. + * After that, the string may contain an optional '+' (positive, default) + * or '-' (negative) character, followed by an optional '0x' prefix if + * @a base is 0 or 16, followed by numeric digits appropriate for the base. + * If there are any more characters after the numeric digits, an error is + * returned. + * + * If @a base is zero, then a leading '0x' or '0X' prefix means hexadecimal, + * else a leading '0' means octal (implemented, though not documented, in + * apr_strtoi64() in APR 0.9.0 through 1.5.0), else use base ten. + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_strtoi64(apr_int64_t *n, const char *str, + apr_int64_t minval, + apr_int64_t maxval, + int base); + +/** + * Parse the C string @a str into a 64 bit number, and return it in @a *n. + * Assume that the number is represented in base 10. + * Raise an error if conversion fails (e.g. due to overflow). + * + * The behaviour otherwise is as described for apr_cstr_strtoi64(). + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_atoi64(apr_int64_t *n, const char *str); + +/** + * Parse the C string @a str into a 32 bit number, and return it in @a *n. + * Assume that the number is represented in base 10. + * Raise an error if conversion fails (e.g. due to overflow). + * + * The behaviour otherwise is as described for apr_cstr_strtoi64(). + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_atoi(int *n, const char *str); + +/** + * Parse the C string @a str into an unsigned 64 bit number, and return + * it in @a *n. Assume that the number is represented in base @a base. + * Raise an error if conversion fails (e.g. due to overflow), or if the + * converted number is smaller than @a minval or larger than @a maxval. + * + * Leading whitespace in @a str is skipped in a locale-dependent way. + * After that, the string may contain an optional '+' (positive, default) + * or '-' (negative) character, followed by an optional '0x' prefix if + * @a base is 0 or 16, followed by numeric digits appropriate for the base. + * If there are any more characters after the numeric digits, an error is + * returned. + * + * If @a base is zero, then a leading '0x' or '0X' prefix means hexadecimal, + * else a leading '0' means octal (as implemented, though not documented, in + * apr_strtoi64(), else use base ten. + * + * @warning The implementation returns APR_ERANGE if the parsed number + * is greater than APR_INT64_MAX, even if it is not greater than @a maxval. + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_strtoui64(apr_uint64_t *n, const char *str, + apr_uint64_t minval, + apr_uint64_t maxval, + int base); + +/** + * Parse the C string @a str into an unsigned 64 bit number, and return + * it in @a *n. Assume that the number is represented in base 10. + * Raise an error if conversion fails (e.g. due to overflow). + * + * The behaviour otherwise is as described for apr_cstr_strtoui64(), + * including the upper limit of APR_INT64_MAX. + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_atoui64(apr_uint64_t *n, const char *str); + +/** + * Parse the C string @a str into an unsigned 32 bit number, and return + * it in @a *n. Assume that the number is represented in base 10. + * Raise an error if conversion fails (e.g. due to overflow). + * + * The behaviour otherwise is as described for apr_cstr_strtoui64(), + * including the upper limit of APR_INT64_MAX. + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_atoui(unsigned int *n, const char *str); + +/** + * Skip the common prefix @a prefix from the C string @a str, and return + * a pointer to the next character after the prefix. + * Return @c NULL if @a str does not start with @a prefix. + * + * @since New in 1.6. + */ +APR_DECLARE(const char *) apr_cstr_skip_prefix(const char *str, + const char *prefix); + +/** @} */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* SVN_STRING_H */ diff --git a/c/dependencies/macos/apr/include/apr_date.h b/c/dependencies/macos/apr/include/apr_date.h new file mode 100644 index 00000000..b098b542 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_date.h @@ -0,0 +1,106 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_DATE_H +#define APR_DATE_H + +/** + * @file apr_date.h + * @brief APR-UTIL date routines + */ + +/** + * @defgroup APR_Util_Date Date routines + * @ingroup APR_Util + * @{ + */ + +/* + * apr_date.h: prototypes for date parsing utility routines + */ + +#include "apu.h" +#include "apr_time.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** A bad date. */ +#define APR_DATE_BAD ((apr_time_t)0) + +/** + * Compare a string to a mask + * @param data The string to compare + * @param mask Mask characters (arbitrary maximum is 256 characters): + *
+ *   '\@' - uppercase letter
+ *   '\$' - lowercase letter
+ *   '\&' - hex digit
+ *   '#' - digit
+ *   '~' - digit or space
+ *   '*' - swallow remaining characters
+ * 
+ * @remark The mask tests for an exact match for any other character + * @return 1 if the string matches, 0 otherwise + */ +APU_DECLARE(int) apr_date_checkmask(const char *data, const char *mask); + +/** + * Parses an HTTP date in one of three standard forms: + *
+ *     Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
+ *     Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
+ *     Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format
+ * 
+ * @param date The date in one of the three formats above + * @return the apr_time_t number of microseconds since 1 Jan 1970 GMT, or + * 0 if this would be out of range or if the date is invalid. + */ +APU_DECLARE(apr_time_t) apr_date_parse_http(const char *date); + +/** + * Parses a string resembling an RFC 822 date. This is meant to be + * leinent in its parsing of dates. Hence, this will parse a wider + * range of dates than apr_date_parse_http. + * + * The prominent mailer (or poster, if mailer is unknown) that has + * been seen in the wild is included for the unknown formats. + *
+ *     Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
+ *     Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
+ *     Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format
+ *     Sun, 6 Nov 1994 08:49:37 GMT   ; RFC 822, updated by RFC 1123
+ *     Sun, 06 Nov 94 08:49:37 GMT    ; RFC 822
+ *     Sun, 6 Nov 94 08:49:37 GMT     ; RFC 822
+ *     Sun, 06 Nov 94 08:49 GMT       ; Unknown [drtr\@ast.cam.ac.uk] 
+ *     Sun, 6 Nov 94 08:49 GMT        ; Unknown [drtr\@ast.cam.ac.uk]
+ *     Sun, 06 Nov 94 8:49:37 GMT     ; Unknown [Elm 70.85]
+ *     Sun, 6 Nov 94 8:49:37 GMT      ; Unknown [Elm 70.85] 
+ * 
+ * + * @param date The date in one of the formats above + * @return the apr_time_t number of microseconds since 1 Jan 1970 GMT, or + * 0 if this would be out of range or if the date is invalid. + */ +APU_DECLARE(apr_time_t) apr_date_parse_rfc(const char *date); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_DATE_H */ diff --git a/c/dependencies/macos/apr/include/apr_dbd.h b/c/dependencies/macos/apr/include/apr_dbd.h new file mode 100644 index 00000000..9912612b --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_dbd.h @@ -0,0 +1,549 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* Overview of what this is and does: + * http://www.apache.org/~niq/dbd.html + */ + +#ifndef APR_DBD_H +#define APR_DBD_H + +#include "apu.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_dbd.h + * @brief APR-UTIL DBD library + */ +/** + * @defgroup APR_Util_DBD DBD routines + * @ingroup APR_Util + * @{ + */ + +/** + * Mapping of C to SQL types, used for prepared statements. + * @remarks + * For apr_dbd_p[v]query/select functions, in and out parameters are always + * const char * (i.e. regular nul terminated strings). LOB types are passed + * with four (4) arguments: payload, length, table and column, all as const + * char *, where table and column are reserved for future use by Oracle. + * @remarks + * For apr_dbd_p[v]bquery/select functions, in and out parameters are + * described next to each enumeration constant and are generally native binary + * types or some APR data type. LOB types are passed with four (4) arguments: + * payload (char*), length (apr_size_t*), table (char*) and column (char*). + * Table and column are reserved for future use by Oracle. + */ +typedef enum { + APR_DBD_TYPE_NONE, + APR_DBD_TYPE_TINY, /**< \%hhd : in, out: char* */ + APR_DBD_TYPE_UTINY, /**< \%hhu : in, out: unsigned char* */ + APR_DBD_TYPE_SHORT, /**< \%hd : in, out: short* */ + APR_DBD_TYPE_USHORT, /**< \%hu : in, out: unsigned short* */ + APR_DBD_TYPE_INT, /**< \%d : in, out: int* */ + APR_DBD_TYPE_UINT, /**< \%u : in, out: unsigned int* */ + APR_DBD_TYPE_LONG, /**< \%ld : in, out: long* */ + APR_DBD_TYPE_ULONG, /**< \%lu : in, out: unsigned long* */ + APR_DBD_TYPE_LONGLONG, /**< \%lld : in, out: apr_int64_t* */ + APR_DBD_TYPE_ULONGLONG, /**< \%llu : in, out: apr_uint64_t* */ + APR_DBD_TYPE_FLOAT, /**< \%f : in, out: float* */ + APR_DBD_TYPE_DOUBLE, /**< \%lf : in, out: double* */ + APR_DBD_TYPE_STRING, /**< \%s : in: char*, out: char** */ + APR_DBD_TYPE_TEXT, /**< \%pDt : in: char*, out: char** */ + APR_DBD_TYPE_TIME, /**< \%pDi : in: char*, out: char** */ + APR_DBD_TYPE_DATE, /**< \%pDd : in: char*, out: char** */ + APR_DBD_TYPE_DATETIME, /**< \%pDa : in: char*, out: char** */ + APR_DBD_TYPE_TIMESTAMP, /**< \%pDs : in: char*, out: char** */ + APR_DBD_TYPE_ZTIMESTAMP, /**< \%pDz : in: char*, out: char** */ + APR_DBD_TYPE_BLOB, /**< \%pDb : in: char* apr_size_t* char* char*, out: apr_bucket_brigade* */ + APR_DBD_TYPE_CLOB, /**< \%pDc : in: char* apr_size_t* char* char*, out: apr_bucket_brigade* */ + APR_DBD_TYPE_NULL /**< \%pDn : in: void*, out: void** */ +} apr_dbd_type_e; + +/* These are opaque structs. Instantiation is up to each backend */ +typedef struct apr_dbd_driver_t apr_dbd_driver_t; +typedef struct apr_dbd_t apr_dbd_t; +typedef struct apr_dbd_transaction_t apr_dbd_transaction_t; +typedef struct apr_dbd_results_t apr_dbd_results_t; +typedef struct apr_dbd_row_t apr_dbd_row_t; +typedef struct apr_dbd_prepared_t apr_dbd_prepared_t; + +/** apr_dbd_init: perform once-only initialisation. Call once only. + * + * @param pool - pool to register any shutdown cleanups, etc + */ +APU_DECLARE(apr_status_t) apr_dbd_init(apr_pool_t *pool); + +/** apr_dbd_get_driver: get the driver struct for a name + * + * @param pool - (process) pool to register cleanup + * @param name - driver name + * @param driver - pointer to driver struct. + * @return APR_SUCCESS for success + * @return APR_ENOTIMPL for no driver (when DSO not enabled) + * @return APR_EDSOOPEN if DSO driver file can't be opened + * @return APR_ESYMNOTFOUND if the driver file doesn't contain a driver + */ +APU_DECLARE(apr_status_t) apr_dbd_get_driver(apr_pool_t *pool, const char *name, + const apr_dbd_driver_t **driver); + +/** apr_dbd_open_ex: open a connection to a backend + * + * @param driver - driver struct. + * @param pool - working pool + * @param params - arguments to driver (implementation-dependent) + * @param handle - pointer to handle to return + * @param error - descriptive error. + * @return APR_SUCCESS for success + * @return APR_EGENERAL if driver exists but connection failed + * @remarks PostgreSQL: the params is passed directly to the PQconnectdb() + * function (check PostgreSQL documentation for more details on the syntax). + * @remarks SQLite2: the params is split on a colon, with the first part used + * as the filename and second part converted to an integer and used as file + * mode. + * @remarks SQLite3: the params is passed directly to the sqlite3_open() + * function as a filename to be opened (check SQLite3 documentation for more + * details). + * @remarks Oracle: the params can have "user", "pass", "dbname" and "server" + * keys, each followed by an equal sign and a value. Such key/value pairs can + * be delimited by space, CR, LF, tab, semicolon, vertical bar or comma. + * @remarks MySQL: the params can have "host", "port", "user", "pass", + * "dbname", "sock", "flags" "fldsz", "group" and "reconnect" keys, each + * followed by an equal sign and a value. Such key/value pairs can be + * delimited by space, CR, LF, tab, semicolon, vertical bar or comma. For + * now, "flags" can only recognise CLIENT_FOUND_ROWS (check MySQL manual for + * details). The value associated with "fldsz" determines maximum amount of + * memory (in bytes) for each of the fields in the result set of prepared + * statements. By default, this value is 1 MB. The value associated with + * "group" determines which group from configuration file to use (see + * MYSQL_READ_DEFAULT_GROUP option of mysql_options() in MySQL manual). + * Reconnect is set to 1 by default (i.e. true). + */ +APU_DECLARE(apr_status_t) apr_dbd_open_ex(const apr_dbd_driver_t *driver, + apr_pool_t *pool, const char *params, + apr_dbd_t **handle, + const char **error); + +/** apr_dbd_open: open a connection to a backend + * + * @param driver - driver struct. + * @param pool - working pool + * @param params - arguments to driver (implementation-dependent) + * @param handle - pointer to handle to return + * @return APR_SUCCESS for success + * @return APR_EGENERAL if driver exists but connection failed + * @see apr_dbd_open_ex + */ +APU_DECLARE(apr_status_t) apr_dbd_open(const apr_dbd_driver_t *driver, + apr_pool_t *pool, const char *params, + apr_dbd_t **handle); + +/** apr_dbd_close: close a connection to a backend + * + * @param driver - driver struct. + * @param handle - handle to close + * @return APR_SUCCESS for success or error status + */ +APU_DECLARE(apr_status_t) apr_dbd_close(const apr_dbd_driver_t *driver, + apr_dbd_t *handle); + +/* apr-function-shaped versions of things */ + +/** apr_dbd_name: get the name of the driver + * + * @param driver - the driver + * @return - name + */ +APU_DECLARE(const char*) apr_dbd_name(const apr_dbd_driver_t *driver); + +/** apr_dbd_native_handle: get native database handle of the underlying db + * + * @param driver - the driver + * @param handle - apr_dbd handle + * @return - native handle + */ +APU_DECLARE(void*) apr_dbd_native_handle(const apr_dbd_driver_t *driver, + apr_dbd_t *handle); + +/** check_conn: check status of a database connection + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection to check + * @return APR_SUCCESS or error + */ +APU_DECLARE(int) apr_dbd_check_conn(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle); + +/** apr_dbd_set_dbname: select database name. May be a no-op if not supported. + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param name - the database to select + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_set_dbname(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, const char *name); + +/** apr_dbd_transaction_start: start a transaction. May be a no-op. + * + * @param driver - the driver + * @param pool - a pool to use for error messages (if any). + * @param handle - the db connection + * @param trans - ptr to a transaction. May be null on entry + * @return 0 for success or error code + * @remarks Note that transaction modes, set by calling + * apr_dbd_transaction_mode_set(), will affect all query/select calls within + * a transaction. By default, any error in query/select during a transaction + * will cause the transaction to inherit the error code and any further + * query/select calls will fail immediately. Put transaction in "ignore + * errors" mode to avoid that. Use "rollback" mode to do explicit rollback. + */ +APU_DECLARE(int) apr_dbd_transaction_start(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_t *handle, + apr_dbd_transaction_t **trans); + +/** apr_dbd_transaction_end: end a transaction + * (commit on success, rollback on error). + * May be a no-op. + * + * @param driver - the driver + * @param handle - the db connection + * @param trans - the transaction. + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_transaction_end(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_transaction_t *trans); + +#define APR_DBD_TRANSACTION_COMMIT 0x00 /**< commit the transaction */ +#define APR_DBD_TRANSACTION_ROLLBACK 0x01 /**< rollback the transaction */ +#define APR_DBD_TRANSACTION_IGNORE_ERRORS 0x02 /**< ignore transaction errors */ + +/** apr_dbd_transaction_mode_get: get the mode of transaction + * + * @param driver - the driver + * @param trans - the transaction + * @return mode of transaction + */ +APU_DECLARE(int) apr_dbd_transaction_mode_get(const apr_dbd_driver_t *driver, + apr_dbd_transaction_t *trans); + +/** apr_dbd_transaction_mode_set: set the mode of transaction + * + * @param driver - the driver + * @param trans - the transaction + * @param mode - new mode of the transaction + * @return the mode of transaction in force after the call + */ +APU_DECLARE(int) apr_dbd_transaction_mode_set(const apr_dbd_driver_t *driver, + apr_dbd_transaction_t *trans, + int mode); + +/** apr_dbd_query: execute an SQL query that doesn't return a result set + * + * @param driver - the driver + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the SQL statement to execute + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_query(const apr_dbd_driver_t *driver, apr_dbd_t *handle, + int *nrows, const char *statement); + +/** apr_dbd_select: execute an SQL query that returns a result set + * + * @param driver - the driver + * @param pool - pool to allocate the result set + * @param handle - the connection + * @param res - pointer to result set pointer. May point to NULL on entry + * @param statement - the SQL statement to execute + * @param random - 1 to support random access to results (seek any row); + * 0 to support only looping through results in order + * (async access - faster) + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_select(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, apr_dbd_results_t **res, + const char *statement, int random); + +/** apr_dbd_num_cols: get the number of columns in a results set + * + * @param driver - the driver + * @param res - result set. + * @return number of columns + */ +APU_DECLARE(int) apr_dbd_num_cols(const apr_dbd_driver_t *driver, + apr_dbd_results_t *res); + +/** apr_dbd_num_tuples: get the number of rows in a results set + * of a synchronous select + * + * @param driver - the driver + * @param res - result set. + * @return number of rows, or -1 if the results are asynchronous + */ +APU_DECLARE(int) apr_dbd_num_tuples(const apr_dbd_driver_t *driver, + apr_dbd_results_t *res); + +/** apr_dbd_get_row: get a row from a result set + * + * @param driver - the driver + * @param pool - pool to allocate the row + * @param res - result set pointer + * @param row - pointer to row pointer. May point to NULL on entry + * @param rownum - row number (counting from 1), or -1 for "next row". + * Ignored if random access is not supported. + * @return 0 for success, -1 for rownum out of range or data finished + */ +APU_DECLARE(int) apr_dbd_get_row(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_results_t *res, apr_dbd_row_t **row, + int rownum); + +/** apr_dbd_get_entry: get an entry from a row + * + * @param driver - the driver + * @param row - row pointer + * @param col - entry number + * @return value from the row, or NULL if col is out of bounds. + */ +APU_DECLARE(const char*) apr_dbd_get_entry(const apr_dbd_driver_t *driver, + apr_dbd_row_t *row, int col); + +/** apr_dbd_get_name: get an entry name from a result set + * + * @param driver - the driver + * @param res - result set pointer + * @param col - entry number + * @return name of the entry, or NULL if col is out of bounds. + */ +APU_DECLARE(const char*) apr_dbd_get_name(const apr_dbd_driver_t *driver, + apr_dbd_results_t *res, int col); + + +/** apr_dbd_error: get current error message (if any) + * + * @param driver - the driver + * @param handle - the connection + * @param errnum - error code from operation that returned an error + * @return the database current error message, or message for errnum + * (implementation-dependent whether errnum is ignored) + */ +APU_DECLARE(const char*) apr_dbd_error(const apr_dbd_driver_t *driver, + apr_dbd_t *handle, int errnum); + +/** apr_dbd_escape: escape a string so it is safe for use in query/select + * + * @param driver - the driver + * @param pool - pool to alloc the result from + * @param string - the string to escape + * @param handle - the connection + * @return the escaped, safe string + */ +APU_DECLARE(const char*) apr_dbd_escape(const apr_dbd_driver_t *driver, + apr_pool_t *pool, const char *string, + apr_dbd_t *handle); + +/** apr_dbd_prepare: prepare a statement + * + * @param driver - the driver + * @param pool - pool to alloc the result from + * @param handle - the connection + * @param query - the SQL query + * @param label - A label for the prepared statement. + * use NULL for temporary prepared statements + * (eg within a Request in httpd) + * @param statement - statement to prepare. May point to null on entry. + * @return 0 for success or error code + * @remarks To specify parameters of the prepared query, use \%s, \%d etc. + * (see below for full list) in place of database specific parameter syntax + * (e.g. for PostgreSQL, this would be $1, $2, for SQLite3 this would be ? + * etc.). For instance: "SELECT name FROM customers WHERE name=%s" would be + * a query that this function understands. + * @remarks Here is the full list of format specifiers that this function + * understands and what they map to in SQL: \%hhd (TINY INT), \%hhu (UNSIGNED + * TINY INT), \%hd (SHORT), \%hu (UNSIGNED SHORT), \%d (INT), \%u (UNSIGNED + * INT), \%ld (LONG), \%lu (UNSIGNED LONG), \%lld (LONG LONG), \%llu + * (UNSIGNED LONG LONG), \%f (FLOAT, REAL), \%lf (DOUBLE PRECISION), \%s + * (VARCHAR), \%pDt (TEXT), \%pDi (TIME), \%pDd (DATE), \%pDa (DATETIME), + * \%pDs (TIMESTAMP), \%pDz (TIMESTAMP WITH TIME ZONE), \%pDb (BLOB), \%pDc + * (CLOB) and \%pDn (NULL). Not all databases have support for all these + * types, so the underlying driver will attempt the "best match" where + * possible. A \% followed by any letter not in the above list will be + * interpreted as VARCHAR (i.e. \%s). + */ +APU_DECLARE(int) apr_dbd_prepare(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, const char *query, + const char *label, + apr_dbd_prepared_t **statement); + + +/** apr_dbd_pquery: query using a prepared statement + args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param nargs - ignored (for backward compatibility only) + * @param args - args to prepared statement + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_pquery(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, int nargs, + const char **args); + +/** apr_dbd_pselect: select using a prepared statement + args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param nargs - ignored (for backward compatibility only) + * @param args - args to prepared statement + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_pselect(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, int random, + int nargs, const char **args); + +/** apr_dbd_pvquery: query using a prepared statement + args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param ... - varargs list + * @return 0 for success or error code + */ +APU_DECLARE_NONSTD(int) apr_dbd_pvquery(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, ...); + +/** apr_dbd_pvselect: select using a prepared statement + args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param ... - varargs list + * @return 0 for success or error code + */ +APU_DECLARE_NONSTD(int) apr_dbd_pvselect(const apr_dbd_driver_t *driver, + apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, + int random, ...); + +/** apr_dbd_pbquery: query using a prepared statement + binary args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_pbquery(const apr_dbd_driver_t *driver, + apr_pool_t *pool, apr_dbd_t *handle, + int *nrows, apr_dbd_prepared_t *statement, + const void **args); + +/** apr_dbd_pbselect: select using a prepared statement + binary args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_pbselect(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_t *handle, apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, int random, + const void **args); + +/** apr_dbd_pvbquery: query using a prepared statement + binary args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param ... - varargs list of binary args + * @return 0 for success or error code + */ +APU_DECLARE_NONSTD(int) apr_dbd_pvbquery(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, ...); + +/** apr_dbd_pvbselect: select using a prepared statement + binary args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param ... - varargs list of binary args + * @return 0 for success or error code + */ +APU_DECLARE_NONSTD(int) apr_dbd_pvbselect(const apr_dbd_driver_t *driver, + apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, + int random, ...); + +/** apr_dbd_datum_get: get a binary entry from a row + * + * @param driver - the driver + * @param row - row pointer + * @param col - entry number + * @param type - type of data to get + * @param data - pointer to data, allocated by the caller + * @return APR_SUCCESS on success, APR_ENOENT if data is NULL or APR_EGENERAL + */ +APU_DECLARE(apr_status_t) apr_dbd_datum_get(const apr_dbd_driver_t *driver, + apr_dbd_row_t *row, int col, + apr_dbd_type_e type, void *data); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/c/dependencies/macos/apr/include/apr_dbm.h b/c/dependencies/macos/apr/include/apr_dbm.h new file mode 100644 index 00000000..ad1b4f39 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_dbm.h @@ -0,0 +1,227 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_DBM_H +#define APR_DBM_H + +#include "apu.h" +#include "apr.h" +#include "apr_errno.h" +#include "apr_pools.h" +#include "apr_file_info.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_dbm.h + * @brief APR-UTIL DBM library + */ +/** + * @defgroup APR_Util_DBM DBM routines + * @ingroup APR_Util + * @{ + */ +/** + * Structure for referencing a dbm + */ +typedef struct apr_dbm_t apr_dbm_t; + +/** + * Structure for referencing the datum record within a dbm + */ +typedef struct +{ + /** pointer to the 'data' to retrieve/store in the DBM */ + char *dptr; + /** size of the 'data' to retrieve/store in the DBM */ + apr_size_t dsize; +} apr_datum_t; + +/* modes to open the DB */ +#define APR_DBM_READONLY 1 /**< open for read-only access */ +#define APR_DBM_READWRITE 2 /**< open for read-write access */ +#define APR_DBM_RWCREATE 3 /**< open for r/w, create if needed */ +#define APR_DBM_RWTRUNC 4 /**< open for r/w, truncating an existing + DB if present */ +/** + * Open a dbm file by file name and type of DBM + * @param dbm The newly opened database + * @param type The type of the DBM (not all may be available at run time) + *
+ *  db   for Berkeley DB files
+ *  gdbm for GDBM files
+ *  ndbm for NDBM files
+ *  sdbm for SDBM files (always available)
+ *  default for the default DBM type
+ *  
+ * @param name The dbm file name to open + * @param mode The flag value + *
+ *           APR_DBM_READONLY   open for read-only access
+ *           APR_DBM_READWRITE  open for read-write access
+ *           APR_DBM_RWCREATE   open for r/w, create if needed
+ *           APR_DBM_RWTRUNC    open for r/w, truncate if already there
+ * 
+ * @param perm Permissions to apply to if created + * @param cntxt The pool to use when creating the dbm + * @remark The dbm name may not be a true file name, as many dbm packages + * append suffixes for seperate data and index files. + * @bug In apr-util 0.9 and 1.x, the type arg was case insensitive. This + * was highly inefficient, and as of 2.x the dbm name must be provided in + * the correct case (lower case for all bundled providers) + */ + +APU_DECLARE(apr_status_t) apr_dbm_open_ex(apr_dbm_t **dbm, const char* type, + const char *name, + apr_int32_t mode, apr_fileperms_t perm, + apr_pool_t *cntxt); + + +/** + * Open a dbm file by file name + * @param dbm The newly opened database + * @param name The dbm file name to open + * @param mode The flag value + *
+ *           APR_DBM_READONLY   open for read-only access
+ *           APR_DBM_READWRITE  open for read-write access
+ *           APR_DBM_RWCREATE   open for r/w, create if needed
+ *           APR_DBM_RWTRUNC    open for r/w, truncate if already there
+ * 
+ * @param perm Permissions to apply to if created + * @param cntxt The pool to use when creating the dbm + * @remark The dbm name may not be a true file name, as many dbm packages + * append suffixes for seperate data and index files. + */ +APU_DECLARE(apr_status_t) apr_dbm_open(apr_dbm_t **dbm, const char *name, + apr_int32_t mode, apr_fileperms_t perm, + apr_pool_t *cntxt); + +/** + * Close a dbm file previously opened by apr_dbm_open + * @param dbm The database to close + */ +APU_DECLARE(void) apr_dbm_close(apr_dbm_t *dbm); + +/** + * Fetch a dbm record value by key + * @param dbm The database + * @param key The key datum to find this record + * @param pvalue The value datum retrieved for this record + */ +APU_DECLARE(apr_status_t) apr_dbm_fetch(apr_dbm_t *dbm, apr_datum_t key, + apr_datum_t *pvalue); +/** + * Store a dbm record value by key + * @param dbm The database + * @param key The key datum to store this record by + * @param value The value datum to store in this record + */ +APU_DECLARE(apr_status_t) apr_dbm_store(apr_dbm_t *dbm, apr_datum_t key, + apr_datum_t value); + +/** + * Delete a dbm record value by key + * @param dbm The database + * @param key The key datum of the record to delete + * @remark It is not an error to delete a non-existent record. + */ +APU_DECLARE(apr_status_t) apr_dbm_delete(apr_dbm_t *dbm, apr_datum_t key); + +/** + * Search for a key within the dbm + * @param dbm The database + * @param key The datum describing a key to test + */ +APU_DECLARE(int) apr_dbm_exists(apr_dbm_t *dbm, apr_datum_t key); + +/** + * Retrieve the first record key from a dbm + * @param dbm The database + * @param pkey The key datum of the first record + */ +APU_DECLARE(apr_status_t) apr_dbm_firstkey(apr_dbm_t *dbm, apr_datum_t *pkey); + +/** + * Retrieve the next record key from a dbm + * @param dbm The database + * @param pkey The key datum of the next record + */ +APU_DECLARE(apr_status_t) apr_dbm_nextkey(apr_dbm_t *dbm, apr_datum_t *pkey); + +/** + * Proactively toss any memory associated with the apr_datum_t. + * @param dbm The database + * @param data The datum to free. + */ +APU_DECLARE(void) apr_dbm_freedatum(apr_dbm_t *dbm, apr_datum_t data); + +/** + * Report more information when an apr_dbm function fails. + * @param dbm The database + * @param errcode A DBM-specific value for the error (for logging). If this + * isn't needed, it may be NULL. + * @param errbuf Location to store the error text + * @param errbufsize The size of the provided buffer + * @return The errbuf parameter, for convenience. + */ +APU_DECLARE(char *) apr_dbm_geterror(apr_dbm_t *dbm, int *errcode, + char *errbuf, apr_size_t errbufsize); +/** + * If the specified file/path were passed to apr_dbm_open(), return the + * actual file/path names which would be (created and) used. At most, two + * files may be used; used2 may be NULL if only one file is used. + * @param pool The pool for allocating used1 and used2. + * @param type The type of DBM you require info on @see apr_dbm_open_ex + * @param pathname The path name to generate used-names from. + * @param used1 The first pathname used by the apr_dbm implementation. + * @param used2 The second pathname used by apr_dbm. If only one file is + * used by the specific implementation, this will be set to NULL. + * @return An error if the specified type is invalid. + * @remark The dbm file(s) don't need to exist. This function only manipulates + * the pathnames. + */ +APU_DECLARE(apr_status_t) apr_dbm_get_usednames_ex(apr_pool_t *pool, + const char *type, + const char *pathname, + const char **used1, + const char **used2); + +/** + * If the specified file/path were passed to apr_dbm_open(), return the + * actual file/path names which would be (created and) used. At most, two + * files may be used; used2 may be NULL if only one file is used. + * @param pool The pool for allocating used1 and used2. + * @param pathname The path name to generate used-names from. + * @param used1 The first pathname used by the apr_dbm implementation. + * @param used2 The second pathname used by apr_dbm. If only one file is + * used by the specific implementation, this will be set to NULL. + * @remark The dbm file(s) don't need to exist. This function only manipulates + * the pathnames. + */ +APU_DECLARE(void) apr_dbm_get_usednames(apr_pool_t *pool, + const char *pathname, + const char **used1, + const char **used2); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_DBM_H */ diff --git a/c/dependencies/macos/apr/include/apr_dso.h b/c/dependencies/macos/apr/include/apr_dso.h new file mode 100644 index 00000000..ac701cfd --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_dso.h @@ -0,0 +1,94 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_DSO_DOT_H +#define APR_DSO_DOT_H + +/** + * @file apr_dso.h + * @brief APR Dynamic Object Handling Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_dso Dynamic Object Handling + * @ingroup APR + * @{ + */ + +#if APR_HAS_DSO || defined(DOXYGEN) + +/** + * Structure for referencing dynamic objects + */ +typedef struct apr_dso_handle_t apr_dso_handle_t; + +/** + * Structure for referencing symbols from dynamic objects + */ +typedef void * apr_dso_handle_sym_t; + +/** + * Load a DSO library. + * @param res_handle Location to store new handle for the DSO. + * @param path Path to the DSO library + * @param ctx Pool to use. + * @bug We aught to provide an alternative to RTLD_GLOBAL, which + * is the only supported method of loading DSOs today. + */ +APR_DECLARE(apr_status_t) apr_dso_load(apr_dso_handle_t **res_handle, + const char *path, apr_pool_t *ctx); + +/** + * Close a DSO library. + * @param handle handle to close. + */ +APR_DECLARE(apr_status_t) apr_dso_unload(apr_dso_handle_t *handle); + +/** + * Load a symbol from a DSO handle. + * @param ressym Location to store the loaded symbol + * @param handle handle to load the symbol from. + * @param symname Name of the symbol to load. + */ +APR_DECLARE(apr_status_t) apr_dso_sym(apr_dso_handle_sym_t *ressym, + apr_dso_handle_t *handle, + const char *symname); + +/** + * Report more information when a DSO function fails. + * @param dso The dso handle that has been opened + * @param buf Location to store the dso error + * @param bufsize The size of the provided buffer + */ +APR_DECLARE(const char *) apr_dso_error(apr_dso_handle_t *dso, char *buf, apr_size_t bufsize); + +#endif /* APR_HAS_DSO */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/c/dependencies/macos/apr/include/apr_encode.h b/c/dependencies/macos/apr/include/apr_encode.h new file mode 100644 index 00000000..8bae61f7 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_encode.h @@ -0,0 +1,650 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_encode.h + * @brief APR-UTIL Encoding + */ +#ifndef APR_ENCODE_H +#define APR_ENCODE_H + +#include "apr.h" +#include "apr_general.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Encode Base64/Base64Url/Base32/Base32Hex/Base16 Encoding + * @ingroup APR_Util + * @{ + */ + +/** + * RFC4648 and RFC7515 compliant BASE64, BASE64URL, BASE32, BASE32HEX + * and BASE16 encode/decode functions. + * + * The following encodings are supported: + * + * - Base 64 Encoding + * + * o Use flag APR_ENCODE_NONE + * o https://tools.ietf.org/html/rfc4648#section-4 + * + * - Base 64 Encoding with URL and Filename Safe Alphabet + * + * o Use flag APR_ENCODE_URL + * o https://tools.ietf.org/html/rfc4648#section-5 + * + * - Base 64 URL Encoding without Padding + * + * o Use flag APR_ENCODE_BASE64URL + * o https://tools.ietf.org/html/rfc7515#appendix-C + * + * - Base 32 Encoding + * + * o Use flag APR_ENCODE_NONE + * o https://tools.ietf.org/html/rfc4648#section-6 + * + * - Base 32 Encoding with Extended Hex Alphabet + * + * o Use flag APR_ENCODE_BASE32HEX + * o https://tools.ietf.org/html/rfc4648#section-7 + * + * - Base 16 Encoding + * + * o Use flags APR_ENCODE_NONE/APR_ENCODE_COLON + * o https://tools.ietf.org/html/rfc4648#section-8 + * + * If a non valid character of any kind including whitespace is passed to any + * of the decoder functions, APR_BADCH will be returned. In this case decoding + * will still take place, but the results can not be trusted. + * + * If APR_ENCODE_RELAXED is passed to the decoder functions, decoding will be + * attempted up until the first non valid character. If this results in an + * invalid state in the decoder, such as but not limited to an odd number of + * base16 characters, APR_BADCH will still be returned. + * + * If APR_ENCODE_RELAXED is not passed to a decoder function, the decoding will + * be done in constant time regardless of whether the result returns APR_SUCCESS + * or APR_BADCH. + * + * If the dest parameter is NULL, the maximum theoretical buffer size is + * returned in the len field, including space for a terminating zero character + * if the destination is a string. This value can be used to allocate buffers + * of a suitable safe size. + * + * If the dest parameter is provided, the encoding or decoding will take place, + * and the actual number of characters written is returned in the len field, + * ignoring any terminating zero. + * + * Plain strings are not assumed '\0' terminated unless APR_ENCODE_STRING is + * provided. + * + */ + +/** + * When passing a string to one of the encode functions, this value can be + * passed to indicate a string-valued key, and have the length computed + * automatically. + */ +#define APR_ENCODE_STRING (-1) + +/** + * Generate RFC4648 base16/base32/base64. + */ +#define APR_ENCODE_NONE 0 + +/** + * If relaxed, decode up until the first non base16/base32/base64 character. + */ +#define APR_ENCODE_RELAXED 1 + +/** + * Omit the padding character (=) while encoding. + */ +#define APR_ENCODE_NOPADDING 2 + +/** + * Generate RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet + */ +#define APR_ENCODE_URL 4 + +/** + * Generate RFC7515 BASE64URL + */ +#define APR_ENCODE_BASE64URL (APR_ENCODE_NOPADDING | APR_ENCODE_URL) + +/** + * Generate base32hex encoding instead of base32 encoding + */ +#define APR_ENCODE_BASE32HEX 8 + +/** + * Generate base16 with colons between each token. + */ +#define APR_ENCODE_COLON 16 + +/** + * Generate base16 with lower case characters. + */ +#define APR_ENCODE_LOWER 32 + +/** + * Convert text data to base64. + * @param dest The destination string, can be NULL to output in \c len the + * needed buffer length for encoding. + * @param src The original string, can be NULL if \c dest is NULL and \c slen + * is positive or nul. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * the actual length should be computed based on NUL termination. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 64 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_URL, + * use RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet. + * If APR_ENCODE_BASE64URL, use RFC7515 base64url Encoding. + * @param len If not NULL, outputs the length of the buffer needed for encoding + * (including the trailing NUL) if \c dest is NULL, or the actual length of + * the encoding (excluding the trailing NUL) if \c dest is not NULL. + * @return APR_SUCCESS, or APR_EINVAL if \c slen is not APR_ENCODE_STRING and + * negative, or APR_NOTFOUND if \c dest is not NULL and \c src is NULL, or + * APR_ENOSPC if \c dest is NULL and the source length (based on \c slen or + * APR_ENCODE_STRING) is too big to encode. + */ +APR_DECLARE(apr_status_t) apr_encode_base64(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert binary data to base64. + * @param dest The destination string, can be NULL to output in \c len the + * needed buffer length for encoding. + * @param src The original buffer, can be NULL if \c dest is NULL. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 64 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_URL, + * use RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet. + * If APR_ENCODE_BASE64URL, use RFC7515 base64url Encoding. + * @param len If not NULL, outputs the length of the buffer needed for encoding + * (including the trailing NUL) if \c dest is NULL, or the actual length of + * the encoding (excluding the trailing NUL) if \c dest is not NULL. + * @return APR_SUCCESS, or APR_EINVAL if \c slen is negative, or APR_NOTFOUND + * if \c dest is not NULL and \c src is NULL, or APR_ENOSPC if \c dest is NULL + * and the source length (based on \c slen or APR_ENCODE_STRING) is too big to + * encode. + */ +APR_DECLARE(apr_status_t) apr_encode_base64_binary(char *dest, const unsigned char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert text data to base64, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * the actual length should be computed based on NUL termination. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 64 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_URL, + * use RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet. + * If APR_ENCODE_BASE64URL, use RFC7515 base64url Encoding. + * @param len If not NULL, outputs the length of the encoding (excluding the + * trailing NUL). + * @return A NUL terminated string allocated from the pool on success, + * or NULL if src is NULL or allocation failed or the encoding is not + * possible (see apr_encode_base64 errors). + */ +APR_DECLARE(const char *)apr_pencode_base64(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len)__attribute__((nonnull(1))); + +/** + * Convert binary data to base64, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 64 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_URL, + * use RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet. + * If APR_ENCODE_BASE64URL, use RFC7515 base64url Encoding. + * @param len If not NULL, outputs the length of the encoding (excluding the + * trailing NUL). + * @return A NUL terminated string allocated from the pool on success, + * or NULL if src is NULL or allocation failed or the encoding is not + * possible (see apr_encode_base64_binary errors). + */ +APR_DECLARE(const char *)apr_pencode_base64_binary(apr_pool_t * p, const unsigned char *src, + apr_ssize_t slen, int flags, apr_size_t * len)__attribute__((nonnull(1))); + +/** + * Convert base64 or base64url with or without padding to text data. + * @param dest The destination string, can be NULL to output in \c len the + * needed buffer length for decoding. + * @param src The base64 string, can be NULL if \c dest is NULL and \c slen + * is positive or nul. + * @param slen The length of the base64 string, or APR_ENCODE_STRING if + * the actual length should be computed based on NUL termination. + * @param flags If APR_ENCODE_NONE, attempt to decode the full base64 string, + * and return NULL if any bad character is detected. If APR_ENCODE_RELAXED, + * decode until the first non base64/base64url character. + * @param len If not NULL, outputs the length of the buffer needed for decoding + * (including the trailing NUL) if \c dest is NULL, or the actual length of + * the decoding (excluding the trailing NUL) if \c dest is not NULL. + * @return APR_SUCCESS, or APR_EINVAL if \c slen is not APR_ENCODE_STRING and + * negative, or APR_NOTFOUND if \c dest is not NULL and \c src is NULL, or + * APR_ENOSPC if \c dest is NULL and the source length (based on \c slen or + * APR_ENCODE_STRING) is too big to decode, or APR_EINCOMPLETE if the source + * length (based on \c slen or APR_ENCODE_STRING) is invalid for a base64 + * encoding, or APR_BADCH if a non base64 character is present and + * APR_ENCODE_RELAXED is not specified. + */ +APR_DECLARE(apr_status_t) apr_decode_base64(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base64 or base64url with or without padding to binary data. + * @param dest The destination string, can be NULL to output in \c len the + * needed buffer length for decoding. + * @param src The base64 string, can be NULL if \c dest is NULL and \c slen + * is positive or nul. + * @param slen The length of the base64 string, or APR_ENCODE_STRING if + * the actual length should be computed based on NUL termination. + * @param flags If APR_ENCODE_NONE, attempt to decode the full base64 string, + * and return NULL if any bad character is detected. If APR_ENCODE_RELAXED, + * decode until the first non base64/base64url character. + * @param len If not NULL, outputs the length of the buffer needed for decoding + * (including the trailing NUL) if \c dest is NULL, or the actual length of + * the decoding (excluding the trailing NUL) if \c dest is not NULL. + * @return APR_SUCCESS, or APR_EINVAL if \c slen is not APR_ENCODE_STRING and + * negative, or APR_NOTFOUND if \c dest is not NULL and \c src is NULL, or + * APR_ENOSPC if \c dest is NULL and the source length (based on \c slen or + * APR_ENCODE_STRING) is too big to decode, or APR_EINCOMPLETE if the source + * length (based on \c slen or APR_ENCODE_STRING) is invalid for a base64 + * encoding, or APR_BADCH if a non base64 character is present and + * APR_ENCODE_RELAXED is not specified. + */ +APR_DECLARE(apr_status_t) apr_decode_base64_binary(unsigned char *dest, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base64 or base64url with or without padding to text data, and + * return the results from a pool. + * @param p Pool to allocate from. + * @param src The base64 string to decode. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * the actual length should be computed based on NUL termination. + * @param flags If APR_ENCODE_NONE, attempt to decode the full original buffer, + * and return NULL if any bad character is detected. If APR_ENCODE_RELAXED, + * decode until the first non base64/base64url character. + * @param len If not NULL, outputs the length of the decoding (excluding the + * trailing NUL). + * @return A NUL terminated string allocated from the pool on success, + * or NULL if src is NULL or allocation failed or the decoding is not + * possible (see apr_decode_base64_binary errors). + */ +APR_DECLARE(const char *)apr_pdecode_base64(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert base64 or base64url with or without padding to binary data, and + * return the results from a pool. + * @param p Pool to allocate from. + * @param src The base64 string to decode. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * the actual length should be computed based on NUL termination. + * @param flags If APR_ENCODE_NONE, attempt to decode the full original buffer, + * and return NULL if any bad character is detected. If APR_ENCODE_RELAXED, + * decode until the first non base64/base64url character. + * @param len If not NULL, outputs the length of the decoding (excluding the + * trailing NUL). + * @return A NUL terminated string allocated from the pool on success, + * or NULL if src is NULL or allocation failed or the decoding is not + * possible (see apr_decode_base64_binary errors). + */ +APR_DECLARE(const unsigned char *)apr_pdecode_base64_binary(apr_pool_t * p, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert text data to base32. + * @param dest The destination string, can be NULL to output in \c len the + * needed buffer length for encoding. + * @param src The original string, can be NULL if \c dest is NULL and \c slen + * is positive or nul. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * the actual length should be computed based on NUL termination. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 32 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_BASE32HEX, + * use RFC4648 base32hex Encoding. + * @param len If not NULL, outputs the length of the buffer needed for encoding + * (including the trailing NUL) if \c dest is NULL, or the actual length of + * the encoding (excluding the trailing NUL) if \c dest is not NULL. + * @return APR_SUCCESS, or APR_EINVAL if \c slen is not APR_ENCODE_STRING and + * negative, or APR_NOTFOUND if \c dest is not NULL and \c src is NULL, or + * APR_ENOSPC if \c dest is NULL and the source length (based on \c slen or + * APR_ENCODE_STRING) is too big to encode. + */ +APR_DECLARE(apr_status_t) apr_encode_base32(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert binary data to base32. + * @param dest The destination string, can be NULL to output in \c len the + * needed buffer length for encoding. + * @param src The original buffer, can be NULL if \c dest is NULL. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 32 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_BASE32HEX, + * use RFC4648 base32hex Encoding. + * @param len If not NULL, outputs the length of the buffer needed for encoding + * (including the trailing NUL) if \c dest is NULL, or the actual length of + * the encoding (excluding the trailing NUL) if \c dest is not NULL. + * @return APR_SUCCESS, or APR_EINVAL if \c slen is negative, or APR_NOTFOUND + * if \c dest is not NULL and \c src is NULL, or APR_ENOSPC if \c dest is NULL + * and the source length (based on \c slen or APR_ENCODE_STRING) is too big to + * encode. + */ +APR_DECLARE(apr_status_t) apr_encode_base32_binary(char *dest, const unsigned char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert text data to base32, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * the actual length should be computed based on NUL termination. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 32 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_BASE32HEX, + * use RFC4648 base32hex Encoding. + * @param len If not NULL, outputs the length of the encoding (excluding the + * trailing NUL). + * @return A NUL terminated string allocated from the pool on success, + * or NULL if src is NULL or allocation failed or the encoding is not + * possible (see apr_encode_base32 errors). + */ +APR_DECLARE(const char *)apr_pencode_base32(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert binary data to base32, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 32 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_BASE32HEX, + * use RFC4648 base32hex Encoding. + * @param len If not NULL, outputs the length of the encoding (excluding the + * trailing NUL). + * @return A NUL terminated string allocated from the pool on success, + * or NULL if src is NULL or allocation failed or the encoding is not + * possible (see apr_encode_base32_binary errors). + */ +APR_DECLARE(const char *)apr_pencode_base32_binary(apr_pool_t * p, const unsigned char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert base32 or base32hex with or without padding to text data. + * @param dest The destination string, can be NULL to output in \c len the + * needed buffer length for decoding. + * @param src The base32 string, can be NULL if \c dest is NULL and \c slen + * is positive or nul. + * @param slen The length of the base32 string, or APR_ENCODE_STRING if + * the actual length should be computed based on NUL termination. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 32 Encoding. If + * APR_ENCODE_BASE32HEX, use RFC4648 base32hex Encoding. + * @param len If not NULL, outputs the length of the buffer needed for decoding + * (including the trailing NUL) if \c dest is NULL, or the actual length of + * the decoding (excluding the trailing NUL) if \c dest is not NULL. + * @return APR_SUCCESS, or APR_EINVAL if \c slen is not APR_ENCODE_STRING and + * negative, or APR_NOTFOUND if \c dest is not NULL and \c src is NULL, or + * APR_ENOSPC if \c dest is NULL and the source length (based on \c slen or + * APR_ENCODE_STRING) is too big to decode, or APR_EINCOMPLETE if the source + * length (based on \c slen or APR_ENCODE_STRING) is invalid for a base32 + * encoding, or APR_BADCH if a non base32 character is present and + * APR_ENCODE_RELAXED is not specified. + */ +APR_DECLARE(apr_status_t) apr_decode_base32(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base32 or base32hex with or without padding to binary data. + * @param dest The destination string, can be NULL to output in \c len the + * needed buffer length for decoding. + * @param src The base32 string, can be NULL if \c dest is NULL and \c slen + * is positive or nul. + * @param slen The length of the base32 string, or APR_ENCODE_STRING if + * the actual length should be computed based on NUL termination. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 32 Encoding. If + * APR_ENCODE_BASE32HEX, use RFC4648 base32hex Encoding. + * @param len If not NULL, outputs the length of the buffer needed for decoding + * (including the trailing NUL) if \c dest is NULL, or the actual length of + * the decoding (excluding the trailing NUL) if \c dest is not NULL. + * @return APR_SUCCESS, or APR_EINVAL if \c slen is not APR_ENCODE_STRING and + * negative, or APR_NOTFOUND if \c dest is not NULL and \c src is NULL, or + * APR_ENOSPC if \c dest is NULL and the source length (based on \c slen or + * APR_ENCODE_STRING) is too big to decode, or APR_EINCOMPLETE if the source + * length (based on \c slen or APR_ENCODE_STRING) is invalid for a base32 + * encoding, or APR_BADCH if a non base32 character is present and + * APR_ENCODE_RELAXED is not specified. + */ +APR_DECLARE(apr_status_t) apr_decode_base32_binary(unsigned char *dest, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base32 or base32hex with or without padding to text data, and + * return the results from a pool. + * @param p Pool to allocate from. + * @param src The base32 string to decode. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * the actual length should be computed based on NUL termination. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 32 Encoding. If + * APR_ENCODE_BASE32HEX, use RFC4648 base32hex Encoding. + * @param len If not NULL, outputs the length of the encoding (excluding the + * trailing NUL). + * @return A NUL terminated string allocated from the pool on success, + * or NULL if src is NULL or allocation failed or the decoding is not + * possible (see apr_decode_base32 errors). + */ +APR_DECLARE(const char *)apr_pdecode_base32(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert base32 or base32hex with or without padding to binary data, and + * return the results from a pool. + * @param p Pool to allocate from. + * @param src The base32 string to decode. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * the actual length should be computed based on NUL termination. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 32 Encoding. If + * APR_ENCODE_BASE32HEX, use RFC4648 base32hex Encoding. + * @param len If not NULL, outputs the length of the encoding (excluding the + * trailing NUL). + * @return A NUL terminated string allocated from the pool on success, + * or NULL if src is NULL or allocation failed or the decoding is not + * possible (see apr_decode_base32_binary errors). + */ +APR_DECLARE(const unsigned char *)apr_pdecode_base32_binary(apr_pool_t * p, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert text data to base16 (hex). + * @param dest The destination string, can be NULL to output in \c len the + * needed buffer length for encoding. + * @param src The original string, can be NULL if \c dest is NULL and \c slen + * is positive or nul. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * the actual length should be computed based on NUL termination. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, separate each token with a colon. + * @param len If not NULL, outputs the length of the buffer needed for encoding + * (including the trailing NUL) if \c dest is NULL, or the actual length of + * the encoding (excluding the trailing NUL) if \c dest is not NULL. + * @return APR_SUCCESS, or APR_EINVAL if \c slen is not APR_ENCODE_STRING and + * negative, or APR_NOTFOUND if \c dest is not NULL and \c src is NULL, or + * APR_ENOSPC if \c dest is NULL and the source length (based on \c slen or + * APR_ENCODE_STRING) is too big to encode. + */ +APR_DECLARE(apr_status_t) apr_encode_base16(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert binary data to base16 (hex). + * @param dest The destination string, can be NULL to output in \c len the + * needed buffer length for encoding. + * @param src The original buffer, can be NULL if \c dest is NULL. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, separate each token with a colon. + * @param len If not NULL, outputs the length of the buffer needed for encoding + * (including the trailing NUL) if \c dest is NULL, or the actual length of + * the encoding (excluding the trailing NUL) if \c dest is not NULL. + * @return APR_SUCCESS, or APR_EINVAL if \c slen is negative, or APR_NOTFOUND + * if \c dest is not NULL and \c src is NULL, or APR_ENOSPC if \c dest is NULL + * and the source length (based on \c slen or APR_ENCODE_STRING) is too big to + * encode. + */ +APR_DECLARE(apr_status_t) apr_encode_base16_binary(char *dest, + const unsigned char *src, apr_ssize_t slen, int flags, + apr_size_t * len); + +/** + * Convert text data to base16 (hex), and return the results from a + * pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * the actual length should be computed based on NUL termination. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, separate each token with a colon. + * @param len If not NULL, outputs the length of the encoding (excluding the + * trailing NUL). + * @return A NUL terminated string allocated from the pool on success, + * or NULL if src is NULL or allocation failed or the encoding is not + * possible (see apr_encode_base16 errors). + */ +APR_DECLARE(const char *)apr_pencode_base16(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert binary data to base16 (hex), and return the results from a + * pool. + * @param p Pool to allocate from. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, separate each token with a colon. + * @param len If not NULL, outputs the length of the encoding (excluding the + * trailing NUL). + * @return A NUL terminated string allocated from the pool on success, + * or NULL if src is NULL or allocation failed or the encoding is not + * possible (see apr_encode_base16_binary errors). + */ +APR_DECLARE(const char *)apr_pencode_base16_binary(apr_pool_t * p, + const unsigned char *src, apr_ssize_t slen, + int flags, apr_size_t * len)__attribute__((nonnull(1))); + +/** + * Convert base16 (hex) to text data. + * @param dest The destination string, can be NULL to output in \c len the + * needed buffer length for decoding. + * @param src The base16 string, can be NULL if \c dest is NULL and \c slen + * is positive or nul. + * @param slen The length of the base16 string, or APR_ENCODE_STRING if + * the actual length should be computed based on NUL termination. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, allow tokens to be separated with a colon. + * @param len If not NULL, outputs the length of the buffer needed for decoding + * (including the trailing NUL) if \c dest is NULL, or the actual length of + * the decoding (excluding the trailing NUL) if \c dest is not NULL. + * @return APR_SUCCESS, or APR_EINVAL if \c slen is not APR_ENCODE_STRING and + * negative, or APR_NOTFOUND if \c dest is not NULL and \c src is NULL, or + * APR_ENOSPC if \c dest is NULL and the source length (based on \c slen or + * APR_ENCODE_STRING) is too big to decode, or APR_EINCOMPLETE if the source + * length (based on \c slen or APR_ENCODE_STRING) is invalid for a base16 + * encoding, or APR_BADCH if a non base16 character is present and + * APR_ENCODE_RELAXED is not specified. + */ +APR_DECLARE(apr_status_t) apr_decode_base16(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base16 (hex) to binary data. + * @param dest The destination string, can be NULL to output in \c len the + * needed buffer length for decoding. + * @param src The base16 string, can be NULL if \c dest is NULL and \c slen + * is positive or nul. + * @param slen The length of the base16 string, or APR_ENCODE_STRING if + * the actual length should be computed based on NUL termination. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, allow tokens to be separated with a colon. + * @param len If not NULL, outputs the length of the buffer needed for decoding + * (including the trailing NUL) if \c dest is NULL, or the actual length of + * the decoding (excluding the trailing NUL) if \c dest is not NULL. + * @return APR_SUCCESS, or APR_EINVAL if \c slen is not APR_ENCODE_STRING and + * negative, or APR_NOTFOUND if \c dest is not NULL and \c src is NULL, or + * APR_ENOSPC if \c dest is NULL and the source length (based on \c slen or + * APR_ENCODE_STRING) is too big to decode, or APR_EINCOMPLETE if the source + * length (based on \c slen or APR_ENCODE_STRING) is invalid for a base16 + * encoding, or APR_BADCH if a non base16 character is present and + * APR_ENCODE_RELAXED is not specified. + */ +APR_DECLARE(apr_status_t) apr_decode_base16_binary(unsigned char *dest, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base16 (hex) and return the results from a pool. + * @param p Pool to allocate from. + * @param src The base16 string to decode. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * the actual length should be computed based on NUL termination. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, allow tokens to be separated with a colon. + * @param len If not NULL, outputs the length of the encoding (excluding the + * trailing NUL). + * @return A NUL terminated string allocated from the pool on success, + * or NULL if src is NULL or allocation failed or the decoding is not + * possible (see apr_decode_base16 errors). + */ +APR_DECLARE(const char *)apr_pdecode_base16(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert base16 (hex) to binary data, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The base16 string to decode. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * the actual length should be computed based on NUL termination. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, allow tokens to be separated with a colon. + * @param len If not NULL, outputs the length of the encoding (excluding the + * trailing NUL). + * @return A NUL terminated string allocated from the pool on success, + * or NULL if src is NULL or allocation failed or the decoding is not + * possible (see apr_decode_base16_binary errors). + */ +APR_DECLARE(const unsigned char *)apr_pdecode_base16_binary(apr_pool_t * p, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ENCODE_H */ diff --git a/c/dependencies/macos/apr/include/apr_env.h b/c/dependencies/macos/apr/include/apr_env.h new file mode 100644 index 00000000..85ab6704 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_env.h @@ -0,0 +1,67 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ENV_H +#define APR_ENV_H +/** + * @file apr_env.h + * @brief APR Environment functions + */ +#include "apr_errno.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_env Functions for manipulating the environment + * @ingroup APR + * @{ + */ + +/** + * Get the value of an environment variable + * @param value the returned value, allocated from @a pool + * @param envvar the name of the environment variable + * @param pool where to allocate @a value and any temporary storage from + */ +APR_DECLARE(apr_status_t) apr_env_get(char **value, const char *envvar, + apr_pool_t *pool); + +/** + * Set the value of an environment variable + * @param envvar the name of the environment variable + * @param value the value to set + * @param pool where to allocate temporary storage from + */ +APR_DECLARE(apr_status_t) apr_env_set(const char *envvar, const char *value, + apr_pool_t *pool); + +/** + * Delete a variable from the environment + * @param envvar the name of the environment variable + * @param pool where to allocate temporary storage from + */ +APR_DECLARE(apr_status_t) apr_env_delete(const char *envvar, apr_pool_t *pool); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_ENV_H */ diff --git a/c/dependencies/macos/apr/include/apr_errno.h b/c/dependencies/macos/apr/include/apr_errno.h new file mode 100644 index 00000000..8fa6628b --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_errno.h @@ -0,0 +1,1342 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ERRNO_H +#define APR_ERRNO_H + +/** + * @file apr_errno.h + * @brief APR Error Codes + */ + +#include "apr.h" + +#if APR_HAVE_ERRNO_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_errno Error Codes + * @ingroup APR + * @{ + */ + +/** + * Type for specifying an error or status code. + */ +typedef int apr_status_t; + +/** + * Return a human readable string describing the specified error. + * @param statcode The error code to get a string for. + * @param buf A buffer to hold the error string. + * @param bufsize Size of the buffer to hold the string. + */ +APR_DECLARE(char *) apr_strerror(apr_status_t statcode, char *buf, + apr_size_t bufsize); + +#if defined(DOXYGEN) +/** + * @def APR_FROM_OS_ERROR(os_err_type syserr) + * Fold a platform specific error into an apr_status_t code. + * @return apr_status_t + * @param e The platform os error code. + * @warning macro implementation; the syserr argument may be evaluated + * multiple times. + */ +#define APR_FROM_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e + APR_OS_START_SYSERR) + +/** + * @def APR_TO_OS_ERROR(apr_status_t statcode) + * @return os_err_type + * Fold an apr_status_t code back to the native platform defined error. + * @param e The apr_status_t folded platform os error code. + * @warning macro implementation; the statcode argument may be evaluated + * multiple times. If the statcode was not created by apr_get_os_error + * or APR_FROM_OS_ERROR, the results are undefined. + */ +#define APR_TO_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e - APR_OS_START_SYSERR) + +/** @def apr_get_os_error() + * @return apr_status_t the last platform error, folded into apr_status_t, on most platforms + * @remark This retrieves errno, or calls a GetLastError() style function, and + * folds it with APR_FROM_OS_ERROR. Some platforms (such as OS2) have no + * such mechanism, so this call may be unsupported. Do NOT use this + * call for socket errors from socket, send, recv etc! + */ + +/** @def apr_set_os_error(e) + * Reset the last platform error, unfolded from an apr_status_t, on some platforms + * @param e The OS error folded in a prior call to APR_FROM_OS_ERROR() + * @warning This is a macro implementation; the statcode argument may be evaluated + * multiple times. If the statcode was not created by apr_get_os_error + * or APR_FROM_OS_ERROR, the results are undefined. This macro sets + * errno, or calls a SetLastError() style function, unfolding statcode + * with APR_TO_OS_ERROR. Some platforms (such as OS2) have no such + * mechanism, so this call may be unsupported. + */ + +/** @def apr_get_netos_error() + * Return the last socket error, folded into apr_status_t, on all platforms + * @remark This retrieves errno or calls a GetLastSocketError() style function, + * and folds it with APR_FROM_OS_ERROR. + */ + +/** @def apr_set_netos_error(e) + * Reset the last socket error, unfolded from an apr_status_t + * @param e The socket error folded in a prior call to APR_FROM_OS_ERROR() + * @warning This is a macro implementation; the statcode argument may be evaluated + * multiple times. If the statcode was not created by apr_get_os_error + * or APR_FROM_OS_ERROR, the results are undefined. This macro sets + * errno, or calls a WSASetLastError() style function, unfolding + * socketcode with APR_TO_OS_ERROR. + */ + +#endif /* defined(DOXYGEN) */ + +/** + * APR_OS_START_ERROR is where the APR specific error values start. + */ +#define APR_OS_START_ERROR 20000 +/** + * APR_OS_ERRSPACE_SIZE is the maximum number of errors you can fit + * into one of the error/status ranges below -- except for + * APR_OS_START_USERERR, which see. + */ +#define APR_OS_ERRSPACE_SIZE 50000 +/** + * APR_UTIL_ERRSPACE_SIZE is the size of the space that is reserved for + * use within apr-util. This space is reserved above that used by APR + * internally. + * @note This number MUST be smaller than APR_OS_ERRSPACE_SIZE by a + * large enough amount that APR has sufficient room for its + * codes. + */ +#define APR_UTIL_ERRSPACE_SIZE 20000 +/** + * APR_OS_START_STATUS is where the APR specific status codes start. + */ +#define APR_OS_START_STATUS (APR_OS_START_ERROR + APR_OS_ERRSPACE_SIZE) +/** + * APR_UTIL_START_STATUS is where APR-Util starts defining its + * status codes. + */ +#define APR_UTIL_START_STATUS (APR_OS_START_STATUS + \ + (APR_OS_ERRSPACE_SIZE - APR_UTIL_ERRSPACE_SIZE)) +/** + * APR_OS_START_USERERR are reserved for applications that use APR that + * layer their own error codes along with APR's. Note that the + * error immediately following this one is set ten times farther + * away than usual, so that users of apr have a lot of room in + * which to declare custom error codes. + * + * In general applications should try and create unique error codes. To try + * and assist in finding suitable ranges of numbers to use, the following + * ranges are known to be used by the listed applications. If your + * application defines error codes please advise the range of numbers it + * uses to dev@apr.apache.org for inclusion in this list. + * + * Ranges shown are in relation to APR_OS_START_USERERR + * + * Subversion - Defined ranges, of less than 100, at intervals of 5000 + * starting at an offset of 5000, e.g. + * +5000 to 5100, +10000 to 10100 + * + * Apache HTTPD - +2000 to 2999 + */ +#define APR_OS_START_USERERR (APR_OS_START_STATUS + APR_OS_ERRSPACE_SIZE) +/** + * APR_OS_START_USEERR is obsolete, defined for compatibility only. + * Use APR_OS_START_USERERR instead. + */ +#define APR_OS_START_USEERR APR_OS_START_USERERR +/** + * APR_OS_START_CANONERR is where APR versions of errno values are defined + * on systems which don't have the corresponding errno. + */ +#define APR_OS_START_CANONERR (APR_OS_START_USERERR \ + + (APR_OS_ERRSPACE_SIZE * 10)) +/** + * APR_OS_START_EAIERR folds EAI_ error codes from getaddrinfo() into + * apr_status_t values. + */ +#define APR_OS_START_EAIERR (APR_OS_START_CANONERR + APR_OS_ERRSPACE_SIZE) +/** + * APR_OS_START_SYSERR folds platform-specific system error values into + * apr_status_t values. + */ +#define APR_OS_START_SYSERR (APR_OS_START_EAIERR + APR_OS_ERRSPACE_SIZE) + +/** + * @defgroup APR_ERROR_map APR Error Space + *
+ * The following attempts to show the relation of the various constants
+ * used for mapping APR Status codes.
+ *
+ *       0
+ *
+ *  20,000     APR_OS_START_ERROR
+ *
+ *         + APR_OS_ERRSPACE_SIZE (50,000)
+ *
+ *  70,000      APR_OS_START_STATUS
+ *
+ *         + APR_OS_ERRSPACE_SIZE - APR_UTIL_ERRSPACE_SIZE (30,000)
+ *
+ * 100,000      APR_UTIL_START_STATUS
+ *
+ *         + APR_UTIL_ERRSPACE_SIZE (20,000)
+ *
+ * 120,000      APR_OS_START_USERERR
+ *
+ *         + 10 x APR_OS_ERRSPACE_SIZE (50,000 * 10)
+ *
+ * 620,000      APR_OS_START_CANONERR
+ *
+ *         + APR_OS_ERRSPACE_SIZE (50,000)
+ *
+ * 670,000      APR_OS_START_EAIERR
+ *
+ *         + APR_OS_ERRSPACE_SIZE (50,000)
+ *
+ * 720,000      APR_OS_START_SYSERR
+ *
+ * 
+ */ + +/** no error. */ +#define APR_SUCCESS 0 + +/** + * @defgroup APR_Error APR Error Values + *
+ * APR ERROR VALUES
+ * APR_ENOSTAT      APR was unable to perform a stat on the file
+ * APR_ENOPOOL      APR was not provided a pool with which to allocate memory
+ * APR_EBADDATE     APR was given an invalid date
+ * APR_EINVALSOCK   APR was given an invalid socket
+ * APR_ENOPROC      APR was not given a process structure
+ * APR_ENOTIME      APR was not given a time structure
+ * APR_ENODIR       APR was not given a directory structure
+ * APR_ENOLOCK      APR was not given a lock structure
+ * APR_ENOPOLL      APR was not given a poll structure
+ * APR_ENOSOCKET    APR was not given a socket
+ * APR_ENOTHREAD    APR was not given a thread structure
+ * APR_ENOTHDKEY    APR was not given a thread key structure
+ * APR_ENOSHMAVAIL  There is no more shared memory available
+ * APR_EDSOOPEN     APR was unable to open the dso object.  For more
+ *                  information call apr_dso_error().
+ * APR_EGENERAL     General failure (specific information not available)
+ * APR_EBADIP       The specified IP address is invalid
+ * APR_EBADMASK     The specified netmask is invalid
+ * APR_ESYMNOTFOUND Could not find the requested symbol
+ * APR_ENOTENOUGHENTROPY Not enough entropy to continue
+ * 
+ * + *
+ * APR STATUS VALUES
+ * APR_INCHILD        Program is currently executing in the child
+ * APR_INPARENT       Program is currently executing in the parent
+ * APR_DETACH         The thread is detached
+ * APR_NOTDETACH      The thread is not detached
+ * APR_CHILD_DONE     The child has finished executing
+ * APR_CHILD_NOTDONE  The child has not finished executing
+ * APR_TIMEUP         The operation did not finish before the timeout
+ * APR_INCOMPLETE     The operation was incomplete although some processing
+ *                    was performed and the results are partially valid
+ * APR_BADCH          Getopt found an option not in the option string
+ * APR_BADARG         Getopt found an option that is missing an argument
+ *                    and an argument was specified in the option string
+ * APR_EOF            APR has encountered the end of the file
+ * APR_NOTFOUND       APR was unable to find the socket in the poll structure
+ * APR_ANONYMOUS      APR is using anonymous shared memory
+ * APR_FILEBASED      APR is using a file name as the key to the shared memory
+ * APR_KEYBASED       APR is using a shared key as the key to the shared memory
+ * APR_EINIT          Ininitalizer value.  If no option has been found, but
+ *                    the status variable requires a value, this should be used
+ * APR_ENOTIMPL       The APR function has not been implemented on this
+ *                    platform, either because nobody has gotten to it yet,
+ *                    or the function is impossible on this platform.
+ * APR_EMISMATCH      Two passwords do not match.
+ * APR_EABSOLUTE      The given path was absolute.
+ * APR_ERELATIVE      The given path was relative.
+ * APR_EINCOMPLETE    The given path was neither relative nor absolute.
+ * APR_EABOVEROOT     The given path was above the root path.
+ * APR_EBUSY          The given lock was busy.
+ * APR_EPROC_UNKNOWN  The given process wasn't recognized by APR
+ * 
+ * @{ + */ +/** @see APR_STATUS_IS_ENOSTAT */ +#define APR_ENOSTAT (APR_OS_START_ERROR + 1) +/** @see APR_STATUS_IS_ENOPOOL */ +#define APR_ENOPOOL (APR_OS_START_ERROR + 2) +/* empty slot: +3 */ +/** @see APR_STATUS_IS_EBADDATE */ +#define APR_EBADDATE (APR_OS_START_ERROR + 4) +/** @see APR_STATUS_IS_EINVALSOCK */ +#define APR_EINVALSOCK (APR_OS_START_ERROR + 5) +/** @see APR_STATUS_IS_ENOPROC */ +#define APR_ENOPROC (APR_OS_START_ERROR + 6) +/** @see APR_STATUS_IS_ENOTIME */ +#define APR_ENOTIME (APR_OS_START_ERROR + 7) +/** @see APR_STATUS_IS_ENODIR */ +#define APR_ENODIR (APR_OS_START_ERROR + 8) +/** @see APR_STATUS_IS_ENOLOCK */ +#define APR_ENOLOCK (APR_OS_START_ERROR + 9) +/** @see APR_STATUS_IS_ENOPOLL */ +#define APR_ENOPOLL (APR_OS_START_ERROR + 10) +/** @see APR_STATUS_IS_ENOSOCKET */ +#define APR_ENOSOCKET (APR_OS_START_ERROR + 11) +/** @see APR_STATUS_IS_ENOTHREAD */ +#define APR_ENOTHREAD (APR_OS_START_ERROR + 12) +/** @see APR_STATUS_IS_ENOTHDKEY */ +#define APR_ENOTHDKEY (APR_OS_START_ERROR + 13) +/** @see APR_STATUS_IS_EGENERAL */ +#define APR_EGENERAL (APR_OS_START_ERROR + 14) +/** @see APR_STATUS_IS_ENOSHMAVAIL */ +#define APR_ENOSHMAVAIL (APR_OS_START_ERROR + 15) +/** @see APR_STATUS_IS_EBADIP */ +#define APR_EBADIP (APR_OS_START_ERROR + 16) +/** @see APR_STATUS_IS_EBADMASK */ +#define APR_EBADMASK (APR_OS_START_ERROR + 17) +/* empty slot: +18 */ +/** @see APR_STATUS_IS_EDSOPEN */ +#define APR_EDSOOPEN (APR_OS_START_ERROR + 19) +/** @see APR_STATUS_IS_EABSOLUTE */ +#define APR_EABSOLUTE (APR_OS_START_ERROR + 20) +/** @see APR_STATUS_IS_ERELATIVE */ +#define APR_ERELATIVE (APR_OS_START_ERROR + 21) +/** @see APR_STATUS_IS_EINCOMPLETE */ +#define APR_EINCOMPLETE (APR_OS_START_ERROR + 22) +/** @see APR_STATUS_IS_EABOVEROOT */ +#define APR_EABOVEROOT (APR_OS_START_ERROR + 23) +/** @see APR_STATUS_IS_EBADPATH */ +#define APR_EBADPATH (APR_OS_START_ERROR + 24) +/** @see APR_STATUS_IS_EPATHWILD */ +#define APR_EPATHWILD (APR_OS_START_ERROR + 25) +/** @see APR_STATUS_IS_ESYMNOTFOUND */ +#define APR_ESYMNOTFOUND (APR_OS_START_ERROR + 26) +/** @see APR_STATUS_IS_EPROC_UNKNOWN */ +#define APR_EPROC_UNKNOWN (APR_OS_START_ERROR + 27) +/** @see APR_STATUS_IS_ENOTENOUGHENTROPY */ +#define APR_ENOTENOUGHENTROPY (APR_OS_START_ERROR + 28) +/** @} */ + +/** + * @defgroup APR_STATUS_IS Status Value Tests + * @warning For any particular error condition, more than one of these tests + * may match. This is because platform-specific error codes may not + * always match the semantics of the POSIX codes these tests (and the + * corresponding APR error codes) are named after. A notable example + * are the APR_STATUS_IS_ENOENT and APR_STATUS_IS_ENOTDIR tests on + * Win32 platforms. The programmer should always be aware of this and + * adjust the order of the tests accordingly. + * @{ + */ +/** + * APR was unable to perform a stat on the file + * @warning always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_ENOSTAT(s) ((s) == APR_ENOSTAT) +/** + * APR was not provided a pool with which to allocate memory + * @warning always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_ENOPOOL(s) ((s) == APR_ENOPOOL) +/** APR was given an invalid date */ +#define APR_STATUS_IS_EBADDATE(s) ((s) == APR_EBADDATE) +/** APR was given an invalid socket */ +#define APR_STATUS_IS_EINVALSOCK(s) ((s) == APR_EINVALSOCK) +/** APR was not given a process structure */ +#define APR_STATUS_IS_ENOPROC(s) ((s) == APR_ENOPROC) +/** APR was not given a time structure */ +#define APR_STATUS_IS_ENOTIME(s) ((s) == APR_ENOTIME) +/** APR was not given a directory structure */ +#define APR_STATUS_IS_ENODIR(s) ((s) == APR_ENODIR) +/** APR was not given a lock structure */ +#define APR_STATUS_IS_ENOLOCK(s) ((s) == APR_ENOLOCK) +/** APR was not given a poll structure */ +#define APR_STATUS_IS_ENOPOLL(s) ((s) == APR_ENOPOLL) +/** APR was not given a socket */ +#define APR_STATUS_IS_ENOSOCKET(s) ((s) == APR_ENOSOCKET) +/** APR was not given a thread structure */ +#define APR_STATUS_IS_ENOTHREAD(s) ((s) == APR_ENOTHREAD) +/** APR was not given a thread key structure */ +#define APR_STATUS_IS_ENOTHDKEY(s) ((s) == APR_ENOTHDKEY) +/** Generic Error which can not be put into another spot */ +#define APR_STATUS_IS_EGENERAL(s) ((s) == APR_EGENERAL) +/** There is no more shared memory available */ +#define APR_STATUS_IS_ENOSHMAVAIL(s) ((s) == APR_ENOSHMAVAIL) +/** The specified IP address is invalid */ +#define APR_STATUS_IS_EBADIP(s) ((s) == APR_EBADIP) +/** The specified netmask is invalid */ +#define APR_STATUS_IS_EBADMASK(s) ((s) == APR_EBADMASK) +/* empty slot: +18 */ +/** + * APR was unable to open the dso object. + * For more information call apr_dso_error(). + */ +#if defined(WIN32) +#define APR_STATUS_IS_EDSOOPEN(s) ((s) == APR_EDSOOPEN \ + || APR_TO_OS_ERROR(s) == ERROR_MOD_NOT_FOUND) +#else +#define APR_STATUS_IS_EDSOOPEN(s) ((s) == APR_EDSOOPEN) +#endif +/** The given path was absolute. */ +#define APR_STATUS_IS_EABSOLUTE(s) ((s) == APR_EABSOLUTE) +/** The given path was relative. */ +#define APR_STATUS_IS_ERELATIVE(s) ((s) == APR_ERELATIVE) +/** The given path was neither relative nor absolute. */ +#define APR_STATUS_IS_EINCOMPLETE(s) ((s) == APR_EINCOMPLETE) +/** The given path was above the root path. */ +#define APR_STATUS_IS_EABOVEROOT(s) ((s) == APR_EABOVEROOT) +/** The given path was bad. */ +#define APR_STATUS_IS_EBADPATH(s) ((s) == APR_EBADPATH) +/** The given path contained wildcards. */ +#define APR_STATUS_IS_EPATHWILD(s) ((s) == APR_EPATHWILD) +/** Could not find the requested symbol. + * For more information call apr_dso_error(). + */ +#if defined(WIN32) +#define APR_STATUS_IS_ESYMNOTFOUND(s) ((s) == APR_ESYMNOTFOUND \ + || APR_TO_OS_ERROR(s) == ERROR_PROC_NOT_FOUND) +#else +#define APR_STATUS_IS_ESYMNOTFOUND(s) ((s) == APR_ESYMNOTFOUND) +#endif +/** The given process was not recognized by APR. */ +#define APR_STATUS_IS_EPROC_UNKNOWN(s) ((s) == APR_EPROC_UNKNOWN) +/** APR could not gather enough entropy to continue. */ +#define APR_STATUS_IS_ENOTENOUGHENTROPY(s) ((s) == APR_ENOTENOUGHENTROPY) + +/** @} */ + +/** + * @addtogroup APR_Error + * @{ + */ +/** @see APR_STATUS_IS_INCHILD */ +#define APR_INCHILD (APR_OS_START_STATUS + 1) +/** @see APR_STATUS_IS_INPARENT */ +#define APR_INPARENT (APR_OS_START_STATUS + 2) +/** @see APR_STATUS_IS_DETACH */ +#define APR_DETACH (APR_OS_START_STATUS + 3) +/** @see APR_STATUS_IS_NOTDETACH */ +#define APR_NOTDETACH (APR_OS_START_STATUS + 4) +/** @see APR_STATUS_IS_CHILD_DONE */ +#define APR_CHILD_DONE (APR_OS_START_STATUS + 5) +/** @see APR_STATUS_IS_CHILD_NOTDONE */ +#define APR_CHILD_NOTDONE (APR_OS_START_STATUS + 6) +/** @see APR_STATUS_IS_TIMEUP */ +#define APR_TIMEUP (APR_OS_START_STATUS + 7) +/** @see APR_STATUS_IS_INCOMPLETE */ +#define APR_INCOMPLETE (APR_OS_START_STATUS + 8) +/* empty slot: +9 */ +/* empty slot: +10 */ +/* empty slot: +11 */ +/** @see APR_STATUS_IS_BADCH */ +#define APR_BADCH (APR_OS_START_STATUS + 12) +/** @see APR_STATUS_IS_BADARG */ +#define APR_BADARG (APR_OS_START_STATUS + 13) +/** @see APR_STATUS_IS_EOF */ +#define APR_EOF (APR_OS_START_STATUS + 14) +/** @see APR_STATUS_IS_NOTFOUND */ +#define APR_NOTFOUND (APR_OS_START_STATUS + 15) +/* empty slot: +16 */ +/* empty slot: +17 */ +/* empty slot: +18 */ +/** @see APR_STATUS_IS_ANONYMOUS */ +#define APR_ANONYMOUS (APR_OS_START_STATUS + 19) +/** @see APR_STATUS_IS_FILEBASED */ +#define APR_FILEBASED (APR_OS_START_STATUS + 20) +/** @see APR_STATUS_IS_KEYBASED */ +#define APR_KEYBASED (APR_OS_START_STATUS + 21) +/** @see APR_STATUS_IS_EINIT */ +#define APR_EINIT (APR_OS_START_STATUS + 22) +/** @see APR_STATUS_IS_ENOTIMPL */ +#define APR_ENOTIMPL (APR_OS_START_STATUS + 23) +/** @see APR_STATUS_IS_EMISMATCH */ +#define APR_EMISMATCH (APR_OS_START_STATUS + 24) +/** @see APR_STATUS_IS_EBUSY */ +#define APR_EBUSY (APR_OS_START_STATUS + 25) +/** @} */ + +/** + * @addtogroup APR_STATUS_IS + * @{ + */ +/** + * Program is currently executing in the child + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code */ +#define APR_STATUS_IS_INCHILD(s) ((s) == APR_INCHILD) +/** + * Program is currently executing in the parent + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_INPARENT(s) ((s) == APR_INPARENT) +/** + * The thread is detached + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_DETACH(s) ((s) == APR_DETACH) +/** + * The thread is not detached + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_NOTDETACH(s) ((s) == APR_NOTDETACH) +/** + * The child has finished executing + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_CHILD_DONE(s) ((s) == APR_CHILD_DONE) +/** + * The child has not finished executing + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_CHILD_NOTDONE(s) ((s) == APR_CHILD_NOTDONE) +/** + * The operation did not finish before the timeout + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_TIMEUP(s) ((s) == APR_TIMEUP) +/** + * The operation was incomplete although some processing was performed + * and the results are partially valid. + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_INCOMPLETE(s) ((s) == APR_INCOMPLETE) +/* empty slot: +9 */ +/* empty slot: +10 */ +/* empty slot: +11 */ +/** + * Getopt found an option not in the option string + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_BADCH(s) ((s) == APR_BADCH) +/** + * Getopt found an option not in the option string and an argument was + * specified in the option string + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_BADARG(s) ((s) == APR_BADARG) +/** + * APR has encountered the end of the file + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_EOF(s) ((s) == APR_EOF) +/** + * APR was unable to find the socket in the poll structure + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_NOTFOUND(s) ((s) == APR_NOTFOUND) +/* empty slot: +16 */ +/* empty slot: +17 */ +/* empty slot: +18 */ +/** + * APR is using anonymous shared memory + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_ANONYMOUS(s) ((s) == APR_ANONYMOUS) +/** + * APR is using a file name as the key to the shared memory + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_FILEBASED(s) ((s) == APR_FILEBASED) +/** + * APR is using a shared key as the key to the shared memory + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_KEYBASED(s) ((s) == APR_KEYBASED) +/** + * Ininitalizer value. If no option has been found, but + * the status variable requires a value, this should be used + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_EINIT(s) ((s) == APR_EINIT) +/** + * The APR function has not been implemented on this + * platform, either because nobody has gotten to it yet, + * or the function is impossible on this platform. + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_ENOTIMPL(s) ((s) == APR_ENOTIMPL) +/** + * Two passwords do not match. + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_EMISMATCH(s) ((s) == APR_EMISMATCH) +/** + * The given lock was busy + * @warning always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_EBUSY(s) ((s) == APR_EBUSY) + +/** @} */ + +/** + * @addtogroup APR_Error APR Error Values + * @{ + */ +/* APR CANONICAL ERROR VALUES */ +/** @see APR_STATUS_IS_EACCES */ +#ifdef EACCES +#define APR_EACCES EACCES +#else +#define APR_EACCES (APR_OS_START_CANONERR + 1) +#endif + +/** @see APR_STATUS_IS_EEXIST */ +#ifdef EEXIST +#define APR_EEXIST EEXIST +#else +#define APR_EEXIST (APR_OS_START_CANONERR + 2) +#endif + +/** @see APR_STATUS_IS_ENAMETOOLONG */ +#ifdef ENAMETOOLONG +#define APR_ENAMETOOLONG ENAMETOOLONG +#else +#define APR_ENAMETOOLONG (APR_OS_START_CANONERR + 3) +#endif + +/** @see APR_STATUS_IS_ENOENT */ +#ifdef ENOENT +#define APR_ENOENT ENOENT +#else +#define APR_ENOENT (APR_OS_START_CANONERR + 4) +#endif + +/** @see APR_STATUS_IS_ENOTDIR */ +#ifdef ENOTDIR +#define APR_ENOTDIR ENOTDIR +#else +#define APR_ENOTDIR (APR_OS_START_CANONERR + 5) +#endif + +/** @see APR_STATUS_IS_ENOSPC */ +#ifdef ENOSPC +#define APR_ENOSPC ENOSPC +#else +#define APR_ENOSPC (APR_OS_START_CANONERR + 6) +#endif + +/** @see APR_STATUS_IS_ENOMEM */ +#ifdef ENOMEM +#define APR_ENOMEM ENOMEM +#else +#define APR_ENOMEM (APR_OS_START_CANONERR + 7) +#endif + +/** @see APR_STATUS_IS_EMFILE */ +#ifdef EMFILE +#define APR_EMFILE EMFILE +#else +#define APR_EMFILE (APR_OS_START_CANONERR + 8) +#endif + +/** @see APR_STATUS_IS_ENFILE */ +#ifdef ENFILE +#define APR_ENFILE ENFILE +#else +#define APR_ENFILE (APR_OS_START_CANONERR + 9) +#endif + +/** @see APR_STATUS_IS_EBADF */ +#ifdef EBADF +#define APR_EBADF EBADF +#else +#define APR_EBADF (APR_OS_START_CANONERR + 10) +#endif + +/** @see APR_STATUS_IS_EINVAL */ +#ifdef EINVAL +#define APR_EINVAL EINVAL +#else +#define APR_EINVAL (APR_OS_START_CANONERR + 11) +#endif + +/** @see APR_STATUS_IS_ESPIPE */ +#ifdef ESPIPE +#define APR_ESPIPE ESPIPE +#else +#define APR_ESPIPE (APR_OS_START_CANONERR + 12) +#endif + +/** + * @see APR_STATUS_IS_EAGAIN + * @warning use APR_STATUS_IS_EAGAIN instead of just testing this value + */ +#ifdef EAGAIN +#define APR_EAGAIN EAGAIN +#elif defined(EWOULDBLOCK) +#define APR_EAGAIN EWOULDBLOCK +#else +#define APR_EAGAIN (APR_OS_START_CANONERR + 13) +#endif + +/** @see APR_STATUS_IS_EINTR */ +#ifdef EINTR +#define APR_EINTR EINTR +#else +#define APR_EINTR (APR_OS_START_CANONERR + 14) +#endif + +/** @see APR_STATUS_IS_ENOTSOCK */ +#ifdef ENOTSOCK +#define APR_ENOTSOCK ENOTSOCK +#else +#define APR_ENOTSOCK (APR_OS_START_CANONERR + 15) +#endif + +/** @see APR_STATUS_IS_ECONNREFUSED */ +#ifdef ECONNREFUSED +#define APR_ECONNREFUSED ECONNREFUSED +#else +#define APR_ECONNREFUSED (APR_OS_START_CANONERR + 16) +#endif + +/** @see APR_STATUS_IS_EINPROGRESS */ +#ifdef EINPROGRESS +#define APR_EINPROGRESS EINPROGRESS +#else +#define APR_EINPROGRESS (APR_OS_START_CANONERR + 17) +#endif + +/** + * @see APR_STATUS_IS_ECONNABORTED + * @warning use APR_STATUS_IS_ECONNABORTED instead of just testing this value + */ + +#ifdef ECONNABORTED +#define APR_ECONNABORTED ECONNABORTED +#else +#define APR_ECONNABORTED (APR_OS_START_CANONERR + 18) +#endif + +/** @see APR_STATUS_IS_ECONNRESET */ +#ifdef ECONNRESET +#define APR_ECONNRESET ECONNRESET +#else +#define APR_ECONNRESET (APR_OS_START_CANONERR + 19) +#endif + +/** @see APR_STATUS_IS_ETIMEDOUT + * @deprecated */ +#ifdef ETIMEDOUT +#define APR_ETIMEDOUT ETIMEDOUT +#else +#define APR_ETIMEDOUT (APR_OS_START_CANONERR + 20) +#endif + +/** @see APR_STATUS_IS_EHOSTUNREACH */ +#ifdef EHOSTUNREACH +#define APR_EHOSTUNREACH EHOSTUNREACH +#else +#define APR_EHOSTUNREACH (APR_OS_START_CANONERR + 21) +#endif + +/** @see APR_STATUS_IS_ENETUNREACH */ +#ifdef ENETUNREACH +#define APR_ENETUNREACH ENETUNREACH +#else +#define APR_ENETUNREACH (APR_OS_START_CANONERR + 22) +#endif + +/** @see APR_STATUS_IS_EFTYPE */ +#ifdef EFTYPE +#define APR_EFTYPE EFTYPE +#else +#define APR_EFTYPE (APR_OS_START_CANONERR + 23) +#endif + +/** @see APR_STATUS_IS_EPIPE */ +#ifdef EPIPE +#define APR_EPIPE EPIPE +#else +#define APR_EPIPE (APR_OS_START_CANONERR + 24) +#endif + +/** @see APR_STATUS_IS_EXDEV */ +#ifdef EXDEV +#define APR_EXDEV EXDEV +#else +#define APR_EXDEV (APR_OS_START_CANONERR + 25) +#endif + +/** @see APR_STATUS_IS_ENOTEMPTY */ +#ifdef ENOTEMPTY +#define APR_ENOTEMPTY ENOTEMPTY +#else +#define APR_ENOTEMPTY (APR_OS_START_CANONERR + 26) +#endif + +/** @see APR_STATUS_IS_EAFNOSUPPORT */ +#ifdef EAFNOSUPPORT +#define APR_EAFNOSUPPORT EAFNOSUPPORT +#else +#define APR_EAFNOSUPPORT (APR_OS_START_CANONERR + 27) +#endif + +/** @see APR_STATUS_IS_EOPNOTSUPP */ +#ifdef EOPNOTSUPP +#define APR_EOPNOTSUPP EOPNOTSUPP +#else +#define APR_EOPNOTSUPP (APR_OS_START_CANONERR + 28) +#endif + +/** @see APR_STATUS_IS_ERANGE */ +#ifdef ERANGE +#define APR_ERANGE ERANGE +#else +#define APR_ERANGE (APR_OS_START_CANONERR + 29) +#endif + +/** @} */ + +#if defined(OS2) && !defined(DOXYGEN) + +#define APR_FROM_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e + APR_OS_START_SYSERR) +#define APR_TO_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e - APR_OS_START_SYSERR) + +#define INCL_DOSERRORS +#define INCL_DOS + +/* Leave these undefined. + * OS2 doesn't rely on the errno concept. + * The API calls always return a result codes which + * should be filtered through APR_FROM_OS_ERROR(). + * + * #define apr_get_os_error() (APR_FROM_OS_ERROR(GetLastError())) + * #define apr_set_os_error(e) (SetLastError(APR_TO_OS_ERROR(e))) + */ + +/* A special case, only socket calls require this; + */ +#define apr_get_netos_error() (APR_FROM_OS_ERROR(errno)) +#define apr_set_netos_error(e) (errno = APR_TO_OS_ERROR(e)) + +/* And this needs to be greped away for good: + */ +#define APR_OS2_STATUS(e) (APR_FROM_OS_ERROR(e)) + +/* These can't sit in a private header, so in spite of the extra size, + * they need to be made available here. + */ +#define SOCBASEERR 10000 +#define SOCEPERM (SOCBASEERR+1) /* Not owner */ +#define SOCESRCH (SOCBASEERR+3) /* No such process */ +#define SOCEINTR (SOCBASEERR+4) /* Interrupted system call */ +#define SOCENXIO (SOCBASEERR+6) /* No such device or address */ +#define SOCEBADF (SOCBASEERR+9) /* Bad file number */ +#define SOCEACCES (SOCBASEERR+13) /* Permission denied */ +#define SOCEFAULT (SOCBASEERR+14) /* Bad address */ +#define SOCEINVAL (SOCBASEERR+22) /* Invalid argument */ +#define SOCEMFILE (SOCBASEERR+24) /* Too many open files */ +#define SOCEPIPE (SOCBASEERR+32) /* Broken pipe */ +#define SOCEOS2ERR (SOCBASEERR+100) /* OS/2 Error */ +#define SOCEWOULDBLOCK (SOCBASEERR+35) /* Operation would block */ +#define SOCEINPROGRESS (SOCBASEERR+36) /* Operation now in progress */ +#define SOCEALREADY (SOCBASEERR+37) /* Operation already in progress */ +#define SOCENOTSOCK (SOCBASEERR+38) /* Socket operation on non-socket */ +#define SOCEDESTADDRREQ (SOCBASEERR+39) /* Destination address required */ +#define SOCEMSGSIZE (SOCBASEERR+40) /* Message too long */ +#define SOCEPROTOTYPE (SOCBASEERR+41) /* Protocol wrong type for socket */ +#define SOCENOPROTOOPT (SOCBASEERR+42) /* Protocol not available */ +#define SOCEPROTONOSUPPORT (SOCBASEERR+43) /* Protocol not supported */ +#define SOCESOCKTNOSUPPORT (SOCBASEERR+44) /* Socket type not supported */ +#define SOCEOPNOTSUPP (SOCBASEERR+45) /* Operation not supported on socket */ +#define SOCEPFNOSUPPORT (SOCBASEERR+46) /* Protocol family not supported */ +#define SOCEAFNOSUPPORT (SOCBASEERR+47) /* Address family not supported by protocol family */ +#define SOCEADDRINUSE (SOCBASEERR+48) /* Address already in use */ +#define SOCEADDRNOTAVAIL (SOCBASEERR+49) /* Can't assign requested address */ +#define SOCENETDOWN (SOCBASEERR+50) /* Network is down */ +#define SOCENETUNREACH (SOCBASEERR+51) /* Network is unreachable */ +#define SOCENETRESET (SOCBASEERR+52) /* Network dropped connection on reset */ +#define SOCECONNABORTED (SOCBASEERR+53) /* Software caused connection abort */ +#define SOCECONNRESET (SOCBASEERR+54) /* Connection reset by peer */ +#define SOCENOBUFS (SOCBASEERR+55) /* No buffer space available */ +#define SOCEISCONN (SOCBASEERR+56) /* Socket is already connected */ +#define SOCENOTCONN (SOCBASEERR+57) /* Socket is not connected */ +#define SOCESHUTDOWN (SOCBASEERR+58) /* Can't send after socket shutdown */ +#define SOCETOOMANYREFS (SOCBASEERR+59) /* Too many references: can't splice */ +#define SOCETIMEDOUT (SOCBASEERR+60) /* Connection timed out */ +#define SOCECONNREFUSED (SOCBASEERR+61) /* Connection refused */ +#define SOCELOOP (SOCBASEERR+62) /* Too many levels of symbolic links */ +#define SOCENAMETOOLONG (SOCBASEERR+63) /* File name too long */ +#define SOCEHOSTDOWN (SOCBASEERR+64) /* Host is down */ +#define SOCEHOSTUNREACH (SOCBASEERR+65) /* No route to host */ +#define SOCENOTEMPTY (SOCBASEERR+66) /* Directory not empty */ + +/* APR CANONICAL ERROR TESTS */ +#define APR_STATUS_IS_EACCES(s) ((s) == APR_EACCES \ + || (s) == APR_OS_START_SYSERR + ERROR_ACCESS_DENIED \ + || (s) == APR_OS_START_SYSERR + ERROR_SHARING_VIOLATION) +#define APR_STATUS_IS_EEXIST(s) ((s) == APR_EEXIST \ + || (s) == APR_OS_START_SYSERR + ERROR_OPEN_FAILED \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_EXISTS \ + || (s) == APR_OS_START_SYSERR + ERROR_ALREADY_EXISTS \ + || (s) == APR_OS_START_SYSERR + ERROR_ACCESS_DENIED) +#define APR_STATUS_IS_ENAMETOOLONG(s) ((s) == APR_ENAMETOOLONG \ + || (s) == APR_OS_START_SYSERR + ERROR_FILENAME_EXCED_RANGE \ + || (s) == APR_OS_START_SYSERR + SOCENAMETOOLONG) +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_PATH_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_MORE_FILES \ + || (s) == APR_OS_START_SYSERR + ERROR_OPEN_FAILED) +#define APR_STATUS_IS_ENOTDIR(s) ((s) == APR_ENOTDIR) +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC \ + || (s) == APR_OS_START_SYSERR + ERROR_DISK_FULL) +#define APR_STATUS_IS_ENOMEM(s) ((s) == APR_ENOMEM) +#define APR_STATUS_IS_EMFILE(s) ((s) == APR_EMFILE \ + || (s) == APR_OS_START_SYSERR + ERROR_TOO_MANY_OPEN_FILES) +#define APR_STATUS_IS_ENFILE(s) ((s) == APR_ENFILE) +#define APR_STATUS_IS_EBADF(s) ((s) == APR_EBADF \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_HANDLE) +#define APR_STATUS_IS_EINVAL(s) ((s) == APR_EINVAL \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_PARAMETER \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_FUNCTION) +#define APR_STATUS_IS_ESPIPE(s) ((s) == APR_ESPIPE \ + || (s) == APR_OS_START_SYSERR + ERROR_NEGATIVE_SEEK) +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_DATA \ + || (s) == APR_OS_START_SYSERR + SOCEWOULDBLOCK \ + || (s) == APR_OS_START_SYSERR + ERROR_LOCK_VIOLATION) +#define APR_STATUS_IS_EINTR(s) ((s) == APR_EINTR \ + || (s) == APR_OS_START_SYSERR + SOCEINTR) +#define APR_STATUS_IS_ENOTSOCK(s) ((s) == APR_ENOTSOCK \ + || (s) == APR_OS_START_SYSERR + SOCENOTSOCK) +#define APR_STATUS_IS_ECONNREFUSED(s) ((s) == APR_ECONNREFUSED \ + || (s) == APR_OS_START_SYSERR + SOCECONNREFUSED) +#define APR_STATUS_IS_EINPROGRESS(s) ((s) == APR_EINPROGRESS \ + || (s) == APR_OS_START_SYSERR + SOCEINPROGRESS) +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED \ + || (s) == APR_OS_START_SYSERR + SOCECONNABORTED) +#define APR_STATUS_IS_ECONNRESET(s) ((s) == APR_ECONNRESET \ + || (s) == APR_OS_START_SYSERR + SOCECONNRESET) +/* XXX deprecated */ +#define APR_STATUS_IS_ETIMEDOUT(s) ((s) == APR_ETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + SOCETIMEDOUT) +#undef APR_STATUS_IS_TIMEUP +#define APR_STATUS_IS_TIMEUP(s) ((s) == APR_TIMEUP \ + || (s) == APR_OS_START_SYSERR + SOCETIMEDOUT) +#define APR_STATUS_IS_EHOSTUNREACH(s) ((s) == APR_EHOSTUNREACH \ + || (s) == APR_OS_START_SYSERR + SOCEHOSTUNREACH) +#define APR_STATUS_IS_ENETUNREACH(s) ((s) == APR_ENETUNREACH \ + || (s) == APR_OS_START_SYSERR + SOCENETUNREACH) +#define APR_STATUS_IS_EFTYPE(s) ((s) == APR_EFTYPE) +#define APR_STATUS_IS_EPIPE(s) ((s) == APR_EPIPE \ + || (s) == APR_OS_START_SYSERR + ERROR_BROKEN_PIPE \ + || (s) == APR_OS_START_SYSERR + SOCEPIPE) +#define APR_STATUS_IS_EXDEV(s) ((s) == APR_EXDEV \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_SAME_DEVICE) +#define APR_STATUS_IS_ENOTEMPTY(s) ((s) == APR_ENOTEMPTY \ + || (s) == APR_OS_START_SYSERR + ERROR_DIR_NOT_EMPTY \ + || (s) == APR_OS_START_SYSERR + ERROR_ACCESS_DENIED) +#define APR_STATUS_IS_EAFNOSUPPORT(s) ((s) == APR_AFNOSUPPORT \ + || (s) == APR_OS_START_SYSERR + SOCEAFNOSUPPORT) +#define APR_STATUS_IS_EOPNOTSUPP(s) ((s) == APR_EOPNOTSUPP \ + || (s) == APR_OS_START_SYSERR + SOCEOPNOTSUPP) +#define APR_STATUS_IS_ERANGE(s) ((s) == APR_ERANGE) + +/* + Sorry, too tired to wrap this up for OS2... feel free to + fit the following into their best matches. + + { ERROR_NO_SIGNAL_SENT, ESRCH }, + { SOCEALREADY, EALREADY }, + { SOCEDESTADDRREQ, EDESTADDRREQ }, + { SOCEMSGSIZE, EMSGSIZE }, + { SOCEPROTOTYPE, EPROTOTYPE }, + { SOCENOPROTOOPT, ENOPROTOOPT }, + { SOCEPROTONOSUPPORT, EPROTONOSUPPORT }, + { SOCESOCKTNOSUPPORT, ESOCKTNOSUPPORT }, + { SOCEPFNOSUPPORT, EPFNOSUPPORT }, + { SOCEADDRINUSE, EADDRINUSE }, + { SOCEADDRNOTAVAIL, EADDRNOTAVAIL }, + { SOCENETDOWN, ENETDOWN }, + { SOCENETRESET, ENETRESET }, + { SOCENOBUFS, ENOBUFS }, + { SOCEISCONN, EISCONN }, + { SOCENOTCONN, ENOTCONN }, + { SOCESHUTDOWN, ESHUTDOWN }, + { SOCETOOMANYREFS, ETOOMANYREFS }, + { SOCELOOP, ELOOP }, + { SOCEHOSTDOWN, EHOSTDOWN }, + { SOCENOTEMPTY, ENOTEMPTY }, + { SOCEPIPE, EPIPE } +*/ + +#elif defined(WIN32) && !defined(DOXYGEN) /* !defined(OS2) */ + +#define APR_FROM_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e + APR_OS_START_SYSERR) +#define APR_TO_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e - APR_OS_START_SYSERR) + +#define apr_get_os_error() (APR_FROM_OS_ERROR(GetLastError())) +#define apr_set_os_error(e) (SetLastError(APR_TO_OS_ERROR(e))) + +/* A special case, only socket calls require this: + */ +#define apr_get_netos_error() (APR_FROM_OS_ERROR(WSAGetLastError())) +#define apr_set_netos_error(e) (WSASetLastError(APR_TO_OS_ERROR(e))) + +/* APR CANONICAL ERROR TESTS */ +#define APR_STATUS_IS_EACCES(s) ((s) == APR_EACCES \ + || (s) == APR_OS_START_SYSERR + ERROR_ACCESS_DENIED \ + || (s) == APR_OS_START_SYSERR + ERROR_CANNOT_MAKE \ + || (s) == APR_OS_START_SYSERR + ERROR_CURRENT_DIRECTORY \ + || (s) == APR_OS_START_SYSERR + ERROR_DRIVE_LOCKED \ + || (s) == APR_OS_START_SYSERR + ERROR_FAIL_I24 \ + || (s) == APR_OS_START_SYSERR + ERROR_LOCK_VIOLATION \ + || (s) == APR_OS_START_SYSERR + ERROR_LOCK_FAILED \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_LOCKED \ + || (s) == APR_OS_START_SYSERR + ERROR_NETWORK_ACCESS_DENIED \ + || (s) == APR_OS_START_SYSERR + ERROR_SHARING_VIOLATION) +#define APR_STATUS_IS_EEXIST(s) ((s) == APR_EEXIST \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_EXISTS \ + || (s) == APR_OS_START_SYSERR + ERROR_ALREADY_EXISTS) +#define APR_STATUS_IS_ENAMETOOLONG(s) ((s) == APR_ENAMETOOLONG \ + || (s) == APR_OS_START_SYSERR + ERROR_FILENAME_EXCED_RANGE \ + || (s) == APR_OS_START_SYSERR + WSAENAMETOOLONG) +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_PATH_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_OPEN_FAILED \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_MORE_FILES) +#define APR_STATUS_IS_ENOTDIR(s) ((s) == APR_ENOTDIR \ + || (s) == APR_OS_START_SYSERR + ERROR_PATH_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_NETPATH \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_NET_NAME \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_PATHNAME \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_DRIVE \ + || (s) == APR_OS_START_SYSERR + ERROR_DIRECTORY) +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC \ + || (s) == APR_OS_START_SYSERR + ERROR_DISK_FULL) +#define APR_STATUS_IS_ENOMEM(s) ((s) == APR_ENOMEM \ + || (s) == APR_OS_START_SYSERR + ERROR_ARENA_TRASHED \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_ENOUGH_MEMORY \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_BLOCK \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_ENOUGH_QUOTA \ + || (s) == APR_OS_START_SYSERR + ERROR_OUTOFMEMORY) +#define APR_STATUS_IS_EMFILE(s) ((s) == APR_EMFILE \ + || (s) == APR_OS_START_SYSERR + ERROR_TOO_MANY_OPEN_FILES) +#define APR_STATUS_IS_ENFILE(s) ((s) == APR_ENFILE) +#define APR_STATUS_IS_EBADF(s) ((s) == APR_EBADF \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_HANDLE \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_TARGET_HANDLE) +#define APR_STATUS_IS_EINVAL(s) ((s) == APR_EINVAL \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_ACCESS \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_DATA \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_FUNCTION \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_HANDLE \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_PARAMETER \ + || (s) == APR_OS_START_SYSERR + ERROR_NEGATIVE_SEEK) +#define APR_STATUS_IS_ESPIPE(s) ((s) == APR_ESPIPE \ + || (s) == APR_OS_START_SYSERR + ERROR_SEEK_ON_DEVICE \ + || (s) == APR_OS_START_SYSERR + ERROR_NEGATIVE_SEEK) +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_DATA \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_PROC_SLOTS \ + || (s) == APR_OS_START_SYSERR + ERROR_NESTING_NOT_ALLOWED \ + || (s) == APR_OS_START_SYSERR + ERROR_MAX_THRDS_REACHED \ + || (s) == APR_OS_START_SYSERR + ERROR_LOCK_VIOLATION \ + || (s) == APR_OS_START_SYSERR + WSAEWOULDBLOCK) +#define APR_STATUS_IS_EINTR(s) ((s) == APR_EINTR \ + || (s) == APR_OS_START_SYSERR + WSAEINTR) +#define APR_STATUS_IS_ENOTSOCK(s) ((s) == APR_ENOTSOCK \ + || (s) == APR_OS_START_SYSERR + WSAENOTSOCK) +#define APR_STATUS_IS_ECONNREFUSED(s) ((s) == APR_ECONNREFUSED \ + || (s) == APR_OS_START_SYSERR + WSAECONNREFUSED) +#define APR_STATUS_IS_EINPROGRESS(s) ((s) == APR_EINPROGRESS \ + || (s) == APR_OS_START_SYSERR + WSAEINPROGRESS) +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED \ + || (s) == APR_OS_START_SYSERR + WSAECONNABORTED) +#define APR_STATUS_IS_ECONNRESET(s) ((s) == APR_ECONNRESET \ + || (s) == APR_OS_START_SYSERR + ERROR_NETNAME_DELETED \ + || (s) == APR_OS_START_SYSERR + WSAECONNRESET) +/* XXX deprecated */ +#define APR_STATUS_IS_ETIMEDOUT(s) ((s) == APR_ETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WSAETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WAIT_TIMEOUT) +#undef APR_STATUS_IS_TIMEUP +#define APR_STATUS_IS_TIMEUP(s) ((s) == APR_TIMEUP \ + || (s) == APR_OS_START_SYSERR + WSAETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WAIT_TIMEOUT) +#define APR_STATUS_IS_EHOSTUNREACH(s) ((s) == APR_EHOSTUNREACH \ + || (s) == APR_OS_START_SYSERR + WSAEHOSTUNREACH) +#define APR_STATUS_IS_ENETUNREACH(s) ((s) == APR_ENETUNREACH \ + || (s) == APR_OS_START_SYSERR + WSAENETUNREACH) +#define APR_STATUS_IS_EFTYPE(s) ((s) == APR_EFTYPE \ + || (s) == APR_OS_START_SYSERR + ERROR_EXE_MACHINE_TYPE_MISMATCH \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_DLL \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_MODULETYPE \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_EXE_FORMAT \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_EXE_SIGNATURE \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_CORRUPT \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_FORMAT) +#define APR_STATUS_IS_EPIPE(s) ((s) == APR_EPIPE \ + || (s) == APR_OS_START_SYSERR + ERROR_BROKEN_PIPE) +#define APR_STATUS_IS_EXDEV(s) ((s) == APR_EXDEV \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_SAME_DEVICE) +#define APR_STATUS_IS_ENOTEMPTY(s) ((s) == APR_ENOTEMPTY \ + || (s) == APR_OS_START_SYSERR + ERROR_DIR_NOT_EMPTY) +#define APR_STATUS_IS_EAFNOSUPPORT(s) ((s) == APR_EAFNOSUPPORT \ + || (s) == APR_OS_START_SYSERR + WSAEAFNOSUPPORT) +#define APR_STATUS_IS_EOPNOTSUPP(s) ((s) == APR_EOPNOTSUPP \ + || (s) == APR_OS_START_SYSERR + WSAEOPNOTSUPP) +#define APR_STATUS_IS_ERANGE(s) ((s) == APR_ERANGE) + +#elif defined(NETWARE) && defined(USE_WINSOCK) && !defined(DOXYGEN) /* !defined(OS2) && !defined(WIN32) */ + +#define APR_FROM_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e + APR_OS_START_SYSERR) +#define APR_TO_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e - APR_OS_START_SYSERR) + +#define apr_get_os_error() (errno) +#define apr_set_os_error(e) (errno = (e)) + +/* A special case, only socket calls require this: */ +#define apr_get_netos_error() (APR_FROM_OS_ERROR(WSAGetLastError())) +#define apr_set_netos_error(e) (WSASetLastError(APR_TO_OS_ERROR(e))) + +/* APR CANONICAL ERROR TESTS */ +#define APR_STATUS_IS_EACCES(s) ((s) == APR_EACCES) +#define APR_STATUS_IS_EEXIST(s) ((s) == APR_EEXIST) +#define APR_STATUS_IS_ENAMETOOLONG(s) ((s) == APR_ENAMETOOLONG) +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT) +#define APR_STATUS_IS_ENOTDIR(s) ((s) == APR_ENOTDIR) +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC) +#define APR_STATUS_IS_ENOMEM(s) ((s) == APR_ENOMEM) +#define APR_STATUS_IS_EMFILE(s) ((s) == APR_EMFILE) +#define APR_STATUS_IS_ENFILE(s) ((s) == APR_ENFILE) +#define APR_STATUS_IS_EBADF(s) ((s) == APR_EBADF) +#define APR_STATUS_IS_EINVAL(s) ((s) == APR_EINVAL) +#define APR_STATUS_IS_ESPIPE(s) ((s) == APR_ESPIPE) + +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN \ + || (s) == EWOULDBLOCK \ + || (s) == APR_OS_START_SYSERR + WSAEWOULDBLOCK) +#define APR_STATUS_IS_EINTR(s) ((s) == APR_EINTR \ + || (s) == APR_OS_START_SYSERR + WSAEINTR) +#define APR_STATUS_IS_ENOTSOCK(s) ((s) == APR_ENOTSOCK \ + || (s) == APR_OS_START_SYSERR + WSAENOTSOCK) +#define APR_STATUS_IS_ECONNREFUSED(s) ((s) == APR_ECONNREFUSED \ + || (s) == APR_OS_START_SYSERR + WSAECONNREFUSED) +#define APR_STATUS_IS_EINPROGRESS(s) ((s) == APR_EINPROGRESS \ + || (s) == APR_OS_START_SYSERR + WSAEINPROGRESS) +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED \ + || (s) == APR_OS_START_SYSERR + WSAECONNABORTED) +#define APR_STATUS_IS_ECONNRESET(s) ((s) == APR_ECONNRESET \ + || (s) == APR_OS_START_SYSERR + WSAECONNRESET) +/* XXX deprecated */ +#define APR_STATUS_IS_ETIMEDOUT(s) ((s) == APR_ETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WSAETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WAIT_TIMEOUT) +#undef APR_STATUS_IS_TIMEUP +#define APR_STATUS_IS_TIMEUP(s) ((s) == APR_TIMEUP \ + || (s) == APR_OS_START_SYSERR + WSAETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WAIT_TIMEOUT) +#define APR_STATUS_IS_EHOSTUNREACH(s) ((s) == APR_EHOSTUNREACH \ + || (s) == APR_OS_START_SYSERR + WSAEHOSTUNREACH) +#define APR_STATUS_IS_ENETUNREACH(s) ((s) == APR_ENETUNREACH \ + || (s) == APR_OS_START_SYSERR + WSAENETUNREACH) +#define APR_STATUS_IS_ENETDOWN(s) ((s) == APR_OS_START_SYSERR + WSAENETDOWN) +#define APR_STATUS_IS_EFTYPE(s) ((s) == APR_EFTYPE) +#define APR_STATUS_IS_EPIPE(s) ((s) == APR_EPIPE) +#define APR_STATUS_IS_EXDEV(s) ((s) == APR_EXDEV) +#define APR_STATUS_IS_ENOTEMPTY(s) ((s) == APR_ENOTEMPTY) +#define APR_STATUS_IS_EAFNOSUPPORT(s) ((s) == APR_EAFNOSUPPORT \ + || (s) == APR_OS_START_SYSERR + WSAEAFNOSUPPORT) +#define APR_STATUS_IS_EOPNOTSUPP(s) ((s) == APR_EOPNOTSUPP \ + || (s) == APR_OS_START_SYSERR + WSAEOPNOTSUPP) +#define APR_STATUS_IS_ERANGE(s) ((s) == APR_ERANGE) + +#else /* !defined(NETWARE) && !defined(OS2) && !defined(WIN32) */ + +/* + * os error codes are clib error codes + */ +#define APR_FROM_OS_ERROR(e) (e) +#define APR_TO_OS_ERROR(e) (e) + +#define apr_get_os_error() (errno) +#define apr_set_os_error(e) (errno = (e)) + +/* A special case, only socket calls require this: + */ +#define apr_get_netos_error() (errno) +#define apr_set_netos_error(e) (errno = (e)) + +/** + * @addtogroup APR_STATUS_IS + * @{ + */ + +/** permission denied */ +#define APR_STATUS_IS_EACCES(s) ((s) == APR_EACCES) +/** file exists */ +#define APR_STATUS_IS_EEXIST(s) ((s) == APR_EEXIST) +/** path name is too long */ +#define APR_STATUS_IS_ENAMETOOLONG(s) ((s) == APR_ENAMETOOLONG) +/** + * no such file or directory + * @remark + * EMVSCATLG can be returned by the automounter on z/OS for + * paths which do not exist. + */ +#ifdef EMVSCATLG +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT \ + || (s) == EMVSCATLG) +#else +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT) +#endif +/** not a directory */ +#define APR_STATUS_IS_ENOTDIR(s) ((s) == APR_ENOTDIR) +/** no space left on device */ +#ifdef EDQUOT +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC \ + || (s) == EDQUOT) +#else +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC) +#endif +/** not enough memory */ +#define APR_STATUS_IS_ENOMEM(s) ((s) == APR_ENOMEM) +/** too many open files */ +#define APR_STATUS_IS_EMFILE(s) ((s) == APR_EMFILE) +/** file table overflow */ +#define APR_STATUS_IS_ENFILE(s) ((s) == APR_ENFILE) +/** bad file # */ +#define APR_STATUS_IS_EBADF(s) ((s) == APR_EBADF) +/** invalid argument */ +#define APR_STATUS_IS_EINVAL(s) ((s) == APR_EINVAL) +/** illegal seek */ +#define APR_STATUS_IS_ESPIPE(s) ((s) == APR_ESPIPE) + +/** operation would block */ +#if !defined(EWOULDBLOCK) || !defined(EAGAIN) +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN) +#elif (EWOULDBLOCK == EAGAIN) +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN) +#else +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN \ + || (s) == EWOULDBLOCK) +#endif + +/** interrupted system call */ +#define APR_STATUS_IS_EINTR(s) ((s) == APR_EINTR) +/** socket operation on a non-socket */ +#define APR_STATUS_IS_ENOTSOCK(s) ((s) == APR_ENOTSOCK) +/** Connection Refused */ +#define APR_STATUS_IS_ECONNREFUSED(s) ((s) == APR_ECONNREFUSED) +/** operation now in progress */ +#define APR_STATUS_IS_EINPROGRESS(s) ((s) == APR_EINPROGRESS) + +/** + * Software caused connection abort + * @remark + * EPROTO on certain older kernels really means ECONNABORTED, so we need to + * ignore it for them. See discussion in new-httpd archives nh.9701 & nh.9603 + * + * There is potentially a bug in Solaris 2.x x<6, and other boxes that + * implement tcp sockets in userland (i.e. on top of STREAMS). On these + * systems, EPROTO can actually result in a fatal loop. See PR#981 for + * example. It's hard to handle both uses of EPROTO. + */ +#ifdef EPROTO +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED \ + || (s) == EPROTO) +#else +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED) +#endif + +/** Connection Reset by peer */ +#define APR_STATUS_IS_ECONNRESET(s) ((s) == APR_ECONNRESET) +/** Operation timed out + * @deprecated */ +#define APR_STATUS_IS_ETIMEDOUT(s) ((s) == APR_ETIMEDOUT) +/** no route to host */ +#define APR_STATUS_IS_EHOSTUNREACH(s) ((s) == APR_EHOSTUNREACH) +/** network is unreachable */ +#define APR_STATUS_IS_ENETUNREACH(s) ((s) == APR_ENETUNREACH) +/** inappropriate file type or format */ +#define APR_STATUS_IS_EFTYPE(s) ((s) == APR_EFTYPE) +/** broken pipe */ +#define APR_STATUS_IS_EPIPE(s) ((s) == APR_EPIPE) +/** cross device link */ +#define APR_STATUS_IS_EXDEV(s) ((s) == APR_EXDEV) +/** Directory Not Empty */ +#define APR_STATUS_IS_ENOTEMPTY(s) ((s) == APR_ENOTEMPTY || \ + (s) == APR_EEXIST) +/** Address Family not supported */ +#define APR_STATUS_IS_EAFNOSUPPORT(s) ((s) == APR_EAFNOSUPPORT) +/** Socket operation not supported */ +#define APR_STATUS_IS_EOPNOTSUPP(s) ((s) == APR_EOPNOTSUPP) + +/** Numeric value not representable */ +#define APR_STATUS_IS_ERANGE(s) ((s) == APR_ERANGE) +/** @} */ + +#endif /* !defined(NETWARE) && !defined(OS2) && !defined(WIN32) */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_ERRNO_H */ diff --git a/c/dependencies/macos/apr/include/apr_escape.h b/c/dependencies/macos/apr/include/apr_escape.h new file mode 100644 index 00000000..ed048c95 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_escape.h @@ -0,0 +1,431 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file apr_escape.h + * @brief APR-UTIL Escaping + */ +#ifndef APR_ESCAPE_H +#define APR_ESCAPE_H +#include "apr.h" +#include "apr_general.h" +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Escaping Escape functions + * @ingroup APR + * @{ + */ + +/* Simple escape/unescape functions. + * + * The design goal of these functions are: + * + * - Avoid unnecessary work. + * + * In most cases the strings passed in do not need to be escaped at all. In + * these cases the original string will be returned. + * + * - Lowest possible memory footprint. + * + * The amount of memory allocated for a given encoding is calculated based + * on the exact amount of memory needed, and not the theoretical worst case + * scenario. + * + */ + +/** + * When passing a string to one of the escape functions, this value can be + * passed to indicate a string-valued key, and have the length computed + * automatically. + */ +#define APR_ESCAPE_STRING (-1) + +/** + * Apply LDAP distinguished name escaping as per RFC4514. + */ +#define APR_ESCAPE_LDAP_DN (0x01) + +/** + * Apply LDAP filter escaping as per RFC4515. + */ +#define APR_ESCAPE_LDAP_FILTER (0x02) + +/** + * Apply both RFC4514 and RFC4515 LDAP escaping. + */ +#define APR_ESCAPE_LDAP_ALL (0x03) + +/** + * Perform shell escaping on the provided string. + * + * Shell escaping causes characters to be prefixed with a '\' character. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_shell(char *escaped, const char *str, + apr_ssize_t slen, apr_size_t *len); + +/** + * Perform shell escaping on the provided string, returning the result + * from the pool. + * + * Shell escaping causes characters to be prefixed with a '\' character. + * + * If no characters were escaped, the original string is returned. + * @param p Pool to allocate from + * @param str The original string + * @return the encoded string, allocated from the pool, or the original + * string if no escaping took place or the string was NULL. + */ +APR_DECLARE(const char *) apr_pescape_shell(apr_pool_t *p, const char *str) + __attribute__((nonnull(1))); + +/** + * Unescapes a URL, leaving reserved characters intact. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param url String to be unescaped + * @param slen The length of the original url, or APR_ESCAPE_STRING + * @param forbid Optional list of forbidden characters, in addition to + * 0x00 + * @param reserved Optional list of reserved characters that will be + * left unescaped + * @param plus If non zero, '+' is converted to ' ' as per + * application/x-www-form-urlencoded encoding + * @param len If set, the length of the escaped string will be returned + * @return APR_SUCCESS on success, APR_NOTFOUND if no characters are + * decoded or the string is NULL, APR_EINVAL if a bad escape sequence is + * found, APR_BADCH if a character on the forbid list is found. + */ +APR_DECLARE(apr_status_t) apr_unescape_url(char *escaped, const char *url, + apr_ssize_t slen, const char *forbid, const char *reserved, int plus, + apr_size_t *len); + +/** + * Unescapes a URL, leaving reserved characters intact, returning the + * result from a pool. + * @param p Pool to allocate from + * @param url String to be unescaped in place + * @param forbid Optional list of forbidden characters, in addition to + * 0x00 + * @param reserved Optional list of reserved characters that will be + * left unescaped + * @param plus If non zero, '+' is converted to ' ' as per + * application/x-www-form-urlencoded encoding + * @return A string allocated from the pool on success, the original string + * if no characters are decoded, or NULL if a bad escape sequence is found + * or if a character on the forbid list is found, or if the original string + * was NULL. + */ +APR_DECLARE(const char *) apr_punescape_url(apr_pool_t *p, const char *url, + const char *forbid, const char *reserved, int plus) + __attribute__((nonnull(1))); + +/** + * Escape a path segment, as defined in RFC1808. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_path_segment(char *escaped, + const char *str, apr_ssize_t slen, apr_size_t *len); + +/** + * Escape a path segment, as defined in RFC1808, returning the result from a + * pool. + * @param p Pool to allocate from + * @param str String to be escaped + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or the string is NULL. + */ +APR_DECLARE(const char *) apr_pescape_path_segment(apr_pool_t *p, + const char *str) __attribute__((nonnull(1))); + +/** + * Converts an OS path to a URL, in an OS dependent way, as defined in RFC1808. + * In all cases if a ':' occurs before the first '/' in the URL, the URL should + * be prefixed with "./" (or the ':' escaped). In the case of Unix, this means + * leaving '/' alone, but otherwise doing what escape_path_segment() does. For + * efficiency reasons, we don't use escape_path_segment(), which is provided for + * reference. Again, RFC 1808 is where this stuff is defined. + * + * If partial is set, os_escape_path() assumes that the path will be appended to + * something with a '/' in it (and thus does not prefix "./"). + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param path The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param partial If non zero, suppresses the prepending of "./" + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or if the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_path(char *escaped, const char *path, + apr_ssize_t slen, int partial, apr_size_t *len); + +/** + * Converts an OS path to a URL, in an OS dependent way, as defined in RFC1808, + * returning the result from a pool. + * + * In all cases if a ':' occurs before the first '/' in the URL, the URL should + * be prefixed with "./" (or the ':' escaped). In the case of Unix, this means + * leaving '/' alone, but otherwise doing what escape_path_segment() does. For + * efficiency reasons, we don't use escape_path_segment(), which is provided for + * reference. Again, RFC 1808 is where this stuff is defined. + * + * If partial is set, os_escape_path() assumes that the path will be appended to + * something with a '/' in it (and thus does not prefix "./"). + * @param p Pool to allocate from + * @param str The original string + * @param partial If non zero, suppresses the prepending of "./" + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or if the string was NULL. + */ +APR_DECLARE(const char *) apr_pescape_path(apr_pool_t *p, const char *str, + int partial) __attribute__((nonnull(1))); + +/** + * Urlencode a string, as defined in + * http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or if the stirng was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_urlencoded(char *escaped, const char *str, + apr_ssize_t slen, apr_size_t *len); + +/** + * Urlencode a string, as defined in + * http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1, returning + * the result from a pool. + * @param p Pool to allocate from + * @param str String to be escaped + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or if the string was NULL. + */ +APR_DECLARE(const char *) apr_pescape_urlencoded(apr_pool_t *p, + const char *str) __attribute__((nonnull(1))); + +/** + * Apply entity encoding to a string. Characters are replaced as follows: + * '<' becomes '\<', '>' becomes '\>', '&' becomes '\&', the + * double quote becomes '\"" and the single quote becomes '\''. + * + * If toasc is not zero, any non ascii character will be encoded as + * '%\#ddd;', where ddd is the decimal code of the character. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param toasc If non zero, encode non ascii characters + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_entity(char *escaped, const char *str, + apr_ssize_t slen, int toasc, apr_size_t *len); + +/** + * Apply entity encoding to a string, returning the result from a pool. + * Characters are replaced as follows: '<' becomes '\<', '>' becomes + * '\>', '&' becomes '\&', the double quote becomes '\"" and the + * single quote becomes '\''. + * @param p Pool to allocate from + * @param str The original string + * @param toasc If non zero, encode non ascii characters + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or the string is NULL. + */ +APR_DECLARE(const char *) apr_pescape_entity(apr_pool_t *p, const char *str, + int toasc) __attribute__((nonnull(1))); + +/** + * Decodes html entities or numeric character references in a string. If + * the string to be unescaped is syntactically incorrect, then the + * following fixups will be made: + * unknown entities will be left undecoded; + * references to unused numeric characters will be deleted. + * In particular, � will not be decoded, but will be deleted. + * @param unescaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_unescape_entity(char *unescaped, const char *str, + apr_ssize_t slen, apr_size_t *len); + +/** + * Decodes html entities or numeric character references in a string. If + * the string to be unescaped is syntactically incorrect, then the + * following fixups will be made: + * unknown entities will be left undecoded; + * references to unused numeric characters will be deleted. + * In particular, � will not be decoded, but will be deleted. + * @param p Pool to allocate from + * @param str The original string + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or the string is NULL. + */ +APR_DECLARE(const char *) apr_punescape_entity(apr_pool_t *p, const char *str) + __attribute__((nonnull(1))); + +/** + * Escape control characters in a string, as performed by the shell's + * 'echo' command. Characters are replaced as follows: + * \\a alert (bell), \\b backspace, \\f form feed, \\n new line, \\r carriage + * return, \\t horizontal tab, \\v vertical tab, \\ backslash. + * + * Any non ascii character will be encoded as '\\xHH', where HH is the hex + * code of the character. + * + * If quote is not zero, the double quote character will also be escaped. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param quote If non zero, encode double quotes + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_echo(char *escaped, const char *str, + apr_ssize_t slen, int quote, apr_size_t *len); + +/** + * Escape control characters in a string, as performed by the shell's + * 'echo' command, and return the results from a pool. Characters are + * replaced as follows: \\a alert (bell), \\b backspace, \\f form feed, + * \\n new line, \\r carriage return, \\t horizontal tab, \\v vertical tab, + * \\ backslash. + * + * Any non ascii character will be encoded as '\\xHH', where HH is the hex + * code of the character. + * + * If quote is not zero, the double quote character will also be escaped. + * @param p Pool to allocate from + * @param str The original string + * @param quote If non zero, encode double quotes + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or the string is NULL. + */ +APR_DECLARE(const char *) apr_pescape_echo(apr_pool_t *p, const char *str, + int quote); + +/** + * Convert binary data to a hex encoding. + * @param dest The destination buffer, can be NULL + * @param src The original buffer + * @param srclen The length of the original buffer + * @param colon If not zero, insert colon characters between hex digits. + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_hex(char *dest, const void *src, + apr_size_t srclen, int colon, apr_size_t *len); + +/** + * Convert binary data to a hex encoding, and return the results from a + * pool. + * @param p Pool to allocate from + * @param src The original buffer + * @param slen The length of the original buffer + * @param colon If not zero, insert colon characters between hex digits. + * @return A zero padded buffer allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *) apr_pescape_hex(apr_pool_t *p, const void *src, + apr_size_t slen, int colon) __attribute__((nonnull(1))); + +/** + * Convert hex encoded string to binary data. + * @param dest The destination buffer, can be NULL + * @param str The original buffer + * @param slen The length of the original buffer + * @param colon If not zero, ignore colon characters between hex digits. + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL, or APR_BADCH + * if a non hex character is present. + */ +APR_DECLARE(apr_status_t) apr_unescape_hex(void *dest, const char *str, + apr_ssize_t slen, int colon, apr_size_t *len); + +/** + * Convert hex encoding to binary data, and return the results from a pool. + * If the colon character appears between pairs of hex digits, it will be + * ignored. + * @param p Pool to allocate from + * @param str The original string + * @param colon If not zero, ignore colon characters between hex digits. + * @param len If present, returns the length of the final buffer + * @return A buffer allocated from the pool on success, or NULL if src was + * NULL, or a bad character was present. + */ +APR_DECLARE(const void *) apr_punescape_hex(apr_pool_t *p, const char *str, + int colon, apr_size_t *len); + +/** + * Apply LDAP escaping to binary data. Characters from RFC4514 and RFC4515 + * are escaped with their hex equivalents. + * @param dest The destination buffer, can be NULL + * @param src The original buffer + * @param srclen The length of the original buffer + * @param flags APR_ESCAPE_LDAP_DN for RFC4514, APR_ESCAPE_LDAP_FILTER for + * RFC4515, APR_ESCAPE_LDAP_ALL for both + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_ldap(char *dest, const void *src, + apr_ssize_t srclen, int flags, apr_size_t *len); + +/** + * Apply LDAP escaping to binary data, and return the results from a + * pool. Characters from RFC4514 and RFC4515 are escaped with their hex + * equivalents. + * @param p Pool to allocate from + * @param src The original buffer + * @param slen The length of the original buffer + * @param flags APR_ESCAPE_LDAP_DN for RFC4514, APR_ESCAPE_LDAP_FILTER for + * RFC4515, APR_ESCAPE_LDAP_ALL for both + * @return A zero padded buffer allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *) apr_pescape_ldap(apr_pool_t *p, const void *src, + apr_ssize_t slen, int flags) __attribute__((nonnull(1))); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ESCAPE_H */ diff --git a/c/dependencies/macos/apr/include/apr_file_info.h b/c/dependencies/macos/apr/include/apr_file_info.h new file mode 100644 index 00000000..cfddc68d --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_file_info.h @@ -0,0 +1,428 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_FILE_INFO_H +#define APR_FILE_INFO_H + +/** + * @file apr_file_info.h + * @brief APR File Information + */ + +#include "apr.h" +#include "apr_user.h" +#include "apr_pools.h" +#include "apr_tables.h" +#include "apr_time.h" +#include "apr_errno.h" + +#if APR_HAVE_SYS_UIO_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_file_info File Information + * @ingroup APR + * @{ + */ + +/* Many applications use the type member to determine the + * existance of a file or initialization of the file info, + * so the APR_NOFILE value must be distinct from APR_UNKFILE. + */ + +/** apr_filetype_e values for the filetype member of the + * apr_file_info_t structure + * @warning Not all of the filetypes below can be determined. + * For example, a given platform might not correctly report + * a socket descriptor as APR_SOCK if that type isn't + * well-identified on that platform. In such cases where + * a filetype exists but cannot be described by the recognized + * flags below, the filetype will be APR_UNKFILE. If the + * filetype member is not determined, the type will be APR_NOFILE. + */ + +typedef enum { + APR_NOFILE = 0, /**< no file type determined */ + APR_REG, /**< a regular file */ + APR_DIR, /**< a directory */ + APR_CHR, /**< a character device */ + APR_BLK, /**< a block device */ + APR_PIPE, /**< a FIFO / pipe */ + APR_LNK, /**< a symbolic link */ + APR_SOCK, /**< a [unix domain] socket */ + APR_UNKFILE = 127 /**< a file of some other unknown type */ +} apr_filetype_e; + +/** + * @defgroup apr_file_permissions File Permissions flags + * @{ + */ + +#define APR_FPROT_USETID 0x8000 /**< Set user id */ +#define APR_FPROT_UREAD 0x0400 /**< Read by user */ +#define APR_FPROT_UWRITE 0x0200 /**< Write by user */ +#define APR_FPROT_UEXECUTE 0x0100 /**< Execute by user */ + +#define APR_FPROT_GSETID 0x4000 /**< Set group id */ +#define APR_FPROT_GREAD 0x0040 /**< Read by group */ +#define APR_FPROT_GWRITE 0x0020 /**< Write by group */ +#define APR_FPROT_GEXECUTE 0x0010 /**< Execute by group */ + +#define APR_FPROT_WSTICKY 0x2000 /**< Sticky bit */ +#define APR_FPROT_WREAD 0x0004 /**< Read by others */ +#define APR_FPROT_WWRITE 0x0002 /**< Write by others */ +#define APR_FPROT_WEXECUTE 0x0001 /**< Execute by others */ + +#define APR_FPROT_OS_DEFAULT 0x0FFF /**< use OS's default permissions */ + +/* additional permission flags for apr_file_copy and apr_file_append */ +#define APR_FPROT_FILE_SOURCE_PERMS 0x1000 /**< Copy source file's permissions */ + +/* backcompat */ +#define APR_USETID APR_FPROT_USETID /**< @deprecated @see APR_FPROT_USETID */ +#define APR_UREAD APR_FPROT_UREAD /**< @deprecated @see APR_FPROT_UREAD */ +#define APR_UWRITE APR_FPROT_UWRITE /**< @deprecated @see APR_FPROT_UWRITE */ +#define APR_UEXECUTE APR_FPROT_UEXECUTE /**< @deprecated @see APR_FPROT_UEXECUTE */ +#define APR_GSETID APR_FPROT_GSETID /**< @deprecated @see APR_FPROT_GSETID */ +#define APR_GREAD APR_FPROT_GREAD /**< @deprecated @see APR_FPROT_GREAD */ +#define APR_GWRITE APR_FPROT_GWRITE /**< @deprecated @see APR_FPROT_GWRITE */ +#define APR_GEXECUTE APR_FPROT_GEXECUTE /**< @deprecated @see APR_FPROT_GEXECUTE */ +#define APR_WSTICKY APR_FPROT_WSTICKY /**< @deprecated @see APR_FPROT_WSTICKY */ +#define APR_WREAD APR_FPROT_WREAD /**< @deprecated @see APR_FPROT_WREAD */ +#define APR_WWRITE APR_FPROT_WWRITE /**< @deprecated @see APR_FPROT_WWRITE */ +#define APR_WEXECUTE APR_FPROT_WEXECUTE /**< @deprecated @see APR_FPROT_WEXECUTE */ +#define APR_OS_DEFAULT APR_FPROT_OS_DEFAULT /**< @deprecated @see APR_FPROT_OS_DEFAULT */ +#define APR_FILE_SOURCE_PERMS APR_FPROT_FILE_SOURCE_PERMS /**< @deprecated @see APR_FPROT_FILE_SOURCE_PERMS */ + +/** @} */ + + +/** + * Structure for referencing directories. + */ +typedef struct apr_dir_t apr_dir_t; +/** + * Structure for determining file permissions. + */ +typedef apr_int32_t apr_fileperms_t; +#if (defined WIN32) || (defined NETWARE) +/** + * Structure for determining the device the file is on. + */ +typedef apr_uint32_t apr_dev_t; +#else +/** + * Structure for determining the device the file is on. + */ +typedef dev_t apr_dev_t; +#endif + +/** + * @defgroup apr_file_stat Stat Functions + * @{ + */ +/** file info structure */ +typedef struct apr_finfo_t apr_finfo_t; + +#define APR_FINFO_LINK 0x00000001 /**< Stat the link not the file itself if it is a link */ +#define APR_FINFO_MTIME 0x00000010 /**< Modification Time */ +#define APR_FINFO_CTIME 0x00000020 /**< Creation or inode-changed time */ +#define APR_FINFO_ATIME 0x00000040 /**< Access Time */ +#define APR_FINFO_SIZE 0x00000100 /**< Size of the file */ +#define APR_FINFO_CSIZE 0x00000200 /**< Storage size consumed by the file */ +#define APR_FINFO_DEV 0x00001000 /**< Device */ +#define APR_FINFO_INODE 0x00002000 /**< Inode */ +#define APR_FINFO_NLINK 0x00004000 /**< Number of links */ +#define APR_FINFO_TYPE 0x00008000 /**< Type */ +#define APR_FINFO_USER 0x00010000 /**< User */ +#define APR_FINFO_GROUP 0x00020000 /**< Group */ +#define APR_FINFO_UPROT 0x00100000 /**< User protection bits */ +#define APR_FINFO_GPROT 0x00200000 /**< Group protection bits */ +#define APR_FINFO_WPROT 0x00400000 /**< World protection bits */ +#define APR_FINFO_ICASE 0x01000000 /**< if dev is case insensitive */ +#define APR_FINFO_NAME 0x02000000 /**< ->name in proper case */ + +#define APR_FINFO_MIN 0x00008170 /**< type, mtime, ctime, atime, size */ +#define APR_FINFO_IDENT 0x00003000 /**< dev and inode */ +#define APR_FINFO_OWNER 0x00030000 /**< user and group */ +#define APR_FINFO_PROT 0x00700000 /**< all protections */ +#define APR_FINFO_NORM 0x0073b170 /**< an atomic unix apr_stat() */ +#define APR_FINFO_DIRENT 0x02000000 /**< an atomic unix apr_dir_read() */ + +/** + * The file information structure. This is analogous to the POSIX + * stat structure. + */ +struct apr_finfo_t { + /** Allocates memory and closes lingering handles in the specified pool */ + apr_pool_t *pool; + /** The bitmask describing valid fields of this apr_finfo_t structure + * including all available 'wanted' fields and potentially more */ + apr_int32_t valid; + /** The access permissions of the file. Mimics Unix access rights. */ + apr_fileperms_t protection; + /** The type of file. One of APR_REG, APR_DIR, APR_CHR, APR_BLK, APR_PIPE, + * APR_LNK or APR_SOCK. If the type is undetermined, the value is APR_NOFILE. + * If the type cannot be determined, the value is APR_UNKFILE. + */ + apr_filetype_e filetype; + /** The user id that owns the file */ + apr_uid_t user; + /** The group id that owns the file */ + apr_gid_t group; + /** The inode of the file. */ + apr_ino_t inode; + /** The id of the device the file is on. */ + apr_dev_t device; + /** The number of hard links to the file. */ + apr_int32_t nlink; + /** The size of the file */ + apr_off_t size; + /** The storage size consumed by the file */ + apr_off_t csize; + /** The time the file was last accessed */ + apr_time_t atime; + /** The time the file was last modified */ + apr_time_t mtime; + /** The time the file was created, or the inode was last changed */ + apr_time_t ctime; + /** The pathname of the file (possibly unrooted) */ + const char *fname; + /** The file's name (no path) in filesystem case */ + const char *name; + /** Unused */ + struct apr_file_t *filehand; +}; + +/** + * get the specified file's stats. The file is specified by filename, + * instead of using a pre-opened file. + * @param finfo Where to store the information about the file, which is + * never touched if the call fails. + * @param fname The name of the file to stat. + * @param wanted The desired apr_finfo_t fields, as a bit flag of APR_FINFO_ + values + * @param pool the pool to use to allocate the new file. + * + * @note If @c APR_INCOMPLETE is returned all the fields in @a finfo may + * not be filled in, and you need to check the @c finfo->valid bitmask + * to verify that what you're looking for is there. + */ +APR_DECLARE(apr_status_t) apr_stat(apr_finfo_t *finfo, const char *fname, + apr_int32_t wanted, apr_pool_t *pool); + +/** @} */ +/** + * @defgroup apr_dir Directory Manipulation Functions + * @{ + */ + +/** + * Open the specified directory. + * @param new_dir The opened directory descriptor. + * @param dirname The full path to the directory (use / on all systems) + * @param pool The pool to use. + */ +APR_DECLARE(apr_status_t) apr_dir_open(apr_dir_t **new_dir, + const char *dirname, + apr_pool_t *pool); + +/** + * close the specified directory. + * @param thedir the directory descriptor to close. + */ +APR_DECLARE(apr_status_t) apr_dir_close(apr_dir_t *thedir); + +/** + * Read the next entry from the specified directory. + * @param finfo the file info structure and filled in by apr_dir_read + * @param wanted The desired apr_finfo_t fields, as a bit flag of APR_FINFO_ + values + * @param thedir the directory descriptor returned from apr_dir_open + * @remark No ordering is guaranteed for the entries read. + * + * @note If @c APR_INCOMPLETE is returned all the fields in @a finfo may + * not be filled in, and you need to check the @c finfo->valid bitmask + * to verify that what you're looking for is there. When no more + * entries are available, APR_ENOENT is returned. + */ +APR_DECLARE(apr_status_t) apr_dir_read(apr_finfo_t *finfo, apr_int32_t wanted, + apr_dir_t *thedir); + +/** + * Rewind the directory to the first entry. + * @param thedir the directory descriptor to rewind. + */ +APR_DECLARE(apr_status_t) apr_dir_rewind(apr_dir_t *thedir); +/** @} */ + +/** + * @defgroup apr_filepath Filepath Manipulation Functions + * @{ + */ + +/** Cause apr_filepath_merge to fail if addpath is above rootpath + * @bug in APR 0.9 and 1.x, this flag's behavior is undefined + * if the rootpath is NULL or empty. In APR 2.0 this should be + * changed to imply NOTABSOLUTE if the rootpath is NULL or empty. + */ +#define APR_FILEPATH_NOTABOVEROOT 0x01 + +/** internal: Only meaningful with APR_FILEPATH_NOTABOVEROOT */ +#define APR_FILEPATH_SECUREROOTTEST 0x02 + +/** Cause apr_filepath_merge to fail if addpath is above rootpath, + * even given a rootpath /foo/bar and an addpath ../bar/bash + */ +#define APR_FILEPATH_SECUREROOT 0x03 + +/** Fail apr_filepath_merge if the merged path is relative */ +#define APR_FILEPATH_NOTRELATIVE 0x04 + +/** Fail apr_filepath_merge if the merged path is absolute */ +#define APR_FILEPATH_NOTABSOLUTE 0x08 + +/** Return the file system's native path format (e.g. path delimiters + * of ':' on MacOS9, '\' on Win32, etc.) */ +#define APR_FILEPATH_NATIVE 0x10 + +/** Resolve the true case of existing directories and file elements + * of addpath, (resolving any aliases on Win32) and append a proper + * trailing slash if a directory + */ +#define APR_FILEPATH_TRUENAME 0x20 + +/** + * Extract the rootpath from the given filepath + * @param rootpath the root file path returned with APR_SUCCESS or APR_EINCOMPLETE + * @param filepath the pathname to parse for its root component + * @param flags the desired rules to apply, from + *
+ *      APR_FILEPATH_NATIVE    Use native path separators (e.g. '\' on Win32)
+ *      APR_FILEPATH_TRUENAME  Tests that the root exists, and makes it proper
+ * 
+ * @param p the pool to allocate the new path string from + * @remark on return, filepath points to the first non-root character in the + * given filepath. In the simplest example, given a filepath of "/foo", + * returns the rootpath of "/" and filepath points at "foo". This is far + * more complex on other platforms, which will canonicalize the root form + * to a consistant format, given the APR_FILEPATH_TRUENAME flag, and also + * test for the validity of that root (e.g., that a drive d:/ or network + * share //machine/foovol/). + * The function returns APR_ERELATIVE if filepath isn't rooted (an + * error), APR_EINCOMPLETE if the root path is ambiguous (but potentially + * legitimate, e.g. "/" on Windows is incomplete because it doesn't specify + * the drive letter), or APR_EBADPATH if the root is simply invalid. + * APR_SUCCESS is returned if filepath is an absolute path. + */ +APR_DECLARE(apr_status_t) apr_filepath_root(const char **rootpath, + const char **filepath, + apr_int32_t flags, + apr_pool_t *p); + +/** + * Merge additional file path onto the previously processed rootpath + * @param newpath the merged paths returned + * @param rootpath the root file path (NULL uses the current working path) + * @param addpath the path to add to the root path + * @param flags the desired APR_FILEPATH_ rules to apply when merging + * @param p the pool to allocate the new path string from + * @remark if the flag APR_FILEPATH_TRUENAME is given, and the addpath + * contains wildcard characters ('*', '?') on platforms that don't support + * such characters within filenames, the paths will be merged, but the + * result code will be APR_EPATHWILD, and all further segments will not + * reflect the true filenames including the wildcard and following segments. + */ +APR_DECLARE(apr_status_t) apr_filepath_merge(char **newpath, + const char *rootpath, + const char *addpath, + apr_int32_t flags, + apr_pool_t *p); + +/** + * Split a search path into separate components + * @param pathelts the returned components of the search path + * @param liststr the search path (e.g., getenv("PATH")) + * @param p the pool to allocate the array and path components from + * @remark empty path components do not become part of @a pathelts. + * @remark the path separator in @a liststr is system specific; + * e.g., ':' on Unix, ';' on Windows, etc. + */ +APR_DECLARE(apr_status_t) apr_filepath_list_split(apr_array_header_t **pathelts, + const char *liststr, + apr_pool_t *p); + +/** + * Merge a list of search path components into a single search path + * @param liststr the returned search path; may be NULL if @a pathelts is empty + * @param pathelts the components of the search path + * @param p the pool to allocate the search path from + * @remark emtpy strings in the source array are ignored. + * @remark the path separator in @a liststr is system specific; + * e.g., ':' on Unix, ';' on Windows, etc. + */ +APR_DECLARE(apr_status_t) apr_filepath_list_merge(char **liststr, + apr_array_header_t *pathelts, + apr_pool_t *p); + +/** + * Return the default file path (for relative file names) + * @param path the default path string returned + * @param flags optional flag APR_FILEPATH_NATIVE to retrieve the + * default file path in os-native format. + * @param p the pool to allocate the default path string from + */ +APR_DECLARE(apr_status_t) apr_filepath_get(char **path, apr_int32_t flags, + apr_pool_t *p); + +/** + * Set the default file path (for relative file names) + * @param path the default path returned + * @param p the pool to allocate any working storage + */ +APR_DECLARE(apr_status_t) apr_filepath_set(const char *path, apr_pool_t *p); + +/** The FilePath character encoding is unknown */ +#define APR_FILEPATH_ENCODING_UNKNOWN 0 + +/** The FilePath character encoding is locale-dependent */ +#define APR_FILEPATH_ENCODING_LOCALE 1 + +/** The FilePath character encoding is UTF-8 */ +#define APR_FILEPATH_ENCODING_UTF8 2 + +/** + * Determine the encoding used internally by the FilePath functions + * @param style points to a variable which receives the encoding style flag + * @param p the pool to allocate any working storage + * @remark Use apr_os_locale_encoding() and/or apr_os_default_encoding() + * to get the name of the path encoding if it's not UTF-8. + */ +APR_DECLARE(apr_status_t) apr_filepath_encoding(int *style, apr_pool_t *p); +/** @} */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_FILE_INFO_H */ diff --git a/c/dependencies/macos/apr/include/apr_file_io.h b/c/dependencies/macos/apr/include/apr_file_io.h new file mode 100644 index 00000000..af931939 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_file_io.h @@ -0,0 +1,1005 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_FILE_IO_H +#define APR_FILE_IO_H + +/** + * @file apr_file_io.h + * @brief APR File I/O Handling + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_time.h" +#include "apr_errno.h" +#include "apr_file_info.h" +#include "apr_inherit.h" + +#define APR_WANT_STDIO /**< for SEEK_* */ +#define APR_WANT_IOVEC /**< for apr_file_writev */ +#include "apr_want.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_file_io File I/O Handling Functions + * @ingroup APR + * @{ + */ + +/** + * @defgroup apr_file_open_flags File Open Flags/Routines + * @{ + */ + +/* Note to implementors: Values in the range 0x00100000--0x80000000 + are reserved for platform-specific values. */ + +#define APR_FOPEN_READ 0x00001 /**< Open the file for reading */ +#define APR_FOPEN_WRITE 0x00002 /**< Open the file for writing */ +#define APR_FOPEN_CREATE 0x00004 /**< Create the file if not there */ +#define APR_FOPEN_APPEND 0x00008 /**< Append to the end of the file */ +#define APR_FOPEN_TRUNCATE 0x00010 /**< Open the file and truncate + to 0 length */ +#define APR_FOPEN_BINARY 0x00020 /**< Open the file in binary mode + (This flag is ignored on UNIX + because it has no meaning)*/ +#define APR_FOPEN_EXCL 0x00040 /**< Open should fail if #APR_FOPEN_CREATE + and file exists. */ +#define APR_FOPEN_BUFFERED 0x00080 /**< Open the file for buffered I/O */ +#define APR_FOPEN_DELONCLOSE 0x00100 /**< Delete the file after close */ +#define APR_FOPEN_XTHREAD 0x00200 /**< Platform dependent tag to open + the file for use across multiple + threads */ +#define APR_FOPEN_SHARELOCK 0x00400 /**< Platform dependent support for + higher level locked read/write + access to support writes across + process/machines */ +#define APR_FOPEN_NOCLEANUP 0x00800 /**< Do not register a cleanup + when the file is opened. The + apr_os_file_t handle in apr_file_t + will not be closed when the pool + is destroyed. */ +#define APR_FOPEN_SENDFILE_ENABLED 0x01000 /**< Advisory flag that this + file should support + apr_socket_sendfile operation */ +#define APR_FOPEN_LARGEFILE 0x04000 /**< Platform dependent flag to enable + * large file support, see WARNING below + */ +#define APR_FOPEN_SPARSE 0x08000 /**< Platform dependent flag to enable + * sparse file support, see WARNING below + */ +#define APR_FOPEN_NONBLOCK 0x40000 /**< Platform dependent flag to enable + * non blocking file io */ + + +/* backcompat */ +#define APR_READ APR_FOPEN_READ /**< @deprecated @see APR_FOPEN_READ */ +#define APR_WRITE APR_FOPEN_WRITE /**< @deprecated @see APR_FOPEN_WRITE */ +#define APR_CREATE APR_FOPEN_CREATE /**< @deprecated @see APR_FOPEN_CREATE */ +#define APR_APPEND APR_FOPEN_APPEND /**< @deprecated @see APR_FOPEN_APPEND */ +#define APR_TRUNCATE APR_FOPEN_TRUNCATE /**< @deprecated @see APR_FOPEN_TRUNCATE */ +#define APR_BINARY APR_FOPEN_BINARY /**< @deprecated @see APR_FOPEN_BINARY */ +#define APR_EXCL APR_FOPEN_EXCL /**< @deprecated @see APR_FOPEN_EXCL */ +#define APR_BUFFERED APR_FOPEN_BUFFERED /**< @deprecated @see APR_FOPEN_BUFFERED */ +#define APR_DELONCLOSE APR_FOPEN_DELONCLOSE /**< @deprecated @see APR_FOPEN_DELONCLOSE */ +#define APR_XTHREAD APR_FOPEN_XTHREAD /**< @deprecated @see APR_FOPEN_XTHREAD */ +#define APR_SHARELOCK APR_FOPEN_SHARELOCK /**< @deprecated @see APR_FOPEN_SHARELOCK */ +#define APR_FILE_NOCLEANUP APR_FOPEN_NOCLEANUP /**< @deprecated @see APR_FOPEN_NOCLEANUP */ +#define APR_SENDFILE_ENABLED APR_FOPEN_SENDFILE_ENABLED /**< @deprecated @see APR_FOPEN_SENDFILE_ENABLED */ +#define APR_LARGEFILE APR_FOPEN_LARGEFILE /**< @deprecated @see APR_FOPEN_LARGEFILE */ + +/** @def APR_FOPEN_LARGEFILE + * @warning APR_FOPEN_LARGEFILE flag only has effect on some + * platforms where sizeof(apr_off_t) == 4. Where implemented, it + * allows opening and writing to a file which exceeds the size which + * can be represented by apr_off_t (2 gigabytes). When a file's size + * does exceed 2Gb, apr_file_info_get() will fail with an error on the + * descriptor, likewise apr_stat()/apr_lstat() will fail on the + * filename. apr_dir_read() will fail with #APR_INCOMPLETE on a + * directory entry for a large file depending on the particular + * APR_FINFO_* flags. Generally, it is not recommended to use this + * flag. + * + * @def APR_FOPEN_SPARSE + * @warning APR_FOPEN_SPARSE may, depending on platform, convert a + * normal file to a sparse file. Some applications may be unable + * to decipher a sparse file, so it's critical that the sparse file + * flag should only be used for files accessed only by APR or other + * applications known to be able to decipher them. APR does not + * guarantee that it will compress the file into sparse segments + * if it was previously created and written without the sparse flag. + * On platforms which do not understand, or on file systems which + * cannot handle sparse files, the flag is ignored by apr_file_open(). + * + * @def APR_FOPEN_NONBLOCK + * @warning APR_FOPEN_NONBLOCK is not implemented on all platforms. + * Callers should be prepared for it to fail with #APR_ENOTIMPL. + */ + +/** @} */ + +/** + * @defgroup apr_file_seek_flags File Seek Flags + * @{ + */ + +/* flags for apr_file_seek */ +/** Set the file position */ +#define APR_SET SEEK_SET +/** Current */ +#define APR_CUR SEEK_CUR +/** Go to end of file */ +#define APR_END SEEK_END +/** @} */ + +/** + * @defgroup apr_file_attrs_set_flags File Attribute Flags + * @{ + */ + +/* flags for apr_file_attrs_set */ +#define APR_FILE_ATTR_READONLY 0x01 /**< File is read-only */ +#define APR_FILE_ATTR_EXECUTABLE 0x02 /**< File is executable */ +#define APR_FILE_ATTR_HIDDEN 0x04 /**< File is hidden */ +/** @} */ + +/** + * @defgroup apr_file_writev{_full} max iovec size + * @{ + */ +#if defined(DOXYGEN) +#define APR_MAX_IOVEC_SIZE 1024 /**< System dependent maximum + size of an iovec array */ +#elif defined(IOV_MAX) +#define APR_MAX_IOVEC_SIZE IOV_MAX +#elif defined(MAX_IOVEC) +#define APR_MAX_IOVEC_SIZE MAX_IOVEC +#else +#define APR_MAX_IOVEC_SIZE 1024 +#endif +/** @} */ + +/** File attributes */ +typedef apr_uint32_t apr_fileattrs_t; + +/** Type to pass as whence argument to apr_file_seek. */ +typedef int apr_seek_where_t; + +/** + * Structure for referencing files. + */ +typedef struct apr_file_t apr_file_t; + +/* File lock types/flags */ +/** + * @defgroup apr_file_lock_types File Lock Types + * @{ + */ + +#define APR_FLOCK_SHARED 1 /**< Shared lock. More than one process + or thread can hold a shared lock + at any given time. Essentially, + this is a "read lock", preventing + writers from establishing an + exclusive lock. */ +#define APR_FLOCK_EXCLUSIVE 2 /**< Exclusive lock. Only one process + may hold an exclusive lock at any + given time. This is analogous to + a "write lock". */ + +#define APR_FLOCK_TYPEMASK 0x000F /**< mask to extract lock type */ +#define APR_FLOCK_NONBLOCK 0x0010 /**< do not block while acquiring the + file lock */ +/** @} */ + +/** + * Open the specified file. + * @param newf The opened file descriptor. + * @param fname The full path to the file (using / on all systems) + * @param flag Or'ed value of: + * @li #APR_FOPEN_READ open for reading + * @li #APR_FOPEN_WRITE open for writing + * @li #APR_FOPEN_CREATE create the file if not there + * @li #APR_FOPEN_APPEND file ptr is set to end prior to all writes + * @li #APR_FOPEN_TRUNCATE set length to zero if file exists + * @li #APR_FOPEN_BINARY not a text file + * @li #APR_FOPEN_BUFFERED buffer the data. Default is non-buffered + * @li #APR_FOPEN_EXCL return error if #APR_FOPEN_CREATE and file exists + * @li #APR_FOPEN_DELONCLOSE delete the file after closing + * @li #APR_FOPEN_XTHREAD Platform dependent tag to open the file + * for use across multiple threads + * @li #APR_FOPEN_SHARELOCK Platform dependent support for higher + * level locked read/write access to support + * writes across process/machines + * @li #APR_FOPEN_NOCLEANUP Do not register a cleanup with the pool + * passed in on the @a pool argument (see below) + * @li #APR_FOPEN_SENDFILE_ENABLED Open with appropriate platform semantics + * for sendfile operations. Advisory only, + * apr_socket_sendfile does not check this flag + * @li #APR_FOPEN_LARGEFILE Platform dependent flag to enable large file + * support, see WARNING below + * @li #APR_FOPEN_SPARSE Platform dependent flag to enable sparse file + * support, see WARNING below + * @li #APR_FOPEN_NONBLOCK Platform dependent flag to enable + * non blocking file io + * @param perm Access permissions for file. + * @param pool The pool to use. + * @remark If perm is #APR_FPROT_OS_DEFAULT and the file is being created, + * appropriate default permissions will be used. + * @remark By default, the returned file descriptor will not be + * inherited by child processes created by apr_proc_create(). This + * can be changed using apr_file_inherit_set(). + */ +APR_DECLARE(apr_status_t) apr_file_open(apr_file_t **newf, const char *fname, + apr_int32_t flag, apr_fileperms_t perm, + apr_pool_t *pool); + +/** + * Close the specified file. + * @param file The file descriptor to close. + */ +APR_DECLARE(apr_status_t) apr_file_close(apr_file_t *file); + +/** + * Delete the specified file. + * @param path The full path to the file (using / on all systems) + * @param pool The pool to use. + * @remark If the file is open, it won't be removed until all + * instances are closed. + */ +APR_DECLARE(apr_status_t) apr_file_remove(const char *path, apr_pool_t *pool); + +/** + * Rename the specified file. + * @param from_path The full path to the original file (using / on all systems) + * @param to_path The full path to the new file (using / on all systems) + * @param pool The pool to use. + * @warning If a file exists at the new location, then it will be + * overwritten. Moving files or directories across devices may not be + * possible. + */ +APR_DECLARE(apr_status_t) apr_file_rename(const char *from_path, + const char *to_path, + apr_pool_t *pool); + +/** + * Create a hard link to the specified file. + * @param from_path The full path to the original file (using / on all systems) + * @param to_path The full path to the new file (using / on all systems) + * @remark Both files must reside on the same device. + */ +APR_DECLARE(apr_status_t) apr_file_link(const char *from_path, + const char *to_path); + +/** + * Copy the specified file to another file. + * @param from_path The full path to the original file (using / on all systems) + * @param to_path The full path to the new file (using / on all systems) + * @param perms Access permissions for the new file if it is created. + * In place of the usual or'd combination of file permissions, the + * value #APR_FPROT_FILE_SOURCE_PERMS may be given, in which case the source + * file's permissions are copied. + * @param pool The pool to use. + * @remark The new file does not need to exist, it will be created if required. + * @warning If the new file already exists, its contents will be overwritten. + */ +APR_DECLARE(apr_status_t) apr_file_copy(const char *from_path, + const char *to_path, + apr_fileperms_t perms, + apr_pool_t *pool); + +/** + * Append the specified file to another file. + * @param from_path The full path to the source file (use / on all systems) + * @param to_path The full path to the destination file (use / on all systems) + * @param perms Access permissions for the destination file if it is created. + * In place of the usual or'd combination of file permissions, the + * value #APR_FPROT_FILE_SOURCE_PERMS may be given, in which case the source + * file's permissions are copied. + * @param pool The pool to use. + * @remark The new file does not need to exist, it will be created if required. + * @remark Note that advanced filesystem permissions such as ACLs are not + * duplicated by this API. The target permissions (including duplicating the + * source file permissions) are assigned only when the target file does not yet + * exist. + */ +APR_DECLARE(apr_status_t) apr_file_append(const char *from_path, + const char *to_path, + apr_fileperms_t perms, + apr_pool_t *pool); + +/** + * Are we at the end of the file + * @param fptr The apr file we are testing. + * @remark Returns #APR_EOF if we are at the end of file, #APR_SUCCESS otherwise. + */ +APR_DECLARE(apr_status_t) apr_file_eof(apr_file_t *fptr); + +/** + * Open standard error as an apr file pointer. + * @param thefile The apr file to use as stderr. + * @param pool The pool to allocate the file out of. + * + * @remark The only reason that the apr_file_open_std* functions exist + * is that you may not always have a stderr/out/in on Windows. This + * is generally a problem with newer versions of Windows and services. + * + * @remark The other problem is that the C library functions generally work + * differently on Windows and Unix. So, by using apr_file_open_std* + * functions, you can get a handle to an APR struct that works with + * the APR functions which are supposed to work identically on all + * platforms. + */ +APR_DECLARE(apr_status_t) apr_file_open_stderr(apr_file_t **thefile, + apr_pool_t *pool); + +/** + * open standard output as an apr file pointer. + * @param thefile The apr file to use as stdout. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_stdout(apr_file_t **thefile, + apr_pool_t *pool); + +/** + * open standard input as an apr file pointer. + * @param thefile The apr file to use as stdin. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_stdin(apr_file_t **thefile, + apr_pool_t *pool); + +/** + * open standard error as an apr file pointer, with flags. + * @param thefile The apr file to use as stderr. + * @param flags The flags to open the file with. Only the + * @li #APR_FOPEN_EXCL + * @li #APR_FOPEN_BUFFERED + * @li #APR_FOPEN_XTHREAD + * @li #APR_FOPEN_SHARELOCK + * @li #APR_FOPEN_SENDFILE_ENABLED + * @li #APR_FOPEN_LARGEFILE + * + * flags should be used. The #APR_FOPEN_WRITE flag will + * be set unconditionally. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_flags_stderr(apr_file_t **thefile, + apr_int32_t flags, + apr_pool_t *pool); + +/** + * open standard output as an apr file pointer, with flags. + * @param thefile The apr file to use as stdout. + * @param flags The flags to open the file with. Only the + * @li #APR_FOPEN_EXCL + * @li #APR_FOPEN_BUFFERED + * @li #APR_FOPEN_XTHREAD + * @li #APR_FOPEN_SHARELOCK + * @li #APR_FOPEN_SENDFILE_ENABLED + * @li #APR_FOPEN_LARGEFILE + * + * flags should be used. The #APR_FOPEN_WRITE flag will + * be set unconditionally. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_flags_stdout(apr_file_t **thefile, + apr_int32_t flags, + apr_pool_t *pool); + +/** + * open standard input as an apr file pointer, with flags. + * @param thefile The apr file to use as stdin. + * @param flags The flags to open the file with. Only the + * @li #APR_FOPEN_EXCL + * @li #APR_FOPEN_BUFFERED + * @li #APR_FOPEN_XTHREAD + * @li #APR_FOPEN_SHARELOCK + * @li #APR_FOPEN_SENDFILE_ENABLED + * @li #APR_FOPEN_LARGEFILE + * + * flags should be used. The #APR_FOPEN_WRITE flag will + * be set unconditionally. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_flags_stdin(apr_file_t **thefile, + apr_int32_t flags, + apr_pool_t *pool); + +/** + * Read data from the specified file. + * @param thefile The file descriptor to read from. + * @param buf The buffer to store the data to. + * @param nbytes On entry, the number of bytes to read; on exit, the number + * of bytes read. + * + * @remark apr_file_read() will read up to the specified number of + * bytes, but never more. If there isn't enough data to fill that + * number of bytes, all of the available data is read. The third + * argument is modified to reflect the number of bytes read. If a + * char was put back into the stream via ungetc, it will be the first + * character returned. + * + * @remark It is not possible for both bytes to be read and an #APR_EOF + * or other error to be returned. #APR_EINTR is never returned. + */ +APR_DECLARE(apr_status_t) apr_file_read(apr_file_t *thefile, void *buf, + apr_size_t *nbytes); + +/** + * Write data to the specified file. + * @param thefile The file descriptor to write to. + * @param buf The buffer which contains the data. + * @param nbytes On entry, the number of bytes to write; on exit, the number + * of bytes written. + * + * @remark apr_file_write() will write up to the specified number of + * bytes, but never more. If the OS cannot write that many bytes, it + * will write as many as it can. The third argument is modified to + * reflect the * number of bytes written. + * + * @remark It is possible for both bytes to be written and an error to + * be returned. #APR_EINTR is never returned. + */ +APR_DECLARE(apr_status_t) apr_file_write(apr_file_t *thefile, const void *buf, + apr_size_t *nbytes); + +/** + * Write data from iovec array to the specified file. + * @param thefile The file descriptor to write to. + * @param vec The array from which to get the data to write to the file. + * @param nvec The number of elements in the struct iovec array. This must + * be smaller than #APR_MAX_IOVEC_SIZE. If it isn't, the function + * will fail with #APR_EINVAL. + * @param nbytes The number of bytes written. + * + * @remark It is possible for both bytes to be written and an error to + * be returned. #APR_EINTR is never returned. + * + * @remark apr_file_writev() is available even if the underlying + * operating system doesn't provide writev(). + */ +APR_DECLARE(apr_status_t) apr_file_writev(apr_file_t *thefile, + const struct iovec *vec, + apr_size_t nvec, apr_size_t *nbytes); + +/** + * Read data from the specified file, ensuring that the buffer is filled + * before returning. + * @param thefile The file descriptor to read from. + * @param buf The buffer to store the data to. + * @param nbytes The number of bytes to read. + * @param bytes_read If non-NULL, this will contain the number of bytes read. + * + * @remark apr_file_read_full() will read up to the specified number of + * bytes, but never more. If there isn't enough data to fill that + * number of bytes, then the process/thread will block until it is + * available or EOF is reached. If a char was put back into the + * stream via ungetc, it will be the first character returned. + * + * @remark It is possible for both bytes to be read and an error to be + * returned. And if *bytes_read is less than nbytes, an accompanying + * error is _always_ returned. + * + * @remark #APR_EINTR is never returned. + */ +APR_DECLARE(apr_status_t) apr_file_read_full(apr_file_t *thefile, void *buf, + apr_size_t nbytes, + apr_size_t *bytes_read); + +/** + * Write data to the specified file, ensuring that all of the data is + * written before returning. + * @param thefile The file descriptor to write to. + * @param buf The buffer which contains the data. + * @param nbytes The number of bytes to write. + * @param bytes_written If non-NULL, set to the number of bytes written. + * + * @remark apr_file_write_full() will write up to the specified number of + * bytes, but never more. If the OS cannot write that many bytes, the + * process/thread will block until they can be written. Exceptional + * error such as "out of space" or "pipe closed" will terminate with + * an error. + * + * @remark It is possible for both bytes to be written and an error to + * be returned. And if *bytes_written is less than nbytes, an + * accompanying error is _always_ returned. + * + * @remark #APR_EINTR is never returned. + */ +APR_DECLARE(apr_status_t) apr_file_write_full(apr_file_t *thefile, + const void *buf, + apr_size_t nbytes, + apr_size_t *bytes_written); + + +/** + * Write data from iovec array to the specified file, ensuring that all of the + * data is written before returning. + * @param thefile The file descriptor to write to. + * @param vec The array from which to get the data to write to the file. + * @param nvec The number of elements in the struct iovec array. This must + * be smaller than #APR_MAX_IOVEC_SIZE. If it isn't, the function + * will fail with #APR_EINVAL. + * @param nbytes The number of bytes written. + * + * @remark apr_file_writev_full() is available even if the underlying + * operating system doesn't provide writev(). + */ +APR_DECLARE(apr_status_t) apr_file_writev_full(apr_file_t *thefile, + const struct iovec *vec, + apr_size_t nvec, + apr_size_t *nbytes); +/** + * Write a character into the specified file. + * @param ch The character to write. + * @param thefile The file descriptor to write to + */ +APR_DECLARE(apr_status_t) apr_file_putc(char ch, apr_file_t *thefile); + +/** + * Read a character from the specified file. + * @param ch The character to read into + * @param thefile The file descriptor to read from + */ +APR_DECLARE(apr_status_t) apr_file_getc(char *ch, apr_file_t *thefile); + +/** + * Put a character back onto a specified stream. + * @param ch The character to write. + * @param thefile The file descriptor to write to + */ +APR_DECLARE(apr_status_t) apr_file_ungetc(char ch, apr_file_t *thefile); + +/** + * Read a line from the specified file + * @param str The buffer to store the string in. + * @param len The length of the string + * @param thefile The file descriptor to read from + * @remark The buffer will be NUL-terminated if any characters are stored. + * The newline at the end of the line will not be stripped. + */ +APR_DECLARE(apr_status_t) apr_file_gets(char *str, int len, + apr_file_t *thefile); + +/** + * Write the string into the specified file. + * @param str The string to write. + * @param thefile The file descriptor to write to + */ +APR_DECLARE(apr_status_t) apr_file_puts(const char *str, apr_file_t *thefile); + +/** + * Flush the file's buffer. + * @param thefile The file descriptor to flush + */ +APR_DECLARE(apr_status_t) apr_file_flush(apr_file_t *thefile); + +/** + * Transfer all file modified data and metadata to disk. + * @param thefile The file descriptor to sync + */ +APR_DECLARE(apr_status_t) apr_file_sync(apr_file_t *thefile); + +/** + * Transfer all file modified data to disk. + * @param thefile The file descriptor to sync + */ +APR_DECLARE(apr_status_t) apr_file_datasync(apr_file_t *thefile); + +/** + * Duplicate the specified file descriptor. + * @param new_file The structure to duplicate into. + * @param old_file The file to duplicate. + * @param p The pool to use for the new file. + * @remark *new_file must point to a valid apr_file_t, or point to NULL. + */ +APR_DECLARE(apr_status_t) apr_file_dup(apr_file_t **new_file, + apr_file_t *old_file, + apr_pool_t *p); + +/** + * Duplicate the specified file descriptor and close the original + * @param new_file The old file that is to be closed and reused + * @param old_file The file to duplicate + * @param p The pool to use for the new file + * + * @remark new_file MUST point at a valid apr_file_t. It cannot be NULL. + */ +APR_DECLARE(apr_status_t) apr_file_dup2(apr_file_t *new_file, + apr_file_t *old_file, + apr_pool_t *p); + +/** + * Move the specified file descriptor to a new pool + * @param new_file Pointer in which to return the new apr_file_t + * @param old_file The file to move + * @param p The pool to which the descriptor is to be moved + * @remark Unlike apr_file_dup2(), this function doesn't do an + * OS dup() operation on the underlying descriptor; it just + * moves the descriptor's apr_file_t wrapper to a new pool. + * @remark The new pool need not be an ancestor of old_file's pool. + * @remark After calling this function, old_file may not be used + */ +APR_DECLARE(apr_status_t) apr_file_setaside(apr_file_t **new_file, + apr_file_t *old_file, + apr_pool_t *p); + +/** + * Give the specified apr file handle a new buffer + * @param thefile The file handle that is to be modified + * @param buffer The buffer + * @param bufsize The size of the buffer + * @remark It is possible to add a buffer to previously unbuffered + * file handles, the #APR_FOPEN_BUFFERED flag will be added to + * the file handle's flags. Likewise, with buffer=NULL and + * bufsize=0 arguments it is possible to make a previously + * buffered file handle unbuffered. + */ +APR_DECLARE(apr_status_t) apr_file_buffer_set(apr_file_t *thefile, + char * buffer, + apr_size_t bufsize); + +/** + * Get the size of any buffer for the specified apr file handle + * @param thefile The file handle + */ +APR_DECLARE(apr_size_t) apr_file_buffer_size_get(apr_file_t *thefile); + +/** + * Move the read/write file offset to a specified byte within a file. + * @param thefile The file descriptor + * @param where How to move the pointer, one of: + * @li #APR_SET -- set the offset to offset + * @li #APR_CUR -- add the offset to the current position + * @li #APR_END -- add the offset to the current file size + * @param offset The offset to move the pointer to. + * @remark The third argument is modified to be the offset the pointer + was actually moved to. + */ +APR_DECLARE(apr_status_t) apr_file_seek(apr_file_t *thefile, + apr_seek_where_t where, + apr_off_t *offset); + +/** + * Create an anonymous pipe. + * @param in The newly created pipe's file for reading. + * @param out The newly created pipe's file for writing. + * @param pool The pool to operate on. + * @remark By default, the returned file descriptors will be inherited + * by child processes created using apr_proc_create(). This can be + * changed using apr_file_inherit_unset(). + * @bug Some platforms cannot toggle between blocking and nonblocking, + * and when passing a pipe as a standard handle to an application which + * does not expect it, a non-blocking stream will fluxor the client app. + * @deprecated @see apr_file_pipe_create_pools() + */ +APR_DECLARE(apr_status_t) apr_file_pipe_create(apr_file_t **in, + apr_file_t **out, + apr_pool_t *pool); + +/** + * Create an anonymous pipe which portably supports async timeout options. + * @param in The newly created pipe's file for reading. + * @param out The newly created pipe's file for writing. + * @param blocking one of these values defined in apr_thread_proc.h; + * @li #APR_FULL_BLOCK + * @li #APR_READ_BLOCK + * @li #APR_WRITE_BLOCK + * @li #APR_FULL_NONBLOCK + * @param pool The pool to operate on. + * @remark By default, the returned file descriptors will be inherited + * by child processes created using apr_proc_create(). This can be + * changed using apr_file_inherit_unset(). + * @remark Some platforms cannot toggle between blocking and nonblocking, + * and when passing a pipe as a standard handle to an application which + * does not expect it, a non-blocking stream will fluxor the client app. + * Use this function rather than apr_file_pipe_create() to create pipes + * where one or both ends require non-blocking semantics. + * @deprecated @see apr_file_pipe_create_pools() + */ +APR_DECLARE(apr_status_t) apr_file_pipe_create_ex(apr_file_t **in, + apr_file_t **out, + apr_int32_t blocking, + apr_pool_t *pool); + +/** + * Create an anonymous pipe which portably supports async timeout options, + * placing each side of the pipe in a different pool. + * @param in The newly created pipe's file for reading. + * @param out The newly created pipe's file for writing. + * @param blocking one of these values defined in apr_thread_proc.h; + * @li #APR_FULL_BLOCK + * @li #APR_READ_BLOCK + * @li #APR_WRITE_BLOCK + * @li #APR_FULL_NONBLOCK + * @param pool_in The pool for the reading pipe. + * @param pool_out The pool for the writing pipe. + * @remark By default, the returned file descriptors will be inherited + * by child processes created using apr_proc_create(). This can be + * changed using apr_file_inherit_unset(). + * @remark Some platforms cannot toggle between blocking and nonblocking, + * and when passing a pipe as a standard handle to an application which + * does not expect it, a non-blocking stream will fluxor the client app. + * Use this function rather than apr_file_pipe_create() to create pipes + * where one or both ends require non-blocking semantics. + */ +APR_DECLARE(apr_status_t) apr_file_pipe_create_pools(apr_file_t **in, + apr_file_t **out, + apr_int32_t blocking, + apr_pool_t *pool_in, + apr_pool_t *pool_out); + +/** + * Create a named pipe. + * @param filename The filename of the named pipe + * @param perm The permissions for the newly created pipe. + * @param pool The pool to operate on. + */ +APR_DECLARE(apr_status_t) apr_file_namedpipe_create(const char *filename, + apr_fileperms_t perm, + apr_pool_t *pool); + +/** + * Get the timeout value for a pipe or manipulate the blocking state. + * @param thepipe The pipe we are getting a timeout for. + * @param timeout The current timeout value in microseconds. + */ +APR_DECLARE(apr_status_t) apr_file_pipe_timeout_get(apr_file_t *thepipe, + apr_interval_time_t *timeout); + +/** + * Set the timeout value for a pipe or manipulate the blocking state. + * @param thepipe The pipe we are setting a timeout on. + * @param timeout The timeout value in microseconds. Values < 0 mean wait + * forever, 0 means do not wait at all. + */ +APR_DECLARE(apr_status_t) apr_file_pipe_timeout_set(apr_file_t *thepipe, + apr_interval_time_t timeout); + +/** file (un)locking functions. */ + +/** + * Establish a lock on the specified, open file. The lock may be advisory + * or mandatory, at the discretion of the platform. The lock applies to + * the file as a whole, rather than a specific range. Locks are established + * on a per-thread/process basis; a second lock by the same thread will not + * block. + * @param thefile The file to lock. + * @param type The type of lock to establish on the file. + */ +APR_DECLARE(apr_status_t) apr_file_lock(apr_file_t *thefile, int type); + +/** + * Remove any outstanding locks on the file. + * @param thefile The file to unlock. + */ +APR_DECLARE(apr_status_t) apr_file_unlock(apr_file_t *thefile); + +/**accessor and general file_io functions. */ + +/** + * return the file name of the current file. + * @param new_path The path of the file. + * @param thefile The currently open file. + */ +APR_DECLARE(apr_status_t) apr_file_name_get(const char **new_path, + apr_file_t *thefile); + +/** + * Return the data associated with the current file. + * @param data The user data associated with the file. + * @param key The key to use for retrieving data associated with this file. + * @param file The currently open file. + */ +APR_DECLARE(apr_status_t) apr_file_data_get(void **data, const char *key, + apr_file_t *file); + +/** + * Set the data associated with the current file. + * @param file The currently open file. + * @param data The user data to associate with the file. + * @param key The key to use for associating data with the file. + * @param cleanup The cleanup routine to use when the file is destroyed. + */ +APR_DECLARE(apr_status_t) apr_file_data_set(apr_file_t *file, void *data, + const char *key, + apr_status_t (*cleanup)(void *)); + +/** + * Write a string to a file using a printf format. + * @param fptr The file to write to. + * @param format The format string + * @param ... The values to substitute in the format string + * @return The number of bytes written + */ +APR_DECLARE_NONSTD(int) apr_file_printf(apr_file_t *fptr, + const char *format, ...) + __attribute__((format(printf,2,3))); + +/** + * set the specified file's permission bits. + * @param fname The file (name) to apply the permissions to. + * @param perms The permission bits to apply to the file. + * + * @warning Some platforms may not be able to apply all of the + * available permission bits; #APR_INCOMPLETE will be returned if some + * permissions are specified which could not be set. + * + * @warning Platforms which do not implement this feature will return + * #APR_ENOTIMPL. + */ +APR_DECLARE(apr_status_t) apr_file_perms_set(const char *fname, + apr_fileperms_t perms); + +/** + * Set attributes of the specified file. + * @param fname The full path to the file (using / on all systems) + * @param attributes Or'd combination of + * @li #APR_FILE_ATTR_READONLY - make the file readonly + * @li #APR_FILE_ATTR_EXECUTABLE - make the file executable + * @li #APR_FILE_ATTR_HIDDEN - make the file hidden + * @param attr_mask Mask of valid bits in attributes. + * @param pool the pool to use. + * @remark This function should be used in preference to explicit manipulation + * of the file permissions, because the operations to provide these + * attributes are platform specific and may involve more than simply + * setting permission bits. + * @warning Platforms which do not implement this feature will return + * #APR_ENOTIMPL. + */ +APR_DECLARE(apr_status_t) apr_file_attrs_set(const char *fname, + apr_fileattrs_t attributes, + apr_fileattrs_t attr_mask, + apr_pool_t *pool); + +/** + * Set the mtime of the specified file. + * @param fname The full path to the file (using / on all systems) + * @param mtime The mtime to apply to the file. + * @param pool The pool to use. + * @warning Platforms which do not implement this feature will return + * #APR_ENOTIMPL. + */ +APR_DECLARE(apr_status_t) apr_file_mtime_set(const char *fname, + apr_time_t mtime, + apr_pool_t *pool); + +/** + * Create a new directory on the file system. + * @param path the path for the directory to be created. (use / on all systems) + * @param perm Permissions for the new directory. + * @param pool the pool to use. + */ +APR_DECLARE(apr_status_t) apr_dir_make(const char *path, apr_fileperms_t perm, + apr_pool_t *pool); + +/** Creates a new directory on the file system, but behaves like + * 'mkdir -p'. Creates intermediate directories as required. No error + * will be reported if PATH already exists. + * @param path the path for the directory to be created. (use / on all systems) + * @param perm Permissions for the new directory. + * @param pool the pool to use. + */ +APR_DECLARE(apr_status_t) apr_dir_make_recursive(const char *path, + apr_fileperms_t perm, + apr_pool_t *pool); + +/** + * Remove directory from the file system. + * @param path the path for the directory to be removed. (use / on all systems) + * @param pool the pool to use. + * @remark Removing a directory which is in-use (e.g., the current working + * directory, or during apr_dir_read, or with an open file) is not portable. + */ +APR_DECLARE(apr_status_t) apr_dir_remove(const char *path, apr_pool_t *pool); + +/** + * get the specified file's stats. + * @param finfo Where to store the information about the file. + * @param wanted The desired apr_finfo_t fields, as a bit flag of APR_FINFO_* values + * @param thefile The file to get information about. + */ +APR_DECLARE(apr_status_t) apr_file_info_get(apr_finfo_t *finfo, + apr_int32_t wanted, + apr_file_t *thefile); + + +/** + * Truncate the file's length to the specified offset + * @param fp The file to truncate + * @param offset The offset to truncate to. + * @remark The read/write file offset is repositioned to offset. + */ +APR_DECLARE(apr_status_t) apr_file_trunc(apr_file_t *fp, apr_off_t offset); + +/** + * Retrieve the flags that were passed into apr_file_open() + * when the file was opened. + * @return apr_int32_t the flags + */ +APR_DECLARE(apr_int32_t) apr_file_flags_get(apr_file_t *f); + +/** + * Get the pool used by the file. + */ +APR_POOL_DECLARE_ACCESSOR(file); + +/** + * Set a file to be inherited by child processes. + * + */ +APR_DECLARE_INHERIT_SET(file); + +/** + * Unset a file from being inherited by child processes. + */ +APR_DECLARE_INHERIT_UNSET(file); + +/** + * Open a temporary file + * @param fp The apr file to use as a temporary file. + * @param templ The template to use when creating a temp file. + * @param flags The flags to open the file with. If this is zero, + * the file is opened with + * #APR_FOPEN_CREATE | #APR_FOPEN_READ | #APR_FOPEN_WRITE | + * #APR_FOPEN_EXCL | #APR_FOPEN_DELONCLOSE + * @param p The pool to allocate the file out of. + * @remark + * This function generates a unique temporary file name from template. + * The last six characters of template must be XXXXXX and these are replaced + * with a string that makes the filename unique. Since it will be modified, + * template must not be a string constant, but should be declared as a character + * array. + * + */ +APR_DECLARE(apr_status_t) apr_file_mktemp(apr_file_t **fp, char *templ, + apr_int32_t flags, apr_pool_t *p); + + +/** + * Find an existing directory suitable as a temporary storage location. + * @param temp_dir The temp directory. + * @param p The pool to use for any necessary allocations. + * @remark + * This function uses an algorithm to search for a directory that an + * an application can use for temporary storage. + * + */ +APR_DECLARE(apr_status_t) apr_temp_dir_get(const char **temp_dir, + apr_pool_t *p); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_FILE_IO_H */ diff --git a/c/dependencies/macos/apr/include/apr_fnmatch.h b/c/dependencies/macos/apr/include/apr_fnmatch.h new file mode 100644 index 00000000..e8f6b03c --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_fnmatch.h @@ -0,0 +1,153 @@ +/* + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)fnmatch.h 8.1 (Berkeley) 6/2/93 + */ + +/* This file has been modified by the Apache Software Foundation. */ +#ifndef _APR_FNMATCH_H_ +#define _APR_FNMATCH_H_ + +/** + * @file apr_fnmatch.h + * @brief APR FNMatch Functions + */ + +#include "apr_errno.h" +#include "apr_tables.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_fnmatch Filename Matching Functions + * @ingroup APR + * @{ + */ + +#define APR_FNM_NOMATCH 1 /**< Match failed. */ + +#define APR_FNM_NOESCAPE 0x01 /**< Disable backslash escaping. */ +#define APR_FNM_PATHNAME 0x02 /**< Slash must be matched by slash. */ +#define APR_FNM_PERIOD 0x04 /**< Period must be matched by period. */ +#define APR_FNM_CASE_BLIND 0x08 /**< Compare characters case-insensitively. */ + +/** + * Try to match the string to the given pattern, return APR_SUCCESS if + * match, else return APR_FNM_NOMATCH. Note that there is no such thing as + * an illegal pattern. + * + * With all flags unset, a pattern is interpreted as such: + * + * PATTERN: Backslash followed by any character, including another + * backslash.
+ * MATCHES: That character exactly. + * + *

+ * PATTERN: ?
+ * MATCHES: Any single character. + *

+ * + *

+ * PATTERN: *
+ * MATCHES: Any sequence of zero or more characters. (Note that multiple + * *s in a row are equivalent to one.) + * + * PATTERN: Any character other than \?*[ or a \ at the end of the pattern
+ * MATCHES: That character exactly. (Case sensitive.) + * + * PATTERN: [ followed by a class description followed by ]
+ * MATCHES: A single character described by the class description. + * (Never matches, if the class description reaches until the + * end of the string without a ].) If the first character of + * the class description is ^ or !, the sense of the description + * is reversed. The rest of the class description is a list of + * single characters or pairs of characters separated by -. Any + * of those characters can have a backslash in front of them, + * which is ignored; this lets you use the characters ] and - + * in the character class, as well as ^ and ! at the + * beginning. The pattern matches a single character if it + * is one of the listed characters or falls into one of the + * listed ranges (inclusive, case sensitive). Ranges with + * the first character larger than the second are legal but + * never match. Edge cases: [] never matches, and [^] and [!] + * always match without consuming a character. + * + * Note that these patterns attempt to match the entire string, not + * just find a substring matching the pattern. + * + * @param pattern The pattern to match to + * @param strings The string we are trying to match + * @param flags flags to use in the match. Bitwise OR of: + *

+ *              APR_FNM_NOESCAPE       Disable backslash escaping
+ *              APR_FNM_PATHNAME       Slash must be matched by slash
+ *              APR_FNM_PERIOD         Period must be matched by period
+ *              APR_FNM_CASE_BLIND     Compare characters case-insensitively.
+ * 
+ */ + +APR_DECLARE(apr_status_t) apr_fnmatch(const char *pattern, + const char *strings, int flags); + +/** + * Determine if the given pattern is a regular expression. + * @param pattern The pattern to search for glob characters. + * @return non-zero if pattern has any glob characters in it + */ +APR_DECLARE(int) apr_fnmatch_test(const char *pattern); + +/** + * Find all files that match a specified pattern in a directory. + * @param dir_pattern The pattern to use for finding files, appended + * to the search directory. The pattern is anything following the + * final forward or backward slash in the parameter. If no slash + * is found, the current directory is searched. + * @param result Array to use when storing the results + * @param p The pool to use. + * @return APR_SUCCESS if no processing errors occurred, APR error + * code otherwise + * @remark The returned array may be empty even if APR_SUCCESS was + * returned. + */ +APR_DECLARE(apr_status_t) apr_match_glob(const char *dir_pattern, + apr_array_header_t **result, + apr_pool_t *p); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !_APR_FNMATCH_H_ */ diff --git a/c/dependencies/macos/apr/include/apr_general.h b/c/dependencies/macos/apr/include/apr_general.h new file mode 100644 index 00000000..fa073c85 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_general.h @@ -0,0 +1,244 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_GENERAL_H +#define APR_GENERAL_H + +/** + * @file apr_general.h + * This is collection of oddballs that didn't fit anywhere else, + * and might move to more appropriate headers with the release + * of APR 1.0. + * @brief APR Miscellaneous library routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" + +#if APR_HAVE_SIGNAL_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_general Miscellaneous library routines + * @ingroup APR + * This is collection of oddballs that didn't fit anywhere else, + * and might move to more appropriate headers with the release + * of APR 1.0. + * @{ + */ + +/** FALSE */ +#ifndef FALSE +#define FALSE 0 +#endif +/** TRUE */ +#ifndef TRUE +#define TRUE (!FALSE) +#endif + +/** a space */ +#define APR_ASCII_BLANK '\040' +/** a carrige return */ +#define APR_ASCII_CR '\015' +/** a line feed */ +#define APR_ASCII_LF '\012' +/** a tab */ +#define APR_ASCII_TAB '\011' + +/** signal numbers typedef */ +typedef int apr_signum_t; + +/** + * Finding offsets of elements within structures. + * Taken from the X code... they've sweated portability of this stuff + * so we don't have to. Sigh... + * @param p_type pointer type name + * @param field data field within the structure pointed to + * @return offset + */ + +#if defined(CRAY) || (defined(__arm) && !(defined(LINUX) || defined(__FreeBSD__))) +#ifdef __STDC__ +#define APR_OFFSET(p_type,field) _Offsetof(p_type,field) +#else +#ifdef CRAY2 +#define APR_OFFSET(p_type,field) \ + (sizeof(int)*((unsigned int)&(((p_type)NULL)->field))) + +#else /* !CRAY2 */ + +#define APR_OFFSET(p_type,field) ((unsigned int)&(((p_type)NULL)->field)) + +#endif /* !CRAY2 */ +#endif /* __STDC__ */ +#else /* ! (CRAY || __arm) */ + +#define APR_OFFSET(p_type,field) \ + ((long) (((char *) (&(((p_type)NULL)->field))) - ((char *) NULL))) + +#endif /* !CRAY */ + +/** + * Finding offsets of elements within structures. + * @param s_type structure type name + * @param field data field within the structure + * @return offset + */ +#if defined(offsetof) && !defined(__cplusplus) +#define APR_OFFSETOF(s_type,field) offsetof(s_type,field) +#else +#define APR_OFFSETOF(s_type,field) APR_OFFSET(s_type*,field) +#endif + +#ifndef DOXYGEN + +/* A couple of prototypes for functions in case some platform doesn't + * have it + */ +#if (!APR_HAVE_STRCASECMP) && (APR_HAVE_STRICMP) +#define strcasecmp(s1, s2) stricmp(s1, s2) +#elif (!APR_HAVE_STRCASECMP) +int strcasecmp(const char *a, const char *b); +#endif + +#if (!APR_HAVE_STRNCASECMP) && (APR_HAVE_STRNICMP) +#define strncasecmp(s1, s2, n) strnicmp(s1, s2, n) +#elif (!APR_HAVE_STRNCASECMP) +int strncasecmp(const char *a, const char *b, size_t n); +#endif + +#endif + +/** + * Alignment macros + */ + +/* APR_ALIGN() is only to be used to align on a power of 2 boundary */ +#define APR_ALIGN(size, boundary) \ + (((size) + ((boundary) - 1)) & ~((boundary) - 1)) + +/** Default alignment */ +#define APR_ALIGN_DEFAULT(size) APR_ALIGN(size, 8) + + +/** + * String and memory functions + */ + +/* APR_STRINGIFY is defined here, and also in apr_release.h, so wrap it */ +#ifndef APR_STRINGIFY +/** Properly quote a value as a string in the C preprocessor */ +#define APR_STRINGIFY(n) APR_STRINGIFY_HELPER(n) +/** Helper macro for APR_STRINGIFY */ +#define APR_STRINGIFY_HELPER(n) #n +#endif + +#if (!APR_HAVE_MEMMOVE) +#define memmove(a,b,c) bcopy(b,a,c) +#endif + +#if (!APR_HAVE_MEMCHR) +void *memchr(const void *s, int c, size_t n); +#endif + +/** @} */ + +/** + * @defgroup apr_library Library initialization and termination + * @{ + */ + +/** + * Setup any APR internal data structures. This MUST be the first function + * called for any APR library. It is safe to call apr_initialize several + * times as long as apr_terminate() is called the same number of times. + * @remark See apr_app_initialize() if this is an application, rather than + * a library consumer of apr. + */ +APR_DECLARE(apr_status_t) apr_initialize(void); + +/** + * Set up an application with normalized argc, argv (and optionally env) in + * order to deal with platform-specific oddities, such as Win32 services, + * code pages and signals. This must be the first function called for any + * APR program. + * @param argc Pointer to the argc that may be corrected + * @param argv Pointer to the argv that may be corrected + * @param env Pointer to the env that may be corrected, may be NULL + * @remark See apr_initialize() if this is a library consumer of apr. + * Otherwise, this call is identical to apr_initialize(), and must be closed + * with a call to apr_terminate() at the end of program execution. + */ +APR_DECLARE(apr_status_t) apr_app_initialize(int *argc, + char const * const * *argv, + char const * const * *env); + +/** + * Tear down any APR internal data structures which aren't torn down + * automatically. apr_terminate must be called once for every call to + * apr_initialize() or apr_app_initialize(). + * @remark An APR program must call this function at termination once it + * has stopped using APR services. The APR developers suggest using + * @c atexit(apr_terminate) to ensure this is called. When using APR + * from a language other than C that has problems with the calling + * convention, use apr_terminate2() instead. + * @see apr_terminate2 + */ +APR_DECLARE_NONSTD(void) apr_terminate(void); + +/** + * Tear down any APR internal data structures which aren't torn down + * automatically, same as apr_terminate() + * @remark An APR program must call either the apr_terminate() or apr_terminate2 + * function once it it has finished using APR services. The APR + * developers suggest using @c atexit(apr_terminate) to ensure this is done. + * apr_terminate2 exists to allow non-c language apps to tear down apr, + * while apr_terminate() is recommended from c language applications. + */ +APR_DECLARE(void) apr_terminate2(void); + +/** @} */ + +/** + * @defgroup apr_random Random Functions + * @{ + */ + +#if APR_HAS_RANDOM || defined(DOXYGEN) + +/* TODO: I'm not sure this is the best place to put this prototype...*/ +/** + * Generate random bytes. + * @param buf Buffer to fill with random bytes + * @param length Length of buffer in bytes + */ +APR_DECLARE(apr_status_t) apr_generate_random_bytes(unsigned char * buf, + apr_size_t length); + +#endif +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_GENERAL_H */ diff --git a/c/dependencies/macos/apr/include/apr_getopt.h b/c/dependencies/macos/apr/include/apr_getopt.h new file mode 100644 index 00000000..75ad5663 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_getopt.h @@ -0,0 +1,160 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_GETOPT_H +#define APR_GETOPT_H + +/** + * @file apr_getopt.h + * @brief APR Command Arguments (getopt) + */ + +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_getopt Command Argument Parsing + * @ingroup APR + * @{ + */ + +/** + * An @c apr_getopt_t error callback function. + * + * @a arg is this @c apr_getopt_t's @c errarg member. + */ +typedef void (apr_getopt_err_fn_t)(void *arg, const char *err, ...); + +/** @see apr_getopt_t */ +typedef struct apr_getopt_t apr_getopt_t; + +/** + * Structure to store command line argument information. + */ +struct apr_getopt_t { + /** context for processing */ + apr_pool_t *cont; + /** function to print error message (NULL == no messages) */ + apr_getopt_err_fn_t *errfn; + /** user defined first arg to pass to error message */ + void *errarg; + /** index into parent argv vector */ + int ind; + /** character checked for validity */ + int opt; + /** reset getopt */ + int reset; + /** count of arguments */ + int argc; + /** array of pointers to arguments */ + const char **argv; + /** argument associated with option */ + char const* place; + /** set to nonzero to support interleaving options with regular args */ + int interleave; + /** start of non-option arguments skipped for interleaving */ + int skip_start; + /** end of non-option arguments skipped for interleaving */ + int skip_end; +}; + +/** @see apr_getopt_option_t */ +typedef struct apr_getopt_option_t apr_getopt_option_t; + +/** + * Structure used to describe options that getopt should search for. + */ +struct apr_getopt_option_t { + /** long option name, or NULL if option has no long name */ + const char *name; + /** option letter, or a value greater than 255 if option has no letter */ + int optch; + /** nonzero if option takes an argument */ + int has_arg; + /** a description of the option */ + const char *description; +}; + +/** + * Initialize the arguments for parsing by apr_getopt(). + * @param os The options structure created for apr_getopt() + * @param cont The pool to operate on + * @param argc The number of arguments to parse + * @param argv The array of arguments to parse + * @remark Arguments 3 and 4 are most commonly argc and argv from main(argc, argv) + * The (*os)->errfn is initialized to fprintf(stderr... but may be overridden. + */ +APR_DECLARE(apr_status_t) apr_getopt_init(apr_getopt_t **os, apr_pool_t *cont, + int argc, const char * const *argv); + +/** + * Parse the options initialized by apr_getopt_init(). + * @param os The apr_opt_t structure returned by apr_getopt_init() + * @param opts A string of characters that are acceptable options to the + * program. Characters followed by ":" are required to have an + * option associated + * @param option_ch The next option character parsed + * @param option_arg The argument following the option character: + * @return There are four potential status values on exit. They are: + *
+ *             APR_EOF      --  No more options to parse
+ *             APR_BADCH    --  Found a bad option character
+ *             APR_BADARG   --  No argument followed the option flag
+ *             APR_SUCCESS  --  The next option was found.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_getopt(apr_getopt_t *os, const char *opts, + char *option_ch, const char **option_arg); + +/** + * Parse the options initialized by apr_getopt_init(), accepting long + * options beginning with "--" in addition to single-character + * options beginning with "-". + * @param os The apr_getopt_t structure created by apr_getopt_init() + * @param opts A pointer to a list of apr_getopt_option_t structures, which + * can be initialized with { "name", optch, has_args }. has_args + * is nonzero if the option requires an argument. A structure + * with an optch value of 0 terminates the list. + * @param option_ch Receives the value of "optch" from the apr_getopt_option_t + * structure corresponding to the next option matched. + * @param option_arg Receives the argument following the option, if any. + * @return There are four potential status values on exit. They are: + *
+ *             APR_EOF      --  No more options to parse
+ *             APR_BADCH    --  Found a bad option character
+ *             APR_BADARG   --  No argument followed the option flag
+ *             APR_SUCCESS  --  The next option was found.
+ * 
+ * When APR_SUCCESS is returned, os->ind gives the index of the first + * non-option argument. On error, a message will be printed to stdout unless + * os->err is set to 0. If os->interleave is set to nonzero, options can come + * after arguments, and os->argv will be permuted to leave non-option arguments + * at the end (the original argv is unaffected). + */ +APR_DECLARE(apr_status_t) apr_getopt_long(apr_getopt_t *os, + const apr_getopt_option_t *opts, + int *option_ch, + const char **option_arg); +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_GETOPT_H */ diff --git a/c/dependencies/macos/apr/include/apr_global_mutex.h b/c/dependencies/macos/apr/include/apr_global_mutex.h new file mode 100644 index 00000000..e3cba23f --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_global_mutex.h @@ -0,0 +1,195 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_GLOBAL_MUTEX_H +#define APR_GLOBAL_MUTEX_H + +/** + * @file apr_global_mutex.h + * @brief APR Global Locking Routines + */ + +#include "apr.h" +#include "apr_proc_mutex.h" /* only for apr_lockmech_e */ +#include "apr_pools.h" +#include "apr_errno.h" +#if APR_PROC_MUTEX_IS_GLOBAL +#include "apr_proc_mutex.h" +#endif +#include "apr_time.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_GlobalMutex Global Locking Routines + * @ingroup APR + * @{ + */ + +#if !APR_PROC_MUTEX_IS_GLOBAL || defined(DOXYGEN) + +/** Opaque global mutex structure. */ +typedef struct apr_global_mutex_t apr_global_mutex_t; + +/* Function definitions */ + +/** + * Create and initialize a mutex that can be used to synchronize both + * processes and threads. Note: There is considerable overhead in using + * this API if only cross-process or cross-thread mutual exclusion is + * required. See apr_proc_mutex.h and apr_thread_mutex.h for more + * specialized lock routines. + * @param mutex the memory address where the newly created mutex will be + * stored. + * @param fname A file name to use if the lock mechanism requires one. This + * argument should always be provided. The lock code itself will + * determine if it should be used. + * @param mech The mechanism to use for the interprocess lock, if any; one of + *
+ *            APR_LOCK_FCNTL
+ *            APR_LOCK_FLOCK
+ *            APR_LOCK_SYSVSEM
+ *            APR_LOCK_POSIXSEM
+ *            APR_LOCK_PROC_PTHREAD
+ *            APR_LOCK_DEFAULT     pick the default mechanism for the platform
+ *            APR_LOCK_DEFAULT_TIMED pick the default timed mechanism
+ * 
+ * @param pool the pool from which to allocate the mutex. + * @warning Check APR_HAS_foo_SERIALIZE defines to see if the platform supports + * APR_LOCK_foo. Only APR_LOCK_DEFAULT is portable. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_create(apr_global_mutex_t **mutex, + const char *fname, + apr_lockmech_e mech, + apr_pool_t *pool); + +/** + * Re-open a mutex in a child process. + * @param mutex The newly re-opened mutex structure. + * @param fname A file name to use if the mutex mechanism requires one. This + * argument should always be provided. The mutex code itself will + * determine if it should be used. This filename should be the + * same one that was passed to apr_global_mutex_create(). + * @param pool The pool to operate on. + * @remark This function must be called to maintain portability, even + * if the underlying lock mechanism does not require it. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_child_init( + apr_global_mutex_t **mutex, + const char *fname, + apr_pool_t *pool); + +/** + * Acquire the lock for the given mutex. If the mutex is already locked, + * the current thread will be put to sleep until the lock becomes available. + * @param mutex the mutex on which to acquire the lock. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_lock(apr_global_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex. If the mutex has already + * been acquired, the call returns immediately with APR_EBUSY. Note: it + * is important that the APR_STATUS_IS_EBUSY(s) macro be used to determine + * if the return value was APR_EBUSY, for portability reasons. + * @param mutex the mutex on which to attempt the lock acquiring. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_trylock(apr_global_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex until timeout expires. + * If the acquisition time outs, the call returns with APR_TIMEUP. + * @param mutex the mutex on which to attempt the lock acquiring. + * @param timeout the relative timeout (microseconds). + * @note A negative or nul timeout means immediate attempt, returning + * APR_TIMEUP without blocking if it the lock is already acquired. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_timedlock(apr_global_mutex_t *mutex, + apr_interval_time_t timeout); + +/** + * Release the lock for the given mutex. + * @param mutex the mutex from which to release the lock. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_unlock(apr_global_mutex_t *mutex); + +/** + * Destroy the mutex and free the memory associated with the lock. + * @param mutex the mutex to destroy. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_destroy(apr_global_mutex_t *mutex); + +/** + * Return the name of the lockfile for the mutex, or NULL + * if the mutex doesn't use a lock file + */ +APR_DECLARE(const char *) apr_global_mutex_lockfile(apr_global_mutex_t *mutex); + +/** + * Get the mechanism of the mutex, as it relates to the actual method + * used for the underlying apr_proc_mutex_t. + * @param mutex the mutex to get the mechanism from. + */ +APR_DECLARE(apr_lockmech_e) apr_global_mutex_mech(apr_global_mutex_t *mutex); + +/** + * Get the mechanism's name of the mutex, as it relates to the actual method + * used for the underlying apr_proc_mutex_t. + * @param mutex the mutex to get the mechanism's name from. + */ +APR_DECLARE(const char *) apr_global_mutex_name(apr_global_mutex_t *mutex); + +/** + * Set mutex permissions. + */ +APR_PERMS_SET_IMPLEMENT(global_mutex); + +/** + * Get the pool used by this global_mutex. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(global_mutex); + +#else /* APR_PROC_MUTEX_IS_GLOBAL */ + +/* Some platforms [e.g. Win32] have cross process locks that are truly + * global locks, since there isn't the concept of cross-process locks. + * Define these platforms in terms of an apr_proc_mutex_t. + */ + +#define apr_global_mutex_t apr_proc_mutex_t +#define apr_global_mutex_create apr_proc_mutex_create +#define apr_global_mutex_child_init apr_proc_mutex_child_init +#define apr_global_mutex_lock apr_proc_mutex_lock +#define apr_global_mutex_trylock apr_proc_mutex_trylock +#define apr_global_mutex_unlock apr_proc_mutex_unlock +#define apr_global_mutex_destroy apr_proc_mutex_destroy +#define apr_global_mutex_lockfile apr_proc_mutex_lockfile +#define apr_global_mutex_mech apr_proc_mutex_mech +#define apr_global_mutex_name apr_proc_mutex_name +#define apr_global_mutex_perms_set apr_proc_mutex_perms_set +#define apr_global_mutex_pool_get apr_proc_mutex_pool_get + +#endif + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ndef APR_GLOBAL_MUTEX_H */ diff --git a/c/dependencies/macos/apr/include/apr_hash.h b/c/dependencies/macos/apr/include/apr_hash.h new file mode 100644 index 00000000..cced5bec --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_hash.h @@ -0,0 +1,283 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_HASH_H +#define APR_HASH_H + +/** + * @file apr_hash.h + * @brief APR Hash Tables + */ + +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_hash Hash Tables + * @ingroup APR + * @{ + */ + +/** + * When passing a key to apr_hash_set or apr_hash_get, this value can be + * passed to indicate a string-valued key, and have apr_hash compute the + * length automatically. + * + * @remark apr_hash will use strlen(key) for the length. The NUL terminator + * is not included in the hash value (why throw a constant in?). + * Since the hash table merely references the provided key (rather + * than copying it), apr_hash_this() will return the NUL-term'd key. + */ +#define APR_HASH_KEY_STRING (-1) + +/** + * Abstract type for hash tables. + */ +typedef struct apr_hash_t apr_hash_t; + +/** + * Abstract type for scanning hash tables. + */ +typedef struct apr_hash_index_t apr_hash_index_t; + +/** + * Callback functions for calculating hash values. + * @param key The key. + * @param klen The length of the key, or APR_HASH_KEY_STRING to use the string + * length. If APR_HASH_KEY_STRING then returns the actual key length. + */ +typedef unsigned int (*apr_hashfunc_t)(const char *key, apr_ssize_t *klen); + +/** + * The default hash function. + */ +APR_DECLARE_NONSTD(unsigned int) apr_hashfunc_default(const char *key, + apr_ssize_t *klen); + +/** + * Create a hash table. + * @param pool The pool to allocate the hash table out of + * @return The hash table just created + */ +APR_DECLARE(apr_hash_t *) apr_hash_make(apr_pool_t *pool); + +/** + * Create a hash table with a custom hash function + * @param pool The pool to allocate the hash table out of + * @param hash_func A custom hash function. + * @return The hash table just created + */ +APR_DECLARE(apr_hash_t *) apr_hash_make_custom(apr_pool_t *pool, + apr_hashfunc_t hash_func); + +/** + * Make a copy of a hash table + * @param pool The pool from which to allocate the new hash table + * @param h The hash table to clone + * @return The hash table just created + * @remark Makes a shallow copy + */ +APR_DECLARE(apr_hash_t *) apr_hash_copy(apr_pool_t *pool, + const apr_hash_t *h); + +/** + * Associate a value with a key in a hash table. + * @param ht The hash table + * @param key Pointer to the key + * @param klen Length of the key. Can be APR_HASH_KEY_STRING to use the string length. + * @param val Value to associate with the key + * @remark If the value is NULL the hash entry is deleted. The key is stored as is, + * and so must have a lifetime at least as long as the hash table's pool. + */ +APR_DECLARE(void) apr_hash_set(apr_hash_t *ht, const void *key, + apr_ssize_t klen, const void *val); + +/** + * Look up the value associated with a key in a hash table. + * @param ht The hash table + * @param key Pointer to the key + * @param klen Length of the key. Can be APR_HASH_KEY_STRING to use the string length. + * @return Returns NULL if the key is not present. + */ +APR_DECLARE(void *) apr_hash_get(apr_hash_t *ht, const void *key, + apr_ssize_t klen); + +/** + * Start iterating over the entries in a hash table. + * @param p The pool to allocate the apr_hash_index_t iterator. If this + * pool is NULL, then an internal, non-thread-safe iterator is used. + * @param ht The hash table + * @return The iteration state + * @remark There is no restriction on adding or deleting hash entries during + * an iteration (although the results may be unpredictable unless all you do + * is delete the current entry) and multiple iterations can be in + * progress at the same time. + * + * @par Example: + * + * @code + * int sum_values(apr_pool_t *p, apr_hash_t *ht) + * { + * apr_hash_index_t *hi; + * void *val; + * int sum = 0; + * for (hi = apr_hash_first(p, ht); hi; hi = apr_hash_next(hi)) { + * apr_hash_this(hi, NULL, NULL, &val); + * sum += *(int *)val; + * } + * return sum; + * } + * @endcode + */ +APR_DECLARE(apr_hash_index_t *) apr_hash_first(apr_pool_t *p, apr_hash_t *ht); + +/** + * Continue iterating over the entries in a hash table. + * @param hi The iteration state + * @return a pointer to the updated iteration state. NULL if there are no more + * entries. + */ +APR_DECLARE(apr_hash_index_t *) apr_hash_next(apr_hash_index_t *hi); + +/** + * Get the current entry's details from the iteration state. + * @param hi The iteration state + * @param key Return pointer for the pointer to the key. + * @param klen Return pointer for the key length. + * @param val Return pointer for the associated value. + * @remark The return pointers should point to a variable that will be set to the + * corresponding data, or they may be NULL if the data isn't interesting. + */ +APR_DECLARE(void) apr_hash_this(apr_hash_index_t *hi, const void **key, + apr_ssize_t *klen, void **val); + +/** + * Get the current entry's key from the iteration state. + * @param hi The iteration state + * @return The pointer to the key + */ +APR_DECLARE(const void*) apr_hash_this_key(apr_hash_index_t *hi); + +/** + * Get the current entry's key length from the iteration state. + * @param hi The iteration state + * @return The key length + */ +APR_DECLARE(apr_ssize_t) apr_hash_this_key_len(apr_hash_index_t *hi); + +/** + * Get the current entry's value from the iteration state. + * @param hi The iteration state + * @return The pointer to the value + */ +APR_DECLARE(void*) apr_hash_this_val(apr_hash_index_t *hi); + +/** + * Get the number of key/value pairs in the hash table. + * @param ht The hash table + * @return The number of key/value pairs in the hash table. + */ +APR_DECLARE(unsigned int) apr_hash_count(apr_hash_t *ht); + +/** + * Clear any key/value pairs in the hash table. + * @param ht The hash table + */ +APR_DECLARE(void) apr_hash_clear(apr_hash_t *ht); + +/** + * Merge two hash tables into one new hash table. The values of the overlay + * hash override the values of the base if both have the same key. Both + * hash tables must use the same hash function. + * @param p The pool to use for the new hash table + * @param overlay The table to add to the initial table + * @param base The table that represents the initial values of the new table + * @return A new hash table containing all of the data from the two passed in + */ +APR_DECLARE(apr_hash_t *) apr_hash_overlay(apr_pool_t *p, + const apr_hash_t *overlay, + const apr_hash_t *base); + +/** + * Merge two hash tables into one new hash table. If the same key + * is present in both tables, call the supplied merge function to + * produce a merged value for the key in the new table. Both + * hash tables must use the same hash function. + * @param p The pool to use for the new hash table + * @param h1 The first of the tables to merge + * @param h2 The second of the tables to merge + * @param merger A callback function to merge values, or NULL to + * make values from h1 override values from h2 (same semantics as + * apr_hash_overlay()) + * @param data Client data to pass to the merger function + * @return A new hash table containing all of the data from the two passed in + */ +APR_DECLARE(apr_hash_t *) apr_hash_merge(apr_pool_t *p, + const apr_hash_t *h1, + const apr_hash_t *h2, + void * (*merger)(apr_pool_t *p, + const void *key, + apr_ssize_t klen, + const void *h1_val, + const void *h2_val, + const void *data), + const void *data); + +/** + * Declaration prototype for the iterator callback function of apr_hash_do(). + * + * @param rec The data passed as the first argument to apr_hash_[v]do() + * @param key The key from this iteration of the hash table + * @param klen The key length from this iteration of the hash table + * @param value The value from this iteration of the hash table + * @remark Iteration continues while this callback function returns non-zero. + * To export the callback function for apr_hash_do() it must be declared + * in the _NONSTD convention. + */ +typedef int (apr_hash_do_callback_fn_t)(void *rec, const void *key, + apr_ssize_t klen, + const void *value); + +/** + * Iterate over a hash table running the provided function once for every + * element in the hash table. The @p comp function will be invoked for + * every element in the hash table. + * + * @param comp The function to run + * @param rec The data to pass as the first argument to the function + * @param ht The hash table to iterate over + * @return FALSE if one of the comp() iterations returned zero; TRUE if all + * iterations returned non-zero + * @see apr_hash_do_callback_fn_t + */ +APR_DECLARE(int) apr_hash_do(apr_hash_do_callback_fn_t *comp, + void *rec, const apr_hash_t *ht); + +/** + * Get a pointer to the pool which the hash table was created in + */ +APR_POOL_DECLARE_ACCESSOR(hash); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_HASH_H */ diff --git a/c/dependencies/macos/apr/include/apr_hooks.h b/c/dependencies/macos/apr/include/apr_hooks.h new file mode 100644 index 00000000..eee16e3c --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_hooks.h @@ -0,0 +1,358 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_HOOKS_H +#define APR_HOOKS_H + +#include "apu.h" +/* For apr_array_header_t */ +#include "apr_tables.h" + +/** + * @file apr_hooks.h + * @brief Apache hook functions + */ + +#ifdef __cplusplus +extern "C" { +#endif +/** + * @defgroup APR_Util_Hook Hook Functions + * @ingroup APR_Util + * @{ + */ + +/** + * @defgroup apr_hook_probes Hook probe capability + * APR hooks provide a trace probe capability for capturing + * the flow of control and return values with hooks. + * + * In order to use this facility, the application must define + * the symbol APR_HOOK_PROBES_ENABLED and the four APR_HOOK_PROBE_ + * macros described below before including apr_hooks.h in files + * that use the APR_IMPLEMENT_EXTERNAL_HOOK_* macros. + * + * This probe facility is not provided for APR optional hooks. + * @{ + */ + +#ifdef APR_HOOK_PROBES_ENABLED +#define APR_HOOK_INT_DCL_UD void *ud = NULL +#else +/** internal implementation detail to avoid the ud declaration when + * hook probes are not used + */ +#define APR_HOOK_INT_DCL_UD +/** + * User-defined hook probe macro that is invoked when the hook + * is run, before calling any hook functions. + * @param ud A void * user data field that should be filled in by + * this macro, and will be provided to the other hook probe macros. + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param args The argument list to the hook functions, with enclosing + * parens. + */ +#define APR_HOOK_PROBE_ENTRY(ud,ns,name,args) +/** + * User-defined hook probe macro that is invoked after the hook + * has run. + * @param ud A void * user data field that was filled in by the user- + * provided APR_HOOK_PROBE_ENTRY(). + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param rv The return value of the hook, or 0 if the hook is void. + * @param args The argument list to the hook functions, with enclosing + * parens. + */ +#define APR_HOOK_PROBE_RETURN(ud,ns,name,rv,args) +/** + * User-defined hook probe macro that is invoked before calling a + * hook function. + * @param ud A void * user data field that was filled in by the user- + * provided APR_HOOK_PROBE_ENTRY(). + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param src The value of apr_hook_debug_current at the time the function + * was hooked (usually the source file implementing the hook function). + * @param args The argument list to the hook functions, with enclosing + * parens. + */ +#define APR_HOOK_PROBE_INVOKE(ud,ns,name,src,args) +/** + * User-defined hook probe macro that is invoked after calling a + * hook function. + * @param ud A void * user data field that was filled in by the user- + * provided APR_HOOK_PROBE_ENTRY(). + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param src The value of apr_hook_debug_current at the time the function + * was hooked (usually the source file implementing the hook function). + * @param rv The return value of the hook function, or 0 if the hook is void. + * @param args The argument list to the hook functions, with enclosing + * parens. + */ +#define APR_HOOK_PROBE_COMPLETE(ud,ns,name,src,rv,args) +#endif + +/** @} */ + +/** macro to return the prototype of the hook function */ +#define APR_IMPLEMENT_HOOK_GET_PROTO(ns,link,name) \ +link##_DECLARE(apr_array_header_t *) ns##_hook_get_##name(void) + +/** macro to declare the hook correctly */ +#define APR_DECLARE_EXTERNAL_HOOK(ns,link,ret,name,args) \ +typedef ret ns##_HOOK_##name##_t args; \ +link##_DECLARE(void) ns##_hook_##name(ns##_HOOK_##name##_t *pf, \ + const char * const *aszPre, \ + const char * const *aszSucc, int nOrder); \ +link##_DECLARE(ret) ns##_run_##name args; \ +APR_IMPLEMENT_HOOK_GET_PROTO(ns,link,name); \ +typedef struct ns##_LINK_##name##_t \ + { \ + ns##_HOOK_##name##_t *pFunc; \ + const char *szName; \ + const char * const *aszPredecessors; \ + const char * const *aszSuccessors; \ + int nOrder; \ + } ns##_LINK_##name##_t; + +/** macro to declare the hook structure */ +#define APR_HOOK_STRUCT(members) \ +static struct { members } _hooks; + +/** macro to link the hook structure */ +#define APR_HOOK_LINK(name) \ + apr_array_header_t *link_##name; + +/** macro to implement the hook */ +#define APR_IMPLEMENT_EXTERNAL_HOOK_BASE(ns,link,name) \ +link##_DECLARE(void) ns##_hook_##name(ns##_HOOK_##name##_t *pf,const char * const *aszPre, \ + const char * const *aszSucc,int nOrder) \ + { \ + ns##_LINK_##name##_t *pHook; \ + if(!_hooks.link_##name) \ + { \ + _hooks.link_##name=apr_array_make(apr_hook_global_pool,1,sizeof(ns##_LINK_##name##_t)); \ + apr_hook_sort_register(#name,&_hooks.link_##name); \ + } \ + pHook=apr_array_push(_hooks.link_##name); \ + pHook->pFunc=pf; \ + pHook->aszPredecessors=aszPre; \ + pHook->aszSuccessors=aszSucc; \ + pHook->nOrder=nOrder; \ + pHook->szName=apr_hook_debug_current; \ + if(apr_hook_debug_enabled) \ + apr_hook_debug_show(#name,aszPre,aszSucc); \ + } \ + APR_IMPLEMENT_HOOK_GET_PROTO(ns,link,name) \ + { \ + return _hooks.link_##name; \ + } + +/** + * Implement a hook that has no return code, and therefore runs all of the + * registered functions + * @param ns The namespace prefix of the hook functions + * @param link The linkage declaration prefix of the hook + * @param name The name of the hook + * @param args_decl The declaration of the arguments for the hook + * @param args_use The names for the arguments for the hook + * @note The link prefix FOO corresponds to FOO_DECLARE() macros, which + * provide export linkage from the module that IMPLEMENTs the hook, and + * import linkage from external modules that link to the hook's module. + */ +#define APR_IMPLEMENT_EXTERNAL_HOOK_VOID(ns,link,name,args_decl,args_use) \ +APR_IMPLEMENT_EXTERNAL_HOOK_BASE(ns,link,name) \ +link##_DECLARE(void) ns##_run_##name args_decl \ + { \ + ns##_LINK_##name##_t *pHook; \ + int n; \ + APR_HOOK_INT_DCL_UD; \ +\ + APR_HOOK_PROBE_ENTRY(ud, ns, name, args_use); \ +\ + if(_hooks.link_##name) \ + { \ + pHook=(ns##_LINK_##name##_t *)_hooks.link_##name->elts; \ + for(n=0 ; n < _hooks.link_##name->nelts ; ++n) \ + { \ + APR_HOOK_PROBE_INVOKE(ud, ns, name, (char *)pHook[n].szName, args_use); \ + pHook[n].pFunc args_use; \ + APR_HOOK_PROBE_COMPLETE(ud, ns, name, (char *)pHook[n].szName, 0, args_use); \ + } \ + } \ +\ + APR_HOOK_PROBE_RETURN(ud, ns, name, 0, args_use); \ +\ + } + +/* FIXME: note that this returns ok when nothing is run. I suspect it should + really return decline, but that breaks Apache currently - Ben +*/ +/** + * Implement a hook that runs until one of the functions returns something + * other than OK or DECLINE + * @param ns The namespace prefix of the hook functions + * @param link The linkage declaration prefix of the hook + * @param ret Type to return + * @param name The name of the hook + * @param args_decl The declaration of the arguments for the hook + * @param args_use The names for the arguments for the hook + * @param ok Success value + * @param decline Decline value + * @note The link prefix FOO corresponds to FOO_DECLARE() macros, which + * provide export linkage from the module that IMPLEMENTs the hook, and + * import linkage from external modules that link to the hook's module. + */ +#define APR_IMPLEMENT_EXTERNAL_HOOK_RUN_ALL(ns,link,ret,name,args_decl,args_use,ok,decline) \ +APR_IMPLEMENT_EXTERNAL_HOOK_BASE(ns,link,name) \ +link##_DECLARE(ret) ns##_run_##name args_decl \ + { \ + ns##_LINK_##name##_t *pHook; \ + int n; \ + ret rv = ok; \ + APR_HOOK_INT_DCL_UD; \ +\ + APR_HOOK_PROBE_ENTRY(ud, ns, name, args_use); \ +\ + if(_hooks.link_##name) \ + { \ + pHook=(ns##_LINK_##name##_t *)_hooks.link_##name->elts; \ + for(n=0 ; n < _hooks.link_##name->nelts ; ++n) \ + { \ + APR_HOOK_PROBE_INVOKE(ud, ns, name, (char *)pHook[n].szName, args_use); \ + rv=pHook[n].pFunc args_use; \ + APR_HOOK_PROBE_COMPLETE(ud, ns, name, (char *)pHook[n].szName, rv, args_use); \ + if(rv != ok && rv != decline) \ + break; \ + rv = ok; \ + } \ + } \ +\ + APR_HOOK_PROBE_RETURN(ud, ns, name, rv, args_use); \ +\ + return rv; \ + } + + +/** + * Implement a hook that runs until the first function returns something + * other than the value of decline + * @param ns The namespace prefix of the hook functions + * @param link The linkage declaration prefix of the hook + * @param name The name of the hook + * @param ret Type to return + * @param args_decl The declaration of the arguments for the hook + * @param args_use The names for the arguments for the hook + * @param decline Decline value + * @note The link prefix FOO corresponds to FOO_DECLARE() macros, which + * provide export linkage from the module that IMPLEMENTs the hook, and + * import linkage from external modules that link to the hook's module. + */ +#define APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(ns,link,ret,name,args_decl,args_use,decline) \ +APR_IMPLEMENT_EXTERNAL_HOOK_BASE(ns,link,name) \ +link##_DECLARE(ret) ns##_run_##name args_decl \ + { \ + ns##_LINK_##name##_t *pHook; \ + int n; \ + ret rv = decline; \ + APR_HOOK_INT_DCL_UD; \ +\ + APR_HOOK_PROBE_ENTRY(ud, ns, name, args_use); \ +\ + if(_hooks.link_##name) \ + { \ + pHook=(ns##_LINK_##name##_t *)_hooks.link_##name->elts; \ + for(n=0 ; n < _hooks.link_##name->nelts ; ++n) \ + { \ + APR_HOOK_PROBE_INVOKE(ud, ns, name, (char *)pHook[n].szName, args_use); \ + rv=pHook[n].pFunc args_use; \ + APR_HOOK_PROBE_COMPLETE(ud, ns, name, (char *)pHook[n].szName, rv, args_use); \ +\ + if(rv != decline) \ + break; \ + } \ + } \ +\ + APR_HOOK_PROBE_RETURN(ud, ns, name, rv, args_use); \ +\ + return rv; \ + } + + /* Hook orderings */ +/** run this hook first, before ANYTHING */ +#define APR_HOOK_REALLY_FIRST (-10) +/** run this hook first */ +#define APR_HOOK_FIRST 0 +/** run this hook somewhere */ +#define APR_HOOK_MIDDLE 10 +/** run this hook after every other hook which is defined*/ +#define APR_HOOK_LAST 20 +/** run this hook last, after EVERYTHING */ +#define APR_HOOK_REALLY_LAST 30 + +/** + * The global pool used to allocate any memory needed by the hooks. + */ +APU_DECLARE_DATA extern apr_pool_t *apr_hook_global_pool; + +/** + * A global variable to determine if debugging information about the + * hooks functions should be printed. + */ +APU_DECLARE_DATA extern int apr_hook_debug_enabled; + +/** + * The name of the module that is currently registering a function. + */ +APU_DECLARE_DATA extern const char *apr_hook_debug_current; + +/** + * Register a hook function to be sorted. + * @param szHookName The name of the Hook the function is registered for + * @param aHooks The array which stores all of the functions for this hook + */ +APU_DECLARE(void) apr_hook_sort_register(const char *szHookName, + apr_array_header_t **aHooks); +/** + * Sort all of the registered functions for a given hook. + */ +APU_DECLARE(void) apr_hook_sort_all(void); + +/** + * Print all of the information about the current hook. This is used for + * debugging purposes. + * @param szName The name of the hook + * @param aszPre All of the functions in the predecessor array + * @param aszSucc All of the functions in the successor array + */ +APU_DECLARE(void) apr_hook_debug_show(const char *szName, + const char * const *aszPre, + const char * const *aszSucc); + +/** + * Remove all currently registered functions. + */ +APU_DECLARE(void) apr_hook_deregister_all(void); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_HOOKS_H */ diff --git a/c/dependencies/macos/apr/include/apr_inherit.h b/c/dependencies/macos/apr/include/apr_inherit.h new file mode 100644 index 00000000..b9fe56fe --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_inherit.h @@ -0,0 +1,51 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_INHERIT_H +#define APR_INHERIT_H + +/** + * @file apr_inherit.h + * @brief APR File Handle Inheritance Helpers + * @remark This internal header includes internal declaration helpers + * for other headers to declare apr_foo_inherit_[un]set functions. + */ + +/** + * Prototype for type-specific declarations of apr_foo_inherit_set + * functions. + * @remark Doxygen unwraps this macro (via doxygen.conf) to provide + * actual help for each specific occurrence of apr_foo_inherit_set. + * @remark the linkage is specified for APR. It would be possible to expand + * the macros to support other linkages. + */ +#define APR_DECLARE_INHERIT_SET(type) \ + APR_DECLARE(apr_status_t) apr_##type##_inherit_set( \ + apr_##type##_t *the##type) + +/** + * Prototype for type-specific declarations of apr_foo_inherit_unset + * functions. + * @remark Doxygen unwraps this macro (via doxygen.conf) to provide + * actual help for each specific occurrence of apr_foo_inherit_unset. + * @remark the linkage is specified for APR. It would be possible to expand + * the macros to support other linkages. + */ +#define APR_DECLARE_INHERIT_UNSET(type) \ + APR_DECLARE(apr_status_t) apr_##type##_inherit_unset( \ + apr_##type##_t *the##type) + +#endif /* ! APR_INHERIT_H */ diff --git a/c/dependencies/macos/apr/include/apr_ldap.h b/c/dependencies/macos/apr/include/apr_ldap.h new file mode 100644 index 00000000..bd328537 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_ldap.h @@ -0,0 +1,197 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_ldap.h is generated from apr_ldap.h.in by configure -- do not edit apr_ldap.h + */ +/** + * @file apr_ldap.h + * @brief APR-UTIL LDAP + */ +#ifndef APU_LDAP_H +#define APU_LDAP_H + +/** + * @defgroup APR_Util_LDAP LDAP + * @ingroup APR_Util + * @{ + */ + +/* this will be defined if LDAP support was compiled into apr-util */ +#define APR_HAS_LDAP 0 + +/* identify the LDAP toolkit used */ +#define APR_HAS_NETSCAPE_LDAPSDK 0 +#define APR_HAS_SOLARIS_LDAPSDK 0 +#define APR_HAS_NOVELL_LDAPSDK 0 +#define APR_HAS_MOZILLA_LDAPSDK 0 +#define APR_HAS_OPENLDAP_LDAPSDK 0 +#define APR_HAS_MICROSOFT_LDAPSDK 0 +#define APR_HAS_TIVOLI_LDAPSDK 0 +#define APR_HAS_ZOS_LDAPSDK 0 +#define APR_HAS_OTHER_LDAPSDK 0 + + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/* + * The following #defines are DEPRECATED and should not be used for + * anything. They remain to maintain binary compatibility. + * The original code defined the OPENLDAP SDK as present regardless + * of what really was there, which was way bogus. In addition, the + * apr_ldap_url_parse*() functions have been rewritten specifically for + * APR, so the APR_HAS_LDAP_URL_PARSE macro is forced to zero. + */ +#if APR_HAS_TIVOLI_LDAPSDK +#define APR_HAS_LDAP_SSL 0 +#else +#define APR_HAS_LDAP_SSL 1 +#endif +#define APR_HAS_LDAP_URL_PARSE 0 + +#if APR_HAS_OPENLDAP_LDAPSDK && !defined(LDAP_DEPRECATED) +/* Ensure that the "deprecated" interfaces are still exposed + * with OpenLDAP >= 2.3; these were exposed by default in earlier + * releases. */ +#define LDAP_DEPRECATED 1 +#endif + +/* + * Include the standard LDAP header files. + */ + + + + + + +/* + * Detected standard functions + */ +#define APR_HAS_LDAPSSL_CLIENT_INIT 0 +#define APR_HAS_LDAPSSL_CLIENT_DEINIT 0 +#define APR_HAS_LDAPSSL_ADD_TRUSTED_CERT 0 +#define APR_HAS_LDAP_START_TLS_S 0 +#define APR_HAS_LDAP_SSLINIT 0 +#define APR_HAS_LDAPSSL_INIT 0 +#define APR_HAS_LDAPSSL_INSTALL_ROUTINES 0 + +/* + * Make sure the secure LDAP port is defined + */ +#ifndef LDAPS_PORT +#define LDAPS_PORT 636 /* ldaps:/// default LDAP over TLS port */ +#endif + +/* + * For ldap function calls that input a size limit on the number of returned elements + * Some SDKs do not have the define for LDAP_DEFAULT_LIMIT (-1) or LDAP_NO_LIMIT (0) + * LDAP_DEFAULT_LIMIT is preferred as it allows inheritance from whatever the SDK + * or process is configured for. + */ +#ifdef LDAP_DEFAULT_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_DEFAULT_LIMIT +#else +#ifdef LDAP_NO_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_NO_LIMIT +#endif +#endif + +#ifndef APR_LDAP_SIZELIMIT +#define APR_LDAP_SIZELIMIT 0 /* equivalent to LDAP_NO_LIMIT, and what goes on the wire */ +#endif + +/* + * z/OS is missing some defines + */ +#ifndef LDAP_VERSION_MAX +#define LDAP_VERSION_MAX LDAP_VERSION +#endif +#if APR_HAS_ZOS_LDAPSDK +#define LDAP_VENDOR_NAME "IBM z/OS" +#endif + +/* Note: Macros defining const casting has been removed in APR v1.0, + * pending real support for LDAP v2.0 toolkits. + * + * In the mean time, please use an LDAP v3.0 toolkit. + */ +#if LDAP_VERSION_MAX <= 2 +#error Support for LDAP v2.0 toolkits has been removed from apr-util. Please use an LDAP v3.0 toolkit. +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * This structure allows the C LDAP API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apr_ldap_err_t { + const char *reason; + const char *msg; + int rc; +} apr_ldap_err_t; + +#ifdef __cplusplus +} +#endif + +/* The MS SDK returns LDAP_UNAVAILABLE when the backend has closed the connection + * between LDAP calls. Protect with APR_HAS_MICROSOFT_LDAPSDK in case someone + * manually chooses another SDK on Windows + */ +#if APR_HAS_MICROSOFT_LDAPSDK +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN \ + || (s) == LDAP_UNAVAILABLE) +#else +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN) +#endif + +/* These symbols are not actually exported in a DSO build, but mapped into + * a private exported function array for apr_ldap_stub to bind dynamically. + * Rename them appropriately to protect the global namespace. + */ +#ifdef APU_DSO_LDAP_BUILD + +#define apr_ldap_info apr__ldap_info +#define apr_ldap_init apr__ldap_init +#define apr_ldap_ssl_init apr__ldap_ssl_init +#define apr_ldap_ssl_deinit apr__ldap_ssl_deinit +#define apr_ldap_get_option apr__ldap_get_option +#define apr_ldap_set_option apr__ldap_set_option +#define apr_ldap_rebind_init apr__ldap_rebind_init +#define apr_ldap_rebind_add apr__ldap_rebind_add +#define apr_ldap_rebind_remove apr__ldap_rebind_remove + +#define APU_DECLARE_LDAP(type) type +#else +#define APU_DECLARE_LDAP(type) APU_DECLARE(type) +#endif + +#include "apr_ldap_url.h" +#include "apr_ldap_init.h" +#include "apr_ldap_option.h" +#include "apr_ldap_rebind.h" + +#endif /* APR_HAS_LDAP */ +/** @} */ +#endif /* APU_LDAP_H */ diff --git a/c/dependencies/macos/apr/include/apr_ldap_init.h b/c/dependencies/macos/apr/include/apr_ldap_init.h new file mode 100644 index 00000000..aeb6d9bb --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_ldap_init.h @@ -0,0 +1,165 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_ldap_init.h + * @brief APR-UTIL LDAP ldap_init() functions + */ +#ifndef APR_LDAP_INIT_H +#define APR_LDAP_INIT_H + +/** + * @addtogroup APR_Util_LDAP + * @{ + */ + +#include "apr_ldap.h" + +#if APR_HAS_LDAP + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + + +/** + * Macro to detect security related return values. + */ +#if defined(LDAP_INSUFFICIENT_ACCESS) +#define APU_LDAP_INSUFFICIENT_ACCESS LDAP_INSUFFICIENT_ACCESS +#elif defined(LDAP_INSUFFICIENT_RIGHTS) +#define APU_LDAP_INSUFFICIENT_ACCESS LDAP_INSUFFICIENT_RIGHTS +#elif defined(APR_HAS_MICROSOFT_LDAPSDK) +/* The macros above fail to contemplate that LDAP_RETCODE values + * may be represented by an enum. autoconf tests would be much + * more robust. + */ +#define APU_LDAP_INSUFFICIENT_ACCESS LDAP_INSUFFICIENT_RIGHTS +#else +#error The security return codes must be added to support this LDAP toolkit. +#endif + +#if defined(LDAP_SECURITY_ERROR) +#define APU_LDAP_SECURITY_ERROR LDAP_SECURITY_ERROR +#else +#define APU_LDAP_SECURITY_ERROR(n) \ + (LDAP_INAPPROPRIATE_AUTH == n) ? 1 \ + : (LDAP_INVALID_CREDENTIALS == n) ? 1 \ + : (APU_LDAP_INSUFFICIENT_ACCESS == n) ? 1 \ + : 0 +#endif + + +/** + * APR LDAP SSL Initialise function + * + * This function initialises SSL on the underlying LDAP toolkit + * if this is necessary. + * + * If a CA certificate is provided, this is set, however the setting + * of certificates via this method has been deprecated and will be removed in + * APR v2.0. + * + * The apr_ldap_set_option() function with the APR_LDAP_OPT_TLS_CERT option + * should be used instead to set certificates. + * + * If SSL support is not available on this platform, or a problem + * was encountered while trying to set the certificate, the function + * will return APR_EGENERAL. Further LDAP specific error information + * can be found in result_err. + * @param pool The pool to use + * @param cert_auth_file The name of the certificate to use, can be NULL + * @param cert_file_type The type of certificate specified. See the + * apr_ldap_set_option() APR_LDAP_OPT_TLS_CERT option for details. + * @param result_err The returned result + */ +APU_DECLARE_LDAP(int) apr_ldap_ssl_init(apr_pool_t *pool, + const char *cert_auth_file, + int cert_file_type, + apr_ldap_err_t **result_err); + +/** + * APR LDAP SSL De-Initialise function + * + * This function tears down any SSL certificate setup previously + * set using apr_ldap_ssl_init(). It should be called to clean + * up if a graceful restart of a service is attempted. + * @todo currently we do not check whether apr_ldap_ssl_init() + * has been called first - we probably should. + */ +APU_DECLARE_LDAP(int) apr_ldap_ssl_deinit(void); + +/** + * APR LDAP initialise function + * + * This function is responsible for initialising an LDAP + * connection in a toolkit independant way. It does the + * job of ldap_init() from the C api. + * + * It handles both the SSL and non-SSL case, and attempts + * to hide the complexity setup from the user. This function + * assumes that any certificate setup necessary has already + * been done. + * + * If SSL or STARTTLS needs to be enabled, and the underlying + * toolkit supports it, the following values are accepted for + * secure: + * + * APR_LDAP_NONE: No encryption + * APR_LDAP_SSL: SSL encryption (ldaps://) + * APR_LDAP_STARTTLS: Force STARTTLS on ldap:// + * @remark The Novell toolkit is only able to set the SSL mode via this + * function. To work around this limitation, set the SSL mode here if no + * per connection client certificates are present, otherwise set secure + * APR_LDAP_NONE here, then set the per connection client certificates, + * followed by setting the SSL mode via apr_ldap_set_option(). As Novell + * does not support per connection client certificates, this problem is + * worked around while still being compatible with other LDAP toolkits. + * @param pool The pool to use + * @param ldap The LDAP handle + * @param hostname The name of the host to connect to. This can be either a + * DNS name, or an IP address. + * @param portno The port to connect to + * @param secure The security mode to set + * @param result_err The returned result + */ +APU_DECLARE_LDAP(int) apr_ldap_init(apr_pool_t *pool, + LDAP **ldap, + const char *hostname, + int portno, + int secure, + apr_ldap_err_t **result_err); + +/** + * APR LDAP info function + * + * This function returns a string describing the LDAP toolkit + * currently in use. The string is placed inside result_err->reason. + * @param pool The pool to use + * @param result_err The returned result + */ +APU_DECLARE_LDAP(int) apr_ldap_info(apr_pool_t *pool, + apr_ldap_err_t **result_err); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_HAS_LDAP */ + +/** @} */ + +#endif /* APR_LDAP_URL_H */ diff --git a/c/dependencies/macos/apr/include/apr_ldap_option.h b/c/dependencies/macos/apr/include/apr_ldap_option.h new file mode 100644 index 00000000..0ff8a862 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_ldap_option.h @@ -0,0 +1,254 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_ldap_option.h + * @brief APR-UTIL LDAP ldap_*_option() functions + */ +#ifndef APR_LDAP_OPTION_H +#define APR_LDAP_OPTION_H + +/** + * @addtogroup APR_Util_LDAP + * @{ + */ + +#include "apr_ldap.h" + +#if APR_HAS_LDAP + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* + * The following defines handle the different TLS certificate + * options available. If these options are missing, APR will try and + * emulate support for this using the deprecated ldap_start_tls_s() + * function. + */ +/** + * Set SSL mode to one of APR_LDAP_NONE, APR_LDAP_SSL, APR_LDAP_STARTTLS + * or APR_LDAP_STOPTLS. + */ +#define APR_LDAP_OPT_TLS 0x6fff +/** + * Set zero or more CA certificates, client certificates or private + * keys globally, or per connection (where supported). + */ +#define APR_LDAP_OPT_TLS_CERT 0x6ffe +/** + * Set the LDAP library to no verify the server certificate. This means + * all servers are considered trusted. + */ +#define APR_LDAP_OPT_VERIFY_CERT 0x6ffd +/** + * Set the LDAP library to indicate if referrals should be chased during + * LDAP searches. + */ +#define APR_LDAP_OPT_REFERRALS 0x6ffc +/** + * Set the LDAP library to indicate a maximum number of referral hops to + * chase before giving up on the search. + */ +#define APR_LDAP_OPT_REFHOPLIMIT 0x6ffb + +/** + * Structures for the apr_set_option() cases + */ + +/** + * APR_LDAP_OPT_TLS_CERT + * + * This structure includes possible options to set certificates on + * system initialisation. Different SDKs have different certificate + * requirements, and to achieve this multiple certificates must be + * specified at once passed as an (apr_array_header_t *). + * + * Netscape: + * Needs the CA cert database (cert7.db), the client cert database (key3.db) + * and the security module file (secmod.db) set at the system initialisation + * time. Three types are supported: APR_LDAP_CERT7_DB, APR_LDAP_KEY3_DB and + * APR_LDAP_SECMOD. + * + * To specify a client cert connection, a certificate nickname needs to be + * provided with a type of APR_LDAP_CERT. + * int ldapssl_enable_clientauth( LDAP *ld, char *keynickname, + * char *keypasswd, char *certnickname ); + * keynickname is currently not used, and should be set to "" + * + * Novell: + * Needs CA certificates and client certificates set at system initialisation + * time. Three types are supported: APR_LDAP_CA*, APR_LDAP_CERT* and + * APR_LDAP_KEY*. + * + * Certificates cannot be specified per connection. + * + * The functions used are: + * ldapssl_add_trusted_cert(serverTrustedRoot, serverTrustedRootEncoding); + * Clients certs and keys are set at system initialisation time with + * int ldapssl_set_client_cert ( + * void *cert, + * int type + * void *password); + * type can be LDAPSSL_CERT_FILETYPE_B64 or LDAPSSL_CERT_FILETYPE_DER + * ldapssl_set_client_private_key(clientPrivateKey, + * clientPrivateKeyEncoding, + * clientPrivateKeyPassword); + * + * OpenSSL: + * Needs one or more CA certificates to be set at system initialisation time + * with a type of APR_LDAP_CA*. + * + * May have one or more client certificates set per connection with a type of + * APR_LDAP_CERT*, and keys with APR_LDAP_KEY*. + */ +/** CA certificate type unknown */ +#define APR_LDAP_CA_TYPE_UNKNOWN 0 +/** binary DER encoded CA certificate */ +#define APR_LDAP_CA_TYPE_DER 1 +/** PEM encoded CA certificate */ +#define APR_LDAP_CA_TYPE_BASE64 2 +/** Netscape/Mozilla cert7.db CA certificate database */ +#define APR_LDAP_CA_TYPE_CERT7_DB 3 +/** Netscape/Mozilla secmod file */ +#define APR_LDAP_CA_TYPE_SECMOD 4 +/** Client certificate type unknown */ +#define APR_LDAP_CERT_TYPE_UNKNOWN 5 +/** binary DER encoded client certificate */ +#define APR_LDAP_CERT_TYPE_DER 6 +/** PEM encoded client certificate */ +#define APR_LDAP_CERT_TYPE_BASE64 7 +/** Netscape/Mozilla key3.db client certificate database */ +#define APR_LDAP_CERT_TYPE_KEY3_DB 8 +/** Netscape/Mozilla client certificate nickname */ +#define APR_LDAP_CERT_TYPE_NICKNAME 9 +/** Private key type unknown */ +#define APR_LDAP_KEY_TYPE_UNKNOWN 10 +/** binary DER encoded private key */ +#define APR_LDAP_KEY_TYPE_DER 11 +/** PEM encoded private key */ +#define APR_LDAP_KEY_TYPE_BASE64 12 +/** PKCS#12 encoded client certificate */ +#define APR_LDAP_CERT_TYPE_PFX 13 +/** PKCS#12 encoded private key */ +#define APR_LDAP_KEY_TYPE_PFX 14 +/** Openldap directory full of base64-encoded cert + * authorities with hashes in corresponding .0 directory + */ +#define APR_LDAP_CA_TYPE_CACERTDIR_BASE64 15 + + +/** + * Certificate structure. + * + * This structure is used to store certificate details. An array of + * these structures is passed to apr_ldap_set_option() to set CA + * and client certificates. + * @param type Type of certificate APR_LDAP_*_TYPE_* + * @param path Path, file or nickname of the certificate + * @param password Optional password, can be NULL + */ +typedef struct apr_ldap_opt_tls_cert_t apr_ldap_opt_tls_cert_t; +struct apr_ldap_opt_tls_cert_t { + int type; + const char *path; + const char *password; +}; + +/** + * APR_LDAP_OPT_TLS + * + * This sets the SSL level on the LDAP handle. + * + * Netscape/Mozilla: + * Supports SSL, but not STARTTLS + * SSL is enabled by calling ldapssl_install_routines(). + * + * Novell: + * Supports SSL and STARTTLS. + * SSL is enabled by calling ldapssl_install_routines(). Note that calling + * other ldap functions before ldapssl_install_routines() may cause this + * function to fail. + * STARTTLS is enabled by calling ldapssl_start_tls_s() after calling + * ldapssl_install_routines() (check this). + * + * OpenLDAP: + * Supports SSL and supports STARTTLS, but none of this is documented: + * http://www.openldap.org/lists/openldap-software/200409/msg00618.html + * Documentation for both SSL support and STARTTLS has been deleted from + * the OpenLDAP documentation and website. + */ + +/** No encryption */ +#define APR_LDAP_NONE 0 +/** SSL encryption (ldaps://) */ +#define APR_LDAP_SSL 1 +/** TLS encryption (STARTTLS) */ +#define APR_LDAP_STARTTLS 2 +/** end TLS encryption (STOPTLS) */ +#define APR_LDAP_STOPTLS 3 + +/** + * APR LDAP get option function + * + * This function gets option values from a given LDAP session if + * one was specified. It maps to the native ldap_get_option() function. + * @param pool The pool to use + * @param ldap The LDAP handle + * @param option The LDAP_OPT_* option to return + * @param outvalue The value returned (if any) + * @param result_err The apr_ldap_err_t structure contained detailed results + * of the operation. + */ +APU_DECLARE_LDAP(int) apr_ldap_get_option(apr_pool_t *pool, + LDAP *ldap, + int option, + void *outvalue, + apr_ldap_err_t **result_err); + +/** + * APR LDAP set option function + * + * This function sets option values to a given LDAP session if + * one was specified. It maps to the native ldap_set_option() function. + * + * Where an option is not supported by an LDAP toolkit, this function + * will try and apply legacy functions to achieve the same effect, + * depending on the platform. + * @param pool The pool to use + * @param ldap The LDAP handle + * @param option The LDAP_OPT_* option to set + * @param invalue The value to set + * @param result_err The apr_ldap_err_t structure contained detailed results + * of the operation. + */ +APU_DECLARE_LDAP(int) apr_ldap_set_option(apr_pool_t *pool, + LDAP *ldap, + int option, + const void *invalue, + apr_ldap_err_t **result_err); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_HAS_LDAP */ + +/** @} */ + +#endif /* APR_LDAP_OPTION_H */ + diff --git a/c/dependencies/macos/apr/include/apr_ldap_rebind.h b/c/dependencies/macos/apr/include/apr_ldap_rebind.h new file mode 100644 index 00000000..342a17c3 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_ldap_rebind.h @@ -0,0 +1,98 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The APR LDAP rebind functions provide an implementation of + * a rebind procedure that can be used to allow clients to chase referrals, + * using the same credentials used to log in originally. + * + * Use of this implementation is optional. + * + * @file apr_ldap_rebind.h + * @brief Apache LDAP library + */ + +#ifndef APU_LDAP_REBIND_H +#define APU_LDAP_REBIND_H + +/** + * @addtogroup APR_Util_LDAP + * @{ + **/ + +#if defined(DOXYGEN) +#include "apr_ldap.h" +#endif + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/** + * APR LDAP initialize rebind lock + * + * This function creates the lock for controlling access to the xref list.. + * @param pool Pool to use when creating the xref_lock. + */ +APU_DECLARE_LDAP(apr_status_t) apr_ldap_rebind_init(apr_pool_t *pool); + + +/** + * APR LDAP rebind_add function + * + * This function creates a cross reference entry for the specified ldap + * connection. The rebind callback function will look up this ldap + * connection so it can retrieve the bindDN and bindPW for use in any + * binds while referrals are being chased. + * + * This function will add the callback to the LDAP handle passed in. + * + * A cleanup is registered within the pool provided to remove this + * entry when the pool is removed. Alternatively apr_ldap_rebind_remove() + * can be called to explicitly remove the entry at will. + * + * @param pool The pool to use + * @param ld The LDAP connectionhandle + * @param bindDN The bind DN to be used for any binds while chasing + * referrals on this ldap connection. + * @param bindPW The bind Password to be used for any binds while + * chasing referrals on this ldap connection. + */ +APU_DECLARE_LDAP(apr_status_t) apr_ldap_rebind_add(apr_pool_t *pool, + LDAP *ld, + const char *bindDN, + const char *bindPW); + +/** + * APR LDAP rebind_remove function + * + * This function removes the rebind cross reference entry for the + * specified ldap connection. + * + * If not explicitly removed, this function will be called automatically + * when the pool is cleaned up. + * + * @param ld The LDAP connectionhandle + */ +APU_DECLARE_LDAP(apr_status_t) apr_ldap_rebind_remove(LDAP *ld); + +#endif /* APR_HAS_LDAP */ + +/** @} */ + +#endif /* APU_LDAP_REBIND_H */ + diff --git a/c/dependencies/macos/apr/include/apr_ldap_url.h b/c/dependencies/macos/apr/include/apr_ldap_url.h new file mode 100644 index 00000000..a71f5b3c --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_ldap_url.h @@ -0,0 +1,120 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_ldap_url.h + * @brief APR-UTIL LDAP ldap_init() functions + */ +#ifndef APR_LDAP_URL_H +#define APR_LDAP_URL_H + +/** + * @addtogroup APR_Util_LDAP + * @{ + */ + +#if defined(DOXYGEN) +#include "apr_ldap.h" +#endif + +#if APR_HAS_LDAP + +#include "apu.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** Structure to access an exploded LDAP URL */ +typedef struct apr_ldap_url_desc_t { + struct apr_ldap_url_desc_t *lud_next; + char *lud_scheme; + char *lud_host; + int lud_port; + char *lud_dn; + char **lud_attrs; + int lud_scope; + char *lud_filter; + char **lud_exts; + int lud_crit_exts; +} apr_ldap_url_desc_t; + +#ifndef APR_LDAP_URL_SUCCESS +#define APR_LDAP_URL_SUCCESS 0x00 /* Success */ +#define APR_LDAP_URL_ERR_MEM 0x01 /* can't allocate memory space */ +#define APR_LDAP_URL_ERR_PARAM 0x02 /* parameter is bad */ +#define APR_LDAP_URL_ERR_BADSCHEME 0x03 /* URL doesn't begin with "ldap[si]://" */ +#define APR_LDAP_URL_ERR_BADENCLOSURE 0x04 /* URL is missing trailing ">" */ +#define APR_LDAP_URL_ERR_BADURL 0x05 /* URL is bad */ +#define APR_LDAP_URL_ERR_BADHOST 0x06 /* host port is bad */ +#define APR_LDAP_URL_ERR_BADATTRS 0x07 /* bad (or missing) attributes */ +#define APR_LDAP_URL_ERR_BADSCOPE 0x08 /* scope string is invalid (or missing) */ +#define APR_LDAP_URL_ERR_BADFILTER 0x09 /* bad or missing filter */ +#define APR_LDAP_URL_ERR_BADEXTS 0x0a /* bad or missing extensions */ +#endif + +/** + * Is this URL an ldap url? ldap:// + * @param url The url to test + */ +APU_DECLARE(int) apr_ldap_is_ldap_url(const char *url); + +/** + * Is this URL an SSL ldap url? ldaps:// + * @param url The url to test + */ +APU_DECLARE(int) apr_ldap_is_ldaps_url(const char *url); + +/** + * Is this URL an ldap socket url? ldapi:// + * @param url The url to test + */ +APU_DECLARE(int) apr_ldap_is_ldapi_url(const char *url); + +/** + * Parse an LDAP URL. + * @param pool The pool to use + * @param url_in The URL to parse + * @param ludpp The structure to return the exploded URL + * @param result_err The result structure of the operation + */ +APU_DECLARE(int) apr_ldap_url_parse_ext(apr_pool_t *pool, + const char *url_in, + apr_ldap_url_desc_t **ludpp, + apr_ldap_err_t **result_err); + +/** + * Parse an LDAP URL. + * @param pool The pool to use + * @param url_in The URL to parse + * @param ludpp The structure to return the exploded URL + * @param result_err The result structure of the operation + */ +APU_DECLARE(int) apr_ldap_url_parse(apr_pool_t *pool, + const char *url_in, + apr_ldap_url_desc_t **ludpp, + apr_ldap_err_t **result_err); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_HAS_LDAP */ + +/** @} */ + +#endif /* APR_LDAP_URL_H */ diff --git a/c/dependencies/macos/apr/include/apr_lib.h b/c/dependencies/macos/apr/include/apr_lib.h new file mode 100644 index 00000000..466e8185 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_lib.h @@ -0,0 +1,241 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_LIB_H +#define APR_LIB_H + +/** + * @file apr_lib.h + * This is collection of oddballs that didn't fit anywhere else, + * and might move to more appropriate headers with the release + * of APR 1.0. + * @brief APR general purpose library routines + */ + +#include "apr.h" +#include "apr_errno.h" + +#if APR_HAVE_CTYPE_H +#include +#endif +#if APR_HAVE_STDARG_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_lib General Purpose Library Routines + * @ingroup APR + * This is collection of oddballs that didn't fit anywhere else, + * and might move to more appropriate headers with the release + * of APR 1.0. + * @{ + */ + +/** A constant representing a 'large' string. */ +#define HUGE_STRING_LEN 8192 + +/* + * Define the structures used by the APR general-purpose library. + */ + +/** @see apr_vformatter_buff_t */ +typedef struct apr_vformatter_buff_t apr_vformatter_buff_t; + +/** + * Structure used by the variable-formatter routines. + */ +struct apr_vformatter_buff_t { + /** The current position */ + char *curpos; + /** The end position of the format string */ + char *endpos; +}; + +/** + * return the final element of the pathname + * @param pathname The path to get the final element of + * @return the final element of the path + * @remark + *
+ * For example:
+ *                 "/foo/bar/gum"    -> "gum"
+ *                 "/foo/bar/gum/"   -> ""
+ *                 "gum"             -> "gum"
+ *                 "bs\\path\\stuff" -> "stuff"
+ * 
+ */ +APR_DECLARE(const char *) apr_filepath_name_get(const char *pathname); + +/** + * apr_killpg + * Small utility macros to make things easier to read. Not usually a + * goal, to be sure.. + */ + +#ifdef WIN32 +#define apr_killpg(x, y) +#else /* WIN32 */ +#ifdef NO_KILLPG +#define apr_killpg(x, y) (kill (-(x), (y))) +#else /* NO_KILLPG */ +#define apr_killpg(x, y) (killpg ((x), (y))) +#endif /* NO_KILLPG */ +#endif /* WIN32 */ + +/** + * apr_vformatter() is a generic printf-style formatting routine + * with some extensions. + * @param flush_func The function to call when the buffer is full + * @param c The buffer to write to + * @param fmt The format string + * @param ap The arguments to use to fill out the format string. + * + * @remark + *
+ * The extensions are:
+ *
+ * - %%pA takes a struct in_addr *, and prints it as a.b.c.d
+ * - %%pI takes an apr_sockaddr_t * and prints it as a.b.c.d:port or
+ * \[ipv6-address\]:port
+ * - %%pT takes an apr_os_thread_t * and prints it in decimal
+ * ('0' is printed if !APR_HAS_THREADS)
+ * - %%pt takes an apr_os_thread_t * and prints it in hexadecimal
+ * ('0' is printed if !APR_HAS_THREADS)
+ * - %%pm takes an apr_status_t * and prints the appropriate error
+ * string (from apr_strerror) corresponding to that error code.
+ * - %%pp takes a void * and outputs it in hex
+ * - %%pB takes a apr_uint32_t * as bytes and outputs it's apr_strfsize
+ * - %%pF same as above, but takes a apr_off_t *
+ * - %%pS same as above, but takes a apr_size_t *
+ *
+ * %%pA, %%pI, %%pT, %%pp are available from APR 1.0.0 onwards (and in 0.9.x).
+ * %%pt is only available from APR 1.2.0 onwards.
+ * %%pm, %%pB, %%pF and %%pS are only available from APR 1.3.0 onwards.
+ *
+ * The %%p hacks are to force gcc's printf warning code to skip
+ * over a pointer argument without complaining.  This does
+ * mean that the ANSI-style %%p (output a void * in hex format) won't
+ * work as expected at all, but that seems to be a fair trade-off
+ * for the increased robustness of having printf-warnings work.
+ *
+ * Additionally, apr_vformatter allows for arbitrary output methods
+ * using the apr_vformatter_buff and flush_func.
+ *
+ * The apr_vformatter_buff has two elements curpos and endpos.
+ * curpos is where apr_vformatter will write the next byte of output.
+ * It proceeds writing output to curpos, and updating curpos, until
+ * either the end of output is reached, or curpos == endpos (i.e. the
+ * buffer is full).
+ *
+ * If the end of output is reached, apr_vformatter returns the
+ * number of bytes written.
+ *
+ * When the buffer is full, the flush_func is called.  The flush_func
+ * can return -1 to indicate that no further output should be attempted,
+ * and apr_vformatter will return immediately with -1.  Otherwise
+ * the flush_func should flush the buffer in whatever manner is
+ * appropriate, re apr_pool_t nitialize curpos and endpos, and return 0.
+ *
+ * Note that flush_func is only invoked as a result of attempting to
+ * write another byte at curpos when curpos >= endpos.  So for
+ * example, it's possible when the output exactly matches the buffer
+ * space available that curpos == endpos will be true when
+ * apr_vformatter returns.
+ *
+ * apr_vformatter does not call out to any other code, it is entirely
+ * self-contained.  This allows the callers to do things which are
+ * otherwise "unsafe".  For example, apr_psprintf uses the "scratch"
+ * space at the unallocated end of a block, and doesn't actually
+ * complete the allocation until apr_vformatter returns.  apr_psprintf
+ * would be completely broken if apr_vformatter were to call anything
+ * that used this same pool.  Similarly http_bprintf() uses the "scratch"
+ * space at the end of its output buffer, and doesn't actually note
+ * that the space is in use until it either has to flush the buffer
+ * or until apr_vformatter returns.
+ * 
+ */ +APR_DECLARE(int) apr_vformatter(int (*flush_func)(apr_vformatter_buff_t *b), + apr_vformatter_buff_t *c, const char *fmt, + va_list ap); + +/** + * Display a prompt and read in the password from stdin. + * @param prompt The prompt to display + * @param pwbuf Buffer to store the password + * @param bufsize The length of the password buffer. + * @remark If the password entered must be truncated to fit in + * the provided buffer, APR_ENAMETOOLONG will be returned. + * Note that the bufsize paramater is passed by reference for no + * reason; its value will never be modified by the apr_password_get() + * function. + */ +APR_DECLARE(apr_status_t) apr_password_get(const char *prompt, char *pwbuf, + apr_size_t *bufsize); + +/** @} */ + +/** + * @defgroup apr_ctype ctype functions + * These macros allow correct support of 8-bit characters on systems which + * support 8-bit characters. Pretty dumb how the cast is required, but + * that's legacy libc for ya. These new macros do not support EOF like + * the standard macros do. Tough. + * @{ + */ +/** @see isalnum */ +#define apr_isalnum(c) (isalnum(((unsigned char)(c)))) +/** @see isalpha */ +#define apr_isalpha(c) (isalpha(((unsigned char)(c)))) +/** @see iscntrl */ +#define apr_iscntrl(c) (iscntrl(((unsigned char)(c)))) +/** @see isdigit */ +#define apr_isdigit(c) (isdigit(((unsigned char)(c)))) +/** @see isgraph */ +#define apr_isgraph(c) (isgraph(((unsigned char)(c)))) +/** @see islower*/ +#define apr_islower(c) (islower(((unsigned char)(c)))) +/** @see isascii */ +#ifdef isascii +#define apr_isascii(c) (isascii(((unsigned char)(c)))) +#else +#define apr_isascii(c) (((c) & ~0x7f)==0) +#endif +/** @see isprint */ +#define apr_isprint(c) (isprint(((unsigned char)(c)))) +/** @see ispunct */ +#define apr_ispunct(c) (ispunct(((unsigned char)(c)))) +/** @see isspace */ +#define apr_isspace(c) (isspace(((unsigned char)(c)))) +/** @see isupper */ +#define apr_isupper(c) (isupper(((unsigned char)(c)))) +/** @see isxdigit */ +#define apr_isxdigit(c) (isxdigit(((unsigned char)(c)))) +/** @see tolower */ +#define apr_tolower(c) (tolower(((unsigned char)(c)))) +/** @see toupper */ +#define apr_toupper(c) (toupper(((unsigned char)(c)))) + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_LIB_H */ diff --git a/c/dependencies/macos/apr/include/apr_md4.h b/c/dependencies/macos/apr/include/apr_md4.h new file mode 100644 index 00000000..43fb33e3 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_md4.h @@ -0,0 +1,135 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* This is derived from material copyright RSA Data Security, Inc. + * Their notice is reproduced below in its entirety. + * + * Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All + * rights reserved. + * + * License to copy and use this software is granted provided that it + * is identified as the "RSA Data Security, Inc. MD4 Message-Digest + * Algorithm" in all material mentioning or referencing this software + * or this function. + * + * License is also granted to make and use derivative works provided + * that such works are identified as "derived from the RSA Data + * Security, Inc. MD4 Message-Digest Algorithm" in all material + * mentioning or referencing the derived work. + * + * RSA Data Security, Inc. makes no representations concerning either + * the merchantability of this software or the suitability of this + * software for any particular purpose. It is provided "as is" + * without express or implied warranty of any kind. + * + * These notices must be retained in any copies of any part of this + * documentation and/or software. + */ + +#ifndef APR_MD4_H +#define APR_MD4_H + +#include "apu.h" +#include "apr_xlate.h" +/** + * @file apr_md4.h + * @brief APR-UTIL MD4 Library + */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_MD4 MD4 Library + * @ingroup APR_Util + * @{ + */ + +/** The digestsize for MD4 */ +#define APR_MD4_DIGESTSIZE 16 + +/** @see apr_md4_ctx_t */ +typedef struct apr_md4_ctx_t apr_md4_ctx_t; + +/** MD4 context. */ +struct apr_md4_ctx_t { + /** state (ABCD) */ + apr_uint32_t state[4]; + /** number of bits, modulo 2^64 (lsb first) */ + apr_uint32_t count[2]; + /** input buffer */ + unsigned char buffer[64]; +#if APR_HAS_XLATE + /** translation handle */ + apr_xlate_t *xlate; +#endif +}; + +/** + * MD4 Initialize. Begins an MD4 operation, writing a new context. + * @param context The MD4 context to initialize. + */ +APU_DECLARE(apr_status_t) apr_md4_init(apr_md4_ctx_t *context); + +#if APR_HAS_XLATE +/** + * MDr4 translation setup. Provides the APR translation handle to be used + * for translating the content before calculating the digest. + * @param context The MD4 content to set the translation for. + * @param xlate The translation handle to use for this MD4 context + */ +APU_DECLARE(apr_status_t) apr_md4_set_xlate(apr_md4_ctx_t *context, + apr_xlate_t *xlate); +#else +#define apr_md4_set_xlate(context, xlate) APR_ENOTIMPL +#endif + +/** + * MD4 block update operation. Continue an MD4 message-digest operation, + * processing another message block, and updating the context. + * @param context The MD4 content to update. + * @param input next message block to update + * @param inputLen The length of the next message block + */ +APU_DECLARE(apr_status_t) apr_md4_update(apr_md4_ctx_t *context, + const unsigned char *input, + apr_size_t inputLen); + +/** + * MD4 finalization. Ends an MD4 message-digest operation, writing the + * message digest and zeroing the context + * @param digest The final MD4 digest + * @param context The MD4 content we are finalizing. + */ +APU_DECLARE(apr_status_t) apr_md4_final( + unsigned char digest[APR_MD4_DIGESTSIZE], + apr_md4_ctx_t *context); + +/** + * MD4 digest computation + * @param digest The MD4 digest + * @param input message block to use + * @param inputLen The length of the message block + */ +APU_DECLARE(apr_status_t) apr_md4(unsigned char digest[APR_MD4_DIGESTSIZE], + const unsigned char *input, + apr_size_t inputLen); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_MD4_H */ diff --git a/c/dependencies/macos/apr/include/apr_md5.h b/c/dependencies/macos/apr/include/apr_md5.h new file mode 100644 index 00000000..e0202dfd --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_md5.h @@ -0,0 +1,176 @@ +/* + * This is work is derived from material Copyright RSA Data Security, Inc. + * + * The RSA copyright statement and Licence for that original material is + * included below. This is followed by the Apache copyright statement and + * licence for the modifications made to that material. + */ + +/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All + rights reserved. + + License to copy and use this software is granted provided that it + is identified as the "RSA Data Security, Inc. MD5 Message-Digest + Algorithm" in all material mentioning or referencing this software + or this function. + + License is also granted to make and use derivative works provided + that such works are identified as "derived from the RSA Data + Security, Inc. MD5 Message-Digest Algorithm" in all material + mentioning or referencing the derived work. + + RSA Data Security, Inc. makes no representations concerning either + the merchantability of this software or the suitability of this + software for any particular purpose. It is provided "as is" + without express or implied warranty of any kind. + + These notices must be retained in any copies of any part of this + documentation and/or software. + */ + +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_MD5_H +#define APR_MD5_H + +#include "apu.h" +#include "apr_xlate.h" + +#ifdef __cplusplus +extern "C" { +#endif +/** + * @file apr_md5.h + * @brief APR MD5 Routines + */ + +/** + * @defgroup APR_MD5 MD5 Routines + * @ingroup APR + * @{ + */ + +/** The MD5 digest size */ +#define APR_MD5_DIGESTSIZE 16 + +/** @see apr_md5_ctx_t */ +typedef struct apr_md5_ctx_t apr_md5_ctx_t; + +/** MD5 context. */ +struct apr_md5_ctx_t { + /** state (ABCD) */ + apr_uint32_t state[4]; + /** number of bits, modulo 2^64 (lsb first) */ + apr_uint32_t count[2]; + /** input buffer */ + unsigned char buffer[64]; + /** translation handle + * ignored if xlate is unsupported + */ + apr_xlate_t *xlate; +}; + +/** + * MD5 Initialize. Begins an MD5 operation, writing a new context. + * @param context The MD5 context to initialize. + */ +APU_DECLARE(apr_status_t) apr_md5_init(apr_md5_ctx_t *context); + +/** + * MD5 translation setup. Provides the APR translation handle to be used + * for translating the content before calculating the digest. + * @param context The MD5 content to set the translation for. + * @param xlate The translation handle to use for this MD5 context + */ +APU_DECLARE(apr_status_t) apr_md5_set_xlate(apr_md5_ctx_t *context, + apr_xlate_t *xlate); + +/** + * MD5 block update operation. Continue an MD5 message-digest operation, + * processing another message block, and updating the context. + * @param context The MD5 content to update. + * @param input next message block to update + * @param inputLen The length of the next message block + */ +APU_DECLARE(apr_status_t) apr_md5_update(apr_md5_ctx_t *context, + const void *input, + apr_size_t inputLen); + +/** + * MD5 finalization. Ends an MD5 message-digest operation, writing the + * message digest and zeroing the context + * @param digest The final MD5 digest + * @param context The MD5 content we are finalizing. + */ +APU_DECLARE(apr_status_t) apr_md5_final(unsigned char digest[APR_MD5_DIGESTSIZE], + apr_md5_ctx_t *context); + +/** + * MD5 in one step + * @param digest The final MD5 digest + * @param input The message block to use + * @param inputLen The length of the message block + */ +APU_DECLARE(apr_status_t) apr_md5(unsigned char digest[APR_MD5_DIGESTSIZE], + const void *input, + apr_size_t inputLen); + +/** + * Encode a password using an MD5 algorithm + * @param password The password to encode + * @param salt The salt string to use for the encoding + * @param result The string to store the encoded password in + * @param nbytes The size of the result buffer + */ +APU_DECLARE(apr_status_t) apr_md5_encode(const char *password, const char *salt, + char *result, apr_size_t nbytes); + +/** + * Encode a password using the bcrypt algorithm + * @param password The password to encode + * @param count The cost of the encoding, possible values are 4 to 31 + * @param salt Pointer to binary data to be used as salt for the encoding + * @param salt_len The size of the salt data (must be >= 16) + * @param out The string to store the encoded password in + * @param out_len The size of the result buffer (must be >= 61) + */ +APU_DECLARE(apr_status_t) apr_bcrypt_encode(const char *pw, + unsigned int count, + const unsigned char *salt, + apr_size_t salt_len, + char *out, apr_size_t out_len); + +/** + * Validate hashes created by APR-supported algorithms: md5, bcrypt, and sha1. + * hashes created by crypt are supported only on platforms that provide + * crypt(3), so don't rely on that function unless you know that your + * application will be run only on platforms that support it. On platforms + * that don't support crypt(3), this falls back to a clear text string + * comparison. + * @param passwd The password to validate + * @param hash The password to validate against + */ +APU_DECLARE(apr_status_t) apr_password_validate(const char *passwd, + const char *hash); + + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_MD5_H */ diff --git a/c/dependencies/macos/apr/include/apr_memcache.h b/c/dependencies/macos/apr/include/apr_memcache.h new file mode 100644 index 00000000..82878825 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_memcache.h @@ -0,0 +1,444 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_MEMCACHE_H +#define APR_MEMCACHE_H + +/** + * @file apr_memcache.h + * @brief Client interface for memcached + * @remark To use this interface you must have a separate memcached + * server running. See the memcached website at http://www.danga.com/memcached/ + * for more information. + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_time.h" +#include "apr_strings.h" +#include "apr_network_io.h" +#include "apr_ring.h" +#include "apr_buckets.h" +#include "apr_reslist.h" +#include "apr_hash.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_Util_MC Memcached Client Routines + * @ingroup APR_Util + * @{ + */ + +/** Specifies the status of a memcached server */ +typedef enum +{ + APR_MC_SERVER_LIVE, /**< Server is alive and responding to requests */ + APR_MC_SERVER_DEAD /**< Server is not responding to requests */ +} apr_memcache_server_status_t; + +/** Opaque memcache client connection object */ +typedef struct apr_memcache_conn_t apr_memcache_conn_t; + +/** Memcache Server Info Object */ +typedef struct apr_memcache_server_t apr_memcache_server_t; +struct apr_memcache_server_t +{ + const char *host; /**< Hostname of this Server */ + apr_port_t port; /**< Port of this Server */ + apr_memcache_server_status_t status; /**< @see apr_memcache_server_status_t */ +#if APR_HAS_THREADS || defined(DOXYGEN) + apr_reslist_t *conns; /**< Resource list of actual client connections */ +#else + apr_memcache_conn_t *conn; +#endif + apr_pool_t *p; /** Pool to use for private allocations */ +#if APR_HAS_THREADS + apr_thread_mutex_t *lock; +#endif + apr_time_t btime; +}; + +/* Custom hash callback function prototype, user for server selection. +* @param baton user selected baton +* @param data data to hash +* @param data_len length of data +*/ +typedef apr_uint32_t (*apr_memcache_hash_func)(void *baton, + const char *data, + const apr_size_t data_len); + +typedef struct apr_memcache_t apr_memcache_t; + +/* Custom Server Select callback function prototype. +* @param baton user selected baton +* @param mc memcache instance, use mc->live_servers to select a node +* @param hash hash of the selected key. +*/ +typedef apr_memcache_server_t* (*apr_memcache_server_func)(void *baton, + apr_memcache_t *mc, + const apr_uint32_t hash); + +/** Container for a set of memcached servers */ +struct apr_memcache_t +{ + apr_uint32_t flags; /**< Flags, Not currently used */ + apr_uint16_t nalloc; /**< Number of Servers Allocated */ + apr_uint16_t ntotal; /**< Number of Servers Added */ + apr_memcache_server_t **live_servers; /**< Array of Servers */ + apr_pool_t *p; /** Pool to use for allocations */ + void *hash_baton; + apr_memcache_hash_func hash_func; + void *server_baton; + apr_memcache_server_func server_func; +}; + +/** Returned Data from a multiple get */ +typedef struct +{ + apr_status_t status; + const char* key; + apr_size_t len; + char *data; + apr_uint16_t flags; +} apr_memcache_value_t; + +/** + * Creates a crc32 hash used to split keys between servers + * @param mc The memcache client object to use + * @param data Data to be hashed + * @param data_len Length of the data to use + * @return crc32 hash of data + * @remark The crc32 hash is not compatible with old memcached clients. + */ +APU_DECLARE(apr_uint32_t) apr_memcache_hash(apr_memcache_t *mc, + const char *data, + const apr_size_t data_len); + +/** + * Pure CRC32 Hash. Used by some clients. + */ +APU_DECLARE(apr_uint32_t) apr_memcache_hash_crc32(void *baton, + const char *data, + const apr_size_t data_len); + +/** + * hash compatible with the standard Perl Client. + */ +APU_DECLARE(apr_uint32_t) apr_memcache_hash_default(void *baton, + const char *data, + const apr_size_t data_len); + +/** + * Picks a server based on a hash + * @param mc The memcache client object to use + * @param hash Hashed value of a Key + * @return server that controls specified hash + * @see apr_memcache_hash + */ +APU_DECLARE(apr_memcache_server_t *) apr_memcache_find_server_hash(apr_memcache_t *mc, + const apr_uint32_t hash); + +/** + * server selection compatible with the standard Perl Client. + */ +APU_DECLARE(apr_memcache_server_t *) apr_memcache_find_server_hash_default(void *baton, + apr_memcache_t *mc, + const apr_uint32_t hash); + +/** + * Adds a server to a client object + * @param mc The memcache client object to use + * @param server Server to add + * @remark Adding servers is not thread safe, and should be done once at startup. + * @warning Changing servers after startup may cause keys to go to + * different servers. + */ +APU_DECLARE(apr_status_t) apr_memcache_add_server(apr_memcache_t *mc, + apr_memcache_server_t *server); + + +/** + * Finds a Server object based on a hostname/port pair + * @param mc The memcache client object to use + * @param host Hostname of the server + * @param port Port of the server + * @return Server with matching Hostname and Port, or NULL if none was found. + */ +APU_DECLARE(apr_memcache_server_t *) apr_memcache_find_server(apr_memcache_t *mc, + const char *host, + apr_port_t port); + +/** + * Enables a Server for use again + * @param mc The memcache client object to use + * @param ms Server to Activate + */ +APU_DECLARE(apr_status_t) apr_memcache_enable_server(apr_memcache_t *mc, + apr_memcache_server_t *ms); + + +/** + * Disable a Server + * @param mc The memcache client object to use + * @param ms Server to Disable + */ +APU_DECLARE(apr_status_t) apr_memcache_disable_server(apr_memcache_t *mc, + apr_memcache_server_t *ms); + +/** + * Creates a new Server Object + * @param p Pool to use + * @param host hostname of the server + * @param port port of the server + * @param min minimum number of client sockets to open + * @param smax soft maximum number of client connections to open + * @param max hard maximum number of client connections + * @param ttl time to live in microseconds of a client connection + * @param ns location of the new server object + * @see apr_reslist_create + * @remark min, smax, and max are only used when APR_HAS_THREADS + */ +APU_DECLARE(apr_status_t) apr_memcache_server_create(apr_pool_t *p, + const char *host, + apr_port_t port, + apr_uint32_t min, + apr_uint32_t smax, + apr_uint32_t max, + apr_uint32_t ttl, + apr_memcache_server_t **ns); +/** + * Creates a new memcached client object + * @param p Pool to use + * @param max_servers maximum number of servers + * @param flags Not currently used + * @param mc location of the new memcache client object + */ +APU_DECLARE(apr_status_t) apr_memcache_create(apr_pool_t *p, + apr_uint16_t max_servers, + apr_uint32_t flags, + apr_memcache_t **mc); + +/** + * Gets a value from the server, allocating the value out of p + * @param mc client to use + * @param p Pool to use + * @param key null terminated string containing the key + * @param baton location of the allocated value + * @param len length of data at baton + * @param flags any flags set by the client for this key + * @return + */ +APU_DECLARE(apr_status_t) apr_memcache_getp(apr_memcache_t *mc, + apr_pool_t *p, + const char* key, + char **baton, + apr_size_t *len, + apr_uint16_t *flags); + + +/** + * Add a key to a hash for a multiget query + * if the hash (*value) is NULL it will be created + * @param data_pool pool from where the hash and their items are created from + * @param key null terminated string containing the key + * @param values hash of keys and values that this key will be added to + * @return + */ +APU_DECLARE(void) apr_memcache_add_multget_key(apr_pool_t *data_pool, + const char* key, + apr_hash_t **values); + +/** + * Gets multiple values from the server, allocating the values out of p + * @param mc client to use + * @param temp_pool Pool used for temporary allocations. May be cleared inside this + * call. + * @param data_pool Pool used to allocate data for the returned values. + * @param values hash of apr_memcache_value_t keyed by strings, contains the + * result of the multiget call. + * @return + */ +APU_DECLARE(apr_status_t) apr_memcache_multgetp(apr_memcache_t *mc, + apr_pool_t *temp_pool, + apr_pool_t *data_pool, + apr_hash_t *values); + +/** + * Sets a value by key on the server + * @param mc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param timeout time in seconds for the data to live on the server + * @param flags any flags set by the client for this key + */ +APU_DECLARE(apr_status_t) apr_memcache_set(apr_memcache_t *mc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint32_t timeout, + apr_uint16_t flags); + +/** + * Adds value by key on the server + * @param mc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param timeout time for the data to live on the server + * @param flags any flags set by the client for this key + * @return APR_SUCCESS if the key was added, APR_EEXIST if the key + * already exists on the server. + */ +APU_DECLARE(apr_status_t) apr_memcache_add(apr_memcache_t *mc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint32_t timeout, + apr_uint16_t flags); + +/** + * Replaces value by key on the server + * @param mc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param timeout time for the data to live on the server + * @param flags any flags set by the client for this key + * @return APR_SUCCESS if the key was added, APR_EEXIST if the key + * did not exist on the server. + */ +APU_DECLARE(apr_status_t) apr_memcache_replace(apr_memcache_t *mc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint32_t timeout, + apr_uint16_t flags); +/** + * Deletes a key from a server + * @param mc client to use + * @param key null terminated string containing the key + * @param timeout time for the delete to stop other clients from adding + */ +APU_DECLARE(apr_status_t) apr_memcache_delete(apr_memcache_t *mc, + const char *key, + apr_uint32_t timeout); + +/** + * Increments a value + * @param mc client to use + * @param key null terminated string containing the key + * @param n number to increment by + * @param nv new value after incrementing + */ +APU_DECLARE(apr_status_t) apr_memcache_incr(apr_memcache_t *mc, + const char *key, + apr_int32_t n, + apr_uint32_t *nv); + +/** + * Decrements a value + * @param mc client to use + * @param key null terminated string containing the key + * @param n number to decrement by + * @param new_value new value after decrementing + */ +APU_DECLARE(apr_status_t) apr_memcache_decr(apr_memcache_t *mc, + const char *key, + apr_int32_t n, + apr_uint32_t *new_value); + +/** + * Query a server's version + * @param ms server to query + * @param p Pool to allocate answer from + * @param baton location to store server version string + * @param len length of the server version string + */ +APU_DECLARE(apr_status_t) apr_memcache_version(apr_memcache_server_t *ms, + apr_pool_t *p, + char **baton); + +typedef struct +{ + /** Version string of this server */ + const char *version; + /** Process id of this server process */ + apr_uint32_t pid; + /** Number of seconds this server has been running */ + apr_uint32_t uptime; + /** current UNIX time according to the server */ + apr_time_t time; + /** The size of a pointer on the current machine */ + apr_uint32_t pointer_size; + /** Accumulated user time for this process */ + apr_time_t rusage_user; + /** Accumulated system time for this process */ + apr_time_t rusage_system; + /** Current number of items stored by the server */ + apr_uint32_t curr_items; + /** Total number of items stored by this server */ + apr_uint32_t total_items; + /** Current number of bytes used by this server to store items */ + apr_uint64_t bytes; + /** Number of open connections */ + apr_uint32_t curr_connections; + /** Total number of connections opened since the server started running */ + apr_uint32_t total_connections; + /** Number of connection structures allocated by the server */ + apr_uint32_t connection_structures; + /** Cumulative number of retrieval requests */ + apr_uint32_t cmd_get; + /** Cumulative number of storage requests */ + apr_uint32_t cmd_set; + /** Number of keys that have been requested and found present */ + apr_uint32_t get_hits; + /** Number of items that have been requested and not found */ + apr_uint32_t get_misses; + /** Number of items removed from cache because they passed their + expiration time */ + apr_uint64_t evictions; + /** Total number of bytes read by this server */ + apr_uint64_t bytes_read; + /** Total number of bytes sent by this server */ + apr_uint64_t bytes_written; + /** Number of bytes this server is allowed to use for storage. */ + apr_uint32_t limit_maxbytes; + /** Number of threads the server is running (if built with threading) */ + apr_uint32_t threads; +} apr_memcache_stats_t; + +/** + * Query a server for statistics + * @param ms server to query + * @param p Pool to allocate answer from + * @param stats location of the new statistics structure + */ +APU_DECLARE(apr_status_t) apr_memcache_stats(apr_memcache_server_t *ms, + apr_pool_t *p, + apr_memcache_stats_t **stats); + + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_MEMCACHE_H */ diff --git a/c/dependencies/macos/apr/include/apr_mmap.h b/c/dependencies/macos/apr/include/apr_mmap.h new file mode 100644 index 00000000..c14de192 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_mmap.h @@ -0,0 +1,171 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_MMAP_H +#define APR_MMAP_H + +/** + * @file apr_mmap.h + * @brief APR MMAP routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_ring.h" +#include "apr_file_io.h" /* for apr_file_t */ + +#ifdef BEOS +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_mmap MMAP (Memory Map) Routines + * @ingroup APR + * @{ + */ + +/** MMap opened for reading */ +#define APR_MMAP_READ 1 +/** MMap opened for writing */ +#define APR_MMAP_WRITE 2 + +/** @see apr_mmap_t */ +typedef struct apr_mmap_t apr_mmap_t; + +/** + * @remark + * As far as I can tell the only really sane way to store an MMAP is as a + * void * and a length. BeOS requires this area_id, but that's just a little + * something extra. I am exposing this type, because it doesn't make much + * sense to keep it private, and opening it up makes some stuff easier in + * Apache. + */ +/** The MMAP structure */ +struct apr_mmap_t { + /** The pool the mmap structure was allocated out of. */ + apr_pool_t *cntxt; +#ifdef BEOS + /** An area ID. Only valid on BeOS */ + area_id area; +#endif +#ifdef WIN32 + /** The handle of the file mapping */ + HANDLE mhandle; + /** The start of the real memory page area (mapped view) */ + void *mv; + /** The physical start, size and offset */ + apr_off_t pstart; + apr_size_t psize; + apr_off_t poffset; +#endif + /** The start of the memory mapped area */ + void *mm; + /** The amount of data in the mmap */ + apr_size_t size; + /** ring of apr_mmap_t's that reference the same + * mmap'ed region; acts in place of a reference count */ + APR_RING_ENTRY(apr_mmap_t) link; +}; + +#if APR_HAS_MMAP || defined(DOXYGEN) + +/** @def APR_MMAP_THRESHOLD + * Files have to be at least this big before they're mmap()d. This is to deal + * with systems where the expense of doing an mmap() and an munmap() outweighs + * the benefit for small files. It shouldn't be set lower than 1. + */ +#ifdef MMAP_THRESHOLD +# define APR_MMAP_THRESHOLD MMAP_THRESHOLD +#else +# ifdef SUNOS4 +# define APR_MMAP_THRESHOLD (8*1024) +# else +# define APR_MMAP_THRESHOLD 1 +# endif /* SUNOS4 */ +#endif /* MMAP_THRESHOLD */ + +/** @def APR_MMAP_LIMIT + * Maximum size of MMap region + */ +#ifdef MMAP_LIMIT +# define APR_MMAP_LIMIT MMAP_LIMIT +#else +# define APR_MMAP_LIMIT (4*1024*1024) +#endif /* MMAP_LIMIT */ + +/** Can this file be MMaped */ +#define APR_MMAP_CANDIDATE(filelength) \ + ((filelength >= APR_MMAP_THRESHOLD) && (filelength < APR_MMAP_LIMIT)) + +/* Function definitions */ + +/** + * Create a new mmap'ed file out of an existing APR file. + * @param newmmap The newly created mmap'ed file. + * @param file The file to turn into an mmap. + * @param offset The offset into the file to start the data pointer at. + * @param size The size of the file + * @param flag bit-wise or of: + *
+ *          APR_MMAP_READ       MMap opened for reading
+ *          APR_MMAP_WRITE      MMap opened for writing
+ * 
+ * @param cntxt The pool to use when creating the mmap. + */ +APR_DECLARE(apr_status_t) apr_mmap_create(apr_mmap_t **newmmap, + apr_file_t *file, apr_off_t offset, + apr_size_t size, apr_int32_t flag, + apr_pool_t *cntxt); + +/** + * Duplicate the specified MMAP. + * @param new_mmap The structure to duplicate into. + * @param old_mmap The mmap to duplicate. + * @param p The pool to use for new_mmap. + */ +APR_DECLARE(apr_status_t) apr_mmap_dup(apr_mmap_t **new_mmap, + apr_mmap_t *old_mmap, + apr_pool_t *p); + +/** + * Remove a mmap'ed. + * @param mm The mmap'ed file. + */ +APR_DECLARE(apr_status_t) apr_mmap_delete(apr_mmap_t *mm); + +/** + * Move the pointer into the mmap'ed file to the specified offset. + * @param addr The pointer to the offset specified. + * @param mm The mmap'ed file. + * @param offset The offset to move to. + */ +APR_DECLARE(apr_status_t) apr_mmap_offset(void **addr, apr_mmap_t *mm, + apr_off_t offset); + +#endif /* APR_HAS_MMAP */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_MMAP_H */ diff --git a/c/dependencies/macos/apr/include/apr_network_io.h b/c/dependencies/macos/apr/include/apr_network_io.h new file mode 100644 index 00000000..d61e424c --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_network_io.h @@ -0,0 +1,953 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_NETWORK_IO_H +#define APR_NETWORK_IO_H +/** + * @file apr_network_io.h + * @brief APR Network library + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_file_io.h" +#include "apr_errno.h" +#include "apr_inherit.h" +#include "apr_perms_set.h" + +#if APR_HAVE_NETINET_IN_H +#include +#endif +#if APR_HAVE_SYS_UN_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_network_io Network Routines + * @ingroup APR + * @{ + */ + +#ifndef APR_MAX_SECS_TO_LINGER +/** Maximum seconds to linger */ +#define APR_MAX_SECS_TO_LINGER 30 +#endif + +#ifndef APRMAXHOSTLEN +/** Maximum hostname length */ +#define APRMAXHOSTLEN 256 +#endif + +#ifndef APR_ANYADDR +/** Default 'any' address */ +#define APR_ANYADDR "0.0.0.0" +#endif + +/** + * @defgroup apr_sockopt Socket option definitions + * @{ + */ +#define APR_SO_LINGER 1 /**< Linger */ +#define APR_SO_KEEPALIVE 2 /**< Keepalive */ +#define APR_SO_DEBUG 4 /**< Debug */ +#define APR_SO_NONBLOCK 8 /**< Non-blocking IO */ +#define APR_SO_REUSEADDR 16 /**< Reuse addresses */ +#define APR_SO_SNDBUF 64 /**< Send buffer */ +#define APR_SO_RCVBUF 128 /**< Receive buffer */ +#define APR_SO_DISCONNECTED 256 /**< Disconnected */ +#define APR_TCP_NODELAY 512 /**< For SCTP sockets, this is mapped + * to STCP_NODELAY internally. + */ +#define APR_TCP_NOPUSH 1024 /**< No push */ +#define APR_RESET_NODELAY 2048 /**< This flag is ONLY set internally + * when we set APR_TCP_NOPUSH with + * APR_TCP_NODELAY set to tell us that + * APR_TCP_NODELAY should be turned on + * again when NOPUSH is turned off + */ +#define APR_INCOMPLETE_READ 4096 /**< Set on non-blocking sockets + * (timeout != 0) on which the + * previous read() did not fill a buffer + * completely. the next apr_socket_recv() + * will first call select()/poll() rather than + * going straight into read(). (Can also + * be set by an application to force a + * select()/poll() call before the next + * read, in cases where the app expects + * that an immediate read would fail.) + */ +#define APR_INCOMPLETE_WRITE 8192 /**< like APR_INCOMPLETE_READ, but for write + * @see APR_INCOMPLETE_READ + */ +#define APR_IPV6_V6ONLY 16384 /**< Don't accept IPv4 connections on an + * IPv6 listening socket. + */ +#define APR_TCP_DEFER_ACCEPT 32768 /**< Delay accepting of new connections + * until data is available. + * @see apr_socket_accept_filter + */ +#define APR_SO_BROADCAST 65536 /**< Allow broadcast + */ +#define APR_SO_FREEBIND 131072 /**< Allow binding to addresses not owned + * by any interface + */ + +/** @} */ + +/** Define what type of socket shutdown should occur. */ +typedef enum { + APR_SHUTDOWN_READ, /**< no longer allow read request */ + APR_SHUTDOWN_WRITE, /**< no longer allow write requests */ + APR_SHUTDOWN_READWRITE /**< no longer allow read or write requests */ +} apr_shutdown_how_e; + +#define APR_IPV4_ADDR_OK 0x01 /**< @see apr_sockaddr_info_get() */ +#define APR_IPV6_ADDR_OK 0x02 /**< @see apr_sockaddr_info_get() */ + +#if (!APR_HAVE_IN_ADDR) +/** + * We need to make sure we always have an in_addr type, so APR will just + * define it ourselves, if the platform doesn't provide it. + */ +struct in_addr { + apr_uint32_t s_addr; /**< storage to hold the IP# */ +}; +#endif + +/** @def APR_INADDR_NONE + * Not all platforms have a real INADDR_NONE. This macro replaces + * INADDR_NONE on all platforms. + */ +#ifdef INADDR_NONE +#define APR_INADDR_NONE INADDR_NONE +#else +#define APR_INADDR_NONE ((unsigned int) 0xffffffff) +#endif + +/** + * @def APR_INET + * Not all platforms have these defined, so we'll define them here + * The default values come from FreeBSD 4.1.1 + */ +#define APR_INET AF_INET +/** @def APR_UNSPEC + * Let the system decide which address family to use + */ +#ifdef AF_UNSPEC +#define APR_UNSPEC AF_UNSPEC +#else +#define APR_UNSPEC 0 +#endif +#if APR_HAVE_IPV6 +/** @def APR_INET6 +* IPv6 Address Family. Not all platforms may have this defined. +*/ + +#define APR_INET6 AF_INET6 +#endif + +#if APR_HAVE_SOCKADDR_UN +#if defined (AF_UNIX) +#define APR_UNIX AF_UNIX +#elif defined(AF_LOCAL) +#define APR_UNIX AF_LOCAL +#else +#error "Neither AF_UNIX nor AF_LOCAL is defined" +#endif +#else /* !APR_HAVE_SOCKADDR_UN */ +#if defined (AF_UNIX) +#define APR_UNIX AF_UNIX +#elif defined(AF_LOCAL) +#define APR_UNIX AF_LOCAL +#else +/* TODO: Use a smarter way to detect unique APR_UNIX value */ +#define APR_UNIX 1234 +#endif +#endif + +/** + * @defgroup IP_Proto IP Protocol Definitions for use when creating sockets + * @{ + */ +#define APR_PROTO_TCP 6 /**< TCP */ +#define APR_PROTO_UDP 17 /**< UDP */ +#define APR_PROTO_SCTP 132 /**< SCTP */ +/** @} */ + +/** + * Enum used to denote either the local and remote endpoint of a + * connection. + */ +typedef enum { + APR_LOCAL, /**< Socket information for local end of connection */ + APR_REMOTE /**< Socket information for remote end of connection */ +} apr_interface_e; + +/** + * The specific declaration of inet_addr's ... some platforms fall back + * inet_network (this is not good, but necessary) + */ + +#if APR_HAVE_INET_ADDR +#define apr_inet_addr inet_addr +#elif APR_HAVE_INET_NETWORK /* only DGUX, as far as I know */ +/** + * @warning + * not generally safe... inet_network() and inet_addr() perform + * different functions */ +#define apr_inet_addr inet_network +#endif + +/** A structure to represent sockets */ +typedef struct apr_socket_t apr_socket_t; +/** + * A structure to encapsulate headers and trailers for apr_socket_sendfile + */ +typedef struct apr_hdtr_t apr_hdtr_t; +/** A structure to represent in_addr */ +typedef struct in_addr apr_in_addr_t; +/** A structure to represent an IP subnet */ +typedef struct apr_ipsubnet_t apr_ipsubnet_t; + +/** @remark use apr_uint16_t just in case some system has a short that isn't 16 bits... */ +typedef apr_uint16_t apr_port_t; + +/** @remark It's defined here as I think it should all be platform safe... + * @see apr_sockaddr_t + */ +typedef struct apr_sockaddr_t apr_sockaddr_t; +/** + * APRs socket address type, used to ensure protocol independence + */ +struct apr_sockaddr_t { + /** The pool to use... */ + apr_pool_t *pool; + /** The hostname */ + char *hostname; + /** Either a string of the port number or the service name for the port */ + char *servname; + /** The numeric port */ + apr_port_t port; + /** The family */ + apr_int32_t family; + /** How big is the sockaddr we're using? */ + apr_socklen_t salen; + /** How big is the ip address structure we're using? */ + int ipaddr_len; + /** How big should the address buffer be? 16 for v4 or 46 for v6 + * used in inet_ntop... */ + int addr_str_len; + /** This points to the IP address structure within the appropriate + * sockaddr structure. */ + void *ipaddr_ptr; + /** If multiple addresses were found by apr_sockaddr_info_get(), this + * points to a representation of the next address. */ + apr_sockaddr_t *next; + /** Union of either IPv4 or IPv6 sockaddr. */ + union { + /** IPv4 sockaddr structure */ + struct sockaddr_in sin; +#if APR_HAVE_IPV6 + /** IPv6 sockaddr structure */ + struct sockaddr_in6 sin6; +#endif +#if APR_HAVE_SA_STORAGE + /** Placeholder to ensure that the size of this union is not + * dependent on whether APR_HAVE_IPV6 is defined. */ + struct sockaddr_storage sas; +#endif +#if APR_HAVE_SOCKADDR_UN + /** Unix domain socket sockaddr structure */ + struct sockaddr_un unx; +#endif + } sa; +}; + +#if APR_HAS_SENDFILE +/** + * Support reusing the socket on platforms which support it (from disconnect, + * specifically Win32. + * @remark Optional flag passed into apr_socket_sendfile() + */ +#define APR_SENDFILE_DISCONNECT_SOCKET 1 +#endif + +/** A structure to encapsulate headers and trailers for apr_socket_sendfile */ +struct apr_hdtr_t { + /** An iovec to store the headers sent before the file. */ + struct iovec* headers; + /** number of headers in the iovec */ + int numheaders; + /** An iovec to store the trailers sent after the file. */ + struct iovec* trailers; + /** number of trailers in the iovec */ + int numtrailers; +}; + +/* function definitions */ + +/** + * Create a socket. + * @param new_sock The new socket that has been set up. + * @param family The address family of the socket (e.g., APR_INET). + * @param type The type of the socket (e.g., SOCK_STREAM). + * @param protocol The protocol of the socket (e.g., APR_PROTO_TCP). + * @param cont The pool for the apr_socket_t and associated storage. + * @note The pool will be used by various functions that operate on the + * socket. The caller must ensure that it is not used by other threads + * at the same time. + */ +APR_DECLARE(apr_status_t) apr_socket_create(apr_socket_t **new_sock, + int family, int type, + int protocol, + apr_pool_t *cont); + +/** + * Shutdown either reading, writing, or both sides of a socket. + * @param thesocket The socket to close + * @param how How to shutdown the socket. One of: + *
+ *            APR_SHUTDOWN_READ         no longer allow read requests
+ *            APR_SHUTDOWN_WRITE        no longer allow write requests
+ *            APR_SHUTDOWN_READWRITE    no longer allow read or write requests 
+ * 
+ * @see apr_shutdown_how_e + * @remark This does not actually close the socket descriptor, it just + * controls which calls are still valid on the socket. + */ +APR_DECLARE(apr_status_t) apr_socket_shutdown(apr_socket_t *thesocket, + apr_shutdown_how_e how); + +/** + * Close a socket. + * @param thesocket The socket to close + */ +APR_DECLARE(apr_status_t) apr_socket_close(apr_socket_t *thesocket); + +/** + * Bind the socket to its associated port + * @param sock The socket to bind + * @param sa The socket address to bind to + * @remark This may be where we will find out if there is any other process + * using the selected port. + */ +APR_DECLARE(apr_status_t) apr_socket_bind(apr_socket_t *sock, + apr_sockaddr_t *sa); + +/** + * Listen to a bound socket for connections. + * @param sock The socket to listen on + * @param backlog The number of outstanding connections allowed in the sockets + * listen queue. If this value is less than zero, the listen + * queue size is set to zero. + */ +APR_DECLARE(apr_status_t) apr_socket_listen(apr_socket_t *sock, + apr_int32_t backlog); + +/** + * Accept a new connection request + * @param new_sock A copy of the socket that is connected to the socket that + * made the connection request. This is the socket which should + * be used for all future communication. + * @param sock The socket we are listening on. + * @param connection_pool The pool for the new socket. + * @note The pool will be used by various functions that operate on the + * socket. The caller must ensure that it is not used by other threads + * at the same time. + */ +APR_DECLARE(apr_status_t) apr_socket_accept(apr_socket_t **new_sock, + apr_socket_t *sock, + apr_pool_t *connection_pool); + +/** + * Issue a connection request to a socket either on the same machine + * or a different one. + * @param sock The socket we wish to use for our side of the connection + * @param sa The address of the machine we wish to connect to. + */ +APR_DECLARE(apr_status_t) apr_socket_connect(apr_socket_t *sock, + apr_sockaddr_t *sa); + +/** + * Determine whether the receive part of the socket has been closed by + * the peer (such that a subsequent call to apr_socket_read would + * return APR_EOF), if the socket's receive buffer is empty. This + * function does not block waiting for I/O. + * + * @param sock The socket to check + * @param atreadeof If APR_SUCCESS is returned, *atreadeof is set to + * non-zero if a subsequent read would return APR_EOF + * @return an error is returned if it was not possible to determine the + * status, in which case *atreadeof is not changed. + */ +APR_DECLARE(apr_status_t) apr_socket_atreadeof(apr_socket_t *sock, + int *atreadeof); + +/** + * Create apr_sockaddr_t from hostname, address family, and port. + * @param sa The new apr_sockaddr_t. + * @param hostname The hostname or numeric address string to resolve/parse, or + * NULL to build an address that corresponds to 0.0.0.0 or :: + * or in case of APR_UNIX family it is absolute socket filename. + * @param family The address family to use, or APR_UNSPEC if the system should + * decide. + * @param port The port number. + * @param flags Special processing flags: + *
+ *       APR_IPV4_ADDR_OK          first query for IPv4 addresses; only look
+ *                                 for IPv6 addresses if the first query failed;
+ *                                 only valid if family is APR_UNSPEC and hostname
+ *                                 isn't NULL; mutually exclusive with
+ *                                 APR_IPV6_ADDR_OK
+ *       APR_IPV6_ADDR_OK          first query for IPv6 addresses; only look
+ *                                 for IPv4 addresses if the first query failed;
+ *                                 only valid if family is APR_UNSPEC and hostname
+ *                                 isn't NULL and APR_HAVE_IPV6; mutually exclusive
+ *                                 with APR_IPV4_ADDR_OK
+ * 
+ * @param p The pool for the apr_sockaddr_t and associated storage. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_info_get(apr_sockaddr_t **sa, + const char *hostname, + apr_int32_t family, + apr_port_t port, + apr_int32_t flags, + apr_pool_t *p); + +/** + * Copy apr_sockaddr_t src to dst on pool p. + * @param dst The destination apr_sockaddr_t. + * @param src The source apr_sockaddr_t. + * @param p The pool for the apr_sockaddr_t and associated storage. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_info_copy(apr_sockaddr_t **dst, + const apr_sockaddr_t *src, + apr_pool_t *p); + +/** + * Set the zone of an IPv6 link-local address object. + * @param sa Socket address object + * @param zone_id Zone ID (textual "eth0" or numeric "3"). + * @return Returns APR_EBADIP for non-IPv6 socket or an IPv6 address + * which isn't link-local. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_zone_set(apr_sockaddr_t *sa, + const char *zone_id); + + +/** + * Retrieve the zone of an IPv6 link-local address object. + * @param sa Socket address object + * @param name If non-NULL, set to the textual representation of the zone id + * @param id If non-NULL, set to the integer zone id + * @param p Pool from which *name is allocated if used. + * @return Returns APR_EBADIP for non-IPv6 socket or socket without any zone id + * set, or other error if the interface could not be mapped to a name. + * @remark Both name and id may be NULL, neither are modified if + * non-NULL in error cases. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_zone_get(const apr_sockaddr_t *sa, + const char **name, + apr_uint32_t *id, + apr_pool_t *p); + +/** + * Look up the host name from an apr_sockaddr_t. + * @param hostname The hostname. + * @param sa The apr_sockaddr_t. + * @param flags Special processing flags. + * @remark Results can vary significantly between platforms + * when processing wildcard socket addresses. + */ +APR_DECLARE(apr_status_t) apr_getnameinfo(char **hostname, + apr_sockaddr_t *sa, + apr_int32_t flags); + +/** + * Parse hostname/IP address with scope id and port. + * + * Any of the following strings are accepted: + * 8080 (just the port number) + * www.apache.org (just the hostname) + * www.apache.org:8080 (hostname and port number) + * [fe80::1]:80 (IPv6 numeric address string only) + * [fe80::1%eth0] (IPv6 numeric address string and scope id) + * + * Invalid strings: + * (empty string) + * [abc] (not valid IPv6 numeric address string) + * abc:65536 (invalid port number) + * + * @param addr The new buffer containing just the hostname. On output, *addr + * will be NULL if no hostname/IP address was specfied. + * @param scope_id The new buffer containing just the scope id. On output, + * *scope_id will be NULL if no scope id was specified. + * @param port The port number. On output, *port will be 0 if no port was + * specified. + * ### FIXME: 0 is a legal port (per RFC 1700). this should + * ### return something besides zero if the port is missing. + * @param str The input string to be parsed. + * @param p The pool from which *addr and *scope_id are allocated. + * @remark If scope id shouldn't be allowed, check for scope_id != NULL in + * addition to checking the return code. If addr/hostname should be + * required, check for addr == NULL in addition to checking the + * return code. + */ +APR_DECLARE(apr_status_t) apr_parse_addr_port(char **addr, + char **scope_id, + apr_port_t *port, + const char *str, + apr_pool_t *p); + +/** + * Get name of the current machine + * @param buf A buffer to store the hostname in. + * @param len The maximum length of the hostname that can be stored in the + * buffer provided. The suggested length is APRMAXHOSTLEN + 1. + * @param cont The pool to use. + * @remark If the buffer was not large enough, an error will be returned. + */ +APR_DECLARE(apr_status_t) apr_gethostname(char *buf, int len, apr_pool_t *cont); + +/** + * Return the data associated with the current socket + * @param data The user data associated with the socket. + * @param key The key to associate with the user data. + * @param sock The currently open socket. + */ +APR_DECLARE(apr_status_t) apr_socket_data_get(void **data, const char *key, + apr_socket_t *sock); + +/** + * Set the data associated with the current socket. + * @param sock The currently open socket. + * @param data The user data to associate with the socket. + * @param key The key to associate with the data. + * @param cleanup The cleanup to call when the socket is destroyed. + */ +APR_DECLARE(apr_status_t) apr_socket_data_set(apr_socket_t *sock, void *data, + const char *key, + apr_status_t (*cleanup)(void*)); + +/** + * Send data over a network. + * @param sock The socket to send the data over. + * @param buf The buffer which contains the data to be sent. + * @param len On entry, the number of bytes to send; on exit, the number + * of bytes sent. + * @remark + *
+ * This functions acts like a blocking write by default.  To change 
+ * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK
+ * socket option.
+ *
+ * It is possible for both bytes to be sent and an error to be returned.
+ *
+ * APR_EINTR is never returned.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_socket_send(apr_socket_t *sock, const char *buf, + apr_size_t *len); + +/** + * Send multiple buffers over a network. + * @param sock The socket to send the data over. + * @param vec The array of iovec structs containing the data to send + * @param nvec The number of iovec structs in the array + * @param len Receives the number of bytes actually written + * @remark + *
+ * This functions acts like a blocking write by default.  To change 
+ * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK
+ * socket option.
+ * The number of bytes actually sent is stored in argument 4.
+ *
+ * It is possible for both bytes to be sent and an error to be returned.
+ *
+ * APR_EINTR is never returned.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_socket_sendv(apr_socket_t *sock, + const struct iovec *vec, + apr_int32_t nvec, apr_size_t *len); + +/** + * @param sock The socket to send from + * @param where The apr_sockaddr_t describing where to send the data + * @param flags The flags to use + * @param buf The data to send + * @param len The length of the data to send + */ +APR_DECLARE(apr_status_t) apr_socket_sendto(apr_socket_t *sock, + apr_sockaddr_t *where, + apr_int32_t flags, const char *buf, + apr_size_t *len); + +/** + * Read data from a socket. On success, the address of the peer from + * which the data was sent is copied into the @a from parameter, and the + * @a len parameter is updated to give the number of bytes written to + * @a buf. + * + * @param from Updated with the address from which the data was received + * @param sock The socket to use + * @param flags The flags to use + * @param buf The buffer to use + * @param len The length of the available buffer + */ + +APR_DECLARE(apr_status_t) apr_socket_recvfrom(apr_sockaddr_t *from, + apr_socket_t *sock, + apr_int32_t flags, char *buf, + apr_size_t *len); + +#if APR_HAS_SENDFILE || defined(DOXYGEN) + +/** + * Send a file from an open file descriptor to a socket, along with + * optional headers and trailers + * @param sock The socket to which we're writing + * @param file The open file from which to read + * @param hdtr A structure containing the headers and trailers to send + * @param offset Offset into the file where we should begin writing + * @param len (input) - Number of bytes to send from the file + * (output) - Number of bytes actually sent, + * including headers, file, and trailers + * @param flags APR flags that are mapped to OS specific flags + * @remark This functions acts like a blocking write by default. To change + * this behavior, use apr_socket_timeout_set() or the + * APR_SO_NONBLOCK socket option. + * The number of bytes actually sent is stored in the len parameter. + * The offset parameter is passed by reference for no reason; its + * value will never be modified by the apr_socket_sendfile() function. + */ +APR_DECLARE(apr_status_t) apr_socket_sendfile(apr_socket_t *sock, + apr_file_t *file, + apr_hdtr_t *hdtr, + apr_off_t *offset, + apr_size_t *len, + apr_int32_t flags); + +#endif /* APR_HAS_SENDFILE */ + +/** + * Read data from a network. + * @param sock The socket to read the data from. + * @param buf The buffer to store the data in. + * @param len On entry, the number of bytes to receive; on exit, the number + * of bytes received. + * @remark + *
+ * This functions acts like a blocking read by default.  To change 
+ * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK
+ * socket option.
+ * The number of bytes actually received is stored in argument 3.
+ *
+ * It is possible for both bytes to be received and an APR_EOF or
+ * other error to be returned.
+ *
+ * APR_EINTR is never returned.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_socket_recv(apr_socket_t *sock, + char *buf, apr_size_t *len); + +/** + * Setup socket options for the specified socket + * @param sock The socket to set up. + * @param opt The option we would like to configure. One of: + *
+ *            APR_SO_DEBUG      --  turn on debugging information 
+ *            APR_SO_KEEPALIVE  --  keep connections active
+ *            APR_SO_LINGER     --  lingers on close if data is present
+ *            APR_SO_NONBLOCK   --  Turns blocking on/off for socket
+ *                                  When this option is enabled, use
+ *                                  the APR_STATUS_IS_EAGAIN() macro to
+ *                                  see if a send or receive function
+ *                                  could not transfer data without
+ *                                  blocking.
+ *            APR_SO_REUSEADDR  --  The rules used in validating addresses
+ *                                  supplied to bind should allow reuse
+ *                                  of local addresses.
+ *            APR_SO_SNDBUF     --  Set the SendBufferSize
+ *            APR_SO_RCVBUF     --  Set the ReceiveBufferSize
+ *            APR_SO_FREEBIND   --  Allow binding to non-local IP address.
+ * 
+ * @param on Value for the option. + */ +APR_DECLARE(apr_status_t) apr_socket_opt_set(apr_socket_t *sock, + apr_int32_t opt, apr_int32_t on); + +/** + * Setup socket timeout for the specified socket + * @param sock The socket to set up. + * @param t Value for the timeout. + *
+ *   t > 0  -- read and write calls return APR_TIMEUP if specified time
+ *             elapsess with no data read or written
+ *   t == 0 -- read and write calls never block
+ *   t < 0  -- read and write calls block
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_socket_timeout_set(apr_socket_t *sock, + apr_interval_time_t t); + +/** + * Query socket options for the specified socket + * @param sock The socket to query + * @param opt The option we would like to query. One of: + *
+ *            APR_SO_DEBUG      --  turn on debugging information 
+ *            APR_SO_KEEPALIVE  --  keep connections active
+ *            APR_SO_LINGER     --  lingers on close if data is present
+ *            APR_SO_NONBLOCK   --  Turns blocking on/off for socket
+ *            APR_SO_REUSEADDR  --  The rules used in validating addresses
+ *                                  supplied to bind should allow reuse
+ *                                  of local addresses.
+ *            APR_SO_SNDBUF     --  Set the SendBufferSize
+ *            APR_SO_RCVBUF     --  Set the ReceiveBufferSize
+ *            APR_SO_DISCONNECTED -- Query the disconnected state of the socket.
+ *                                  (Currently only used on Windows)
+ * 
+ * @param on Socket option returned on the call. + */ +APR_DECLARE(apr_status_t) apr_socket_opt_get(apr_socket_t *sock, + apr_int32_t opt, apr_int32_t *on); + +/** + * Query socket timeout for the specified socket + * @param sock The socket to query + * @param t Socket timeout returned from the query. + */ +APR_DECLARE(apr_status_t) apr_socket_timeout_get(apr_socket_t *sock, + apr_interval_time_t *t); + +/** + * Query the specified socket if at the OOB/Urgent data mark + * @param sock The socket to query + * @param atmark Is set to true if socket is at the OOB/urgent mark, + * otherwise is set to false. + */ +APR_DECLARE(apr_status_t) apr_socket_atmark(apr_socket_t *sock, + int *atmark); + +/** + * Return an address associated with a socket; either the address to + * which the socket is bound locally or the address of the peer + * to which the socket is connected. + * @param sa The returned apr_sockaddr_t. + * @param which Whether to retrieve the local or remote address + * @param sock The socket to use + */ +APR_DECLARE(apr_status_t) apr_socket_addr_get(apr_sockaddr_t **sa, + apr_interface_e which, + apr_socket_t *sock); + +/** + * Return the IP address (in numeric address string format) in + * an APR socket address. APR will allocate storage for the IP address + * string from the pool of the apr_sockaddr_t. + * @param addr The IP address. + * @param sockaddr The socket address to reference. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_ip_get(char **addr, + apr_sockaddr_t *sockaddr); + +/** + * Write the IP address (in numeric address string format) of the APR + * socket address @a sockaddr into the buffer @a buf (of size @a buflen). + * @param sockaddr The socket address to reference. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_ip_getbuf(char *buf, apr_size_t buflen, + apr_sockaddr_t *sockaddr); + +/** + * See if the IP addresses in two APR socket addresses are + * equivalent. Appropriate logic is present for comparing + * IPv4-mapped IPv6 addresses with IPv4 addresses. + * + * @param addr1 One of the APR socket addresses. + * @param addr2 The other APR socket address. + * @remark The return value will be non-zero if the addresses + * are equivalent. + */ +APR_DECLARE(int) apr_sockaddr_equal(const apr_sockaddr_t *addr1, + const apr_sockaddr_t *addr2); + +/** + * See if the IP address in an APR socket address refers to the wildcard + * address for the protocol family (e.g., INADDR_ANY for IPv4). + * + * @param addr The APR socket address to examine. + * @remark The return value will be non-zero if the address is + * initialized and is the wildcard address. + */ +APR_DECLARE(int) apr_sockaddr_is_wildcard(const apr_sockaddr_t *addr); + +/** +* Return the type of the socket. +* @param sock The socket to query. +* @param type The returned type (e.g., SOCK_STREAM). +*/ +APR_DECLARE(apr_status_t) apr_socket_type_get(apr_socket_t *sock, + int *type); + +/** + * Given an apr_sockaddr_t and a service name, set the port for the service + * @param sockaddr The apr_sockaddr_t that will have its port set + * @param servname The name of the service you wish to use + */ +APR_DECLARE(apr_status_t) apr_getservbyname(apr_sockaddr_t *sockaddr, + const char *servname); +/** + * Build an ip-subnet representation from an IP address and optional netmask or + * number-of-bits. + * @param ipsub The new ip-subnet representation + * @param ipstr The input IP address string + * @param mask_or_numbits The input netmask or number-of-bits string, or NULL + * @param p The pool to allocate from + */ +APR_DECLARE(apr_status_t) apr_ipsubnet_create(apr_ipsubnet_t **ipsub, + const char *ipstr, + const char *mask_or_numbits, + apr_pool_t *p); + +/** + * Test the IP address in an apr_sockaddr_t against a pre-built ip-subnet + * representation. + * @param ipsub The ip-subnet representation + * @param sa The socket address to test + * @return non-zero if the socket address is within the subnet, 0 otherwise + */ +APR_DECLARE(int) apr_ipsubnet_test(apr_ipsubnet_t *ipsub, apr_sockaddr_t *sa); + +#if APR_HAS_SO_ACCEPTFILTER || defined(DOXYGEN) +/** + * Set an OS level accept filter. + * @param sock The socket to put the accept filter on. + * @param name The accept filter + * @param args Any extra args to the accept filter. Passing NULL here removes + * the accept filter. + * @bug name and args should have been declared as const char *, as they are in + * APR 2.0 + */ +apr_status_t apr_socket_accept_filter(apr_socket_t *sock, char *name, + char *args); +#endif + +/** + * Return the protocol of the socket. + * @param sock The socket to query. + * @param protocol The returned protocol (e.g., APR_PROTO_TCP). + */ +APR_DECLARE(apr_status_t) apr_socket_protocol_get(apr_socket_t *sock, + int *protocol); + +/** + * Get the pool used by the socket. + */ +APR_POOL_DECLARE_ACCESSOR(socket); + +/** + * Set a socket to be inherited by child processes. + */ +APR_DECLARE_INHERIT_SET(socket); + +/** + * Unset a socket from being inherited by child processes. + */ +APR_DECLARE_INHERIT_UNSET(socket); + +/** + * Set socket permissions. + */ +APR_PERMS_SET_IMPLEMENT(socket); + +/** + * @defgroup apr_mcast IP Multicast + * @{ + */ + +/** + * Join a Multicast Group + * @param sock The socket to join a multicast group + * @param join The address of the multicast group to join + * @param iface Address of the interface to use. If NULL is passed, the + * default multicast interface will be used. (OS Dependent) + * @param source Source Address to accept transmissions from (non-NULL + * implies Source-Specific Multicast) + */ +APR_DECLARE(apr_status_t) apr_mcast_join(apr_socket_t *sock, + apr_sockaddr_t *join, + apr_sockaddr_t *iface, + apr_sockaddr_t *source); + +/** + * Leave a Multicast Group. All arguments must be the same as + * apr_mcast_join. + * @param sock The socket to leave a multicast group + * @param addr The address of the multicast group to leave + * @param iface Address of the interface to use. If NULL is passed, the + * default multicast interface will be used. (OS Dependent) + * @param source Source Address to accept transmissions from (non-NULL + * implies Source-Specific Multicast) + */ +APR_DECLARE(apr_status_t) apr_mcast_leave(apr_socket_t *sock, + apr_sockaddr_t *addr, + apr_sockaddr_t *iface, + apr_sockaddr_t *source); + +/** + * Set the Multicast Time to Live (ttl) for a multicast transmission. + * @param sock The socket to set the multicast ttl + * @param ttl Time to live to Assign. 0-255, default=1 + * @remark If the TTL is 0, packets will only be seen by sockets on + * the local machine, and only when multicast loopback is enabled. + */ +APR_DECLARE(apr_status_t) apr_mcast_hops(apr_socket_t *sock, + apr_byte_t ttl); + +/** + * Toggle IP Multicast Loopback + * @param sock The socket to set multicast loopback + * @param opt 0=disable, 1=enable + */ +APR_DECLARE(apr_status_t) apr_mcast_loopback(apr_socket_t *sock, + apr_byte_t opt); + + +/** + * Set the Interface to be used for outgoing Multicast Transmissions. + * @param sock The socket to set the multicast interface on + * @param iface Address of the interface to use for Multicast + */ +APR_DECLARE(apr_status_t) apr_mcast_interface(apr_socket_t *sock, + apr_sockaddr_t *iface); + +/** @} */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_NETWORK_IO_H */ + diff --git a/c/dependencies/macos/apr/include/apr_optional.h b/c/dependencies/macos/apr/include/apr_optional.h new file mode 100644 index 00000000..3301d66e --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_optional.h @@ -0,0 +1,92 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_OPTIONAL_H +#define APR_OPTIONAL_H + +#include "apu.h" +/** + * @file apr_optional.h + * @brief APR-UTIL registration of functions exported by modules + */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Opt Optional Functions + * @ingroup APR_Util + * + * Typesafe registration and retrieval of functions that may not be present + * (i.e. functions exported by optional modules) + * @{ + */ + +/** + * The type of an optional function. + * @param name The name of the function + */ +#define APR_OPTIONAL_FN_TYPE(name) apr_OFN_##name##_t + +/** + * Declare an optional function. + * @param ret The return type of the function + * @param name The name of the function + * @param args The function arguments (including brackets) + */ +#define APR_DECLARE_OPTIONAL_FN(ret,name,args) \ +typedef ret (APR_OPTIONAL_FN_TYPE(name)) args + +/** + * XXX: This doesn't belong here, then! + * Private function! DO NOT USE! + * @internal + */ + +typedef void (apr_opt_fn_t)(void); +/** @internal */ +APU_DECLARE_NONSTD(void) apr_dynamic_fn_register(const char *szName, + apr_opt_fn_t *pfn); + +/** + * Register an optional function. This can be later retrieved, type-safely, by + * name. Like all global functions, the name must be unique. Note that, + * confusingly but correctly, the function itself can be static! + * @param name The name of the function + */ +#define APR_REGISTER_OPTIONAL_FN(name) do { \ + APR_OPTIONAL_FN_TYPE(name) *apu__opt = name; \ + apr_dynamic_fn_register(#name,(apr_opt_fn_t *)apu__opt); \ +} while (0) + +/** @internal + * Private function! DO NOT USE! + */ +APU_DECLARE(apr_opt_fn_t *) apr_dynamic_fn_retrieve(const char *szName); + +/** + * Retrieve an optional function. Returns NULL if the function is not present. + * @param name The name of the function + */ +#define APR_RETRIEVE_OPTIONAL_FN(name) \ + (APR_OPTIONAL_FN_TYPE(name) *)apr_dynamic_fn_retrieve(#name) + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_OPTIONAL_H */ diff --git a/c/dependencies/macos/apr/include/apr_optional_hooks.h b/c/dependencies/macos/apr/include/apr_optional_hooks.h new file mode 100644 index 00000000..8265f03f --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_optional_hooks.h @@ -0,0 +1,117 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file apr_optional_hooks.h + * @brief Apache optional hook functions + */ + + +#ifndef APR_OPTIONAL_HOOK_H +#define APR_OPTIONAL_HOOK_H + +#include "apr_tables.h" + +#ifdef __cplusplus +extern "C" { +#endif +/** + * @defgroup APR_Util_OPT_HOOK Optional Hook Functions + * @ingroup APR_Util_Hook + * @{ + */ +/** + * Function to implement the APR_OPTIONAL_HOOK Macro + * @internal + * @see APR_OPTIONAL_HOOK + * + * @param szName The name of the hook + * @param pfn A pointer to a function that will be called + * @param aszPre a NULL-terminated array of strings that name modules whose hooks should precede this one + * @param aszSucc a NULL-terminated array of strings that name modules whose hooks should succeed this one + * @param nOrder an integer determining order before honouring aszPre and aszSucc (for example HOOK_MIDDLE) + */ + + +APU_DECLARE(void) apr_optional_hook_add(const char *szName,void (*pfn)(void), + const char * const *aszPre, + const char * const *aszSucc, + int nOrder); + +/** + * Hook to an optional hook. + * + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param pfn A pointer to a function that will be called + * @param aszPre a NULL-terminated array of strings that name modules whose hooks should precede this one + * @param aszSucc a NULL-terminated array of strings that name modules whose hooks should succeed this one + * @param nOrder an integer determining order before honouring aszPre and aszSucc (for example HOOK_MIDDLE) + */ + +#define APR_OPTIONAL_HOOK(ns,name,pfn,aszPre,aszSucc,nOrder) do { \ + ns##_HOOK_##name##_t *apu__hook = pfn; \ + apr_optional_hook_add(#name,(void (*)(void))apu__hook,aszPre, aszSucc, nOrder); \ +} while (0) + +/** + * @internal + * @param szName - the name of the function + * @return the hook structure for a given hook + */ +APU_DECLARE(apr_array_header_t *) apr_optional_hook_get(const char *szName); + +/** + * Implement an optional hook that runs until one of the functions + * returns something other than OK or DECLINE. + * + * @param ns The namespace prefix of the hook functions + * @param link The linkage declaration prefix of the hook + * @param ret The type of the return value of the hook + * @param ret The type of the return value of the hook + * @param name The name of the hook + * @param args_decl The declaration of the arguments for the hook + * @param args_use The names for the arguments for the hook + * @param ok Success value + * @param decline Decline value + */ +#define APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(ns,link,ret,name,args_decl,args_use,ok,decline) \ +link##_DECLARE(ret) ns##_run_##name args_decl \ + { \ + ns##_LINK_##name##_t *pHook; \ + int n; \ + ret rv; \ + apr_array_header_t *pHookArray=apr_optional_hook_get(#name); \ +\ + if(!pHookArray) \ + return ok; \ +\ + pHook=(ns##_LINK_##name##_t *)pHookArray->elts; \ + for(n=0 ; n < pHookArray->nelts ; ++n) \ + { \ + rv=(pHook[n].pFunc)args_use; \ +\ + if(rv != ok && rv != decline) \ + return rv; \ + } \ + return ok; \ + } + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_OPTIONAL_HOOK_H */ diff --git a/c/dependencies/macos/apr/include/apr_perms_set.h b/c/dependencies/macos/apr/include/apr_perms_set.h new file mode 100644 index 00000000..92a1362b --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_perms_set.h @@ -0,0 +1,65 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_PERMS_SET_H +#define APR_PERMS_SET_H + +/** + * @file apr_perms_set.h + * @brief APR Process Locking Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_user.h" +#include "apr_file_info.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_perms_set Object permission set functions + * @ingroup APR + * @{ + */ + +/** Permission set callback function. */ +typedef apr_status_t (apr_perms_setfn_t)(void *object, apr_fileperms_t perms, + apr_uid_t uid, apr_gid_t gid); + +#define APR_PERMS_SET_IMPLEMENT(type) \ + APR_DECLARE(apr_status_t) apr_##type##_perms_set \ + (void *the##type, apr_fileperms_t perms, \ + apr_uid_t uid, apr_gid_t gid) + +#define APR_PERMS_SET_ENOTIMPL(type) \ + APR_DECLARE(apr_status_t) apr_##type##_perms_set \ + (void *the##type, apr_fileperms_t perms, \ + apr_uid_t uid, apr_gid_t gid) \ + { return APR_ENOTIMPL ; } + +#define APR_PERMS_SET_FN(type) apr_##type##_perms_set + + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_PERMS_SET */ diff --git a/c/dependencies/macos/apr/include/apr_poll.h b/c/dependencies/macos/apr/include/apr_poll.h new file mode 100644 index 00000000..482d6ee1 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_poll.h @@ -0,0 +1,446 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_POLL_H +#define APR_POLL_H +/** + * @file apr_poll.h + * @brief APR Poll interface + */ +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_inherit.h" +#include "apr_file_io.h" +#include "apr_network_io.h" + +#if APR_HAVE_NETINET_IN_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_poll Poll Routines + * @ingroup APR + * @{ + */ + +/** + * @defgroup pollopts Poll options + * @ingroup apr_poll + * @{ + */ +#define APR_POLLIN 0x001 /**< Can read without blocking */ +#define APR_POLLPRI 0x002 /**< Priority data available */ +#define APR_POLLOUT 0x004 /**< Can write without blocking */ +#define APR_POLLERR 0x010 /**< Pending error */ +#define APR_POLLHUP 0x020 /**< Hangup occurred */ +#define APR_POLLNVAL 0x040 /**< Descriptor invalid */ +/** @} */ + +/** + * @defgroup pollflags Pollset Flags + * @ingroup apr_poll + * @{ + */ +#define APR_POLLSET_THREADSAFE 0x001 /**< Adding or removing a descriptor is + * thread-safe + */ +#define APR_POLLSET_NOCOPY 0x002 /**< Descriptors passed to apr_pollset_add() + * are not copied + */ +#define APR_POLLSET_WAKEABLE 0x004 /**< Poll operations are interruptable by + * apr_pollset_wakeup() or apr_pollcb_wakeup() + */ +#define APR_POLLSET_NODEFAULT 0x010 /**< Do not try to use the default method if + * the specified non-default method cannot be + * used + */ +/** @} */ + +/** + * Pollset Methods + */ +typedef enum { + APR_POLLSET_DEFAULT, /**< Platform default poll method */ + APR_POLLSET_SELECT, /**< Poll uses select method */ + APR_POLLSET_KQUEUE, /**< Poll uses kqueue method */ + APR_POLLSET_PORT, /**< Poll uses Solaris event port method */ + APR_POLLSET_EPOLL, /**< Poll uses epoll method */ + APR_POLLSET_POLL, /**< Poll uses poll method */ + APR_POLLSET_AIO_MSGQ /**< Poll uses z/OS asio method */ +} apr_pollset_method_e; + +/** Used in apr_pollfd_t to determine what the apr_descriptor is */ +typedef enum { + APR_NO_DESC, /**< nothing here */ + APR_POLL_SOCKET, /**< descriptor refers to a socket */ + APR_POLL_FILE, /**< descriptor refers to a file */ + APR_POLL_LASTDESC /**< @deprecated descriptor is the last one in the list */ +} apr_datatype_e ; + +/** Union of either an APR file or socket. */ +typedef union { + apr_file_t *f; /**< file */ + apr_socket_t *s; /**< socket */ +} apr_descriptor; + +/** @see apr_pollfd_t */ +typedef struct apr_pollfd_t apr_pollfd_t; + +/** Poll descriptor set. */ +struct apr_pollfd_t { + apr_pool_t *p; /**< associated pool */ + apr_datatype_e desc_type; /**< descriptor type */ + apr_int16_t reqevents; /**< requested events */ + apr_int16_t rtnevents; /**< returned events */ + apr_descriptor desc; /**< @see apr_descriptor */ + void *client_data; /**< allows app to associate context */ +}; + + +/* General-purpose poll API for arbitrarily large numbers of + * file descriptors + */ + +/** Opaque structure used for pollset API */ +typedef struct apr_pollset_t apr_pollset_t; + +/** + * Set up a pollset object + * @param pollset The pointer in which to return the newly created object + * @param size The maximum number of descriptors that this pollset can hold + * @param p The pool from which to allocate the pollset + * @param flags Optional flags to modify the operation of the pollset. + * + * @remark If flags contains APR_POLLSET_THREADSAFE, then a pollset is + * created on which it is safe to make concurrent calls to + * apr_pollset_add(), apr_pollset_remove() and apr_pollset_poll() + * from separate threads. This feature is only supported on some + * platforms; the apr_pollset_create() call will fail with + * APR_ENOTIMPL on platforms where it is not supported. + * @remark If flags contains APR_POLLSET_WAKEABLE, then a pollset is + * created with an additional internal pipe object used for the + * apr_pollset_wakeup() call. The actual size of pollset is + * in that case @a size + 1. This feature is only supported on some + * platforms; the apr_pollset_create() call will fail with + * APR_ENOTIMPL on platforms where it is not supported. + * @remark If flags contains APR_POLLSET_NOCOPY, then the apr_pollfd_t + * structures passed to apr_pollset_add() are not copied and + * must have a lifetime at least as long as the pollset. + * @remark Some poll methods (including APR_POLLSET_KQUEUE, + * APR_POLLSET_PORT, and APR_POLLSET_EPOLL) do not have a + * fixed limit on the size of the pollset. For these methods, + * the size parameter controls the maximum number of + * descriptors that will be returned by a single call to + * apr_pollset_poll(). + */ +APR_DECLARE(apr_status_t) apr_pollset_create(apr_pollset_t **pollset, + apr_uint32_t size, + apr_pool_t *p, + apr_uint32_t flags); + +/** + * Set up a pollset object + * @param pollset The pointer in which to return the newly created object + * @param size The maximum number of descriptors that this pollset can hold + * @param p The pool from which to allocate the pollset + * @param flags Optional flags to modify the operation of the pollset. + * @param method Poll method to use. See #apr_pollset_method_e. If this + * method cannot be used, the default method will be used unless the + * APR_POLLSET_NODEFAULT flag has been specified. + * + * @remark If flags contains APR_POLLSET_THREADSAFE, then a pollset is + * created on which it is safe to make concurrent calls to + * apr_pollset_add(), apr_pollset_remove() and apr_pollset_poll() + * from separate threads. This feature is only supported on some + * platforms; the apr_pollset_create_ex() call will fail with + * APR_ENOTIMPL on platforms where it is not supported. + * @remark If flags contains APR_POLLSET_WAKEABLE, then a pollset is + * created with additional internal pipe object used for the + * apr_pollset_wakeup() call. The actual size of pollset is + * in that case size + 1. This feature is only supported on some + * platforms; the apr_pollset_create_ex() call will fail with + * APR_ENOTIMPL on platforms where it is not supported. + * @remark If flags contains APR_POLLSET_NOCOPY, then the apr_pollfd_t + * structures passed to apr_pollset_add() are not copied and + * must have a lifetime at least as long as the pollset. + * @remark Some poll methods (including APR_POLLSET_KQUEUE, + * APR_POLLSET_PORT, and APR_POLLSET_EPOLL) do not have a + * fixed limit on the size of the pollset. For these methods, + * the size parameter controls the maximum number of + * descriptors that will be returned by a single call to + * apr_pollset_poll(). + */ +APR_DECLARE(apr_status_t) apr_pollset_create_ex(apr_pollset_t **pollset, + apr_uint32_t size, + apr_pool_t *p, + apr_uint32_t flags, + apr_pollset_method_e method); + +/** + * Destroy a pollset object + * @param pollset The pollset to destroy + */ +APR_DECLARE(apr_status_t) apr_pollset_destroy(apr_pollset_t *pollset); + +/** + * Add a socket or file descriptor to a pollset + * @param pollset The pollset to which to add the descriptor + * @param descriptor The descriptor to add + * @remark If you set client_data in the descriptor, that value + * will be returned in the client_data field whenever this + * descriptor is signalled in apr_pollset_poll(). + * @remark If the pollset has been created with APR_POLLSET_THREADSAFE + * and thread T1 is blocked in a call to apr_pollset_poll() for + * this same pollset that is being modified via apr_pollset_add() + * in thread T2, the currently executing apr_pollset_poll() call in + * T1 will either: (1) automatically include the newly added descriptor + * in the set of descriptors it is watching or (2) return immediately + * with APR_EINTR. Option (1) is recommended, but option (2) is + * allowed for implementations where option (1) is impossible + * or impractical. + * @remark If the pollset has been created with APR_POLLSET_NOCOPY, the + * apr_pollfd_t structure referenced by descriptor will not be copied + * and must have a lifetime at least as long as the pollset. + * @remark Do not add the same socket or file descriptor to the same pollset + * multiple times, even if the requested events differ for the + * different calls to apr_pollset_add(). If the events of interest + * for a descriptor change, you must first remove the descriptor + * from the pollset with apr_pollset_remove(), then add it again + * specifying all requested events. + */ +APR_DECLARE(apr_status_t) apr_pollset_add(apr_pollset_t *pollset, + const apr_pollfd_t *descriptor); + +/** + * Remove a descriptor from a pollset + * @param pollset The pollset from which to remove the descriptor + * @param descriptor The descriptor to remove + * @remark If the descriptor is not found, APR_NOTFOUND is returned. + * @remark If the pollset has been created with APR_POLLSET_THREADSAFE + * and thread T1 is blocked in a call to apr_pollset_poll() for + * this same pollset that is being modified via apr_pollset_remove() + * in thread T2, the currently executing apr_pollset_poll() call in + * T1 will either: (1) automatically exclude the newly added descriptor + * in the set of descriptors it is watching or (2) return immediately + * with APR_EINTR. Option (1) is recommended, but option (2) is + * allowed for implementations where option (1) is impossible + * or impractical. + * @remark apr_pollset_remove() cannot be used to remove a subset of requested + * events for a descriptor. The reqevents field in the apr_pollfd_t + * parameter must contain the same value when removing as when adding. + */ +APR_DECLARE(apr_status_t) apr_pollset_remove(apr_pollset_t *pollset, + const apr_pollfd_t *descriptor); + +/** + * Block for activity on the descriptor(s) in a pollset + * @param pollset The pollset to use + * @param timeout The amount of time in microseconds to wait. This is a + * maximum, not a minimum. If a descriptor is signalled, the + * function will return before this time. If timeout is + * negative, the function will block until a descriptor is + * signalled or until apr_pollset_wakeup() has been called. + * @param num Number of signalled descriptors (output parameter) + * @param descriptors Array of signalled descriptors (output parameter) + * @remark APR_EINTR will be returned if the pollset has been created with + * APR_POLLSET_WAKEABLE, apr_pollset_wakeup() has been called while + * waiting for activity, and there were no signalled descriptors at the + * time of the wakeup call. + * @remark Multiple signalled conditions for the same descriptor may be reported + * in one or more returned apr_pollfd_t structures, depending on the + * implementation. + */ +APR_DECLARE(apr_status_t) apr_pollset_poll(apr_pollset_t *pollset, + apr_interval_time_t timeout, + apr_int32_t *num, + const apr_pollfd_t **descriptors); + +/** + * Interrupt the blocked apr_pollset_poll() call. + * @param pollset The pollset to use + * @remark If the pollset was not created with APR_POLLSET_WAKEABLE the + * return value is APR_EINIT. + */ +APR_DECLARE(apr_status_t) apr_pollset_wakeup(apr_pollset_t *pollset); + +/** + * Poll the descriptors in the poll structure + * @param aprset The poll structure we will be using. + * @param numsock The number of descriptors we are polling + * @param nsds The number of descriptors signalled (output parameter) + * @param timeout The amount of time in microseconds to wait. This is a + * maximum, not a minimum. If a descriptor is signalled, the + * function will return before this time. If timeout is + * negative, the function will block until a descriptor is + * signalled or until apr_pollset_wakeup() has been called. + * @remark The number of descriptors signalled is returned in the third argument. + * This is a blocking call, and it will not return until either a + * descriptor has been signalled or the timeout has expired. + * @remark The rtnevents field in the apr_pollfd_t array will only be filled- + * in if the return value is APR_SUCCESS. + */ +APR_DECLARE(apr_status_t) apr_poll(apr_pollfd_t *aprset, apr_int32_t numsock, + apr_int32_t *nsds, + apr_interval_time_t timeout); + +/** + * Return a printable representation of the pollset method. + * @param pollset The pollset to use + */ +APR_DECLARE(const char *) apr_pollset_method_name(apr_pollset_t *pollset); + +/** + * Return a printable representation of the default pollset method + * (APR_POLLSET_DEFAULT). + */ +APR_DECLARE(const char *) apr_poll_method_defname(void); + +/** Opaque structure used for pollcb API */ +typedef struct apr_pollcb_t apr_pollcb_t; + +/** + * Set up a pollcb object + * @param pollcb The pointer in which to return the newly created object + * @param size The maximum number of descriptors that a single _poll can return. + * @param p The pool from which to allocate the pollcb + * @param flags Optional flags to modify the operation of the pollcb. + * + * @remark If flags contains APR_POLLSET_WAKEABLE, then a pollcb is + * created with an additional internal pipe object used for the + * apr_pollcb_wakeup() call. The actual size of pollcb is + * in that case @a size + 1. + * @remark Pollcb is only supported on some platforms; the apr_pollcb_create() + * call will fail with APR_ENOTIMPL on platforms where it is not supported. + */ +APR_DECLARE(apr_status_t) apr_pollcb_create(apr_pollcb_t **pollcb, + apr_uint32_t size, + apr_pool_t *p, + apr_uint32_t flags); + +/** + * Set up a pollcb object + * @param pollcb The pointer in which to return the newly created object + * @param size The maximum number of descriptors that a single _poll can return. + * @param p The pool from which to allocate the pollcb + * @param flags Optional flags to modify the operation of the pollcb. + * @param method Poll method to use. See #apr_pollset_method_e. If this + * method cannot be used, the default method will be used unless the + * APR_POLLSET_NODEFAULT flag has been specified. + * + * @remark If flags contains APR_POLLSET_WAKEABLE, then a pollcb is + * created with an additional internal pipe object used for the + * apr_pollcb_wakeup() call. The actual size of pollcb is + * in that case @a size + 1. + * @remark Pollcb is only supported on some platforms; the apr_pollcb_create_ex() + * call will fail with APR_ENOTIMPL on platforms where it is not supported. + */ +APR_DECLARE(apr_status_t) apr_pollcb_create_ex(apr_pollcb_t **pollcb, + apr_uint32_t size, + apr_pool_t *p, + apr_uint32_t flags, + apr_pollset_method_e method); + +/** + * Add a socket or file descriptor to a pollcb + * @param pollcb The pollcb to which to add the descriptor + * @param descriptor The descriptor to add + * @remark If you set client_data in the descriptor, that value will be + * returned in the client_data field whenever this descriptor is + * signalled in apr_pollcb_poll(). + * @remark Unlike the apr_pollset API, the descriptor is not copied, and users + * must retain the memory used by descriptor, as the same pointer will + * be returned to them from apr_pollcb_poll. + * @remark Do not add the same socket or file descriptor to the same pollcb + * multiple times, even if the requested events differ for the + * different calls to apr_pollcb_add(). If the events of interest + * for a descriptor change, you must first remove the descriptor + * from the pollcb with apr_pollcb_remove(), then add it again + * specifying all requested events. + */ +APR_DECLARE(apr_status_t) apr_pollcb_add(apr_pollcb_t *pollcb, + apr_pollfd_t *descriptor); +/** + * Remove a descriptor from a pollcb + * @param pollcb The pollcb from which to remove the descriptor + * @param descriptor The descriptor to remove + * @remark If the descriptor is not found, APR_NOTFOUND is returned. + * @remark apr_pollcb_remove() cannot be used to remove a subset of requested + * events for a descriptor. The reqevents field in the apr_pollfd_t + * parameter must contain the same value when removing as when adding. + */ +APR_DECLARE(apr_status_t) apr_pollcb_remove(apr_pollcb_t *pollcb, + apr_pollfd_t *descriptor); + +/** + * Function prototype for pollcb handlers + * @param baton Opaque baton passed into apr_pollcb_poll() + * @param descriptor Contains the notification for an active descriptor. + * The @a rtnevents member describes which events were triggered + * for this descriptor. + * @remark If the pollcb handler does not return APR_SUCCESS, the apr_pollcb_poll() + * call returns with the handler's return value. + */ +typedef apr_status_t (*apr_pollcb_cb_t)(void *baton, apr_pollfd_t *descriptor); + +/** + * Block for activity on the descriptor(s) in a pollcb + * @param pollcb The pollcb to use + * @param timeout The amount of time in microseconds to wait. This is a + * maximum, not a minimum. If a descriptor is signalled, the + * function will return before this time. If timeout is + * negative, the function will block until a descriptor is + * signalled or until apr_pollcb_wakeup() has been called. + * @param func Callback function to call for each active descriptor. + * @param baton Opaque baton passed to the callback function. + * @remark Multiple signalled conditions for the same descriptor may be reported + * in one or more calls to the callback function, depending on the + * implementation. + * @remark APR_EINTR will be returned if the pollset has been created with + * APR_POLLSET_WAKEABLE and apr_pollcb_wakeup() has been called while + * waiting for activity. + */ +APR_DECLARE(apr_status_t) apr_pollcb_poll(apr_pollcb_t *pollcb, + apr_interval_time_t timeout, + apr_pollcb_cb_t func, + void *baton); + +/** + * Interrupt the blocked apr_pollcb_poll() call. + * @param pollcb The pollcb to use + * @remark If the pollcb was not created with APR_POLLSET_WAKEABLE the + * return value is APR_EINIT. + */ +APR_DECLARE(apr_status_t) apr_pollcb_wakeup(apr_pollcb_t *pollcb); + +/** + * Return a printable representation of the pollcb method. + * @param pollcb The pollcb to use + */ +APR_DECLARE(const char *) apr_pollcb_method_name(apr_pollcb_t *pollcb); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_POLL_H */ + diff --git a/c/dependencies/macos/apr/include/apr_pools.h b/c/dependencies/macos/apr/include/apr_pools.h new file mode 100644 index 00000000..eae9c218 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_pools.h @@ -0,0 +1,815 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_POOLS_H +#define APR_POOLS_H + +/** + * @file apr_pools.h + * @brief APR memory allocation + * + * Resource allocation routines... + * + * designed so that we don't have to keep track of EVERYTHING so that + * it can be explicitly freed later (a fundamentally unsound strategy --- + * particularly in the presence of die()). + * + * Instead, we maintain pools, and allocate items (both memory and I/O + * handlers) from the pools --- currently there are two, one for + * per-transaction info, and one for config info. When a transaction is + * over, we can delete everything in the per-transaction apr_pool_t without + * fear, and without thinking too hard about it either. + * + * Note that most operations on pools are not thread-safe: a single pool + * should only be accessed by a single thread at any given time. The one + * exception to this rule is creating a subpool of a given pool: one or more + * threads can safely create subpools at the same time that another thread + * accesses the parent pool. + */ + +#include "apr.h" +#include "apr_errno.h" +#include "apr_general.h" /* for APR_STRINGIFY */ +#define APR_WANT_MEMFUNC /**< for no good reason? */ +#include "apr_want.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_pools Memory Pool Functions + * @ingroup APR + * @{ + */ + +/** The fundamental pool type */ +typedef struct apr_pool_t apr_pool_t; + + +/** + * Declaration helper macro to construct apr_foo_pool_get()s. + * + * This standardized macro is used by opaque (APR) data types to return + * the apr_pool_t that is associated with the data type. + * + * APR_POOL_DECLARE_ACCESSOR() is used in a header file to declare the + * accessor function. A typical usage and result would be: + *
+ *    APR_POOL_DECLARE_ACCESSOR(file);
+ * becomes:
+ *    APR_DECLARE(apr_pool_t *) apr_file_pool_get(const apr_file_t *thefile);
+ * 
+ * @remark Doxygen unwraps this macro (via doxygen.conf) to provide + * actual help for each specific occurrence of apr_foo_pool_get. + * @remark the linkage is specified for APR. It would be possible to expand + * the macros to support other linkages. + */ +#define APR_POOL_DECLARE_ACCESSOR(type) \ + APR_DECLARE(apr_pool_t *) apr_##type##_pool_get \ + (const apr_##type##_t *the##type) + +/** + * Implementation helper macro to provide apr_foo_pool_get()s. + * + * In the implementation, the APR_POOL_IMPLEMENT_ACCESSOR() is used to + * actually define the function. It assumes the field is named "pool". + */ +#define APR_POOL_IMPLEMENT_ACCESSOR(type) \ + APR_DECLARE(apr_pool_t *) apr_##type##_pool_get \ + (const apr_##type##_t *the##type) \ + { return the##type->pool; } + + +/** + * Pool debug levels + * + *
+ * | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
+ * ---------------------------------
+ * |   |   |   |   |   |   |   | x |  General debug code enabled (useful in
+ *                                    combination with --with-efence).
+ *
+ * |   |   |   |   |   |   | x |   |  Verbose output on stderr (report
+ *                                    CREATE, CLEAR, DESTROY).
+ *
+ * |   |   |   | x |   |   |   |   |  Verbose output on stderr (report
+ *                                    PALLOC, PCALLOC).
+ *
+ * |   |   |   |   |   | x |   |   |  Lifetime checking. On each use of a
+ *                                    pool, check its lifetime.  If the pool
+ *                                    is out of scope, abort().
+ *                                    In combination with the verbose flag
+ *                                    above, it will output LIFE in such an
+ *                                    event prior to aborting.
+ *
+ * |   |   |   |   | x |   |   |   |  Pool owner checking.  On each use of a
+ *                                    pool, check if the current thread is the
+ *                                    pool's owner.  If not, abort().  In
+ *                                    combination with the verbose flag above,
+ *                                    it will output OWNER in such an event
+ *                                    prior to aborting.  Use the debug
+ *                                    function apr_pool_owner_set() to switch
+ *                                    a pool's ownership.
+ *
+ * When no debug level was specified, assume general debug mode.
+ * If level 0 was specified, debugging is switched off.
+ * 
+ */ +#if defined(APR_POOL_DEBUG) +/* If APR_POOL_DEBUG is blank, we get 1; if it is a number, we get -1. */ +#if (APR_POOL_DEBUG - APR_POOL_DEBUG -1 == 1) +#undef APR_POOL_DEBUG +#define APR_POOL_DEBUG 1 +#endif +#else +#define APR_POOL_DEBUG 0 +#endif + +/** the place in the code where the particular function was called */ +#define APR_POOL__FILE_LINE__ __FILE__ ":" APR_STRINGIFY(__LINE__) + + + +/** A function that is called when allocation fails. */ +typedef int (*apr_abortfunc_t)(int retcode); + +/* + * APR memory structure manipulators (pools, tables, and arrays). + */ + +/* + * Initialization + */ + +/** + * Setup all of the internal structures required to use pools + * @remark Programs do NOT need to call this directly. APR will call this + * automatically from apr_initialize. + * @internal + */ +APR_DECLARE(apr_status_t) apr_pool_initialize(void); + +/** + * Tear down all of the internal structures required to use pools + * @remark Programs do NOT need to call this directly. APR will call this + * automatically from apr_terminate. + * @internal + */ +APR_DECLARE(void) apr_pool_terminate(void); + + +/* + * Pool creation/destruction + */ + +#include "apr_allocator.h" + +/** + * Create a new pool. + * @param newpool The pool we have just created. + * @param parent The parent pool. If this is NULL, the new pool is a root + * pool. If it is non-NULL, the new pool will inherit all + * of its parent pool's attributes, except the apr_pool_t will + * be a sub-pool. + * @param abort_fn A function to use if the pool cannot allocate more memory. + * @param allocator The allocator to use with the new pool. If NULL the + * allocator of the parent pool will be used. + * @remark This function is thread-safe, in the sense that multiple threads + * can safely create subpools of the same parent pool concurrently. + * Similarly, a subpool can be created by one thread at the same + * time that another thread accesses the parent pool. + */ +APR_DECLARE(apr_status_t) apr_pool_create_ex(apr_pool_t **newpool, + apr_pool_t *parent, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +/** + * Create a new pool. + * @deprecated @see apr_pool_create_unmanaged_ex. + */ +APR_DECLARE(apr_status_t) apr_pool_create_core_ex(apr_pool_t **newpool, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator); + +/** + * Create a new unmanaged pool. + * @param newpool The pool we have just created. + * @param abort_fn A function to use if the pool cannot allocate more memory. + * @param allocator The allocator to use with the new pool. If NULL a + * new allocator will be created with the new pool as owner. + * @remark An unmanaged pool is a special pool without a parent; it will + * NOT be destroyed upon apr_terminate. It must be explicitly + * destroyed by calling apr_pool_destroy, to prevent memory leaks. + * Use of this function is discouraged, think twice about whether + * you really really need it. + * @warning Any child cleanups registered against the new pool, or + * against sub-pools thereof, will not be executed during an + * invocation of apr_proc_create(), so resources created in an + * "unmanaged" pool hierarchy will leak to child processes. + */ +APR_DECLARE(apr_status_t) apr_pool_create_unmanaged_ex(apr_pool_t **newpool, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +/** + * Debug version of apr_pool_create_ex. + * @param newpool @see apr_pool_create. + * @param parent @see apr_pool_create. + * @param abort_fn @see apr_pool_create. + * @param allocator @see apr_pool_create. + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @remark Only available when APR_POOL_DEBUG is defined. + * Call this directly if you have your apr_pool_create_ex + * calls in a wrapper function and wish to override + * the file_line argument to reflect the caller of + * your wrapper function. If you do not have + * apr_pool_create_ex in a wrapper, trust the macro + * and don't call apr_pool_create_ex_debug directly. + */ +APR_DECLARE(apr_status_t) apr_pool_create_ex_debug(apr_pool_t **newpool, + apr_pool_t *parent, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pool_create_ex(newpool, parent, abort_fn, allocator) \ + apr_pool_create_ex_debug(newpool, parent, abort_fn, allocator, \ + APR_POOL__FILE_LINE__) +#endif + +/** + * Debug version of apr_pool_create_core_ex. + * @deprecated @see apr_pool_create_unmanaged_ex_debug. + */ +APR_DECLARE(apr_status_t) apr_pool_create_core_ex_debug(apr_pool_t **newpool, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator, + const char *file_line); + +/** + * Debug version of apr_pool_create_unmanaged_ex. + * @param newpool @see apr_pool_create_unmanaged. + * @param abort_fn @see apr_pool_create_unmanaged. + * @param allocator @see apr_pool_create_unmanaged. + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @remark Only available when APR_POOL_DEBUG is defined. + * Call this directly if you have your apr_pool_create_unmanaged_ex + * calls in a wrapper function and wish to override + * the file_line argument to reflect the caller of + * your wrapper function. If you do not have + * apr_pool_create_core_ex in a wrapper, trust the macro + * and don't call apr_pool_create_core_ex_debug directly. + */ +APR_DECLARE(apr_status_t) apr_pool_create_unmanaged_ex_debug(apr_pool_t **newpool, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pool_create_core_ex(newpool, abort_fn, allocator) \ + apr_pool_create_unmanaged_ex_debug(newpool, abort_fn, allocator, \ + APR_POOL__FILE_LINE__) + +#define apr_pool_create_unmanaged_ex(newpool, abort_fn, allocator) \ + apr_pool_create_unmanaged_ex_debug(newpool, abort_fn, allocator, \ + APR_POOL__FILE_LINE__) + +#endif + +/** + * Create a new pool. + * @param newpool The pool we have just created. + * @param parent The parent pool. If this is NULL, the new pool is a root + * pool. If it is non-NULL, the new pool will inherit all + * of its parent pool's attributes, except the apr_pool_t will + * be a sub-pool. + * @remark This function is thread-safe, in the sense that multiple threads + * can safely create subpools of the same parent pool concurrently. + * Similarly, a subpool can be created by one thread at the same + * time that another thread accesses the parent pool. + */ +#if defined(DOXYGEN) +APR_DECLARE(apr_status_t) apr_pool_create(apr_pool_t **newpool, + apr_pool_t *parent); +#else +#if APR_POOL_DEBUG +#define apr_pool_create(newpool, parent) \ + apr_pool_create_ex_debug(newpool, parent, NULL, NULL, \ + APR_POOL__FILE_LINE__) +#else +#define apr_pool_create(newpool, parent) \ + apr_pool_create_ex(newpool, parent, NULL, NULL) +#endif +#endif + +/** + * Create a new unmanaged pool. + * @param newpool The pool we have just created. + */ +#if defined(DOXYGEN) +APR_DECLARE(apr_status_t) apr_pool_create_core(apr_pool_t **newpool); +APR_DECLARE(apr_status_t) apr_pool_create_unmanaged(apr_pool_t **newpool); +#else +#if APR_POOL_DEBUG +#define apr_pool_create_core(newpool) \ + apr_pool_create_unmanaged_ex_debug(newpool, NULL, NULL, \ + APR_POOL__FILE_LINE__) +#define apr_pool_create_unmanaged(newpool) \ + apr_pool_create_unmanaged_ex_debug(newpool, NULL, NULL, \ + APR_POOL__FILE_LINE__) +#else +#define apr_pool_create_core(newpool) \ + apr_pool_create_unmanaged_ex(newpool, NULL, NULL) +#define apr_pool_create_unmanaged(newpool) \ + apr_pool_create_unmanaged_ex(newpool, NULL, NULL) +#endif +#endif + +/** + * Find the pool's allocator + * @param pool The pool to get the allocator from. + */ +APR_DECLARE(apr_allocator_t *) apr_pool_allocator_get(apr_pool_t *pool) + __attribute__((nonnull(1))); + +/** + * Clear all memory in the pool and run all the cleanups. This also destroys all + * subpools. + * @param p The pool to clear + * @remark This does not actually free the memory, it just allows the pool + * to re-use this memory for the next allocation. + * @see apr_pool_destroy() + */ +APR_DECLARE(void) apr_pool_clear(apr_pool_t *p) __attribute__((nonnull(1))); + +/** + * Debug version of apr_pool_clear. + * @param p See: apr_pool_clear. + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @remark Only available when APR_POOL_DEBUG is defined. + * Call this directly if you have your apr_pool_clear + * calls in a wrapper function and wish to override + * the file_line argument to reflect the caller of + * your wrapper function. If you do not have + * apr_pool_clear in a wrapper, trust the macro + * and don't call apr_pool_destroy_clear directly. + */ +APR_DECLARE(void) apr_pool_clear_debug(apr_pool_t *p, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pool_clear(p) \ + apr_pool_clear_debug(p, APR_POOL__FILE_LINE__) +#endif + +/** + * Destroy the pool. This takes similar action as apr_pool_clear() and then + * frees all the memory. + * @param p The pool to destroy + * @remark This will actually free the memory + */ +APR_DECLARE(void) apr_pool_destroy(apr_pool_t *p) __attribute__((nonnull(1))); + +/** + * Debug version of apr_pool_destroy. + * @param p See: apr_pool_destroy. + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @remark Only available when APR_POOL_DEBUG is defined. + * Call this directly if you have your apr_pool_destroy + * calls in a wrapper function and wish to override + * the file_line argument to reflect the caller of + * your wrapper function. If you do not have + * apr_pool_destroy in a wrapper, trust the macro + * and don't call apr_pool_destroy_debug directly. + */ +APR_DECLARE(void) apr_pool_destroy_debug(apr_pool_t *p, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pool_destroy(p) \ + apr_pool_destroy_debug(p, APR_POOL__FILE_LINE__) +#endif + + +/* + * Memory allocation + */ + +/** + * Allocate a block of memory from a pool + * @param p The pool to allocate from + * @param size The amount of memory to allocate + * @return The allocated memory + */ +APR_DECLARE(void *) apr_palloc(apr_pool_t *p, apr_size_t size) +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) + __attribute__((alloc_size(2))) +#endif + __attribute__((nonnull(1))); + +/** + * Debug version of apr_palloc + * @param p See: apr_palloc + * @param size See: apr_palloc + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @return See: apr_palloc + */ +APR_DECLARE(void *) apr_palloc_debug(apr_pool_t *p, apr_size_t size, + const char *file_line) +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) + __attribute__((alloc_size(2))) +#endif + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_palloc(p, size) \ + apr_palloc_debug(p, size, APR_POOL__FILE_LINE__) +#endif + +/** + * Allocate a block of memory from a pool and set all of the memory to 0 + * @param p The pool to allocate from + * @param size The amount of memory to allocate + * @return The allocated memory + */ +#if defined(DOXYGEN) +APR_DECLARE(void *) apr_pcalloc(apr_pool_t *p, apr_size_t size); +#elif !APR_POOL_DEBUG +#define apr_pcalloc(p, size) memset(apr_palloc(p, size), 0, size) +#endif + +/** + * Debug version of apr_pcalloc + * @param p See: apr_pcalloc + * @param size See: apr_pcalloc + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @return See: apr_pcalloc + */ +APR_DECLARE(void *) apr_pcalloc_debug(apr_pool_t *p, apr_size_t size, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pcalloc(p, size) \ + apr_pcalloc_debug(p, size, APR_POOL__FILE_LINE__) +#endif + + +/* + * Pool Properties + */ + +/** + * Set the function to be called when an allocation failure occurs. + * @remark If the program wants APR to exit on a memory allocation error, + * then this function can be called to set the callback to use (for + * performing cleanup and then exiting). If this function is not called, + * then APR will return an error and expect the calling program to + * deal with the error accordingly. + */ +APR_DECLARE(void) apr_pool_abort_set(apr_abortfunc_t abortfunc, + apr_pool_t *pool) + __attribute__((nonnull(2))); + +/** + * Get the abort function associated with the specified pool. + * @param pool The pool for retrieving the abort function. + * @return The abort function for the given pool. + */ +APR_DECLARE(apr_abortfunc_t) apr_pool_abort_get(apr_pool_t *pool) + __attribute__((nonnull(1))); + +/** + * Get the parent pool of the specified pool. + * @param pool The pool for retrieving the parent pool. + * @return The parent of the given pool. + */ +APR_DECLARE(apr_pool_t *) apr_pool_parent_get(apr_pool_t *pool) + __attribute__((nonnull(1))); + +/** + * Determine if pool a is an ancestor of pool b. + * @param a The pool to search + * @param b The pool to search for + * @return True if a is an ancestor of b, NULL is considered an ancestor + * of all pools. + * @remark if compiled with APR_POOL_DEBUG, this function will also + * return true if A is a pool which has been guaranteed by the caller + * (using apr_pool_join) to have a lifetime at least as long as some + * ancestor of pool B. + */ +APR_DECLARE(int) apr_pool_is_ancestor(apr_pool_t *a, apr_pool_t *b); + +/** + * Tag a pool (give it a name) + * @param pool The pool to tag + * @param tag The tag + */ +APR_DECLARE(void) apr_pool_tag(apr_pool_t *pool, const char *tag) + __attribute__((nonnull(1))); + + +/* + * User data management + */ + +/** + * Set the data associated with the current pool + * @param data The user data associated with the pool. + * @param key The key to use for association + * @param cleanup The cleanup program to use to cleanup the data (NULL if none) + * @param pool The current pool + * @warning The data to be attached to the pool should have a life span + * at least as long as the pool it is being attached to. + * + * Users of APR must take EXTREME care when choosing a key to + * use for their data. It is possible to accidentally overwrite + * data by choosing a key that another part of the program is using. + * Therefore it is advised that steps are taken to ensure that unique + * keys are used for all of the userdata objects in a particular pool + * (the same key in two different pools or a pool and one of its + * subpools is okay) at all times. Careful namespace prefixing of + * key names is a typical way to help ensure this uniqueness. + * + */ +APR_DECLARE(apr_status_t) apr_pool_userdata_set(const void *data, + const char *key, + apr_status_t (*cleanup)(void *), + apr_pool_t *pool) + __attribute__((nonnull(2,4))); + +/** + * Set the data associated with the current pool + * @param data The user data associated with the pool. + * @param key The key to use for association + * @param cleanup The cleanup program to use to cleanup the data (NULL if none) + * @param pool The current pool + * @note same as apr_pool_userdata_set(), except that this version doesn't + * make a copy of the key (this function is useful, for example, when + * the key is a string literal) + * @warning This should NOT be used if the key could change addresses by + * any means between the apr_pool_userdata_setn() call and a + * subsequent apr_pool_userdata_get() on that key, such as if a + * static string is used as a userdata key in a DSO and the DSO could + * be unloaded and reloaded between the _setn() and the _get(). You + * MUST use apr_pool_userdata_set() in such cases. + * @warning More generally, the key and the data to be attached to the + * pool should have a life span at least as long as the pool itself. + * + */ +APR_DECLARE(apr_status_t) apr_pool_userdata_setn( + const void *data, const char *key, + apr_status_t (*cleanup)(void *), + apr_pool_t *pool) + __attribute__((nonnull(2,4))); + +/** + * Return the data associated with the current pool. + * @param data The user data associated with the pool. + * @param key The key for the data to retrieve + * @param pool The current pool. + */ +APR_DECLARE(apr_status_t) apr_pool_userdata_get(void **data, const char *key, + apr_pool_t *pool) + __attribute__((nonnull(1,2,3))); + + +/** + * @defgroup PoolCleanup Pool Cleanup Functions + * + * Cleanups are performed in the reverse order they were registered. That is: + * Last In, First Out. A cleanup function can safely allocate memory from + * the pool that is being cleaned up. It can also safely register additional + * cleanups which will be run LIFO, directly after the current cleanup + * terminates. Cleanups have to take caution in calling functions that + * create subpools. Subpools, created during cleanup will NOT automatically + * be cleaned up. In other words, cleanups are to clean up after themselves. + * + * @{ + */ + +/** + * Register a function to be called when a pool is cleared or destroyed + * @param p The pool to register the cleanup with + * @param data The data to pass to the cleanup function. + * @param plain_cleanup The function to call when the pool is cleared + * or destroyed + * @param child_cleanup The function to call when a child process is about + * to exec - this function is called in the child, obviously! + */ +APR_DECLARE(void) apr_pool_cleanup_register( + apr_pool_t *p, const void *data, + apr_status_t (*plain_cleanup)(void *), + apr_status_t (*child_cleanup)(void *)) + __attribute__((nonnull(3,4))); + +/** + * Register a function to be called when a pool is cleared or destroyed. + * + * Unlike apr_pool_cleanup_register which registers a cleanup + * that is called AFTER all subpools are destroyed, this function registers + * a function that will be called before any of the subpools are destroyed. + * + * @param p The pool to register the cleanup with + * @param data The data to pass to the cleanup function. + * @param plain_cleanup The function to call when the pool is cleared + * or destroyed + */ +APR_DECLARE(void) apr_pool_pre_cleanup_register( + apr_pool_t *p, const void *data, + apr_status_t (*plain_cleanup)(void *)) + __attribute__((nonnull(3))); + +/** + * Remove a previously registered cleanup function. + * + * The cleanup most recently registered with @a p having the same values of + * @a data and @a cleanup will be removed. + * + * @param p The pool to remove the cleanup from + * @param data The data of the registered cleanup + * @param cleanup The function to remove from cleanup + * @remarks For some strange reason only the plain_cleanup is handled by this + * function + */ +APR_DECLARE(void) apr_pool_cleanup_kill(apr_pool_t *p, const void *data, + apr_status_t (*cleanup)(void *)) + __attribute__((nonnull(3))); + +/** + * Replace the child cleanup function of a previously registered cleanup. + * + * The cleanup most recently registered with @a p having the same values of + * @a data and @a plain_cleanup will have the registered child cleanup + * function replaced with @a child_cleanup. + * + * @param p The pool of the registered cleanup + * @param data The data of the registered cleanup + * @param plain_cleanup The plain cleanup function of the registered cleanup + * @param child_cleanup The function to register as the child cleanup + */ +APR_DECLARE(void) apr_pool_child_cleanup_set( + apr_pool_t *p, const void *data, + apr_status_t (*plain_cleanup)(void *), + apr_status_t (*child_cleanup)(void *)) + __attribute__((nonnull(3,4))); + +/** + * Run the specified cleanup function immediately and unregister it. + * + * The cleanup most recently registered with @a p having the same values of + * @a data and @a cleanup will be removed and @a cleanup will be called + * with @a data as the argument. + * + * @param p The pool to remove the cleanup from + * @param data The data to remove from cleanup + * @param cleanup The function to remove from cleanup + */ +APR_DECLARE(apr_status_t) apr_pool_cleanup_run(apr_pool_t *p, void *data, + apr_status_t (*cleanup)(void *)) + __attribute__((nonnull(3))); + +/** + * An empty cleanup function. + * + * Passed to apr_pool_cleanup_register() when no cleanup is required. + * + * @param data The data to cleanup, will not be used by this function. + */ +APR_DECLARE_NONSTD(apr_status_t) apr_pool_cleanup_null(void *data); + +/** + * Run all registered child cleanups, in preparation for an exec() + * call in a forked child -- close files, etc., but *don't* flush I/O + * buffers, *don't* wait for subprocesses, and *don't* free any + * memory. + */ +APR_DECLARE(void) apr_pool_cleanup_for_exec(void); + +/** @} */ + +/** + * @defgroup PoolDebug Pool Debugging functions + * + * pools have nested lifetimes -- sub_pools are destroyed when the + * parent pool is cleared. We allow certain liberties with operations + * on things such as tables (and on other structures in a more general + * sense) where we allow the caller to insert values into a table which + * were not allocated from the table's pool. The table's data will + * remain valid as long as all the pools from which its values are + * allocated remain valid. + * + * For example, if B is a sub pool of A, and you build a table T in + * pool B, then it's safe to insert data allocated in A or B into T + * (because B lives at most as long as A does, and T is destroyed when + * B is cleared/destroyed). On the other hand, if S is a table in + * pool A, it is safe to insert data allocated in A into S, but it + * is *not safe* to insert data allocated from B into S... because + * B can be cleared/destroyed before A is (which would leave dangling + * pointers in T's data structures). + * + * In general we say that it is safe to insert data into a table T + * if the data is allocated in any ancestor of T's pool. This is the + * basis on which the APR_POOL_DEBUG code works -- it tests these ancestor + * relationships for all data inserted into tables. APR_POOL_DEBUG also + * provides tools (apr_pool_find, and apr_pool_is_ancestor) for other + * folks to implement similar restrictions for their own data + * structures. + * + * However, sometimes this ancestor requirement is inconvenient -- + * sometimes it's necessary to create a sub pool where the sub pool is + * guaranteed to have the same lifetime as the parent pool. This is a + * guarantee implemented by the *caller*, not by the pool code. That + * is, the caller guarantees they won't destroy the sub pool + * individually prior to destroying the parent pool. + * + * In this case the caller must call apr_pool_join() to indicate this + * guarantee to the APR_POOL_DEBUG code. + * + * These functions are only implemented when #APR_POOL_DEBUG is set. + * + * @{ + */ +#if APR_POOL_DEBUG || defined(DOXYGEN) +/** + * Guarantee that a subpool has the same lifetime as the parent. + * @param p The parent pool + * @param sub The subpool + */ +APR_DECLARE(void) apr_pool_join(apr_pool_t *p, apr_pool_t *sub) + __attribute__((nonnull(2))); + +/** + * Find a pool from something allocated in it. + * @param mem The thing allocated in the pool + * @return The pool it is allocated in + */ +APR_DECLARE(apr_pool_t *) apr_pool_find(const void *mem); + +/** + * Report the number of bytes currently in the pool + * @param p The pool to inspect + * @param recurse Recurse/include the subpools' sizes + * @return The number of bytes + */ +APR_DECLARE(apr_size_t) apr_pool_num_bytes(apr_pool_t *p, int recurse) + __attribute__((nonnull(1))); + +/** + * Lock a pool + * @param pool The pool to lock + * @param flag The flag + */ +APR_DECLARE(void) apr_pool_lock(apr_pool_t *pool, int flag); + +/** @} */ + +#else /* APR_POOL_DEBUG or DOXYGEN */ + +#ifdef apr_pool_join +#undef apr_pool_join +#endif +#define apr_pool_join(a,b) + +#ifdef apr_pool_lock +#undef apr_pool_lock +#endif +#define apr_pool_lock(pool, lock) + +#endif /* APR_POOL_DEBUG or DOXYGEN */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_POOLS_H */ diff --git a/c/dependencies/macos/apr/include/apr_portable.h b/c/dependencies/macos/apr/include/apr_portable.h new file mode 100644 index 00000000..f56997e4 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_portable.h @@ -0,0 +1,549 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* This header file is where you should put ANY platform specific information. + * This should be the only header file that programs need to include that + * actually has platform dependent code which refers to the . + */ +#ifndef APR_PORTABLE_H +#define APR_PORTABLE_H +/** + * @file apr_portable.h + * @brief APR Portability Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" +#include "apr_network_io.h" +#include "apr_errno.h" +#include "apr_global_mutex.h" +#include "apr_proc_mutex.h" +#include "apr_time.h" +#include "apr_dso.h" +#include "apr_shm.h" + +#if APR_HAVE_DIRENT_H +#include +#endif +#if APR_HAVE_FCNTL_H +#include +#endif +#if APR_HAVE_PTHREAD_H +#include +#endif +#if APR_HAVE_SEMAPHORE_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_portabile Portability Routines + * @ingroup APR + * @{ + */ + +#ifdef WIN32 +/* The primitives for Windows types */ +typedef HANDLE apr_os_file_t; +typedef HANDLE apr_os_dir_t; +typedef SOCKET apr_os_sock_t; +typedef HANDLE apr_os_proc_mutex_t; +typedef HANDLE apr_os_thread_t; +typedef HANDLE apr_os_proc_t; +typedef DWORD apr_os_threadkey_t; +typedef FILETIME apr_os_imp_time_t; +typedef SYSTEMTIME apr_os_exp_time_t; +typedef HANDLE apr_os_dso_handle_t; +typedef HANDLE apr_os_shm_t; + +#elif defined(OS2) +typedef HFILE apr_os_file_t; +typedef HDIR apr_os_dir_t; +typedef int apr_os_sock_t; +typedef HMTX apr_os_proc_mutex_t; +typedef TID apr_os_thread_t; +typedef PID apr_os_proc_t; +typedef PULONG apr_os_threadkey_t; +typedef struct timeval apr_os_imp_time_t; +typedef struct tm apr_os_exp_time_t; +typedef HMODULE apr_os_dso_handle_t; +typedef void* apr_os_shm_t; + +#elif defined(__BEOS__) +#include +#include + +struct apr_os_proc_mutex_t { + sem_id sem; + int32 ben; +}; + +typedef int apr_os_file_t; +typedef DIR apr_os_dir_t; +typedef int apr_os_sock_t; +typedef struct apr_os_proc_mutex_t apr_os_proc_mutex_t; +typedef thread_id apr_os_thread_t; +typedef thread_id apr_os_proc_t; +typedef int apr_os_threadkey_t; +typedef struct timeval apr_os_imp_time_t; +typedef struct tm apr_os_exp_time_t; +typedef image_id apr_os_dso_handle_t; +typedef void* apr_os_shm_t; + +#elif defined(NETWARE) +typedef int apr_os_file_t; +typedef DIR apr_os_dir_t; +typedef int apr_os_sock_t; +typedef NXMutex_t apr_os_proc_mutex_t; +typedef NXThreadId_t apr_os_thread_t; +typedef long apr_os_proc_t; +typedef NXKey_t apr_os_threadkey_t; +typedef struct timeval apr_os_imp_time_t; +typedef struct tm apr_os_exp_time_t; +typedef void * apr_os_dso_handle_t; +typedef void* apr_os_shm_t; + +#else +/* Any other OS should go above this one. This is the lowest common + * denominator typedefs for all UNIX-like systems. :) + */ + +/** Basic OS process mutex structure. */ +struct apr_os_proc_mutex_t { +#if APR_HAS_SYSVSEM_SERIALIZE || APR_HAS_FCNTL_SERIALIZE || APR_HAS_FLOCK_SERIALIZE + /** Value used for SYS V Semaphore, FCNTL and FLOCK serialization */ + int crossproc; +#endif +#if APR_HAS_PROC_PTHREAD_SERIALIZE + /** Value used for PTHREAD serialization */ + pthread_mutex_t *pthread_interproc; +#endif +#if APR_HAS_THREADS + /* If no threads, no need for thread locks */ +#if APR_USE_PTHREAD_SERIALIZE + /** This value is currently unused within APR and Apache */ + pthread_mutex_t *intraproc; +#endif +#endif +#if APR_HAS_POSIXSEM_SERIALIZE + /** Value used for POSIX semaphores serialization */ + sem_t *psem_interproc; +#endif +}; + +typedef int apr_os_file_t; /**< native file */ +typedef DIR apr_os_dir_t; /**< native dir */ +typedef int apr_os_sock_t; /**< native dir */ +typedef struct apr_os_proc_mutex_t apr_os_proc_mutex_t; /**< native process + * mutex + */ +#if APR_HAS_THREADS && APR_HAVE_PTHREAD_H +typedef pthread_t apr_os_thread_t; /**< native thread */ +typedef pthread_key_t apr_os_threadkey_t; /**< native thread address + * space */ +#endif +typedef pid_t apr_os_proc_t; /**< native pid */ +typedef struct timeval apr_os_imp_time_t; /**< native timeval */ +typedef struct tm apr_os_exp_time_t; /**< native tm */ +/** @var apr_os_dso_handle_t + * native dso types + */ +#if defined(HPUX) || defined(HPUX10) || defined(HPUX11) +#include +typedef shl_t apr_os_dso_handle_t; +#elif defined(DARWIN) +#include +typedef NSModule apr_os_dso_handle_t; +#else +typedef void * apr_os_dso_handle_t; +#endif +typedef void* apr_os_shm_t; /**< native SHM */ + +#endif + +/** + * @typedef apr_os_sock_info_t + * @brief alias for local OS socket + */ +/** + * everything APR needs to know about an active socket to construct + * an APR socket from it; currently, this is platform-independent + */ +struct apr_os_sock_info_t { + apr_os_sock_t *os_sock; /**< always required */ + struct sockaddr *local; /**< NULL if not yet bound */ + struct sockaddr *remote; /**< NULL if not connected */ + int family; /**< always required (APR_INET, APR_INET6, etc.) */ + int type; /**< always required (SOCK_STREAM, SOCK_DGRAM, etc.) */ + int protocol; /**< 0 or actual protocol (APR_PROTO_SCTP, APR_PROTO_TCP, etc.) */ +}; + +typedef struct apr_os_sock_info_t apr_os_sock_info_t; + +#if APR_PROC_MUTEX_IS_GLOBAL || defined(DOXYGEN) +/** Opaque global mutex type */ +#define apr_os_global_mutex_t apr_os_proc_mutex_t +/** @return apr_os_global_mutex */ +#define apr_os_global_mutex_get apr_os_proc_mutex_get +#else + /** Thread and process mutex for those platforms where process mutexes + * are not held in threads. + */ + struct apr_os_global_mutex_t { + apr_pool_t *pool; + apr_proc_mutex_t *proc_mutex; +#if APR_HAS_THREADS + apr_thread_mutex_t *thread_mutex; +#endif /* APR_HAS_THREADS */ + }; + typedef struct apr_os_global_mutex_t apr_os_global_mutex_t; + +APR_DECLARE(apr_status_t) apr_os_global_mutex_get(apr_os_global_mutex_t *ospmutex, + apr_global_mutex_t *pmutex); +#endif + + +/** + * convert the file from apr type to os specific type. + * @param thefile The os specific file we are converting to + * @param file The apr file to convert. + * @remark On Unix, it is only possible to get a file descriptor from + * an apr file type. + */ +APR_DECLARE(apr_status_t) apr_os_file_get(apr_os_file_t *thefile, + apr_file_t *file); + +/** + * convert the dir from apr type to os specific type. + * @param thedir The os specific dir we are converting to + * @param dir The apr dir to convert. + */ +APR_DECLARE(apr_status_t) apr_os_dir_get(apr_os_dir_t **thedir, + apr_dir_t *dir); + +/** + * Convert the socket from an apr type to an OS specific socket + * @param thesock The socket to convert. + * @param sock The os specific equivalent of the apr socket.. + */ +APR_DECLARE(apr_status_t) apr_os_sock_get(apr_os_sock_t *thesock, + apr_socket_t *sock); + +/** + * Convert the proc mutex from apr type to os specific type + * @param ospmutex The os specific proc mutex we are converting to. + * @param pmutex The apr proc mutex to convert. + */ +APR_DECLARE(apr_status_t) apr_os_proc_mutex_get(apr_os_proc_mutex_t *ospmutex, + apr_proc_mutex_t *pmutex); + +/** + * Convert the proc mutex from apr type to os specific type, also + * providing the mechanism used by the apr mutex. + * @param ospmutex The os specific proc mutex we are converting to. + * @param pmutex The apr proc mutex to convert. + * @param mech The mechanism used by the apr proc mutex (if not NULL). + * @remark Allows for disambiguation for platforms with multiple mechanisms + * available. + */ +APR_DECLARE(apr_status_t) apr_os_proc_mutex_get_ex(apr_os_proc_mutex_t *ospmutex, + apr_proc_mutex_t *pmutex, + apr_lockmech_e *mech); + +/** + * Get the exploded time in the platforms native format. + * @param ostime the native time format + * @param aprtime the time to convert + */ +APR_DECLARE(apr_status_t) apr_os_exp_time_get(apr_os_exp_time_t **ostime, + apr_time_exp_t *aprtime); + +/** + * Get the imploded time in the platforms native format. + * @param ostime the native time format + * @param aprtime the time to convert + */ +APR_DECLARE(apr_status_t) apr_os_imp_time_get(apr_os_imp_time_t **ostime, + apr_time_t *aprtime); + +/** + * convert the shm from apr type to os specific type. + * @param osshm The os specific shm representation + * @param shm The apr shm to convert. + */ +APR_DECLARE(apr_status_t) apr_os_shm_get(apr_os_shm_t *osshm, + apr_shm_t *shm); + +#if APR_HAS_THREADS || defined(DOXYGEN) +/** + * @defgroup apr_os_thread Thread portability Routines + * @{ + */ +/** + * convert the thread to os specific type from apr type. + * @param thethd The apr thread to convert + * @param thd The os specific thread we are converting to + */ +APR_DECLARE(apr_status_t) apr_os_thread_get(apr_os_thread_t **thethd, + apr_thread_t *thd); + +/** + * convert the thread private memory key to os specific type from an apr type. + * @param thekey The apr handle we are converting from. + * @param key The os specific handle we are converting to. + */ +APR_DECLARE(apr_status_t) apr_os_threadkey_get(apr_os_threadkey_t *thekey, + apr_threadkey_t *key); + +/** + * convert the thread from os specific type to apr type. + * @param thd The apr thread we are converting to. + * @param thethd The os specific thread to convert + * @param cont The pool to use if it is needed. + */ +APR_DECLARE(apr_status_t) apr_os_thread_put(apr_thread_t **thd, + apr_os_thread_t *thethd, + apr_pool_t *cont); + +/** + * convert the thread private memory key from os specific type to apr type. + * @param key The apr handle we are converting to. + * @param thekey The os specific handle to convert + * @param cont The pool to use if it is needed. + */ +APR_DECLARE(apr_status_t) apr_os_threadkey_put(apr_threadkey_t **key, + apr_os_threadkey_t *thekey, + apr_pool_t *cont); +/** + * Get the thread ID + */ +APR_DECLARE(apr_os_thread_t) apr_os_thread_current(void); + +/** + * Compare two thread id's + * @param tid1 1st Thread ID to compare + * @param tid2 2nd Thread ID to compare + * @return non-zero if the two threads are equal, zero otherwise + */ +APR_DECLARE(int) apr_os_thread_equal(apr_os_thread_t tid1, + apr_os_thread_t tid2); + +/** @} */ +#endif /* APR_HAS_THREADS */ + +/** + * convert the file from os specific type to apr type. + * @param file The apr file we are converting to. + * @param thefile The os specific file to convert + * @param flags The flags that were used to open this file. + * @param cont The pool to use if it is needed. + * @remark On Unix, it is only possible to put a file descriptor into + * an apr file type. + */ +APR_DECLARE(apr_status_t) apr_os_file_put(apr_file_t **file, + apr_os_file_t *thefile, + apr_int32_t flags, apr_pool_t *cont); + +/** + * convert the file from os specific type to apr type. + * @param file The apr file we are converting to. + * @param thefile The os specific pipe to convert + * @param cont The pool to use if it is needed. + * @remark On Unix, it is only possible to put a file descriptor into + * an apr file type. + */ +APR_DECLARE(apr_status_t) apr_os_pipe_put(apr_file_t **file, + apr_os_file_t *thefile, + apr_pool_t *cont); + +/** + * convert the file from os specific type to apr type. + * @param file The apr file we are converting to. + * @param thefile The os specific pipe to convert + * @param register_cleanup A cleanup will be registered on the apr_file_t + * to issue apr_file_close(). + * @param cont The pool to use if it is needed. + * @remark On Unix, it is only possible to put a file descriptor into + * an apr file type. + */ +APR_DECLARE(apr_status_t) apr_os_pipe_put_ex(apr_file_t **file, + apr_os_file_t *thefile, + int register_cleanup, + apr_pool_t *cont); + +/** + * convert the dir from os specific type to apr type. + * @param dir The apr dir we are converting to. + * @param thedir The os specific dir to convert + * @param cont The pool to use when creating to apr directory. + */ +APR_DECLARE(apr_status_t) apr_os_dir_put(apr_dir_t **dir, + apr_os_dir_t *thedir, + apr_pool_t *cont); + +/** + * Convert a socket from the os specific type to the APR type. If + * sock points to NULL, a socket will be created from the pool + * provided. If **sock does not point to NULL, the structure pointed + * to by sock will be reused and updated with the given socket. + * @param sock The pool to use. + * @param thesock The socket to convert to. + * @param cont The socket we are converting to an apr type. + * @remark If it is a true socket, it is best to call apr_os_sock_make() + * and provide APR with more information about the socket. + */ +APR_DECLARE(apr_status_t) apr_os_sock_put(apr_socket_t **sock, + apr_os_sock_t *thesock, + apr_pool_t *cont); + +/** + * Create a socket from an existing descriptor and local and remote + * socket addresses. + * @param apr_sock The new socket that has been set up + * @param os_sock_info The os representation of the socket handle and + * other characteristics of the socket + * @param cont The pool to use + * @remark If you only know the descriptor/handle or if it isn't really + * a true socket, use apr_os_sock_put() instead. + */ +APR_DECLARE(apr_status_t) apr_os_sock_make(apr_socket_t **apr_sock, + apr_os_sock_info_t *os_sock_info, + apr_pool_t *cont); + +/** + * Convert the proc mutex from os specific type to apr type + * @param pmutex The apr proc mutex we are converting to. + * @param ospmutex The os specific proc mutex to convert. + * @param cont The pool to use if it is needed. + */ +APR_DECLARE(apr_status_t) apr_os_proc_mutex_put(apr_proc_mutex_t **pmutex, + apr_os_proc_mutex_t *ospmutex, + apr_pool_t *cont); + +/** + * Convert the proc mutex from os specific type to apr type, using the + * specified mechanism. + * @param pmutex The apr proc mutex we are converting to. + * @param ospmutex The os specific proc mutex to convert. + * @param mech The apr mutex locking mechanism + * @param register_cleanup Whether to destroy the os mutex with the apr + * one (either on explicit destroy or pool cleanup). + * @param cont The pool to use if it is needed. + * @remark Allows for disambiguation for platforms with multiple mechanisms + * available. + */ +APR_DECLARE(apr_status_t) apr_os_proc_mutex_put_ex(apr_proc_mutex_t **pmutex, + apr_os_proc_mutex_t *ospmutex, + apr_lockmech_e mech, + int register_cleanup, + apr_pool_t *cont); + +/** + * Put the imploded time in the APR format. + * @param aprtime the APR time format + * @param ostime the time to convert + * @param cont the pool to use if necessary + */ +APR_DECLARE(apr_status_t) apr_os_imp_time_put(apr_time_t *aprtime, + apr_os_imp_time_t **ostime, + apr_pool_t *cont); + +/** + * Put the exploded time in the APR format. + * @param aprtime the APR time format + * @param ostime the time to convert + * @param cont the pool to use if necessary + */ +APR_DECLARE(apr_status_t) apr_os_exp_time_put(apr_time_exp_t *aprtime, + apr_os_exp_time_t **ostime, + apr_pool_t *cont); + +/** + * convert the shared memory from os specific type to apr type. + * @param shm The apr shm representation of osshm + * @param osshm The os specific shm identity + * @param cont The pool to use if it is needed. + * @remark On fork()ed architectures, this is typically nothing more than + * the memory block mapped. On non-fork architectures, this is typically + * some internal handle to pass the mapping from process to process. + */ +APR_DECLARE(apr_status_t) apr_os_shm_put(apr_shm_t **shm, + apr_os_shm_t *osshm, + apr_pool_t *cont); + + +#if APR_HAS_DSO || defined(DOXYGEN) +/** + * @defgroup apr_os_dso DSO (Dynamic Loading) Portability Routines + * @{ + */ +/** + * convert the dso handle from os specific to apr + * @param dso The apr handle we are converting to + * @param thedso the os specific handle to convert + * @param pool the pool to use if it is needed + */ +APR_DECLARE(apr_status_t) apr_os_dso_handle_put(apr_dso_handle_t **dso, + apr_os_dso_handle_t thedso, + apr_pool_t *pool); + +/** + * convert the apr dso handle into an os specific one + * @param aprdso The apr dso handle to convert + * @param dso The os specific dso to return + */ +APR_DECLARE(apr_status_t) apr_os_dso_handle_get(apr_os_dso_handle_t *dso, + apr_dso_handle_t *aprdso); + +/** @} */ +#endif /* APR_HAS_DSO */ + + +#if APR_HAS_OS_UUID +/** + * Private: apr-util's apr_uuid module when supported by the platform + */ +APR_DECLARE(apr_status_t) apr_os_uuid_get(unsigned char *uuid_data); +#endif + + +/** + * Get the name of the system default character set. + * @param pool the pool to allocate the name from, if needed + */ +APR_DECLARE(const char*) apr_os_default_encoding(apr_pool_t *pool); + + +/** + * Get the name of the current locale character set. + * @param pool the pool to allocate the name from, if needed + * @remark Defers to apr_os_default_encoding() if the current locale's + * data can't be retrieved on this system. + */ +APR_DECLARE(const char*) apr_os_locale_encoding(apr_pool_t *pool); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_PORTABLE_H */ diff --git a/c/dependencies/macos/apr/include/apr_proc_mutex.h b/c/dependencies/macos/apr/include/apr_proc_mutex.h new file mode 100644 index 00000000..418c9504 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_proc_mutex.h @@ -0,0 +1,192 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_PROC_MUTEX_H +#define APR_PROC_MUTEX_H + +/** + * @file apr_proc_mutex.h + * @brief APR Process Locking Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_perms_set.h" +#include "apr_time.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_proc_mutex Process Locking Routines + * @ingroup APR + * @{ + */ + +/** + * Enumerated potential types for APR process locking methods + * @warning Check APR_HAS_foo_SERIALIZE defines to see if the platform supports + * APR_LOCK_foo. Only APR_LOCK_DEFAULT is portable. + */ +typedef enum { + APR_LOCK_FCNTL, /**< fcntl() */ + APR_LOCK_FLOCK, /**< flock() */ + APR_LOCK_SYSVSEM, /**< System V Semaphores */ + APR_LOCK_PROC_PTHREAD, /**< POSIX pthread process-based locking */ + APR_LOCK_POSIXSEM, /**< POSIX semaphore process-based locking */ + APR_LOCK_DEFAULT, /**< Use the default process lock */ + APR_LOCK_DEFAULT_TIMED /**< Use the default process timed lock */ +} apr_lockmech_e; + +/** Opaque structure representing a process mutex. */ +typedef struct apr_proc_mutex_t apr_proc_mutex_t; + +/* Function definitions */ + +/** + * Create and initialize a mutex that can be used to synchronize processes. + * @param mutex the memory address where the newly created mutex will be + * stored. + * @param fname A file name to use if the lock mechanism requires one. This + * argument should always be provided. The lock code itself will + * determine if it should be used. + * @param mech The mechanism to use for the interprocess lock, if any; one of + *
+ *            APR_LOCK_FCNTL
+ *            APR_LOCK_FLOCK
+ *            APR_LOCK_SYSVSEM
+ *            APR_LOCK_POSIXSEM
+ *            APR_LOCK_PROC_PTHREAD
+ *            APR_LOCK_DEFAULT     pick the default mechanism for the platform
+ * 
+ * @param pool the pool from which to allocate the mutex. + * @see apr_lockmech_e + * @warning Check APR_HAS_foo_SERIALIZE defines to see if the platform supports + * APR_LOCK_foo. Only APR_LOCK_DEFAULT is portable. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_create(apr_proc_mutex_t **mutex, + const char *fname, + apr_lockmech_e mech, + apr_pool_t *pool); + +/** + * Re-open a mutex in a child process. + * @param mutex The newly re-opened mutex structure. + * @param fname A file name to use if the mutex mechanism requires one. This + * argument should always be provided. The mutex code itself will + * determine if it should be used. This filename should be the + * same one that was passed to apr_proc_mutex_create(). + * @param pool The pool to operate on. + * @remark This function must be called to maintain portability, even + * if the underlying lock mechanism does not require it. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_child_init(apr_proc_mutex_t **mutex, + const char *fname, + apr_pool_t *pool); + +/** + * Acquire the lock for the given mutex. If the mutex is already locked, + * the current thread will be put to sleep until the lock becomes available. + * @param mutex the mutex on which to acquire the lock. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_lock(apr_proc_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex. If the mutex has already + * been acquired, the call returns immediately with APR_EBUSY. Note: it + * is important that the APR_STATUS_IS_EBUSY(s) macro be used to determine + * if the return value was APR_EBUSY, for portability reasons. + * @param mutex the mutex on which to attempt the lock acquiring. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_trylock(apr_proc_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex until timeout expires. + * If the acquisition time outs, the call returns with APR_TIMEUP. + * @param mutex the mutex on which to attempt the lock acquiring. + * @param timeout the relative timeout (microseconds). + * @note A negative or nul timeout means immediate attempt, returning + * APR_TIMEUP without blocking if it the lock is already acquired. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_timedlock(apr_proc_mutex_t *mutex, + apr_interval_time_t timeout); + +/** + * Release the lock for the given mutex. + * @param mutex the mutex from which to release the lock. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_unlock(apr_proc_mutex_t *mutex); + +/** + * Destroy the mutex and free the memory associated with the lock. + * @param mutex the mutex to destroy. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_destroy(apr_proc_mutex_t *mutex); + +/** + * Destroy the mutex and free the memory associated with the lock. + * @param mutex the mutex to destroy. + * @note This function is generally used to kill a cleanup on an already + * created mutex + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_cleanup(void *mutex); + +/** + * Return the name of the lockfile for the mutex, or NULL + * if the mutex doesn't use a lock file + */ + +APR_DECLARE(const char *) apr_proc_mutex_lockfile(apr_proc_mutex_t *mutex); + +/** + * Get the mechanism of the mutex, as it relates to the actual method + * used for the underlying apr_proc_mutex_t. + * @param mutex the mutex to get the mechanism from. + */ +APR_DECLARE(apr_lockmech_e) apr_proc_mutex_mech(apr_proc_mutex_t *mutex); + +/** + * Get the mechanism's name of the mutex, as it relates to the actual method + * used for the underlying apr_proc_mutex_t. + * @param mutex the mutex to get the mechanism's name from. + */ +APR_DECLARE(const char *) apr_proc_mutex_name(apr_proc_mutex_t *mutex); + +/** + * Display the name of the default mutex: APR_LOCK_DEFAULT + */ +APR_DECLARE(const char *) apr_proc_mutex_defname(void); + +/** + * Set mutex permissions. + */ +APR_PERMS_SET_IMPLEMENT(proc_mutex); + +/** + * Get the pool used by this proc_mutex. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(proc_mutex); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_PROC_MUTEX_H */ diff --git a/c/dependencies/macos/apr/include/apr_queue.h b/c/dependencies/macos/apr/include/apr_queue.h new file mode 100644 index 00000000..a3a41704 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_queue.h @@ -0,0 +1,138 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_QUEUE_H +#define APR_QUEUE_H + +/** + * @file apr_queue.h + * @brief Thread Safe FIFO bounded queue + * @note Since most implementations of the queue are backed by a condition + * variable implementation, it isn't available on systems without threads. + * Although condition variables are sometimes available without threads. + */ + +#include "apu.h" +#include "apr_errno.h" +#include "apr_pools.h" + +#if APR_HAS_THREADS + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_Util_FIFO Thread Safe FIFO bounded queue + * @ingroup APR_Util + * @{ + */ + +/** + * opaque structure + */ +typedef struct apr_queue_t apr_queue_t; + +/** + * create a FIFO queue + * @param queue The new queue + * @param queue_capacity maximum size of the queue + * @param a pool to allocate queue from + */ +APU_DECLARE(apr_status_t) apr_queue_create(apr_queue_t **queue, + unsigned int queue_capacity, + apr_pool_t *a); + +/** + * push/add an object to the queue, blocking if the queue is already full + * + * @param queue the queue + * @param data the data + * @returns APR_EINTR the blocking was interrupted (try again) + * @returns APR_EOF the queue has been terminated + * @returns APR_SUCCESS on a successful push + */ +APU_DECLARE(apr_status_t) apr_queue_push(apr_queue_t *queue, void *data); + +/** + * pop/get an object from the queue, blocking if the queue is already empty + * + * @param queue the queue + * @param data the data + * @returns APR_EINTR the blocking was interrupted (try again) + * @returns APR_EOF if the queue has been terminated + * @returns APR_SUCCESS on a successful pop + */ +APU_DECLARE(apr_status_t) apr_queue_pop(apr_queue_t *queue, void **data); + +/** + * push/add an object to the queue, returning immediately if the queue is full + * + * @param queue the queue + * @param data the data + * @returns APR_EINTR the blocking operation was interrupted (try again) + * @returns APR_EAGAIN the queue is full + * @returns APR_EOF the queue has been terminated + * @returns APR_SUCCESS on a successful push + */ +APU_DECLARE(apr_status_t) apr_queue_trypush(apr_queue_t *queue, void *data); + +/** + * pop/get an object to the queue, returning immediately if the queue is empty + * + * @param queue the queue + * @param data the data + * @returns APR_EINTR the blocking operation was interrupted (try again) + * @returns APR_EAGAIN the queue is empty + * @returns APR_EOF the queue has been terminated + * @returns APR_SUCCESS on a successful pop + */ +APU_DECLARE(apr_status_t) apr_queue_trypop(apr_queue_t *queue, void **data); + +/** + * returns the size of the queue. + * + * @warning this is not threadsafe, and is intended for reporting/monitoring + * of the queue. + * @param queue the queue + * @returns the size of the queue + */ +APU_DECLARE(unsigned int) apr_queue_size(apr_queue_t *queue); + +/** + * interrupt all the threads blocking on this queue. + * + * @param queue the queue + */ +APU_DECLARE(apr_status_t) apr_queue_interrupt_all(apr_queue_t *queue); + +/** + * terminate the queue, sending an interrupt to all the + * blocking threads + * + * @param queue the queue + */ +APU_DECLARE(apr_status_t) apr_queue_term(apr_queue_t *queue); + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif /* APR_HAS_THREADS */ + +#endif /* APRQUEUE_H */ diff --git a/c/dependencies/macos/apr/include/apr_random.h b/c/dependencies/macos/apr/include/apr_random.h new file mode 100644 index 00000000..29154358 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_random.h @@ -0,0 +1,153 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_RANDOM_H +#define APR_RANDOM_H + +/** + * @file apr_random.h + * @brief APR PRNG routines + */ + +#include "apr_pools.h" +#include "apr_thread_proc.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_random PRNG Routines + * @ingroup APR + * @{ + */ + +typedef struct apr_crypto_hash_t apr_crypto_hash_t; + +typedef void apr_crypto_hash_init_t(apr_crypto_hash_t *hash); +typedef void apr_crypto_hash_add_t(apr_crypto_hash_t *hash, const void *data, + apr_size_t bytes); +typedef void apr_crypto_hash_finish_t(apr_crypto_hash_t *hash, + unsigned char *result); + + +/* FIXME: make this opaque */ +struct apr_crypto_hash_t { + apr_crypto_hash_init_t *init; + apr_crypto_hash_add_t *add; + apr_crypto_hash_finish_t *finish; + apr_size_t size; + void *data; +}; + +/** + * Allocate and initialize the SHA-256 context + * @param p The pool to allocate from + */ +APR_DECLARE(apr_crypto_hash_t *) apr_crypto_sha256_new(apr_pool_t *p); + +/** Opaque PRNG structure. */ +typedef struct apr_random_t apr_random_t; + +/** + * Initialize a PRNG state + * @param g The PRNG state + * @param p The pool to allocate from + * @param pool_hash Pool hash functions + * @param key_hash Key hash functions + * @param prng_hash PRNG hash functions + */ +APR_DECLARE(void) apr_random_init(apr_random_t *g, apr_pool_t *p, + apr_crypto_hash_t *pool_hash, + apr_crypto_hash_t *key_hash, + apr_crypto_hash_t *prng_hash); +/** + * Allocate and initialize (apr_crypto_sha256_new) a new PRNG state. + * @param p The pool to allocate from + */ +APR_DECLARE(apr_random_t *) apr_random_standard_new(apr_pool_t *p); + +/** + * Mix the randomness pools. + * @param g The PRNG state + * @param entropy_ Entropy buffer + * @param bytes Length of entropy_ in bytes + */ +APR_DECLARE(void) apr_random_add_entropy(apr_random_t *g, + const void *entropy_, + apr_size_t bytes); +/** + * Generate cryptographically insecure random bytes. + * @param g The RNG state + * @param random Buffer to fill with random bytes + * @param bytes Length of buffer in bytes + */ +APR_DECLARE(apr_status_t) apr_random_insecure_bytes(apr_random_t *g, + void *random, + apr_size_t bytes); + +/** + * Generate cryptographically secure random bytes. + * @param g The RNG state + * @param random Buffer to fill with random bytes + * @param bytes Length of buffer in bytes + */ +APR_DECLARE(apr_status_t) apr_random_secure_bytes(apr_random_t *g, + void *random, + apr_size_t bytes); +/** + * Ensures that E bits of conditional entropy are mixed into the PRNG + * before any further randomness is extracted. + * @param g The RNG state + */ +APR_DECLARE(void) apr_random_barrier(apr_random_t *g); + +/** + * Return APR_SUCCESS if the cryptographic PRNG has been seeded with + * enough data, APR_ENOTENOUGHENTROPY otherwise. + * @param r The RNG state + */ +APR_DECLARE(apr_status_t) apr_random_secure_ready(apr_random_t *r); + +/** + * Return APR_SUCCESS if the PRNG has been seeded with enough data, + * APR_ENOTENOUGHENTROPY otherwise. + * @param r The PRNG state + */ +APR_DECLARE(apr_status_t) apr_random_insecure_ready(apr_random_t *r); + +/** + * Mix the randomness pools after forking. + * @param proc The resulting process handle from apr_proc_fork() + * @remark Call this in the child after forking to mix the randomness + * pools. Note that its generally a bad idea to fork a process with a + * real PRNG in it - better to have the PRNG externally and get the + * randomness from there. However, if you really must do it, then you + * should supply all your entropy to all the PRNGs - don't worry, they + * won't produce the same output. + * @remark Note that apr_proc_fork() calls this for you, so only weird + * applications need ever call it themselves. + * @internal + */ +APR_DECLARE(void) apr_random_after_fork(apr_proc_t *proc); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_RANDOM_H */ diff --git a/c/dependencies/macos/apr/include/apr_redis.h b/c/dependencies/macos/apr/include/apr_redis.h new file mode 100644 index 00000000..66a828b0 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_redis.h @@ -0,0 +1,459 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_redis.h + * @brief Client interface for redis + * @remark To use this interface you must have a separate redis + * for more information. + */ + +#ifndef APR_REDIS_H +#define APR_REDIS_H + +#include "apr.h" +#include "apr_pools.h" +#include "apr_time.h" +#include "apr_strings.h" +#include "apr_network_io.h" +#include "apr_ring.h" +#include "apr_buckets.h" +#include "apr_reslist.h" +#include "apr_hash.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#ifndef RC_DEFAULT_SERVER_PORT +#define RC_DEFAULT_SERVER_PORT 6379 +#endif + +#ifndef RC_DEFAULT_SERVER_MIN +#define RC_DEFAULT_SERVER_MIN 0 +#endif + +#ifndef RC_DEFAULT_SERVER_SMAX +#define RC_DEFAULT_SERVER_SMAX 1 +#endif + +#ifndef RC_DEFAULT_SERVER_TTL +#define RC_DEFAULT_SERVER_TTL 600 +#endif + +/** + * @defgroup APR_Util_RC Redis Client Routines + * @ingroup APR_Util + * @{ + */ + +/** Specifies the status of a redis server */ +typedef enum +{ + APR_RC_SERVER_LIVE, /**< Server is alive and responding to requests */ + APR_RC_SERVER_DEAD /**< Server is not responding to requests */ +} apr_redis_server_status_t; + +/** Opaque redis client connection object */ +typedef struct apr_redis_conn_t apr_redis_conn_t; + +/** Redis Server Info Object */ +typedef struct apr_redis_server_t apr_redis_server_t; +struct apr_redis_server_t +{ + const char *host; /**< Hostname of this Server */ + apr_port_t port; /**< Port of this Server */ + apr_redis_server_status_t status; /**< @see apr_redis_server_status_t */ +#if APR_HAS_THREADS || defined(DOXYGEN) + apr_reslist_t *conns; /**< Resource list of actual client connections */ +#else + apr_redis_conn_t *conn; +#endif + apr_pool_t *p; /** Pool to use for private allocations */ +#if APR_HAS_THREADS + apr_thread_mutex_t *lock; +#endif + apr_time_t btime; + apr_uint32_t rwto; + struct + { + int major; + int minor; + int patch; + char *number; + } version; +}; + +typedef struct apr_redis_t apr_redis_t; + +/* Custom hash callback function prototype, user for server selection. +* @param baton user selected baton +* @param data data to hash +* @param data_len length of data +*/ +typedef apr_uint32_t (*apr_redis_hash_func)(void *baton, + const char *data, + const apr_size_t data_len); +/* Custom Server Select callback function prototype. +* @param baton user selected baton +* @param rc redis instance, use rc->live_servers to select a node +* @param hash hash of the selected key. +*/ +typedef apr_redis_server_t* (*apr_redis_server_func)(void *baton, + apr_redis_t *rc, + const apr_uint32_t hash); + +/** Container for a set of redis servers */ +struct apr_redis_t +{ + apr_uint32_t flags; /**< Flags, Not currently used */ + apr_uint16_t nalloc; /**< Number of Servers Allocated */ + apr_uint16_t ntotal; /**< Number of Servers Added */ + apr_redis_server_t **live_servers; /**< Array of Servers */ + apr_pool_t *p; /** Pool to use for allocations */ + void *hash_baton; + apr_redis_hash_func hash_func; + void *server_baton; + apr_redis_server_func server_func; +}; + +/** + * Creates a crc32 hash used to split keys between servers + * @param rc The redis client object to use + * @param data Data to be hashed + * @param data_len Length of the data to use + * @return crc32 hash of data + * @remark The crc32 hash is not compatible with old redisd clients. + */ +APU_DECLARE(apr_uint32_t) apr_redis_hash(apr_redis_t *rc, + const char *data, + const apr_size_t data_len); + +/** + * Pure CRC32 Hash. Used by some clients. + */ +APU_DECLARE(apr_uint32_t) apr_redis_hash_crc32(void *baton, + const char *data, + const apr_size_t data_len); + +/** + * hash compatible with the standard Perl Client. + */ +APU_DECLARE(apr_uint32_t) apr_redis_hash_default(void *baton, + const char *data, + const apr_size_t data_len); + +/** + * Picks a server based on a hash + * @param rc The redis client object to use + * @param hash Hashed value of a Key + * @return server that controls specified hash + * @see apr_redis_hash + */ +APU_DECLARE(apr_redis_server_t *) apr_redis_find_server_hash(apr_redis_t *rc, + const apr_uint32_t hash); + +/** + * server selection compatible with the standard Perl Client. + */ +APU_DECLARE(apr_redis_server_t *) apr_redis_find_server_hash_default(void *baton, + apr_redis_t *rc, + const apr_uint32_t hash); + +/** + * Adds a server to a client object + * @param rc The redis client object to use + * @param server Server to add + * @remark Adding servers is not thread safe, and should be done once at startup. + * @warning Changing servers after startup may cause keys to go to + * different servers. + */ +APU_DECLARE(apr_status_t) apr_redis_add_server(apr_redis_t *rc, + apr_redis_server_t *server); + + +/** + * Finds a Server object based on a hostname/port pair + * @param rc The redis client object to use + * @param host Hostname of the server + * @param port Port of the server + * @return Server with matching Hostname and Port, or NULL if none was found. + */ +APU_DECLARE(apr_redis_server_t *) apr_redis_find_server(apr_redis_t *rc, + const char *host, + apr_port_t port); + +/** + * Enables a Server for use again + * @param rc The redis client object to use + * @param rs Server to Activate + */ +APU_DECLARE(apr_status_t) apr_redis_enable_server(apr_redis_t *rc, + apr_redis_server_t *rs); + + +/** + * Disable a Server + * @param rc The redis client object to use + * @param rs Server to Disable + */ +APU_DECLARE(apr_status_t) apr_redis_disable_server(apr_redis_t *rc, + apr_redis_server_t *rs); + +/** + * Creates a new Server Object + * @param p Pool to use + * @param host hostname of the server + * @param port port of the server + * @param min minimum number of client sockets to open + * @param smax soft maximum number of client connections to open + * @param max hard maximum number of client connections + * @param ttl time to live in microseconds of a client connection + * @param rwto r/w timeout value in seconds of a client connection + * @param ns location of the new server object + * @see apr_reslist_create + * @remark min, smax, and max are only used when APR_HAS_THREADS + */ +APU_DECLARE(apr_status_t) apr_redis_server_create(apr_pool_t *p, + const char *host, + apr_port_t port, + apr_uint32_t min, + apr_uint32_t smax, + apr_uint32_t max, + apr_uint32_t ttl, + apr_uint32_t rwto, + apr_redis_server_t **ns); +/** + * Creates a new redisd client object + * @param p Pool to use + * @param max_servers maximum number of servers + * @param flags Not currently used + * @param rc location of the new redis client object + */ +APU_DECLARE(apr_status_t) apr_redis_create(apr_pool_t *p, + apr_uint16_t max_servers, + apr_uint32_t flags, + apr_redis_t **rc); + +/** + * Gets a value from the server, allocating the value out of p + * @param rc client to use + * @param p Pool to use + * @param key null terminated string containing the key + * @param baton location of the allocated value + * @param len length of data at baton + * @param flags any flags set by the client for this key + * @return + */ +APU_DECLARE(apr_status_t) apr_redis_getp(apr_redis_t *rc, + apr_pool_t *p, + const char* key, + char **baton, + apr_size_t *len, + apr_uint16_t *flags); + +/** + * Sets a value by key on the server + * @param rc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param flags any flags set by the client for this key + */ +APU_DECLARE(apr_status_t) apr_redis_set(apr_redis_t *rc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint16_t flags); + +/** + * Sets a value by key on the server + * @param rc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param timeout time in seconds for the data to live on the server + * @param flags any flags set by the client for this key + */ +APU_DECLARE(apr_status_t) apr_redis_setex(apr_redis_t *rc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint32_t timeout, + apr_uint16_t flags); + +/** + * Deletes a key from a server + * @param rc client to use + * @param key null terminated string containing the key + * @param timeout time for the delete to stop other clients from adding + */ +APU_DECLARE(apr_status_t) apr_redis_delete(apr_redis_t *rc, + const char *key, + apr_uint32_t timeout); + +/** + * Query a server's version + * @param rs server to query + * @param p Pool to allocate answer from + * @param baton location to store server version string + */ +APU_DECLARE(apr_status_t) apr_redis_version(apr_redis_server_t *rs, + apr_pool_t *p, + char **baton); + +/** + * Query a server's INFO + * @param rs server to query + * @param p Pool to allocate answer from + * @param baton location to store server INFO response string + */ +APU_DECLARE(apr_status_t) apr_redis_info(apr_redis_server_t *rs, + apr_pool_t *p, + char **baton); + +/** + * Increments a value + * @param rc client to use + * @param key null terminated string containing the key + * @param inc number to increment by + * @param new_value new value after incrementing + */ +APU_DECLARE(apr_status_t) apr_redis_incr(apr_redis_t *rc, + const char *key, + apr_int32_t inc, + apr_uint32_t *new_value); +/** + * Decrements a value + * @param rc client to use + * @param key null terminated string containing the key + * @param inc number to decrement by + * @param new_value new value after decrementing + */ +APU_DECLARE(apr_status_t) apr_redis_decr(apr_redis_t *rc, + const char *key, + apr_int32_t inc, + apr_uint32_t *new_value); + + +/** + * Pings the server + * @param rs Server to ping + */ +APU_DECLARE(apr_status_t) apr_redis_ping(apr_redis_server_t *rs); + +/** + * Gets multiple values from the server, allocating the values out of p + * @param rc client to use + * @param temp_pool Pool used for temporary allocations. May be cleared inside this + * call. + * @param data_pool Pool used to allocate data for the returned values. + * @param values hash of apr_redis_value_t keyed by strings, contains the + * result of the multiget call. + * @return + */ +APU_DECLARE(apr_status_t) apr_redis_multgetp(apr_redis_t *rc, + apr_pool_t *temp_pool, + apr_pool_t *data_pool, + apr_hash_t *values); + +typedef enum +{ + APR_RS_SERVER_MASTER, /**< Server is a master */ + APR_RS_SERVER_SLAVE, /**< Server is a slave */ + APR_RS_SERVER_UNKNOWN /**< Server role is unknown */ +} apr_redis_server_role_t; + +typedef struct +{ +/* # Server */ + /** Major version number of this server */ + apr_uint32_t major; + /** Minor version number of this server */ + apr_uint32_t minor; + /** Patch version number of this server */ + apr_uint32_t patch; + /** Process id of this server process */ + apr_uint32_t process_id; + /** Number of seconds this server has been running */ + apr_uint32_t uptime_in_seconds; + /** Bitsize of the arch on the current machine */ + apr_uint32_t arch_bits; + +/* # Clients */ + /** Number of connected clients */ + apr_uint32_t connected_clients; + /** Number of blocked clients */ + apr_uint32_t blocked_clients; + +/* # Memory */ + /** Max memory of this server */ + apr_uint64_t maxmemory; + /** Amount of used memory */ + apr_uint64_t used_memory; + /** Total memory available on this server */ + apr_uint64_t total_system_memory; + +/* # Stats */ + /** Total connections received */ + apr_uint64_t total_connections_received; + /** Total commands processed */ + apr_uint64_t total_commands_processed; + /** Total commands rejected */ + apr_uint64_t rejected_connections; + /** Total net input bytes */ + apr_uint64_t total_net_input_bytes; + /** Total net output bytes */ + apr_uint64_t total_net_output_bytes; + /** Keyspace hits */ + apr_uint64_t keyspace_hits; + /** Keyspace misses */ + apr_uint64_t keyspace_misses; + +/* # Replication */ + /** Role */ + apr_redis_server_role_t role; + /** Number of connected slave */ + apr_uint32_t connected_slaves; + +/* # CPU */ + /** Accumulated CPU user time for this process */ + apr_uint32_t used_cpu_sys; + /** Accumulated CPU system time for this process */ + apr_uint32_t used_cpu_user; + +/* # Cluster */ + /** Is cluster enabled */ + apr_uint32_t cluster_enabled; +} apr_redis_stats_t; + +/** + * Query a server for statistics + * @param rs server to query + * @param p Pool to allocate answer from + * @param stats location of the new statistics structure + */ +APU_DECLARE(apr_status_t) apr_redis_stats(apr_redis_server_t *rs, + apr_pool_t *p, + apr_redis_stats_t **stats); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_REDIS_H */ diff --git a/c/dependencies/macos/apr/include/apr_reslist.h b/c/dependencies/macos/apr/include/apr_reslist.h new file mode 100644 index 00000000..02a8192b --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_reslist.h @@ -0,0 +1,183 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_RESLIST_H +#define APR_RESLIST_H + +/** + * @file apr_reslist.h + * @brief APR-UTIL Resource List Routines + */ + +#include "apr.h" +#include "apu.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_time.h" + +/** + * @defgroup APR_Util_RL Resource List Routines + * @ingroup APR_Util + * @{ + */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** Opaque resource list object */ +typedef struct apr_reslist_t apr_reslist_t; + +/* Generic constructor called by resource list when it needs to create a + * resource. + * @param resource opaque resource + * @param params flags + * @param pool Pool + */ +typedef apr_status_t (*apr_reslist_constructor)(void **resource, void *params, + apr_pool_t *pool); + +/* Generic destructor called by resource list when it needs to destroy a + * resource. + * @param resource opaque resource + * @param params flags + * @param pool Pool + */ +typedef apr_status_t (*apr_reslist_destructor)(void *resource, void *params, + apr_pool_t *pool); + +/* Cleanup order modes */ +#define APR_RESLIST_CLEANUP_DEFAULT 0 /**< default pool cleanup */ +#define APR_RESLIST_CLEANUP_FIRST 1 /**< use pool pre cleanup */ + +/** + * Create a new resource list with the following parameters: + * @param reslist An address where the pointer to the new resource + * list will be stored. + * @param min Allowed minimum number of available resources. Zero + * creates new resources only when needed. + * @param smax Resources will be destroyed during reslist maintenance to + * meet this maximum restriction as they expire (reach their ttl). + * @param hmax Absolute maximum limit on the number of total resources. + * @param ttl If non-zero, sets the maximum amount of time in microseconds an + * unused resource is valid. Any resource which has exceeded this + * time will be destroyed, either when encountered by + * apr_reslist_acquire() or during reslist maintenance. + * @param con Constructor routine that is called to create a new resource. + * @param de Destructor routine that is called to destroy an expired resource. + * @param params Passed to constructor and deconstructor + * @param pool The pool from which to create this resource list. Also the + * same pool that is passed to the constructor and destructor + * routines. + * @remark If APR has been compiled without thread support, hmax will be + * automatically set to 1 and values of min and smax will be forced to + * 1 for any non-zero value. + */ +APU_DECLARE(apr_status_t) apr_reslist_create(apr_reslist_t **reslist, + int min, int smax, int hmax, + apr_interval_time_t ttl, + apr_reslist_constructor con, + apr_reslist_destructor de, + void *params, + apr_pool_t *pool); + +/** + * Destroy the given resource list and all resources controlled by + * this list. + * FIXME: Should this block until all resources become available, + * or maybe just destroy all the free ones, or maybe destroy + * them even though they might be in use by something else? + * Currently it will abort if there are resources that haven't + * been released, so there is an assumption that all resources + * have been released to the list before calling this function. + * @param reslist The reslist to destroy + */ +APU_DECLARE(apr_status_t) apr_reslist_destroy(apr_reslist_t *reslist); + +/** + * Retrieve a resource from the list, creating a new one if necessary. + * If we have met our maximum number of resources, we will block + * until one becomes available. + * @param reslist The resource list. + * @param resource An address where the pointer to the resource + * will be stored. + */ +APU_DECLARE(apr_status_t) apr_reslist_acquire(apr_reslist_t *reslist, + void **resource); + +/** + * Return a resource back to the list of available resources. + * @param reslist The resource list. + * @param resource The resource to return to the list. + */ +APU_DECLARE(apr_status_t) apr_reslist_release(apr_reslist_t *reslist, + void *resource); + +/** + * Set the timeout the acquire will wait for a free resource + * when the maximum number of resources is exceeded. + * @param reslist The resource list. + * @param timeout Timeout to wait. The zero waits forever. + */ +APU_DECLARE(void) apr_reslist_timeout_set(apr_reslist_t *reslist, + apr_interval_time_t timeout); + +/** + * Return the number of outstanding resources. + * @param reslist The resource list. + */ +APU_DECLARE(apr_uint32_t) apr_reslist_acquired_count(apr_reslist_t *reslist); + +/** + * Invalidate a resource in the pool - e.g. a database connection + * that returns a "lost connection" error and can't be restored. + * Use this instead of apr_reslist_release if the resource is bad. + * @param reslist The resource list. + * @param resource The resource to invalidate. + */ +APU_DECLARE(apr_status_t) apr_reslist_invalidate(apr_reslist_t *reslist, + void *resource); + +/** + * Perform routine maintenance on the resource list. This call + * may instantiate new resources or expire old resources. + * @param reslist The resource list. + */ +APU_DECLARE(apr_status_t) apr_reslist_maintain(apr_reslist_t *reslist); + +/** + * Set reslist cleanup order. + * @param reslist The resource list. + * @param mode Cleanup order mode + *
+ *           APR_RESLIST_CLEANUP_DEFAULT  default pool cleanup order
+ *           APR_RESLIST_CLEANUP_FIRST    use pool pre cleanup
+ * 
+ * @remark If APR_RESLIST_CLEANUP_FIRST is used the destructors will + * be called before child pools of the pool used to create the reslist + * are destroyed. This allows to explicitly destroy the child pools + * inside reslist destructors. + */ +APU_DECLARE(void) apr_reslist_cleanup_order_set(apr_reslist_t *reslist, + apr_uint32_t mode); + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif /* ! APR_RESLIST_H */ diff --git a/c/dependencies/macos/apr/include/apr_ring.h b/c/dependencies/macos/apr/include/apr_ring.h new file mode 100644 index 00000000..7280245e --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_ring.h @@ -0,0 +1,517 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * This code draws heavily from the 4.4BSD macros + * and Dean Gaudet's "splim/ring.h". + * + * + * + * We'd use Dean's code directly if we could guarantee the + * availability of inline functions. + */ + +#ifndef APR_RING_H +#define APR_RING_H + +/** + * @file apr_ring.h + * @brief APR Rings + */ + +/* + * for offsetof() + */ +#include "apr_general.h" + +/** + * @defgroup apr_ring Ring Macro Implementations + * @ingroup APR + * A ring is a kind of doubly-linked list that can be manipulated + * without knowing where its head is. + * @{ + */ + +/** + * The Ring Element + * + * A ring element struct is linked to the other elements in the ring + * through its ring entry field, e.g. + *
+ *      struct my_element_t {
+ *          APR_RING_ENTRY(my_element_t) link;
+ *          int foo;
+ *          char *bar;
+ *      };
+ * 
+ * + * An element struct may be put on more than one ring if it has more + * than one APR_RING_ENTRY field. Each APR_RING_ENTRY has a corresponding + * APR_RING_HEAD declaration. + * + * @warning For strict C standards compliance you should put the APR_RING_ENTRY + * first in the element struct unless the head is always part of a larger + * object with enough earlier fields to accommodate the offsetof() used + * to compute the ring sentinel below. You can usually ignore this caveat. + */ +#define APR_RING_ENTRY(elem) \ + struct { \ + struct elem * volatile next; \ + struct elem * volatile prev; \ + } + +/** + * The Ring Head + * + * Each ring is managed via its head, which is a struct declared like this: + *
+ *      APR_RING_HEAD(my_ring_t, my_element_t);
+ *      struct my_ring_t ring, *ringp;
+ * 
+ * + * This struct looks just like the element link struct so that we can + * be sure that the typecasting games will work as expected. + * + * The first element in the ring is next after the head, and the last + * element is just before the head. + */ +#define APR_RING_HEAD(head, elem) \ + struct head { \ + struct elem * volatile next; \ + struct elem * volatile prev; \ + } + +/** + * The Ring Sentinel + * + * This is the magic pointer value that occurs before the first and + * after the last elements in the ring, computed from the address of + * the ring's head. The head itself isn't an element, but in order to + * get rid of all the special cases when dealing with the ends of the + * ring, we play typecasting games to make it look like one. + * + * Here is a diagram to illustrate the arrangements of the next and + * prev pointers of each element in a single ring. Note that they point + * to the start of each element, not to the APR_RING_ENTRY structure. + * + *
+ *     +->+------+<-+  +->+------+<-+  +->+------+<-+
+ *     |  |struct|  |  |  |struct|  |  |  |struct|  |
+ *    /   | elem |   \/   | elem |   \/   | elem |  \
+ * ...    |      |   /\   |      |   /\   |      |   ...
+ *        +------+  |  |  +------+  |  |  +------+
+ *   ...--|prev  |  |  +--|ring  |  |  +--|prev  |
+ *        |  next|--+     | entry|--+     |  next|--...
+ *        +------+        +------+        +------+
+ *        | etc. |        | etc. |        | etc. |
+ *        :      :        :      :        :      :
+ * 
+ * + * The APR_RING_HEAD is nothing but a bare APR_RING_ENTRY. The prev + * and next pointers in the first and last elements don't actually + * point to the head, they point to a phantom place called the + * sentinel. Its value is such that last->next->next == first because + * the offset from the sentinel to the head's next pointer is the same + * as the offset from the start of an element to its next pointer. + * This also works in the opposite direction. + * + *
+ *        last                            first
+ *     +->+------+<-+  +->sentinel<-+  +->+------+<-+
+ *     |  |struct|  |  |            |  |  |struct|  |
+ *    /   | elem |   \/              \/   | elem |  \
+ * ...    |      |   /\              /\   |      |   ...
+ *        +------+  |  |  +------+  |  |  +------+
+ *   ...--|prev  |  |  +--|ring  |  |  +--|prev  |
+ *        |  next|--+     |  head|--+     |  next|--...
+ *        +------+        +------+        +------+
+ *        | etc. |                        | etc. |
+ *        :      :                        :      :
+ * 
+ * + * Note that the offset mentioned above is different for each kind of + * ring that the element may be on, and each kind of ring has a unique + * name for its APR_RING_ENTRY in each element, and has its own type + * for its APR_RING_HEAD. + * + * Note also that if the offset is non-zero (which is required if an + * element has more than one APR_RING_ENTRY), the unreality of the + * sentinel may have bad implications on very perverse implementations + * of C -- see the warning in APR_RING_ENTRY. + * + * @param hp The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SENTINEL(hp, elem, link) \ + (struct elem *)((char *)(&(hp)->next) - APR_OFFSETOF(struct elem, link)) + +/** + * The first element of the ring + * @param hp The head of the ring + */ +#define APR_RING_FIRST(hp) (hp)->next +/** + * The last element of the ring + * @param hp The head of the ring + */ +#define APR_RING_LAST(hp) (hp)->prev +/** + * The next element in the ring + * @param ep The current element + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_NEXT(ep, link) (ep)->link.next +/** + * The previous element in the ring + * @param ep The current element + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_PREV(ep, link) (ep)->link.prev + + +/** + * Initialize a ring + * @param hp The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INIT(hp, elem, link) do { \ + APR_RING_FIRST((hp)) = APR_RING_SENTINEL((hp), elem, link); \ + APR_RING_LAST((hp)) = APR_RING_SENTINEL((hp), elem, link); \ + } while (0) + +/** + * Determine if a ring is empty + * @param hp The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + * @return true or false + */ +#define APR_RING_EMPTY(hp, elem, link) \ + (APR_RING_FIRST((hp)) == APR_RING_SENTINEL((hp), elem, link)) + +/** + * Initialize a singleton element + * @param ep The element + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_ELEM_INIT(ep, link) do { \ + APR_RING_NEXT((ep), link) = (ep); \ + APR_RING_PREV((ep), link) = (ep); \ + } while (0) + + +/** + * Splice the sequence ep1..epN into the ring before element lep + * (..lep.. becomes ..ep1..epN..lep..) + * @warning This doesn't work for splicing before the first element or on + * empty rings... see APR_RING_SPLICE_HEAD for one that does + * @param lep Element in the ring to splice before + * @param ep1 First element in the sequence to splice in + * @param epN Last element in the sequence to splice in + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SPLICE_BEFORE(lep, ep1, epN, link) do { \ + APR_RING_NEXT((epN), link) = (lep); \ + APR_RING_PREV((ep1), link) = APR_RING_PREV((lep), link); \ + APR_RING_NEXT(APR_RING_PREV((lep), link), link) = (ep1); \ + APR_RING_PREV((lep), link) = (epN); \ + } while (0) + +/** + * Splice the sequence ep1..epN into the ring after element lep + * (..lep.. becomes ..lep..ep1..epN..) + * @warning This doesn't work for splicing after the last element or on + * empty rings... see APR_RING_SPLICE_TAIL for one that does + * @param lep Element in the ring to splice after + * @param ep1 First element in the sequence to splice in + * @param epN Last element in the sequence to splice in + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SPLICE_AFTER(lep, ep1, epN, link) do { \ + APR_RING_PREV((ep1), link) = (lep); \ + APR_RING_NEXT((epN), link) = APR_RING_NEXT((lep), link); \ + APR_RING_PREV(APR_RING_NEXT((lep), link), link) = (epN); \ + APR_RING_NEXT((lep), link) = (ep1); \ + } while (0) + +/** + * Insert the element nep into the ring before element lep + * (..lep.. becomes ..nep..lep..) + * @warning This doesn't work for inserting before the first element or on + * empty rings... see APR_RING_INSERT_HEAD for one that does + * @param lep Element in the ring to insert before + * @param nep Element to insert + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INSERT_BEFORE(lep, nep, link) \ + APR_RING_SPLICE_BEFORE((lep), (nep), (nep), link) + +/** + * Insert the element nep into the ring after element lep + * (..lep.. becomes ..lep..nep..) + * @warning This doesn't work for inserting after the last element or on + * empty rings... see APR_RING_INSERT_TAIL for one that does + * @param lep Element in the ring to insert after + * @param nep Element to insert + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INSERT_AFTER(lep, nep, link) \ + APR_RING_SPLICE_AFTER((lep), (nep), (nep), link) + + +/** + * Splice the sequence ep1..epN into the ring before the first element + * (..hp.. becomes ..hp..ep1..epN..) + * @param hp Head of the ring + * @param ep1 First element in the sequence to splice in + * @param epN Last element in the sequence to splice in + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SPLICE_HEAD(hp, ep1, epN, elem, link) do { \ + APR_RING_PREV((ep1), link) = APR_RING_SENTINEL((hp), elem, link);\ + APR_RING_NEXT((epN), link) = APR_RING_FIRST((hp)); \ + APR_RING_PREV(APR_RING_FIRST((hp)), link) = (epN); \ + APR_RING_FIRST((hp)) = (ep1); \ + } while (0) + +/** + * Splice the sequence ep1..epN into the ring after the last element + * (..hp.. becomes ..ep1..epN..hp..) + * @param hp Head of the ring + * @param ep1 First element in the sequence to splice in + * @param epN Last element in the sequence to splice in + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SPLICE_TAIL(hp, ep1, epN, elem, link) do { \ + APR_RING_NEXT((epN), link) = APR_RING_SENTINEL((hp), elem, link);\ + APR_RING_PREV((ep1), link) = APR_RING_LAST((hp)); \ + APR_RING_NEXT(APR_RING_LAST((hp)), link) = (ep1); \ + APR_RING_LAST((hp)) = (epN); \ + } while (0) + +/** + * Insert the element nep into the ring before the first element + * (..hp.. becomes ..hp..nep..) + * @param hp Head of the ring + * @param nep Element to insert + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INSERT_HEAD(hp, nep, elem, link) \ + APR_RING_SPLICE_HEAD((hp), (nep), (nep), elem, link) + +/** + * Insert the element nep into the ring after the last element + * (..hp.. becomes ..nep..hp..) + * @param hp Head of the ring + * @param nep Element to insert + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INSERT_TAIL(hp, nep, elem, link) \ + APR_RING_SPLICE_TAIL((hp), (nep), (nep), elem, link) + +/** + * Concatenate ring h2 onto the end of ring h1, leaving h2 empty. + * @param h1 Head of the ring to concatenate onto + * @param h2 Head of the ring to concatenate + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_CONCAT(h1, h2, elem, link) do { \ + if (!APR_RING_EMPTY((h2), elem, link)) { \ + APR_RING_SPLICE_TAIL((h1), APR_RING_FIRST((h2)), \ + APR_RING_LAST((h2)), elem, link); \ + APR_RING_INIT((h2), elem, link); \ + } \ + } while (0) + +/** + * Prepend ring h2 onto the beginning of ring h1, leaving h2 empty. + * @param h1 Head of the ring to prepend onto + * @param h2 Head of the ring to prepend + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_PREPEND(h1, h2, elem, link) do { \ + if (!APR_RING_EMPTY((h2), elem, link)) { \ + APR_RING_SPLICE_HEAD((h1), APR_RING_FIRST((h2)), \ + APR_RING_LAST((h2)), elem, link); \ + APR_RING_INIT((h2), elem, link); \ + } \ + } while (0) + +/** + * Unsplice a sequence of elements from a ring + * @warning The unspliced sequence is left with dangling pointers at either end + * @param ep1 First element in the sequence to unsplice + * @param epN Last element in the sequence to unsplice + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_UNSPLICE(ep1, epN, link) do { \ + APR_RING_NEXT(APR_RING_PREV((ep1), link), link) = \ + APR_RING_NEXT((epN), link); \ + APR_RING_PREV(APR_RING_NEXT((epN), link), link) = \ + APR_RING_PREV((ep1), link); \ + } while (0) + +/** + * Remove a single element from a ring + * @warning The unspliced element is left with dangling pointers at either end + * @param ep Element to remove + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_REMOVE(ep, link) \ + APR_RING_UNSPLICE((ep), (ep), link) + +/** + * Iterate over a ring + * @param ep The current element + * @param head The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_FOREACH(ep, head, elem, link) \ + for (ep = APR_RING_FIRST(head); \ + ep != APR_RING_SENTINEL(head, elem, link); \ + ep = APR_RING_NEXT(ep, link)) + +/** + * Iterate over a ring safe against removal of the current element + * @param ep1 The current element + * @param ep2 Iteration cursor + * @param head The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_FOREACH_SAFE(ep1, ep2, head, elem, link) \ + for (ep1 = APR_RING_FIRST(head), ep2 = APR_RING_NEXT(ep1, link); \ + ep1 != APR_RING_SENTINEL(head, elem, link); \ + ep1 = ep2, ep2 = APR_RING_NEXT(ep1, link)) + +/* Debugging tools: */ + +#ifdef APR_RING_DEBUG +#include +#include + +#define APR_RING_CHECK_ONE(msg, ptr) \ + fprintf(stderr, "*** %s %p\n", msg, ptr) + +#define APR_RING_CHECK(hp, elem, link, msg) \ + APR_RING_CHECK_ELEM(APR_RING_SENTINEL(hp, elem, link), elem, link, msg) + +#define APR_RING_CHECK_ELEM(ep, elem, link, msg) do { \ + struct elem *start = (ep); \ + struct elem *here = start; \ + fprintf(stderr, "*** ring check start -- %s\n", msg); \ + do { \ + fprintf(stderr, "\telem %p\n", here); \ + fprintf(stderr, "\telem->next %p\n", \ + APR_RING_NEXT(here, link)); \ + fprintf(stderr, "\telem->prev %p\n", \ + APR_RING_PREV(here, link)); \ + fprintf(stderr, "\telem->next->prev %p\n", \ + APR_RING_PREV(APR_RING_NEXT(here, link), link)); \ + fprintf(stderr, "\telem->prev->next %p\n", \ + APR_RING_NEXT(APR_RING_PREV(here, link), link)); \ + if (APR_RING_PREV(APR_RING_NEXT(here, link), link) != here) { \ + fprintf(stderr, "\t*** elem->next->prev != elem\n"); \ + break; \ + } \ + if (APR_RING_NEXT(APR_RING_PREV(here, link), link) != here) { \ + fprintf(stderr, "\t*** elem->prev->next != elem\n"); \ + break; \ + } \ + here = APR_RING_NEXT(here, link); \ + } while (here != start); \ + fprintf(stderr, "*** ring check end\n"); \ + } while (0) + +#define APR_RING_CHECK_CONSISTENCY(hp, elem, link) \ + APR_RING_CHECK_ELEM_CONSISTENCY(APR_RING_SENTINEL(hp, elem, link),\ + elem, link) + +#define APR_RING_CHECK_ELEM_CONSISTENCY(ep, elem, link) do { \ + struct elem *start = (ep); \ + struct elem *here = start; \ + do { \ + assert(APR_RING_PREV(APR_RING_NEXT(here, link), link) == here); \ + assert(APR_RING_NEXT(APR_RING_PREV(here, link), link) == here); \ + here = APR_RING_NEXT(here, link); \ + } while (here != start); \ + } while (0) + +#else +/** + * Print a single pointer value to STDERR + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param msg Descriptive message + * @param ptr Pointer value to print + */ +#define APR_RING_CHECK_ONE(msg, ptr) +/** + * Dump all ring pointers to STDERR, starting with the head and looping all + * the way around the ring back to the head. Aborts if an inconsistency + * is found. + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param hp Head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + * @param msg Descriptive message + */ +#define APR_RING_CHECK(hp, elem, link, msg) +/** + * Loops around a ring and checks all the pointers for consistency. Pops + * an assertion if any inconsistency is found. Same idea as APR_RING_CHECK() + * except that it's silent if all is well. + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param hp Head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_CHECK_CONSISTENCY(hp, elem, link) +/** + * Dump all ring pointers to STDERR, starting with the given element and + * looping all the way around the ring back to that element. Aborts if + * an inconsistency is found. + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param ep The element + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + * @param msg Descriptive message + */ +#define APR_RING_CHECK_ELEM(ep, elem, link, msg) +/** + * Loops around a ring, starting with the given element, and checks all + * the pointers for consistency. Pops an assertion if any inconsistency + * is found. Same idea as APR_RING_CHECK_ELEM() except that it's silent + * if all is well. + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param ep The element + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_CHECK_ELEM_CONSISTENCY(ep, elem, link) +#endif + +/** @} */ + +#endif /* !APR_RING_H */ diff --git a/c/dependencies/macos/apr/include/apr_rmm.h b/c/dependencies/macos/apr/include/apr_rmm.h new file mode 100644 index 00000000..976fe9c5 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_rmm.h @@ -0,0 +1,137 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_RMM_H +#define APR_RMM_H +/** + * @file apr_rmm.h + * @brief APR-UTIL Relocatable Memory Management Routines + */ +/** + * @defgroup APR_Util_RMM Relocatable Memory Management Routines + * @ingroup APR_Util + * @{ + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apu.h" +#include "apr_anylock.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** Structure to access Relocatable, Managed Memory */ +typedef struct apr_rmm_t apr_rmm_t; + +/** Fundamental allocation unit, within a specific apr_rmm_t */ +typedef apr_size_t apr_rmm_off_t; + +/** + * Initialize a relocatable memory block to be managed by the apr_rmm API. + * @param rmm The relocatable memory block + * @param lock An apr_anylock_t of the appropriate type of lock, or NULL + * if no locking is required. + * @param membuf The block of relocatable memory to be managed + * @param memsize The size of relocatable memory block to be managed + * @param cont The pool to use for local storage and management + * @remark Both @param membuf and @param memsize must be aligned + * (for instance using APR_ALIGN_DEFAULT). + */ +APU_DECLARE(apr_status_t) apr_rmm_init(apr_rmm_t **rmm, apr_anylock_t *lock, + void *membuf, apr_size_t memsize, + apr_pool_t *cont); + +/** + * Destroy a managed memory block. + * @param rmm The relocatable memory block to destroy + */ +APU_DECLARE(apr_status_t) apr_rmm_destroy(apr_rmm_t *rmm); + +/** + * Attach to a relocatable memory block already managed by the apr_rmm API. + * @param rmm The relocatable memory block + * @param lock An apr_anylock_t of the appropriate type of lock + * @param membuf The block of relocatable memory already under management + * @param cont The pool to use for local storage and management + */ +APU_DECLARE(apr_status_t) apr_rmm_attach(apr_rmm_t **rmm, apr_anylock_t *lock, + void *membuf, apr_pool_t *cont); + +/** + * Detach from the managed block of memory. + * @param rmm The relocatable memory block to detach from + */ +APU_DECLARE(apr_status_t) apr_rmm_detach(apr_rmm_t *rmm); + +/** + * Allocate memory from the block of relocatable memory. + * @param rmm The relocatable memory block + * @param reqsize How much memory to allocate + */ +APU_DECLARE(apr_rmm_off_t) apr_rmm_malloc(apr_rmm_t *rmm, apr_size_t reqsize); + +/** + * Realloc memory from the block of relocatable memory. + * @param rmm The relocatable memory block + * @param entity The memory allocation to realloc + * @param reqsize The new size + */ +APU_DECLARE(apr_rmm_off_t) apr_rmm_realloc(apr_rmm_t *rmm, void *entity, apr_size_t reqsize); + +/** + * Allocate memory from the block of relocatable memory and initialize it to zero. + * @param rmm The relocatable memory block + * @param reqsize How much memory to allocate + */ +APU_DECLARE(apr_rmm_off_t) apr_rmm_calloc(apr_rmm_t *rmm, apr_size_t reqsize); + +/** + * Free allocation returned by apr_rmm_malloc or apr_rmm_calloc. + * @param rmm The relocatable memory block + * @param entity The memory allocation to free + */ +APU_DECLARE(apr_status_t) apr_rmm_free(apr_rmm_t *rmm, apr_rmm_off_t entity); + +/** + * Retrieve the physical address of a relocatable allocation of memory + * @param rmm The relocatable memory block + * @param entity The memory allocation to free + * @return address The address, aligned with APR_ALIGN_DEFAULT. + */ +APU_DECLARE(void *) apr_rmm_addr_get(apr_rmm_t *rmm, apr_rmm_off_t entity); + +/** + * Compute the offset of a relocatable allocation of memory + * @param rmm The relocatable memory block + * @param entity The physical address to convert to an offset + */ +APU_DECLARE(apr_rmm_off_t) apr_rmm_offset_get(apr_rmm_t *rmm, void *entity); + +/** + * Compute the required overallocation of memory needed to fit n allocs + * @param n The number of alloc/calloc regions desired + */ +APU_DECLARE(apr_size_t) apr_rmm_overhead_get(int n); + +#ifdef __cplusplus +} +#endif +/** @} */ +#endif /* ! APR_RMM_H */ + diff --git a/c/dependencies/macos/apr/include/apr_sdbm.h b/c/dependencies/macos/apr/include/apr_sdbm.h new file mode 100644 index 00000000..5759508b --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_sdbm.h @@ -0,0 +1,176 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * sdbm - ndbm work-alike hashed database library + * based on Per-Ake Larson's Dynamic Hashing algorithms. BIT 18 (1978). + * author: oz@nexus.yorku.ca + * status: ex-public domain + */ + +#ifndef APR_SDBM_H +#define APR_SDBM_H + +#include "apu.h" +#include "apr_errno.h" +#include "apr_file_io.h" /* for apr_fileperms_t */ + +/** + * @file apr_sdbm.h + * @brief apr-util SDBM library + */ +/** + * @defgroup APR_Util_DBM_SDBM SDBM library + * @ingroup APR_Util_DBM + * @{ + */ + +/** + * Structure for referencing an sdbm + */ +typedef struct apr_sdbm_t apr_sdbm_t; + +/** + * Structure for referencing the datum record within an sdbm + */ +typedef struct { + /** pointer to the data stored/retrieved */ + char *dptr; + /** size of data */ + /* apr_ssize_t for release 2.0??? */ + int dsize; +} apr_sdbm_datum_t; + +/* The extensions used for the database files */ +/** SDBM Directory file extension */ +#define APR_SDBM_DIRFEXT ".dir" +/** SDBM page file extension */ +#define APR_SDBM_PAGFEXT ".pag" + +/* flags to sdbm_store */ +#define APR_SDBM_INSERT 0 /**< Insert */ +#define APR_SDBM_REPLACE 1 /**< Replace */ +#define APR_SDBM_INSERTDUP 2 /**< Insert with duplicates */ + +/** + * Open an sdbm database by file name + * @param db The newly opened database + * @param name The sdbm file to open + * @param mode The flag values (APR_READ and APR_BINARY flags are implicit) + *
+ *           APR_WRITE          open for read-write access
+ *           APR_CREATE         create the sdbm if it does not exist
+ *           APR_TRUNCATE       empty the contents of the sdbm
+ *           APR_EXCL           fail for APR_CREATE if the file exists
+ *           APR_DELONCLOSE     delete the sdbm when closed
+ *           APR_SHARELOCK      support locking across process/machines
+ * 
+ * @param perms Permissions to apply to if created + * @param p The pool to use when creating the sdbm + * @remark The sdbm name is not a true file name, as sdbm appends suffixes + * for seperate data and index files. + */ +APU_DECLARE(apr_status_t) apr_sdbm_open(apr_sdbm_t **db, const char *name, + apr_int32_t mode, + apr_fileperms_t perms, apr_pool_t *p); + +/** + * Close an sdbm file previously opened by apr_sdbm_open + * @param db The database to close + */ +APU_DECLARE(apr_status_t) apr_sdbm_close(apr_sdbm_t *db); + +/** + * Lock an sdbm database for concurency of multiple operations + * @param db The database to lock + * @param type The lock type + *
+ *           APR_FLOCK_SHARED
+ *           APR_FLOCK_EXCLUSIVE
+ * 
+ * @remark Calls to apr_sdbm_lock may be nested. All apr_sdbm functions + * perform implicit locking. Since an APR_FLOCK_SHARED lock cannot be + * portably promoted to an APR_FLOCK_EXCLUSIVE lock, apr_sdbm_store and + * apr_sdbm_delete calls will fail if an APR_FLOCK_SHARED lock is held. + * The apr_sdbm_lock call requires the database to be opened with the + * APR_SHARELOCK mode value. + */ +APU_DECLARE(apr_status_t) apr_sdbm_lock(apr_sdbm_t *db, int type); + +/** + * Release an sdbm lock previously aquired by apr_sdbm_lock + * @param db The database to unlock + */ +APU_DECLARE(apr_status_t) apr_sdbm_unlock(apr_sdbm_t *db); + +/** + * Fetch an sdbm record value by key + * @param db The database + * @param value The value datum retrieved for this record + * @param key The key datum to find this record + */ +APU_DECLARE(apr_status_t) apr_sdbm_fetch(apr_sdbm_t *db, + apr_sdbm_datum_t *value, + apr_sdbm_datum_t key); + +/** + * Store an sdbm record value by key + * @param db The database + * @param key The key datum to store this record by + * @param value The value datum to store in this record + * @param opt The method used to store the record + *
+ *           APR_SDBM_INSERT     return an error if the record exists
+ *           APR_SDBM_REPLACE    overwrite any existing record for key
+ * 
+ */ +APU_DECLARE(apr_status_t) apr_sdbm_store(apr_sdbm_t *db, apr_sdbm_datum_t key, + apr_sdbm_datum_t value, int opt); + +/** + * Delete an sdbm record value by key + * @param db The database + * @param key The key datum of the record to delete + * @remark It is not an error to delete a non-existent record. + */ +APU_DECLARE(apr_status_t) apr_sdbm_delete(apr_sdbm_t *db, + const apr_sdbm_datum_t key); + +/** + * Retrieve the first record key from a dbm + * @param db The database + * @param key The key datum of the first record + * @remark The keys returned are not ordered. To traverse the list of keys + * for an sdbm opened with APR_SHARELOCK, the caller must use apr_sdbm_lock + * prior to retrieving the first record, and hold the lock until after the + * last call to apr_sdbm_nextkey. + */ +APU_DECLARE(apr_status_t) apr_sdbm_firstkey(apr_sdbm_t *db, apr_sdbm_datum_t *key); + +/** + * Retrieve the next record key from an sdbm + * @param db The database + * @param key The key datum of the next record + */ +APU_DECLARE(apr_status_t) apr_sdbm_nextkey(apr_sdbm_t *db, apr_sdbm_datum_t *key); + +/** + * Returns true if the sdbm database opened for read-only access + * @param db The database to test + */ +APU_DECLARE(int) apr_sdbm_rdonly(apr_sdbm_t *db); +/** @} */ +#endif /* APR_SDBM_H */ diff --git a/c/dependencies/macos/apr/include/apr_sha1.h b/c/dependencies/macos/apr/include/apr_sha1.h new file mode 100644 index 00000000..2a4edf36 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_sha1.h @@ -0,0 +1,121 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* NIST Secure Hash Algorithm + * heavily modified by Uwe Hollerbach uh@alumni.caltech edu + * from Peter C. Gutmann's implementation as found in + * Applied Cryptography by Bruce Schneier + * This code is hereby placed in the public domain + */ + +#ifndef APR_SHA1_H +#define APR_SHA1_H + +#include "apu.h" +#include "apr_general.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_sha1.h + * @brief APR-UTIL SHA1 library + */ + +/** size of the SHA1 DIGEST */ +#define APR_SHA1_DIGESTSIZE 20 + +/** + * Define the Magic String prefix that identifies a password as being + * hashed using our algorithm. + */ +#define APR_SHA1PW_ID "{SHA}" + +/** length of the SHA Password */ +#define APR_SHA1PW_IDLEN 5 + +/** @see apr_sha1_ctx_t */ +typedef struct apr_sha1_ctx_t apr_sha1_ctx_t; + +/** + * SHA1 context structure + */ +struct apr_sha1_ctx_t { + /** message digest */ + apr_uint32_t digest[5]; + /** 64-bit bit counts */ + apr_uint32_t count_lo, count_hi; + /** SHA data buffer */ + apr_uint32_t data[16]; + /** unprocessed amount in data */ + int local; +}; + +/** + * Provide a means to SHA1 crypt/encode a plaintext password in a way which + * makes password file compatible with those commonly use in netscape web + * and ldap installations. + * @param clear The plaintext password + * @param len The length of the plaintext password + * @param out The encrypted/encoded password + * @note SHA1 support is useful for migration purposes, but is less + * secure than Apache's password format, since Apache's (MD5) + * password format uses a random eight character salt to generate + * one of many possible hashes for the same password. Netscape + * uses plain SHA1 without a salt, so the same password + * will always generate the same hash, making it easier + * to break since the search space is smaller. + */ +APU_DECLARE(void) apr_sha1_base64(const char *clear, int len, char *out); + +/** + * Initialize the SHA digest + * @param context The SHA context to initialize + */ +APU_DECLARE(void) apr_sha1_init(apr_sha1_ctx_t *context); + +/** + * Update the SHA digest + * @param context The SHA1 context to update + * @param input The buffer to add to the SHA digest + * @param inputLen The length of the input buffer + */ +APU_DECLARE(void) apr_sha1_update(apr_sha1_ctx_t *context, const char *input, + unsigned int inputLen); + +/** + * Update the SHA digest with binary data + * @param context The SHA1 context to update + * @param input The buffer to add to the SHA digest + * @param inputLen The length of the input buffer + */ +APU_DECLARE(void) apr_sha1_update_binary(apr_sha1_ctx_t *context, + const unsigned char *input, + unsigned int inputLen); + +/** + * Finish computing the SHA digest + * @param digest the output buffer in which to store the digest + * @param context The context to finalize + */ +APU_DECLARE(void) apr_sha1_final(unsigned char digest[APR_SHA1_DIGESTSIZE], + apr_sha1_ctx_t *context); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_SHA1_H */ diff --git a/c/dependencies/macos/apr/include/apr_shm.h b/c/dependencies/macos/apr/include/apr_shm.h new file mode 100644 index 00000000..635c654b --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_shm.h @@ -0,0 +1,229 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_SHM_H +#define APR_SHM_H + +/** + * @file apr_shm.h + * @brief APR Shared Memory Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_perms_set.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_shm Shared Memory Routines + * @ingroup APR + * @{ + */ + +/** + * Private, platform-specific data struture representing a shared memory + * segment. + */ +typedef struct apr_shm_t apr_shm_t; + +/** + * Create and make accessible a shared memory segment with default + * properties. + * @param m The shared memory structure to create. + * @param reqsize The desired size of the segment. + * @param filename The file to use for shared memory on platforms that + * require it. + * @param pool the pool from which to allocate the shared memory + * structure. + * @remark A note about Anonymous vs. Named shared memory segments: + * Not all plaforms support anonymous shared memory segments, but in + * some cases it is prefered over other types of shared memory + * implementations. Passing a NULL 'file' parameter to this function + * will cause the subsystem to use anonymous shared memory segments. + * If such a system is not available, APR_ENOTIMPL is returned. + * @remark A note about allocation sizes: + * On some platforms it is necessary to store some metainformation + * about the segment within the actual segment. In order to supply + * the caller with the requested size it may be necessary for the + * implementation to request a slightly greater segment length + * from the subsystem. In all cases, the apr_shm_baseaddr_get() + * function will return the first usable byte of memory. + * + */ +APR_DECLARE(apr_status_t) apr_shm_create(apr_shm_t **m, + apr_size_t reqsize, + const char *filename, + apr_pool_t *pool); + +/** + * Special processing flags for apr_shm_create_ex() and apr_shm_attach_ex(). + */ +#define APR_SHM_NS_LOCAL 1 /* Create or attach to named shared memory + * segment in the "Local" namespace on + * Windows. (Ignored on other platforms.) + * By default, the "Global" namespace is + * used for privileged processes and the + * "Local" namespace is used otherwise. + */ +#define APR_SHM_NS_GLOBAL 2 /* Create or attach to named shared memory + * segment in the "Global" namespace on + * Windows. (Ignored on other platforms.) + */ + +/** + * Create and make accessible a shared memory segment with platform- + * specific processing. + * @param m The shared memory structure to create. + * @param reqsize The desired size of the segment. + * @param filename The file to use for shared memory on platforms that + * require it. + * @param pool the pool from which to allocate the shared memory + * structure. + * @param flags mask of APR_SHM_* (defined above) + * @remark A note about Anonymous vs. Named shared memory segments: + * Not all plaforms support anonymous shared memory segments, but in + * some cases it is prefered over other types of shared memory + * implementations. Passing a NULL 'file' parameter to this function + * will cause the subsystem to use anonymous shared memory segments. + * If such a system is not available, APR_ENOTIMPL is returned. + * @remark A note about allocation sizes: + * On some platforms it is necessary to store some metainformation + * about the segment within the actual segment. In order to supply + * the caller with the requested size it may be necessary for the + * implementation to request a slightly greater segment length + * from the subsystem. In all cases, the apr_shm_baseaddr_get() + * function will return the first usable byte of memory. + * + */ +APR_DECLARE(apr_status_t) apr_shm_create_ex(apr_shm_t **m, + apr_size_t reqsize, + const char *filename, + apr_pool_t *pool, + apr_int32_t flags); + +/** + * Remove named resource associated with a shared memory segment, + * preventing attachments to the resource, but not destroying it. + * @param filename The filename associated with shared-memory segment which + * needs to be removed + * @param pool The pool used for file operations + * @remark This function is only supported on platforms which support + * name-based shared memory segments, and will return APR_ENOTIMPL on + * platforms without such support. Removing the file while the shm + * is in use is not entirely portable, caller may use this to enhance + * obscurity of the resource, but be prepared for the call to fail, + * and for concurrent attempts to create a resource of the same name + * to also fail. The pool cleanup of apr_shm_create (apr_shm_destroy) + * also removes the named resource. + */ +APR_DECLARE(apr_status_t) apr_shm_remove(const char *filename, + apr_pool_t *pool); + +/** + * Delete named resource associated with a shared memory segment, + * preventing attachments to the resource. + * @param m The shared memory segment structure to delete. + * @remark This function is only supported on platforms which support + * name-based shared memory segments, and will return APR_ENOTIMPL on + * platforms without such support. Removing the file while the shm + * is in use is not entirely portable, caller may use this to enhance + * obscurity of the resource, but be prepared for the call to fail, + * and for concurrent attempts to create a resource of the same name + * to also fail. The pool cleanup of apr_shm_create (apr_shm_destroy) + * also removes the named resource. + */ +APR_DECLARE(apr_status_t) apr_shm_delete(apr_shm_t *m); + +/** + * Destroy a shared memory segment and associated memory. + * @param m The shared memory segment structure to destroy. + */ +APR_DECLARE(apr_status_t) apr_shm_destroy(apr_shm_t *m); + +/** + * Attach to a shared memory segment that was created + * by another process. + * @param m The shared memory structure to create. + * @param filename The file used to create the original segment. + * (This MUST match the original filename.) + * @param pool the pool from which to allocate the shared memory + * structure for this process. + */ +APR_DECLARE(apr_status_t) apr_shm_attach(apr_shm_t **m, + const char *filename, + apr_pool_t *pool); + +/** + * Attach to a shared memory segment that was created + * by another process, with platform-specific processing. + * @param m The shared memory structure to create. + * @param filename The file used to create the original segment. + * (This MUST match the original filename.) + * @param pool the pool from which to allocate the shared memory + * structure for this process. + * @param flags mask of APR_SHM_* (defined above) + */ +APR_DECLARE(apr_status_t) apr_shm_attach_ex(apr_shm_t **m, + const char *filename, + apr_pool_t *pool, + apr_int32_t flags); + +/** + * Detach from a shared memory segment without destroying it. + * @param m The shared memory structure representing the segment + * to detach from. + */ +APR_DECLARE(apr_status_t) apr_shm_detach(apr_shm_t *m); + +/** + * Retrieve the base address of the shared memory segment. + * NOTE: This address is only usable within the callers address + * space, since this API does not guarantee that other attaching + * processes will maintain the same address mapping. + * @param m The shared memory segment from which to retrieve + * the base address. + * @return address, aligned by APR_ALIGN_DEFAULT. + */ +APR_DECLARE(void *) apr_shm_baseaddr_get(const apr_shm_t *m); + +/** + * Retrieve the length of a shared memory segment in bytes. + * @param m The shared memory segment from which to retrieve + * the segment length. + */ +APR_DECLARE(apr_size_t) apr_shm_size_get(const apr_shm_t *m); + +/** + * Set shared memory permissions. + */ +APR_PERMS_SET_IMPLEMENT(shm); + +/** + * Get the pool used by this shared memory segment. + */ +APR_POOL_DECLARE_ACCESSOR(shm); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_SHM_T */ diff --git a/c/dependencies/macos/apr/include/apr_signal.h b/c/dependencies/macos/apr/include/apr_signal.h new file mode 100644 index 00000000..20631333 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_signal.h @@ -0,0 +1,109 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_SIGNAL_H +#define APR_SIGNAL_H + +/** + * @file apr_signal.h + * @brief APR Signal Handling + */ + +#include "apr.h" +#include "apr_pools.h" + +#if APR_HAVE_SIGNAL_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_signal Signal Handling + * @ingroup APR + * @{ + */ + +#if APR_HAVE_SIGACTION || defined(DOXYGEN) + +#if defined(DARWIN) && !defined(__cplusplus) && !defined(_ANSI_SOURCE) +/* work around Darwin header file bugs + * http://www.opensource.apple.com/bugs/X/BSD%20Kernel/2657228.html + */ +#undef SIG_DFL +#undef SIG_IGN +#undef SIG_ERR +#define SIG_DFL (void (*)(int))0 +#define SIG_IGN (void (*)(int))1 +#define SIG_ERR (void (*)(int))-1 +#endif + +/** Function prototype for signal handlers */ +typedef void apr_sigfunc_t(int); + +/** + * Set the signal handler function for a given signal + * @param signo The signal (eg... SIGWINCH) + * @param func the function to get called + */ +APR_DECLARE(apr_sigfunc_t *) apr_signal(int signo, apr_sigfunc_t * func); + +#if defined(SIG_IGN) && !defined(SIG_ERR) +#define SIG_ERR ((apr_sigfunc_t *) -1) +#endif + +#else /* !APR_HAVE_SIGACTION */ +#define apr_signal(a, b) signal(a, b) +#endif + + +/** + * Get the description for a specific signal number + * @param signum The signal number + * @return The description of the signal + */ +APR_DECLARE(const char *) apr_signal_description_get(int signum); + +/** + * APR-private function for initializing the signal package + * @internal + * @param pglobal The internal, global pool + */ +void apr_signal_init(apr_pool_t *pglobal); + +/** + * Block the delivery of a particular signal + * @param signum The signal number + * @return status + */ +APR_DECLARE(apr_status_t) apr_signal_block(int signum); + +/** + * Enable the delivery of a particular signal + * @param signum The signal number + * @return status + */ +APR_DECLARE(apr_status_t) apr_signal_unblock(int signum); + +/** @} */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* APR_SIGNAL_H */ diff --git a/c/dependencies/macos/apr/include/apr_siphash.h b/c/dependencies/macos/apr/include/apr_siphash.h new file mode 100644 index 00000000..42aa8874 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_siphash.h @@ -0,0 +1,148 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + SipHash reference C implementation + Copyright (c) 2012-2014 Jean-Philippe Aumasson + + Copyright (c) 2012-2014 Daniel J. Bernstein + To the extent possible under law, the author(s) have dedicated all copyright + and related and neighboring rights to this software to the public domain + worldwide. This software is distributed without any warranty. + You should have received a copy of the CC0 Public Domain Dedication along + with this software. If not, see + . + */ + +#ifndef APR_SIPHASH_H +#define APR_SIPHASH_H + +#include "apr.h" +#include "apu.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_siphash.h + * @brief APR-UTIL siphash library + * "SipHash-c-d is a family of pseudorandom functions (a.k.a. keyed + * hash functions) optimized for speed on short messages", designed by + * Jean-Philippe Aumasson and Daniel J. Bernstein. It generates a 64bit + * hash (or MAC) from the message and a 128bit key. + * See http://cr.yp.to/siphash/siphash-20120620.pdf for the details, + * c is the number of compression rounds, d the number of finalization + * rounds; we also define fast implementations for c = 2 with d = 4 (aka + * siphash-2-4), and c = 4 with d = 8 (aka siphash-4-8), as recommended + * parameters per the authors. + */ + +/** size of the siphash digest */ +#define APR_SIPHASH_DSIZE 8 + +/** size of the siphash key */ +#define APR_SIPHASH_KSIZE 16 + + +/** + * @brief Computes SipHash-c-d, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key. + * @param src The message + * @param len The length of the message + * @param key The secret key + * @param c The number of compression rounds + * @param d The number of finalization rounds + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(apr_uint64_t) apr_siphash(const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE], + unsigned int c, unsigned int d); + +/** + * @brief Computes SipHash-c-d, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key, into a possibly + * unaligned buffer (using the little endian representation as defined by the + * authors for interoperabilty) usable as a MAC. + * @param out The output buffer (or MAC) + * @param src The message + * @param len The length of the message + * @param key The secret key + * @param c The number of compression rounds + * @param d The number of finalization rounds + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(void) apr_siphash_auth(unsigned char out[APR_SIPHASH_DSIZE], + const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE], + unsigned int c, unsigned int d); + +/** + * @brief Computes SipHash-2-4, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key. + * @param src The message to hash + * @param len The length of the message + * @param key The secret key + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(apr_uint64_t) apr_siphash24(const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE]); + +/** + * @brief Computes SipHash-2-4, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key, into a possibly + * unaligned buffer (using the little endian representation as defined by the + * authors for interoperabilty) usable as a MAC. + * @param out The output buffer (or MAC) + * @param src The message + * @param len The length of the message + * @param key The secret key + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(void) apr_siphash24_auth(unsigned char out[APR_SIPHASH_DSIZE], + const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE]); + +/** + * @brief Computes SipHash-4-8, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key. + * @param src The message + * @param len The length of the message + * @param key The secret key + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(apr_uint64_t) apr_siphash48(const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE]); + +/** + * @brief Computes SipHash-4-8, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key, into a possibly + * unaligned buffer (using the little endian representation as defined by the + * authors for interoperabilty) usable as a MAC. + * @param out The output buffer (or MAC) + * @param src The message + * @param len The length of the message + * @param key The secret key + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(void) apr_siphash48_auth(unsigned char out[APR_SIPHASH_DSIZE], + const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE]); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_SIPHASH_H */ diff --git a/c/dependencies/macos/apr/include/apr_skiplist.h b/c/dependencies/macos/apr/include/apr_skiplist.h new file mode 100644 index 00000000..eeab10bf --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_skiplist.h @@ -0,0 +1,381 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_SKIPLIST_H +#define APR_SKIPLIST_H +/** + * @file apr_skiplist.h + * @brief APR skip list implementation + */ + +#include "apr.h" +#include "apr_portable.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_skiplist Skip list implementation + * Refer to http://en.wikipedia.org/wiki/Skip_list for information + * about the purpose of and ideas behind skip lists. + * @ingroup APR + * @{ + */ + +/** + * apr_skiplist_compare is the function type that must be implemented + * per object type that is used in a skip list for comparisons to maintain + * order + * */ +typedef int (*apr_skiplist_compare) (void *, void *); + +/** + * apr_skiplist_freefunc is the function type that must be implemented + * to handle elements as they are removed from a skip list. + */ +typedef void (*apr_skiplist_freefunc) (void *); + +/** Opaque structure used to represent the skip list */ +struct apr_skiplist; +/** Opaque structure used to represent the skip list */ +typedef struct apr_skiplist apr_skiplist; + +/** + * Opaque structure used to represent abstract nodes in the skip list + * (an abstraction above the raw elements which are collected in the + * skip list). + */ +struct apr_skiplistnode; +/** Opaque structure */ +typedef struct apr_skiplistnode apr_skiplistnode; + +/** + * Allocate memory using the same mechanism as the skip list. + * @param sl The skip list + * @param size The amount to allocate + * @remark If a pool was provided to apr_skiplist_init(), memory will + * be allocated from the pool or from a free list maintained with + * the skip list. Otherwise, memory will be allocated using the + * C standard library heap functions. + */ +APR_DECLARE(void *) apr_skiplist_alloc(apr_skiplist *sl, size_t size); + +/** + * Free memory using the same mechanism as the skip list. + * @param sl The skip list + * @param mem The object to free + * @remark If a pool was provided to apr_skiplist_init(), memory will + * be added to a free list maintained with the skip list and be available + * to operations on the skip list or to other calls to apr_skiplist_alloc(). + * Otherwise, memory will be freed using the C standard library heap + * functions. + */ +APR_DECLARE(void) apr_skiplist_free(apr_skiplist *sl, void *mem); + +/** + * Allocate a new skip list + * @param sl The pointer in which to return the newly created skip list + * @param p The pool from which to allocate the skip list (optional). + * @remark Unlike most APR functions, a pool is optional. If no pool + * is provided, the C standard library heap functions will be used instead. + */ +APR_DECLARE(apr_status_t) apr_skiplist_init(apr_skiplist **sl, apr_pool_t *p); + +/** + * Set the comparison functions to be used for searching the skip list. + * @param sl The skip list + * @param XXX1 FIXME + * @param XXX2 FIXME + * + * @remark If existing comparison functions are being replaced, the index + * will be replaced during this call. That is a potentially expensive + * operation. + */ +APR_DECLARE(void) apr_skiplist_set_compare(apr_skiplist *sl, apr_skiplist_compare XXX1, + apr_skiplist_compare XXX2); + +/** + * Set the indexing functions to the specified comparison functions and + * rebuild the index. + * @param sl The skip list + * @param XXX1 FIXME + * @param XXX2 FIXME + * + * @remark If an index already exists, it will not be replaced and the + * comparison functions will not be changed. + */ +APR_DECLARE(void) apr_skiplist_add_index(apr_skiplist *sl, apr_skiplist_compare XXX1, + apr_skiplist_compare XXX2); + +/** + * Return the list maintained by the skip list abstraction. + * @param sl The skip list + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_getlist(apr_skiplist *sl); + +/** + * Return the next matching element in the skip list using the specified + * comparison function. + * @param sl The skip list + * @param data The value to search for + * @param iter A pointer to the returned skip list node representing the element + * found + * @param func The comparison function to use + */ +APR_DECLARE(void *) apr_skiplist_find_compare(apr_skiplist *sl, + void *data, + apr_skiplistnode **iter, + apr_skiplist_compare func); + +/** + * Return the next matching element in the skip list using the current comparison + * function. + * @param sl The skip list + * @param data The value to search for + * @param iter A pointer to the returned skip list node representing the element + * found + */ +APR_DECLARE(void *) apr_skiplist_find(apr_skiplist *sl, void *data, apr_skiplistnode **iter); + +/** + * Return the last matching element in the skip list using the specified + * comparison function. + * @param sl The skip list + * @param data The value to search for + * @param iter A pointer to the returned skip list node representing the element + * found + * @param comp The comparison function to use + */ +APR_DECLARE(void *) apr_skiplist_last_compare(apr_skiplist *sl, void *data, + apr_skiplistnode **iter, + apr_skiplist_compare comp); + +/** + * Return the last matching element in the skip list using the current comparison + * function. + * @param sl The skip list + * @param data The value to search for + * @param iter A pointer to the returned skip list node representing the element + * found + */ +APR_DECLARE(void *) apr_skiplist_last(apr_skiplist *sl, void *data, + apr_skiplistnode **iter); + +/** + * Return the next element in the skip list. + * @param sl The skip list + * @param iter On entry, a pointer to the skip list node to start with; on return, + * a pointer to the skip list node representing the element returned + * @remark If iter points to a NULL value on entry, NULL will be returned. + */ +APR_DECLARE(void *) apr_skiplist_next(apr_skiplist *sl, apr_skiplistnode **iter); + +/** + * Return the previous element in the skip list. + * @param sl The skip list + * @param iter On entry, a pointer to the skip list node to start with; on return, + * a pointer to the skip list node representing the element returned + * @remark If iter points to a NULL value on entry, NULL will be returned. + */ +APR_DECLARE(void *) apr_skiplist_previous(apr_skiplist *sl, apr_skiplistnode **iter); + +/** + * Return the element of the skip list node + * @param iter The skip list node + */ +APR_DECLARE(void *) apr_skiplist_element(apr_skiplistnode *iter); + +/** + * Insert an element into the skip list using the specified comparison function + * if it does not already exist. + * @param sl The skip list + * @param data The element to insert + * @param comp The comparison function to use for placement into the skip list + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_insert_compare(apr_skiplist *sl, + void *data, apr_skiplist_compare comp); + +/** + * Insert an element into the skip list using the existing comparison function + * if it does not already exist. + * @param sl The skip list + * @param data The element to insert + * @remark If no comparison function has been set for the skip list, the element + * will not be inserted and NULL will be returned. + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_insert(apr_skiplist* sl, void *data); + +/** + * Add an element into the skip list using the specified comparison function + * allowing for duplicates. + * @param sl The skip list + * @param data The element to add + * @param comp The comparison function to use for placement into the skip list + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_add_compare(apr_skiplist *sl, + void *data, apr_skiplist_compare comp); + +/** + * Add an element into the skip list using the existing comparison function + * allowing for duplicates. + * @param sl The skip list + * @param data The element to insert + * @remark If no comparison function has been set for the skip list, the element + * will not be inserted and NULL will be returned. + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_add(apr_skiplist* sl, void *data); + +/** + * Add an element into the skip list using the specified comparison function + * removing the existing duplicates. + * @param sl The skip list + * @param data The element to insert + * @param comp The comparison function to use for placement into the skip list + * @param myfree A function to be called for each removed duplicate + * @remark If no comparison function has been set for the skip list, the element + * will not be inserted, none will be replaced, and NULL will be returned. + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_replace_compare(apr_skiplist *sl, + void *data, apr_skiplist_freefunc myfree, + apr_skiplist_compare comp); + +/** + * Add an element into the skip list using the existing comparison function + * removing the existing duplicates. + * @param sl The skip list + * @param data The element to insert + * @param myfree A function to be called for each removed duplicate + * @remark If no comparison function has been set for the skip list, the element + * will not be inserted, none will be replaced, and NULL will be returned. + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_replace(apr_skiplist *sl, + void *data, apr_skiplist_freefunc myfree); + +/** + * Remove a node from the skip list. + * @param sl The skip list + * @param iter The skip list node to remove + * @param myfree A function to be called for the removed element + */ +APR_DECLARE(int) apr_skiplist_remove_node(apr_skiplist *sl, + apr_skiplistnode *iter, + apr_skiplist_freefunc myfree); + +/** + * Remove an element from the skip list using the specified comparison function for + * locating the element. In the case of duplicates, the 1st entry will be removed. + * @param sl The skip list + * @param data The element to remove + * @param myfree A function to be called for each removed element + * @param comp The comparison function to use for placement into the skip list + * @remark If the element is not found, 0 will be returned. Otherwise, the heightXXX + * will be returned. + */ +APR_DECLARE(int) apr_skiplist_remove_compare(apr_skiplist *sl, void *data, + apr_skiplist_freefunc myfree, apr_skiplist_compare comp); + +/** + * Remove an element from the skip list using the existing comparison function for + * locating the element. In the case of duplicates, the 1st entry will be removed. + * @param sl The skip list + * @param data The element to remove + * @param myfree A function to be called for each removed element + * @remark If the element is not found, 0 will be returned. Otherwise, the heightXXX + * will be returned. + * @remark If no comparison function has been set for the skip list, the element + * will not be removed and 0 will be returned. + */ +APR_DECLARE(int) apr_skiplist_remove(apr_skiplist *sl, void *data, apr_skiplist_freefunc myfree); + +/** + * Remove all elements from the skip list. + * @param sl The skip list + * @param myfree A function to be called for each removed element + */ +APR_DECLARE(void) apr_skiplist_remove_all(apr_skiplist *sl, apr_skiplist_freefunc myfree); + +/** + * Remove each element from the skip list. + * @param sl The skip list + * @param myfree A function to be called for each removed element + */ +APR_DECLARE(void) apr_skiplist_destroy(apr_skiplist *sl, apr_skiplist_freefunc myfree); + +/** + * Return the first element in the skip list, removing the element from the skip list. + * @param sl The skip list + * @param myfree A function to be called for the removed element + * @remark NULL will be returned if there are no elements + */ +APR_DECLARE(void *) apr_skiplist_pop(apr_skiplist *sl, apr_skiplist_freefunc myfree); + +/** + * Return the first element in the skip list, leaving the element in the skip list. + * @param sl The skip list + * @remark NULL will be returned if there are no elements + */ +APR_DECLARE(void *) apr_skiplist_peek(apr_skiplist *sl); + +/** + * Return the size of the list (number of elements), in O(1). + * @param sl The skip list + */ +APR_DECLARE(size_t) apr_skiplist_size(const apr_skiplist *sl); + +/** + * Return the height of the list (number of skip paths), in O(1). + * @param sl The skip list + */ +APR_DECLARE(int) apr_skiplist_height(const apr_skiplist *sl); + +/** + * Return the predefined maximum height of the skip list. + * @param sl The skip list + */ +APR_DECLARE(int) apr_skiplist_preheight(const apr_skiplist *sl); + +/** + * Set a predefined maximum height for the skip list. + * @param sl The skip list + * @param to The preheight to set, or a nul/negative value to disable. + * @remark When a preheight is used, the height of each inserted element is + * computed randomly up to this preheight instead of the current skip list's + * height plus one used by the default implementation. Using a preheight can + * probably ensure more fairness with long living elements (since with an + * adaptative height, former elements may have been created with a low height, + * hence a longest path to reach them while the skip list grows). On the other + * hand, the default behaviour (preheight <= 0) with a growing and decreasing + * maximum height is more adaptative/suitable for short living values. + * @note Should be called before any insertion/add. + */ +APR_DECLARE(void) apr_skiplist_set_preheight(apr_skiplist *sl, int to); + +/** + * Merge two skip lists. XXX SEMANTICS + * @param sl1 One of two skip lists to be merged + * @param sl2 The other of two skip lists to be merged + */ +APR_DECLARE(apr_skiplist *) apr_skiplist_merge(apr_skiplist *sl1, apr_skiplist *sl2); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_SKIPLIST_H */ diff --git a/c/dependencies/macos/apr/include/apr_strings.h b/c/dependencies/macos/apr/include/apr_strings.h new file mode 100644 index 00000000..d5f8719d --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_strings.h @@ -0,0 +1,380 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* Portions of this file are covered by */ +/* -*- mode: c; c-file-style: "k&r" -*- + + strnatcmp.c -- Perform 'natural order' comparisons of strings in C. + Copyright (C) 2000 by Martin Pool + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef APR_STRINGS_H +#define APR_STRINGS_H + +/** + * @file apr_strings.h + * @brief APR Strings library + */ + +#include "apr.h" +#include "apr_errno.h" +#include "apr_pools.h" +#define APR_WANT_IOVEC +#include "apr_want.h" + +#if APR_HAVE_STDARG_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_strings String routines + * @ingroup APR + * @{ + */ + +/** + * Do a natural order comparison of two strings. + * @param a The first string to compare + * @param b The second string to compare + * @return Either <0, 0, or >0. If the first string is less than the second + * this returns <0, if they are equivalent it returns 0, and if the + * first string is greater than second string it retuns >0. + */ +APR_DECLARE(int) apr_strnatcmp(char const *a, char const *b); + +/** + * Do a natural order comparison of two strings ignoring the case of the + * strings. + * @param a The first string to compare + * @param b The second string to compare + * @return Either <0, 0, or >0. If the first string is less than the second + * this returns <0, if they are equivalent it returns 0, and if the + * first string is greater than second string it retuns >0. + */ +APR_DECLARE(int) apr_strnatcasecmp(char const *a, char const *b); + +/** + * duplicate a string into memory allocated out of a pool + * @param p The pool to allocate out of + * @param s The string to duplicate + * @return The new string or NULL if s == NULL + */ +APR_DECLARE(char *) apr_pstrdup(apr_pool_t *p, const char *s); + +/** + * Create a null-terminated string by making a copy of a sequence + * of characters and appending a null byte + * @param p The pool to allocate out of + * @param s The block of characters to duplicate + * @param n The number of characters to duplicate + * @return The new string or NULL if s == NULL + * @remark This is a faster alternative to apr_pstrndup(), for use + * when you know that the string being duplicated really + * has 'n' or more characters. If the string might contain + * fewer characters, use apr_pstrndup(). + */ +APR_DECLARE(char *) apr_pstrmemdup(apr_pool_t *p, const char *s, apr_size_t n) +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) + __attribute__((alloc_size(3))) +#endif + ; + +/** + * Duplicate at most n characters of a string into memory allocated + * out of a pool; the new string will be NUL-terminated + * @param p The pool to allocate out of + * @param s The string to duplicate + * @param n The maximum number of characters to duplicate + * @return The new string or NULL if s == NULL + * @remark The amount of memory allocated from the pool is the length + * of the returned string including the NUL terminator + */ +APR_DECLARE(char *) apr_pstrndup(apr_pool_t *p, const char *s, apr_size_t n); + +/** + * Duplicate a block of memory. + * + * @param p The pool to allocate from + * @param m The memory to duplicate + * @param n The number of bytes to duplicate + * @return The new block of memory or NULL if m == NULL + */ +APR_DECLARE(void *) apr_pmemdup(apr_pool_t *p, const void *m, apr_size_t n) +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) + __attribute__((alloc_size(3))) +#endif + ; + +/** + * Concatenate multiple strings, allocating memory out a pool + * @param p The pool to allocate out of + * @param ... The strings to concatenate. The final string must be NULL + * @return The new string + */ +APR_DECLARE_NONSTD(char *) apr_pstrcat(apr_pool_t *p, ...) +#if defined(__GNUC__) && __GNUC__ >= 4 + __attribute__((sentinel)) +#endif + ; + +/** + * Concatenate multiple strings specified in a writev-style vector + * @param p The pool from which to allocate + * @param vec The strings to concatenate + * @param nvec The number of strings to concatenate + * @param nbytes (output) strlen of new string (pass in NULL to omit) + * @return The new string + */ +APR_DECLARE(char *) apr_pstrcatv(apr_pool_t *p, const struct iovec *vec, + apr_size_t nvec, apr_size_t *nbytes); + +/** + * printf-style style printing routine. The data is output to a string + * allocated from a pool + * @param p The pool to allocate out of + * @param fmt The format of the string + * @param ap The arguments to use while printing the data + * @return The new string + */ +APR_DECLARE(char *) apr_pvsprintf(apr_pool_t *p, const char *fmt, va_list ap); + +/** + * printf-style style printing routine. The data is output to a string + * allocated from a pool + * @param p The pool to allocate out of + * @param fmt The format of the string + * @param ... The arguments to use while printing the data + * @return The new string + */ +APR_DECLARE_NONSTD(char *) apr_psprintf(apr_pool_t *p, const char *fmt, ...) + __attribute__((format(printf,2,3))); + +/** + * Copy up to dst_size characters from src to dst; does not copy + * past a NUL terminator in src, but always terminates dst with a NUL + * regardless. + * @param dst The destination string + * @param src The source string + * @param dst_size The space available in dst; dst always receives + * NUL termination, so if src is longer than + * dst_size, the actual number of characters copied is + * dst_size - 1. + * @return Pointer to the NUL terminator of the destination string, dst + * @remark + *
+ * Note the differences between this function and strncpy():
+ *  1) strncpy() doesn't always NUL terminate; apr_cpystrn() does.
+ *  2) strncpy() pads the destination string with NULs, which is often 
+ *     unnecessary; apr_cpystrn() does not.
+ *  3) strncpy() returns a pointer to the beginning of the dst string;
+ *     apr_cpystrn() returns a pointer to the NUL terminator of dst, 
+ *     to allow a check for truncation.
+ * 
+ */ +APR_DECLARE(char *) apr_cpystrn(char *dst, const char *src, + apr_size_t dst_size); + +/** + * Remove all whitespace from a string + * @param dest The destination string. It is okay to modify the string + * in place. Namely dest == src + * @param src The string to rid the spaces from. + * @return A pointer to the destination string's null terminator. + */ +APR_DECLARE(char *) apr_collapse_spaces(char *dest, const char *src); + +/** + * Convert the arguments to a program from one string to an array of + * strings terminated by a NULL pointer + * @param arg_str The arguments to convert + * @param argv_out Output location. This is a pointer to an array of strings. + * @param token_context Pool to use. + */ +APR_DECLARE(apr_status_t) apr_tokenize_to_argv(const char *arg_str, + char ***argv_out, + apr_pool_t *token_context); + +/** + * Split a string into separate null-terminated tokens. The tokens are + * delimited in the string by one or more characters from the sep + * argument. + * @param str The string to separate; this should be specified on the + * first call to apr_strtok() for a given string, and NULL + * on subsequent calls. + * @param sep The set of delimiters + * @param last State saved by apr_strtok() between calls. + * @return The next token from the string + * @note the 'last' state points to the trailing NUL char of the final + * token, otherwise it points to the character following the current + * token (all successive or empty occurances of sep are skiped on the + * subsequent call to apr_strtok). Therefore it is possible to avoid + * a strlen() determination, with the following logic; + * toklen = last - retval; if (*last) --toklen; + */ +APR_DECLARE(char *) apr_strtok(char *str, const char *sep, char **last); + +/** + * @defgroup APR_Strings_Snprintf snprintf implementations + * @warning + * These are snprintf implementations based on apr_vformatter(). + * + * Note that various standards and implementations disagree on the return + * value of snprintf, and side-effects due to %n in the formatting string. + * apr_snprintf (and apr_vsnprintf) behaves as follows: + * + * Process the format string until the entire string is exhausted, or + * the buffer fills. If the buffer fills then stop processing immediately + * (so no further %n arguments are processed), and return the buffer + * length. In all cases the buffer is NUL terminated. It will return the + * number of characters inserted into the buffer, not including the + * terminating NUL. As a special case, if len is 0, apr_snprintf will + * return the number of characters that would have been inserted if + * the buffer had been infinite (in this case, *buffer can be NULL) + * + * In no event does apr_snprintf return a negative number. + * @{ + */ + +/** + * snprintf routine based on apr_vformatter. This means it understands the + * same extensions. + * @param buf The buffer to write to + * @param len The size of the buffer + * @param format The format string + * @param ... The arguments to use to fill out the format string. + */ +APR_DECLARE_NONSTD(int) apr_snprintf(char *buf, apr_size_t len, + const char *format, ...) + __attribute__((format(printf,3,4))); + +/** + * vsnprintf routine based on apr_vformatter. This means it understands the + * same extensions. + * @param buf The buffer to write to + * @param len The size of the buffer + * @param format The format string + * @param ap The arguments to use to fill out the format string. + */ +APR_DECLARE(int) apr_vsnprintf(char *buf, apr_size_t len, const char *format, + va_list ap); +/** @} */ + +/** + * create a string representation of an int, allocated from a pool + * @param p The pool from which to allocate + * @param n The number to format + * @return The string representation of the number + */ +APR_DECLARE(char *) apr_itoa(apr_pool_t *p, int n); + +/** + * create a string representation of a long, allocated from a pool + * @param p The pool from which to allocate + * @param n The number to format + * @return The string representation of the number + */ +APR_DECLARE(char *) apr_ltoa(apr_pool_t *p, long n); + +/** + * create a string representation of an apr_off_t, allocated from a pool + * @param p The pool from which to allocate + * @param n The number to format + * @return The string representation of the number + */ +APR_DECLARE(char *) apr_off_t_toa(apr_pool_t *p, apr_off_t n); + +/** + * Convert a numeric string into an apr_off_t numeric value. + * @param offset The value of the parsed string. + * @param buf The string to parse. It may contain optional whitespace, + * followed by an optional '+' (positive, default) or '-' (negative) + * character, followed by an optional '0x' prefix if base is 0 or 16, + * followed by numeric digits appropriate for base. + * @param end A pointer to the end of the valid character in buf. If + * not NULL, it is set to the first invalid character in buf. + * @param base A numeric base in the range between 2 and 36 inclusive, + * or 0. If base is zero, buf will be treated as base ten unless its + * digits are prefixed with '0x', in which case it will be treated as + * base 16. + * @bug *end breaks type safety; where *buf is const, *end needs to be + * declared as const in APR 2.0 + */ +APR_DECLARE(apr_status_t) apr_strtoff(apr_off_t *offset, const char *buf, + char **end, int base); + +/** + * parse a numeric string into a 64-bit numeric value + * @param buf The string to parse. It may contain optional whitespace, + * followed by an optional '+' (positive, default) or '-' (negative) + * character, followed by an optional '0x' prefix if base is 0 or 16, + * followed by numeric digits appropriate for base. + * @param end A pointer to the end of the valid character in buf. If + * not NULL, it is set to the first invalid character in buf. + * @param base A numeric base in the range between 2 and 36 inclusive, + * or 0. If base is zero, buf will be treated as base ten unless its + * digits are prefixed with '0x', in which case it will be treated as + * base 16. + * @return The numeric value of the string. On overflow, errno is set + * to ERANGE. On success, errno is set to 0. + */ +APR_DECLARE(apr_int64_t) apr_strtoi64(const char *buf, char **end, int base); + +/** + * parse a base-10 numeric string into a 64-bit numeric value. + * Equivalent to apr_strtoi64(buf, (char**)NULL, 10). + * @param buf The string to parse + * @return The numeric value of the string. On overflow, errno is set + * to ERANGE. On success, errno is set to 0. + */ +APR_DECLARE(apr_int64_t) apr_atoi64(const char *buf); + +/** + * Format a binary size (magnitiudes are 2^10 rather than 10^3) from an apr_off_t, + * as bytes, K, M, T, etc, to a four character compacted human readable string. + * @param size The size to format + * @param buf The 5 byte text buffer (counting the trailing null) + * @return The buf passed to apr_strfsize() + * @remark All negative sizes report ' - ', apr_strfsize only formats positive values. + */ +APR_DECLARE(char *) apr_strfsize(apr_off_t size, char *buf); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_STRINGS_H */ diff --git a/c/dependencies/macos/apr/include/apr_strmatch.h b/c/dependencies/macos/apr/include/apr_strmatch.h new file mode 100644 index 00000000..53fadad5 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_strmatch.h @@ -0,0 +1,81 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_STRMATCH_H +#define APR_STRMATCH_H +/** + * @file apr_strmatch.h + * @brief APR-UTIL string matching routines + */ + +#include "apu.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_StrMatch String matching routines + * @ingroup APR_Util + * @{ + */ + +/** @see apr_strmatch_pattern */ +typedef struct apr_strmatch_pattern apr_strmatch_pattern; + +/** + * Precompiled search pattern + */ +struct apr_strmatch_pattern { + /** Function called to compare */ + const char *(*compare)(const apr_strmatch_pattern *this_pattern, + const char *s, apr_size_t slen); + const char *pattern; /**< Current pattern */ + apr_size_t length; /**< Current length */ + void *context; /**< hook to add precomputed metadata */ +}; + +#if defined(DOXYGEN) +/** + * Search for a precompiled pattern within a string + * @param pattern The pattern + * @param s The string in which to search for the pattern + * @param slen The length of s (excluding null terminator) + * @return A pointer to the first instance of the pattern in s, or + * NULL if not found + */ +APU_DECLARE(const char *) apr_strmatch(const apr_strmatch_pattern *pattern, + const char *s, apr_size_t slen); +#else +#define apr_strmatch(pattern, s, slen) (*((pattern)->compare))((pattern), (s), (slen)) +#endif + +/** + * Precompile a pattern for matching using the Boyer-Moore-Horspool algorithm + * @param p The pool from which to allocate the pattern + * @param s The pattern string + * @param case_sensitive Whether the matching should be case-sensitive + * @return a pointer to the compiled pattern, or NULL if compilation fails + */ +APU_DECLARE(const apr_strmatch_pattern *) apr_strmatch_precompile(apr_pool_t *p, const char *s, int case_sensitive); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_STRMATCH_H */ diff --git a/c/dependencies/macos/apr/include/apr_support.h b/c/dependencies/macos/apr/include/apr_support.h new file mode 100644 index 00000000..79c8cb47 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_support.h @@ -0,0 +1,57 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_SUPPORT_H +#define APR_SUPPORT_H + +/** + * @file apr_support.h + * @brief APR Support functions + */ + +#include "apr.h" +#include "apr_network_io.h" +#include "apr_file_io.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_support Internal APR support functions + * @ingroup APR + * @{ + */ + +/** + * Wait for IO to occur or timeout. + * + * @param f The file to wait on. + * @param s The socket to wait on if @a f is @c NULL. + * @param for_read If non-zero wait for data to be available to read, + * otherwise wait for data to be able to be written. + * @return APR_TIMEUP if we run out of time. + */ +apr_status_t apr_wait_for_io_or_timeout(apr_file_t *f, apr_socket_t *s, + int for_read); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_SUPPORT_H */ diff --git a/c/dependencies/macos/apr/include/apr_tables.h b/c/dependencies/macos/apr/include/apr_tables.h new file mode 100644 index 00000000..7ce2adaf --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_tables.h @@ -0,0 +1,507 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_TABLES_H +#define APR_TABLES_H + +/** + * @file apr_tables.h + * @brief APR Table library + */ + +#include "apr.h" +#include "apr_pools.h" + +#if APR_HAVE_STDARG_H +#include /* for va_list */ +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_tables Table and Array Functions + * @ingroup APR + * Arrays are used to store data which is referenced sequentially or + * as a stack. Functions are provided to push and pop individual + * elements as well as to operate on the entire array. + * + * Tables are used to store data which can be referenced by key. + * Limited capabilities are provided for tables with multiple elements + * which share a key; while key lookup will return only a single + * element, iteration is available. Additionally, a table can be + * compressed to resolve duplicates. + * + * Both arrays and tables may store string or binary data; some features, + * such as concatenation or merging of elements, work only for string + * data. + * @{ + */ + +/** the table abstract data type */ +typedef struct apr_table_t apr_table_t; + +/** @see apr_array_header_t */ +typedef struct apr_array_header_t apr_array_header_t; + +/** An opaque array type */ +struct apr_array_header_t { + /** The pool the array is allocated out of */ + apr_pool_t *pool; + /** The amount of memory allocated for each element of the array */ + int elt_size; + /** The number of active elements in the array */ + int nelts; + /** The number of elements allocated in the array */ + int nalloc; + /** The elements in the array */ + char *elts; +}; + +/** + * The (opaque) structure for string-content tables. + */ +typedef struct apr_table_entry_t apr_table_entry_t; + +/** The type for each entry in a string-content table */ +struct apr_table_entry_t { + /** The key for the current table entry */ + char *key; /* maybe NULL in future; + * check when iterating thru table_elts + */ + /** The value for the current table entry */ + char *val; + + /** A checksum for the key, for use by the apr_table internals */ + apr_uint32_t key_checksum; +}; + +/** + * Get the elements from a table. + * @param t The table + * @return An array containing the contents of the table + */ +APR_DECLARE(const apr_array_header_t *) apr_table_elts(const apr_table_t *t); + +/** + * Determine if the table is empty (either NULL or having no elements). + * @param t The table to check + * @return True if empty, False otherwise + */ +APR_DECLARE(int) apr_is_empty_table(const apr_table_t *t); + +/** + * Determine if the array is empty (either NULL or having no elements). + * @param a The array to check + * @return True if empty, False otherwise + */ +APR_DECLARE(int) apr_is_empty_array(const apr_array_header_t *a); + +/** + * Create an array. + * @param p The pool to allocate the memory out of + * @param nelts the number of elements in the initial array + * @param elt_size The size of each element in the array. + * @return The new array + */ +APR_DECLARE(apr_array_header_t *) apr_array_make(apr_pool_t *p, + int nelts, int elt_size); + +/** + * Add a new element to an array (as a first-in, last-out stack). + * @param arr The array to add an element to. + * @return Location for the new element in the array. + * @remark If there are no free spots in the array, then this function will + * allocate new space for the new element. + */ +APR_DECLARE(void *) apr_array_push(apr_array_header_t *arr); + +/** A helper macro for accessing a member of an APR array. + * + * @param ary the array + * @param i the index into the array to return + * @param type the type of the objects stored in the array + * + * @return the item at index i + */ +#define APR_ARRAY_IDX(ary,i,type) (((type *)(ary)->elts)[i]) + +/** A helper macro for pushing elements into an APR array. + * + * @param ary the array + * @param type the type of the objects stored in the array + * + * @return the location where the new object should be placed + */ +#define APR_ARRAY_PUSH(ary,type) (*((type *)apr_array_push(ary))) + +/** + * Remove an element from an array (as a first-in, last-out stack). + * @param arr The array to remove an element from. + * @return Location of the element in the array. + * @remark If there are no elements in the array, NULL is returned. + */ +APR_DECLARE(void *) apr_array_pop(apr_array_header_t *arr); + +/** + * Remove all elements from an array. + * @param arr The array to remove all elements from. + * @remark As the underlying storage is allocated from a pool, no + * memory is freed by this operation, but is available for reuse. + */ +APR_DECLARE(void) apr_array_clear(apr_array_header_t *arr); + +/** + * Concatenate two arrays together. + * @param dst The destination array, and the one to go first in the combined + * array + * @param src The source array to add to the destination array + */ +APR_DECLARE(void) apr_array_cat(apr_array_header_t *dst, + const apr_array_header_t *src); + +/** + * Copy the entire array. + * @param p The pool to allocate the copy of the array out of + * @param arr The array to copy + * @return An exact copy of the array passed in + * @remark The alternate apr_array_copy_hdr() copies only the header, and arranges + * for the elements to be copied if (and only if) the code subsequently + * does a push or arraycat. + */ +APR_DECLARE(apr_array_header_t *) apr_array_copy(apr_pool_t *p, + const apr_array_header_t *arr); +/** + * Copy the headers of the array, and arrange for the elements to be copied if + * and only if the code subsequently does a push or arraycat. + * @param p The pool to allocate the copy of the array out of + * @param arr The array to copy + * @return An exact copy of the array passed in + * @remark The alternate apr_array_copy() copies the *entire* array. + */ +APR_DECLARE(apr_array_header_t *) apr_array_copy_hdr(apr_pool_t *p, + const apr_array_header_t *arr); + +/** + * Append one array to the end of another, creating a new array in the process. + * @param p The pool to allocate the new array out of + * @param first The array to put first in the new array. + * @param second The array to put second in the new array. + * @return A new array containing the data from the two arrays passed in. +*/ +APR_DECLARE(apr_array_header_t *) apr_array_append(apr_pool_t *p, + const apr_array_header_t *first, + const apr_array_header_t *second); + +/** + * Generate a new string from the apr_pool_t containing the concatenated + * sequence of substrings referenced as elements within the array. The string + * will be empty if all substrings are empty or null, or if there are no + * elements in the array. If sep is non-NUL, it will be inserted between + * elements as a separator. + * @param p The pool to allocate the string out of + * @param arr The array to generate the string from + * @param sep The separator to use + * @return A string containing all of the data in the array. + */ +APR_DECLARE(char *) apr_array_pstrcat(apr_pool_t *p, + const apr_array_header_t *arr, + const char sep); + +/** + * Make a new table. + * @param p The pool to allocate the pool out of + * @param nelts The number of elements in the initial table. + * @return The new table. + * @warning This table can only store text data + */ +APR_DECLARE(apr_table_t *) apr_table_make(apr_pool_t *p, int nelts); + +/** + * Create a new table and copy another table into it. + * @param p The pool to allocate the new table out of + * @param t The table to copy + * @return A copy of the table passed in + * @warning The table keys and respective values are not copied + */ +APR_DECLARE(apr_table_t *) apr_table_copy(apr_pool_t *p, + const apr_table_t *t); + +/** + * Create a new table whose contents are deep copied from the given + * table. A deep copy operation copies all fields, and makes copies + * of dynamically allocated memory pointed to by the fields. + * @param p The pool to allocate the new table out of + * @param t The table to clone + * @return A deep copy of the table passed in + */ +APR_DECLARE(apr_table_t *) apr_table_clone(apr_pool_t *p, + const apr_table_t *t); + +/** + * Delete all of the elements from a table. + * @param t The table to clear + */ +APR_DECLARE(void) apr_table_clear(apr_table_t *t); + +/** + * Get the value associated with a given key from the table. After this call, + * the data is still in the table. + * @param t The table to search for the key + * @param key The key to search for (case does not matter) + * @return The value associated with the key, or NULL if the key does not exist. + */ +APR_DECLARE(const char *) apr_table_get(const apr_table_t *t, const char *key); + +/** + * Get values associated with a given key from the table. If more than one + * value exists, return a comma separated list of values. After this call, the + * data is still in the table. + * @param p The pool to allocate the combined value from, if necessary + * @param t The table to search for the key + * @param key The key to search for (case does not matter) + * @return The value associated with the key, or NULL if the key does not exist. + */ +APR_DECLARE(const char *) apr_table_getm(apr_pool_t *p, const apr_table_t *t, + const char *key); + +/** + * Add a key/value pair to a table. If another element already exists with the + * same key, this will overwrite the old data. + * @param t The table to add the data to. + * @param key The key to use (case does not matter) + * @param val The value to add + * @remark When adding data, this function makes a copy of both the key and the + * value. + */ +APR_DECLARE(void) apr_table_set(apr_table_t *t, const char *key, + const char *val); + +/** + * Add a key/value pair to a table. If another element already exists with the + * same key, this will overwrite the old data. + * @param t The table to add the data to. + * @param key The key to use (case does not matter) + * @param val The value to add + * @warning When adding data, this function does not make a copy of the key or + * the value, so care should be taken to ensure that the values will + * not change after they have been added.. + */ +APR_DECLARE(void) apr_table_setn(apr_table_t *t, const char *key, + const char *val); + +/** + * Remove data from the table. + * @param t The table to remove data from + * @param key The key of the data being removed (case does not matter) + */ +APR_DECLARE(void) apr_table_unset(apr_table_t *t, const char *key); + +/** + * Add data to a table by merging the value with data that has already been + * stored. The merging is done by concatenating the two values, separated + * by the string ", ". + * @param t The table to search for the data + * @param key The key to merge data for (case does not matter) + * @param val The data to add + * @remark If the key is not found, then this function acts like apr_table_add() + */ +APR_DECLARE(void) apr_table_merge(apr_table_t *t, const char *key, + const char *val); + +/** + * Add data to a table by merging the value with data that has already been + * stored. The merging is done by concatenating the two values, separated + * by the string ", ". + * @param t The table to search for the data + * @param key The key to merge data for (case does not matter) + * @param val The data to add + * @remark If the key is not found, then this function acts like apr_table_addn() + */ +APR_DECLARE(void) apr_table_mergen(apr_table_t *t, const char *key, + const char *val); + +/** + * Add data to a table, regardless of whether there is another element with the + * same key. + * @param t The table to add to + * @param key The key to use + * @param val The value to add. + * @remark When adding data, this function makes a copy of both the key and the + * value. + */ +APR_DECLARE(void) apr_table_add(apr_table_t *t, const char *key, + const char *val); + +/** + * Add data to a table, regardless of whether there is another element with the + * same key. + * @param t The table to add to + * @param key The key to use + * @param val The value to add. + * @remark When adding data, this function does not make a copy of the key or the + * value, so care should be taken to ensure that the values will not + * change after they have been added. + */ +APR_DECLARE(void) apr_table_addn(apr_table_t *t, const char *key, + const char *val); + +/** + * Merge two tables into one new table. + * @param p The pool to use for the new table + * @param overlay The first table to put in the new table + * @param base The table to add at the end of the new table + * @return A new table containing all of the data from the two passed in + */ +APR_DECLARE(apr_table_t *) apr_table_overlay(apr_pool_t *p, + const apr_table_t *overlay, + const apr_table_t *base); + +/** + * Declaration prototype for the iterator callback function of apr_table_do() + * and apr_table_vdo(). + * @param rec The data passed as the first argument to apr_table_[v]do() + * @param key The key from this iteration of the table + * @param value The value from this iteration of the table + * @remark Iteration continues while this callback function returns non-zero. + * To export the callback function for apr_table_[v]do() it must be declared + * in the _NONSTD convention. + * @see apr_table_do @see apr_table_vdo + */ +typedef int (apr_table_do_callback_fn_t)(void *rec, const char *key, + const char *value); + +/** + * Iterate over a table running the provided function once for every + * element in the table. The varargs array must be a list of zero or + * more (char *) keys followed by a NULL pointer. If zero keys are + * given, the @p comp function will be invoked for every element + * in the table. Otherwise, the function is invoked only for those + * elements matching the keys specified. + * + * If an invocation of the @p comp function returns zero, + * iteration will continue using the next specified key, if any. + * + * @param comp The function to run + * @param rec The data to pass as the first argument to the function + * @param t The table to iterate over + * @param ... A varargs array of zero or more (char *) keys followed by NULL + * @return FALSE if one of the comp() iterations returned zero; TRUE if all + * iterations returned non-zero + * @see apr_table_do_callback_fn_t @see apr_table_vdo + */ +APR_DECLARE_NONSTD(int) apr_table_do(apr_table_do_callback_fn_t *comp, + void *rec, const apr_table_t *t, ...) +#if defined(__GNUC__) && __GNUC__ >= 4 + __attribute__((sentinel)) +#endif + ; + +/** + * Iterate over a table running the provided function once for every + * element in the table. The @p vp varargs parameter must be a + * list of zero or more (char *) keys followed by a NULL pointer. If + * zero keys are given, the @p comp function will be invoked for + * every element in the table. Otherwise, the function is invoked + * only for those elements matching the keys specified. + * + * If an invocation of the @p comp function returns zero, + * iteration will continue using the next specified key, if any. + * + * @param comp The function to run + * @param rec The data to pass as the first argument to the function + * @param t The table to iterate over + * @param vp List of zero or more (char *) keys followed by NULL + * @return FALSE if one of the comp() iterations returned zero; TRUE if all + * iterations returned non-zero + * @see apr_table_do_callback_fn_t @see apr_table_do + */ +APR_DECLARE(int) apr_table_vdo(apr_table_do_callback_fn_t *comp, + void *rec, const apr_table_t *t, va_list vp); + +/** flag for overlap to use apr_table_setn */ +#define APR_OVERLAP_TABLES_SET (0) +/** flag for overlap to use apr_table_mergen */ +#define APR_OVERLAP_TABLES_MERGE (1) +/** flag for overlap to use apr_table_addn */ +#define APR_OVERLAP_TABLES_ADD (2) +/** + * For each element in table b, either use setn or mergen to add the data + * to table a. Which method is used is determined by the flags passed in. + * @param a The table to add the data to. + * @param b The table to iterate over, adding its data to table a + * @param flags How to add the table to table a. One of: + * APR_OVERLAP_TABLES_SET Use apr_table_setn + * APR_OVERLAP_TABLES_MERGE Use apr_table_mergen + * APR_OVERLAP_TABLES_ADD Use apr_table_addn + * @remark When merging duplicates, the two values are concatenated, + * separated by the string ", ". + * @remark This function is highly optimized, and uses less memory and CPU cycles + * than a function that just loops through table b calling other functions. + */ +/** + * Conceptually, apr_table_overlap does this: + * + *
+ *  apr_array_header_t *barr = apr_table_elts(b);
+ *  apr_table_entry_t *belt = (apr_table_entry_t *)barr->elts;
+ *  int i;
+ *
+ *  for (i = 0; i < barr->nelts; ++i) {
+ *      if (flags & APR_OVERLAP_TABLES_MERGE) {
+ *          apr_table_mergen(a, belt[i].key, belt[i].val);
+ *      }
+ *      else if (flags & APR_OVERLAP_TABLES_ADD) {
+ *          apr_table_addn(a, belt[i].key, belt[i].val);
+ *      }
+ *      else {
+ *          apr_table_setn(a, belt[i].key, belt[i].val);
+ *      }
+ *  }
+ * 
+ * + * Except that it is more efficient (less space and cpu-time) especially + * when b has many elements. + * + * Notice the assumptions on the keys and values in b -- they must be + * in an ancestor of a's pool. In practice b and a are usually from + * the same pool. + */ + +APR_DECLARE(void) apr_table_overlap(apr_table_t *a, const apr_table_t *b, + unsigned flags); + +/** + * Eliminate redundant entries in a table by either overwriting + * or merging duplicates. + * + * @param t Table. + * @param flags APR_OVERLAP_TABLES_MERGE to merge, or + * APR_OVERLAP_TABLES_SET to overwrite, or + * APR_OVERLAP_TABLES_ADD to add + * @remark When merging duplicates, the two values are concatenated, + * separated by the string ", ". + */ +APR_DECLARE(void) apr_table_compress(apr_table_t *t, unsigned flags); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_TABLES_H */ diff --git a/c/dependencies/macos/apr/include/apr_thread_cond.h b/c/dependencies/macos/apr/include/apr_thread_cond.h new file mode 100644 index 00000000..199f1ded --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_thread_cond.h @@ -0,0 +1,139 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_THREAD_COND_H +#define APR_THREAD_COND_H + +/** + * @file apr_thread_cond.h + * @brief APR Condition Variable Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_time.h" +#include "apr_thread_mutex.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#if APR_HAS_THREADS || defined(DOXYGEN) + +/** + * @defgroup apr_thread_cond Condition Variable Routines + * @ingroup APR + * @{ + */ + +/** Opaque structure for thread condition variables */ +typedef struct apr_thread_cond_t apr_thread_cond_t; + +/** + * Note: destroying a condition variable (or likewise, destroying or + * clearing the pool from which a condition variable was allocated) if + * any threads are blocked waiting on it gives undefined results. + */ + +/** + * Create and initialize a condition variable that can be used to signal + * and schedule threads in a single process. + * @param cond the memory address where the newly created condition variable + * will be stored. + * @param pool the pool from which to allocate the condition. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_create(apr_thread_cond_t **cond, + apr_pool_t *pool); + +/** + * Put the active calling thread to sleep until signaled to wake up. Each + * condition variable must be associated with a mutex, and that mutex must + * be locked before calling this function, or the behavior will be + * undefined. As the calling thread is put to sleep, the given mutex + * will be simultaneously released; and as this thread wakes up the lock + * is again simultaneously acquired. + * @param cond the condition variable on which to block. + * @param mutex the mutex that must be locked upon entering this function, + * is released while the thread is asleep, and is again acquired before + * returning from this function. + * @remark Spurious wakeups may occur. Before and after every call to wait on + * a condition variable, the caller should test whether the condition is already + * met. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_wait(apr_thread_cond_t *cond, + apr_thread_mutex_t *mutex); + +/** + * Put the active calling thread to sleep until signaled to wake up or + * the timeout is reached. Each condition variable must be associated + * with a mutex, and that mutex must be locked before calling this + * function, or the behavior will be undefined. As the calling thread + * is put to sleep, the given mutex will be simultaneously released; + * and as this thread wakes up the lock is again simultaneously acquired. + * @param cond the condition variable on which to block. + * @param mutex the mutex that must be locked upon entering this function, + * is released while the thread is asleep, and is again acquired before + * returning from this function. + * @param timeout The amount of time in microseconds to wait. This is + * a maximum, not a minimum. If the condition is signaled, we + * will wake up before this time, otherwise the error APR_TIMEUP + * is returned. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_timedwait(apr_thread_cond_t *cond, + apr_thread_mutex_t *mutex, + apr_interval_time_t timeout); + +/** + * Signals a single thread, if one exists, that is blocking on the given + * condition variable. That thread is then scheduled to wake up and acquire + * the associated mutex. Although it is not required, if predictable scheduling + * is desired, that mutex must be locked while calling this function. + * @param cond the condition variable on which to produce the signal. + * @remark If no threads are waiting on the condition variable, nothing happens. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_signal(apr_thread_cond_t *cond); + +/** + * Signals all threads blocking on the given condition variable. + * Each thread that was signaled is then scheduled to wake up and acquire + * the associated mutex. This will happen in a serialized manner. + * @param cond the condition variable on which to produce the broadcast. + * @remark If no threads are waiting on the condition variable, nothing happens. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_broadcast(apr_thread_cond_t *cond); + +/** + * Destroy the condition variable and free the associated memory. + * @param cond the condition variable to destroy. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_destroy(apr_thread_cond_t *cond); + +/** + * Get the pool used by this thread_cond. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(thread_cond); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_THREAD_COND_H */ diff --git a/c/dependencies/macos/apr/include/apr_thread_mutex.h b/c/dependencies/macos/apr/include/apr_thread_mutex.h new file mode 100644 index 00000000..8eb61729 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_thread_mutex.h @@ -0,0 +1,123 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_THREAD_MUTEX_H +#define APR_THREAD_MUTEX_H + +/** + * @file apr_thread_mutex.h + * @brief APR Thread Mutex Routines + */ + +#include "apr.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#if APR_HAS_THREADS || defined(DOXYGEN) + +/** + * @defgroup apr_thread_mutex Thread Mutex Routines + * @ingroup APR + * @{ + */ + +/** Opaque thread-local mutex structure */ +typedef struct apr_thread_mutex_t apr_thread_mutex_t; + +#define APR_THREAD_MUTEX_DEFAULT 0x0 /**< platform-optimal lock behavior */ +#define APR_THREAD_MUTEX_NESTED 0x1 /**< enable nested (recursive) locks */ +#define APR_THREAD_MUTEX_UNNESTED 0x2 /**< disable nested locks */ +#define APR_THREAD_MUTEX_TIMED 0x4 /**< enable timed locks */ + +/* Delayed the include to avoid a circular reference */ +#include "apr_pools.h" +#include "apr_time.h" + +/** + * Create and initialize a mutex that can be used to synchronize threads. + * @param mutex the memory address where the newly created mutex will be + * stored. + * @param flags Or'ed value of: + *
+ *           APR_THREAD_MUTEX_DEFAULT   platform-optimal lock behavior.
+ *           APR_THREAD_MUTEX_NESTED    enable nested (recursive) locks.
+ *           APR_THREAD_MUTEX_UNNESTED  disable nested locks (non-recursive).
+ * 
+ * @param pool the pool from which to allocate the mutex. + * @warning Be cautious in using APR_THREAD_MUTEX_DEFAULT. While this is the + * most optimal mutex based on a given platform's performance characteristics, + * it will behave as either a nested or an unnested lock. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_create(apr_thread_mutex_t **mutex, + unsigned int flags, + apr_pool_t *pool); +/** + * Acquire the lock for the given mutex. If the mutex is already locked, + * the current thread will be put to sleep until the lock becomes available. + * @param mutex the mutex on which to acquire the lock. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_lock(apr_thread_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex. If the mutex has already + * been acquired, the call returns immediately with APR_EBUSY. Note: it + * is important that the APR_STATUS_IS_EBUSY(s) macro be used to determine + * if the return value was APR_EBUSY, for portability reasons. + * @param mutex the mutex on which to attempt the lock acquiring. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_trylock(apr_thread_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex until timeout expires. + * If the acquisition time outs, the call returns with APR_TIMEUP. + * @param mutex the mutex on which to attempt the lock acquiring. + * @param timeout the relative timeout (microseconds). + * @note A timeout negative or nul means immediate attempt, returning + * APR_TIMEUP without blocking if it the lock is already acquired. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_timedlock(apr_thread_mutex_t *mutex, + apr_interval_time_t timeout); + +/** + * Release the lock for the given mutex. + * @param mutex the mutex from which to release the lock. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_unlock(apr_thread_mutex_t *mutex); + +/** + * Destroy the mutex and free the memory associated with the lock. + * @param mutex the mutex to destroy. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_destroy(apr_thread_mutex_t *mutex); + +/** + * Get the pool used by this thread_mutex. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(thread_mutex); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_THREAD_MUTEX_H */ diff --git a/c/dependencies/macos/apr/include/apr_thread_pool.h b/c/dependencies/macos/apr/include/apr_thread_pool.h new file mode 100644 index 00000000..cbf382b3 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_thread_pool.h @@ -0,0 +1,299 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +#ifndef APU_THREAD_POOL_H +#define APU_THREAD_POOL_H + +#include "apu.h" +#include "apr_thread_proc.h" + +/** + * @file apr_thread_pool.h + * @brief APR Thread Pool Library + + * @remarks This library implements a thread pool using apr_thread_t. A thread + * pool is a set of threads that can be created in advance or on demand until a + * maximum number. When a task is scheduled, the thread pool will find an idle + * thread to handle the task. In case all existing threads are busy and the + * number of tasks in the queue is higher than the adjustable threshold, the + * pool will try to create a new thread to serve the task if the maximum number + * has not been reached. Otherwise, the task will be put into a queue based on + * priority, which can be valued from 0 to 255, with higher values being served + * first. If there are tasks with the same priority, the new task might be put at + * the top or at the bottom - it depends on which function is used to put the task. + * + * @remarks There may be the case where the thread pool can use up to the maximum + * number of threads at peak load, but having those threads idle afterwards. A + * maximum number of idle threads can be set so that the extra idling threads will + * be terminated to save system resources. + */ +#if APR_HAS_THREADS + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_Util_TP Thread Pool routines + * @ingroup APR_Util + * @{ + */ + +/** Opaque Thread Pool structure. */ +typedef struct apr_thread_pool apr_thread_pool_t; + +#define APR_THREAD_TASK_PRIORITY_LOWEST 0 +#define APR_THREAD_TASK_PRIORITY_LOW 63 +#define APR_THREAD_TASK_PRIORITY_NORMAL 127 +#define APR_THREAD_TASK_PRIORITY_HIGH 191 +#define APR_THREAD_TASK_PRIORITY_HIGHEST 255 + +/** + * Create a thread pool + * @param me The pointer in which to return the newly created apr_thread_pool + * object, or NULL if thread pool creation fails. + * @param init_threads The number of threads to be created initially, this number + * will also be used as the initial value for the maximum number of idle threads. + * @param max_threads The maximum number of threads that can be created + * @param pool The pool to use + * @return APR_SUCCESS if the thread pool was created successfully. Otherwise, + * the error code. + */ +APU_DECLARE(apr_status_t) apr_thread_pool_create(apr_thread_pool_t **me, + apr_size_t init_threads, + apr_size_t max_threads, + apr_pool_t *pool); + +/** + * Destroy the thread pool and stop all the threads + * @return APR_SUCCESS if all threads are stopped. + */ +APU_DECLARE(apr_status_t) apr_thread_pool_destroy(apr_thread_pool_t *me); + +/** + * Schedule a task to the bottom of the tasks of same priority. + * @param me The thread pool + * @param func The task function + * @param param The parameter for the task function + * @param priority The priority of the task. + * @param owner Owner of this task. + * @return APR_SUCCESS if the task had been scheduled successfully + */ +APU_DECLARE(apr_status_t) apr_thread_pool_push(apr_thread_pool_t *me, + apr_thread_start_t func, + void *param, + apr_byte_t priority, + void *owner); +/** + * Schedule a task to be run after a delay + * @param me The thread pool + * @param func The task function + * @param param The parameter for the task function + * @param time Time in microseconds + * @param owner Owner of this task. + * @return APR_SUCCESS if the task had been scheduled successfully + */ +APU_DECLARE(apr_status_t) apr_thread_pool_schedule(apr_thread_pool_t *me, + apr_thread_start_t func, + void *param, + apr_interval_time_t time, + void *owner); + +/** + * Schedule a task to the top of the tasks of same priority. + * @param me The thread pool + * @param func The task function + * @param param The parameter for the task function + * @param priority The priority of the task. + * @param owner Owner of this task. + * @return APR_SUCCESS if the task had been scheduled successfully + */ +APU_DECLARE(apr_status_t) apr_thread_pool_top(apr_thread_pool_t *me, + apr_thread_start_t func, + void *param, + apr_byte_t priority, + void *owner); + +/** + * Cancel tasks submitted by the owner. If there is any task from the owner that + * is currently running, the function will spin until the task finished. + * @param me The thread pool + * @param owner Owner of the task + * @return APR_SUCCESS if the task has been cancelled successfully + * @note The task function should not be calling cancel, otherwise the function + * may get stuck forever. The function assert if it detect such a case. + */ +APU_DECLARE(apr_status_t) apr_thread_pool_tasks_cancel(apr_thread_pool_t *me, + void *owner); + +/** + * Get the current number of tasks waiting in the queue + * @param me The thread pool + * @return Number of tasks in the queue + */ +APU_DECLARE(apr_size_t) apr_thread_pool_tasks_count(apr_thread_pool_t *me); + +/** + * Get the current number of scheduled tasks waiting in the queue + * @param me The thread pool + * @return Number of scheduled tasks in the queue + */ +APU_DECLARE(apr_size_t) apr_thread_pool_scheduled_tasks_count(apr_thread_pool_t *me); + +/** + * Get the current number of threads + * @param me The thread pool + * @return Total number of threads + */ +APU_DECLARE(apr_size_t) apr_thread_pool_threads_count(apr_thread_pool_t *me); + +/** + * Get the current number of busy threads + * @param me The thread pool + * @return Number of busy threads + */ +APU_DECLARE(apr_size_t) apr_thread_pool_busy_count(apr_thread_pool_t *me); + +/** + * Get the current number of idle threads + * @param me The thread pool + * @return Number of idle threads + */ +APU_DECLARE(apr_size_t) apr_thread_pool_idle_count(apr_thread_pool_t *me); + +/** + * Access function for the maximum number of idle threads. Number of current + * idle threads will be reduced to the new limit. + * @param me The thread pool + * @param cnt The number + * @return The number of threads that were stopped. + */ +APU_DECLARE(apr_size_t) apr_thread_pool_idle_max_set(apr_thread_pool_t *me, + apr_size_t cnt); + +/** + * Get number of tasks that have run + * @param me The thread pool + * @return Number of tasks that have run + */ +APU_DECLARE(apr_size_t) + apr_thread_pool_tasks_run_count(apr_thread_pool_t * me); + +/** + * Get high water mark of the number of tasks waiting to run + * @param me The thread pool + * @return High water mark of tasks waiting to run + */ +APU_DECLARE(apr_size_t) + apr_thread_pool_tasks_high_count(apr_thread_pool_t * me); + +/** + * Get high water mark of the number of threads + * @param me The thread pool + * @return High water mark of threads in thread pool + */ +APU_DECLARE(apr_size_t) + apr_thread_pool_threads_high_count(apr_thread_pool_t * me); + +/** + * Get the number of idle threads that were destroyed after timing out + * @param me The thread pool + * @return Number of idle threads that timed out + */ +APU_DECLARE(apr_size_t) + apr_thread_pool_threads_idle_timeout_count(apr_thread_pool_t * me); + +/** + * Access function for the maximum number of idle threads + * @param me The thread pool + * @return The current maximum number + */ +APU_DECLARE(apr_size_t) apr_thread_pool_idle_max_get(apr_thread_pool_t *me); + +/** + * Access function for the maximum number of threads. + * @param me The thread pool + * @param cnt Number of threads + * @return The original maximum number of threads + */ +APU_DECLARE(apr_size_t) apr_thread_pool_thread_max_set(apr_thread_pool_t *me, + apr_size_t cnt); + +/** + * Access function for the maximum wait time (in microseconds) of an + * idling thread that exceeds the maximum number of idling threads. + * A non-zero value allows for the reaping of idling threads to shrink + * over time. Which helps reduce thrashing. + * @param me The thread pool + * @param timeout The number of microseconds an idle thread should wait + * till it reaps itself + * @return The original maximum wait time + */ +APU_DECLARE(apr_interval_time_t) + apr_thread_pool_idle_wait_set(apr_thread_pool_t * me, + apr_interval_time_t timeout); + +/** + * Access function for the maximum wait time (in microseconds) of an + * idling thread that exceeds the maximum number of idling threads + * @param me The thread pool + * @return The current maximum wait time + */ +APU_DECLARE(apr_interval_time_t) + apr_thread_pool_idle_wait_get(apr_thread_pool_t * me); + +/** + * Access function for the maximum number of threads + * @param me The thread pool + * @return The current maximum number + */ +APU_DECLARE(apr_size_t) apr_thread_pool_thread_max_get(apr_thread_pool_t *me); + +/** + * Access function for the threshold of tasks in queue to trigger a new thread. + * @param me The thread pool + * @param cnt The new threshold + * @return The original threshold + */ +APU_DECLARE(apr_size_t) apr_thread_pool_threshold_set(apr_thread_pool_t *me, + apr_size_t val); + +/** + * Access function for the threshold of tasks in queue to trigger a new thread. + * @param me The thread pool + * @return The current threshold + */ +APU_DECLARE(apr_size_t) apr_thread_pool_threshold_get(apr_thread_pool_t * me); + +/** + * Get owner of the task currently been executed by the thread. + * @param thd The thread is executing a task + * @param owner Pointer to receive owner of the task. + * @return APR_SUCCESS if the owner is retrieved successfully + */ +APU_DECLARE(apr_status_t) apr_thread_pool_task_owner_get(apr_thread_t *thd, + void **owner); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_HAS_THREADS */ +#endif /* !APR_THREAD_POOL_H */ diff --git a/c/dependencies/macos/apr/include/apr_thread_proc.h b/c/dependencies/macos/apr/include/apr_thread_proc.h new file mode 100644 index 00000000..ea3c43f9 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_thread_proc.h @@ -0,0 +1,846 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_THREAD_PROC_H +#define APR_THREAD_PROC_H + +/** + * @file apr_thread_proc.h + * @brief APR Thread and Process Library + */ + +#include "apr.h" +#include "apr_file_io.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_perms_set.h" + +#if APR_HAVE_STRUCT_RLIMIT +#include +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_thread_proc Threads and Process Functions + * @ingroup APR + * @{ + */ + +typedef enum { + APR_SHELLCMD, /**< use the shell to invoke the program */ + APR_PROGRAM, /**< invoke the program directly, no copied env */ + APR_PROGRAM_ENV, /**< invoke the program, replicating our environment */ + APR_PROGRAM_PATH, /**< find program on PATH, use our environment */ + APR_SHELLCMD_ENV /**< use the shell to invoke the program, + * replicating our environment + */ +} apr_cmdtype_e; + +typedef enum { + APR_WAIT, /**< wait for the specified process to finish */ + APR_NOWAIT /**< do not wait -- just see if it has finished */ +} apr_wait_how_e; + +/* I am specifically calling out the values so that the macros below make + * more sense. Yes, I know I don't need to, but I am hoping this makes what + * I am doing more clear. If you want to add more reasons to exit, continue + * to use bitmasks. + */ +typedef enum { + APR_PROC_EXIT = 1, /**< process exited normally */ + APR_PROC_SIGNAL = 2, /**< process exited due to a signal */ + APR_PROC_SIGNAL_CORE = 4 /**< process exited and dumped a core file */ +} apr_exit_why_e; + +/** did we exit the process */ +#define APR_PROC_CHECK_EXIT(x) (x & APR_PROC_EXIT) +/** did we get a signal */ +#define APR_PROC_CHECK_SIGNALED(x) (x & APR_PROC_SIGNAL) +/** did we get core */ +#define APR_PROC_CHECK_CORE_DUMP(x) (x & APR_PROC_SIGNAL_CORE) + +/** @see apr_procattr_io_set */ +#define APR_NO_PIPE 0 +/** @see apr_procattr_io_set and apr_file_pipe_create_ex */ +#define APR_FULL_BLOCK 1 +/** @see apr_procattr_io_set and apr_file_pipe_create_ex */ +#define APR_FULL_NONBLOCK 2 +/** @see apr_procattr_io_set */ +#define APR_PARENT_BLOCK 3 +/** @see apr_procattr_io_set */ +#define APR_CHILD_BLOCK 4 +/** @see apr_procattr_io_set */ +#define APR_NO_FILE 8 + +/** @see apr_file_pipe_create_ex */ +#define APR_READ_BLOCK 3 +/** @see apr_file_pipe_create_ex */ +#define APR_WRITE_BLOCK 4 + +/** @see apr_procattr_io_set + * @note Win32 only effective with version 1.2.12, portably introduced in 1.3.0 + */ +#define APR_NO_FILE 8 + +/** @see apr_procattr_limit_set */ +#define APR_LIMIT_CPU 0 +/** @see apr_procattr_limit_set */ +#define APR_LIMIT_MEM 1 +/** @see apr_procattr_limit_set */ +#define APR_LIMIT_NPROC 2 +/** @see apr_procattr_limit_set */ +#define APR_LIMIT_NOFILE 3 + +/** + * @defgroup APR_OC Other Child Flags + * @{ + */ +#define APR_OC_REASON_DEATH 0 /**< child has died, caller must call + * unregister still */ +#define APR_OC_REASON_UNWRITABLE 1 /**< write_fd is unwritable */ +#define APR_OC_REASON_RESTART 2 /**< a restart is occurring, perform + * any necessary cleanup (including + * sending a special signal to child) + */ +#define APR_OC_REASON_UNREGISTER 3 /**< unregister has been called, do + * whatever is necessary (including + * kill the child) */ +#define APR_OC_REASON_LOST 4 /**< somehow the child exited without + * us knowing ... buggy os? */ +#define APR_OC_REASON_RUNNING 5 /**< a health check is occurring, + * for most maintainence functions + * this is a no-op. + */ +/** @} */ + +/** The APR process type */ +typedef struct apr_proc_t { + /** The process ID */ + pid_t pid; + /** Parent's side of pipe to child's stdin */ + apr_file_t *in; + /** Parent's side of pipe to child's stdout */ + apr_file_t *out; + /** Parent's side of pipe to child's stdouterr */ + apr_file_t *err; +#if APR_HAS_PROC_INVOKED || defined(DOXYGEN) + /** Diagnositics/debugging string of the command invoked for + * this process [only present if APR_HAS_PROC_INVOKED is true] + * @remark Only enabled on Win32 by default. + * @bug This should either always or never be present in release + * builds - since it breaks binary compatibility. We may enable + * it always in APR 1.0 yet leave it undefined in most cases. + */ + char *invoked; +#endif +#if defined(WIN32) || defined(DOXYGEN) + /** (Win32 only) Creator's handle granting access to the process + * @remark This handle is closed and reset to NULL in every case + * corresponding to a waitpid() on Unix which returns the exit status. + * Therefore Win32 correspond's to Unix's zombie reaping characteristics + * and avoids potential handle leaks. + */ + HANDLE hproc; +#endif +} apr_proc_t; + +/** + * The prototype for APR child errfn functions. (See the description + * of apr_procattr_child_errfn_set() for more information.) + * It is passed the following parameters: + * @param pool Pool associated with the apr_proc_t. If your child + * error function needs user data, associate it with this + * pool. + * @param err APR error code describing the error + * @param description Text description of type of processing which failed + */ +typedef void (apr_child_errfn_t)(apr_pool_t *proc, apr_status_t err, + const char *description); + +/** Opaque Thread structure. */ +typedef struct apr_thread_t apr_thread_t; + +/** Opaque Thread attributes structure. */ +typedef struct apr_threadattr_t apr_threadattr_t; + +/** Opaque Process attributes structure. */ +typedef struct apr_procattr_t apr_procattr_t; + +/** Opaque control variable for one-time atomic variables. */ +typedef struct apr_thread_once_t apr_thread_once_t; + +/** Opaque thread private address space. */ +typedef struct apr_threadkey_t apr_threadkey_t; + +/** Opaque record of child process. */ +typedef struct apr_other_child_rec_t apr_other_child_rec_t; + +/** + * The prototype for any APR thread worker functions. + */ +typedef void *(APR_THREAD_FUNC *apr_thread_start_t)(apr_thread_t*, void*); + +typedef enum { + APR_KILL_NEVER, /**< process is never killed (i.e., never sent + * any signals), but it will be reaped if it exits + * before the pool is cleaned up */ + APR_KILL_ALWAYS, /**< process is sent SIGKILL on apr_pool_t cleanup */ + APR_KILL_AFTER_TIMEOUT, /**< SIGTERM, wait 3 seconds, SIGKILL */ + APR_JUST_WAIT, /**< wait forever for the process to complete */ + APR_KILL_ONLY_ONCE /**< send SIGTERM and then wait */ +} apr_kill_conditions_e; + +/* Thread Function definitions */ + +#if APR_HAS_THREADS + +/** + * Create and initialize a new threadattr variable + * @param new_attr The newly created threadattr. + * @param cont The pool to use + */ +APR_DECLARE(apr_status_t) apr_threadattr_create(apr_threadattr_t **new_attr, + apr_pool_t *cont); + +/** + * Set if newly created threads should be created in detached state. + * @param attr The threadattr to affect + * @param on Non-zero if detached threads should be created. + */ +APR_DECLARE(apr_status_t) apr_threadattr_detach_set(apr_threadattr_t *attr, + apr_int32_t on); + +/** + * Get the detach state for this threadattr. + * @param attr The threadattr to reference + * @return APR_DETACH if threads are to be detached, or APR_NOTDETACH + * if threads are to be joinable. + */ +APR_DECLARE(apr_status_t) apr_threadattr_detach_get(apr_threadattr_t *attr); + +/** + * Set the stack size of newly created threads. + * @param attr The threadattr to affect + * @param stacksize The stack size in bytes + */ +APR_DECLARE(apr_status_t) apr_threadattr_stacksize_set(apr_threadattr_t *attr, + apr_size_t stacksize); + +/** + * Set the stack guard area size of newly created threads. + * @param attr The threadattr to affect + * @param guardsize The stack guard area size in bytes + * @note Thread library implementations commonly use a "guard area" + * after each thread's stack which is not readable or writable such that + * stack overflows cause a segfault; this consumes e.g. 4K of memory + * and increases memory management overhead. Setting the guard area + * size to zero hence trades off reliable behaviour on stack overflow + * for performance. */ +APR_DECLARE(apr_status_t) apr_threadattr_guardsize_set(apr_threadattr_t *attr, + apr_size_t guardsize); + +/** + * Create a new thread of execution + * @param new_thread The newly created thread handle. + * @param attr The threadattr to use to determine how to create the thread + * @param func The function to start the new thread in + * @param data Any data to be passed to the starting function + * @param cont The pool to use + */ +APR_DECLARE(apr_status_t) apr_thread_create(apr_thread_t **new_thread, + apr_threadattr_t *attr, + apr_thread_start_t func, + void *data, apr_pool_t *cont); + +/** + * stop the current thread + * @param thd The thread to stop + * @param retval The return value to pass back to any thread that cares + */ +APR_DECLARE(apr_status_t) apr_thread_exit(apr_thread_t *thd, + apr_status_t retval); + +/** + * block until the desired thread stops executing. + * @param retval The return value from the dead thread. + * @param thd The thread to join + */ +APR_DECLARE(apr_status_t) apr_thread_join(apr_status_t *retval, + apr_thread_t *thd); + +/** + * force the current thread to yield the processor + */ +APR_DECLARE(void) apr_thread_yield(void); + +/** + * Initialize the control variable for apr_thread_once. If this isn't + * called, apr_initialize won't work. + * @param control The control variable to initialize + * @param p The pool to allocate data from. + */ +APR_DECLARE(apr_status_t) apr_thread_once_init(apr_thread_once_t **control, + apr_pool_t *p); + +/** + * Run the specified function one time, regardless of how many threads + * call it. + * @param control The control variable. The same variable should + * be passed in each time the function is tried to be + * called. This is how the underlying functions determine + * if the function has ever been called before. + * @param func The function to call. + */ +APR_DECLARE(apr_status_t) apr_thread_once(apr_thread_once_t *control, + void (*func)(void)); + +/** + * detach a thread + * @param thd The thread to detach + */ +APR_DECLARE(apr_status_t) apr_thread_detach(apr_thread_t *thd); + +/** + * Return user data associated with the current thread. + * @param data The user data associated with the thread. + * @param key The key to associate with the data + * @param thread The currently open thread. + */ +APR_DECLARE(apr_status_t) apr_thread_data_get(void **data, const char *key, + apr_thread_t *thread); + +/** + * Set user data associated with the current thread. + * @param data The user data to associate with the thread. + * @param key The key to use for associating the data with the thread + * @param cleanup The cleanup routine to use when the thread is destroyed. + * @param thread The currently open thread. + */ +APR_DECLARE(apr_status_t) apr_thread_data_set(void *data, const char *key, + apr_status_t (*cleanup) (void *), + apr_thread_t *thread); + +/** + * Create and initialize a new thread private address space + * @param key The thread private handle. + * @param dest The destructor to use when freeing the private memory. + * @param cont The pool to use + */ +APR_DECLARE(apr_status_t) apr_threadkey_private_create(apr_threadkey_t **key, + void (*dest)(void *), + apr_pool_t *cont); + +/** + * Get a pointer to the thread private memory + * @param new_mem The data stored in private memory + * @param key The handle for the desired thread private memory + */ +APR_DECLARE(apr_status_t) apr_threadkey_private_get(void **new_mem, + apr_threadkey_t *key); + +/** + * Set the data to be stored in thread private memory + * @param priv The data to be stored in private memory + * @param key The handle for the desired thread private memory + */ +APR_DECLARE(apr_status_t) apr_threadkey_private_set(void *priv, + apr_threadkey_t *key); + +/** + * Free the thread private memory + * @param key The handle for the desired thread private memory + */ +APR_DECLARE(apr_status_t) apr_threadkey_private_delete(apr_threadkey_t *key); + +/** + * Return the pool associated with the current threadkey. + * @param data The user data associated with the threadkey. + * @param key The key associated with the data + * @param threadkey The currently open threadkey. + */ +APR_DECLARE(apr_status_t) apr_threadkey_data_get(void **data, const char *key, + apr_threadkey_t *threadkey); + +/** + * Return the pool associated with the current threadkey. + * @param data The data to set. + * @param key The key to associate with the data. + * @param cleanup The cleanup routine to use when the file is destroyed. + * @param threadkey The currently open threadkey. + */ +APR_DECLARE(apr_status_t) apr_threadkey_data_set(void *data, const char *key, + apr_status_t (*cleanup) (void *), + apr_threadkey_t *threadkey); + +#endif + +/** + * Create and initialize a new procattr variable + * @param new_attr The newly created procattr. + * @param cont The pool to use + */ +APR_DECLARE(apr_status_t) apr_procattr_create(apr_procattr_t **new_attr, + apr_pool_t *cont); + +/** + * Determine if any of stdin, stdout, or stderr should be linked to pipes + * when starting a child process. + * @param attr The procattr we care about. + * @param in Should stdin be a pipe back to the parent? + * @param out Should stdout be a pipe back to the parent? + * @param err Should stderr be a pipe back to the parent? + * @note If APR_NO_PIPE, there will be no special channel, the child + * inherits the parent's corresponding stdio stream. If APR_NO_FILE is + * specified, that corresponding stream is closed in the child (and will + * be INVALID_HANDLE_VALUE when inspected on Win32). This can have ugly + * side effects, as the next file opened in the child on Unix will fall + * into the stdio stream fd slot! + */ +APR_DECLARE(apr_status_t) apr_procattr_io_set(apr_procattr_t *attr, + apr_int32_t in, apr_int32_t out, + apr_int32_t err); + +/** + * Set the child_in and/or parent_in values to existing apr_file_t values. + * @param attr The procattr we care about. + * @param child_in apr_file_t value to use as child_in. Must be a valid file. + * @param parent_in apr_file_t value to use as parent_in. Must be a valid file. + * @remark This is NOT a required initializer function. This is + * useful if you have already opened a pipe (or multiple files) + * that you wish to use, perhaps persistently across multiple + * process invocations - such as a log file. You can save some + * extra function calls by not creating your own pipe since this + * creates one in the process space for you. + * @bug Note that calling this function with two NULL files on some platforms + * creates an APR_FULL_BLOCK pipe, but this behavior is neither portable nor + * is it supported. @see apr_procattr_io_set instead for simple pipes. + */ +APR_DECLARE(apr_status_t) apr_procattr_child_in_set(struct apr_procattr_t *attr, + apr_file_t *child_in, + apr_file_t *parent_in); + +/** + * Set the child_out and parent_out values to existing apr_file_t values. + * @param attr The procattr we care about. + * @param child_out apr_file_t value to use as child_out. Must be a valid file. + * @param parent_out apr_file_t value to use as parent_out. Must be a valid file. + * @remark This is NOT a required initializer function. This is + * useful if you have already opened a pipe (or multiple files) + * that you wish to use, perhaps persistently across multiple + * process invocations - such as a log file. + * @bug Note that calling this function with two NULL files on some platforms + * creates an APR_FULL_BLOCK pipe, but this behavior is neither portable nor + * is it supported. @see apr_procattr_io_set instead for simple pipes. + */ +APR_DECLARE(apr_status_t) apr_procattr_child_out_set(struct apr_procattr_t *attr, + apr_file_t *child_out, + apr_file_t *parent_out); + +/** + * Set the child_err and parent_err values to existing apr_file_t values. + * @param attr The procattr we care about. + * @param child_err apr_file_t value to use as child_err. Must be a valid file. + * @param parent_err apr_file_t value to use as parent_err. Must be a valid file. + * @remark This is NOT a required initializer function. This is + * useful if you have already opened a pipe (or multiple files) + * that you wish to use, perhaps persistently across multiple + * process invocations - such as a log file. + * @bug Note that calling this function with two NULL files on some platforms + * creates an APR_FULL_BLOCK pipe, but this behavior is neither portable nor + * is it supported. @see apr_procattr_io_set instead for simple pipes. + */ +APR_DECLARE(apr_status_t) apr_procattr_child_err_set(struct apr_procattr_t *attr, + apr_file_t *child_err, + apr_file_t *parent_err); + +/** + * Set which directory the child process should start executing in. + * @param attr The procattr we care about. + * @param dir Which dir to start in. By default, this is the same dir as + * the parent currently resides in, when the createprocess call + * is made. + */ +APR_DECLARE(apr_status_t) apr_procattr_dir_set(apr_procattr_t *attr, + const char *dir); + +/** + * Set what type of command the child process will call. + * @param attr The procattr we care about. + * @param cmd The type of command. One of: + *
+ *            APR_SHELLCMD     --  Anything that the shell can handle
+ *            APR_PROGRAM      --  Executable program   (default) 
+ *            APR_PROGRAM_ENV  --  Executable program, copy environment
+ *            APR_PROGRAM_PATH --  Executable program on PATH, copy env
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_procattr_cmdtype_set(apr_procattr_t *attr, + apr_cmdtype_e cmd); + +/** + * Determine if the child should start in detached state. + * @param attr The procattr we care about. + * @param detach Should the child start in detached state? Default is no. + */ +APR_DECLARE(apr_status_t) apr_procattr_detach_set(apr_procattr_t *attr, + apr_int32_t detach); + +#if APR_HAVE_STRUCT_RLIMIT +/** + * Set the Resource Utilization limits when starting a new process. + * @param attr The procattr we care about. + * @param what Which limit to set, one of: + *
+ *                 APR_LIMIT_CPU
+ *                 APR_LIMIT_MEM
+ *                 APR_LIMIT_NPROC
+ *                 APR_LIMIT_NOFILE
+ * 
+ * @param limit Value to set the limit to. + */ +APR_DECLARE(apr_status_t) apr_procattr_limit_set(apr_procattr_t *attr, + apr_int32_t what, + struct rlimit *limit); +#endif + +/** + * Specify an error function to be called in the child process if APR + * encounters an error in the child prior to running the specified program. + * @param attr The procattr describing the child process to be created. + * @param errfn The function to call in the child process. + * @remark At the present time, it will only be called from apr_proc_create() + * on platforms where fork() is used. It will never be called on other + * platforms, on those platforms apr_proc_create() will return the error + * in the parent process rather than invoke the callback in the now-forked + * child process. + */ +APR_DECLARE(apr_status_t) apr_procattr_child_errfn_set(apr_procattr_t *attr, + apr_child_errfn_t *errfn); + +/** + * Specify that apr_proc_create() should do whatever it can to report + * failures to the caller of apr_proc_create(), rather than find out in + * the child. + * @param attr The procattr describing the child process to be created. + * @param chk Flag to indicate whether or not extra work should be done + * to try to report failures to the caller. + * @remark This flag only affects apr_proc_create() on platforms where + * fork() is used. This leads to extra overhead in the calling + * process, but that may help the application handle such + * errors more gracefully. + */ +APR_DECLARE(apr_status_t) apr_procattr_error_check_set(apr_procattr_t *attr, + apr_int32_t chk); + +/** + * Determine if the child should start in its own address space or using the + * current one from its parent + * @param attr The procattr we care about. + * @param addrspace Should the child start in its own address space? Default + * is no on NetWare and yes on other platforms. + */ +APR_DECLARE(apr_status_t) apr_procattr_addrspace_set(apr_procattr_t *attr, + apr_int32_t addrspace); + +/** + * Set the username used for running process + * @param attr The procattr we care about. + * @param username The username used + * @param password User password if needed. Password is needed on WIN32 + * or any other platform having + * APR_PROCATTR_USER_SET_REQUIRES_PASSWORD set. + */ +APR_DECLARE(apr_status_t) apr_procattr_user_set(apr_procattr_t *attr, + const char *username, + const char *password); + +/** + * Set the group used for running process + * @param attr The procattr we care about. + * @param groupname The group name used + */ +APR_DECLARE(apr_status_t) apr_procattr_group_set(apr_procattr_t *attr, + const char *groupname); + + +/** + * Register permission set function + * @param attr The procattr we care about. + * @param perms_set_fn Permission set callback + * @param data Data to pass to permission callback function + * @param perms Permissions to set + */ +APR_DECLARE(apr_status_t) apr_procattr_perms_set_register(apr_procattr_t *attr, + apr_perms_setfn_t *perms_set_fn, + void *data, + apr_fileperms_t perms); + +#if APR_HAS_FORK +/** + * This is currently the only non-portable call in APR. This executes + * a standard unix fork. + * @param proc The resulting process handle. + * @param cont The pool to use. + * @remark returns APR_INCHILD for the child, and APR_INPARENT for the parent + * or an error. + */ +APR_DECLARE(apr_status_t) apr_proc_fork(apr_proc_t *proc, apr_pool_t *cont); +#endif + +/** + * Create a new process and execute a new program within that process. + * @param new_proc The resulting process handle. + * @param progname The program to run + * @param args the arguments to pass to the new program. The first + * one should be the program name. + * @param env The new environment table for the new process. This + * should be a list of NULL-terminated strings. This argument + * is ignored for APR_PROGRAM_ENV, APR_PROGRAM_PATH, and + * APR_SHELLCMD_ENV types of commands. + * @param attr the procattr we should use to determine how to create the new + * process + * @param pool The pool to use. + * @note This function returns without waiting for the new process to terminate; + * use apr_proc_wait for that. + */ +APR_DECLARE(apr_status_t) apr_proc_create(apr_proc_t *new_proc, + const char *progname, + const char * const *args, + const char * const *env, + apr_procattr_t *attr, + apr_pool_t *pool); + +/** + * Wait for a child process to die + * @param proc The process handle that corresponds to the desired child process + * @param exitcode The returned exit status of the child, if a child process + * dies, or the signal that caused the child to die. + * On platforms that don't support obtaining this information, + * the status parameter will be returned as APR_ENOTIMPL. + * @param exitwhy Why the child died, the bitwise or of: + *
+ *            APR_PROC_EXIT         -- process terminated normally
+ *            APR_PROC_SIGNAL       -- process was killed by a signal
+ *            APR_PROC_SIGNAL_CORE  -- process was killed by a signal, and
+ *                                     generated a core dump.
+ * 
+ * @param waithow How should we wait. One of: + *
+ *            APR_WAIT   -- block until the child process dies.
+ *            APR_NOWAIT -- return immediately regardless of if the 
+ *                          child is dead or not.
+ * 
+ * @remark The child's status is in the return code to this process. It is one of: + *
+ *            APR_CHILD_DONE     -- child is no longer running.
+ *            APR_CHILD_NOTDONE  -- child is still running.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_proc_wait(apr_proc_t *proc, + int *exitcode, apr_exit_why_e *exitwhy, + apr_wait_how_e waithow); + +/** + * Wait for any current child process to die and return information + * about that child. + * @param proc Pointer to NULL on entry, will be filled out with child's + * information + * @param exitcode The returned exit status of the child, if a child process + * dies, or the signal that caused the child to die. + * On platforms that don't support obtaining this information, + * the status parameter will be returned as APR_ENOTIMPL. + * @param exitwhy Why the child died, the bitwise or of: + *
+ *            APR_PROC_EXIT         -- process terminated normally
+ *            APR_PROC_SIGNAL       -- process was killed by a signal
+ *            APR_PROC_SIGNAL_CORE  -- process was killed by a signal, and
+ *                                     generated a core dump.
+ * 
+ * @param waithow How should we wait. One of: + *
+ *            APR_WAIT   -- block until the child process dies.
+ *            APR_NOWAIT -- return immediately regardless of if the 
+ *                          child is dead or not.
+ * 
+ * @param p Pool to allocate child information out of. + * @bug Passing proc as a *proc rather than **proc was an odd choice + * for some platforms... this should be revisited in 1.0 + */ +APR_DECLARE(apr_status_t) apr_proc_wait_all_procs(apr_proc_t *proc, + int *exitcode, + apr_exit_why_e *exitwhy, + apr_wait_how_e waithow, + apr_pool_t *p); + +#define APR_PROC_DETACH_FOREGROUND 0 /**< Do not detach */ +#define APR_PROC_DETACH_DAEMONIZE 1 /**< Detach */ + +/** + * Detach the process from the controlling terminal. + * @param daemonize set to non-zero if the process should daemonize + * and become a background process, else it will + * stay in the foreground. + */ +APR_DECLARE(apr_status_t) apr_proc_detach(int daemonize); + +/** + * Register an other_child -- a child associated to its registered + * maintence callback. This callback is invoked when the process + * dies, is disconnected or disappears. + * @param proc The child process to register. + * @param maintenance maintenance is a function that is invoked with a + * reason and the data pointer passed here. + * @param data Opaque context data passed to the maintenance function. + * @param write_fd An fd that is probed for writing. If it is ever unwritable + * then the maintenance is invoked with reason + * OC_REASON_UNWRITABLE. + * @param p The pool to use for allocating memory. + * @bug write_fd duplicates the proc->out stream, it's really redundant + * and should be replaced in the APR 1.0 API with a bitflag of which + * proc->in/out/err handles should be health checked. + * @bug no platform currently tests the pipes health. + */ +APR_DECLARE(void) apr_proc_other_child_register(apr_proc_t *proc, + void (*maintenance) (int reason, + void *, + int status), + void *data, apr_file_t *write_fd, + apr_pool_t *p); + +/** + * Stop watching the specified other child. + * @param data The data to pass to the maintenance function. This is + * used to find the process to unregister. + * @warning Since this can be called by a maintenance function while we're + * scanning the other_children list, all scanners should protect + * themself by loading ocr->next before calling any maintenance + * function. + */ +APR_DECLARE(void) apr_proc_other_child_unregister(void *data); + +/** + * Notify the maintenance callback of a registered other child process + * that application has detected an event, such as death. + * @param proc The process to check + * @param reason The reason code to pass to the maintenance function + * @param status The status to pass to the maintenance function + * @remark An example of code using this behavior; + *
+ * rv = apr_proc_wait_all_procs(&proc, &exitcode, &status, APR_WAIT, p);
+ * if (APR_STATUS_IS_CHILD_DONE(rv)) {
+ * \#if APR_HAS_OTHER_CHILD
+ *     if (apr_proc_other_child_alert(&proc, APR_OC_REASON_DEATH, status)
+ *             == APR_SUCCESS) {
+ *         ;  (already handled)
+ *     }
+ *     else
+ * \#endif
+ *         [... handling non-otherchild processes death ...]
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_proc_other_child_alert(apr_proc_t *proc, + int reason, + int status); + +/** + * Test one specific other child processes and invoke the maintenance callback + * with the appropriate reason code, if still running, or the appropriate reason + * code if the process is no longer healthy. + * @param ocr The registered other child + * @param reason The reason code (e.g. APR_OC_REASON_RESTART) if still running + */ +APR_DECLARE(void) apr_proc_other_child_refresh(apr_other_child_rec_t *ocr, + int reason); + +/** + * Test all registered other child processes and invoke the maintenance callback + * with the appropriate reason code, if still running, or the appropriate reason + * code if the process is no longer healthy. + * @param reason The reason code (e.g. APR_OC_REASON_RESTART) to running processes + */ +APR_DECLARE(void) apr_proc_other_child_refresh_all(int reason); + +/** + * Terminate a process. + * @param proc The process to terminate. + * @param sig How to kill the process. + */ +APR_DECLARE(apr_status_t) apr_proc_kill(apr_proc_t *proc, int sig); + +/** + * Register a process to be killed when a pool dies. + * @param a The pool to use to define the processes lifetime + * @param proc The process to register + * @param how How to kill the process, one of: + *
+ *         APR_KILL_NEVER         -- process is never sent any signals
+ *         APR_KILL_ALWAYS        -- process is sent SIGKILL on apr_pool_t cleanup
+ *         APR_KILL_AFTER_TIMEOUT -- SIGTERM, wait 3 seconds, SIGKILL
+ *         APR_JUST_WAIT          -- wait forever for the process to complete
+ *         APR_KILL_ONLY_ONCE     -- send SIGTERM and then wait
+ * 
+ */ +APR_DECLARE(void) apr_pool_note_subprocess(apr_pool_t *a, apr_proc_t *proc, + apr_kill_conditions_e how); + +#if APR_HAS_THREADS + +#if (APR_HAVE_SIGWAIT || APR_HAVE_SIGSUSPEND) && !defined(OS2) + +/** + * Setup the process for a single thread to be used for all signal handling. + * @warning This must be called before any threads are created + */ +APR_DECLARE(apr_status_t) apr_setup_signal_thread(void); + +/** + * Make the current thread listen for signals. This thread will loop + * forever, calling a provided function whenever it receives a signal. That + * functions should return 1 if the signal has been handled, 0 otherwise. + * @param signal_handler The function to call when a signal is received + * apr_status_t apr_signal_thread((int)(*signal_handler)(int signum)) + * @note Synchronous signals like SIGABRT/SIGSEGV/SIGBUS/... are ignored by + * apr_signal_thread() and thus can't be waited by this function (they remain + * handled by the operating system or its native signals interface). + * @remark In APR version 1.6 and ealier, SIGUSR2 was part of these ignored + * signals and thus was never passed in to the signal_handler. From APR 1.7 + * this is no more the case so SIGUSR2 can be handled in signal_handler and + * acted upon like the other asynchronous signals. + */ +APR_DECLARE(apr_status_t) apr_signal_thread(int(*signal_handler)(int signum)); + +#endif /* (APR_HAVE_SIGWAIT || APR_HAVE_SIGSUSPEND) && !defined(OS2) */ + +/** + * Get the child-pool used by the thread from the thread info. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(thread); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_THREAD_PROC_H */ + diff --git a/c/dependencies/macos/apr/include/apr_thread_rwlock.h b/c/dependencies/macos/apr/include/apr_thread_rwlock.h new file mode 100644 index 00000000..0bd958fb --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_thread_rwlock.h @@ -0,0 +1,129 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_THREAD_RWLOCK_H +#define APR_THREAD_RWLOCK_H + +/** + * @file apr_thread_rwlock.h + * @brief APR Reader/Writer Lock Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#if APR_HAS_THREADS + +/** + * @defgroup apr_thread_rwlock Reader/Writer Lock Routines + * @ingroup APR + * @{ + */ + +/** Opaque read-write thread-safe lock. */ +typedef struct apr_thread_rwlock_t apr_thread_rwlock_t; + +/** + * Note: The following operations have undefined results: unlocking a + * read-write lock which is not locked in the calling thread; write + * locking a read-write lock which is already locked by the calling + * thread; destroying a read-write lock more than once; clearing or + * destroying the pool from which a locked read-write lock is + * allocated. + */ + +/** + * Create and initialize a read-write lock that can be used to synchronize + * threads. + * @param rwlock the memory address where the newly created readwrite lock + * will be stored. + * @param pool the pool from which to allocate the mutex. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_create(apr_thread_rwlock_t **rwlock, + apr_pool_t *pool); +/** + * Acquire a shared-read lock on the given read-write lock. This will allow + * multiple threads to enter the same critical section while they have acquired + * the read lock. + * @param rwlock the read-write lock on which to acquire the shared read. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_rdlock(apr_thread_rwlock_t *rwlock); + +/** + * Attempt to acquire the shared-read lock on the given read-write lock. This + * is the same as apr_thread_rwlock_rdlock(), only that the function fails + * if there is another thread holding the write lock, or if there are any + * write threads blocking on the lock. If the function fails for this case, + * APR_EBUSY will be returned. Note: it is important that the + * APR_STATUS_IS_EBUSY(s) macro be used to determine if the return value was + * APR_EBUSY, for portability reasons. + * @param rwlock the rwlock on which to attempt the shared read. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_tryrdlock(apr_thread_rwlock_t *rwlock); + +/** + * Acquire an exclusive-write lock on the given read-write lock. This will + * allow only one single thread to enter the critical sections. If there + * are any threads currently holding the read-lock, this thread is put to + * sleep until it can have exclusive access to the lock. + * @param rwlock the read-write lock on which to acquire the exclusive write. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_wrlock(apr_thread_rwlock_t *rwlock); + +/** + * Attempt to acquire the exclusive-write lock on the given read-write lock. + * This is the same as apr_thread_rwlock_wrlock(), only that the function fails + * if there is any other thread holding the lock (for reading or writing), + * in which case the function will return APR_EBUSY. Note: it is important + * that the APR_STATUS_IS_EBUSY(s) macro be used to determine if the return + * value was APR_EBUSY, for portability reasons. + * @param rwlock the rwlock on which to attempt the exclusive write. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_trywrlock(apr_thread_rwlock_t *rwlock); + +/** + * Release either the read or write lock currently held by the calling thread + * associated with the given read-write lock. + * @param rwlock the read-write lock to be released (unlocked). + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_unlock(apr_thread_rwlock_t *rwlock); + +/** + * Destroy the read-write lock and free the associated memory. + * @param rwlock the rwlock to destroy. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_destroy(apr_thread_rwlock_t *rwlock); + +/** + * Get the pool used by this thread_rwlock. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(thread_rwlock); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_THREAD_RWLOCK_H */ diff --git a/c/dependencies/macos/apr/include/apr_time.h b/c/dependencies/macos/apr/include/apr_time.h new file mode 100644 index 00000000..b0efd791 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_time.h @@ -0,0 +1,237 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_TIME_H +#define APR_TIME_H + +/** + * @file apr_time.h + * @brief APR Time Library + */ + +#include "apr.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_time Time Routines + * @ingroup APR + * @{ + */ + +/** month names */ +APR_DECLARE_DATA extern const char apr_month_snames[12][4]; +/** day names */ +APR_DECLARE_DATA extern const char apr_day_snames[7][4]; + + +/** number of microseconds since 00:00:00 January 1, 1970 UTC */ +typedef apr_int64_t apr_time_t; + + +/** mechanism to properly type apr_time_t literals */ +#define APR_TIME_C(val) APR_INT64_C(val) + +/** mechanism to properly print apr_time_t values */ +#define APR_TIME_T_FMT APR_INT64_T_FMT + +/** intervals for I/O timeouts, in microseconds */ +typedef apr_int64_t apr_interval_time_t; +/** short interval for I/O timeouts, in microseconds */ +typedef apr_int32_t apr_short_interval_time_t; + +/** number of microseconds per second */ +#define APR_USEC_PER_SEC APR_TIME_C(1000000) + +/** @return apr_time_t as a second */ +#define apr_time_sec(time) ((time) / APR_USEC_PER_SEC) + +/** @return apr_time_t as a usec */ +#define apr_time_usec(time) ((time) % APR_USEC_PER_SEC) + +/** @return apr_time_t as a msec */ +#define apr_time_msec(time) (((time) / 1000) % 1000) + +/** @return apr_time_t as a msec */ +#define apr_time_as_msec(time) ((time) / 1000) + +/** @return milliseconds as an apr_time_t */ +#define apr_time_from_msec(msec) ((apr_time_t)(msec) * 1000) + +/** @return seconds as an apr_time_t */ +#define apr_time_from_sec(sec) ((apr_time_t)(sec) * APR_USEC_PER_SEC) + +/** @return a second and usec combination as an apr_time_t */ +#define apr_time_make(sec, usec) ((apr_time_t)(sec) * APR_USEC_PER_SEC \ + + (apr_time_t)(usec)) + +/** + * @return the current time + */ +APR_DECLARE(apr_time_t) apr_time_now(void); + +/** @see apr_time_exp_t */ +typedef struct apr_time_exp_t apr_time_exp_t; + +/** + * a structure similar to ANSI struct tm with the following differences: + * - tm_usec isn't an ANSI field + * - tm_gmtoff isn't an ANSI field (it's a BSDism) + */ +struct apr_time_exp_t { + /** microseconds past tm_sec */ + apr_int32_t tm_usec; + /** (0-61) seconds past tm_min */ + apr_int32_t tm_sec; + /** (0-59) minutes past tm_hour */ + apr_int32_t tm_min; + /** (0-23) hours past midnight */ + apr_int32_t tm_hour; + /** (1-31) day of the month */ + apr_int32_t tm_mday; + /** (0-11) month of the year */ + apr_int32_t tm_mon; + /** year since 1900 */ + apr_int32_t tm_year; + /** (0-6) days since Sunday */ + apr_int32_t tm_wday; + /** (0-365) days since January 1 */ + apr_int32_t tm_yday; + /** daylight saving time */ + apr_int32_t tm_isdst; + /** seconds east of UTC */ + apr_int32_t tm_gmtoff; +}; + +/* Delayed the include to avoid a circular reference */ +#include "apr_pools.h" + +/** + * Convert an ansi time_t to an apr_time_t + * @param result the resulting apr_time_t + * @param input the time_t to convert + */ +APR_DECLARE(apr_status_t) apr_time_ansi_put(apr_time_t *result, + time_t input); + +/** + * Convert a time to its human readable components using an offset + * from GMT. + * @param result the exploded time + * @param input the time to explode + * @param offs the number of seconds offset to apply + */ +APR_DECLARE(apr_status_t) apr_time_exp_tz(apr_time_exp_t *result, + apr_time_t input, + apr_int32_t offs); + +/** + * Convert a time to its human readable components (GMT). + * @param result the exploded time + * @param input the time to explode + */ +APR_DECLARE(apr_status_t) apr_time_exp_gmt(apr_time_exp_t *result, + apr_time_t input); + +/** + * Convert a time to its human readable components in the local timezone. + * @param result the exploded time + * @param input the time to explode + */ +APR_DECLARE(apr_status_t) apr_time_exp_lt(apr_time_exp_t *result, + apr_time_t input); + +/** + * Convert time value from human readable format to a numeric apr_time_t + * (elapsed microseconds since the epoch). + * @param result the resulting imploded time + * @param input the input exploded time + */ +APR_DECLARE(apr_status_t) apr_time_exp_get(apr_time_t *result, + apr_time_exp_t *input); + +/** + * Convert time value from human readable format to a numeric apr_time_t that + * always represents GMT. + * @param result the resulting imploded time + * @param input the input exploded time + */ +APR_DECLARE(apr_status_t) apr_time_exp_gmt_get(apr_time_t *result, + apr_time_exp_t *input); + +/** + * Sleep for the specified number of micro-seconds. + * @param t desired amount of time to sleep. + * @warning May sleep for longer than the specified time. + */ +APR_DECLARE(void) apr_sleep(apr_interval_time_t t); + +/** length of a RFC822 Date */ +#define APR_RFC822_DATE_LEN (30) +/** + * apr_rfc822_date formats dates in the RFC822 + * format in an efficient manner. It is a fixed length + * format which requires APR_RFC822_DATA_LEN bytes of storage, + * including the trailing NUL terminator. + * @param date_str String to write to. + * @param t the time to convert + */ +APR_DECLARE(apr_status_t) apr_rfc822_date(char *date_str, apr_time_t t); + +/** length of a CTIME date */ +#define APR_CTIME_LEN (25) +/** + * apr_ctime formats dates in the ctime() format + * in an efficient manner. It is a fixed length format + * and requires APR_CTIME_LEN bytes of storage including + * the trailing NUL terminator. + * Unlike ANSI/ISO C ctime(), apr_ctime() does not include + * a \\n at the end of the string. + * @param date_str String to write to. + * @param t the time to convert + */ +APR_DECLARE(apr_status_t) apr_ctime(char *date_str, apr_time_t t); + +/** + * Formats the exploded time according to the format specified + * @param s string to write to + * @param retsize The length of the returned string + * @param max The maximum length of the string + * @param format The format for the time string + * @param tm The time to convert + */ +APR_DECLARE(apr_status_t) apr_strftime(char *s, apr_size_t *retsize, + apr_size_t max, const char *format, + apr_time_exp_t *tm); + +/** + * Improve the clock resolution for the lifetime of the given pool. + * Generally this is only desirable on benchmarking and other very + * time-sensitive applications, and has no impact on most platforms. + * @param p The pool to associate the finer clock resolution + */ +APR_DECLARE(void) apr_time_clock_hires(apr_pool_t *p); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_TIME_H */ diff --git a/c/dependencies/macos/apr/include/apr_uri.h b/c/dependencies/macos/apr/include/apr_uri.h new file mode 100644 index 00000000..02908a9d --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_uri.h @@ -0,0 +1,178 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_uri.h: External Interface of apr_uri.c + */ + +/** + * @file apr_uri.h + * @brief APR-UTIL URI Routines + */ + +#ifndef APR_URI_H +#define APR_URI_H + +#include "apu.h" + +#include "apr_network_io.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_URI URI + * @ingroup APR_Util + * @{ + */ + +#define APR_URI_FTP_DEFAULT_PORT 21 /**< default FTP port */ +#define APR_URI_SSH_DEFAULT_PORT 22 /**< default SSH port */ +#define APR_URI_TELNET_DEFAULT_PORT 23 /**< default telnet port */ +#define APR_URI_GOPHER_DEFAULT_PORT 70 /**< default Gopher port */ +#define APR_URI_HTTP_DEFAULT_PORT 80 /**< default HTTP port */ +#define APR_URI_POP_DEFAULT_PORT 110 /**< default POP port */ +#define APR_URI_NNTP_DEFAULT_PORT 119 /**< default NNTP port */ +#define APR_URI_IMAP_DEFAULT_PORT 143 /**< default IMAP port */ +#define APR_URI_PROSPERO_DEFAULT_PORT 191 /**< default Prospero port */ +#define APR_URI_WAIS_DEFAULT_PORT 210 /**< default WAIS port */ +#define APR_URI_LDAP_DEFAULT_PORT 389 /**< default LDAP port */ +#define APR_URI_HTTPS_DEFAULT_PORT 443 /**< default HTTPS port */ +#define APR_URI_RTSP_DEFAULT_PORT 554 /**< default RTSP port */ +#define APR_URI_SNEWS_DEFAULT_PORT 563 /**< default SNEWS port */ +#define APR_URI_ACAP_DEFAULT_PORT 674 /**< default ACAP port */ +#define APR_URI_NFS_DEFAULT_PORT 2049 /**< default NFS port */ +#define APR_URI_TIP_DEFAULT_PORT 3372 /**< default TIP port */ +#define APR_URI_SIP_DEFAULT_PORT 5060 /**< default SIP port */ + +/** Flags passed to unparse_uri_components(): */ +/** suppress "scheme://user\@site:port" */ +#define APR_URI_UNP_OMITSITEPART (1U<<0) +/** Just omit user */ +#define APR_URI_UNP_OMITUSER (1U<<1) +/** Just omit password */ +#define APR_URI_UNP_OMITPASSWORD (1U<<2) +/** omit "user:password\@" part */ +#define APR_URI_UNP_OMITUSERINFO (APR_URI_UNP_OMITUSER | \ + APR_URI_UNP_OMITPASSWORD) +/** Show plain text password (default: show XXXXXXXX) */ +#define APR_URI_UNP_REVEALPASSWORD (1U<<3) +/** Show "scheme://user\@site:port" only */ +#define APR_URI_UNP_OMITPATHINFO (1U<<4) +/** Omit the "?queryarg" from the path */ +#define APR_URI_UNP_OMITQUERY (1U<<5) + +/** @see apr_uri_t */ +typedef struct apr_uri_t apr_uri_t; + +/** + * A structure to encompass all of the fields in a uri + */ +struct apr_uri_t { + /** scheme ("http"/"ftp"/...) */ + char *scheme; + /** combined [user[:password]\@]host[:port] */ + char *hostinfo; + /** user name, as in http://user:passwd\@host:port/ */ + char *user; + /** password, as in http://user:passwd\@host:port/ */ + char *password; + /** hostname from URI (or from Host: header) */ + char *hostname; + /** port string (integer representation is in "port") */ + char *port_str; + /** the request path (or NULL if only scheme://host was given) */ + char *path; + /** Everything after a '?' in the path, if present */ + char *query; + /** Trailing "#fragment" string, if present */ + char *fragment; + + /** structure returned from gethostbyname() */ + struct hostent *hostent; + + /** The port number, numeric, valid only if port_str != NULL */ + apr_port_t port; + + /** has the structure been initialized */ + unsigned is_initialized:1; + + /** has the DNS been looked up yet */ + unsigned dns_looked_up:1; + /** has the dns been resolved yet */ + unsigned dns_resolved:1; +}; + +/* apr_uri.c */ +/** + * Return the default port for a given scheme. The schemes recognized are + * http, ftp, https, gopher, wais, nntp, snews, and prospero + * @param scheme_str The string that contains the current scheme + * @return The default port for this scheme + */ +APU_DECLARE(apr_port_t) apr_uri_port_of_scheme(const char *scheme_str); + +/** + * Unparse a apr_uri_t structure to an URI string. Optionally + * suppress the password for security reasons. + * @param p The pool to allocate out of + * @param uptr All of the parts of the uri + * @param flags How to unparse the uri. One of: + *
+ *    APR_URI_UNP_OMITSITEPART        Suppress "scheme://user\@site:port" 
+ *    APR_URI_UNP_OMITUSER            Just omit user 
+ *    APR_URI_UNP_OMITPASSWORD        Just omit password 
+ *    APR_URI_UNP_OMITUSERINFO        Omit "user:password\@" part
+ *    APR_URI_UNP_REVEALPASSWORD      Show plain text password (default: show XXXXXXXX)
+ *    APR_URI_UNP_OMITPATHINFO        Show "scheme://user\@site:port" only 
+ *    APR_URI_UNP_OMITQUERY           Omit "?queryarg" or "#fragment" 
+ * 
+ * @return The uri as a string + */ +APU_DECLARE(char *) apr_uri_unparse(apr_pool_t *p, + const apr_uri_t *uptr, + unsigned flags); + +/** + * Parse a given URI, fill in all supplied fields of a apr_uri_t + * structure. This eliminates the necessity of extracting host, port, + * path, query info repeatedly in the modules. + * @param p The pool to allocate out of + * @param uri The uri to parse + * @param uptr The apr_uri_t to fill out + * @return APR_SUCCESS for success or error code + */ +APU_DECLARE(apr_status_t) apr_uri_parse(apr_pool_t *p, const char *uri, + apr_uri_t *uptr); + +/** + * Special case for CONNECT parsing: it comes with the hostinfo part only + * @param p The pool to allocate out of + * @param hostinfo The hostinfo string to parse + * @param uptr The apr_uri_t to fill out + * @return APR_SUCCESS for success or error code + */ +APU_DECLARE(apr_status_t) apr_uri_parse_hostinfo(apr_pool_t *p, + const char *hostinfo, + apr_uri_t *uptr); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_URI_H */ diff --git a/c/dependencies/macos/apr/include/apr_user.h b/c/dependencies/macos/apr/include/apr_user.h new file mode 100644 index 00000000..0e0a3ac5 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_user.h @@ -0,0 +1,158 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_USER_H +#define APR_USER_H + +/** + * @file apr_user.h + * @brief APR User ID Services + */ + +#include "apr.h" +#include "apr_errno.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_user User and Group ID Services + * @ingroup APR + * @{ + */ + +/** + * Structure for determining user ownership. + */ +#ifdef WIN32 +typedef PSID apr_uid_t; +#else +typedef uid_t apr_uid_t; +#endif + +/** + * Structure for determining group ownership. + */ +#ifdef WIN32 +typedef PSID apr_gid_t; +#else +typedef gid_t apr_gid_t; +#endif + +#if APR_HAS_USER + +/** + * Get the userid (and groupid) of the calling process + * @param userid Returns the user id + * @param groupid Returns the user's group id + * @param p The pool from which to allocate working space + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_uid_current(apr_uid_t *userid, + apr_gid_t *groupid, + apr_pool_t *p); + +/** + * Get the user name for a specified userid + * @param username Pointer to new string containing user name (on output) + * @param userid The userid + * @param p The pool from which to allocate the string + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_uid_name_get(char **username, apr_uid_t userid, + apr_pool_t *p); + +/** + * Get the userid (and groupid) for the specified username + * @param userid Returns the user id + * @param groupid Returns the user's group id + * @param username The username to look up + * @param p The pool from which to allocate working space + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_uid_get(apr_uid_t *userid, apr_gid_t *groupid, + const char *username, apr_pool_t *p); + +/** + * Get the home directory for the named user + * @param dirname Pointer to new string containing directory name (on output) + * @param username The named user + * @param p The pool from which to allocate the string + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_uid_homepath_get(char **dirname, + const char *username, + apr_pool_t *p); + +/** + * Compare two user identifiers for equality. + * @param left One uid to test + * @param right Another uid to test + * @return APR_SUCCESS if the apr_uid_t structures identify the same user, + * APR_EMISMATCH if not, APR_BADARG if an apr_uid_t is invalid. + * @remark This function is available only if APR_HAS_USER is defined. + */ +#if defined(WIN32) +APR_DECLARE(apr_status_t) apr_uid_compare(apr_uid_t left, apr_uid_t right); +#else +#define apr_uid_compare(left,right) (((left) == (right)) ? APR_SUCCESS : APR_EMISMATCH) +#endif + +/** + * Get the group name for a specified groupid + * @param groupname Pointer to new string containing group name (on output) + * @param groupid The groupid + * @param p The pool from which to allocate the string + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_gid_name_get(char **groupname, + apr_gid_t groupid, apr_pool_t *p); + +/** + * Get the groupid for a specified group name + * @param groupid Pointer to the group id (on output) + * @param groupname The group name to look up + * @param p The pool from which to allocate the string + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_gid_get(apr_gid_t *groupid, + const char *groupname, apr_pool_t *p); + +/** + * Compare two group identifiers for equality. + * @param left One gid to test + * @param right Another gid to test + * @return APR_SUCCESS if the apr_gid_t structures identify the same group, + * APR_EMISMATCH if not, APR_BADARG if an apr_gid_t is invalid. + * @remark This function is available only if APR_HAS_USER is defined. + */ +#if defined(WIN32) +APR_DECLARE(apr_status_t) apr_gid_compare(apr_gid_t left, apr_gid_t right); +#else +#define apr_gid_compare(left,right) (((left) == (right)) ? APR_SUCCESS : APR_EMISMATCH) +#endif + +#endif /* ! APR_HAS_USER */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_USER_H */ diff --git a/c/dependencies/macos/apr/include/apr_uuid.h b/c/dependencies/macos/apr/include/apr_uuid.h new file mode 100644 index 00000000..5312a9f6 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_uuid.h @@ -0,0 +1,76 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_uuid.h + * @brief APR UUID library + */ +#ifndef APR_UUID_H +#define APR_UUID_H + +#include "apu.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_UUID UUID Handling + * @ingroup APR + * @{ + */ + +/** + * we represent a UUID as a block of 16 bytes. + */ + +typedef struct { + unsigned char data[16]; /**< the actual UUID */ +} apr_uuid_t; + +/** UUIDs are formatted as: 00112233-4455-6677-8899-AABBCCDDEEFF */ +#define APR_UUID_FORMATTED_LENGTH 36 + + +/** + * Generate and return a (new) UUID + * @param uuid The resulting UUID + */ +APU_DECLARE(void) apr_uuid_get(apr_uuid_t *uuid); + +/** + * Format a UUID into a string, following the standard format + * @param buffer The buffer to place the formatted UUID string into. It must + * be at least APR_UUID_FORMATTED_LENGTH + 1 bytes long to hold + * the formatted UUID and a null terminator + * @param uuid The UUID to format + */ +APU_DECLARE(void) apr_uuid_format(char *buffer, const apr_uuid_t *uuid); + +/** + * Parse a standard-format string into a UUID + * @param uuid The resulting UUID + * @param uuid_str The formatted UUID + */ +APU_DECLARE(apr_status_t) apr_uuid_parse(apr_uuid_t *uuid, const char *uuid_str); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_UUID_H */ diff --git a/c/dependencies/macos/apr/include/apr_version.h b/c/dependencies/macos/apr/include/apr_version.h new file mode 100644 index 00000000..4883007f --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_version.h @@ -0,0 +1,164 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_VERSION_H +#define APR_VERSION_H + +/** + * @file apr_version.h + * @brief APR Versioning Interface + * + * APR's Version + * + * There are several different mechanisms for accessing the version. There + * is a string form, and a set of numbers; in addition, there are constants + * which can be compiled into your application, and you can query the library + * being used for its actual version. + * + * Note that it is possible for an application to detect that it has been + * compiled against a different version of APR by use of the compile-time + * constants and the use of the run-time query function. + * + * APR version numbering follows the guidelines specified in: + * + * http://apr.apache.org/versioning.html + */ + + +#define APR_COPYRIGHT "Copyright (c) 2000-2023 The Apache Software " \ + "Foundation or its licensors, as applicable." + +/* The numeric compile-time version constants. These constants are the + * authoritative version numbers for APR. + */ + +/** major version + * Major API changes that could cause compatibility problems for older + * programs such as structure size changes. No binary compatibility is + * possible across a change in the major version. + */ +#define APR_MAJOR_VERSION 1 + +/** minor version + * Minor API changes that do not cause binary compatibility problems. + * Reset to 0 when upgrading APR_MAJOR_VERSION + */ +#define APR_MINOR_VERSION 7 + +/** patch level + * The Patch Level never includes API changes, simply bug fixes. + * Reset to 0 when upgrading APR_MINOR_VERSION + */ +#define APR_PATCH_VERSION 4 + +/** + * The symbol APR_IS_DEV_VERSION is only defined for internal, + * "development" copies of APR. It is undefined for released versions + * of APR. + */ +/* #undef APR_IS_DEV_VERSION */ + +/** + * Check at compile time if the APR version is at least a certain + * level. + * @param major The major version component of the version checked + * for (e.g., the "1" of "1.3.0"). + * @param minor The minor version component of the version checked + * for (e.g., the "3" of "1.3.0"). + * @param patch The patch level component of the version checked + * for (e.g., the "0" of "1.3.0"). + * @remark This macro is available with APR versions starting with + * 1.3.0. + */ +#define APR_VERSION_AT_LEAST(major,minor,patch) \ +(((major) < APR_MAJOR_VERSION) \ + || ((major) == APR_MAJOR_VERSION && (minor) < APR_MINOR_VERSION) \ + || ((major) == APR_MAJOR_VERSION && (minor) == APR_MINOR_VERSION && (patch) <= APR_PATCH_VERSION)) + +#if defined(APR_IS_DEV_VERSION) || defined(DOXYGEN) +/** Internal: string form of the "is dev" flag */ +#ifndef APR_IS_DEV_STRING +#define APR_IS_DEV_STRING "-dev" +#endif +#else +#define APR_IS_DEV_STRING "" +#endif + +/* APR_STRINGIFY is defined here, and also in apr_general.h, so wrap it */ +#ifndef APR_STRINGIFY +/** Properly quote a value as a string in the C preprocessor */ +#define APR_STRINGIFY(n) APR_STRINGIFY_HELPER(n) +/** Helper macro for APR_STRINGIFY */ +#define APR_STRINGIFY_HELPER(n) #n +#endif + +/** The formatted string of APR's version */ +#define APR_VERSION_STRING \ + APR_STRINGIFY(APR_MAJOR_VERSION) "." \ + APR_STRINGIFY(APR_MINOR_VERSION) "." \ + APR_STRINGIFY(APR_PATCH_VERSION) \ + APR_IS_DEV_STRING + +/** An alternative formatted string of APR's version */ +/* macro for Win32 .rc files using numeric csv representation */ +#define APR_VERSION_STRING_CSV APR_MAJOR_VERSION ##, \ + ##APR_MINOR_VERSION ##, \ + ##APR_PATCH_VERSION + + +#ifndef APR_VERSION_ONLY + +/* The C language API to access the version at run time, + * as opposed to compile time. APR_VERSION_ONLY may be defined + * externally when preprocessing apr_version.h to obtain strictly + * the C Preprocessor macro declarations. + */ + +#include "apr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The numeric version information is broken out into fields within this + * structure. + */ +typedef struct { + int major; /**< major number */ + int minor; /**< minor number */ + int patch; /**< patch number */ + int is_dev; /**< is development (1 or 0) */ +} apr_version_t; + +/** + * Return APR's version information information in a numeric form. + * + * @param pvsn Pointer to a version structure for returning the version + * information. + */ +APR_DECLARE(void) apr_version(apr_version_t *pvsn); + +/** Return APR's version information as a string. */ +APR_DECLARE(const char *) apr_version_string(void); + +#ifdef __cplusplus +} +#endif + +#endif /* ndef APR_VERSION_ONLY */ + +#endif /* ndef APR_VERSION_H */ diff --git a/c/dependencies/macos/apr/include/apr_want.h b/c/dependencies/macos/apr/include/apr_want.h new file mode 100644 index 00000000..2863b001 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_want.h @@ -0,0 +1,124 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr.h" /* configuration data */ +/** + * @file apr_want.h + * @brief APR Standard Headers Support + * + *
+ * Features:
+ *
+ *   APR_WANT_STRFUNC:  strcmp, strcat, strcpy, etc
+ *   APR_WANT_MEMFUNC:  memcmp, memcpy, etc
+ *   APR_WANT_STDIO:     and related bits
+ *   APR_WANT_IOVEC:    struct iovec
+ *   APR_WANT_BYTEFUNC: htons, htonl, ntohl, ntohs
+ *
+ * Typical usage:
+ *
+ *   \#define APR_WANT_STRFUNC
+ *   \#define APR_WANT_MEMFUNC
+ *   \#include "apr_want.h"
+ *
+ * The appropriate headers will be included.
+ *
+ * Note: it is safe to use this in a header (it won't interfere with other
+ *       headers' or source files' use of apr_want.h)
+ * 
+ */ + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_STRFUNC + +#if APR_HAVE_STRING_H +#include +#endif +#if APR_HAVE_STRINGS_H +#include +#endif + +#undef APR_WANT_STRFUNC +#endif + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_MEMFUNC + +#if APR_HAVE_STRING_H +#include +#endif + +#undef APR_WANT_MEMFUNC +#endif + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_STDIO + +#if APR_HAVE_STDIO_H +#include +#endif + +#undef APR_WANT_STDIO +#endif + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_IOVEC + +#if APR_HAVE_IOVEC + +#if APR_HAVE_SYS_UIO_H +#include +#endif + +#else + +#ifndef APR_IOVEC_DEFINED +#define APR_IOVEC_DEFINED +struct iovec +{ + void *iov_base; + size_t iov_len; +}; +#endif /* !APR_IOVEC_DEFINED */ + +#endif /* APR_HAVE_IOVEC */ + +#undef APR_WANT_IOVEC +#endif + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_BYTEFUNC + +/* Single Unix says they are in arpa/inet.h. Linux has them in + * netinet/in.h. FreeBSD has them in arpa/inet.h but requires that + * netinet/in.h be included first. + */ +#if APR_HAVE_NETINET_IN_H +#include +#endif +#if APR_HAVE_ARPA_INET_H +#include +#endif + +#undef APR_WANT_BYTEFUNC +#endif + +/* --------------------------------------------------------------------- */ diff --git a/c/dependencies/macos/apr/include/apr_xlate.h b/c/dependencies/macos/apr/include/apr_xlate.h new file mode 100644 index 00000000..32636685 --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_xlate.h @@ -0,0 +1,163 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_XLATE_H +#define APR_XLATE_H + +#include "apu.h" +#include "apr_pools.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @file apr_xlate.h + * @brief APR I18N translation library + */ + +/** + * @defgroup APR_XLATE I18N translation library + * @ingroup APR + * @{ + */ +/** Opaque translation buffer */ +typedef struct apr_xlate_t apr_xlate_t; + +/** + * Set up for converting text from one charset to another. + * @param convset The handle to be filled in by this function + * @param topage The name of the target charset + * @param frompage The name of the source charset + * @param pool The pool to use + * @remark + * Specify APR_DEFAULT_CHARSET for one of the charset + * names to indicate the charset of the source code at + * compile time. This is useful if there are literal + * strings in the source code which must be translated + * according to the charset of the source code. + * APR_DEFAULT_CHARSET is not useful if the source code + * of the caller was not encoded in the same charset as + * APR at compile time. + * + * @remark + * Specify APR_LOCALE_CHARSET for one of the charset + * names to indicate the charset of the current locale. + * + * @remark + * Return APR_EINVAL if unable to procure a convset, or APR_ENOTIMPL + * if charset transcoding is not available in this instance of + * apr-util at all (i.e., APR_HAS_XLATE is undefined). + */ +APU_DECLARE(apr_status_t) apr_xlate_open(apr_xlate_t **convset, + const char *topage, + const char *frompage, + apr_pool_t *pool); + +/** + * This is to indicate the charset of the sourcecode at compile time + * names to indicate the charset of the source code at + * compile time. This is useful if there are literal + * strings in the source code which must be translated + * according to the charset of the source code. + */ +#define APR_DEFAULT_CHARSET (const char *)0 +/** + * To indicate charset names of the current locale + */ +#define APR_LOCALE_CHARSET (const char *)1 + +/** + * Find out whether or not the specified conversion is single-byte-only. + * @param convset The handle allocated by apr_xlate_open, specifying the + * parameters of conversion + * @param onoff Output: whether or not the conversion is single-byte-only + * @remark + * Return APR_ENOTIMPL if charset transcoding is not available + * in this instance of apr-util (i.e., APR_HAS_XLATE is undefined). + */ +APU_DECLARE(apr_status_t) apr_xlate_sb_get(apr_xlate_t *convset, int *onoff); + +/** + * Convert a buffer of text from one codepage to another. + * @param convset The handle allocated by apr_xlate_open, specifying + * the parameters of conversion + * @param inbuf The address of the source buffer + * @param inbytes_left Input: the amount of input data to be translated + * Output: the amount of input data not yet translated + * @param outbuf The address of the destination buffer + * @param outbytes_left Input: the size of the output buffer + * Output: the amount of the output buffer not yet used + * @remark + * Returns APR_ENOTIMPL if charset transcoding is not available + * in this instance of apr-util (i.e., APR_HAS_XLATE is undefined). + * Returns APR_INCOMPLETE if the input buffer ends in an incomplete + * multi-byte character. + * + * To correctly terminate the output buffer for some multi-byte + * character set encodings, a final call must be made to this function + * after the complete input string has been converted, passing + * the inbuf and inbytes_left parameters as NULL. (Note that this + * mode only works from version 1.1.0 onwards) + */ +APU_DECLARE(apr_status_t) apr_xlate_conv_buffer(apr_xlate_t *convset, + const char *inbuf, + apr_size_t *inbytes_left, + char *outbuf, + apr_size_t *outbytes_left); + +/* @see apr_file_io.h the comment in apr_file_io.h about this hack */ +#ifdef APR_NOT_DONE_YET +/** + * The purpose of apr_xlate_conv_char is to translate one character + * at a time. This needs to be written carefully so that it works + * with double-byte character sets. + * @param convset The handle allocated by apr_xlate_open, specifying the + * parameters of conversion + * @param inchar The character to convert + * @param outchar The converted character + */ +APU_DECLARE(apr_status_t) apr_xlate_conv_char(apr_xlate_t *convset, + char inchar, char outchar); +#endif + +/** + * Convert a single-byte character from one charset to another. + * @param convset The handle allocated by apr_xlate_open, specifying the + * parameters of conversion + * @param inchar The single-byte character to convert. + * @warning This only works when converting between single-byte character sets. + * -1 will be returned if the conversion can't be performed. + */ +APU_DECLARE(apr_int32_t) apr_xlate_conv_byte(apr_xlate_t *convset, + unsigned char inchar); + +/** + * Close a codepage translation handle. + * @param convset The codepage translation handle to close + * @remark + * Return APR_ENOTIMPL if charset transcoding is not available + * in this instance of apr-util (i.e., APR_HAS_XLATE is undefined). + */ +APU_DECLARE(apr_status_t) apr_xlate_close(apr_xlate_t *convset); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_XLATE_H */ diff --git a/c/dependencies/macos/apr/include/apr_xml.h b/c/dependencies/macos/apr/include/apr_xml.h new file mode 100644 index 00000000..87a696cc --- /dev/null +++ b/c/dependencies/macos/apr/include/apr_xml.h @@ -0,0 +1,358 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file apr_xml.h + * @brief APR-UTIL XML Library + */ +#ifndef APR_XML_H +#define APR_XML_H + +/** + * @defgroup APR_Util_XML XML + * @ingroup APR_Util + * @{ + */ +#include "apr_pools.h" +#include "apr_tables.h" +#include "apr_file_io.h" + +#include "apu.h" +#if APR_CHARSET_EBCDIC +#include "apr_xlate.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @package Apache XML library + */ + +/* -------------------------------------------------------------------- */ + +/* ### these will need to move at some point to a more logical spot */ + +/** @see apr_text */ +typedef struct apr_text apr_text; + +/** Structure to keep a linked list of pieces of text */ +struct apr_text { + /** The current piece of text */ + const char *text; + /** a pointer to the next piece of text */ + struct apr_text *next; +}; + +/** @see apr_text_header */ +typedef struct apr_text_header apr_text_header; + +/** A list of pieces of text */ +struct apr_text_header { + /** The first piece of text in the list */ + apr_text *first; + /** The last piece of text in the list */ + apr_text *last; +}; + +/** + * Append a piece of text to the end of a list + * @param p The pool to allocate out of + * @param hdr The text header to append to + * @param text The new text to append + */ +APU_DECLARE(void) apr_text_append(apr_pool_t *p, apr_text_header *hdr, + const char *text); + + +/* -------------------------------------------------------------------- +** +** XML PARSING +*/ + +/* +** Qualified namespace values +** +** APR_XML_NS_DAV_ID +** We always insert the "DAV:" namespace URI at the head of the +** namespace array. This means that it will always be at ID==0, +** making it much easier to test for. +** +** APR_XML_NS_NONE +** This special ID is used for two situations: +** +** 1) The namespace prefix begins with "xml" (and we do not know +** what it means). Namespace prefixes with "xml" (any case) as +** their first three characters are reserved by the XML Namespaces +** specification for future use. mod_dav will pass these through +** unchanged. When this identifier is used, the prefix is LEFT in +** the element/attribute name. Downstream processing should not +** prepend another prefix. +** +** 2) The element/attribute does not have a namespace. +** +** a) No prefix was used, and a default namespace has not been +** defined. +** b) No prefix was used, and the default namespace was specified +** to mean "no namespace". This is done with a namespace +** declaration of: xmlns="" +** (this declaration is typically used to override a previous +** specification for the default namespace) +** +** In these cases, we need to record that the elem/attr has no +** namespace so that we will not attempt to prepend a prefix. +** All namespaces that are used will have a prefix assigned to +** them -- mod_dav will never set or use the default namespace +** when generating XML. This means that "no prefix" will always +** mean "no namespace". +** +** In both cases, the XML generation will avoid prepending a prefix. +** For the first case, this means the original prefix/name will be +** inserted into the output stream. For the latter case, it means +** the name will have no prefix, and since we never define a default +** namespace, this means it will have no namespace. +** +** Note: currently, mod_dav understands the "xmlns" prefix and the +** "xml:lang" attribute. These are handled specially (they aren't +** left within the XML tree), so the APR_XML_NS_NONE value won't ever +** really apply to these values. +*/ +#define APR_XML_NS_DAV_ID 0 /**< namespace ID for "DAV:" */ +#define APR_XML_NS_NONE -10 /**< no namespace for this elem/attr */ + +#define APR_XML_NS_ERROR_BASE -100 /**< used only during processing */ +/** Is this namespace an error? */ +#define APR_XML_NS_IS_ERROR(e) ((e) <= APR_XML_NS_ERROR_BASE) + +/** @see apr_xml_attr */ +typedef struct apr_xml_attr apr_xml_attr; +/** @see apr_xml_elem */ +typedef struct apr_xml_elem apr_xml_elem; +/** @see apr_xml_doc */ +typedef struct apr_xml_doc apr_xml_doc; + +/** apr_xml_attr: holds a parsed XML attribute */ +struct apr_xml_attr { + /** attribute name */ + const char *name; + /** index into namespace array */ + int ns; + + /** attribute value */ + const char *value; + + /** next attribute */ + struct apr_xml_attr *next; +}; + +/** apr_xml_elem: holds a parsed XML element */ +struct apr_xml_elem { + /** element name */ + const char *name; + /** index into namespace array */ + int ns; + /** xml:lang for attrs/contents */ + const char *lang; + + /** cdata right after start tag */ + apr_text_header first_cdata; + /** cdata after MY end tag */ + apr_text_header following_cdata; + + /** parent element */ + struct apr_xml_elem *parent; + /** next (sibling) element */ + struct apr_xml_elem *next; + /** first child element */ + struct apr_xml_elem *first_child; + /** first attribute */ + struct apr_xml_attr *attr; + + /* used only during parsing */ + /** last child element */ + struct apr_xml_elem *last_child; + /** namespaces scoped by this elem */ + struct apr_xml_ns_scope *ns_scope; + + /* used by modules during request processing */ + /** Place for modules to store private data */ + void *priv; +}; + +/** Is this XML element empty? */ +#define APR_XML_ELEM_IS_EMPTY(e) ((e)->first_child == NULL && \ + (e)->first_cdata.first == NULL) + +/** apr_xml_doc: holds a parsed XML document */ +struct apr_xml_doc { + /** root element */ + apr_xml_elem *root; + /** array of namespaces used */ + apr_array_header_t *namespaces; +}; + +/** Opaque XML parser structure */ +typedef struct apr_xml_parser apr_xml_parser; + +/** + * Create an XML parser + * @param pool The pool for allocating the parser and the parse results. + * @return The new parser. + */ +APU_DECLARE(apr_xml_parser *) apr_xml_parser_create(apr_pool_t *pool); + +/** + * Parse a File, producing a xml_doc + * @param p The pool for allocating the parse results. + * @param parser A pointer to *parser (needed so calling function can get + * errors), will be set to NULL on successful completion. + * @param ppdoc A pointer to *apr_xml_doc (which has the parsed results in it) + * @param xmlfd A file to read from. + * @param buffer_length Buffer length which would be suitable + * @return Any errors found during parsing. + */ +APU_DECLARE(apr_status_t) apr_xml_parse_file(apr_pool_t *p, + apr_xml_parser **parser, + apr_xml_doc **ppdoc, + apr_file_t *xmlfd, + apr_size_t buffer_length); + + +/** + * Feed input into the parser + * @param parser The XML parser for parsing this data. + * @param data The data to parse. + * @param len The length of the data. + * @return Any errors found during parsing. + * @remark Use apr_xml_parser_geterror() to get more error information. + */ +APU_DECLARE(apr_status_t) apr_xml_parser_feed(apr_xml_parser *parser, + const char *data, + apr_size_t len); + +/** + * Terminate the parsing and return the result + * @param parser The XML parser for parsing this data. + * @param pdoc The resulting parse information. May be NULL to simply + * terminate the parsing without fetching the info. + * @return Any errors found during the final stage of parsing. + * @remark Use apr_xml_parser_geterror() to get more error information. + */ +APU_DECLARE(apr_status_t) apr_xml_parser_done(apr_xml_parser *parser, + apr_xml_doc **pdoc); + +/** + * Fetch additional error information from the parser. + * @param parser The XML parser to query for errors. + * @param errbuf A buffer for storing error text. + * @param errbufsize The length of the error text buffer. + * @return The error buffer + */ +APU_DECLARE(char *) apr_xml_parser_geterror(apr_xml_parser *parser, + char *errbuf, + apr_size_t errbufsize); + + +/** + * Converts an XML element tree to flat text + * @param p The pool to allocate out of + * @param elem The XML element to convert + * @param style How to covert the XML. One of: + *
+ *     APR_XML_X2T_FULL                start tag, contents, end tag 
+ *     APR_XML_X2T_INNER               contents only 
+ *     APR_XML_X2T_LANG_INNER          xml:lang + inner contents 
+ *     APR_XML_X2T_FULL_NS_LANG        FULL + ns defns + xml:lang 
+ *     APR_XML_X2T_PARSED              original prefixes
+ * 
+ * @param namespaces The namespace of the current XML element + * @param ns_map Namespace mapping + * @param pbuf Buffer to put the converted text into + * @param psize Size of the converted text + */ +APU_DECLARE(void) apr_xml_to_text(apr_pool_t *p, const apr_xml_elem *elem, + int style, apr_array_header_t *namespaces, + int *ns_map, const char **pbuf, + apr_size_t *psize); + +/* style argument values: */ +#define APR_XML_X2T_FULL 0 /**< start tag, contents, end tag */ +#define APR_XML_X2T_INNER 1 /**< contents only */ +#define APR_XML_X2T_LANG_INNER 2 /**< xml:lang + inner contents */ +#define APR_XML_X2T_FULL_NS_LANG 3 /**< FULL + ns defns + xml:lang */ +#define APR_XML_X2T_PARSED 4 /**< original prefixes */ + +/** + * empty XML element + * @param p The pool to allocate out of + * @param elem The XML element to empty + * @return the string that was stored in the XML element + */ +APU_DECLARE(const char *) apr_xml_empty_elem(apr_pool_t *p, + const apr_xml_elem *elem); + +/** + * quote an XML string + * Replace '\<', '\>', and '\&' with '\<', '\>', and '\&'. + * @param p The pool to allocate out of + * @param s The string to quote + * @param quotes If quotes is true, then replace '"' with '\"'. + * @return The quoted string + * @note If the string does not contain special characters, it is not + * duplicated into the pool and the original string is returned. + */ +APU_DECLARE(const char *) apr_xml_quote_string(apr_pool_t *p, const char *s, + int quotes); + +/** + * Quote an XML element + * @param p The pool to allocate out of + * @param elem The element to quote + */ +APU_DECLARE(void) apr_xml_quote_elem(apr_pool_t *p, apr_xml_elem *elem); + +/* manage an array of unique URIs: apr_xml_insert_uri() and APR_XML_URI_ITEM() */ + +/** + * return the URI's (existing) index, or insert it and return a new index + * @param uri_array array to insert into + * @param uri The uri to insert + * @return int The uri's index + */ +APU_DECLARE(int) apr_xml_insert_uri(apr_array_header_t *uri_array, + const char *uri); + +/** Get the URI item for this XML element */ +#define APR_XML_GET_URI_ITEM(ary, i) (((const char * const *)(ary)->elts)[i]) + +#if APR_CHARSET_EBCDIC +/** + * Convert parsed tree in EBCDIC + * @param p The pool to allocate out of + * @param pdoc The apr_xml_doc to convert. + * @param xlate The translation handle to use. + * @return Any errors found during conversion. + */ +APU_DECLARE(apr_status_t) apr_xml_parser_convert_doc(apr_pool_t *p, + apr_xml_doc *pdoc, + apr_xlate_t *convset); +#endif + +#ifdef __cplusplus +} +#endif +/** @} */ +#endif /* APR_XML_H */ diff --git a/c/dependencies/macos/apr/include/apu.h b/c/dependencies/macos/apr/include/apu.h new file mode 100644 index 00000000..5b5d59b1 --- /dev/null +++ b/c/dependencies/macos/apr/include/apu.h @@ -0,0 +1,128 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apu.h is generated from apu.h.in by configure -- do not edit apu.h + */ +/* @file apu.h + * @brief APR-Utility main file + */ +/** + * @defgroup APR_Util APR Utility Functions + * @{ + */ + + +#ifndef APU_H +#define APU_H + +/** + * APU_DECLARE_EXPORT is defined when building the APR-UTIL dynamic library, + * so that all public symbols are exported. + * + * APU_DECLARE_STATIC is defined when including the APR-UTIL public headers, + * to provide static linkage when the dynamic library may be unavailable. + * + * APU_DECLARE_STATIC and APU_DECLARE_EXPORT are left undefined when + * including the APR-UTIL public headers, to import and link the symbols from + * the dynamic APR-UTIL library and assure appropriate indirection and calling + * conventions at compile time. + */ + +#if defined(DOXYGEN) || !defined(WIN32) +/** + * The public APR-UTIL functions are declared with APU_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APU_DECLARE_NONSTD(). + * + * @fn APU_DECLARE(rettype) apr_func(args); + */ +#define APU_DECLARE(type) type +/** + * The public APR-UTIL functions using variable arguments are declared with + * APU_DECLARE_NONSTD(), as they must use the C language calling convention. + * + * @fn APU_DECLARE_NONSTD(rettype) apr_func(args, ...); + */ +#define APU_DECLARE_NONSTD(type) type +/** + * The public APR-UTIL variables are declared with APU_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * + * @fn APU_DECLARE_DATA type apr_variable; + * @note APU_DECLARE_DATA extern type apr_variable; syntax is required for + * declarations within headers to properly import the variable. + */ +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_STATIC) +#define APU_DECLARE(type) type __stdcall +#define APU_DECLARE_NONSTD(type) type __cdecl +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_EXPORT) +#define APU_DECLARE(type) __declspec(dllexport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllexport) +#else +#define APU_DECLARE(type) __declspec(dllimport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllimport) +#endif + +#if !defined(WIN32) || defined(APU_MODULE_DECLARE_STATIC) +/** + * Declare a dso module's exported module structure as APU_MODULE_DECLARE_DATA. + * + * Unless APU_MODULE_DECLARE_STATIC is defined at compile time, symbols + * declared with APU_MODULE_DECLARE_DATA are always exported. + * @code + * module APU_MODULE_DECLARE_DATA mod_tag + * @endcode + */ +#define APU_MODULE_DECLARE_DATA +#else +#define APU_MODULE_DECLARE_DATA __declspec(dllexport) +#endif + +/* + * we always have SDBM (it's in our codebase) + */ +#define APU_HAVE_SDBM 1 +#define APU_HAVE_GDBM 0 +#define APU_HAVE_NDBM 0 +#define APU_HAVE_DB 0 + +#if APU_HAVE_DB +#define APU_HAVE_DB_VERSION 0 +#endif + +#define APU_HAVE_PGSQL 0 +#define APU_HAVE_MYSQL 0 +#define APU_HAVE_SQLITE3 1 +#define APU_HAVE_SQLITE2 0 +#define APU_HAVE_ORACLE 0 +#define APU_HAVE_ODBC 0 + +#define APU_HAVE_CRYPTO 0 +#define APU_HAVE_OPENSSL 0 +#define APU_HAVE_NSS 0 +#define APU_HAVE_COMMONCRYPTO 0 + +#define APU_HAVE_APR_ICONV 0 +#define APU_HAVE_ICONV 1 +#define APR_HAS_XLATE (APU_HAVE_APR_ICONV || APU_HAVE_ICONV) + +#endif /* APU_H */ +/** @} */ diff --git a/c/dependencies/macos/apr/include/apu_errno.h b/c/dependencies/macos/apr/include/apu_errno.h new file mode 100644 index 00000000..c0a8ec7d --- /dev/null +++ b/c/dependencies/macos/apr/include/apu_errno.h @@ -0,0 +1,173 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APU_ERRNO_H +#define APU_ERRNO_H + +/** + * @file apu_errno.h + * @brief APR-Util Error Codes + */ + +#include "apr.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apu_errno Error Codes + * @ingroup APR_Util + * @{ + */ + +/** + * @defgroup APR_Util_Error APR_Util Error Values + *
+ * APU ERROR VALUES
+ * APR_ENOKEY         The key provided was empty or NULL
+ * APR_ENOIV          The initialisation vector provided was NULL
+ * APR_EKEYTYPE       The key type was not recognised
+ * APR_ENOSPACE       The buffer supplied was not big enough
+ * APR_ECRYPT         An error occurred while encrypting or decrypting
+ * APR_EPADDING       Padding was not supported
+ * APR_EKEYLENGTH     The key length was incorrect
+ * APR_ENOCIPHER      The cipher provided was not recognised
+ * APR_ENODIGEST      The digest provided was not recognised
+ * APR_ENOENGINE      The engine provided was not recognised
+ * APR_EINITENGINE    The engine could not be initialised
+ * APR_EREINIT        Underlying crypto has already been initialised
+ * 
+ * + *
+ * APR STATUS VALUES
+ * APR_INCHILD        Program is currently executing in the child
+ * 
+ * @{ + */ +/** @see APR_STATUS_IS_ENOKEY */ +#define APR_ENOKEY (APR_UTIL_START_STATUS + 1) +/** @see APR_STATUS_IS_ENOIV */ +#define APR_ENOIV (APR_UTIL_START_STATUS + 2) +/** @see APR_STATUS_IS_EKEYTYPE */ +#define APR_EKEYTYPE (APR_UTIL_START_STATUS + 3) +/** @see APR_STATUS_IS_ENOSPACE */ +#define APR_ENOSPACE (APR_UTIL_START_STATUS + 4) +/** @see APR_STATUS_IS_ECRYPT */ +#define APR_ECRYPT (APR_UTIL_START_STATUS + 5) +/** @see APR_STATUS_IS_EPADDING */ +#define APR_EPADDING (APR_UTIL_START_STATUS + 6) +/** @see APR_STATUS_IS_EKEYLENGTH */ +#define APR_EKEYLENGTH (APR_UTIL_START_STATUS + 7) +/** @see APR_STATUS_IS_ENOCIPHER */ +#define APR_ENOCIPHER (APR_UTIL_START_STATUS + 8) +/** @see APR_STATUS_IS_ENODIGEST */ +#define APR_ENODIGEST (APR_UTIL_START_STATUS + 9) +/** @see APR_STATUS_IS_ENOENGINE */ +#define APR_ENOENGINE (APR_UTIL_START_STATUS + 10) +/** @see APR_STATUS_IS_EINITENGINE */ +#define APR_EINITENGINE (APR_UTIL_START_STATUS + 11) +/** @see APR_STATUS_IS_EREINIT */ +#define APR_EREINIT (APR_UTIL_START_STATUS + 12) +/** @} */ + +/** + * @defgroup APU_STATUS_IS Status Value Tests + * @warning For any particular error condition, more than one of these tests + * may match. This is because platform-specific error codes may not + * always match the semantics of the POSIX codes these tests (and the + * corresponding APR error codes) are named after. A notable example + * are the APR_STATUS_IS_ENOENT and APR_STATUS_IS_ENOTDIR tests on + * Win32 platforms. The programmer should always be aware of this and + * adjust the order of the tests accordingly. + * @{ + */ + +/** @} */ + +/** + * @addtogroup APR_Util_Error + * @{ + */ +/** + * The key was empty or not provided + */ +#define APR_STATUS_IS_ENOKEY(s) ((s) == APR_ENOKEY) +/** + * The initialisation vector was not provided + */ +#define APR_STATUS_IS_ENOIV(s) ((s) == APR_ENOIV) +/** + * The key type was not recognised + */ +#define APR_STATUS_IS_EKEYTYPE(s) ((s) == APR_EKEYTYPE) +/** + * The buffer provided was not big enough + */ +#define APR_STATUS_IS_ENOSPACE(s) ((s) == APR_ENOSPACE) +/** + * An error occurred while encrypting or decrypting + */ +#define APR_STATUS_IS_ECRYPT(s) ((s) == APR_ECRYPT) +/** + * An error occurred while padding + */ +#define APR_STATUS_IS_EPADDING(s) ((s) == APR_EPADDING) +/** + * An error occurred with the key length + */ +#define APR_STATUS_IS_EKEYLENGTH(s) ((s) == APR_EKEYLENGTH) +/** + * The cipher provided was not recognised + */ +#define APR_STATUS_IS_ENOCIPHER(s) ((s) == APR_ENOCIPHER) +/** + * The digest provided was not recognised + */ +#define APR_STATUS_IS_ENODIGEST(s) ((s) == APR_ENODIGEST) +/** + * The engine provided was not recognised + */ +#define APR_STATUS_IS_ENOENGINE(s) ((s) == APR_ENOENGINE) +/** + * The engine could not be initialised + */ +#define APR_STATUS_IS_EINITENGINE(s) ((s) == APR_EINITENGINE) +/** + * Crypto has already been initialised + */ +#define APR_STATUS_IS_EREINIT(s) ((s) == APR_EREINIT) +/** @} */ + +/** + * This structure allows the underlying API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apu_err_t { + const char *reason; + const char *msg; + int rc; +} apu_err_t; + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APU_ERRNO_H */ diff --git a/c/dependencies/macos/apr/include/apu_version.h b/c/dependencies/macos/apr/include/apu_version.h new file mode 100644 index 00000000..4af44cd7 --- /dev/null +++ b/c/dependencies/macos/apr/include/apu_version.h @@ -0,0 +1,139 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APU_VERSION_H +#define APU_VERSION_H + +/** + * @file apu_version.h + * @brief APR-util Versioning Interface + * + * APR-util's Version + * + * There are several different mechanisms for accessing the version. There + * is a string form, and a set of numbers; in addition, there are constants + * which can be compiled into your application, and you can query the library + * being used for its actual version. + * + * Note that it is possible for an application to detect that it has been + * compiled against a different version of APU by use of the compile-time + * constants and the use of the run-time query function. + * + * APU version numbering follows the guidelines specified in: + * + * http://apr.apache.org/versioning.html + */ + + +#define APU_COPYRIGHT "Copyright (c) 2000-2023 The Apache Software " \ + "Foundation or its licensors, as applicable." + +/* The numeric compile-time version constants. These constants are the + * authoritative version numbers for APU. + */ + +/** major version + * Major API changes that could cause compatibility problems for older + * programs such as structure size changes. No binary compatibility is + * possible across a change in the major version. + */ +#define APU_MAJOR_VERSION 1 + +/** minor version + * Minor API changes that do not cause binary compatibility problems. + * Reset to 0 when upgrading APU_MAJOR_VERSION + */ +#define APU_MINOR_VERSION 6 + +/** patch level + * The Patch Level never includes API changes, simply bug fixes. + * Reset to 0 when upgrading APR_MINOR_VERSION + */ +#define APU_PATCH_VERSION 3 + +/** + * The symbol APU_IS_DEV_VERSION is only defined for internal, + * "development" copies of APU. It is undefined for released versions + * of APU. + */ +/* #undef APU_IS_DEV_VERSION */ + + +#if defined(APU_IS_DEV_VERSION) || defined(DOXYGEN) +/** Internal: string form of the "is dev" flag */ +#ifndef APU_IS_DEV_STRING +#define APU_IS_DEV_STRING "-dev" +#endif +#else +#define APU_IS_DEV_STRING "" +#endif + + +#ifndef APU_STRINGIFY +/** Properly quote a value as a string in the C preprocessor */ +#define APU_STRINGIFY(n) APU_STRINGIFY_HELPER(n) +/** Helper macro for APU_STRINGIFY */ +#define APU_STRINGIFY_HELPER(n) #n +#endif + +/** The formatted string of APU's version */ +#define APU_VERSION_STRING \ + APU_STRINGIFY(APU_MAJOR_VERSION) "." \ + APU_STRINGIFY(APU_MINOR_VERSION) "." \ + APU_STRINGIFY(APU_PATCH_VERSION) \ + APU_IS_DEV_STRING + +/** An alternative formatted string of APR's version */ +/* macro for Win32 .rc files using numeric csv representation */ +#define APU_VERSION_STRING_CSV APU_MAJOR_VERSION ##, \ + ##APU_MINOR_VERSION ##, \ + ##APU_PATCH_VERSION + + +#ifndef APU_VERSION_ONLY + +/* The C language API to access the version at run time, + * as opposed to compile time. APU_VERSION_ONLY may be defined + * externally when preprocessing apr_version.h to obtain strictly + * the C Preprocessor macro declarations. + */ + +#include "apr_version.h" + +#include "apu.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Return APR-util's version information information in a numeric form. + * + * @param pvsn Pointer to a version structure for returning the version + * information. + */ +APU_DECLARE(void) apu_version(apr_version_t *pvsn); + +/** Return APU's version information as a string. */ +APU_DECLARE(const char *) apu_version_string(void); + +#ifdef __cplusplus +} +#endif + +#endif /* ndef APU_VERSION_ONLY */ + +#endif /* ndef APU_VERSION_H */ diff --git a/c/dependencies/macos/apr/include/apu_want.h b/c/dependencies/macos/apr/include/apu_want.h new file mode 100644 index 00000000..25f1100d --- /dev/null +++ b/c/dependencies/macos/apr/include/apu_want.h @@ -0,0 +1,51 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apu.h" /* configuration data */ + +/** + * @file apu_want.h + * @brief APR Standard Headers Support + * + *
+ * Features:
+ *
+ *   APU_WANT_DB:       
+ *
+ * Typical usage:
+ *
+ *   #define APU_WANT_DB
+ *   #include "apu_want.h"
+ *
+ * The appropriate headers will be included.
+ *
+ * Note: it is safe to use this in a header (it won't interfere with other
+ *       headers' or source files' use of apu_want.h)
+ * 
+ */ + +/* --------------------------------------------------------------------- */ + +#ifdef APU_WANT_DB + +#if APU_HAVE_DB +#include +#endif + +#undef APU_WANT_DB +#endif + +/* --------------------------------------------------------------------- */ diff --git a/c/dependencies/macos/apr/lib/arm64/libapr.a b/c/dependencies/macos/apr/lib/arm64/libapr.a new file mode 100644 index 00000000..5dc1ca42 Binary files /dev/null and b/c/dependencies/macos/apr/lib/arm64/libapr.a differ diff --git a/c/dependencies/macos/apr/lib/arm64/libaprutil.a b/c/dependencies/macos/apr/lib/arm64/libaprutil.a new file mode 100644 index 00000000..2914b8dc Binary files /dev/null and b/c/dependencies/macos/apr/lib/arm64/libaprutil.a differ diff --git a/c/dependencies/macos/apr/lib/x86_64/libapr.a b/c/dependencies/macos/apr/lib/x86_64/libapr.a new file mode 100644 index 00000000..b73473b1 Binary files /dev/null and b/c/dependencies/macos/apr/lib/x86_64/libapr.a differ diff --git a/c/dependencies/macos/apr/lib/x86_64/libaprutil.a b/c/dependencies/macos/apr/lib/x86_64/libaprutil.a new file mode 100644 index 00000000..7b81bffa Binary files /dev/null and b/c/dependencies/macos/apr/lib/x86_64/libaprutil.a differ diff --git a/c/dependencies/windows/apr/x64/include/api_version.h b/c/dependencies/windows/apr/x64/include/api_version.h new file mode 100644 index 00000000..c2788959 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/api_version.h @@ -0,0 +1,132 @@ +/* Copyright 2000-2017 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef API_VERSION_H +#define API_VERSION_H + +/** + * @file api_version.h + * @brief APR-iconv Versioning Interface + * + * APR-iconv's Version + * + * There are several different mechanisms for accessing the version. There + * is a string form, and a set of numbers; in addition, there are constants + * which can be compiled into your application, and you can query the library + * being used for its actual version. + * + * Note that it is possible for an application to detect that it has been + * compiled against a different version of API by use of the compile-time + * constants and the use of the run-time query function. + * + * API version numbering follows the guidelines specified in: + * + * http://apr.apache.org/versioning.html + */ + + +/* The numeric compile-time version constants. These constants are the + * authoritative version numbers for API. + */ + +/** major version + * Major API changes that could cause compatibility problems for older + * programs such as structure size changes. No binary compatibility is + * possible across a change in the major version. + */ +#define API_MAJOR_VERSION 1 + +/** minor version + * Minor API changes that do not cause binary compatibility problems. + * Reset to 0 when upgrading API_MAJOR_VERSION + */ +#define API_MINOR_VERSION 2 + +/** patch level + * The Patch Level never includes API changes, simply bug fixes. + * Reset to 0 when upgrading API_MINOR_VERSION + */ +#define API_PATCH_VERSION 2 + +/** + * The symbol API_IS_DEV_VERSION is only defined for internal, + * "development" copies of API. It is undefined for released versions + * of API. + */ +/* #undef API_IS_DEV_VERSION */ + + +#if defined(API_IS_DEV_VERSION) || defined(DOXYGEN) +/** Internal: string form of the "is dev" flag */ +#define API_IS_DEV_STRING "-dev" +#else +#define API_IS_DEV_STRING "" +#endif + +#ifndef API_STRINGIFY +/** Properly quote a value as a string in the C preprocessor */ +#define API_STRINGIFY(n) API_STRINGIFY_HELPER(n) +/** Helper macro for API_STRINGIFY */ +#define API_STRINGIFY_HELPER(n) #n +#endif + +/** The formatted string of API's version */ +#define API_VERSION_STRING \ + API_STRINGIFY(API_MAJOR_VERSION) "." \ + API_STRINGIFY(API_MINOR_VERSION) "." \ + API_STRINGIFY(API_PATCH_VERSION) \ + API_IS_DEV_STRING + +/** An alternative formatted string of APR's version */ +/* macro for Win32 .rc files using numeric csv representation */ +#define API_VERSION_STRING_CSV API_MAJOR_VERSION ##, \ + ##API_MINOR_VERSION ##, \ + ##API_PATCH_VERSION + + +#ifndef API_VERSION_ONLY + +/* The C language API to access the version at run time, + * as opposed to compile time. API_VERSION_ONLY may be defined + * externally when preprocessing apr_version.h to obtain strictly + * the C Preprocessor macro declarations. + */ + +#include "apr_version.h" + +#include "apr_iconv.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Return APR-iconv's version information information in a numeric form. + * + * @param pvsn Pointer to a version structure for returning the version + * information. + */ +API_DECLARE(void) api_version(apr_version_t *pvsn); + +/** Return API's version information as a string. */ +API_DECLARE(const char *) api_version_string(void); + +#ifdef __cplusplus +} +#endif + +#endif /* ndef API_VERSION_ONLY */ + +#endif /* ndef API_VERSION_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr.h b/c/dependencies/windows/apr/x64/include/apr.h new file mode 100644 index 00000000..3352fef3 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr.h @@ -0,0 +1,667 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef APR_H +#define APR_H + +/* GENERATED FILE WARNING! DO NOT EDIT apr.h + * + * You must modify apr.hw instead. + * + * And please, make an effort to stub apr.hnw and apr.h.in in the process. + * + * This is the Win32 specific version of apr.h. It is copied from + * apr.hw by the apr.dsp and libapr.dsp projects. + */ + +/** + * @file apr.h + * @brief APR Platform Definitions + * @remark This is a generated header generated from include/apr.h.in by + * ./configure, or copied from include/apr.hw or include/apr.hnw + * for Win32 or Netware by those build environments, respectively. + */ + +/* Make sure we have our platform identifier macro defined we ask for later. + */ +#if defined(_WIN32) && !defined(WIN32) +#define WIN32 1 +#endif + +#if defined(WIN32) || defined(DOXYGEN) + +/* Ignore most warnings (back down to /W3) for poorly constructed headers + */ +#if defined(_MSC_VER) && _MSC_VER >= 1200 +#pragma warning(push, 3) +#endif + +/* disable or reduce the frequency of... + * C4057: indirection to slightly different base types + * C4075: slight indirection changes (unsigned short* vs short[]) + * C4100: unreferenced formal parameter + * C4127: conditional expression is constant + * C4163: '_rotl64' : not available as an intrinsic function + * C4201: nonstandard extension nameless struct/unions + * C4244: int to char/short - precision loss + * C4514: unreferenced inline function removed + */ +#if defined(_MSC_VER) +#pragma warning(disable: 4100 4127 4163 4201 4514; once: 4057 4075 4244) +#endif + +/* Ignore Microsoft's interpretation of secure development + * and the POSIX string handling API + */ +#if defined(_MSC_VER) && _MSC_VER >= 1400 +#ifndef _CRT_SECURE_NO_DEPRECATE +#define _CRT_SECURE_NO_DEPRECATE +#endif +#pragma warning(disable: 4996) +#endif + +/* Has windows.h already been included? If so, our preferences don't matter, + * but we will still need the winsock things no matter what was included. + * If not, include a restricted set of windows headers to our tastes. + */ +#ifndef _WINDOWS_ +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef _WIN32_WINNT + +/* Restrict the server to a subset of Windows XP header files by default + */ +#define _WIN32_WINNT 0x0A00 +#endif +#ifndef NOUSER +#define NOUSER +#endif +#ifndef NOMCX +#define NOMCX +#endif +#ifndef NOIME +#define NOIME +#endif +#include +/* + * Add a _very_few_ declarations missing from the restricted set of headers + * (If this list becomes extensive, re-enable the required headers above!) + * winsock headers were excluded by WIN32_LEAN_AND_MEAN, so include them now + */ +#define SW_HIDE 0 +#ifndef _WIN32_WCE +#include +#include +#include +#else +#include +#endif +#endif /* !_WINDOWS_ */ + +/** + * @defgroup APR Apache Portability Runtime library + * @{ + */ +/** + * @defgroup apr_platform Platform Definitions + * @{ + * @warning + * The actual values of macros and typedefs on this page
+ * are platform specific and should NOT be relied upon!
+ */ + +#define APR_INLINE __inline +#define APR_HAS_INLINE 1 +#if !defined(__GNUC__) && !defined(__attribute__) +#define __attribute__(__x) +#endif + +#ifndef _WIN32_WCE +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_CONIO_H 1 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 1 +#define APR_HAVE_DIRENT_H 0 +#define APR_HAVE_ERRNO_H 1 +#define APR_HAVE_FCNTL_H 1 +#define APR_HAVE_IO_H 1 +#define APR_HAVE_LIMITS_H 1 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SEMAPHORE_H 0 +#define APR_HAVE_SIGNAL_H 1 +#define APR_HAVE_STDARG_H 1 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_SYS_IOCTL_H 0 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SIGNAL_H 0 +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#define APR_HAVE_SYS_TIME_H 0 +#define APR_HAVE_SYS_TYPES_H 1 +#define APR_HAVE_SYS_UIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#define APR_HAVE_SYS_WAIT_H 0 +#define APR_HAVE_TIME_H 1 +#define APR_HAVE_UNISTD_H 0 +#define APR_HAVE_STDDEF_H 1 +#define APR_HAVE_PROCESS_H 1 +#else +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_CONIO_H 0 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 0 +#define APR_HAVE_DIRENT_H 0 +#define APR_HAVE_ERRNO_H 0 +#define APR_HAVE_FCNTL_H 0 +#define APR_HAVE_IO_H 0 +#define APR_HAVE_LIMITS_H 0 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SEMAPHORE_H 0 +#define APR_HAVE_SIGNAL_H 0 +#define APR_HAVE_STDARG_H 0 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_SYS_IOCTL_H 0 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SIGNAL_H 0 +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#define APR_HAVE_SYS_TIME_H 0 +#define APR_HAVE_SYS_TYPES_H 0 +#define APR_HAVE_SYS_UIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#define APR_HAVE_SYS_WAIT_H 0 +#define APR_HAVE_TIME_H 0 +#define APR_HAVE_UNISTD_H 0 +#define APR_HAVE_STDDEF_H 0 +#define APR_HAVE_PROCESS_H 0 +#endif + +/** @} */ +/** @} */ + +/* We don't include our conditional headers within the doxyblocks + * or the extern "C" namespace + */ + +#if APR_HAVE_STDLIB_H +#include +#endif + +#if APR_HAVE_STDIO_H +#include +#endif + +#if APR_HAVE_SYS_TYPES_H +#include +#endif + +#if APR_HAVE_STDDEF_H +#include +#endif + +#if APR_HAVE_SYS_SOCKET_H +#include +#endif + +#if APR_HAVE_STDINT_H +#include +#endif + +#if APR_HAVE_SYS_WAIT_H +#include +#endif + +#if APR_HAVE_TIME_H +#include +#endif + +#if APR_HAVE_PROCESS_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @addtogroup apr_platform + * @ingroup APR + * @{ + */ + +#define APR_HAVE_SHMEM_MMAP_TMP 0 +#define APR_HAVE_SHMEM_MMAP_SHM 0 +#define APR_HAVE_SHMEM_MMAP_ZERO 0 +#define APR_HAVE_SHMEM_SHMGET_ANON 0 +#define APR_HAVE_SHMEM_SHMGET 0 +#define APR_HAVE_SHMEM_MMAP_ANON 0 +#define APR_HAVE_SHMEM_BEOS 0 + +#define APR_USE_SHMEM_MMAP_TMP 0 +#define APR_USE_SHMEM_MMAP_SHM 0 +#define APR_USE_SHMEM_MMAP_ZERO 0 +#define APR_USE_SHMEM_SHMGET_ANON 0 +#define APR_USE_SHMEM_SHMGET 0 +#define APR_USE_SHMEM_MMAP_ANON 0 +#define APR_USE_SHMEM_BEOS 0 + +#define APR_USE_FLOCK_SERIALIZE 0 +#define APR_USE_POSIXSEM_SERIALIZE 0 +#define APR_USE_SYSVSEM_SERIALIZE 0 +#define APR_USE_FCNTL_SERIALIZE 0 +#define APR_USE_PROC_PTHREAD_SERIALIZE 0 +#define APR_USE_PTHREAD_SERIALIZE 0 + +#define APR_HAS_FLOCK_SERIALIZE 0 +#define APR_HAS_SYSVSEM_SERIALIZE 0 +#define APR_HAS_POSIXSEM_SERIALIZE 0 +#define APR_HAS_FCNTL_SERIALIZE 0 +#define APR_HAS_PROC_PTHREAD_SERIALIZE 0 + +#define APR_PROCESS_LOCK_IS_GLOBAL 0 + +#define APR_HAVE_CORKABLE_TCP 0 +#define APR_HAVE_GETRLIMIT 0 +#define APR_HAVE_ICONV 0 +#define APR_HAVE_IN_ADDR 1 +#define APR_HAVE_INET_ADDR 1 +#define APR_HAVE_INET_NETWORK 0 +#define APR_HAVE_IPV6 1 +#define APR_HAVE_SOCKADDR_UN 0 +#define APR_HAVE_MEMMOVE 1 +#define APR_HAVE_SETRLIMIT 0 +#define APR_HAVE_SIGACTION 0 +#define APR_HAVE_SIGSUSPEND 0 +#define APR_HAVE_SIGWAIT 0 +#define APR_HAVE_SA_STORAGE 0 +#define APR_HAVE_STRCASECMP 0 +#define APR_HAVE_STRDUP 1 +#define APR_HAVE_STRNCASECMP 0 +#define APR_HAVE_STRSTR 1 +#define APR_HAVE_MEMCHR 1 +#define APR_HAVE_STRUCT_RLIMIT 0 +#define APR_HAVE_UNION_SEMUN 0 +#define APR_HAVE_SCTP 0 +#define APR_HAVE_IOVEC 0 + +#ifndef _WIN32_WCE +#define APR_HAVE_STRICMP 1 +#define APR_HAVE_STRNICMP 1 +#else +#define APR_HAVE_STRICMP 0 +#define APR_HAVE_STRNICMP 0 +#endif + +/* APR Feature Macros */ +#define APR_HAS_SHARED_MEMORY 1 +#define APR_HAS_THREADS 1 +#define APR_HAS_MMAP 1 +#define APR_HAS_FORK 0 +#define APR_HAS_RANDOM 1 +#define APR_HAS_OTHER_CHILD 1 +#define APR_HAS_DSO 1 +#define APR_HAS_SO_ACCEPTFILTER 0 +#define APR_HAS_UNICODE_FS 1 +#define APR_HAS_PROC_INVOKED 1 +#define APR_HAS_OS_UUID 1 +#define APR_HAS_TIMEDLOCKS 1 + +#ifndef _WIN32_WCE +#define APR_HAS_SENDFILE 1 +#define APR_HAS_USER 1 +#define APR_HAS_LARGE_FILES 1 +#define APR_HAS_XTHREAD_FILES 1 +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 1 +#else +#define APR_HAS_SENDFILE 0 +#define APR_HAS_USER 0 +#define APR_HAS_LARGE_FILES 0 +#define APR_HAS_XTHREAD_FILES 0 +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 0 +#endif + +/* APR sets APR_FILES_AS_SOCKETS to 1 on systems where it is possible + * to poll on files/pipes. + */ +#define APR_FILES_AS_SOCKETS 0 + +/* This macro indicates whether or not EBCDIC is the native character set. + */ +#define APR_CHARSET_EBCDIC 0 + +/* If we have a TCP implementation that can be "corked", what flag + * do we use? + */ +#define APR_TCP_NOPUSH_FLAG @apr_tcp_nopush_flag@ + +/* Is the TCP_NODELAY socket option inherited from listening sockets? + */ +#define APR_TCP_NODELAY_INHERITED 1 + +/* Is the O_NONBLOCK flag inherited from listening sockets? + */ +#define APR_O_NONBLOCK_INHERITED 1 + +/* Typedefs that APR needs. */ + +typedef unsigned char apr_byte_t; + +typedef short apr_int16_t; +typedef unsigned short apr_uint16_t; + +typedef int apr_int32_t; +typedef unsigned int apr_uint32_t; + +typedef __int64 apr_int64_t; +typedef unsigned __int64 apr_uint64_t; + +typedef size_t apr_size_t; +#if APR_HAVE_STDDEF_H +typedef ptrdiff_t apr_ssize_t; +#else +typedef int apr_ssize_t; +#endif +#if APR_HAS_LARGE_FILES +typedef __int64 apr_off_t; +#else +typedef int apr_off_t; +#endif +typedef int apr_socklen_t; +typedef apr_uint64_t apr_ino_t; + +#ifdef _WIN64 +#define APR_SIZEOF_VOIDP 8 +#else +#define APR_SIZEOF_VOIDP 4 +#endif + +#if APR_SIZEOF_VOIDP == 8 +typedef apr_uint64_t apr_uintptr_t; +#else +typedef apr_uint32_t apr_uintptr_t; +#endif + +/* Are we big endian? */ +/* XXX: Fatal assumption on Alpha platforms */ +#define APR_IS_BIGENDIAN 0 + +/* Mechanisms to properly type numeric literals */ + +#ifndef __GNUC__ +#define APR_INT64_C(val) (val##i64) +#define APR_UINT64_C(val) (val##Ui64) +#else +#define APR_INT64_C(val) (val##LL) +#define APR_UINT64_C(val) (val##ULL) +#endif + +#ifdef INT16_MIN +#define APR_INT16_MIN INT16_MIN +#else +#define APR_INT16_MIN (-0x7fff - 1) +#endif + +#ifdef INT16_MAX +#define APR_INT16_MAX INT16_MAX +#else +#define APR_INT16_MAX (0x7fff) +#endif + +#ifdef UINT16_MAX +#define APR_UINT16_MAX UINT16_MAX +#else +#define APR_UINT16_MAX (0xffff) +#endif + +#ifdef INT32_MIN +#define APR_INT32_MIN INT32_MIN +#else +#define APR_INT32_MIN (-0x7fffffff - 1) +#endif + +#ifdef INT32_MAX +#define APR_INT32_MAX INT32_MAX +#else +#define APR_INT32_MAX 0x7fffffff +#endif + +#ifdef UINT32_MAX +#define APR_UINT32_MAX UINT32_MAX +#else +#define APR_UINT32_MAX (0xffffffffU) +#endif + +#ifdef INT64_MIN +#define APR_INT64_MIN INT64_MIN +#else +#define APR_INT64_MIN (APR_INT64_C(-0x7fffffffffffffff) - 1) +#endif + +#ifdef INT64_MAX +#define APR_INT64_MAX INT64_MAX +#else +#define APR_INT64_MAX APR_INT64_C(0x7fffffffffffffff) +#endif + +#ifdef UINT64_MAX +#define APR_UINT64_MAX UINT64_MAX +#else +#define APR_UINT64_MAX APR_UINT64_C(0xffffffffffffffff) +#endif + +#define APR_SIZE_MAX (~((apr_size_t)0)) + +/* Definitions that APR programs need to work properly. */ + +/** + * APR public API wrap for C++ compilers. + */ +#ifdef __cplusplus +#define APR_BEGIN_DECLS extern "C" { +#define APR_END_DECLS } +#else +#define APR_BEGIN_DECLS +#define APR_END_DECLS +#endif + +/** + * Thread callbacks from APR functions must be declared with APR_THREAD_FUNC, + * so that they follow the platform's calling convention. + *
+ *
+ * void* APR_THREAD_FUNC my_thread_entry_fn(apr_thread_t *thd, void *data);
+ *
+ * 
+ */ +#define APR_THREAD_FUNC __stdcall + + +#if defined(DOXYGEN) || !defined(WIN32) + +/** + * The public APR functions are declared with APR_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APR_DECLARE_NONSTD(). + * + * @remark Both the declaration and implementations must use the same macro. + * + *
+ * APR_DECLARE(rettype) apr_func(args)
+ * 
+ * @see APR_DECLARE_NONSTD @see APR_DECLARE_DATA + * @remark Note that when APR compiles the library itself, it passes the + * symbol -DAPR_DECLARE_EXPORT to the compiler on some platforms (e.g. Win32) + * to export public symbols from the dynamic library build.\n + * The user must define the APR_DECLARE_STATIC when compiling to target + * the static APR library on some platforms (e.g. Win32.) The public symbols + * are neither exported nor imported when APR_DECLARE_STATIC is defined.\n + * By default, compiling an application and including the APR public + * headers, without defining APR_DECLARE_STATIC, will prepare the code to be + * linked to the dynamic library. + */ +#define APR_DECLARE(type) type + +/** + * The public APR functions using variable arguments are declared with + * APR_DECLARE_NONSTD(), as they must follow the C language calling convention. + * @see APR_DECLARE @see APR_DECLARE_DATA + * @remark Both the declaration and implementations must use the same macro. + *
+ *
+ * APR_DECLARE_NONSTD(rettype) apr_func(args, ...);
+ *
+ * 
+ */ +#define APR_DECLARE_NONSTD(type) type + +/** + * The public APR variables are declared with AP_MODULE_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * @see APR_DECLARE @see APR_DECLARE_NONSTD + * @remark Note that the declaration and implementations use different forms, + * but both must include the macro. + * + *
+ *
+ * extern APR_DECLARE_DATA type apr_variable;\n
+ * APR_DECLARE_DATA type apr_variable = value;
+ *
+ * 
+ */ +#define APR_DECLARE_DATA + +#elif defined(APR_DECLARE_STATIC) +#define APR_DECLARE(type) type __stdcall +#define APR_DECLARE_NONSTD(type) type __cdecl +#define APR_DECLARE_DATA +#elif defined(APR_DECLARE_EXPORT) +#define APR_DECLARE(type) __declspec(dllexport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllexport) +#else +#define APR_DECLARE(type) __declspec(dllimport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllimport) +#endif + +#ifdef _WIN64 +#define APR_SSIZE_T_FMT "I64d" +#define APR_SIZE_T_FMT "I64u" +#else +#define APR_SSIZE_T_FMT "d" +#define APR_SIZE_T_FMT "u" +#endif + +#if APR_HAS_LARGE_FILES +#define APR_OFF_T_FMT "I64d" +#else +#define APR_OFF_T_FMT "d" +#endif + +#define APR_PID_T_FMT "d" + +#define APR_INT64_T_FMT "I64d" +#define APR_UINT64_T_FMT "I64u" +#define APR_UINT64_T_HEX_FMT "I64x" + +/* No difference between PROC and GLOBAL mutex */ +#define APR_PROC_MUTEX_IS_GLOBAL 1 + +/* Local machine definition for console and log output. */ +#define APR_EOL_STR "\r\n" + +typedef int apr_wait_t; + +#if APR_HAS_UNICODE_FS +/* An arbitrary size that is digestable. True max is a bit less than 32000 */ +#define APR_PATH_MAX 8192 +#else /* !APR_HAS_UNICODE_FS */ +#define APR_PATH_MAX MAX_PATH +#endif + +#define APR_DSOPATH "PATH" + +/** @} */ + +/* Definitions that only Win32 programs need to compile properly. */ + +/* XXX These simply don't belong here, perhaps in apr_portable.h + * based on some APR_HAVE_PID/GID/UID? + */ +#ifndef __GNUC__ +typedef int pid_t; +#endif +typedef int uid_t; +typedef int gid_t; + +/* Win32 .h ommissions we really need */ +#define STDIN_FILENO 0 +#define STDOUT_FILENO 1 +#define STDERR_FILENO 2 + +#if APR_HAVE_IPV6 + +/* Appears in later flavors, not the originals. */ +#ifndef in_addr6 +#define in6_addr in_addr6 +#endif + +#ifndef WS2TCPIP_INLINE +#define IN6_IS_ADDR_V4MAPPED(a) \ + ( (*(const apr_uint64_t *)(const void *)(&(a)->s6_addr[0]) == 0) \ + && (*(const apr_uint32_t *)(const void *)(&(a)->s6_addr[8]) == ntohl(0x0000ffff))) +#endif + +#endif /* APR_HAVE_IPV6 */ + +#ifdef __cplusplus +} +#endif + +/* Done with badly written headers, leave 'deprecated CRT' undeprecated + */ +#if defined(_MSC_VER) && _MSC_VER >= 1200 +#pragma warning(pop) +#if _MSC_VER >= 1400 +#pragma warning(disable: 4996) +#endif +#endif + +#endif /* WIN32 */ + +#endif /* APR_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr.h.in b/c/dependencies/windows/apr/x64/include/apr.h.in new file mode 100644 index 00000000..47d8b55a --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr.h.in @@ -0,0 +1,656 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef APR_H +#define APR_H + +/* GENERATED FILE WARNING! DO NOT EDIT apr.h + * + * You must modify apr.h.in instead. + * + * And please, make an effort to stub apr.hw and apr.hnw in the process. + */ + +/** + * @file apr.h + * @brief APR Platform Definitions + * @remark This is a generated header generated from include/apr.h.in by + * ./configure, or copied from include/apr.hw or include/apr.hnw + * for Win32 or Netware by those build environments, respectively. + */ + +/** + * @defgroup APR Apache Portability Runtime library + * @{ + */ +/** + * @defgroup apr_platform Platform Definitions + * @{ + * @warning + * The actual values of macros and typedefs on this page
+ * are platform specific and should NOT be relied upon!
+ */ + +/* So that we can use inline on some critical functions, and use + * GNUC attributes (such as to get -Wall warnings for printf-like + * functions). Only do this in gcc 2.7 or later ... it may work + * on earlier stuff, but why chance it. + * + * We've since discovered that the gcc shipped with NeXT systems + * as "cc" is completely broken. It claims to be __GNUC__ and so + * on, but it doesn't implement half of the things that __GNUC__ + * means. In particular it's missing inline and the __attribute__ + * stuff. So we hack around it. PR#1613. -djg + */ +#if !defined(__GNUC__) || __GNUC__ < 2 || \ + (__GNUC__ == 2 && __GNUC_MINOR__ < 7) ||\ + defined(NEXT) +#ifndef __attribute__ +#define __attribute__(__x) +#endif +#define APR_INLINE +#define APR_HAS_INLINE 0 +#else +#define APR_INLINE __inline__ +#define APR_HAS_INLINE 1 +#endif + +#define APR_HAVE_ARPA_INET_H @arpa_ineth@ +#define APR_HAVE_CONIO_H @conioh@ +#define APR_HAVE_CRYPT_H @crypth@ +#define APR_HAVE_CTYPE_H @ctypeh@ +#define APR_HAVE_DIRENT_H @direnth@ +#define APR_HAVE_ERRNO_H @errnoh@ +#define APR_HAVE_FCNTL_H @fcntlh@ +#define APR_HAVE_IO_H @ioh@ +#define APR_HAVE_LIMITS_H @limitsh@ +#define APR_HAVE_NETDB_H @netdbh@ +#define APR_HAVE_NETINET_IN_H @netinet_inh@ +#define APR_HAVE_NETINET_SCTP_H @netinet_sctph@ +#define APR_HAVE_NETINET_SCTP_UIO_H @netinet_sctp_uioh@ +#define APR_HAVE_NETINET_TCP_H @netinet_tcph@ +#define APR_HAVE_PROCESS_H @processh@ +#define APR_HAVE_PTHREAD_H @pthreadh@ +#define APR_HAVE_SEMAPHORE_H @semaphoreh@ +#define APR_HAVE_SIGNAL_H @signalh@ +#define APR_HAVE_STDARG_H @stdargh@ +#define APR_HAVE_STDINT_H @stdint@ +#define APR_HAVE_STDIO_H @stdioh@ +#define APR_HAVE_STDLIB_H @stdlibh@ +#define APR_HAVE_STRING_H @stringh@ +#define APR_HAVE_STRINGS_H @stringsh@ +#define APR_HAVE_INTTYPES_H @inttypesh@ +#define APR_HAVE_SYS_IOCTL_H @sys_ioctlh@ +#define APR_HAVE_SYS_SENDFILE_H @sys_sendfileh@ +#define APR_HAVE_SYS_SIGNAL_H @sys_signalh@ +#define APR_HAVE_SYS_SOCKET_H @sys_socketh@ +#define APR_HAVE_SYS_SOCKIO_H @sys_sockioh@ +#define APR_HAVE_SYS_SYSLIMITS_H @sys_syslimitsh@ +#define APR_HAVE_SYS_TIME_H @sys_timeh@ +#define APR_HAVE_SYS_TYPES_H @sys_typesh@ +#define APR_HAVE_SYS_UIO_H @sys_uioh@ +#define APR_HAVE_SYS_UN_H @sys_unh@ +#define APR_HAVE_SYS_WAIT_H @sys_waith@ +#define APR_HAVE_TIME_H @timeh@ +#define APR_HAVE_UNISTD_H @unistdh@ +#define APR_HAVE_WINDOWS_H @windowsh@ +#define APR_HAVE_WINSOCK2_H @winsock2h@ + +/** @} */ +/** @} */ + +/* We don't include our conditional headers within the doxyblocks + * or the extern "C" namespace + */ + +#if APR_HAVE_WINDOWS_H && defined(WIN32) +/* If windows.h was already included, our preferences don't matter. + * If not, include a restricted set of windows headers to our tastes. + */ +#ifndef _WINDOWS_ + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif + +#ifndef _WIN32_WINNT +/* Restrict the server to a subset of Windows XP header files by default + */ +#define _WIN32_WINNT 0x0501 +#endif + +#ifndef NOUSER +#define NOUSER +#endif +#ifndef NOMCX +#define NOMCX +#endif +#ifndef NOIME +#define NOIME +#endif + +#include +/* + * Add a _very_few_ declarations missing from the restricted set of headers + * (If this list becomes extensive, re-enable the required headers above!) + * winsock headers were excluded by WIN32_LEAN_AND_MEAN, so include them now + */ +#define SW_HIDE 0 +#ifndef _WIN32_WCE +#include +#include +#include +#else +#include +#endif + +#endif /* ndef _WINDOWS_ */ +#endif /* APR_HAVE_WINDOWS_H */ + +#if APR_HAVE_SYS_TYPES_H +#include +#endif + +#if APR_HAVE_SYS_SOCKET_H +#include +#endif + +#if APR_HAVE_STDINT_H +#ifdef __cplusplus +/* C99 7.18.4 requires that stdint.h only exposes INT64_C + * and UINT64_C for C++ implementations if this is defined: */ +#ifndef __STDC_CONSTANT_MACROS +#define __STDC_CONSTANT_MACROS +#endif +/* C++ needs this too for PRI*NN formats: */ +#ifndef __STDC_FORMAT_MACROS +#define __STDC_FORMAT_MACROS +#endif +#endif /* __cplusplus */ +#include +#endif + +#if APR_HAVE_INTTYPES_H +#include +#endif + +#if APR_HAVE_SYS_WAIT_H +#include +#endif + +#ifdef OS2 +#define INCL_DOS +#define INCL_DOSERRORS +#include +#endif + +/* header files for PATH_MAX, _POSIX_PATH_MAX */ +#if APR_HAVE_LIMITS_H +#include +#else +#if APR_HAVE_SYS_SYSLIMITS_H +#include +#endif +#endif + +/* __APPLE__ is now the official pre-defined macro for macOS */ +#ifdef __APPLE__ +#undef DARWIN +#undef DARWIN_10 +#define DARWIN +#define DARWIN_10 +#endif /* __APPLE__ */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @addtogroup apr_platform + * @ingroup APR + * @{ + */ + +#define APR_HAVE_SHMEM_MMAP_TMP @havemmaptmp@ +#define APR_HAVE_SHMEM_MMAP_SHM @havemmapshm@ +#define APR_HAVE_SHMEM_MMAP_ZERO @havemmapzero@ +#define APR_HAVE_SHMEM_SHMGET_ANON @haveshmgetanon@ +#define APR_HAVE_SHMEM_SHMGET @haveshmget@ +#define APR_HAVE_SHMEM_MMAP_ANON @havemmapanon@ +#define APR_HAVE_SHMEM_BEOS @havebeosarea@ + +#define APR_USE_SHMEM_MMAP_TMP @usemmaptmp@ +#define APR_USE_SHMEM_MMAP_SHM @usemmapshm@ +#define APR_USE_SHMEM_MMAP_ZERO @usemmapzero@ +#define APR_USE_SHMEM_SHMGET_ANON @useshmgetanon@ +#define APR_USE_SHMEM_SHMGET @useshmget@ +#define APR_USE_SHMEM_MMAP_ANON @usemmapanon@ +#define APR_USE_SHMEM_BEOS @usebeosarea@ + +#define APR_USE_FLOCK_SERIALIZE @flockser@ +#define APR_USE_SYSVSEM_SERIALIZE @sysvser@ +#define APR_USE_POSIXSEM_SERIALIZE @posixser@ +#define APR_USE_FCNTL_SERIALIZE @fcntlser@ +#define APR_USE_PROC_PTHREAD_SERIALIZE @procpthreadser@ +#define APR_USE_PTHREAD_SERIALIZE @pthreadser@ + +#define APR_HAS_FLOCK_SERIALIZE @hasflockser@ +#define APR_HAS_SYSVSEM_SERIALIZE @hassysvser@ +#define APR_HAS_POSIXSEM_SERIALIZE @hasposixser@ +#define APR_HAS_FCNTL_SERIALIZE @hasfcntlser@ +#define APR_HAS_PROC_PTHREAD_SERIALIZE @hasprocpthreadser@ + +#define APR_PROCESS_LOCK_IS_GLOBAL @proclockglobal@ + +#define APR_HAVE_CORKABLE_TCP @have_corkable_tcp@ +#define APR_HAVE_GETRLIMIT @have_getrlimit@ +#define APR_HAVE_IN_ADDR @have_in_addr@ +#define APR_HAVE_INET_ADDR @have_inet_addr@ +#define APR_HAVE_INET_NETWORK @have_inet_network@ +#define APR_HAVE_IPV6 @have_ipv6@ +#define APR_HAVE_SOCKADDR_UN @have_sockaddr_un@ +#define APR_HAVE_MEMMOVE @have_memmove@ +#define APR_HAVE_SETRLIMIT @have_setrlimit@ +#define APR_HAVE_SIGACTION @have_sigaction@ +#define APR_HAVE_SIGSUSPEND @have_sigsuspend@ +#define APR_HAVE_SIGWAIT @have_sigwait@ +#define APR_HAVE_SA_STORAGE @have_sa_storage@ +#define APR_HAVE_STRCASECMP @have_strcasecmp@ +#define APR_HAVE_STRDUP @have_strdup@ +#define APR_HAVE_STRICMP @have_stricmp@ +#define APR_HAVE_STRNCASECMP @have_strncasecmp@ +#define APR_HAVE_STRNICMP @have_strnicmp@ +#define APR_HAVE_STRSTR @have_strstr@ +#define APR_HAVE_MEMCHR @have_memchr@ +#define APR_HAVE_STRUCT_RLIMIT @struct_rlimit@ +#define APR_HAVE_UNION_SEMUN @have_union_semun@ +#define APR_HAVE_SCTP @have_sctp@ +#define APR_HAVE_IOVEC @have_iovec@ + +/* APR Feature Macros */ +#define APR_HAS_SHARED_MEMORY @sharedmem@ +#define APR_HAS_THREADS @threads@ +#define APR_HAS_SENDFILE @sendfile@ +#define APR_HAS_MMAP @mmap@ +#define APR_HAS_FORK @fork@ +#define APR_HAS_RANDOM @rand@ +#define APR_HAS_OTHER_CHILD @oc@ +#define APR_HAS_DSO @aprdso@ +#define APR_HAS_SO_ACCEPTFILTER @acceptfilter@ +#define APR_HAS_UNICODE_FS @have_unicode_fs@ +#define APR_HAS_PROC_INVOKED @have_proc_invoked@ +#define APR_HAS_USER @apr_has_user@ +#define APR_HAS_LARGE_FILES @aprlfs@ +#define APR_HAS_XTHREAD_FILES @apr_has_xthread_files@ +#define APR_HAS_OS_UUID @osuuid@ +#define APR_HAS_TIMEDLOCKS @apr_has_timedlocks@ + +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD @apr_procattr_user_set_requires_password@ + +/* APR sets APR_FILES_AS_SOCKETS to 1 on systems where it is possible + * to poll on files/pipes. + */ +#define APR_FILES_AS_SOCKETS @file_as_socket@ + +/* This macro indicates whether or not EBCDIC is the native character set. + */ +#define APR_CHARSET_EBCDIC @apr_charset_ebcdic@ + +/* If we have a TCP implementation that can be "corked", what flag + * do we use? + */ +#define APR_TCP_NOPUSH_FLAG @apr_tcp_nopush_flag@ + +/* Is the TCP_NODELAY socket option inherited from listening sockets? +*/ +#define APR_TCP_NODELAY_INHERITED @tcp_nodelay_inherited@ + +/* Is the O_NONBLOCK flag inherited from listening sockets? +*/ +#define APR_O_NONBLOCK_INHERITED @o_nonblock_inherited@ + +/* Typedefs that APR needs. */ + +typedef unsigned char apr_byte_t; + +typedef @short_value@ apr_int16_t; +typedef unsigned @short_value@ apr_uint16_t; + +typedef @int_value@ apr_int32_t; +typedef unsigned @int_value@ apr_uint32_t; + +#define APR_SIZEOF_VOIDP @voidp_size@ + +/* + * Darwin 10's default compiler (gcc42) builds for both 64 and + * 32 bit architectures unless specifically told not to. + * In those cases, we need to override types depending on how + * we're being built at compile time. + * NOTE: This is an ugly work-around for Darwin's + * concept of universal binaries, a single package + * (executable, lib, etc...) which contains both 32 + * and 64 bit versions. The issue is that if APR is + * built universally, if something else is compiled + * against it, some bit sizes will depend on whether + * it is 32 or 64 bit. This is determined by the __LP64__ + * flag. Since we need to support both, we have to + * handle OS X unqiuely. + */ +#ifdef DARWIN_10 +#undef APR_SIZEOF_VOIDP +#undef APR_INT64_C +#undef APR_UINT64_C +#ifdef __LP64__ + typedef long apr_int64_t; + typedef unsigned long apr_uint64_t; + #define APR_SIZEOF_VOIDP 8 + #define APR_INT64_C(v) (v ## L) + #define APR_UINT64_C(v) (v ## UL) +#else + typedef long long apr_int64_t; + typedef unsigned long long apr_uint64_t; + #define APR_SIZEOF_VOIDP 4 + #define APR_INT64_C(v) (v ## LL) + #define APR_UINT64_C(v) (v ## ULL) +#endif +#else + typedef @int64_value@ apr_int64_t; + typedef @uint64_value@ apr_uint64_t; + + /* Mechanisms to properly type numeric literals */ + @int64_literal@ + @uint64_literal@ +#endif + +typedef @size_t_value@ apr_size_t; +typedef @ssize_t_value@ apr_ssize_t; +typedef @off_t_value@ apr_off_t; +typedef @socklen_t_value@ apr_socklen_t; +typedef @ino_t_value@ apr_ino_t; + +#if APR_SIZEOF_VOIDP == 8 +typedef apr_uint64_t apr_uintptr_t; +#else +typedef apr_uint32_t apr_uintptr_t; +#endif + +/* Are we big endian? */ +#define APR_IS_BIGENDIAN @bigendian@ + +#ifdef INT16_MIN +#define APR_INT16_MIN INT16_MIN +#else +#define APR_INT16_MIN (-0x7fff - 1) +#endif + +#ifdef INT16_MAX +#define APR_INT16_MAX INT16_MAX +#else +#define APR_INT16_MAX (0x7fff) +#endif + +#ifdef UINT16_MAX +#define APR_UINT16_MAX UINT16_MAX +#else +#define APR_UINT16_MAX (0xffff) +#endif + +#ifdef INT32_MIN +#define APR_INT32_MIN INT32_MIN +#else +#define APR_INT32_MIN (-0x7fffffff - 1) +#endif + +#ifdef INT32_MAX +#define APR_INT32_MAX INT32_MAX +#else +#define APR_INT32_MAX 0x7fffffff +#endif + +#ifdef UINT32_MAX +#define APR_UINT32_MAX UINT32_MAX +#else +#define APR_UINT32_MAX (0xffffffffU) +#endif + +#ifdef INT64_MIN +#define APR_INT64_MIN INT64_MIN +#else +#define APR_INT64_MIN (APR_INT64_C(-0x7fffffffffffffff) - 1) +#endif + +#ifdef INT64_MAX +#define APR_INT64_MAX INT64_MAX +#else +#define APR_INT64_MAX APR_INT64_C(0x7fffffffffffffff) +#endif + +#ifdef UINT64_MAX +#define APR_UINT64_MAX UINT64_MAX +#else +#define APR_UINT64_MAX APR_UINT64_C(0xffffffffffffffff) +#endif + +#define APR_SIZE_MAX (~((apr_size_t)0)) + + +/* Definitions that APR programs need to work properly. */ + +/** + * APR public API wrap for C++ compilers. + */ +#ifdef __cplusplus +#define APR_BEGIN_DECLS extern "C" { +#define APR_END_DECLS } +#else +#define APR_BEGIN_DECLS +#define APR_END_DECLS +#endif + +/** + * Thread callbacks from APR functions must be declared with APR_THREAD_FUNC, + * so that they follow the platform's calling convention. + *
+ *
+ * void* APR_THREAD_FUNC my_thread_entry_fn(apr_thread_t *thd, void *data);
+ *
+ * 
+ */ +#define APR_THREAD_FUNC @apr_thread_func@ + +#if defined(DOXYGEN) || !defined(WIN32) + +/** + * The public APR functions are declared with APR_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APR_DECLARE_NONSTD(). + * + * @remark Both the declaration and implementations must use the same macro. + * + *
+ * APR_DECLARE(rettype) apr_func(args)
+ * 
+ * @see APR_DECLARE_NONSTD @see APR_DECLARE_DATA + * @remark Note that when APR compiles the library itself, it passes the + * symbol -DAPR_DECLARE_EXPORT to the compiler on some platforms (e.g. Win32) + * to export public symbols from the dynamic library build.\n + * The user must define the APR_DECLARE_STATIC when compiling to target + * the static APR library on some platforms (e.g. Win32.) The public symbols + * are neither exported nor imported when APR_DECLARE_STATIC is defined.\n + * By default, compiling an application and including the APR public + * headers, without defining APR_DECLARE_STATIC, will prepare the code to be + * linked to the dynamic library. + */ +#define APR_DECLARE(type) type + +/** + * The public APR functions using variable arguments are declared with + * APR_DECLARE_NONSTD(), as they must follow the C language calling convention. + * @see APR_DECLARE @see APR_DECLARE_DATA + * @remark Both the declaration and implementations must use the same macro. + *
+ *
+ * APR_DECLARE_NONSTD(rettype) apr_func(args, ...);
+ *
+ * 
+ */ +#define APR_DECLARE_NONSTD(type) type + +/** + * The public APR variables are declared with AP_MODULE_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * @see APR_DECLARE @see APR_DECLARE_NONSTD + * @remark Note that the declaration and implementations use different forms, + * but both must include the macro. + * + *
+ *
+ * extern APR_DECLARE_DATA type apr_variable;\n
+ * APR_DECLARE_DATA type apr_variable = value;
+ *
+ * 
+ */ +#define APR_DECLARE_DATA + +#elif defined(APR_DECLARE_STATIC) +#define APR_DECLARE(type) type __stdcall +#define APR_DECLARE_NONSTD(type) type __cdecl +#define APR_DECLARE_DATA +#elif defined(APR_DECLARE_EXPORT) +#define APR_DECLARE(type) __declspec(dllexport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllexport) +#else +#define APR_DECLARE(type) __declspec(dllimport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllimport) +#endif + +/* Define APR_SSIZE_T_FMT. + * If ssize_t is an integer we define it to be "d", + * if ssize_t is a long int we define it to be "ld", + * if ssize_t is neither we declare an error here. + * I looked for a better way to define this here, but couldn't find one, so + * to find the logic for this definition search for "ssize_t_fmt" in + * configure.in. + */ + +@ssize_t_fmt@ + +/* And APR_SIZE_T_FMT */ +@size_t_fmt@ + +/* And APR_OFF_T_FMT */ +@off_t_fmt@ + +/* And APR_PID_T_FMT */ +@pid_t_fmt@ + +/* And APR_INT64_T_FMT */ +@int64_t_fmt@ + +/* And APR_UINT64_T_FMT */ +@uint64_t_fmt@ + +/* And APR_UINT64_T_HEX_FMT */ +@uint64_t_hex_fmt@ + +/* + * Ensure we work with universal binaries on Darwin + */ +#ifdef DARWIN_10 + +#undef APR_HAS_LARGE_FILES +#undef APR_SIZEOF_VOIDP +#undef APR_INT64_T_FMT +#undef APR_UINT64_T_FMT +#undef APR_UINT64_T_HEX_FMT + +#ifdef __LP64__ + #define APR_HAS_LARGE_FILES 0 + #define APR_SIZEOF_VOIDP 8 + #define APR_INT64_T_FMT "ld" + #define APR_UINT64_T_FMT "lu" + #define APR_UINT64_T_HEX_FMT "lx" +#else + #define APR_HAS_LARGE_FILES 1 + #define APR_SIZEOF_VOIDP 4 + #define APR_INT64_T_FMT "lld" + #define APR_UINT64_T_FMT "llu" + #define APR_UINT64_T_HEX_FMT "llx" +#endif + +#undef APR_IS_BIGENDIAN +#ifdef __BIG_ENDIAN__ + #define APR_IS_BIGENDIAN 1 +#else + #define APR_IS_BIGENDIAN 0 +#endif + +#undef APR_OFF_T_FMT +#define APR_OFF_T_FMT "lld" + +#endif /* DARWIN_10 */ + +/* Does the proc mutex lock threads too */ +#define APR_PROC_MUTEX_IS_GLOBAL @proc_mutex_is_global@ + +/* Local machine definition for console and log output. */ +#define APR_EOL_STR "@eolstr@" + +#if APR_HAVE_SYS_WAIT_H +#ifdef WEXITSTATUS +#define apr_wait_t int +#else +#define apr_wait_t union wait +#define WEXITSTATUS(status) (int)((status).w_retcode) +#define WTERMSIG(status) (int)((status).w_termsig) +#endif /* !WEXITSTATUS */ +#elif defined(__MINGW32__) +typedef int apr_wait_t; +#endif /* HAVE_SYS_WAIT_H */ + +#if defined(PATH_MAX) +#define APR_PATH_MAX PATH_MAX +#elif defined(_POSIX_PATH_MAX) +#define APR_PATH_MAX _POSIX_PATH_MAX +#else +#error no decision has been made on APR_PATH_MAX for your platform +#endif + +#define APR_DSOPATH "@shlibpath_var@" + +/** @} */ + +/* Definitions that only Win32 programs need to compile properly. */ + +/* XXX These simply don't belong here, perhaps in apr_portable.h + * based on some APR_HAVE_PID/GID/UID? + */ +#ifdef __MINGW32__ +#ifndef __GNUC__ +typedef int pid_t; +#endif +typedef int uid_t; +typedef int gid_t; +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* APR_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr.hnw b/c/dependencies/windows/apr/x64/include/apr.hnw new file mode 100644 index 00000000..21c8a98e --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr.hnw @@ -0,0 +1,445 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef APR_H +#define APR_H + +/* GENERATED FILE WARNING! DO NOT EDIT apr.h + * + * You must modify apr.hnw instead. + * + * And please, make an effort to stub apr.hw and apr.h.in in the process. + * + * This is the NetWare specific version of apr.h. It is copied from + * apr.hnw at the start of a NetWare build by the ./build/NWGNmakefile. + */ + +/** + * @file apr.h + * @brief APR Platform Definitions + * @remark This is a generated header generated from include/apr.h.in by + * ./configure, or copied from include/apr.hw or include/apr.hnw + * for Win32 or Netware by those build environments, respectively. + */ + +#if defined(NETWARE) || defined(DOXYGEN) + +#undef FD_SETSIZE +#define FD_SETSIZE 1024 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef USE_WINSOCK +#include +#ifdef NW_BUILD_IPV6 +#include +#endif +#else +#include +#include +#endif +#include + +#define _POSIX_THREAD_SAFE_FUNCTIONS 1 +#define READDIR_IS_THREAD_SAFE 1 + +/* Keep #include'd headers from within the __cplusplus or doxyblocks */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_platform Platform Definitions + * @ingroup APR + * @{ + */ + +#define APR_INLINE +#define APR_HAS_INLINE 0 +#ifndef __attribute__ +#define __attribute__(__x) +#endif +#define ENUM_BITFIELD(e,n,w) signed int n : w + +#define APR_HAVE_CONIO_H 0 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 1 +#define APR_HAVE_DIRENT_H 1 +#define APR_HAVE_ERRNO_H 1 +#define APR_HAVE_FCNTL_H 1 +#define APR_HAVE_IO_H 0 +#define APR_HAVE_LIMITS_H 1 +#ifdef USE_WINSOCK +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#else +#define APR_HAVE_ARPA_INET_H 1 +#define APR_HAVE_NETDB_H 1 +#define APR_HAVE_NETINET_IN_H 1 +#endif +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SIGNAL_H 1 +#define APR_HAVE_STDARG_H 1 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_STRTOLL 1 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#ifdef USE_WINSOCK +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#else +#define APR_HAVE_SYS_SOCKET_H 1 +#define APR_HAVE_SYS_SOCKIO_H 1 +#define APR_HAVE_SYS_UN_H 1 +#endif +#define APR_HAVE_SYS_SIGNAL_H 1 +#define APR_HAVE_SYS_TIME_H 1 +#define APR_HAVE_SYS_TYPES_H 1 +#define APR_HAVE_SYS_UIO_H 1 +#define APR_HAVE_SYS_WAIT_H 1 +#define APR_HAVE_TIME_H 1 +#define APR_HAVE_UNISTD_H 1 + +#define APR_HAVE_SHMEM_MMAP_TMP 0 +#define APR_HAVE_SHMEM_MMAP_SHM 0 +#define APR_HAVE_SHMEM_MMAP_ZERO 0 +#define APR_HAVE_SHMEM_SHMGET_ANON 0 +#define APR_HAVE_SHMEM_SHMGET 0 +#define APR_HAVE_SHMEM_MMAP_ANON 0 +#define APR_HAVE_SHMEM_BEOS 0 + +#define APR_USE_SHMEM_MMAP_TMP 0 +#define APR_USE_SHMEM_MMAP_SHM 0 +#define APR_USE_SHMEM_MMAP_ZERO 0 +#define APR_USE_SHMEM_SHMGET_ANON 0 +#define APR_USE_SHMEM_SHMGET 0 +#define APR_USE_SHMEM_MMAP_ANON 0 +#define APR_USE_SHMEM_BEOS 0 + +#define APR_USE_FLOCK_SERIALIZE 0 +#define APR_USE_SYSVSEM_SERIALIZE 0 +#define APR_USE_FCNTL_SERIALIZE 0 +#define APR_USE_PROC_PTHREAD_SERIALIZE 0 +#define APR_USE_PTHREAD_SERIALIZE 0 + +#define APR_HAS_FLOCK_SERIALIZE 0 +#define APR_HAS_SYSVSEM_SERIALIZE 0 +#define APR_HAS_FCNTL_SERIALIZE 0 +#define APR_HAS_PROC_PTHREAD_SERIALIZE 0 +#define APR_HAS_RWLOCK_SERIALIZE 0 + +#define APR_HAS_LOCK_CREATE_NP 0 + +#define APR_PROCESS_LOCK_IS_GLOBAL 1 + +#define APR_FILE_BASED_SHM 0 + +#define APR_HAVE_CORKABLE_TCP 0 +#define APR_HAVE_GETRLIMIT 0 +#define APR_HAVE_ICONV 0 +#define APR_HAVE_IN_ADDR 1 +#define APR_HAVE_INET_ADDR 1 +#define APR_HAVE_INET_NETWORK 0 +#ifdef NW_BUILD_IPV6 +#define APR_HAVE_IPV6 1 +#else +#define APR_HAVE_IPV6 0 +#endif +#define APR_HAVE_SOCKADDR_UN 0 +#define APR_HAVE_MEMCHR 1 +#define APR_HAVE_MEMMOVE 1 +#define APR_HAVE_SETRLIMIT 0 +#define APR_HAVE_SIGACTION 0 +#define APR_HAVE_SIGSUSPEND 0 +#define APR_HAVE_SIGWAIT 0 +#define APR_HAVE_STRCASECMP 1 +#define APR_HAVE_STRDUP 1 +#define APR_HAVE_STRICMP 1 +#define APR_HAVE_STRNCASECMP 1 +#define APR_HAVE_STRNICMP 1 +#define APR_HAVE_STRSTR 1 +#define APR_HAVE_STRUCT_RLIMIT 0 +#define APR_HAVE_UNION_SEMUN 0 +#define APR_HAVE_SCTP 0 +#define APR_HAVE_IOVEC 1 + +/* APR Feature Macros */ +#define APR_HAS_SHARED_MEMORY 0 +#define APR_HAS_THREADS 1 +#define APR_HAS_SENDFILE 0 +#define APR_HAS_MMAP 0 +#define APR_HAS_FORK 0 +#define APR_HAS_RANDOM 1 +#define APR_HAS_OTHER_CHILD 0 +#define APR_HAS_DSO 1 +#define APR_HAS_SO_ACCEPTFILTER 0 +#define APR_HAS_UNICODE_FS 0 +#define APR_HAS_PROC_INVOKED 0 +#define APR_HAS_USER 1 +#define APR_HAS_LARGE_FILES 1 +#define APR_HAS_XTHREAD_FILES 0 +#define APR_HAS_OS_UUID 0 +#define APR_HAS_TIMEDLOCKS 1 + +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 0 + +/* Netware can poll on files/pipes. + */ +#define APR_FILES_AS_SOCKETS 1 + +/* This macro indicates whether or not EBCDIC is the native character set. + */ +#define APR_CHARSET_EBCDIC 0 + +/* Is the TCP_NODELAY socket option inherited from listening sockets? +*/ +#define APR_TCP_NODELAY_INHERITED 1 + +/* Is the O_NONBLOCK flag inherited from listening sockets? +*/ +#define APR_O_NONBLOCK_INHERITED 1 + +/* Typedefs that APR needs. */ + +typedef unsigned char apr_byte_t; + +typedef short apr_int16_t; +typedef unsigned short apr_uint16_t; + +typedef int apr_int32_t; +typedef unsigned int apr_uint32_t; + +typedef long long apr_int64_t; +typedef unsigned long long apr_uint64_t; + +typedef size_t apr_size_t; +typedef ssize_t apr_ssize_t; +#if APR_HAS_LARGE_FILES +typedef off64_t apr_off_t; +#else +typedef off_t apr_off_t; +#endif +#ifdef USE_WINSOCK +typedef int apr_socklen_t; +#else +typedef size_t apr_socklen_t; +#endif +typedef apr_uint64_t apr_ino_t; + +/* Are we big endian? */ +/* XXX: Fatal assumption on Alpha platforms */ +#define APR_IS_BIGENDIAN 0 + +#ifdef UNKNOWN_NETWARE_64BIT_FLAG_NEEDED +#define APR_SIZEOF_VOIDP 8 +#else +#define APR_SIZEOF_VOIDP 4 +#endif + +#if APR_SIZEOF_VOIDP == 8 +typedef apr_uint64_t apr_uintptr_t; +#else +typedef apr_uint32_t apr_uintptr_t; +#endif + +/* Mechanisms to properly type numeric literals */ +#define APR_INT64_C(val) (val##LL) +#define APR_UINT64_C(val) (val##ULL) + +#ifdef INT16_MIN +#define APR_INT16_MIN INT16_MIN +#else +#define APR_INT16_MIN (-0x7fff - 1) +#endif + +#ifdef INT16_MAX +#define APR_INT16_MAX INT16_MAX +#else +#define APR_INT16_MAX (0x7fff) +#endif + +#ifdef UINT16_MAX +#define APR_UINT16_MAX UINT16_MAX +#else +#define APR_UINT16_MAX (0xffff) +#endif + +#ifdef INT32_MIN +#define APR_INT32_MIN INT32_MIN +#else +#define APR_INT32_MIN (-0x7fffffff - 1) +#endif + +#ifdef INT32_MAX +#define APR_INT32_MAX INT32_MAX +#else +#define APR_INT32_MAX 0x7fffffff +#endif + +#ifdef UINT32_MAX +#define APR_UINT32_MAX UINT32_MAX +#else +#define APR_UINT32_MAX (0xffffffffU) +#endif + +#ifdef INT64_MIN +#define APR_INT64_MIN INT64_MIN +#else +#define APR_INT64_MIN (APR_INT64_C(-0x7fffffffffffffff) - 1) +#endif + +#ifdef INT64_MAX +#define APR_INT64_MAX INT64_MAX +#else +#define APR_INT64_MAX APR_INT64_C(0x7fffffffffffffff) +#endif + +#ifdef UINT64_MAX +#define APR_UINT64_MAX UINT64_MAX +#else +#define APR_UINT64_MAX APR_UINT64_C(0xffffffffffffffff) +#endif + +#define APR_SIZE_MAX (~((apr_size_t)0)) + +/* PROC mutex is a GLOBAL mutex on Netware */ +#define APR_PROC_MUTEX_IS_GLOBAL 1 + +/* Definitions that APR programs need to work properly. */ + +/** + * APR public API wrap for C++ compilers. + */ +#ifdef __cplusplus +#define APR_BEGIN_DECLS extern "C" { +#define APR_END_DECLS } +#else +#define APR_BEGIN_DECLS +#define APR_END_DECLS +#endif + +/** + * Thread callbacks from APR functions must be declared with APR_THREAD_FUNC, + * so that they follow the platform's calling convention. + * @example + */ +/** void* APR_THREAD_FUNC my_thread_entry_fn(apr_thread_t *thd, void *data); + */ +#define APR_THREAD_FUNC + +/** + * The public APR functions are declared with APR_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APR_DECLARE_NONSTD(). + * + * @remark Both the declaration and implementations must use the same macro. + * @example + */ +/** APR_DECLARE(rettype) apr_func(args) + * @see APR_DECLARE_NONSTD @see APR_DECLARE_DATA + * @remark Note that when APR compiles the library itself, it passes the + * symbol -DAPR_DECLARE_EXPORT to the compiler on some platforms (e.g. Win32) + * to export public symbols from the dynamic library build.\n + * The user must define the APR_DECLARE_STATIC when compiling to target + * the static APR library on some platforms (e.g. Win32.) The public symbols + * are neither exported nor imported when APR_DECLARE_STATIC is defined.\n + * By default, compiling an application and including the APR public + * headers, without defining APR_DECLARE_STATIC, will prepare the code to be + * linked to the dynamic library. + */ +#define APR_DECLARE(type) type + +/** + * The public APR functions using variable arguments are declared with + * APR_DECLARE_NONSTD(), as they must follow the C language calling convention. + * @see APR_DECLARE @see APR_DECLARE_DATA + * @remark Both the declaration and implementations must use the same macro. + * @example + */ +/** APR_DECLARE_NONSTD(rettype) apr_func(args, ...); + */ +#define APR_DECLARE_NONSTD(type) type + +/** + * The public APR variables are declared with APR_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * @see APR_DECLARE @see APR_DECLARE_NONSTD + * @remark Note that the declaration and implementations use different forms, + * but both must include the macro. + * @example + */ +/** extern APR_DECLARE_DATA type apr_variable;\n + * APR_DECLARE_DATA type apr_variable = value; + */ +#define APR_DECLARE_DATA + +#define APR_SSIZE_T_FMT "d" + +#define APR_SIZE_T_FMT "d" + +#if APR_HAS_LARGE_FILES +#define APR_OFF_T_FMT "lld" +#else +#define APR_OFF_T_FMT "ld" +#endif + +#define APR_PID_T_FMT "d" + +/* Local machine definition for console and log output. */ +#define APR_EOL_STR "\r\n" + +typedef int apr_wait_t; + +#define APR_PATH_MAX PATH_MAX + +#define APR_DSOPATH "PATH" + +#define APR_INT64_T_FMT "lld" +#define APR_UINT64_T_FMT "llu" +#define APR_UINT64_T_HEX_FMT "llx" +#define APR_TIME_T_FMT APR_INT64_T_FMT + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* NETWARE */ + +#endif /* APR_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr.hw b/c/dependencies/windows/apr/x64/include/apr.hw new file mode 100644 index 00000000..b8d97495 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr.hw @@ -0,0 +1,667 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef APR_H +#define APR_H + +/* GENERATED FILE WARNING! DO NOT EDIT apr.h + * + * You must modify apr.hw instead. + * + * And please, make an effort to stub apr.hnw and apr.h.in in the process. + * + * This is the Win32 specific version of apr.h. It is copied from + * apr.hw by the apr.dsp and libapr.dsp projects. + */ + +/** + * @file apr.h + * @brief APR Platform Definitions + * @remark This is a generated header generated from include/apr.h.in by + * ./configure, or copied from include/apr.hw or include/apr.hnw + * for Win32 or Netware by those build environments, respectively. + */ + +/* Make sure we have our platform identifier macro defined we ask for later. + */ +#if defined(_WIN32) && !defined(WIN32) +#define WIN32 1 +#endif + +#if defined(WIN32) || defined(DOXYGEN) + +/* Ignore most warnings (back down to /W3) for poorly constructed headers + */ +#if defined(_MSC_VER) && _MSC_VER >= 1200 +#pragma warning(push, 3) +#endif + +/* disable or reduce the frequency of... + * C4057: indirection to slightly different base types + * C4075: slight indirection changes (unsigned short* vs short[]) + * C4100: unreferenced formal parameter + * C4127: conditional expression is constant + * C4163: '_rotl64' : not available as an intrinsic function + * C4201: nonstandard extension nameless struct/unions + * C4244: int to char/short - precision loss + * C4514: unreferenced inline function removed + */ +#if defined(_MSC_VER) +#pragma warning(disable: 4100 4127 4163 4201 4514; once: 4057 4075 4244) +#endif + +/* Ignore Microsoft's interpretation of secure development + * and the POSIX string handling API + */ +#if defined(_MSC_VER) && _MSC_VER >= 1400 +#ifndef _CRT_SECURE_NO_DEPRECATE +#define _CRT_SECURE_NO_DEPRECATE +#endif +#pragma warning(disable: 4996) +#endif + +/* Has windows.h already been included? If so, our preferences don't matter, + * but we will still need the winsock things no matter what was included. + * If not, include a restricted set of windows headers to our tastes. + */ +#ifndef _WINDOWS_ +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef _WIN32_WINNT + +/* Restrict the server to a subset of Windows XP header files by default + */ +#define _WIN32_WINNT 0x0A00 +#endif +#ifndef NOUSER +#define NOUSER +#endif +#ifndef NOMCX +#define NOMCX +#endif +#ifndef NOIME +#define NOIME +#endif +#include +/* + * Add a _very_few_ declarations missing from the restricted set of headers + * (If this list becomes extensive, re-enable the required headers above!) + * winsock headers were excluded by WIN32_LEAN_AND_MEAN, so include them now + */ +#define SW_HIDE 0 +#ifndef _WIN32_WCE +#include +#include +#include +#else +#include +#endif +#endif /* !_WINDOWS_ */ + +/** + * @defgroup APR Apache Portability Runtime library + * @{ + */ +/** + * @defgroup apr_platform Platform Definitions + * @{ + * @warning + * The actual values of macros and typedefs on this page
+ * are platform specific and should NOT be relied upon!
+ */ + +#define APR_INLINE __inline +#define APR_HAS_INLINE 1 +#if !defined(__GNUC__) && !defined(__attribute__) +#define __attribute__(__x) +#endif + +#ifndef _WIN32_WCE +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_CONIO_H 1 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 1 +#define APR_HAVE_DIRENT_H 0 +#define APR_HAVE_ERRNO_H 1 +#define APR_HAVE_FCNTL_H 1 +#define APR_HAVE_IO_H 1 +#define APR_HAVE_LIMITS_H 1 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SEMAPHORE_H 0 +#define APR_HAVE_SIGNAL_H 1 +#define APR_HAVE_STDARG_H 1 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_SYS_IOCTL_H 0 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SIGNAL_H 0 +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#define APR_HAVE_SYS_TIME_H 0 +#define APR_HAVE_SYS_TYPES_H 1 +#define APR_HAVE_SYS_UIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#define APR_HAVE_SYS_WAIT_H 0 +#define APR_HAVE_TIME_H 1 +#define APR_HAVE_UNISTD_H 0 +#define APR_HAVE_STDDEF_H 1 +#define APR_HAVE_PROCESS_H 1 +#else +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_CONIO_H 0 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 0 +#define APR_HAVE_DIRENT_H 0 +#define APR_HAVE_ERRNO_H 0 +#define APR_HAVE_FCNTL_H 0 +#define APR_HAVE_IO_H 0 +#define APR_HAVE_LIMITS_H 0 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SEMAPHORE_H 0 +#define APR_HAVE_SIGNAL_H 0 +#define APR_HAVE_STDARG_H 0 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_SYS_IOCTL_H 0 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SIGNAL_H 0 +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#define APR_HAVE_SYS_TIME_H 0 +#define APR_HAVE_SYS_TYPES_H 0 +#define APR_HAVE_SYS_UIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#define APR_HAVE_SYS_WAIT_H 0 +#define APR_HAVE_TIME_H 0 +#define APR_HAVE_UNISTD_H 0 +#define APR_HAVE_STDDEF_H 0 +#define APR_HAVE_PROCESS_H 0 +#endif + +/** @} */ +/** @} */ + +/* We don't include our conditional headers within the doxyblocks + * or the extern "C" namespace + */ + +#if APR_HAVE_STDLIB_H +#include +#endif + +#if APR_HAVE_STDIO_H +#include +#endif + +#if APR_HAVE_SYS_TYPES_H +#include +#endif + +#if APR_HAVE_STDDEF_H +#include +#endif + +#if APR_HAVE_SYS_SOCKET_H +#include +#endif + +#if APR_HAVE_STDINT_H +#include +#endif + +#if APR_HAVE_SYS_WAIT_H +#include +#endif + +#if APR_HAVE_TIME_H +#include +#endif + +#if APR_HAVE_PROCESS_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @addtogroup apr_platform + * @ingroup APR + * @{ + */ + +#define APR_HAVE_SHMEM_MMAP_TMP 0 +#define APR_HAVE_SHMEM_MMAP_SHM 0 +#define APR_HAVE_SHMEM_MMAP_ZERO 0 +#define APR_HAVE_SHMEM_SHMGET_ANON 0 +#define APR_HAVE_SHMEM_SHMGET 0 +#define APR_HAVE_SHMEM_MMAP_ANON 0 +#define APR_HAVE_SHMEM_BEOS 0 + +#define APR_USE_SHMEM_MMAP_TMP 0 +#define APR_USE_SHMEM_MMAP_SHM 0 +#define APR_USE_SHMEM_MMAP_ZERO 0 +#define APR_USE_SHMEM_SHMGET_ANON 0 +#define APR_USE_SHMEM_SHMGET 0 +#define APR_USE_SHMEM_MMAP_ANON 0 +#define APR_USE_SHMEM_BEOS 0 + +#define APR_USE_FLOCK_SERIALIZE 0 +#define APR_USE_POSIXSEM_SERIALIZE 0 +#define APR_USE_SYSVSEM_SERIALIZE 0 +#define APR_USE_FCNTL_SERIALIZE 0 +#define APR_USE_PROC_PTHREAD_SERIALIZE 0 +#define APR_USE_PTHREAD_SERIALIZE 0 + +#define APR_HAS_FLOCK_SERIALIZE 0 +#define APR_HAS_SYSVSEM_SERIALIZE 0 +#define APR_HAS_POSIXSEM_SERIALIZE 0 +#define APR_HAS_FCNTL_SERIALIZE 0 +#define APR_HAS_PROC_PTHREAD_SERIALIZE 0 + +#define APR_PROCESS_LOCK_IS_GLOBAL 0 + +#define APR_HAVE_CORKABLE_TCP 0 +#define APR_HAVE_GETRLIMIT 0 +#define APR_HAVE_ICONV 0 +#define APR_HAVE_IN_ADDR 1 +#define APR_HAVE_INET_ADDR 1 +#define APR_HAVE_INET_NETWORK 0 +#define APR_HAVE_IPV6 1 +#define APR_HAVE_SOCKADDR_UN 0 +#define APR_HAVE_MEMMOVE 1 +#define APR_HAVE_SETRLIMIT 0 +#define APR_HAVE_SIGACTION 0 +#define APR_HAVE_SIGSUSPEND 0 +#define APR_HAVE_SIGWAIT 0 +#define APR_HAVE_SA_STORAGE 0 +#define APR_HAVE_STRCASECMP 0 +#define APR_HAVE_STRDUP 1 +#define APR_HAVE_STRNCASECMP 0 +#define APR_HAVE_STRSTR 1 +#define APR_HAVE_MEMCHR 1 +#define APR_HAVE_STRUCT_RLIMIT 0 +#define APR_HAVE_UNION_SEMUN 0 +#define APR_HAVE_SCTP 0 +#define APR_HAVE_IOVEC 0 + +#ifndef _WIN32_WCE +#define APR_HAVE_STRICMP 1 +#define APR_HAVE_STRNICMP 1 +#else +#define APR_HAVE_STRICMP 0 +#define APR_HAVE_STRNICMP 0 +#endif + +/* APR Feature Macros */ +#define APR_HAS_SHARED_MEMORY 1 +#define APR_HAS_THREADS 1 +#define APR_HAS_MMAP 1 +#define APR_HAS_FORK 0 +#define APR_HAS_RANDOM 1 +#define APR_HAS_OTHER_CHILD 1 +#define APR_HAS_DSO 1 +#define APR_HAS_SO_ACCEPTFILTER 0 +#define APR_HAS_UNICODE_FS 1 +#define APR_HAS_PROC_INVOKED 1 +#define APR_HAS_OS_UUID 1 +#define APR_HAS_TIMEDLOCKS 1 + +#ifndef _WIN32_WCE +#define APR_HAS_SENDFILE 1 +#define APR_HAS_USER 1 +#define APR_HAS_LARGE_FILES 1 +#define APR_HAS_XTHREAD_FILES 1 +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 1 +#else +#define APR_HAS_SENDFILE 0 +#define APR_HAS_USER 0 +#define APR_HAS_LARGE_FILES 0 +#define APR_HAS_XTHREAD_FILES 0 +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 0 +#endif + +/* APR sets APR_FILES_AS_SOCKETS to 1 on systems where it is possible + * to poll on files/pipes. + */ +#define APR_FILES_AS_SOCKETS 0 + +/* This macro indicates whether or not EBCDIC is the native character set. + */ +#define APR_CHARSET_EBCDIC 0 + +/* If we have a TCP implementation that can be "corked", what flag + * do we use? + */ +#define APR_TCP_NOPUSH_FLAG @apr_tcp_nopush_flag@ + +/* Is the TCP_NODELAY socket option inherited from listening sockets? + */ +#define APR_TCP_NODELAY_INHERITED 1 + +/* Is the O_NONBLOCK flag inherited from listening sockets? + */ +#define APR_O_NONBLOCK_INHERITED 1 + +/* Typedefs that APR needs. */ + +typedef unsigned char apr_byte_t; + +typedef short apr_int16_t; +typedef unsigned short apr_uint16_t; + +typedef int apr_int32_t; +typedef unsigned int apr_uint32_t; + +typedef __int64 apr_int64_t; +typedef unsigned __int64 apr_uint64_t; + +typedef size_t apr_size_t; +#if APR_HAVE_STDDEF_H +typedef ptrdiff_t apr_ssize_t; +#else +typedef int apr_ssize_t; +#endif +#if APR_HAS_LARGE_FILES +typedef __int64 apr_off_t; +#else +typedef int apr_off_t; +#endif +typedef int apr_socklen_t; +typedef apr_uint64_t apr_ino_t; + +#ifdef _WIN64 +#define APR_SIZEOF_VOIDP 8 +#else +#define APR_SIZEOF_VOIDP 4 +#endif + +#if APR_SIZEOF_VOIDP == 8 +typedef apr_uint64_t apr_uintptr_t; +#else +typedef apr_uint32_t apr_uintptr_t; +#endif + +/* Are we big endian? */ +/* XXX: Fatal assumption on Alpha platforms */ +#define APR_IS_BIGENDIAN 0 + +/* Mechanisms to properly type numeric literals */ + +#ifndef __GNUC__ +#define APR_INT64_C(val) (val##i64) +#define APR_UINT64_C(val) (val##Ui64) +#else +#define APR_INT64_C(val) (val##LL) +#define APR_UINT64_C(val) (val##ULL) +#endif + +#ifdef INT16_MIN +#define APR_INT16_MIN INT16_MIN +#else +#define APR_INT16_MIN (-0x7fff - 1) +#endif + +#ifdef INT16_MAX +#define APR_INT16_MAX INT16_MAX +#else +#define APR_INT16_MAX (0x7fff) +#endif + +#ifdef UINT16_MAX +#define APR_UINT16_MAX UINT16_MAX +#else +#define APR_UINT16_MAX (0xffff) +#endif + +#ifdef INT32_MIN +#define APR_INT32_MIN INT32_MIN +#else +#define APR_INT32_MIN (-0x7fffffff - 1) +#endif + +#ifdef INT32_MAX +#define APR_INT32_MAX INT32_MAX +#else +#define APR_INT32_MAX 0x7fffffff +#endif + +#ifdef UINT32_MAX +#define APR_UINT32_MAX UINT32_MAX +#else +#define APR_UINT32_MAX (0xffffffffU) +#endif + +#ifdef INT64_MIN +#define APR_INT64_MIN INT64_MIN +#else +#define APR_INT64_MIN (APR_INT64_C(-0x7fffffffffffffff) - 1) +#endif + +#ifdef INT64_MAX +#define APR_INT64_MAX INT64_MAX +#else +#define APR_INT64_MAX APR_INT64_C(0x7fffffffffffffff) +#endif + +#ifdef UINT64_MAX +#define APR_UINT64_MAX UINT64_MAX +#else +#define APR_UINT64_MAX APR_UINT64_C(0xffffffffffffffff) +#endif + +#define APR_SIZE_MAX (~((apr_size_t)0)) + +/* Definitions that APR programs need to work properly. */ + +/** + * APR public API wrap for C++ compilers. + */ +#ifdef __cplusplus +#define APR_BEGIN_DECLS extern "C" { +#define APR_END_DECLS } +#else +#define APR_BEGIN_DECLS +#define APR_END_DECLS +#endif + +/** + * Thread callbacks from APR functions must be declared with APR_THREAD_FUNC, + * so that they follow the platform's calling convention. + *
+ *
+ * void* APR_THREAD_FUNC my_thread_entry_fn(apr_thread_t *thd, void *data);
+ *
+ * 
+ */ +#define APR_THREAD_FUNC __stdcall + + +#if defined(DOXYGEN) || !defined(WIN32) + +/** + * The public APR functions are declared with APR_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APR_DECLARE_NONSTD(). + * + * @remark Both the declaration and implementations must use the same macro. + * + *
+ * APR_DECLARE(rettype) apr_func(args)
+ * 
+ * @see APR_DECLARE_NONSTD @see APR_DECLARE_DATA + * @remark Note that when APR compiles the library itself, it passes the + * symbol -DAPR_DECLARE_EXPORT to the compiler on some platforms (e.g. Win32) + * to export public symbols from the dynamic library build.\n + * The user must define the APR_DECLARE_STATIC when compiling to target + * the static APR library on some platforms (e.g. Win32.) The public symbols + * are neither exported nor imported when APR_DECLARE_STATIC is defined.\n + * By default, compiling an application and including the APR public + * headers, without defining APR_DECLARE_STATIC, will prepare the code to be + * linked to the dynamic library. + */ +#define APR_DECLARE(type) type + +/** + * The public APR functions using variable arguments are declared with + * APR_DECLARE_NONSTD(), as they must follow the C language calling convention. + * @see APR_DECLARE @see APR_DECLARE_DATA + * @remark Both the declaration and implementations must use the same macro. + *
+ *
+ * APR_DECLARE_NONSTD(rettype) apr_func(args, ...);
+ *
+ * 
+ */ +#define APR_DECLARE_NONSTD(type) type + +/** + * The public APR variables are declared with AP_MODULE_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * @see APR_DECLARE @see APR_DECLARE_NONSTD + * @remark Note that the declaration and implementations use different forms, + * but both must include the macro. + * + *
+ *
+ * extern APR_DECLARE_DATA type apr_variable;\n
+ * APR_DECLARE_DATA type apr_variable = value;
+ *
+ * 
+ */ +#define APR_DECLARE_DATA + +#elif defined(APR_DECLARE_STATIC) +#define APR_DECLARE(type) type __stdcall +#define APR_DECLARE_NONSTD(type) type __cdecl +#define APR_DECLARE_DATA +#elif defined(APR_DECLARE_EXPORT) +#define APR_DECLARE(type) __declspec(dllexport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllexport) +#else +#define APR_DECLARE(type) __declspec(dllimport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllimport) +#endif + +#ifdef _WIN64 +#define APR_SSIZE_T_FMT "I64d" +#define APR_SIZE_T_FMT "I64u" +#else +#define APR_SSIZE_T_FMT "d" +#define APR_SIZE_T_FMT "u" +#endif + +#if APR_HAS_LARGE_FILES +#define APR_OFF_T_FMT "I64d" +#else +#define APR_OFF_T_FMT "d" +#endif + +#define APR_PID_T_FMT "d" + +#define APR_INT64_T_FMT "I64d" +#define APR_UINT64_T_FMT "I64u" +#define APR_UINT64_T_HEX_FMT "I64x" + +/* No difference between PROC and GLOBAL mutex */ +#define APR_PROC_MUTEX_IS_GLOBAL 1 + +/* Local machine definition for console and log output. */ +#define APR_EOL_STR "\r\n" + +typedef int apr_wait_t; + +#if APR_HAS_UNICODE_FS +/* An arbitrary size that is digestable. True max is a bit less than 32000 */ +#define APR_PATH_MAX 8192 +#else /* !APR_HAS_UNICODE_FS */ +#define APR_PATH_MAX MAX_PATH +#endif + +#define APR_DSOPATH "PATH" + +/** @} */ + +/* Definitions that only Win32 programs need to compile properly. */ + +/* XXX These simply don't belong here, perhaps in apr_portable.h + * based on some APR_HAVE_PID/GID/UID? + */ +#ifndef __GNUC__ +typedef int pid_t; +#endif +typedef int uid_t; +typedef int gid_t; + +/* Win32 .h ommissions we really need */ +#define STDIN_FILENO 0 +#define STDOUT_FILENO 1 +#define STDERR_FILENO 2 + +#if APR_HAVE_IPV6 + +/* Appears in later flavors, not the originals. */ +#ifndef in_addr6 +#define in6_addr in_addr6 +#endif + +#ifndef WS2TCPIP_INLINE +#define IN6_IS_ADDR_V4MAPPED(a) \ + ( (*(const apr_uint64_t *)(const void *)(&(a)->s6_addr[0]) == 0) \ + && (*(const apr_uint32_t *)(const void *)(&(a)->s6_addr[8]) == ntohl(0x0000ffff))) +#endif + +#endif /* APR_HAVE_IPV6 */ + +#ifdef __cplusplus +} +#endif + +/* Done with badly written headers, leave 'deprecated CRT' undeprecated + */ +#if defined(_MSC_VER) && _MSC_VER >= 1200 +#pragma warning(pop) +#if _MSC_VER >= 1400 +#pragma warning(disable: 4996) +#endif +#endif + +#endif /* WIN32 */ + +#endif /* APR_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr.hwc b/c/dependencies/windows/apr/x64/include/apr.hwc new file mode 100644 index 00000000..ffb8368b --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr.hwc @@ -0,0 +1,664 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef APR_H +#define APR_H + +/* GENERATED FILE WARNING! DO NOT EDIT apr.h + * + * You must modify apr.hwc instead. + * + * And please, make an effort to stub apr.hnw and apr.h.in in the process. + * + * This is the Win32 specific version of apr.h. It is copied from + * apr.hw by the apr.dsp and libapr.dsp projects. + */ + +/** + * @file apr.h + * @brief APR Platform Definitions + * @remark This is a generated header generated from include/apr.h.in by + * ./configure, or copied from include/apr.hw or include/apr.hnw + * for Win32 or Netware by those build environments, respectively. + */ + +/* Make sure we have our platform identifier macro defined we ask for later. + */ +#if defined(_WIN32) && !defined(WIN32) +#define WIN32 1 +#endif + +#if defined(WIN32) || defined(DOXYGEN) + +/* Ignore most warnings (back down to /W3) for poorly constructed headers + */ +#if defined(_MSC_VER) && _MSC_VER >= 1200 +#pragma warning(push, 3) +#endif + +/* disable or reduce the frequency of... + * C4057: indirection to slightly different base types + * C4075: slight indirection changes (unsigned short* vs short[]) + * C4100: unreferenced formal parameter + * C4127: conditional expression is constant + * C4163: '_rotl64' : not available as an intrinsic function + * C4201: nonstandard extension nameless struct/unions + * C4244: int to char/short - precision loss + * C4514: unreferenced inline function removed + */ +#if defined(_MSC_VER) +#pragma warning(disable: 4100 4127 4163 4201 4514; once: 4057 4075 4244) +#endif + +/* Ignore Microsoft's interpretation of secure development + * and the POSIX string handling API + */ +#if defined(_MSC_VER) && _MSC_VER >= 1400 +#ifndef _CRT_SECURE_NO_DEPRECATE +#define _CRT_SECURE_NO_DEPRECATE +#endif +#pragma warning(disable: 4996) +#endif + +/* Has windows.h already been included? If so, our preferences don't matter, + * but we will still need the winsock things no matter what was included. + * If not, include a restricted set of windows headers to our tastes. + */ +#ifndef _WINDOWS_ +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef _WIN32_WINNT +#define _WIN32_WINNT @win32_winnt_str@ +#endif +#ifndef NOUSER +#define NOUSER +#endif +#ifndef NOMCX +#define NOMCX +#endif +#ifndef NOIME +#define NOIME +#endif +#include +/* + * Add a _very_few_ declarations missing from the restricted set of headers + * (If this list becomes extensive, re-enable the required headers above!) + * winsock headers were excluded by WIN32_LEAN_AND_MEAN, so include them now + */ +#define SW_HIDE 0 +#ifndef _WIN32_WCE +#include +#include +#include +#else +#include +#endif +#endif /* !_WINDOWS_ */ + +/** + * @defgroup APR Apache Portability Runtime library + * @{ + */ +/** + * @defgroup apr_platform Platform Definitions + * @{ + * @warning + * The actual values of macros and typedefs on this page
+ * are platform specific and should NOT be relied upon!
+ */ + +#define APR_INLINE __inline +#define APR_HAS_INLINE 1 +#if !defined(__GNUC__) && !defined(__attribute__) +#define __attribute__(__x) +#endif + +#ifndef _WIN32_WCE +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_CONIO_H 1 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 1 +#define APR_HAVE_DIRENT_H 0 +#define APR_HAVE_ERRNO_H 1 +#define APR_HAVE_FCNTL_H 1 +#define APR_HAVE_IO_H 1 +#define APR_HAVE_LIMITS_H 1 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SEMAPHORE_H 0 +#define APR_HAVE_SIGNAL_H 1 +#define APR_HAVE_STDARG_H 1 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_SYS_IOCTL_H 0 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SIGNAL_H 0 +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#define APR_HAVE_SYS_TIME_H 0 +#define APR_HAVE_SYS_TYPES_H 1 +#define APR_HAVE_SYS_UIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#define APR_HAVE_SYS_WAIT_H 0 +#define APR_HAVE_TIME_H 1 +#define APR_HAVE_UNISTD_H 0 +#define APR_HAVE_STDDEF_H 1 +#define APR_HAVE_PROCESS_H 1 +#else +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_CONIO_H 0 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 0 +#define APR_HAVE_DIRENT_H 0 +#define APR_HAVE_ERRNO_H 0 +#define APR_HAVE_FCNTL_H 0 +#define APR_HAVE_IO_H 0 +#define APR_HAVE_LIMITS_H 0 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SEMAPHORE_H 0 +#define APR_HAVE_SIGNAL_H 0 +#define APR_HAVE_STDARG_H 0 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_SYS_IOCTL_H 0 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SIGNAL_H 0 +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#define APR_HAVE_SYS_TIME_H 0 +#define APR_HAVE_SYS_TYPES_H 0 +#define APR_HAVE_SYS_UIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#define APR_HAVE_SYS_WAIT_H 0 +#define APR_HAVE_TIME_H 0 +#define APR_HAVE_UNISTD_H 0 +#define APR_HAVE_STDDEF_H 0 +#define APR_HAVE_PROCESS_H 0 +#endif + +/** @} */ +/** @} */ + +/* We don't include our conditional headers within the doxyblocks + * or the extern "C" namespace + */ + +#if APR_HAVE_STDLIB_H +#include +#endif + +#if APR_HAVE_STDIO_H +#include +#endif + +#if APR_HAVE_SYS_TYPES_H +#include +#endif + +#if APR_HAVE_STDDEF_H +#include +#endif + +#if APR_HAVE_SYS_SOCKET_H +#include +#endif + +#if APR_HAVE_STDINT_H +#include +#endif + +#if APR_HAVE_SYS_WAIT_H +#include +#endif + +#if APR_HAVE_TIME_H +#include +#endif + +#if APR_HAVE_PROCESS_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @addtogroup apr_platform + * @ingroup APR + * @{ + */ + +#define APR_HAVE_SHMEM_MMAP_TMP 0 +#define APR_HAVE_SHMEM_MMAP_SHM 0 +#define APR_HAVE_SHMEM_MMAP_ZERO 0 +#define APR_HAVE_SHMEM_SHMGET_ANON 0 +#define APR_HAVE_SHMEM_SHMGET 0 +#define APR_HAVE_SHMEM_MMAP_ANON 0 +#define APR_HAVE_SHMEM_BEOS 0 + +#define APR_USE_SHMEM_MMAP_TMP 0 +#define APR_USE_SHMEM_MMAP_SHM 0 +#define APR_USE_SHMEM_MMAP_ZERO 0 +#define APR_USE_SHMEM_SHMGET_ANON 0 +#define APR_USE_SHMEM_SHMGET 0 +#define APR_USE_SHMEM_MMAP_ANON 0 +#define APR_USE_SHMEM_BEOS 0 + +#define APR_USE_FLOCK_SERIALIZE 0 +#define APR_USE_POSIXSEM_SERIALIZE 0 +#define APR_USE_SYSVSEM_SERIALIZE 0 +#define APR_USE_FCNTL_SERIALIZE 0 +#define APR_USE_PROC_PTHREAD_SERIALIZE 0 +#define APR_USE_PTHREAD_SERIALIZE 0 + +#define APR_HAS_FLOCK_SERIALIZE 0 +#define APR_HAS_SYSVSEM_SERIALIZE 0 +#define APR_HAS_POSIXSEM_SERIALIZE 0 +#define APR_HAS_FCNTL_SERIALIZE 0 +#define APR_HAS_PROC_PTHREAD_SERIALIZE 0 + +#define APR_PROCESS_LOCK_IS_GLOBAL 0 + +#define APR_HAVE_CORKABLE_TCP 0 +#define APR_HAVE_GETRLIMIT 0 +#define APR_HAVE_ICONV 0 +#define APR_HAVE_IN_ADDR 1 +#define APR_HAVE_INET_ADDR 1 +#define APR_HAVE_INET_NETWORK 0 +#define APR_HAVE_IPV6 @apr_have_ipv6_10@ +#define APR_HAVE_SOCKADDR_UN 0 +#define APR_HAVE_MEMMOVE 1 +#define APR_HAVE_SETRLIMIT 0 +#define APR_HAVE_SIGACTION 0 +#define APR_HAVE_SIGSUSPEND 0 +#define APR_HAVE_SIGWAIT 0 +#define APR_HAVE_SA_STORAGE 0 +#define APR_HAVE_STRCASECMP 0 +#define APR_HAVE_STRDUP 1 +#define APR_HAVE_STRNCASECMP 0 +#define APR_HAVE_STRSTR 1 +#define APR_HAVE_MEMCHR 1 +#define APR_HAVE_STRUCT_RLIMIT 0 +#define APR_HAVE_UNION_SEMUN 0 +#define APR_HAVE_SCTP 0 +#define APR_HAVE_IOVEC 0 + +#ifndef _WIN32_WCE +#define APR_HAVE_STRICMP 1 +#define APR_HAVE_STRNICMP 1 +#else +#define APR_HAVE_STRICMP 0 +#define APR_HAVE_STRNICMP 0 +#endif + +/* APR Feature Macros */ +#define APR_HAS_SHARED_MEMORY 1 +#define APR_HAS_THREADS 1 +#define APR_HAS_MMAP 1 +#define APR_HAS_FORK 0 +#define APR_HAS_RANDOM 1 +#define APR_HAS_OTHER_CHILD 1 +#define APR_HAS_DSO 1 +#define APR_HAS_SO_ACCEPTFILTER 0 +#define APR_HAS_UNICODE_FS 1 +#define APR_HAS_PROC_INVOKED 1 +#define APR_HAS_OS_UUID 1 +#define APR_HAS_TIMEDLOCKS 1 + +#ifndef _WIN32_WCE +#define APR_HAS_SENDFILE 1 +#define APR_HAS_USER 1 +#define APR_HAS_LARGE_FILES 1 +#define APR_HAS_XTHREAD_FILES 1 +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 1 +#else +#define APR_HAS_SENDFILE 0 +#define APR_HAS_USER 0 +#define APR_HAS_LARGE_FILES 0 +#define APR_HAS_XTHREAD_FILES 0 +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 0 +#endif + +/* APR sets APR_FILES_AS_SOCKETS to 1 on systems where it is possible + * to poll on files/pipes. + */ +#define APR_FILES_AS_SOCKETS 0 + +/* This macro indicates whether or not EBCDIC is the native character set. + */ +#define APR_CHARSET_EBCDIC 0 + +/* If we have a TCP implementation that can be "corked", what flag + * do we use? + */ +#define APR_TCP_NOPUSH_FLAG @apr_tcp_nopush_flag@ + +/* Is the TCP_NODELAY socket option inherited from listening sockets? + */ +#define APR_TCP_NODELAY_INHERITED 1 + +/* Is the O_NONBLOCK flag inherited from listening sockets? + */ +#define APR_O_NONBLOCK_INHERITED 1 + +/* Typedefs that APR needs. */ + +typedef unsigned char apr_byte_t; + +typedef short apr_int16_t; +typedef unsigned short apr_uint16_t; + +typedef int apr_int32_t; +typedef unsigned int apr_uint32_t; + +typedef __int64 apr_int64_t; +typedef unsigned __int64 apr_uint64_t; + +typedef size_t apr_size_t; +#if APR_HAVE_STDDEF_H +typedef ptrdiff_t apr_ssize_t; +#else +typedef int apr_ssize_t; +#endif +#if APR_HAS_LARGE_FILES +typedef __int64 apr_off_t; +#else +typedef int apr_off_t; +#endif +typedef int apr_socklen_t; +typedef apr_uint64_t apr_ino_t; + +#ifdef _WIN64 +#define APR_SIZEOF_VOIDP 8 +#else +#define APR_SIZEOF_VOIDP 4 +#endif + +#if APR_SIZEOF_VOIDP == 8 +typedef apr_uint64_t apr_uintptr_t; +#else +typedef apr_uint32_t apr_uintptr_t; +#endif + +/* Are we big endian? */ +/* XXX: Fatal assumption on Alpha platforms */ +#define APR_IS_BIGENDIAN 0 + +/* Mechanisms to properly type numeric literals */ + +#ifndef __GNUC__ +#define APR_INT64_C(val) (val##i64) +#define APR_UINT64_C(val) (val##Ui64) +#else +#define APR_INT64_C(val) (val##LL) +#define APR_UINT64_C(val) (val##ULL) +#endif + +#ifdef INT16_MIN +#define APR_INT16_MIN INT16_MIN +#else +#define APR_INT16_MIN (-0x7fff - 1) +#endif + +#ifdef INT16_MAX +#define APR_INT16_MAX INT16_MAX +#else +#define APR_INT16_MAX (0x7fff) +#endif + +#ifdef UINT16_MAX +#define APR_UINT16_MAX UINT16_MAX +#else +#define APR_UINT16_MAX (0xffff) +#endif + +#ifdef INT32_MIN +#define APR_INT32_MIN INT32_MIN +#else +#define APR_INT32_MIN (-0x7fffffff - 1) +#endif + +#ifdef INT32_MAX +#define APR_INT32_MAX INT32_MAX +#else +#define APR_INT32_MAX 0x7fffffff +#endif + +#ifdef UINT32_MAX +#define APR_UINT32_MAX UINT32_MAX +#else +#define APR_UINT32_MAX (0xffffffffU) +#endif + +#ifdef INT64_MIN +#define APR_INT64_MIN INT64_MIN +#else +#define APR_INT64_MIN (APR_INT64_C(-0x7fffffffffffffff) - 1) +#endif + +#ifdef INT64_MAX +#define APR_INT64_MAX INT64_MAX +#else +#define APR_INT64_MAX APR_INT64_C(0x7fffffffffffffff) +#endif + +#ifdef UINT64_MAX +#define APR_UINT64_MAX UINT64_MAX +#else +#define APR_UINT64_MAX APR_UINT64_C(0xffffffffffffffff) +#endif + +#define APR_SIZE_MAX (~((apr_size_t)0)) + +/* Definitions that APR programs need to work properly. */ + +/** + * APR public API wrap for C++ compilers. + */ +#ifdef __cplusplus +#define APR_BEGIN_DECLS extern "C" { +#define APR_END_DECLS } +#else +#define APR_BEGIN_DECLS +#define APR_END_DECLS +#endif + +/** + * Thread callbacks from APR functions must be declared with APR_THREAD_FUNC, + * so that they follow the platform's calling convention. + *
+ *
+ * void* APR_THREAD_FUNC my_thread_entry_fn(apr_thread_t *thd, void *data);
+ *
+ * 
+ */ +#define APR_THREAD_FUNC __stdcall + + +#if defined(DOXYGEN) || !defined(WIN32) + +/** + * The public APR functions are declared with APR_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APR_DECLARE_NONSTD(). + * + * @remark Both the declaration and implementations must use the same macro. + * + *
+ * APR_DECLARE(rettype) apr_func(args)
+ * 
+ * @see APR_DECLARE_NONSTD @see APR_DECLARE_DATA + * @remark Note that when APR compiles the library itself, it passes the + * symbol -DAPR_DECLARE_EXPORT to the compiler on some platforms (e.g. Win32) + * to export public symbols from the dynamic library build.\n + * The user must define the APR_DECLARE_STATIC when compiling to target + * the static APR library on some platforms (e.g. Win32.) The public symbols + * are neither exported nor imported when APR_DECLARE_STATIC is defined.\n + * By default, compiling an application and including the APR public + * headers, without defining APR_DECLARE_STATIC, will prepare the code to be + * linked to the dynamic library. + */ +#define APR_DECLARE(type) type + +/** + * The public APR functions using variable arguments are declared with + * APR_DECLARE_NONSTD(), as they must follow the C language calling convention. + * @see APR_DECLARE @see APR_DECLARE_DATA + * @remark Both the declaration and implementations must use the same macro. + *
+ *
+ * APR_DECLARE_NONSTD(rettype) apr_func(args, ...);
+ *
+ * 
+ */ +#define APR_DECLARE_NONSTD(type) type + +/** + * The public APR variables are declared with AP_MODULE_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * @see APR_DECLARE @see APR_DECLARE_NONSTD + * @remark Note that the declaration and implementations use different forms, + * but both must include the macro. + * + *
+ *
+ * extern APR_DECLARE_DATA type apr_variable;\n
+ * APR_DECLARE_DATA type apr_variable = value;
+ *
+ * 
+ */ +#define APR_DECLARE_DATA + +#elif defined(APR_DECLARE_STATIC) +#define APR_DECLARE(type) type __stdcall +#define APR_DECLARE_NONSTD(type) type __cdecl +#define APR_DECLARE_DATA +#elif defined(APR_DECLARE_EXPORT) +#define APR_DECLARE(type) __declspec(dllexport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllexport) +#else +#define APR_DECLARE(type) __declspec(dllimport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllimport) +#endif + +#ifdef _WIN64 +#define APR_SSIZE_T_FMT "I64d" +#define APR_SIZE_T_FMT "I64u" +#else +#define APR_SSIZE_T_FMT "d" +#define APR_SIZE_T_FMT "u" +#endif + +#if APR_HAS_LARGE_FILES +#define APR_OFF_T_FMT "I64d" +#else +#define APR_OFF_T_FMT "d" +#endif + +#define APR_PID_T_FMT "d" + +#define APR_INT64_T_FMT "I64d" +#define APR_UINT64_T_FMT "I64u" +#define APR_UINT64_T_HEX_FMT "I64x" + +/* No difference between PROC and GLOBAL mutex */ +#define APR_PROC_MUTEX_IS_GLOBAL 1 + +/* Local machine definition for console and log output. */ +#define APR_EOL_STR "\r\n" + +typedef int apr_wait_t; + +#if APR_HAS_UNICODE_FS +/* An arbitrary size that is digestable. True max is a bit less than 32000 */ +#define APR_PATH_MAX 8192 +#else /* !APR_HAS_UNICODE_FS */ +#define APR_PATH_MAX MAX_PATH +#endif + +#define APR_DSOPATH "PATH" + +/** @} */ + +/* Definitions that only Win32 programs need to compile properly. */ + +/* XXX These simply don't belong here, perhaps in apr_portable.h + * based on some APR_HAVE_PID/GID/UID? + */ +#ifndef __GNUC__ +typedef int pid_t; +#endif +typedef int uid_t; +typedef int gid_t; + +/* Win32 .h ommissions we really need */ +#define STDIN_FILENO 0 +#define STDOUT_FILENO 1 +#define STDERR_FILENO 2 + +#if APR_HAVE_IPV6 + +/* Appears in later flavors, not the originals. */ +#ifndef in_addr6 +#define in6_addr in_addr6 +#endif + +#ifndef WS2TCPIP_INLINE +#define IN6_IS_ADDR_V4MAPPED(a) \ + ( (*(const apr_uint64_t *)(const void *)(&(a)->s6_addr[0]) == 0) \ + && (*(const apr_uint32_t *)(const void *)(&(a)->s6_addr[8]) == ntohl(0x0000ffff))) +#endif + +#endif /* APR_HAVE_IPV6 */ + +#ifdef __cplusplus +} +#endif + +/* Done with badly written headers, leave 'deprecated CRT' undeprecated + */ +#if defined(_MSC_VER) && _MSC_VER >= 1200 +#pragma warning(pop) +#if _MSC_VER >= 1400 +#pragma warning(disable: 4996) +#endif +#endif + +#endif /* WIN32 */ + +#endif /* APR_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_allocator.h b/c/dependencies/windows/apr/x64/include/apr_allocator.h new file mode 100644 index 00000000..be05d0e4 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_allocator.h @@ -0,0 +1,179 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ALLOCATOR_H +#define APR_ALLOCATOR_H + +/** + * @file apr_allocator.h + * @brief APR Internal Memory Allocation + */ + +#include "apr.h" +#include "apr_errno.h" +#define APR_WANT_MEMFUNC /**< For no good reason? */ +#include "apr_want.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_allocator Internal Memory Allocation + * @ingroup APR + * @{ + */ + +/** the allocator structure */ +typedef struct apr_allocator_t apr_allocator_t; +/** the structure which holds information about the allocation */ +typedef struct apr_memnode_t apr_memnode_t; + +/** basic memory node structure + * @note The next, ref and first_avail fields are available for use by the + * caller of apr_allocator_alloc(), the remaining fields are read-only. + * The next field has to be used with caution and sensibly set when the + * memnode is passed back to apr_allocator_free(). See apr_allocator_free() + * for details. + * The ref and first_avail fields will be properly restored by + * apr_allocator_free(). + */ +struct apr_memnode_t { + apr_memnode_t *next; /**< next memnode */ + apr_memnode_t **ref; /**< reference to self */ + apr_uint32_t index; /**< size */ + apr_uint32_t free_index; /**< how much free */ + char *first_avail; /**< pointer to first free memory */ + char *endp; /**< pointer to end of free memory */ +}; + +/** The base size of a memory node - aligned. */ +#define APR_MEMNODE_T_SIZE APR_ALIGN_DEFAULT(sizeof(apr_memnode_t)) + +/** Symbolic constants */ +#define APR_ALLOCATOR_MAX_FREE_UNLIMITED 0 + +/** + * Create a new allocator + * @param allocator The allocator we have just created. + * + */ +APR_DECLARE(apr_status_t) apr_allocator_create(apr_allocator_t **allocator) + __attribute__((nonnull(1))); + +/** + * Destroy an allocator + * @param allocator The allocator to be destroyed + * @remark Any memnodes not given back to the allocator prior to destroying + * will _not_ be free()d. + */ +APR_DECLARE(void) apr_allocator_destroy(apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +/** + * Allocate a block of mem from the allocator + * @param allocator The allocator to allocate from + * @param size The size of the mem to allocate (excluding the + * memnode structure) + */ +APR_DECLARE(apr_memnode_t *) apr_allocator_alloc(apr_allocator_t *allocator, + apr_size_t size) + __attribute__((nonnull(1))); + +/** + * Free a list of blocks of mem, giving them back to the allocator. + * The list is typically terminated by a memnode with its next field + * set to NULL. + * @param allocator The allocator to give the mem back to + * @param memnode The memory node to return + */ +APR_DECLARE(void) apr_allocator_free(apr_allocator_t *allocator, + apr_memnode_t *memnode) + __attribute__((nonnull(1,2))); + +/** + * Get the true size that would be allocated for the given size (including + * the header and alignment). + * @param allocator The allocator from which to the memory would be allocated + * @param size The size to align + * @return The aligned size (or zero on apr_size_t overflow) + */ +APR_DECLARE(apr_size_t) apr_allocator_align(apr_allocator_t *allocator, + apr_size_t size); + +#include "apr_pools.h" + +/** + * Set the owner of the allocator + * @param allocator The allocator to set the owner for + * @param pool The pool that is to own the allocator + * @remark Typically pool is the highest level pool using the allocator + */ +/* + * XXX: see if we can come up with something a bit better. Currently + * you can make a pool an owner, but if the pool doesn't use the allocator + * the allocator will never be destroyed. + */ +APR_DECLARE(void) apr_allocator_owner_set(apr_allocator_t *allocator, + apr_pool_t *pool) + __attribute__((nonnull(1))); + +/** + * Get the current owner of the allocator + * @param allocator The allocator to get the owner from + */ +APR_DECLARE(apr_pool_t *) apr_allocator_owner_get(apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +/** + * Set the current threshold at which the allocator should start + * giving blocks back to the system. + * @param allocator The allocator to set the threshold on + * @param size The threshold. 0 == unlimited. + */ +APR_DECLARE(void) apr_allocator_max_free_set(apr_allocator_t *allocator, + apr_size_t size) + __attribute__((nonnull(1))); + +#include "apr_thread_mutex.h" + +#if APR_HAS_THREADS +/** + * Set a mutex for the allocator to use + * @param allocator The allocator to set the mutex for + * @param mutex The mutex + */ +APR_DECLARE(void) apr_allocator_mutex_set(apr_allocator_t *allocator, + apr_thread_mutex_t *mutex) + __attribute__((nonnull(1))); + +/** + * Get the mutex currently set for the allocator + * @param allocator The allocator + */ +APR_DECLARE(apr_thread_mutex_t *) apr_allocator_mutex_get( + apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ALLOCATOR_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_anylock.h b/c/dependencies/windows/apr/x64/include/apr_anylock.h new file mode 100644 index 00000000..51e97ff3 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_anylock.h @@ -0,0 +1,128 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_anylock.h + * @brief APR-Util transparent any lock flavor wrapper + */ +#ifndef APR_ANYLOCK_H +#define APR_ANYLOCK_H + +#include "apr_proc_mutex.h" +#include "apr_thread_mutex.h" +#include "apr_thread_rwlock.h" + +/** Structure that may contain any APR lock type */ +typedef struct apr_anylock_t { + /** Indicates what type of lock is in lock */ + enum tm_lock { + apr_anylock_none, /**< None */ + apr_anylock_procmutex, /**< Process-based */ + apr_anylock_threadmutex, /**< Thread-based */ + apr_anylock_readlock, /**< Read lock */ + apr_anylock_writelock /**< Write lock */ + } type; + /** Union of all possible APR locks */ + union apr_anylock_u_t { + apr_proc_mutex_t *pm; /**< Process mutex */ +#if APR_HAS_THREADS + apr_thread_mutex_t *tm; /**< Thread mutex */ + apr_thread_rwlock_t *rw; /**< Read-write lock */ +#endif + } lock; +} apr_anylock_t; + +#if APR_HAS_THREADS + +/** Lock an apr_anylock_t structure */ +#define APR_ANYLOCK_LOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_threadmutex) \ + ? apr_thread_mutex_lock((lck)->lock.tm) \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_lock((lck)->lock.pm) \ + : (((lck)->type == apr_anylock_readlock) \ + ? apr_thread_rwlock_rdlock((lck)->lock.rw) \ + : (((lck)->type == apr_anylock_writelock) \ + ? apr_thread_rwlock_wrlock((lck)->lock.rw) \ + : APR_EINVAL))))) + +#else /* APR_HAS_THREADS */ + +#define APR_ANYLOCK_LOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_lock((lck)->lock.pm) \ + : APR_EINVAL)) + +#endif /* APR_HAS_THREADS */ + +#if APR_HAS_THREADS + +/** Try to lock an apr_anylock_t structure */ +#define APR_ANYLOCK_TRYLOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_threadmutex) \ + ? apr_thread_mutex_trylock((lck)->lock.tm) \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_trylock((lck)->lock.pm) \ + : (((lck)->type == apr_anylock_readlock) \ + ? apr_thread_rwlock_tryrdlock((lck)->lock.rw) \ + : (((lck)->type == apr_anylock_writelock) \ + ? apr_thread_rwlock_trywrlock((lck)->lock.rw) \ + : APR_EINVAL))))) + +#else /* APR_HAS_THREADS */ + +#define APR_ANYLOCK_TRYLOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_trylock((lck)->lock.pm) \ + : APR_EINVAL)) + +#endif /* APR_HAS_THREADS */ + +#if APR_HAS_THREADS + +/** Unlock an apr_anylock_t structure */ +#define APR_ANYLOCK_UNLOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_threadmutex) \ + ? apr_thread_mutex_unlock((lck)->lock.tm) \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_unlock((lck)->lock.pm) \ + : ((((lck)->type == apr_anylock_readlock) || \ + ((lck)->type == apr_anylock_writelock)) \ + ? apr_thread_rwlock_unlock((lck)->lock.rw) \ + : APR_EINVAL)))) + +#else /* APR_HAS_THREADS */ + +#define APR_ANYLOCK_UNLOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_unlock((lck)->lock.pm) \ + : APR_EINVAL)) + +#endif /* APR_HAS_THREADS */ + +#endif /* !APR_ANYLOCK_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_atomic.h b/c/dependencies/windows/apr/x64/include/apr_atomic.h new file mode 100644 index 00000000..3d203edc --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_atomic.h @@ -0,0 +1,207 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ATOMIC_H +#define APR_ATOMIC_H + +/** + * @file apr_atomic.h + * @brief APR Atomic Operations + */ + +#include "apr.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_atomic Atomic Operations + * @ingroup APR + * @{ + */ + +/** + * this function is required on some platforms to initialize the + * atomic operation's internal structures + * @param p pool + * @return APR_SUCCESS on successful completion + * @remark Programs do NOT need to call this directly. APR will call this + * automatically from apr_initialize(). + * @internal + */ +APR_DECLARE(apr_status_t) apr_atomic_init(apr_pool_t *p); + +/* + * Atomic operations on 32-bit values + * Note: Each of these functions internally implements a memory barrier + * on platforms that require it + */ + +/** + * atomically read an apr_uint32_t from memory + * @param mem the pointer + */ +APR_DECLARE(apr_uint32_t) apr_atomic_read32(volatile apr_uint32_t *mem); + +/** + * atomically set an apr_uint32_t in memory + * @param mem pointer to the object + * @param val value that the object will assume + */ +APR_DECLARE(void) apr_atomic_set32(volatile apr_uint32_t *mem, apr_uint32_t val); + +/** + * atomically add 'val' to an apr_uint32_t + * @param mem pointer to the object + * @param val amount to add + * @return old value pointed to by mem + */ +APR_DECLARE(apr_uint32_t) apr_atomic_add32(volatile apr_uint32_t *mem, apr_uint32_t val); + +/** + * atomically subtract 'val' from an apr_uint32_t + * @param mem pointer to the object + * @param val amount to subtract + */ +APR_DECLARE(void) apr_atomic_sub32(volatile apr_uint32_t *mem, apr_uint32_t val); + +/** + * atomically increment an apr_uint32_t by 1 + * @param mem pointer to the object + * @return old value pointed to by mem + */ +APR_DECLARE(apr_uint32_t) apr_atomic_inc32(volatile apr_uint32_t *mem); + +/** + * atomically decrement an apr_uint32_t by 1 + * @param mem pointer to the atomic value + * @return zero if the value becomes zero on decrement, otherwise non-zero + */ +APR_DECLARE(int) apr_atomic_dec32(volatile apr_uint32_t *mem); + +/** + * compare an apr_uint32_t's value with 'cmp'. + * If they are the same swap the value with 'with' + * @param mem pointer to the value + * @param with what to swap it with + * @param cmp the value to compare it to + * @return the old value of *mem + */ +APR_DECLARE(apr_uint32_t) apr_atomic_cas32(volatile apr_uint32_t *mem, apr_uint32_t with, + apr_uint32_t cmp); + +/** + * exchange an apr_uint32_t's value with 'val'. + * @param mem pointer to the value + * @param val what to swap it with + * @return the old value of *mem + */ +APR_DECLARE(apr_uint32_t) apr_atomic_xchg32(volatile apr_uint32_t *mem, apr_uint32_t val); + +/* + * Atomic operations on 64-bit values + * Note: Each of these functions internally implements a memory barrier + * on platforms that require it + */ + +/** + * atomically read an apr_uint64_t from memory + * @param mem the pointer + */ +APR_DECLARE(apr_uint64_t) apr_atomic_read64(volatile apr_uint64_t *mem); + +/** + * atomically set an apr_uint64_t in memory + * @param mem pointer to the object + * @param val value that the object will assume + */ +APR_DECLARE(void) apr_atomic_set64(volatile apr_uint64_t *mem, apr_uint64_t val); + +/** + * atomically add 'val' to an apr_uint64_t + * @param mem pointer to the object + * @param val amount to add + * @return old value pointed to by mem + */ +APR_DECLARE(apr_uint64_t) apr_atomic_add64(volatile apr_uint64_t *mem, apr_uint64_t val); + +/** + * atomically subtract 'val' from an apr_uint64_t + * @param mem pointer to the object + * @param val amount to subtract + */ +APR_DECLARE(void) apr_atomic_sub64(volatile apr_uint64_t *mem, apr_uint64_t val); + +/** + * atomically increment an apr_uint64_t by 1 + * @param mem pointer to the object + * @return old value pointed to by mem + */ +APR_DECLARE(apr_uint64_t) apr_atomic_inc64(volatile apr_uint64_t *mem); + +/** + * atomically decrement an apr_uint64_t by 1 + * @param mem pointer to the atomic value + * @return zero if the value becomes zero on decrement, otherwise non-zero + */ +APR_DECLARE(int) apr_atomic_dec64(volatile apr_uint64_t *mem); + +/** + * compare an apr_uint64_t's value with 'cmp'. + * If they are the same swap the value with 'with' + * @param mem pointer to the value + * @param with what to swap it with + * @param cmp the value to compare it to + * @return the old value of *mem + */ +APR_DECLARE(apr_uint64_t) apr_atomic_cas64(volatile apr_uint64_t *mem, apr_uint64_t with, + apr_uint64_t cmp); + +/** + * exchange an apr_uint64_t's value with 'val'. + * @param mem pointer to the value + * @param val what to swap it with + * @return the old value of *mem + */ +APR_DECLARE(apr_uint64_t) apr_atomic_xchg64(volatile apr_uint64_t *mem, apr_uint64_t val); + +/** + * compare the pointer's value with cmp. + * If they are the same swap the value with 'with' + * @param mem pointer to the pointer + * @param with what to swap it with + * @param cmp the value to compare it to + * @return the old value of the pointer + */ +APR_DECLARE(void*) apr_atomic_casptr(volatile void **mem, void *with, const void *cmp); + +/** + * exchange a pair of pointer values + * @param mem pointer to the pointer + * @param with what to swap it with + * @return the old value of the pointer + */ +APR_DECLARE(void*) apr_atomic_xchgptr(volatile void **mem, void *with); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ATOMIC_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_base64.h b/c/dependencies/windows/apr/x64/include/apr_base64.h new file mode 100644 index 00000000..17de1c58 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_base64.h @@ -0,0 +1,113 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * The apr_vsnprintf/apr_snprintf functions are based on, and used with the + * permission of, the SIO stdio-replacement strx_* functions by Panos + * Tsirigotis for xinetd. + */ + +/** + * @file apr_base64.h + * @brief APR-UTIL Base64 Encoding + */ +#ifndef APR_BASE64_H +#define APR_BASE64_H + +#include "apu.h" +#include "apr_general.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Base64 Base64 Encoding + * @ingroup APR_Util + * @{ + */ + +/* Simple BASE64 encode/decode functions. + * + * As we might encode binary strings, hence we require the length of + * the incoming plain source. And return the length of what we decoded. + * + * The decoding function takes any non valid char (i.e. whitespace, \0 + * or anything non A-Z,0-9 etc as terminal. + * + * plain strings/binary sequences are not assumed '\0' terminated. Encoded + * strings are neither. But probably should. + * + */ + +/** + * Given the length of an un-encoded string, get the length of the + * encoded string. + * @param len the length of an unencoded string. + * @return the length of the string after it is encoded, including the + * trailing \0 + */ +APU_DECLARE(int) apr_base64_encode_len(int len); + +/** + * Encode a text string using base64encoding. + * @param coded_dst The destination string for the encoded string. + * @param plain_src The original string in plain text + * @param len_plain_src The length of the plain text string + * @return the length of the encoded string + */ +APU_DECLARE(int) apr_base64_encode(char * coded_dst, const char *plain_src, + int len_plain_src); + +/** + * Encode an EBCDIC string using base64encoding. + * @param coded_dst The destination string for the encoded string. + * @param plain_src The original string in plain text + * @param len_plain_src The length of the plain text string + * @return the length of the encoded string + */ +APU_DECLARE(int) apr_base64_encode_binary(char * coded_dst, + const unsigned char *plain_src, + int len_plain_src); + +/** + * Determine the maximum buffer length required to decode the plain text + * string given the encoded string. + * @param coded_src The encoded string + * @return the maximum required buffer length for the plain text string + */ +APU_DECLARE(int) apr_base64_decode_len(const char * coded_src); + +/** + * Decode a string to plain text + * @param plain_dst The destination string for the plain text + * @param coded_src The encoded string + * @return the length of the plain text string + */ +APU_DECLARE(int) apr_base64_decode(char * plain_dst, const char *coded_src); + +/** + * Decode an EBCDIC string to plain text + * @param plain_dst The destination string for the plain text + * @param coded_src The encoded string + * @return the length of the plain text string + */ +APU_DECLARE(int) apr_base64_decode_binary(unsigned char * plain_dst, + const char *coded_src); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_BASE64_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_buckets.h b/c/dependencies/windows/apr/x64/include/apr_buckets.h new file mode 100644 index 00000000..ce64b78d --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_buckets.h @@ -0,0 +1,1598 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file apr_buckets.h + * @brief APR-UTIL Buckets/Bucket Brigades + */ + +#ifndef APR_BUCKETS_H +#define APR_BUCKETS_H + +#if defined(APR_BUCKET_DEBUG) && !defined(APR_RING_DEBUG) +#define APR_RING_DEBUG +#endif + +#include "apu.h" +#include "apr_network_io.h" +#include "apr_file_io.h" +#include "apr_general.h" +#include "apr_mmap.h" +#include "apr_errno.h" +#include "apr_ring.h" +#include "apr.h" +#if APR_HAVE_SYS_UIO_H +#include /* for struct iovec */ +#endif +#if APR_HAVE_STDARG_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Bucket_Brigades Bucket Brigades + * @ingroup APR_Util + * @{ + */ + +/** default bucket buffer size - 8KB minus room for memory allocator headers */ +#define APR_BUCKET_BUFF_SIZE 8000 + +/** Determines how a bucket or brigade should be read */ +typedef enum { + APR_BLOCK_READ, /**< block until data becomes available */ + APR_NONBLOCK_READ /**< return immediately if no data is available */ +} apr_read_type_e; + +/** + * The one-sentence buzzword-laden overview: Bucket brigades represent + * a complex data stream that can be passed through a layered IO + * system without unnecessary copying. A longer overview follows... + * + * A bucket brigade is a doubly linked list (ring) of buckets, so we + * aren't limited to inserting at the front and removing at the end. + * Buckets are only passed around as members of a brigade, although + * singleton buckets can occur for short periods of time. + * + * Buckets are data stores of various types. They can refer to data in + * memory, or part of a file or mmap area, or the output of a process, + * etc. Buckets also have some type-dependent accessor functions: + * read, split, copy, setaside, and destroy. + * + * read returns the address and size of the data in the bucket. If the + * data isn't in memory then it is read in and the bucket changes type + * so that it can refer to the new location of the data. If all the + * data doesn't fit in the bucket then a new bucket is inserted into + * the brigade to hold the rest of it. + * + * split divides the data in a bucket into two regions. After a split + * the original bucket refers to the first part of the data and a new + * bucket inserted into the brigade after the original bucket refers + * to the second part of the data. Reference counts are maintained as + * necessary. + * + * setaside ensures that the data in the bucket has a long enough + * lifetime. Sometimes it is convenient to create a bucket referring + * to data on the stack in the expectation that it will be consumed + * (output to the network) before the stack is unwound. If that + * expectation turns out not to be valid, the setaside function is + * called to move the data somewhere safer. + * + * copy makes a duplicate of the bucket structure as long as it's + * possible to have multiple references to a single copy of the + * data itself. Not all bucket types can be copied. + * + * destroy maintains the reference counts on the resources used by a + * bucket and frees them if necessary. + * + * Note: all of the above functions have wrapper macros (apr_bucket_read(), + * apr_bucket_destroy(), etc), and those macros should be used rather + * than using the function pointers directly. + * + * To write a bucket brigade, they are first made into an iovec, so that we + * don't write too little data at one time. Currently we ignore compacting the + * buckets into as few buckets as possible, but if we really want good + * performance, then we need to compact the buckets before we convert to an + * iovec, or possibly while we are converting to an iovec. + */ + +/* + * Forward declaration of the main types. + */ + +/** @see apr_bucket_brigade */ +typedef struct apr_bucket_brigade apr_bucket_brigade; +/** @see apr_bucket */ +typedef struct apr_bucket apr_bucket; +/** @see apr_bucket_alloc_t */ +typedef struct apr_bucket_alloc_t apr_bucket_alloc_t; + +/** @see apr_bucket_type_t */ +typedef struct apr_bucket_type_t apr_bucket_type_t; + +/** + * Basic bucket type + */ +struct apr_bucket_type_t { + /** + * The name of the bucket type + */ + const char *name; + /** + * The number of functions this bucket understands. Can not be less than + * five. + */ + int num_func; + /** + * Whether the bucket contains metadata (ie, information that + * describes the regular contents of the brigade). The metadata + * is not returned by apr_bucket_read() and is not indicated by + * the ->length of the apr_bucket itself. In other words, an + * empty bucket is safe to arbitrarily remove if and only if it + * contains no metadata. In this sense, "data" is just raw bytes + * that are the "content" of the brigade and "metadata" describes + * that data but is not a proper part of it. + */ + enum { + /** This bucket type represents actual data to send to the client. */ + APR_BUCKET_DATA = 0, + /** This bucket type represents metadata. */ + APR_BUCKET_METADATA = 1 + } is_metadata; + /** + * Free the private data and any resources used by the bucket (if they + * aren't shared with another bucket). This function is required to be + * implemented for all bucket types, though it might be a no-op on some + * of them (namely ones that never allocate any private data structures). + * @param data The private data pointer from the bucket to be destroyed + */ + void (*destroy)(void *data); + + /** + * Read the data from the bucket. This is required to be implemented + * for all bucket types. + * @param b The bucket to read from + * @param str A place to store the data read. Allocation should only be + * done if absolutely necessary. + * @param len The amount of data read. + * @param block Should this read function block if there is more data that + * cannot be read immediately. + */ + apr_status_t (*read)(apr_bucket *b, const char **str, apr_size_t *len, + apr_read_type_e block); + + /** + * Make it possible to set aside the data for at least as long as the + * given pool. Buckets containing data that could potentially die before + * this pool (e.g. the data resides on the stack, in a child pool of + * the given pool, or in a disjoint pool) must somehow copy, shift, or + * transform the data to have the proper lifetime. + * @param e The bucket to convert + * @remark Some bucket types contain data that will always outlive the + * bucket itself. For example no data (EOS and FLUSH), or the data + * resides in global, constant memory (IMMORTAL), or the data is on + * the heap (HEAP). For these buckets, apr_bucket_setaside_noop can + * be used. + */ + apr_status_t (*setaside)(apr_bucket *e, apr_pool_t *pool); + + /** + * Split one bucket in two at the specified position by duplicating + * the bucket structure (not the data) and modifying any necessary + * start/end/offset information. If it's not possible to do this + * for the bucket type (perhaps the length of the data is indeterminate, + * as with pipe and socket buckets), then APR_ENOTIMPL is returned. + * @param e The bucket to split + * @param point The offset of the first byte in the new bucket + */ + apr_status_t (*split)(apr_bucket *e, apr_size_t point); + + /** + * Copy the bucket structure (not the data), assuming that this is + * possible for the bucket type. If it's not, APR_ENOTIMPL is returned. + * @param e The bucket to copy + * @param c Returns a pointer to the new bucket + */ + apr_status_t (*copy)(apr_bucket *e, apr_bucket **c); + +}; + +/** + * apr_bucket structures are allocated on the malloc() heap and + * their lifetime is controlled by the parent apr_bucket_brigade + * structure. Buckets can move from one brigade to another e.g. by + * calling APR_BRIGADE_CONCAT(). In general the data in a bucket has + * the same lifetime as the bucket and is freed when the bucket is + * destroyed; if the data is shared by more than one bucket (e.g. + * after a split) the data is freed when the last bucket goes away. + */ +struct apr_bucket { + /** Links to the rest of the brigade */ + APR_RING_ENTRY(apr_bucket) link; + /** The type of bucket. */ + const apr_bucket_type_t *type; + /** The length of the data in the bucket. This could have been implemented + * with a function, but this is an optimization, because the most + * common thing to do will be to get the length. If the length is unknown, + * the value of this field will be (apr_size_t)(-1). + */ + apr_size_t length; + /** The start of the data in the bucket relative to the private base + * pointer. The vast majority of bucket types allow a fixed block of + * data to be referenced by multiple buckets, each bucket pointing to + * a different segment of the data. That segment starts at base+start + * and ends at base+start+length. + * If the length == (apr_size_t)(-1), then start == -1. + */ + apr_off_t start; + /** type-dependent data hangs off this pointer */ + void *data; + /** + * Pointer to function used to free the bucket. This function should + * always be defined and it should be consistent with the memory + * function used to allocate the bucket. For example, if malloc() is + * used to allocate the bucket, this pointer should point to free(). + * @param e Pointer to the bucket being freed + */ + void (*free)(void *e); + /** The freelist from which this bucket was allocated */ + apr_bucket_alloc_t *list; +}; + +/** A list of buckets */ +struct apr_bucket_brigade { + /** The pool to associate the brigade with. The data is not allocated out + * of the pool, but a cleanup is registered with this pool. If the + * brigade is destroyed by some mechanism other than pool destruction, + * the destroying function is responsible for killing the cleanup. + */ + apr_pool_t *p; + /** The buckets in the brigade are on this list. */ + /* + * The apr_bucket_list structure doesn't actually need a name tag + * because it has no existence independent of struct apr_bucket_brigade; + * the ring macros are designed so that you can leave the name tag + * argument empty in this situation but apparently the Windows compiler + * doesn't like that. + */ + APR_RING_HEAD(apr_bucket_list, apr_bucket) list; + /** The freelist from which this bucket was allocated */ + apr_bucket_alloc_t *bucket_alloc; +}; + + +/** + * Function called when a brigade should be flushed + */ +typedef apr_status_t (*apr_brigade_flush)(apr_bucket_brigade *bb, void *ctx); + +/* + * define APR_BUCKET_DEBUG if you want your brigades to be checked for + * validity at every possible instant. this will slow your code down + * substantially but is a very useful debugging tool. + */ +#ifdef APR_BUCKET_DEBUG + +#define APR_BRIGADE_CHECK_CONSISTENCY(b) \ + APR_RING_CHECK_CONSISTENCY(&(b)->list, apr_bucket, link) + +#define APR_BUCKET_CHECK_CONSISTENCY(e) \ + APR_RING_CHECK_ELEM_CONSISTENCY((e), apr_bucket, link) + +#else +/** + * checks the ring pointers in a bucket brigade for consistency. an + * abort() will be triggered if any inconsistencies are found. + * note: this is a no-op unless APR_BUCKET_DEBUG is defined. + * @param b The brigade + */ +#define APR_BRIGADE_CHECK_CONSISTENCY(b) +/** + * checks the brigade a bucket is in for ring consistency. an + * abort() will be triggered if any inconsistencies are found. + * note: this is a no-op unless APR_BUCKET_DEBUG is defined. + * @param e The bucket + */ +#define APR_BUCKET_CHECK_CONSISTENCY(e) +#endif + + +/** + * Wrappers around the RING macros to reduce the verbosity of the code + * that handles bucket brigades. + */ +/** + * The magic pointer value that indicates the head of the brigade + * @remark This is used to find the beginning and end of the brigade, eg: + *
+ *      while (e != APR_BRIGADE_SENTINEL(b)) {
+ *          ...
+ *          e = APR_BUCKET_NEXT(e);
+ *      }
+ * 
+ * @param b The brigade + * @return The magic pointer value + */ +#define APR_BRIGADE_SENTINEL(b) APR_RING_SENTINEL(&(b)->list, apr_bucket, link) + +/** + * Determine if the bucket brigade is empty + * @param b The brigade to check + * @return true or false + */ +#define APR_BRIGADE_EMPTY(b) APR_RING_EMPTY(&(b)->list, apr_bucket, link) + +/** + * Return the first bucket in a brigade + * @param b The brigade to query + * @return The first bucket in the brigade + */ +#define APR_BRIGADE_FIRST(b) APR_RING_FIRST(&(b)->list) +/** + * Return the last bucket in a brigade + * @param b The brigade to query + * @return The last bucket in the brigade + */ +#define APR_BRIGADE_LAST(b) APR_RING_LAST(&(b)->list) + +/** + * Insert a single bucket at the front of a brigade + * @param b The brigade to add to + * @param e The bucket to insert + */ +#define APR_BRIGADE_INSERT_HEAD(b, e) do { \ + apr_bucket *ap__b = (e); \ + APR_RING_INSERT_HEAD(&(b)->list, ap__b, apr_bucket, link); \ + APR_BRIGADE_CHECK_CONSISTENCY((b)); \ + } while (0) + +/** + * Insert a single bucket at the end of a brigade + * @param b The brigade to add to + * @param e The bucket to insert + */ +#define APR_BRIGADE_INSERT_TAIL(b, e) do { \ + apr_bucket *ap__b = (e); \ + APR_RING_INSERT_TAIL(&(b)->list, ap__b, apr_bucket, link); \ + APR_BRIGADE_CHECK_CONSISTENCY((b)); \ + } while (0) + +/** + * Concatenate brigade b onto the end of brigade a, leaving brigade b empty + * @param a The first brigade + * @param b The second brigade + */ +#define APR_BRIGADE_CONCAT(a, b) do { \ + APR_RING_CONCAT(&(a)->list, &(b)->list, apr_bucket, link); \ + APR_BRIGADE_CHECK_CONSISTENCY((a)); \ + } while (0) + +/** + * Prepend brigade b onto the beginning of brigade a, leaving brigade b empty + * @param a The first brigade + * @param b The second brigade + */ +#define APR_BRIGADE_PREPEND(a, b) do { \ + APR_RING_PREPEND(&(a)->list, &(b)->list, apr_bucket, link); \ + APR_BRIGADE_CHECK_CONSISTENCY((a)); \ + } while (0) + +/** + * Insert a single bucket before a specified bucket + * @param a The bucket to insert before + * @param b The bucket to insert + */ +#define APR_BUCKET_INSERT_BEFORE(a, b) do { \ + apr_bucket *ap__a = (a), *ap__b = (b); \ + APR_RING_INSERT_BEFORE(ap__a, ap__b, link); \ + APR_BUCKET_CHECK_CONSISTENCY(ap__a); \ + } while (0) + +/** + * Insert a single bucket after a specified bucket + * @param a The bucket to insert after + * @param b The bucket to insert + */ +#define APR_BUCKET_INSERT_AFTER(a, b) do { \ + apr_bucket *ap__a = (a), *ap__b = (b); \ + APR_RING_INSERT_AFTER(ap__a, ap__b, link); \ + APR_BUCKET_CHECK_CONSISTENCY(ap__a); \ + } while (0) + +/** + * Get the next bucket in the list + * @param e The current bucket + * @return The next bucket + */ +#define APR_BUCKET_NEXT(e) APR_RING_NEXT((e), link) +/** + * Get the previous bucket in the list + * @param e The current bucket + * @return The previous bucket + */ +#define APR_BUCKET_PREV(e) APR_RING_PREV((e), link) + +/** + * Remove a bucket from its bucket brigade + * @param e The bucket to remove + */ +#define APR_BUCKET_REMOVE(e) APR_RING_REMOVE((e), link) + +/** + * Initialize a new bucket's prev/next pointers + * @param e The bucket to initialize + */ +#define APR_BUCKET_INIT(e) APR_RING_ELEM_INIT((e), link) + +/** + * Determine if a bucket contains metadata. An empty bucket is + * safe to arbitrarily remove if and only if this is false. + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_METADATA(e) ((e)->type->is_metadata) + +/** + * Determine if a bucket is a FLUSH bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_FLUSH(e) ((e)->type == &apr_bucket_type_flush) +/** + * Determine if a bucket is an EOS bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_EOS(e) ((e)->type == &apr_bucket_type_eos) +/** + * Determine if a bucket is a FILE bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_FILE(e) ((e)->type == &apr_bucket_type_file) +/** + * Determine if a bucket is a PIPE bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_PIPE(e) ((e)->type == &apr_bucket_type_pipe) +/** + * Determine if a bucket is a SOCKET bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_SOCKET(e) ((e)->type == &apr_bucket_type_socket) +/** + * Determine if a bucket is a HEAP bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_HEAP(e) ((e)->type == &apr_bucket_type_heap) +/** + * Determine if a bucket is a TRANSIENT bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_TRANSIENT(e) ((e)->type == &apr_bucket_type_transient) +/** + * Determine if a bucket is a IMMORTAL bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_IMMORTAL(e) ((e)->type == &apr_bucket_type_immortal) +#if APR_HAS_MMAP +/** + * Determine if a bucket is a MMAP bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_MMAP(e) ((e)->type == &apr_bucket_type_mmap) +#endif +/** + * Determine if a bucket is a POOL bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_POOL(e) ((e)->type == &apr_bucket_type_pool) + +/* + * General-purpose reference counting for the various bucket types. + * + * Any bucket type that keeps track of the resources it uses (i.e. + * most of them except for IMMORTAL, TRANSIENT, and EOS) needs to + * attach a reference count to the resource so that it can be freed + * when the last bucket that uses it goes away. Resource-sharing may + * occur because of bucket splits or buckets that refer to globally + * cached data. */ + +/** @see apr_bucket_refcount */ +typedef struct apr_bucket_refcount apr_bucket_refcount; +/** + * The structure used to manage the shared resource must start with an + * apr_bucket_refcount which is updated by the general-purpose refcount + * code. A pointer to the bucket-type-dependent private data structure + * can be cast to a pointer to an apr_bucket_refcount and vice versa. + */ +struct apr_bucket_refcount { + /** The number of references to this bucket */ + int refcount; +}; + +/* ***** Reference-counted bucket types ***** */ + +/** @see apr_bucket_heap */ +typedef struct apr_bucket_heap apr_bucket_heap; +/** + * A bucket referring to data allocated off the heap. + */ +struct apr_bucket_heap { + /** Number of buckets using this memory */ + apr_bucket_refcount refcount; + /** The start of the data actually allocated. This should never be + * modified, it is only used to free the bucket. + */ + char *base; + /** how much memory was allocated */ + apr_size_t alloc_len; + /** function to use to delete the data */ + void (*free_func)(void *data); +}; + +/** @see apr_bucket_pool */ +typedef struct apr_bucket_pool apr_bucket_pool; +/** + * A bucket referring to data allocated from a pool + */ +struct apr_bucket_pool { + /** The pool bucket must be able to be easily morphed to a heap + * bucket if the pool gets cleaned up before all references are + * destroyed. This apr_bucket_heap structure is populated automatically + * when the pool gets cleaned up, and subsequent calls to pool_read() + * will result in the apr_bucket in question being morphed into a + * regular heap bucket. (To avoid having to do many extra refcount + * manipulations and b->data manipulations, the apr_bucket_pool + * struct actually *contains* the apr_bucket_heap struct that it + * will become as its first element; the two share their + * apr_bucket_refcount members.) + */ + apr_bucket_heap heap; + /** The block of data actually allocated from the pool. + * Segments of this block are referenced by adjusting + * the start and length of the apr_bucket accordingly. + * This will be NULL after the pool gets cleaned up. + */ + const char *base; + /** The pool the data was allocated from. When the pool + * is cleaned up, this gets set to NULL as an indicator + * to pool_read() that the data is now on the heap and + * so it should morph the bucket into a regular heap + * bucket before continuing. + */ + apr_pool_t *pool; + /** The freelist this structure was allocated from, which is + * needed in the cleanup phase in order to allocate space on the heap + */ + apr_bucket_alloc_t *list; +}; + +#if APR_HAS_MMAP +/** @see apr_bucket_mmap */ +typedef struct apr_bucket_mmap apr_bucket_mmap; +/** + * A bucket referring to an mmap()ed file + */ +struct apr_bucket_mmap { + /** Number of buckets using this memory */ + apr_bucket_refcount refcount; + /** The mmap this sub_bucket refers to */ + apr_mmap_t *mmap; +}; +#endif + +/** @see apr_bucket_file */ +typedef struct apr_bucket_file apr_bucket_file; +/** + * A bucket referring to an file + */ +struct apr_bucket_file { + /** Number of buckets using this memory */ + apr_bucket_refcount refcount; + /** The file this bucket refers to */ + apr_file_t *fd; + /** The pool into which any needed structures should + * be created while reading from this file bucket */ + apr_pool_t *readpool; +#if APR_HAS_MMAP + /** Whether this bucket should be memory-mapped if + * a caller tries to read from it */ + int can_mmap; +#endif /* APR_HAS_MMAP */ + /** File read block size */ + apr_size_t read_size; +}; + +/** @see apr_bucket_structs */ +typedef union apr_bucket_structs apr_bucket_structs; +/** + * A union of all bucket structures so we know what + * the max size is. + */ +union apr_bucket_structs { + apr_bucket b; /**< Bucket */ + apr_bucket_heap heap; /**< Heap */ + apr_bucket_pool pool; /**< Pool */ +#if APR_HAS_MMAP + apr_bucket_mmap mmap; /**< MMap */ +#endif + apr_bucket_file file; /**< File */ +}; + +/** + * The amount that apr_bucket_alloc() should allocate in the common case. + * Note: this is twice as big as apr_bucket_structs to allow breathing + * room for third-party bucket types. + */ +#define APR_BUCKET_ALLOC_SIZE APR_ALIGN_DEFAULT(2*sizeof(apr_bucket_structs)) + +/* ***** Bucket Brigade Functions ***** */ +/** + * Create a new bucket brigade. The bucket brigade is originally empty. + * @param p The pool to associate with the brigade. Data is not allocated out + * of the pool, but a cleanup is registered. + * @param list The bucket allocator to use + * @return The empty bucket brigade + */ +APU_DECLARE(apr_bucket_brigade *) apr_brigade_create(apr_pool_t *p, + apr_bucket_alloc_t *list); + +/** + * destroy an entire bucket brigade. This includes destroying all of the + * buckets within the bucket brigade's bucket list. + * @param b The bucket brigade to destroy + */ +APU_DECLARE(apr_status_t) apr_brigade_destroy(apr_bucket_brigade *b); + +/** + * empty out an entire bucket brigade. This includes destroying all of the + * buckets within the bucket brigade's bucket list. This is similar to + * apr_brigade_destroy(), except that it does not deregister the brigade's + * pool cleanup function. + * @param data The bucket brigade to clean up + * @remark Generally, you should use apr_brigade_destroy(). This function + * can be useful in situations where you have a single brigade that + * you wish to reuse many times by destroying all of the buckets in + * the brigade and putting new buckets into it later. + */ +APU_DECLARE(apr_status_t) apr_brigade_cleanup(void *data); + +/** + * Move the buckets from the tail end of the existing brigade @a b into + * the brigade @a a. If @a a is NULL a new brigade is created. Buckets + * from @a e to the last bucket (inclusively) of brigade @a b are moved + * from @a b to the returned brigade @a a. + * + * @param b The brigade to split + * @param e The first bucket to move + * @param a The brigade which should be used for the result or NULL if + * a new brigade should be created. The brigade @a a will be + * cleared if it is not empty. + * @return The brigade supplied in @a a or a new one if @a a was NULL. + * @warning Note that this function allocates a new brigade if @a a is + * NULL so memory consumption should be carefully considered. + */ +APU_DECLARE(apr_bucket_brigade *) apr_brigade_split_ex(apr_bucket_brigade *b, + apr_bucket *e, + apr_bucket_brigade *a); + +/** + * Create a new bucket brigade and move the buckets from the tail end + * of an existing brigade into the new brigade. Buckets from + * @a e to the last bucket (inclusively) of brigade @a b + * are moved from @a b to the returned brigade. + * @param b The brigade to split + * @param e The first bucket to move + * @return The new brigade + * @warning Note that this function always allocates a new brigade + * so memory consumption should be carefully considered. + */ +APU_DECLARE(apr_bucket_brigade *) apr_brigade_split(apr_bucket_brigade *b, + apr_bucket *e); + +/** + * Partition a bucket brigade at a given offset (in bytes from the start of + * the brigade). This is useful whenever a filter wants to use known ranges + * of bytes from the brigade; the ranges can even overlap. + * @param b The brigade to partition + * @param point The offset at which to partition the brigade + * @param after_point Returns a pointer to the first bucket after the partition + * @return APR_SUCCESS on success, APR_INCOMPLETE if the contents of the + * brigade were shorter than @a point, or an error code. + * @remark if APR_INCOMPLETE is returned, @a after_point will be set to + * the brigade sentinel. + */ +APU_DECLARE(apr_status_t) apr_brigade_partition(apr_bucket_brigade *b, + apr_off_t point, + apr_bucket **after_point); + +/** + * Return the total length of the brigade. + * @param bb The brigade to compute the length of + * @param read_all Read unknown-length buckets to force a size + * @param length Returns the length of the brigade (up to the end, or up + * to a bucket read error), or -1 if the brigade has buckets + * of indeterminate length and read_all is 0. + */ +APU_DECLARE(apr_status_t) apr_brigade_length(apr_bucket_brigade *bb, + int read_all, + apr_off_t *length); + +/** + * Take a bucket brigade and store the data in a flat char* + * @param bb The bucket brigade to create the char* from + * @param c The char* to write into + * @param len The maximum length of the char array. On return, it is the + * actual length of the char array. + */ +APU_DECLARE(apr_status_t) apr_brigade_flatten(apr_bucket_brigade *bb, + char *c, + apr_size_t *len); + +/** + * Creates a pool-allocated string representing a flat bucket brigade + * @param bb The bucket brigade to create the char array from + * @param c On return, the allocated char array + * @param len On return, the length of the char array. + * @param pool The pool to allocate the string from. + */ +APU_DECLARE(apr_status_t) apr_brigade_pflatten(apr_bucket_brigade *bb, + char **c, + apr_size_t *len, + apr_pool_t *pool); + +/** + * Split a brigade to represent one LF line. + * @param bbOut The bucket brigade that will have the LF line appended to. + * @param bbIn The input bucket brigade to search for a LF-line. + * @param block The blocking mode to be used to split the line. + * @param maxbytes The maximum bytes to read. If this many bytes are seen + * without a LF, the brigade will contain a partial line. + */ +APU_DECLARE(apr_status_t) apr_brigade_split_line(apr_bucket_brigade *bbOut, + apr_bucket_brigade *bbIn, + apr_read_type_e block, + apr_off_t maxbytes); + +/** + * Create an iovec of the elements in a bucket_brigade... return number + * of elements used. This is useful for writing to a file or to the + * network efficiently. + * @param b The bucket brigade to create the iovec from + * @param vec The iovec to create + * @param nvec The number of elements in the iovec. On return, it is the + * number of iovec elements actually filled out. + */ +APU_DECLARE(apr_status_t) apr_brigade_to_iovec(apr_bucket_brigade *b, + struct iovec *vec, int *nvec); + +/** + * This function writes a list of strings into a bucket brigade. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param va A list of strings to add + * @return APR_SUCCESS or error code. + */ +APU_DECLARE(apr_status_t) apr_brigade_vputstrs(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, + va_list va); + +/** + * This function writes a string into a bucket brigade. + * + * The apr_brigade_write function attempts to be efficient with the + * handling of heap buckets. Regardless of the amount of data stored + * inside a heap bucket, heap buckets are a fixed size to promote their + * reuse. + * + * If an attempt is made to write a string to a brigade that already + * ends with a heap bucket, this function will attempt to pack the + * string into the remaining space in the previous heap bucket, before + * allocating a new heap bucket. + * + * This function always returns APR_SUCCESS, unless a flush function is + * passed, in which case the return value of the flush function will be + * returned if used. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param str The string to add + * @param nbyte The number of bytes to write + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_write(apr_bucket_brigade *b, + apr_brigade_flush flush, void *ctx, + const char *str, apr_size_t nbyte); + +/** + * This function writes multiple strings into a bucket brigade. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param vec The strings to add (address plus length for each) + * @param nvec The number of entries in iovec + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_writev(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, + const struct iovec *vec, + apr_size_t nvec); + +/** + * This function writes a string into a bucket brigade. + * @param bb The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param str The string to add + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_puts(apr_bucket_brigade *bb, + apr_brigade_flush flush, void *ctx, + const char *str); + +/** + * This function writes a character into a bucket brigade. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param c The character to add + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_putc(apr_bucket_brigade *b, + apr_brigade_flush flush, void *ctx, + const char c); + +/** + * This function writes an unspecified number of strings into a bucket brigade. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param ... The strings to add + * @return APR_SUCCESS or error code + */ +APU_DECLARE_NONSTD(apr_status_t) apr_brigade_putstrs(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, ...); + +/** + * Evaluate a printf and put the resulting string at the end + * of the bucket brigade. + * @param b The brigade to write to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param fmt The format of the string to write + * @param ... The arguments to fill out the format + * @return APR_SUCCESS or error code + */ +APU_DECLARE_NONSTD(apr_status_t) apr_brigade_printf(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, + const char *fmt, ...) + __attribute__((format(printf,4,5))); + +/** + * Evaluate a printf and put the resulting string at the end + * of the bucket brigade. + * @param b The brigade to write to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param fmt The format of the string to write + * @param va The arguments to fill out the format + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_vprintf(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, + const char *fmt, va_list va); + +/** + * Utility function to insert a file (or a segment of a file) onto the + * end of the brigade. The file is split into multiple buckets if it + * is larger than the maximum size which can be represented by a + * single bucket. + * @param bb the brigade to insert into + * @param f the file to insert + * @param start the offset of the start of the segment + * @param len the length of the segment of the file to insert + * @param p pool from which file buckets are allocated + * @return the last bucket inserted + */ +APU_DECLARE(apr_bucket *) apr_brigade_insert_file(apr_bucket_brigade *bb, + apr_file_t *f, + apr_off_t start, + apr_off_t len, + apr_pool_t *p); + + + +/* ***** Bucket freelist functions ***** */ +/** + * Create a bucket allocator. + * @param p This pool's underlying apr_allocator_t is used to allocate memory + * for the bucket allocator. When the pool is destroyed, the bucket + * allocator's cleanup routine will free all memory that has been + * allocated from it. + * @remark The reason the allocator gets its memory from the pool's + * apr_allocator_t rather than from the pool itself is because + * the bucket allocator will free large memory blocks back to the + * allocator when it's done with them, thereby preventing memory + * footprint growth that would occur if we allocated from the pool. + * @warning The allocator must never be used by more than one thread at a time. + */ +APU_DECLARE_NONSTD(apr_bucket_alloc_t *) apr_bucket_alloc_create(apr_pool_t *p); + +/** + * Create a bucket allocator. + * @param allocator This apr_allocator_t is used to allocate both the bucket + * allocator and all memory handed out by the bucket allocator. The + * caller is responsible for destroying the bucket allocator and the + * apr_allocator_t -- no automatic cleanups will happen. + * @warning The allocator must never be used by more than one thread at a time. + */ +APU_DECLARE_NONSTD(apr_bucket_alloc_t *) apr_bucket_alloc_create_ex(apr_allocator_t *allocator); + +/** + * Destroy a bucket allocator. + * @param list The allocator to be destroyed + */ +APU_DECLARE_NONSTD(void) apr_bucket_alloc_destroy(apr_bucket_alloc_t *list); + +/** + * Get the aligned size corresponding to the requested size, but minus the + * allocator(s) overhead such that the allocation would remain in the + * same boundary. + * @param list The allocator from which to the memory would be allocated. + * @param size The requested size. + * @return The corresponding aligned/floored size. + */ +APU_DECLARE_NONSTD(apr_size_t) apr_bucket_alloc_aligned_floor(apr_bucket_alloc_t *list, + apr_size_t size) + __attribute__((nonnull(1))); + +/** + * Allocate memory for use by the buckets. + * @param size The amount to allocate. + * @param list The allocator from which to allocate the memory. + */ +APU_DECLARE_NONSTD(void *) apr_bucket_alloc(apr_size_t size, apr_bucket_alloc_t *list); + +/** + * Free memory previously allocated with apr_bucket_alloc(). + * @param block The block of memory to be freed. + */ +APU_DECLARE_NONSTD(void) apr_bucket_free(void *block); + + +/* ***** Bucket Functions ***** */ +/** + * Free the resources used by a bucket. If multiple buckets refer to + * the same resource it is freed when the last one goes away. + * @see apr_bucket_delete() + * @param e The bucket to destroy + */ +#define apr_bucket_destroy(e) do { \ + (e)->type->destroy((e)->data); \ + (e)->free(e); \ + } while (0) + +/** + * Delete a bucket by removing it from its brigade (if any) and then + * destroying it. + * @remark This mainly acts as an aid in avoiding code verbosity. It is + * the preferred exact equivalent to: + *
+ *      APR_BUCKET_REMOVE(e);
+ *      apr_bucket_destroy(e);
+ * 
+ * @param e The bucket to delete + */ +#define apr_bucket_delete(e) do { \ + APR_BUCKET_REMOVE(e); \ + apr_bucket_destroy(e); \ + } while (0) + +/** + * Read some data from the bucket. + * + * The apr_bucket_read function returns a convenient amount of data + * from the bucket provided, writing the address and length of the + * data to the pointers provided by the caller. The function tries + * as hard as possible to avoid a memory copy. + * + * Buckets are expected to be a member of a brigade at the time they + * are read. + * + * In typical application code, buckets are read in a loop, and after + * each bucket is read and processed, it is moved or deleted from the + * brigade and the next bucket read. + * + * The definition of "convenient" depends on the type of bucket that + * is being read, and is decided by APR. In the case of memory based + * buckets such as heap and immortal buckets, a pointer will be + * returned to the location of the buffer containing the complete + * contents of the bucket. + * + * Some buckets, such as the socket bucket, might have no concept + * of length. If an attempt is made to read such a bucket, the + * apr_bucket_read function will read a convenient amount of data + * from the socket. The socket bucket is magically morphed into a + * heap bucket containing the just-read data, and a new socket bucket + * is inserted just after this heap bucket. + * + * To understand why apr_bucket_read might do this, consider the loop + * described above to read and process buckets. The current bucket + * is magically morphed into a heap bucket and returned to the caller. + * The caller processes the data, and deletes the heap bucket, moving + * onto the next bucket, the new socket bucket. This process repeats, + * giving the illusion of a bucket brigade that contains potentially + * infinite amounts of data. It is up to the caller to decide at what + * point to stop reading buckets. + * + * Some buckets, such as the file bucket, might have a fixed size, + * but be significantly larger than is practical to store in RAM in + * one go. As with the socket bucket, if an attempt is made to read + * from a file bucket, the file bucket is magically morphed into a + * heap bucket containing a convenient amount of data read from the + * current offset in the file. During the read, the offset will be + * moved forward on the file, and a new file bucket will be inserted + * directly after the current bucket representing the remainder of the + * file. If the heap bucket was large enough to store the whole + * remainder of the file, no more file buckets are inserted, and the + * file bucket will disappear completely. + * + * The pattern for reading buckets described above does create the + * illusion that the code is willing to swallow buckets that might be + * too large for the system to handle in one go. This however is just + * an illusion: APR will always ensure that large (file) or infinite + * (socket) buckets are broken into convenient bite sized heap buckets + * before data is returned to the caller. + * + * There is a potential gotcha to watch for: if buckets are read in a + * loop, and aren't deleted after being processed, the potentially large + * bucket will slowly be converted into RAM resident heap buckets. If + * the file is larger than available RAM, an out of memory condition + * could be caused if the application is not careful to manage this. + * + * @param e The bucket to read from + * @param str The location to store a pointer to the data in + * @param len The location to store the amount of data read + * @param block Whether the read function blocks + */ +#define apr_bucket_read(e,str,len,block) (e)->type->read(e, str, len, block) + +/** + * Setaside data so that stack data is not destroyed on returning from + * the function + * @param e The bucket to setaside + * @param p The pool to setaside into + */ +#define apr_bucket_setaside(e,p) (e)->type->setaside(e,p) + +/** + * Split one bucket in two at the point provided. + * + * Once split, the original bucket becomes the first of the two new buckets. + * + * (It is assumed that the bucket is a member of a brigade when this + * function is called). + * @param e The bucket to split + * @param point The offset to split the bucket at + */ +#define apr_bucket_split(e,point) (e)->type->split(e, point) + +/** + * Copy a bucket. + * @param e The bucket to copy + * @param c Returns a pointer to the new bucket + */ +#define apr_bucket_copy(e,c) (e)->type->copy(e, c) + +/* Bucket type handling */ + +/** + * This function simply returns APR_SUCCESS to denote that the bucket does + * not require anything to happen for its setaside() function. This is + * appropriate for buckets that have "immortal" data -- the data will live + * at least as long as the bucket. + * @param data The bucket to setaside + * @param pool The pool defining the desired lifetime of the bucket data + * @return APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_setaside_noop(apr_bucket *data, + apr_pool_t *pool); + +/** + * A place holder function that signifies that the setaside function was not + * implemented for this bucket + * @param data The bucket to setaside + * @param pool The pool defining the desired lifetime of the bucket data + * @return APR_ENOTIMPL + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_setaside_notimpl(apr_bucket *data, + apr_pool_t *pool); + +/** + * A place holder function that signifies that the split function was not + * implemented for this bucket + * @param data The bucket to split + * @param point The location to split the bucket + * @return APR_ENOTIMPL + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_split_notimpl(apr_bucket *data, + apr_size_t point); + +/** + * A place holder function that signifies that the copy function was not + * implemented for this bucket + * @param e The bucket to copy + * @param c Returns a pointer to the new bucket + * @return APR_ENOTIMPL + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_copy_notimpl(apr_bucket *e, + apr_bucket **c); + +/** + * A place holder function that signifies that this bucket does not need + * to do anything special to be destroyed. That's only the case for buckets + * that either have no data (metadata buckets) or buckets whose data pointer + * points to something that's not a bucket-type-specific structure, as with + * simple buckets where data points to a string and pipe buckets where data + * points directly to the apr_file_t. + * @param data The bucket data to destroy + */ +APU_DECLARE_NONSTD(void) apr_bucket_destroy_noop(void *data); + +/** + * There is no apr_bucket_destroy_notimpl, because destruction is required + * to be implemented (it could be a noop, but only if that makes sense for + * the bucket type) + */ + +/* There is no apr_bucket_read_notimpl, because it is a required function + */ + + +/* All of the bucket types implemented by the core */ +/** + * The flush bucket type. This signifies that all data should be flushed to + * the next filter. The flush bucket should be sent with the other buckets. + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_flush; +/** + * The EOS bucket type. This signifies that there will be no more data, ever. + * All filters MUST send all data to the next filter when they receive a + * bucket of this type + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_eos; +/** + * The FILE bucket type. This bucket represents a file on disk + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_file; +/** + * The HEAP bucket type. This bucket represents a data allocated from the + * heap. + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_heap; +#if APR_HAS_MMAP +/** + * The MMAP bucket type. This bucket represents an MMAP'ed file + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_mmap; +#endif +/** + * The POOL bucket type. This bucket represents a data that was allocated + * from a pool. IF this bucket is still available when the pool is cleared, + * the data is copied on to the heap. + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_pool; +/** + * The PIPE bucket type. This bucket represents a pipe to another program. + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_pipe; +/** + * The IMMORTAL bucket type. This bucket represents a segment of data that + * the creator is willing to take responsibility for. The core will do + * nothing with the data in an immortal bucket + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_immortal; +/** + * The TRANSIENT bucket type. This bucket represents a data allocated off + * the stack. When the setaside function is called, this data is copied on + * to the heap + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_transient; +/** + * The SOCKET bucket type. This bucket represents a socket to another machine + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_socket; + + +/* ***** Simple buckets ***** */ + +/** + * Split a simple bucket into two at the given point. Most non-reference + * counting buckets that allow multiple references to the same block of + * data (eg transient and immortal) will use this as their split function + * without any additional type-specific handling. + * @param b The bucket to be split + * @param point The offset of the first byte in the new bucket + * @return APR_EINVAL if the point is not within the bucket; + * APR_ENOMEM if allocation failed; + * or APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_simple_split(apr_bucket *b, + apr_size_t point); + +/** + * Copy a simple bucket. Most non-reference-counting buckets that allow + * multiple references to the same block of data (eg transient and immortal) + * will use this as their copy function without any additional type-specific + * handling. + * @param a The bucket to copy + * @param b Returns a pointer to the new bucket + * @return APR_ENOMEM if allocation failed; + * or APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_simple_copy(apr_bucket *a, + apr_bucket **b); + + +/* ***** Shared, reference-counted buckets ***** */ + +/** + * Initialize a bucket containing reference-counted data that may be + * shared. The caller must allocate the bucket if necessary and + * initialize its type-dependent fields, and allocate and initialize + * its own private data structure. This function should only be called + * by type-specific bucket creation functions. + * @param b The bucket to initialize + * @param data A pointer to the private data structure + * with the reference count at the start + * @param start The start of the data in the bucket + * relative to the private base pointer + * @param length The length of the data in the bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_shared_make(apr_bucket *b, void *data, + apr_off_t start, + apr_size_t length); + +/** + * Decrement the refcount of the data in the bucket. This function + * should only be called by type-specific bucket destruction functions. + * @param data The private data pointer from the bucket to be destroyed + * @return TRUE or FALSE; TRUE if the reference count is now + * zero, indicating that the shared resource itself can + * be destroyed by the caller. + */ +APU_DECLARE(int) apr_bucket_shared_destroy(void *data); + +/** + * Split a bucket into two at the given point, and adjust the refcount + * to the underlying data. Most reference-counting bucket types will + * be able to use this function as their split function without any + * additional type-specific handling. + * @param b The bucket to be split + * @param point The offset of the first byte in the new bucket + * @return APR_EINVAL if the point is not within the bucket; + * APR_ENOMEM if allocation failed; + * or APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_shared_split(apr_bucket *b, + apr_size_t point); + +/** + * Copy a refcounted bucket, incrementing the reference count. Most + * reference-counting bucket types will be able to use this function + * as their copy function without any additional type-specific handling. + * @param a The bucket to copy + * @param b Returns a pointer to the new bucket + * @return APR_ENOMEM if allocation failed; + or APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_shared_copy(apr_bucket *a, + apr_bucket **b); + + +/* ***** Functions to Create Buckets of varying types ***** */ +/* + * Each bucket type foo has two initialization functions: + * apr_bucket_foo_make which sets up some already-allocated memory as a + * bucket of type foo; and apr_bucket_foo_create which allocates memory + * for the bucket, calls apr_bucket_make_foo, and initializes the + * bucket's list pointers. The apr_bucket_foo_make functions are used + * inside the bucket code to change the type of buckets in place; + * other code should call apr_bucket_foo_create. All the initialization + * functions change nothing if they fail. + */ + +/** + * Create an End of Stream bucket. This indicates that there is no more data + * coming from down the filter stack. All filters should flush at this point. + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_eos_create(apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in an EOS bucket. This indicates that there is no + * more data coming from down the filter stack. All filters should flush at + * this point. + * @param b The bucket to make into an EOS bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_eos_make(apr_bucket *b); + +/** + * Create a flush bucket. This indicates that filters should flush their + * data. There is no guarantee that they will flush it, but this is the + * best we can do. + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_flush_create(apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a FLUSH bucket. This indicates that filters + * should flush their data. There is no guarantee that they will flush it, + * but this is the best we can do. + * @param b The bucket to make into a FLUSH bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_flush_make(apr_bucket *b); + +/** + * Create a bucket referring to long-lived data. + * @param buf The data to insert into the bucket + * @param nbyte The size of the data to insert. + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_immortal_create(const char *buf, + apr_size_t nbyte, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to long-lived data + * @param b The bucket to make into a IMMORTAL bucket + * @param buf The data to insert into the bucket + * @param nbyte The size of the data to insert. + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_immortal_make(apr_bucket *b, + const char *buf, + apr_size_t nbyte); + +/** + * Create a bucket referring to data on the stack. + * @param buf The data to insert into the bucket + * @param nbyte The size of the data to insert. + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_transient_create(const char *buf, + apr_size_t nbyte, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to stack data + * @param b The bucket to make into a TRANSIENT bucket + * @param buf The data to insert into the bucket + * @param nbyte The size of the data to insert. + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_transient_make(apr_bucket *b, + const char *buf, + apr_size_t nbyte); + +/** + * Create a bucket referring to memory on the heap. If the caller asks + * for the data to be copied, this function always allocates 4K of + * memory so that more data can be added to the bucket without + * requiring another allocation. Therefore not all the data may be put + * into the bucket. If copying is not requested then the bucket takes + * over responsibility for free()ing the memory. + * @param buf The buffer to insert into the bucket + * @param nbyte The size of the buffer to insert. + * @param free_func Function to use to free the data; NULL indicates that the + * bucket should make a copy of the data + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_heap_create(const char *buf, + apr_size_t nbyte, + void (*free_func)(void *data), + apr_bucket_alloc_t *list); +/** + * Make the bucket passed in a bucket refer to heap data + * @param b The bucket to make into a HEAP bucket + * @param buf The buffer to insert into the bucket + * @param nbyte The size of the buffer to insert. + * @param free_func Function to use to free the data; NULL indicates that the + * bucket should make a copy of the data + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_heap_make(apr_bucket *b, const char *buf, + apr_size_t nbyte, + void (*free_func)(void *data)); + +/** + * Create a bucket referring to memory allocated from a pool. + * + * @param buf The buffer to insert into the bucket + * @param length The number of bytes referred to by this bucket + * @param pool The pool the memory was allocated from + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_pool_create(const char *buf, + apr_size_t length, + apr_pool_t *pool, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to pool data + * @param b The bucket to make into a pool bucket + * @param buf The buffer to insert into the bucket + * @param length The number of bytes referred to by this bucket + * @param pool The pool the memory was allocated from + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_pool_make(apr_bucket *b, const char *buf, + apr_size_t length, + apr_pool_t *pool); + +#if APR_HAS_MMAP +/** + * Create a bucket referring to mmap()ed memory. + * @param mm The mmap to insert into the bucket + * @param start The offset of the first byte in the mmap + * that this bucket refers to + * @param length The number of bytes referred to by this bucket + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_mmap_create(apr_mmap_t *mm, + apr_off_t start, + apr_size_t length, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to an MMAP'ed file + * @param b The bucket to make into a MMAP bucket + * @param mm The mmap to insert into the bucket + * @param start The offset of the first byte in the mmap + * that this bucket refers to + * @param length The number of bytes referred to by this bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_mmap_make(apr_bucket *b, apr_mmap_t *mm, + apr_off_t start, + apr_size_t length); +#endif + +/** + * Create a bucket referring to a socket. + * @param thissock The socket to put in the bucket + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_socket_create(apr_socket_t *thissock, + apr_bucket_alloc_t *list); +/** + * Make the bucket passed in a bucket refer to a socket + * @param b The bucket to make into a SOCKET bucket + * @param thissock The socket to put in the bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_socket_make(apr_bucket *b, + apr_socket_t *thissock); + +/** + * Create a bucket referring to a pipe. + * @param thispipe The pipe to put in the bucket + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_pipe_create(apr_file_t *thispipe, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to a pipe + * @param b The bucket to make into a PIPE bucket + * @param thispipe The pipe to put in the bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_pipe_make(apr_bucket *b, + apr_file_t *thispipe); + +/** + * Create a bucket referring to a file. + * @param fd The file to put in the bucket + * @param offset The offset where the data of interest begins in the file + * @param len The amount of data in the file we are interested in + * @param p The pool into which any needed structures should be created + * while reading from this file bucket + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + * @remark If the file is truncated such that the segment of the file + * referenced by the bucket no longer exists, an attempt to read + * from the bucket will fail with APR_EOF. + * @remark apr_brigade_insert_file() should generally be used to + * insert files into brigades, since that function can correctly + * handle large file issues. + */ +APU_DECLARE(apr_bucket *) apr_bucket_file_create(apr_file_t *fd, + apr_off_t offset, + apr_size_t len, + apr_pool_t *p, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to a file + * @param b The bucket to make into a FILE bucket + * @param fd The file to put in the bucket + * @param offset The offset where the data of interest begins in the file + * @param len The amount of data in the file we are interested in + * @param p The pool into which any needed structures should be created + * while reading from this file bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_file_make(apr_bucket *b, apr_file_t *fd, + apr_off_t offset, + apr_size_t len, apr_pool_t *p); + +/** + * Enable or disable memory-mapping for a FILE bucket (default is enabled) + * @param b The bucket + * @param enabled Whether memory-mapping should be enabled + * @return APR_SUCCESS normally, or an error code if the operation fails + */ +APU_DECLARE(apr_status_t) apr_bucket_file_enable_mmap(apr_bucket *b, + int enabled); + +/** + * Set the size of the read buffer allocated by a FILE bucket (default + * is @a APR_BUCKET_BUFF_SIZE) + * memory-mapping is disabled only) + * @param b The bucket + * @param size Size of the allocated buffers + * @return APR_SUCCESS normally, or an error code if the operation fails + * @remark Relevant/used only when memory-mapping is disabled (@see + * apr_bucket_file_enable_mmap) + */ +APU_DECLARE(apr_status_t) apr_bucket_file_set_buf_size(apr_bucket *e, + apr_size_t size); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_BUCKETS_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_crypto.h b/c/dependencies/windows/apr/x64/include/apr_crypto.h new file mode 100644 index 00000000..b90f3fec --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_crypto.h @@ -0,0 +1,507 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_CRYPTO_H +#define APR_CRYPTO_H + +#include "apu.h" +#include "apr_pools.h" +#include "apr_tables.h" +#include "apr_hash.h" +#include "apu_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_crypto.h + * @brief APR-UTIL Crypto library + */ +/** + * @defgroup APR_Util_Crypto Crypto routines + * @ingroup APR_Util + * @{ + */ + +#if APU_HAVE_CRYPTO + +#ifndef APU_CRYPTO_RECOMMENDED_DRIVER +#if APU_HAVE_COMMONCRYPTO +#define APU_CRYPTO_RECOMMENDED_DRIVER "commoncrypto" +#else +#if APU_HAVE_OPENSSL +#define APU_CRYPTO_RECOMMENDED_DRIVER "openssl" +#else +#if APU_HAVE_NSS +#define APU_CRYPTO_RECOMMENDED_DRIVER "nss" +#else +#if APU_HAVE_MSCNG +#define APU_CRYPTO_RECOMMENDED_DRIVER "mscng" +#else +#if APU_HAVE_MSCAPI +#define APU_CRYPTO_RECOMMENDED_DRIVER "mscapi" +#else +#endif +#endif +#endif +#endif +#endif +#endif + +/** + * Symmetric Key types understood by the library. + * + * NOTE: It is expected that this list will grow over time. + * + * Interoperability Matrix: + * + * The matrix is based on the testcrypto.c unit test, which attempts to + * test whether a simple encrypt/decrypt will succeed, as well as testing + * whether an encrypted string by one library can be decrypted by the + * others. + * + * Some libraries will successfully encrypt and decrypt their own data, + * but won't decrypt data from another library. It is hoped that over + * time these anomalies will be found and fixed, but until then it is + * recommended that ciphers are chosen that interoperate across platform. + * + * An X below means the test passes, it does not necessarily mean that + * encryption performed is correct or secure. Applications should stick + * to ciphers that pass the interoperablity tests on the right hand side + * of the table. + * + * Aligned data is data whose length is a multiple of the block size for + * the chosen cipher. Padded data is data that is not aligned by block + * size and must be padded by the crypto library. + * + * OpenSSL CommonCrypto NSS Interop + * Align Pad Align Pad Align Pad Align Pad + * 3DES_192/CBC X X X X X X X X + * 3DES_192/ECB X X X X + * AES_256/CBC X X X X X X X X + * AES_256/ECB X X X X X X + * AES_192/CBC X X X X X X + * AES_192/ECB X X X X X + * AES_128/CBC X X X X X X + * AES_128/ECB X X X X X + * + * Conclusion: for padded data, use 3DES_192/CBC or AES_256/CBC. For + * aligned data, use 3DES_192/CBC, AES_256/CBC or AES_256/ECB. + */ + +typedef enum +{ + APR_KEY_NONE, APR_KEY_3DES_192, /** 192 bit (3-Key) 3DES */ + APR_KEY_AES_128, /** 128 bit AES */ + APR_KEY_AES_192, /** 192 bit AES */ + APR_KEY_AES_256 +/** 256 bit AES */ +} apr_crypto_block_key_type_e; + +typedef enum +{ + APR_MODE_NONE, /** An error condition */ + APR_MODE_ECB, /** Electronic Code Book */ + APR_MODE_CBC +/** Cipher Block Chaining */ +} apr_crypto_block_key_mode_e; + +/* These are opaque structs. Instantiation is up to each backend */ +typedef struct apr_crypto_driver_t apr_crypto_driver_t; +typedef struct apr_crypto_t apr_crypto_t; +typedef struct apr_crypto_config_t apr_crypto_config_t; +typedef struct apr_crypto_key_t apr_crypto_key_t; +typedef struct apr_crypto_block_t apr_crypto_block_t; + +typedef struct apr_crypto_block_key_type_t { + apr_crypto_block_key_type_e type; + int keysize; + int blocksize; + int ivsize; +} apr_crypto_block_key_type_t; + +typedef struct apr_crypto_block_key_mode_t { + apr_crypto_block_key_mode_e mode; +} apr_crypto_block_key_mode_t; + +typedef struct apr_crypto_passphrase_t { + const char *pass; + apr_size_t passLen; + const unsigned char * salt; + apr_size_t saltLen; + int iterations; +} apr_crypto_passphrase_t; + +typedef struct apr_crypto_secret_t { + const unsigned char *secret; + apr_size_t secretLen; +} apr_crypto_secret_t; + +typedef enum { + /** Key is derived from a passphrase */ + APR_CRYPTO_KTYPE_PASSPHRASE = 1, + /** Key is derived from a raw key */ + APR_CRYPTO_KTYPE_SECRET = 2, +} apr_crypto_key_type; + +typedef struct apr_crypto_key_rec_t { + apr_crypto_key_type ktype; + apr_crypto_block_key_type_e type; + apr_crypto_block_key_mode_e mode; + int pad; + union { + apr_crypto_passphrase_t passphrase; + apr_crypto_secret_t secret; + } k; +} apr_crypto_key_rec_t; + +/** + * @brief Perform once-only initialisation. Call once only. + * + * @param pool - pool to register any shutdown cleanups, etc + * @return APR_NOTIMPL in case of no crypto support. + */ +APU_DECLARE(apr_status_t) apr_crypto_init(apr_pool_t *pool); + +/** + * @brief Zero out the buffer provided when the pool is cleaned up. + * + * @param pool - pool to register the cleanup + * @param buffer - buffer to zero out + * @param size - size of the buffer to zero out + */ +APU_DECLARE(apr_status_t) apr_crypto_clear(apr_pool_t *pool, void *buffer, + apr_size_t size); + +/** + * @brief Always zero out the buffer provided, without being optimized out by + * the compiler. + * + * @param buffer - buffer to zero out + * @param size - size of the buffer to zero out + */ +APU_DECLARE(apr_status_t) apr_crypto_memzero(void *buffer, apr_size_t size); + +/** + * @brief Timing attacks safe buffers comparison, where the executing time does + * not depend on the bytes compared but solely on the number of bytes. + * + * @param buf1 - first buffer to compare + * @param buf2 - second buffer to compare + * @param size - size of the buffers to compare + * @return 1 if the buffers are equals, 0 otherwise. + */ +APU_DECLARE(int) apr_crypto_equals(const void *buf1, const void *buf2, + apr_size_t size); + +/** + * @brief Get the driver struct for a name + * + * @param driver - pointer to driver struct. + * @param name - driver name + * @param params - array of initialisation parameters + * @param result - result and error message on failure + * @param pool - (process) pool to register cleanup + * @return APR_SUCCESS for success + * @return APR_ENOTIMPL for no driver (when DSO not enabled) + * @return APR_EDSOOPEN if DSO driver file can't be opened + * @return APR_ESYMNOTFOUND if the driver file doesn't contain a driver + * @remarks NSS: the params can have "dir", "key3", "cert7" and "secmod" + * keys, each followed by an equal sign and a value. Such key/value pairs can + * be delimited by space or tab. If the value contains a space, surround the + * whole key value pair in quotes: "dir=My Directory". + * @remarks OpenSSL: currently no params are supported. + */ +APU_DECLARE(apr_status_t) apr_crypto_get_driver( + const apr_crypto_driver_t **driver, + const char *name, const char *params, const apu_err_t **result, + apr_pool_t *pool); + +/** + * @brief Return the name of the driver. + * + * @param driver - The driver in use. + * @return The name of the driver. + */ +APU_DECLARE(const char *) apr_crypto_driver_name( + const apr_crypto_driver_t *driver); + +/** + * @brief Get the result of the last operation on a context. If the result + * is NULL, the operation was successful. + * @param result - the result structure + * @param f - context pointer + * @return APR_SUCCESS for success + */ +APU_DECLARE(apr_status_t) apr_crypto_error(const apu_err_t **result, + const apr_crypto_t *f); + +/** + * @brief Create a context for supporting encryption. Keys, certificates, + * algorithms and other parameters will be set per context. More than + * one context can be created at one time. A cleanup will be automatically + * registered with the given pool to guarantee a graceful shutdown. + * @param f - context pointer will be written here + * @param driver - driver to use + * @param params - array of key parameters + * @param pool - process pool + * @return APR_ENOENGINE when the engine specified does not exist. APR_EINITENGINE + * if the engine cannot be initialised. + * @remarks NSS: currently no params are supported. + * @remarks OpenSSL: the params can have "engine" as a key, followed by an equal + * sign and a value. + */ +APU_DECLARE(apr_status_t) apr_crypto_make(apr_crypto_t **f, + const apr_crypto_driver_t *driver, const char *params, + apr_pool_t *pool); + +/** + * @brief Get a hash table of key types, keyed by the name of the type against + * a pointer to apr_crypto_block_key_type_t, which in turn begins with an + * integer. + * + * @param types - hashtable of key types keyed to constants. + * @param f - encryption context + * @return APR_SUCCESS for success + */ +APU_DECLARE(apr_status_t) apr_crypto_get_block_key_types(apr_hash_t **types, + const apr_crypto_t *f); + +/** + * @brief Get a hash table of key modes, keyed by the name of the mode against + * a pointer to apr_crypto_block_key_mode_t, which in turn begins with an + * integer. + * + * @param modes - hashtable of key modes keyed to constants. + * @param f - encryption context + * @return APR_SUCCESS for success + */ +APU_DECLARE(apr_status_t) apr_crypto_get_block_key_modes(apr_hash_t **modes, + const apr_crypto_t *f); + +/** + * @brief Create a key from the provided secret or passphrase. The key is cleaned + * up when the context is cleaned, and may be reused with multiple encryption + * or decryption operations. + * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If + * *key is not NULL, *key must point at a previously created structure. + * @param key The key returned, see note. + * @param rec The key record, from which the key will be derived. + * @param f The context to use. + * @param p The pool to use. + * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend + * error occurred while generating the key. APR_ENOCIPHER if the type or mode + * is not supported by the particular backend. APR_EKEYTYPE if the key type is + * not known. APR_EPADDING if padding was requested but is not supported. + * APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_key(apr_crypto_key_t **key, + const apr_crypto_key_rec_t *rec, const apr_crypto_t *f, apr_pool_t *p); + +/** + * @brief Create a key from the given passphrase. By default, the PBKDF2 + * algorithm is used to generate the key from the passphrase. It is expected + * that the same pass phrase will generate the same key, regardless of the + * backend crypto platform used. The key is cleaned up when the context + * is cleaned, and may be reused with multiple encryption or decryption + * operations. + * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If + * *key is not NULL, *key must point at a previously created structure. + * @param key The key returned, see note. + * @param ivSize The size of the initialisation vector will be returned, based + * on whether an IV is relevant for this type of crypto. + * @param pass The passphrase to use. + * @param passLen The passphrase length in bytes + * @param salt The salt to use. + * @param saltLen The salt length in bytes + * @param type 3DES_192, AES_128, AES_192, AES_256. + * @param mode Electronic Code Book / Cipher Block Chaining. + * @param doPad Pad if necessary. + * @param iterations Number of iterations to use in algorithm + * @param f The context to use. + * @param p The pool to use. + * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend + * error occurred while generating the key. APR_ENOCIPHER if the type or mode + * is not supported by the particular backend. APR_EKEYTYPE if the key type is + * not known. APR_EPADDING if padding was requested but is not supported. + * APR_ENOTIMPL if not implemented. + * @deprecated Replaced by apr_crypto_key(). + */ +APU_DECLARE(apr_status_t) apr_crypto_passphrase(apr_crypto_key_t **key, + apr_size_t *ivSize, const char *pass, apr_size_t passLen, + const unsigned char * salt, apr_size_t saltLen, + const apr_crypto_block_key_type_e type, + const apr_crypto_block_key_mode_e mode, const int doPad, + const int iterations, const apr_crypto_t *f, apr_pool_t *p); + +/** + * @brief Initialise a context for encrypting arbitrary data using the given key. + * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If + * *ctx is not NULL, *ctx must point at a previously created structure. + * @param ctx The block context returned, see note. + * @param iv Optional initialisation vector. If the buffer pointed to is NULL, + * an IV will be created at random, in space allocated from the pool. + * If the buffer pointed to is not NULL, the IV in the buffer will be + * used. + * @param key The key structure to use. + * @param blockSize The block size of the cipher. + * @param p The pool to use. + * @return Returns APR_ENOIV if an initialisation vector is required but not specified. + * Returns APR_EINIT if the backend failed to initialise the context. Returns + * APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_encrypt_init( + apr_crypto_block_t **ctx, const unsigned char **iv, + const apr_crypto_key_t *key, apr_size_t *blockSize, apr_pool_t *p); + +/** + * @brief Encrypt data provided by in, write it to out. + * @note The number of bytes written will be written to outlen. If + * out is NULL, outlen will contain the maximum size of the + * buffer needed to hold the data, including any data + * generated by apr_crypto_block_encrypt_finish below. If *out points + * to NULL, a buffer sufficiently large will be created from + * the pool provided. If *out points to a not-NULL value, this + * value will be used as a buffer instead. + * @param out Address of a buffer to which data will be written, + * see note. + * @param outlen Length of the output will be written here. + * @param in Address of the buffer to read. + * @param inlen Length of the buffer to read. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if + * not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_encrypt(unsigned char **out, + apr_size_t *outlen, const unsigned char *in, apr_size_t inlen, + apr_crypto_block_t *ctx); + +/** + * @brief Encrypt final data block, write it to out. + * @note If necessary the final block will be written out after being + * padded. Typically the final block will be written to the + * same buffer used by apr_crypto_block_encrypt, offset by the + * number of bytes returned as actually written by the + * apr_crypto_block_encrypt() call. After this call, the context + * is cleaned and can be reused by apr_crypto_block_encrypt_init(). + * @param out Address of a buffer to which data will be written. This + * buffer must already exist, and is usually the same + * buffer used by apr_evp_crypt(). See note. + * @param outlen Length of the output will be written here. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. + * @return APR_EPADDING if padding was enabled and the block was incorrectly + * formatted. + * @return APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_encrypt_finish(unsigned char *out, + apr_size_t *outlen, apr_crypto_block_t *ctx); + +/** + * @brief Initialise a context for decrypting arbitrary data using the given key. + * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If + * *ctx is not NULL, *ctx must point at a previously created structure. + * @param ctx The block context returned, see note. + * @param blockSize The block size of the cipher. + * @param iv Optional initialisation vector. + * @param key The key structure to use. + * @param p The pool to use. + * @return Returns APR_ENOIV if an initialisation vector is required but not specified. + * Returns APR_EINIT if the backend failed to initialise the context. Returns + * APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_decrypt_init( + apr_crypto_block_t **ctx, apr_size_t *blockSize, + const unsigned char *iv, const apr_crypto_key_t *key, apr_pool_t *p); + +/** + * @brief Decrypt data provided by in, write it to out. + * @note The number of bytes written will be written to outlen. If + * out is NULL, outlen will contain the maximum size of the + * buffer needed to hold the data, including any data + * generated by apr_crypto_block_decrypt_finish below. If *out points + * to NULL, a buffer sufficiently large will be created from + * the pool provided. If *out points to a not-NULL value, this + * value will be used as a buffer instead. + * @param out Address of a buffer to which data will be written, + * see note. + * @param outlen Length of the output will be written here. + * @param in Address of the buffer to read. + * @param inlen Length of the buffer to read. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if + * not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_decrypt(unsigned char **out, + apr_size_t *outlen, const unsigned char *in, apr_size_t inlen, + apr_crypto_block_t *ctx); + +/** + * @brief Decrypt final data block, write it to out. + * @note If necessary the final block will be written out after being + * padded. Typically the final block will be written to the + * same buffer used by apr_crypto_block_decrypt, offset by the + * number of bytes returned as actually written by the + * apr_crypto_block_decrypt() call. After this call, the context + * is cleaned and can be reused by apr_crypto_block_decrypt_init(). + * @param out Address of a buffer to which data will be written. This + * buffer must already exist, and is usually the same + * buffer used by apr_evp_crypt(). See note. + * @param outlen Length of the output will be written here. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. + * @return APR_EPADDING if padding was enabled and the block was incorrectly + * formatted. + * @return APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_decrypt_finish(unsigned char *out, + apr_size_t *outlen, apr_crypto_block_t *ctx); + +/** + * @brief Clean encryption / decryption context. + * @note After cleanup, a context is free to be reused if necessary. + * @param ctx The block context to use. + * @return Returns APR_ENOTIMPL if not supported. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_cleanup(apr_crypto_block_t *ctx); + +/** + * @brief Clean encryption / decryption context. + * @note After cleanup, a context is free to be reused if necessary. + * @param f The context to use. + * @return Returns APR_ENOTIMPL if not supported. + */ +APU_DECLARE(apr_status_t) apr_crypto_cleanup(apr_crypto_t *f); + +/** + * @brief Shutdown the crypto library. + * @note After shutdown, it is expected that the init function can be called again. + * @param driver - driver to use + * @return Returns APR_ENOTIMPL if not supported. + */ +APU_DECLARE(apr_status_t) apr_crypto_shutdown( + const apr_crypto_driver_t *driver); + +#endif /* APU_HAVE_CRYPTO */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/c/dependencies/windows/apr/x64/include/apr_cstr.h b/c/dependencies/windows/apr/x64/include/apr_cstr.h new file mode 100644 index 00000000..3f1b1a09 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_cstr.h @@ -0,0 +1,292 @@ +/* ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * ==================================================================== + */ + +/** + * @file apr_cstr.h + * @brief C string goodies. + */ + +#ifndef APR_CSTR_H +#define APR_CSTR_H + +#include /* for apr_size_t */ +#include /* for apr_pool_t */ +#include /* for apr_array_header_t */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_cstr C (POSIX) locale string functions + * @ingroup apr_strings + * + * The apr_cstr_* functions provide traditional C char * string text handling, + * and notabilty they treat all text in the C (a.k.a. POSIX) locale using the + * minimal POSIX character set, represented in either ASCII or a corresponding + * EBCDIC subset. + * + * Character values outside of that set are treated as opaque bytes, and all + * multi-byte character sequences are handled as individual distinct octets. + * + * Multi-byte characters sequences whose octets fall in the ASCII range cause + * unexpected results, such as in the ISO-2022-JP code page where ASCII octets + * occur within both shift-state and multibyte sequences. + * + * In the case of the UTF-8 encoding, all multibyte characters all fall outside + * of the C/POSIX range of characters, so these functions are generally safe + * to use on UTF-8 strings. The programmer must be aware that each octet may + * not represent a distinct printable character in such encodings. + * + * The standard C99/POSIX string functions, rather than apr_cstr, should be + * used in all cases where the current locale and encoding of the text is + * significant. + * @{ + */ + + +/** Divide @a input into substrings, interpreting any char from @a sep + * as a token separator. + * + * Return an array of copies of those substrings (plain const char*), + * allocating both the array and the copies in @a pool. + * + * None of the elements added to the array contain any of the + * characters in @a sep_chars, and none of the new elements are empty + * (thus, it is possible that the returned array will have length + * zero). + * + * If @a chop_whitespace is TRUE, then remove leading and trailing + * whitespace from the returned strings. + * + * @since New in 1.6 + */ +APR_DECLARE(apr_array_header_t *) apr_cstr_split(const char *input, + const char *sep_chars, + int chop_whitespace, + apr_pool_t *pool); + +/** Like apr_cstr_split(), but append to existing @a array instead of + * creating a new one. Allocate the copied substrings in @a pool + * (i.e., caller decides whether or not to pass @a array->pool as @a pool). + * + * @since New in 1.6 + */ +APR_DECLARE(void) apr_cstr_split_append(apr_array_header_t *array, + const char *input, + const char *sep_chars, + int chop_whitespace, + apr_pool_t *pool); + + +/** Return @c TRUE iff @a str matches any of the elements of @a list, a list + * of zero or more glob patterns. + * + * @since New in 1.6 + */ +APR_DECLARE(int) apr_cstr_match_glob_list(const char *str, + const apr_array_header_t *list); + +/** Return @c TRUE iff @a str exactly matches any of the elements of @a list. + * + * @since New in 1.6 + */ +APR_DECLARE(int) apr_cstr_match_list(const char *str, + const apr_array_header_t *list); + +/** + * Get the next token from @a *str interpreting any char from @a sep as a + * token separator. Separators at the beginning of @a str will be skipped. + * Returns a pointer to the beginning of the first token in @a *str or NULL + * if no token is left. Modifies @a str such that the next call will return + * the next token. + * + * @note The content of @a *str may be modified by this function. + * + * @since New in 1.6. + */ +APR_DECLARE(char *) apr_cstr_tokenize(const char *sep, char **str); + +/** + * Return the number of line breaks in @a msg, allowing any kind of newline + * termination (CR, LF, CRLF, or LFCR), even inconsistent. + * + * @since New in 1.6. + */ +APR_DECLARE(int) apr_cstr_count_newlines(const char *msg); + +#if 0 /* XXX: stringbuf logic is not present in APR */ +/** + * Return a cstring which is the concatenation of @a strings (an array + * of char *) each followed by @a separator (that is, @a separator + * will also end the resulting string). Allocate the result in @a pool. + * If @a strings is empty, then return the empty string. + * + * @since New in 1.6. + */ +APR_DECLARE(char *) apr_cstr_join(const apr_array_header_t *strings, + const char *separator, + apr_pool_t *pool); +#endif + +/** + * Perform a case-insensitive comparison of two strings @a atr1 and @a atr2, + * treating upper and lower case values of the 26 standard C/POSIX alphabetic + * characters as equivalent. Extended latin characters outside of this set + * are treated as unique octets, irrespective of the current locale. + * + * Returns in integer greater than, equal to, or less than 0, + * according to whether @a str1 is considered greater than, equal to, + * or less than @a str2. + * + * @since New in 1.6. + */ +APR_DECLARE(int) apr_cstr_casecmp(const char *str1, const char *str2); + +/** + * Perform a case-insensitive comparison of two strings @a atr1 and @a atr2, + * treating upper and lower case values of the 26 standard C/POSIX alphabetic + * characters as equivalent. Extended latin characters outside of this set + * are treated as unique octets, irrespective of the current locale. + * + * Returns in integer greater than, equal to, or less than 0, + * according to whether @a str1 is considered greater than, equal to, + * or less than @a str2. + * + * @since New in 1.6. + */ +APR_DECLARE(int) apr_cstr_casecmpn(const char *str1, + const char *str2, + apr_size_t n); + +/** + * Parse the C string @a str into a 64 bit number, and return it in @a *n. + * Assume that the number is represented in base @a base. + * Raise an error if conversion fails (e.g. due to overflow), or if the + * converted number is smaller than @a minval or larger than @a maxval. + * + * Leading whitespace in @a str is skipped in a locale-dependent way. + * After that, the string may contain an optional '+' (positive, default) + * or '-' (negative) character, followed by an optional '0x' prefix if + * @a base is 0 or 16, followed by numeric digits appropriate for the base. + * If there are any more characters after the numeric digits, an error is + * returned. + * + * If @a base is zero, then a leading '0x' or '0X' prefix means hexadecimal, + * else a leading '0' means octal (implemented, though not documented, in + * apr_strtoi64() in APR 0.9.0 through 1.5.0), else use base ten. + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_strtoi64(apr_int64_t *n, const char *str, + apr_int64_t minval, + apr_int64_t maxval, + int base); + +/** + * Parse the C string @a str into a 64 bit number, and return it in @a *n. + * Assume that the number is represented in base 10. + * Raise an error if conversion fails (e.g. due to overflow). + * + * The behaviour otherwise is as described for apr_cstr_strtoi64(). + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_atoi64(apr_int64_t *n, const char *str); + +/** + * Parse the C string @a str into a 32 bit number, and return it in @a *n. + * Assume that the number is represented in base 10. + * Raise an error if conversion fails (e.g. due to overflow). + * + * The behaviour otherwise is as described for apr_cstr_strtoi64(). + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_atoi(int *n, const char *str); + +/** + * Parse the C string @a str into an unsigned 64 bit number, and return + * it in @a *n. Assume that the number is represented in base @a base. + * Raise an error if conversion fails (e.g. due to overflow), or if the + * converted number is smaller than @a minval or larger than @a maxval. + * + * Leading whitespace in @a str is skipped in a locale-dependent way. + * After that, the string may contain an optional '+' (positive, default) + * or '-' (negative) character, followed by an optional '0x' prefix if + * @a base is 0 or 16, followed by numeric digits appropriate for the base. + * If there are any more characters after the numeric digits, an error is + * returned. + * + * If @a base is zero, then a leading '0x' or '0X' prefix means hexadecimal, + * else a leading '0' means octal (as implemented, though not documented, in + * apr_strtoi64(), else use base ten. + * + * @warning The implementation returns APR_ERANGE if the parsed number + * is greater than APR_INT64_MAX, even if it is not greater than @a maxval. + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_strtoui64(apr_uint64_t *n, const char *str, + apr_uint64_t minval, + apr_uint64_t maxval, + int base); + +/** + * Parse the C string @a str into an unsigned 64 bit number, and return + * it in @a *n. Assume that the number is represented in base 10. + * Raise an error if conversion fails (e.g. due to overflow). + * + * The behaviour otherwise is as described for apr_cstr_strtoui64(), + * including the upper limit of APR_INT64_MAX. + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_atoui64(apr_uint64_t *n, const char *str); + +/** + * Parse the C string @a str into an unsigned 32 bit number, and return + * it in @a *n. Assume that the number is represented in base 10. + * Raise an error if conversion fails (e.g. due to overflow). + * + * The behaviour otherwise is as described for apr_cstr_strtoui64(), + * including the upper limit of APR_INT64_MAX. + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_atoui(unsigned int *n, const char *str); + +/** + * Skip the common prefix @a prefix from the C string @a str, and return + * a pointer to the next character after the prefix. + * Return @c NULL if @a str does not start with @a prefix. + * + * @since New in 1.6. + */ +APR_DECLARE(const char *) apr_cstr_skip_prefix(const char *str, + const char *prefix); + +/** @} */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* SVN_STRING_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_date.h b/c/dependencies/windows/apr/x64/include/apr_date.h new file mode 100644 index 00000000..b098b542 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_date.h @@ -0,0 +1,106 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_DATE_H +#define APR_DATE_H + +/** + * @file apr_date.h + * @brief APR-UTIL date routines + */ + +/** + * @defgroup APR_Util_Date Date routines + * @ingroup APR_Util + * @{ + */ + +/* + * apr_date.h: prototypes for date parsing utility routines + */ + +#include "apu.h" +#include "apr_time.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** A bad date. */ +#define APR_DATE_BAD ((apr_time_t)0) + +/** + * Compare a string to a mask + * @param data The string to compare + * @param mask Mask characters (arbitrary maximum is 256 characters): + *
+ *   '\@' - uppercase letter
+ *   '\$' - lowercase letter
+ *   '\&' - hex digit
+ *   '#' - digit
+ *   '~' - digit or space
+ *   '*' - swallow remaining characters
+ * 
+ * @remark The mask tests for an exact match for any other character + * @return 1 if the string matches, 0 otherwise + */ +APU_DECLARE(int) apr_date_checkmask(const char *data, const char *mask); + +/** + * Parses an HTTP date in one of three standard forms: + *
+ *     Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
+ *     Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
+ *     Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format
+ * 
+ * @param date The date in one of the three formats above + * @return the apr_time_t number of microseconds since 1 Jan 1970 GMT, or + * 0 if this would be out of range or if the date is invalid. + */ +APU_DECLARE(apr_time_t) apr_date_parse_http(const char *date); + +/** + * Parses a string resembling an RFC 822 date. This is meant to be + * leinent in its parsing of dates. Hence, this will parse a wider + * range of dates than apr_date_parse_http. + * + * The prominent mailer (or poster, if mailer is unknown) that has + * been seen in the wild is included for the unknown formats. + *
+ *     Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
+ *     Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
+ *     Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format
+ *     Sun, 6 Nov 1994 08:49:37 GMT   ; RFC 822, updated by RFC 1123
+ *     Sun, 06 Nov 94 08:49:37 GMT    ; RFC 822
+ *     Sun, 6 Nov 94 08:49:37 GMT     ; RFC 822
+ *     Sun, 06 Nov 94 08:49 GMT       ; Unknown [drtr\@ast.cam.ac.uk] 
+ *     Sun, 6 Nov 94 08:49 GMT        ; Unknown [drtr\@ast.cam.ac.uk]
+ *     Sun, 06 Nov 94 8:49:37 GMT     ; Unknown [Elm 70.85]
+ *     Sun, 6 Nov 94 8:49:37 GMT      ; Unknown [Elm 70.85] 
+ * 
+ * + * @param date The date in one of the formats above + * @return the apr_time_t number of microseconds since 1 Jan 1970 GMT, or + * 0 if this would be out of range or if the date is invalid. + */ +APU_DECLARE(apr_time_t) apr_date_parse_rfc(const char *date); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_DATE_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_dbd.h b/c/dependencies/windows/apr/x64/include/apr_dbd.h new file mode 100644 index 00000000..9912612b --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_dbd.h @@ -0,0 +1,549 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* Overview of what this is and does: + * http://www.apache.org/~niq/dbd.html + */ + +#ifndef APR_DBD_H +#define APR_DBD_H + +#include "apu.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_dbd.h + * @brief APR-UTIL DBD library + */ +/** + * @defgroup APR_Util_DBD DBD routines + * @ingroup APR_Util + * @{ + */ + +/** + * Mapping of C to SQL types, used for prepared statements. + * @remarks + * For apr_dbd_p[v]query/select functions, in and out parameters are always + * const char * (i.e. regular nul terminated strings). LOB types are passed + * with four (4) arguments: payload, length, table and column, all as const + * char *, where table and column are reserved for future use by Oracle. + * @remarks + * For apr_dbd_p[v]bquery/select functions, in and out parameters are + * described next to each enumeration constant and are generally native binary + * types or some APR data type. LOB types are passed with four (4) arguments: + * payload (char*), length (apr_size_t*), table (char*) and column (char*). + * Table and column are reserved for future use by Oracle. + */ +typedef enum { + APR_DBD_TYPE_NONE, + APR_DBD_TYPE_TINY, /**< \%hhd : in, out: char* */ + APR_DBD_TYPE_UTINY, /**< \%hhu : in, out: unsigned char* */ + APR_DBD_TYPE_SHORT, /**< \%hd : in, out: short* */ + APR_DBD_TYPE_USHORT, /**< \%hu : in, out: unsigned short* */ + APR_DBD_TYPE_INT, /**< \%d : in, out: int* */ + APR_DBD_TYPE_UINT, /**< \%u : in, out: unsigned int* */ + APR_DBD_TYPE_LONG, /**< \%ld : in, out: long* */ + APR_DBD_TYPE_ULONG, /**< \%lu : in, out: unsigned long* */ + APR_DBD_TYPE_LONGLONG, /**< \%lld : in, out: apr_int64_t* */ + APR_DBD_TYPE_ULONGLONG, /**< \%llu : in, out: apr_uint64_t* */ + APR_DBD_TYPE_FLOAT, /**< \%f : in, out: float* */ + APR_DBD_TYPE_DOUBLE, /**< \%lf : in, out: double* */ + APR_DBD_TYPE_STRING, /**< \%s : in: char*, out: char** */ + APR_DBD_TYPE_TEXT, /**< \%pDt : in: char*, out: char** */ + APR_DBD_TYPE_TIME, /**< \%pDi : in: char*, out: char** */ + APR_DBD_TYPE_DATE, /**< \%pDd : in: char*, out: char** */ + APR_DBD_TYPE_DATETIME, /**< \%pDa : in: char*, out: char** */ + APR_DBD_TYPE_TIMESTAMP, /**< \%pDs : in: char*, out: char** */ + APR_DBD_TYPE_ZTIMESTAMP, /**< \%pDz : in: char*, out: char** */ + APR_DBD_TYPE_BLOB, /**< \%pDb : in: char* apr_size_t* char* char*, out: apr_bucket_brigade* */ + APR_DBD_TYPE_CLOB, /**< \%pDc : in: char* apr_size_t* char* char*, out: apr_bucket_brigade* */ + APR_DBD_TYPE_NULL /**< \%pDn : in: void*, out: void** */ +} apr_dbd_type_e; + +/* These are opaque structs. Instantiation is up to each backend */ +typedef struct apr_dbd_driver_t apr_dbd_driver_t; +typedef struct apr_dbd_t apr_dbd_t; +typedef struct apr_dbd_transaction_t apr_dbd_transaction_t; +typedef struct apr_dbd_results_t apr_dbd_results_t; +typedef struct apr_dbd_row_t apr_dbd_row_t; +typedef struct apr_dbd_prepared_t apr_dbd_prepared_t; + +/** apr_dbd_init: perform once-only initialisation. Call once only. + * + * @param pool - pool to register any shutdown cleanups, etc + */ +APU_DECLARE(apr_status_t) apr_dbd_init(apr_pool_t *pool); + +/** apr_dbd_get_driver: get the driver struct for a name + * + * @param pool - (process) pool to register cleanup + * @param name - driver name + * @param driver - pointer to driver struct. + * @return APR_SUCCESS for success + * @return APR_ENOTIMPL for no driver (when DSO not enabled) + * @return APR_EDSOOPEN if DSO driver file can't be opened + * @return APR_ESYMNOTFOUND if the driver file doesn't contain a driver + */ +APU_DECLARE(apr_status_t) apr_dbd_get_driver(apr_pool_t *pool, const char *name, + const apr_dbd_driver_t **driver); + +/** apr_dbd_open_ex: open a connection to a backend + * + * @param driver - driver struct. + * @param pool - working pool + * @param params - arguments to driver (implementation-dependent) + * @param handle - pointer to handle to return + * @param error - descriptive error. + * @return APR_SUCCESS for success + * @return APR_EGENERAL if driver exists but connection failed + * @remarks PostgreSQL: the params is passed directly to the PQconnectdb() + * function (check PostgreSQL documentation for more details on the syntax). + * @remarks SQLite2: the params is split on a colon, with the first part used + * as the filename and second part converted to an integer and used as file + * mode. + * @remarks SQLite3: the params is passed directly to the sqlite3_open() + * function as a filename to be opened (check SQLite3 documentation for more + * details). + * @remarks Oracle: the params can have "user", "pass", "dbname" and "server" + * keys, each followed by an equal sign and a value. Such key/value pairs can + * be delimited by space, CR, LF, tab, semicolon, vertical bar or comma. + * @remarks MySQL: the params can have "host", "port", "user", "pass", + * "dbname", "sock", "flags" "fldsz", "group" and "reconnect" keys, each + * followed by an equal sign and a value. Such key/value pairs can be + * delimited by space, CR, LF, tab, semicolon, vertical bar or comma. For + * now, "flags" can only recognise CLIENT_FOUND_ROWS (check MySQL manual for + * details). The value associated with "fldsz" determines maximum amount of + * memory (in bytes) for each of the fields in the result set of prepared + * statements. By default, this value is 1 MB. The value associated with + * "group" determines which group from configuration file to use (see + * MYSQL_READ_DEFAULT_GROUP option of mysql_options() in MySQL manual). + * Reconnect is set to 1 by default (i.e. true). + */ +APU_DECLARE(apr_status_t) apr_dbd_open_ex(const apr_dbd_driver_t *driver, + apr_pool_t *pool, const char *params, + apr_dbd_t **handle, + const char **error); + +/** apr_dbd_open: open a connection to a backend + * + * @param driver - driver struct. + * @param pool - working pool + * @param params - arguments to driver (implementation-dependent) + * @param handle - pointer to handle to return + * @return APR_SUCCESS for success + * @return APR_EGENERAL if driver exists but connection failed + * @see apr_dbd_open_ex + */ +APU_DECLARE(apr_status_t) apr_dbd_open(const apr_dbd_driver_t *driver, + apr_pool_t *pool, const char *params, + apr_dbd_t **handle); + +/** apr_dbd_close: close a connection to a backend + * + * @param driver - driver struct. + * @param handle - handle to close + * @return APR_SUCCESS for success or error status + */ +APU_DECLARE(apr_status_t) apr_dbd_close(const apr_dbd_driver_t *driver, + apr_dbd_t *handle); + +/* apr-function-shaped versions of things */ + +/** apr_dbd_name: get the name of the driver + * + * @param driver - the driver + * @return - name + */ +APU_DECLARE(const char*) apr_dbd_name(const apr_dbd_driver_t *driver); + +/** apr_dbd_native_handle: get native database handle of the underlying db + * + * @param driver - the driver + * @param handle - apr_dbd handle + * @return - native handle + */ +APU_DECLARE(void*) apr_dbd_native_handle(const apr_dbd_driver_t *driver, + apr_dbd_t *handle); + +/** check_conn: check status of a database connection + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection to check + * @return APR_SUCCESS or error + */ +APU_DECLARE(int) apr_dbd_check_conn(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle); + +/** apr_dbd_set_dbname: select database name. May be a no-op if not supported. + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param name - the database to select + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_set_dbname(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, const char *name); + +/** apr_dbd_transaction_start: start a transaction. May be a no-op. + * + * @param driver - the driver + * @param pool - a pool to use for error messages (if any). + * @param handle - the db connection + * @param trans - ptr to a transaction. May be null on entry + * @return 0 for success or error code + * @remarks Note that transaction modes, set by calling + * apr_dbd_transaction_mode_set(), will affect all query/select calls within + * a transaction. By default, any error in query/select during a transaction + * will cause the transaction to inherit the error code and any further + * query/select calls will fail immediately. Put transaction in "ignore + * errors" mode to avoid that. Use "rollback" mode to do explicit rollback. + */ +APU_DECLARE(int) apr_dbd_transaction_start(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_t *handle, + apr_dbd_transaction_t **trans); + +/** apr_dbd_transaction_end: end a transaction + * (commit on success, rollback on error). + * May be a no-op. + * + * @param driver - the driver + * @param handle - the db connection + * @param trans - the transaction. + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_transaction_end(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_transaction_t *trans); + +#define APR_DBD_TRANSACTION_COMMIT 0x00 /**< commit the transaction */ +#define APR_DBD_TRANSACTION_ROLLBACK 0x01 /**< rollback the transaction */ +#define APR_DBD_TRANSACTION_IGNORE_ERRORS 0x02 /**< ignore transaction errors */ + +/** apr_dbd_transaction_mode_get: get the mode of transaction + * + * @param driver - the driver + * @param trans - the transaction + * @return mode of transaction + */ +APU_DECLARE(int) apr_dbd_transaction_mode_get(const apr_dbd_driver_t *driver, + apr_dbd_transaction_t *trans); + +/** apr_dbd_transaction_mode_set: set the mode of transaction + * + * @param driver - the driver + * @param trans - the transaction + * @param mode - new mode of the transaction + * @return the mode of transaction in force after the call + */ +APU_DECLARE(int) apr_dbd_transaction_mode_set(const apr_dbd_driver_t *driver, + apr_dbd_transaction_t *trans, + int mode); + +/** apr_dbd_query: execute an SQL query that doesn't return a result set + * + * @param driver - the driver + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the SQL statement to execute + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_query(const apr_dbd_driver_t *driver, apr_dbd_t *handle, + int *nrows, const char *statement); + +/** apr_dbd_select: execute an SQL query that returns a result set + * + * @param driver - the driver + * @param pool - pool to allocate the result set + * @param handle - the connection + * @param res - pointer to result set pointer. May point to NULL on entry + * @param statement - the SQL statement to execute + * @param random - 1 to support random access to results (seek any row); + * 0 to support only looping through results in order + * (async access - faster) + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_select(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, apr_dbd_results_t **res, + const char *statement, int random); + +/** apr_dbd_num_cols: get the number of columns in a results set + * + * @param driver - the driver + * @param res - result set. + * @return number of columns + */ +APU_DECLARE(int) apr_dbd_num_cols(const apr_dbd_driver_t *driver, + apr_dbd_results_t *res); + +/** apr_dbd_num_tuples: get the number of rows in a results set + * of a synchronous select + * + * @param driver - the driver + * @param res - result set. + * @return number of rows, or -1 if the results are asynchronous + */ +APU_DECLARE(int) apr_dbd_num_tuples(const apr_dbd_driver_t *driver, + apr_dbd_results_t *res); + +/** apr_dbd_get_row: get a row from a result set + * + * @param driver - the driver + * @param pool - pool to allocate the row + * @param res - result set pointer + * @param row - pointer to row pointer. May point to NULL on entry + * @param rownum - row number (counting from 1), or -1 for "next row". + * Ignored if random access is not supported. + * @return 0 for success, -1 for rownum out of range or data finished + */ +APU_DECLARE(int) apr_dbd_get_row(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_results_t *res, apr_dbd_row_t **row, + int rownum); + +/** apr_dbd_get_entry: get an entry from a row + * + * @param driver - the driver + * @param row - row pointer + * @param col - entry number + * @return value from the row, or NULL if col is out of bounds. + */ +APU_DECLARE(const char*) apr_dbd_get_entry(const apr_dbd_driver_t *driver, + apr_dbd_row_t *row, int col); + +/** apr_dbd_get_name: get an entry name from a result set + * + * @param driver - the driver + * @param res - result set pointer + * @param col - entry number + * @return name of the entry, or NULL if col is out of bounds. + */ +APU_DECLARE(const char*) apr_dbd_get_name(const apr_dbd_driver_t *driver, + apr_dbd_results_t *res, int col); + + +/** apr_dbd_error: get current error message (if any) + * + * @param driver - the driver + * @param handle - the connection + * @param errnum - error code from operation that returned an error + * @return the database current error message, or message for errnum + * (implementation-dependent whether errnum is ignored) + */ +APU_DECLARE(const char*) apr_dbd_error(const apr_dbd_driver_t *driver, + apr_dbd_t *handle, int errnum); + +/** apr_dbd_escape: escape a string so it is safe for use in query/select + * + * @param driver - the driver + * @param pool - pool to alloc the result from + * @param string - the string to escape + * @param handle - the connection + * @return the escaped, safe string + */ +APU_DECLARE(const char*) apr_dbd_escape(const apr_dbd_driver_t *driver, + apr_pool_t *pool, const char *string, + apr_dbd_t *handle); + +/** apr_dbd_prepare: prepare a statement + * + * @param driver - the driver + * @param pool - pool to alloc the result from + * @param handle - the connection + * @param query - the SQL query + * @param label - A label for the prepared statement. + * use NULL for temporary prepared statements + * (eg within a Request in httpd) + * @param statement - statement to prepare. May point to null on entry. + * @return 0 for success or error code + * @remarks To specify parameters of the prepared query, use \%s, \%d etc. + * (see below for full list) in place of database specific parameter syntax + * (e.g. for PostgreSQL, this would be $1, $2, for SQLite3 this would be ? + * etc.). For instance: "SELECT name FROM customers WHERE name=%s" would be + * a query that this function understands. + * @remarks Here is the full list of format specifiers that this function + * understands and what they map to in SQL: \%hhd (TINY INT), \%hhu (UNSIGNED + * TINY INT), \%hd (SHORT), \%hu (UNSIGNED SHORT), \%d (INT), \%u (UNSIGNED + * INT), \%ld (LONG), \%lu (UNSIGNED LONG), \%lld (LONG LONG), \%llu + * (UNSIGNED LONG LONG), \%f (FLOAT, REAL), \%lf (DOUBLE PRECISION), \%s + * (VARCHAR), \%pDt (TEXT), \%pDi (TIME), \%pDd (DATE), \%pDa (DATETIME), + * \%pDs (TIMESTAMP), \%pDz (TIMESTAMP WITH TIME ZONE), \%pDb (BLOB), \%pDc + * (CLOB) and \%pDn (NULL). Not all databases have support for all these + * types, so the underlying driver will attempt the "best match" where + * possible. A \% followed by any letter not in the above list will be + * interpreted as VARCHAR (i.e. \%s). + */ +APU_DECLARE(int) apr_dbd_prepare(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, const char *query, + const char *label, + apr_dbd_prepared_t **statement); + + +/** apr_dbd_pquery: query using a prepared statement + args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param nargs - ignored (for backward compatibility only) + * @param args - args to prepared statement + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_pquery(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, int nargs, + const char **args); + +/** apr_dbd_pselect: select using a prepared statement + args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param nargs - ignored (for backward compatibility only) + * @param args - args to prepared statement + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_pselect(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, int random, + int nargs, const char **args); + +/** apr_dbd_pvquery: query using a prepared statement + args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param ... - varargs list + * @return 0 for success or error code + */ +APU_DECLARE_NONSTD(int) apr_dbd_pvquery(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, ...); + +/** apr_dbd_pvselect: select using a prepared statement + args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param ... - varargs list + * @return 0 for success or error code + */ +APU_DECLARE_NONSTD(int) apr_dbd_pvselect(const apr_dbd_driver_t *driver, + apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, + int random, ...); + +/** apr_dbd_pbquery: query using a prepared statement + binary args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_pbquery(const apr_dbd_driver_t *driver, + apr_pool_t *pool, apr_dbd_t *handle, + int *nrows, apr_dbd_prepared_t *statement, + const void **args); + +/** apr_dbd_pbselect: select using a prepared statement + binary args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_pbselect(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_t *handle, apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, int random, + const void **args); + +/** apr_dbd_pvbquery: query using a prepared statement + binary args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param ... - varargs list of binary args + * @return 0 for success or error code + */ +APU_DECLARE_NONSTD(int) apr_dbd_pvbquery(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, ...); + +/** apr_dbd_pvbselect: select using a prepared statement + binary args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param ... - varargs list of binary args + * @return 0 for success or error code + */ +APU_DECLARE_NONSTD(int) apr_dbd_pvbselect(const apr_dbd_driver_t *driver, + apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, + int random, ...); + +/** apr_dbd_datum_get: get a binary entry from a row + * + * @param driver - the driver + * @param row - row pointer + * @param col - entry number + * @param type - type of data to get + * @param data - pointer to data, allocated by the caller + * @return APR_SUCCESS on success, APR_ENOENT if data is NULL or APR_EGENERAL + */ +APU_DECLARE(apr_status_t) apr_dbd_datum_get(const apr_dbd_driver_t *driver, + apr_dbd_row_t *row, int col, + apr_dbd_type_e type, void *data); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/c/dependencies/windows/apr/x64/include/apr_dbm.h b/c/dependencies/windows/apr/x64/include/apr_dbm.h new file mode 100644 index 00000000..ad1b4f39 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_dbm.h @@ -0,0 +1,227 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_DBM_H +#define APR_DBM_H + +#include "apu.h" +#include "apr.h" +#include "apr_errno.h" +#include "apr_pools.h" +#include "apr_file_info.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_dbm.h + * @brief APR-UTIL DBM library + */ +/** + * @defgroup APR_Util_DBM DBM routines + * @ingroup APR_Util + * @{ + */ +/** + * Structure for referencing a dbm + */ +typedef struct apr_dbm_t apr_dbm_t; + +/** + * Structure for referencing the datum record within a dbm + */ +typedef struct +{ + /** pointer to the 'data' to retrieve/store in the DBM */ + char *dptr; + /** size of the 'data' to retrieve/store in the DBM */ + apr_size_t dsize; +} apr_datum_t; + +/* modes to open the DB */ +#define APR_DBM_READONLY 1 /**< open for read-only access */ +#define APR_DBM_READWRITE 2 /**< open for read-write access */ +#define APR_DBM_RWCREATE 3 /**< open for r/w, create if needed */ +#define APR_DBM_RWTRUNC 4 /**< open for r/w, truncating an existing + DB if present */ +/** + * Open a dbm file by file name and type of DBM + * @param dbm The newly opened database + * @param type The type of the DBM (not all may be available at run time) + *
+ *  db   for Berkeley DB files
+ *  gdbm for GDBM files
+ *  ndbm for NDBM files
+ *  sdbm for SDBM files (always available)
+ *  default for the default DBM type
+ *  
+ * @param name The dbm file name to open + * @param mode The flag value + *
+ *           APR_DBM_READONLY   open for read-only access
+ *           APR_DBM_READWRITE  open for read-write access
+ *           APR_DBM_RWCREATE   open for r/w, create if needed
+ *           APR_DBM_RWTRUNC    open for r/w, truncate if already there
+ * 
+ * @param perm Permissions to apply to if created + * @param cntxt The pool to use when creating the dbm + * @remark The dbm name may not be a true file name, as many dbm packages + * append suffixes for seperate data and index files. + * @bug In apr-util 0.9 and 1.x, the type arg was case insensitive. This + * was highly inefficient, and as of 2.x the dbm name must be provided in + * the correct case (lower case for all bundled providers) + */ + +APU_DECLARE(apr_status_t) apr_dbm_open_ex(apr_dbm_t **dbm, const char* type, + const char *name, + apr_int32_t mode, apr_fileperms_t perm, + apr_pool_t *cntxt); + + +/** + * Open a dbm file by file name + * @param dbm The newly opened database + * @param name The dbm file name to open + * @param mode The flag value + *
+ *           APR_DBM_READONLY   open for read-only access
+ *           APR_DBM_READWRITE  open for read-write access
+ *           APR_DBM_RWCREATE   open for r/w, create if needed
+ *           APR_DBM_RWTRUNC    open for r/w, truncate if already there
+ * 
+ * @param perm Permissions to apply to if created + * @param cntxt The pool to use when creating the dbm + * @remark The dbm name may not be a true file name, as many dbm packages + * append suffixes for seperate data and index files. + */ +APU_DECLARE(apr_status_t) apr_dbm_open(apr_dbm_t **dbm, const char *name, + apr_int32_t mode, apr_fileperms_t perm, + apr_pool_t *cntxt); + +/** + * Close a dbm file previously opened by apr_dbm_open + * @param dbm The database to close + */ +APU_DECLARE(void) apr_dbm_close(apr_dbm_t *dbm); + +/** + * Fetch a dbm record value by key + * @param dbm The database + * @param key The key datum to find this record + * @param pvalue The value datum retrieved for this record + */ +APU_DECLARE(apr_status_t) apr_dbm_fetch(apr_dbm_t *dbm, apr_datum_t key, + apr_datum_t *pvalue); +/** + * Store a dbm record value by key + * @param dbm The database + * @param key The key datum to store this record by + * @param value The value datum to store in this record + */ +APU_DECLARE(apr_status_t) apr_dbm_store(apr_dbm_t *dbm, apr_datum_t key, + apr_datum_t value); + +/** + * Delete a dbm record value by key + * @param dbm The database + * @param key The key datum of the record to delete + * @remark It is not an error to delete a non-existent record. + */ +APU_DECLARE(apr_status_t) apr_dbm_delete(apr_dbm_t *dbm, apr_datum_t key); + +/** + * Search for a key within the dbm + * @param dbm The database + * @param key The datum describing a key to test + */ +APU_DECLARE(int) apr_dbm_exists(apr_dbm_t *dbm, apr_datum_t key); + +/** + * Retrieve the first record key from a dbm + * @param dbm The database + * @param pkey The key datum of the first record + */ +APU_DECLARE(apr_status_t) apr_dbm_firstkey(apr_dbm_t *dbm, apr_datum_t *pkey); + +/** + * Retrieve the next record key from a dbm + * @param dbm The database + * @param pkey The key datum of the next record + */ +APU_DECLARE(apr_status_t) apr_dbm_nextkey(apr_dbm_t *dbm, apr_datum_t *pkey); + +/** + * Proactively toss any memory associated with the apr_datum_t. + * @param dbm The database + * @param data The datum to free. + */ +APU_DECLARE(void) apr_dbm_freedatum(apr_dbm_t *dbm, apr_datum_t data); + +/** + * Report more information when an apr_dbm function fails. + * @param dbm The database + * @param errcode A DBM-specific value for the error (for logging). If this + * isn't needed, it may be NULL. + * @param errbuf Location to store the error text + * @param errbufsize The size of the provided buffer + * @return The errbuf parameter, for convenience. + */ +APU_DECLARE(char *) apr_dbm_geterror(apr_dbm_t *dbm, int *errcode, + char *errbuf, apr_size_t errbufsize); +/** + * If the specified file/path were passed to apr_dbm_open(), return the + * actual file/path names which would be (created and) used. At most, two + * files may be used; used2 may be NULL if only one file is used. + * @param pool The pool for allocating used1 and used2. + * @param type The type of DBM you require info on @see apr_dbm_open_ex + * @param pathname The path name to generate used-names from. + * @param used1 The first pathname used by the apr_dbm implementation. + * @param used2 The second pathname used by apr_dbm. If only one file is + * used by the specific implementation, this will be set to NULL. + * @return An error if the specified type is invalid. + * @remark The dbm file(s) don't need to exist. This function only manipulates + * the pathnames. + */ +APU_DECLARE(apr_status_t) apr_dbm_get_usednames_ex(apr_pool_t *pool, + const char *type, + const char *pathname, + const char **used1, + const char **used2); + +/** + * If the specified file/path were passed to apr_dbm_open(), return the + * actual file/path names which would be (created and) used. At most, two + * files may be used; used2 may be NULL if only one file is used. + * @param pool The pool for allocating used1 and used2. + * @param pathname The path name to generate used-names from. + * @param used1 The first pathname used by the apr_dbm implementation. + * @param used2 The second pathname used by apr_dbm. If only one file is + * used by the specific implementation, this will be set to NULL. + * @remark The dbm file(s) don't need to exist. This function only manipulates + * the pathnames. + */ +APU_DECLARE(void) apr_dbm_get_usednames(apr_pool_t *pool, + const char *pathname, + const char **used1, + const char **used2); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_DBM_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_dso.h b/c/dependencies/windows/apr/x64/include/apr_dso.h new file mode 100644 index 00000000..ac701cfd --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_dso.h @@ -0,0 +1,94 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_DSO_DOT_H +#define APR_DSO_DOT_H + +/** + * @file apr_dso.h + * @brief APR Dynamic Object Handling Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_dso Dynamic Object Handling + * @ingroup APR + * @{ + */ + +#if APR_HAS_DSO || defined(DOXYGEN) + +/** + * Structure for referencing dynamic objects + */ +typedef struct apr_dso_handle_t apr_dso_handle_t; + +/** + * Structure for referencing symbols from dynamic objects + */ +typedef void * apr_dso_handle_sym_t; + +/** + * Load a DSO library. + * @param res_handle Location to store new handle for the DSO. + * @param path Path to the DSO library + * @param ctx Pool to use. + * @bug We aught to provide an alternative to RTLD_GLOBAL, which + * is the only supported method of loading DSOs today. + */ +APR_DECLARE(apr_status_t) apr_dso_load(apr_dso_handle_t **res_handle, + const char *path, apr_pool_t *ctx); + +/** + * Close a DSO library. + * @param handle handle to close. + */ +APR_DECLARE(apr_status_t) apr_dso_unload(apr_dso_handle_t *handle); + +/** + * Load a symbol from a DSO handle. + * @param ressym Location to store the loaded symbol + * @param handle handle to load the symbol from. + * @param symname Name of the symbol to load. + */ +APR_DECLARE(apr_status_t) apr_dso_sym(apr_dso_handle_sym_t *ressym, + apr_dso_handle_t *handle, + const char *symname); + +/** + * Report more information when a DSO function fails. + * @param dso The dso handle that has been opened + * @param buf Location to store the dso error + * @param bufsize The size of the provided buffer + */ +APR_DECLARE(const char *) apr_dso_error(apr_dso_handle_t *dso, char *buf, apr_size_t bufsize); + +#endif /* APR_HAS_DSO */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/c/dependencies/windows/apr/x64/include/apr_encode.h b/c/dependencies/windows/apr/x64/include/apr_encode.h new file mode 100644 index 00000000..20fc932f --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_encode.h @@ -0,0 +1,569 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_encode.h + * @brief APR-UTIL Encoding + */ +#ifndef APR_ENCODE_H +#define APR_ENCODE_H + +#include "apr.h" +#include "apr_general.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Encode Base64/Base64Url/Base32/Base32Hex/Base16 Encoding + * @ingroup APR_Util + * @{ + */ + +/** + * RFC4648 and RFC7515 compliant BASE64, BASE64URL, BASE32, BASE32HEX + * and BASE16 encode/decode functions. + * + * The following encodings are supported: + * + * - Base 64 Encoding + * + * o Use flag APR_ENCODE_NONE + * o https://tools.ietf.org/html/rfc4648#section-4 + * + * - Base 64 Encoding with URL and Filename Safe Alphabet + * + * o Use flag APR_ENCODE_URL + * o https://tools.ietf.org/html/rfc4648#section-5 + * + * - Base 64 URL Encoding without Padding + * + * o Use flag APR_ENCODE_BASE64URL + * o https://tools.ietf.org/html/rfc7515#appendix-C + * + * - Base 32 Encoding + * + * o Use flag APR_ENCODE_NONE + * o https://tools.ietf.org/html/rfc4648#section-6 + * + * - Base 32 Encoding with Extended Hex Alphabet + * + * o Use flag APR_ENCODE_BASE32HEX + * o https://tools.ietf.org/html/rfc4648#section-7 + * + * - Base 16 Encoding + * + * o Use flags APR_ENCODE_NONE/APR_ENCODE_COLON + * o https://tools.ietf.org/html/rfc4648#section-8 + * + * If a non valid character of any kind including whitespace is passed to any + * of the decoder functions, APR_BADCH will be returned. In this case decoding + * will still take place, but the results can not be trusted. + * + * If APR_ENCODE_RELAXED is passed to the decoder functions, decoding will be + * attempted up until the first non valid character. If this results in an + * invalid state in the decoder, such as but not limited to an odd number of + * base16 characters, APR_BADCH will still be returned. + * + * If APR_ENCODE_RELAXED is not passed to a decoder function, the decoding will + * be done in constant time regardless of whether the result returns APR_SUCCESS + * or APR_BADCH. + * + * If the dest parameter is NULL, the maximum theoretical buffer size is + * returned in the len field, including space for a terminating zero character + * if the destination is a string. This value can be used to allocate buffers + * of a suitable safe size. + * + * If the dest parameter is provided, the encoding or decoding will take place, + * and the actual number of characters written is returned in the len field, + * ignoring any terminating zero. + * + * Plain strings are not assumed '\0' terminated unless APR_ENCODE_STRING is + * provided. + * + */ + +/** + * When passing a string to one of the encode functions, this value can be + * passed to indicate a string-valued key, and have the length computed + * automatically. + */ +#define APR_ENCODE_STRING (-1) + +/** + * Generate RFC4648 base16/base32/base64. + */ +#define APR_ENCODE_NONE 0 + +/** + * If relaxed, decode up until the first non base16/base32/base64 character. + */ +#define APR_ENCODE_RELAXED 1 + +/** + * Omit the padding character (=) while encoding. + */ +#define APR_ENCODE_NOPADDING 2 + +/** + * Generate RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet + */ +#define APR_ENCODE_URL 4 + +/** + * Generate RFC7515 BASE64URL + */ +#define APR_ENCODE_BASE64URL (APR_ENCODE_NOPADDING | APR_ENCODE_URL) + +/** + * Generate base32hex encoding instead of base32 encoding + */ +#define APR_ENCODE_BASE32HEX 8 + +/** + * Generate base16 with colons between each token. + */ +#define APR_ENCODE_COLON 16 + +/** + * Generate base16 with lower case characters. + */ +#define APR_ENCODE_LOWER 32 + +/** + * Convert text data to base64. + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 64 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_URL, + * use RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet. + * If APR_ENCODE_BASE64URL, use RFC7515 base64url Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination string, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base64(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert binary data to base64. + * @param dest The destination string, can be NULL. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 64 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_URL, + * use RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet. + * If APR_ENCODE_BASE64URL, use RFC7515 base64url Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination string, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base64_binary(char *dest, const unsigned char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert text data to base64, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 64 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_URL, + * use RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet. + * If APR_ENCODE_BASE64URL, use RFC7515 base64url Encoding. + * @param len If present, returns the number of characters written excluding + * the zero pad. + * @return A zero padded string allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *)apr_pencode_base64(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len)__attribute__((nonnull(1))); + +/** + * Convert binary data to base64, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 64 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_URL, + * use RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet. + * If APR_ENCODE_BASE64URL, use RFC7515 base64url Encoding. + * @param len If present, returns the number of characters written excluding + * the zero pad. + * @return A zero padded string allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *)apr_pencode_base64_binary(apr_pool_t * p, const unsigned char *src, + apr_ssize_t slen, int flags, apr_size_t * len)__attribute__((nonnull(1))); + +/** + * Convert base64 or base64url with or without padding to text data. + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, attempt to decode the full original buffer, + * and return NULL if any bad character is detected. If APR_ENCODE_RELAXED, + * decode until the first non base64/base64url character. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination string, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL, or APR_BADCH + * if a non hex character is present. + */ +APR_DECLARE(apr_status_t) apr_decode_base64(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base64 or base64url with or without padding to binary data. + * @param dest The destination buffer, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, attempt to decode the full original buffer, + * and return NULL if any bad character is detected. If APR_ENCODE_RELAXED, + * decode until the first non base64/base64url character. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the src was NULL, or APR_BADCH + * if a non base64 character is present. + */ +APR_DECLARE(apr_status_t) apr_decode_base64_binary(unsigned char *dest, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base64 or base64url with or without padding to text data, and + * return the results from a pool. + * @param p Pool to allocate from. + * @param src The base64 string to decode. + * @param slen The length of the base64 string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, attempt to decode the full original buffer, + * and return NULL if any bad character is detected. If APR_ENCODE_RELAXED, + * decode until the first non base64/base64url character. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A string allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const char *)apr_pdecode_base64(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert base64 or base64url with or without padding to binary data, and + * return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, attempt to decode the full original buffer, + * and return NULL if any bad character is detected. If APR_ENCODE_RELAXED, + * decode until the first non base64/base64url character. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A buffer allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const unsigned char *)apr_pdecode_base64_binary(apr_pool_t * p, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert text data to base32. + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 32 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_BASE32HEX, + * use RFC4648 base32hex Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination string, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base32(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert binary data to base32. + * @param dest The destination string, can be NULL. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 32 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_BASE32HEX, + * use RFC4648 base32hex Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination string, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base32_binary(char *dest, const unsigned char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert text data to base32, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 32 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_BASE32HEX, + * use RFC4648 base32hex Encoding. + * @param len If present, returns the number of characters written excluding + * the zero pad. + * @return A zero padded string allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *)apr_pencode_base32(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert binary data to base32, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 32 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_BASE32HEX, + * use RFC7515 base32hex Encoding. + * @param len If present, returns the number of characters written excluding + * the zero pad. + * @return A zero padded string allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *)apr_pencode_base32_binary(apr_pool_t * p, const unsigned char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert base32 or base32hex with or without padding to text data. + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 32 Encoding. If + * APR_ENCODE_BASE32HEX, use RFC4648 base32hex Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL, or APR_BADCH + * if a non base32 character is present. + */ +APR_DECLARE(apr_status_t) apr_decode_base32(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base32 or base32hex with or without padding to binary data. + * @param dest The destination buffer, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 32 Encoding. If + * APR_ENCODE_BASE32HEX, use RFC4648 base32hex Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the src was NULL, or APR_BADCH + * if a non base32 character is present. + */ +APR_DECLARE(apr_status_t) apr_decode_base32_binary(unsigned char *dest, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base32 or base32hex with or without padding to text data, and + * return the results from a pool. + * @param p Pool to allocate from. + * @param src The base32 string to decode. + * @param slen The length of the base32 string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 32 Encoding. If + * APR_ENCODE_BASE32HEX, use RFC4648 base32hex Encoding. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A string allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const char *)apr_pdecode_base32(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert base32 or base32hex with or without padding to binary data, and + * return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 32 Encoding. If + * APR_ENCODE_BASE32HEX, use RFC4648 base32hex Encoding. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A buffer allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const unsigned char *)apr_pdecode_base32_binary(apr_pool_t * p, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert text data to base16 (hex). + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, separate each token with a colon. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base16(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert binary data to base16 (hex). + * @param dest The destination string, can be NULL. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, separate each token with a colon. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base16_binary(char *dest, + const unsigned char *src, apr_ssize_t slen, int flags, + apr_size_t * len); + +/** + * Convert text data to base16 (hex), and return the results from a + * pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, separate each token with a colon. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A string allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const char *)apr_pencode_base16(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert binary data to base16 (hex), and return the results from a + * pool. + * @param p Pool to allocate from. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, separate each token with a colon. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A string allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const char *)apr_pencode_base16_binary(apr_pool_t * p, + const unsigned char *src, apr_ssize_t slen, + int flags, apr_size_t * len)__attribute__((nonnull(1))); + +/** + * Convert base16 (hex) to text data. + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, allow tokens to be separated with a colon. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL, or APR_BADCH + * if a non hex character is present. A zero pad is appended to the buffer. + */ +APR_DECLARE(apr_status_t) apr_decode_base16(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base16 (hex) to binary data. + * @param dest The destination buffer, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, allow tokens to be separated with a colon. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL, or APR_BADCH + * if a non hex character is present. No zero pad is written to the buffer. + */ +APR_DECLARE(apr_status_t) apr_decode_base16_binary(unsigned char *dest, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base16 (hex) and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, allow tokens to be separated with a colon. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A buffer allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const char *)apr_pdecode_base16(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert base16 (hex) to binary data, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, allow tokens to be separated with a colon. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A buffer allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const unsigned char *)apr_pdecode_base16_binary(apr_pool_t * p, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ENCODE_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_env.h b/c/dependencies/windows/apr/x64/include/apr_env.h new file mode 100644 index 00000000..85ab6704 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_env.h @@ -0,0 +1,67 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ENV_H +#define APR_ENV_H +/** + * @file apr_env.h + * @brief APR Environment functions + */ +#include "apr_errno.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_env Functions for manipulating the environment + * @ingroup APR + * @{ + */ + +/** + * Get the value of an environment variable + * @param value the returned value, allocated from @a pool + * @param envvar the name of the environment variable + * @param pool where to allocate @a value and any temporary storage from + */ +APR_DECLARE(apr_status_t) apr_env_get(char **value, const char *envvar, + apr_pool_t *pool); + +/** + * Set the value of an environment variable + * @param envvar the name of the environment variable + * @param value the value to set + * @param pool where to allocate temporary storage from + */ +APR_DECLARE(apr_status_t) apr_env_set(const char *envvar, const char *value, + apr_pool_t *pool); + +/** + * Delete a variable from the environment + * @param envvar the name of the environment variable + * @param pool where to allocate temporary storage from + */ +APR_DECLARE(apr_status_t) apr_env_delete(const char *envvar, apr_pool_t *pool); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_ENV_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_errno.h b/c/dependencies/windows/apr/x64/include/apr_errno.h new file mode 100644 index 00000000..8fa6628b --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_errno.h @@ -0,0 +1,1342 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ERRNO_H +#define APR_ERRNO_H + +/** + * @file apr_errno.h + * @brief APR Error Codes + */ + +#include "apr.h" + +#if APR_HAVE_ERRNO_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_errno Error Codes + * @ingroup APR + * @{ + */ + +/** + * Type for specifying an error or status code. + */ +typedef int apr_status_t; + +/** + * Return a human readable string describing the specified error. + * @param statcode The error code to get a string for. + * @param buf A buffer to hold the error string. + * @param bufsize Size of the buffer to hold the string. + */ +APR_DECLARE(char *) apr_strerror(apr_status_t statcode, char *buf, + apr_size_t bufsize); + +#if defined(DOXYGEN) +/** + * @def APR_FROM_OS_ERROR(os_err_type syserr) + * Fold a platform specific error into an apr_status_t code. + * @return apr_status_t + * @param e The platform os error code. + * @warning macro implementation; the syserr argument may be evaluated + * multiple times. + */ +#define APR_FROM_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e + APR_OS_START_SYSERR) + +/** + * @def APR_TO_OS_ERROR(apr_status_t statcode) + * @return os_err_type + * Fold an apr_status_t code back to the native platform defined error. + * @param e The apr_status_t folded platform os error code. + * @warning macro implementation; the statcode argument may be evaluated + * multiple times. If the statcode was not created by apr_get_os_error + * or APR_FROM_OS_ERROR, the results are undefined. + */ +#define APR_TO_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e - APR_OS_START_SYSERR) + +/** @def apr_get_os_error() + * @return apr_status_t the last platform error, folded into apr_status_t, on most platforms + * @remark This retrieves errno, or calls a GetLastError() style function, and + * folds it with APR_FROM_OS_ERROR. Some platforms (such as OS2) have no + * such mechanism, so this call may be unsupported. Do NOT use this + * call for socket errors from socket, send, recv etc! + */ + +/** @def apr_set_os_error(e) + * Reset the last platform error, unfolded from an apr_status_t, on some platforms + * @param e The OS error folded in a prior call to APR_FROM_OS_ERROR() + * @warning This is a macro implementation; the statcode argument may be evaluated + * multiple times. If the statcode was not created by apr_get_os_error + * or APR_FROM_OS_ERROR, the results are undefined. This macro sets + * errno, or calls a SetLastError() style function, unfolding statcode + * with APR_TO_OS_ERROR. Some platforms (such as OS2) have no such + * mechanism, so this call may be unsupported. + */ + +/** @def apr_get_netos_error() + * Return the last socket error, folded into apr_status_t, on all platforms + * @remark This retrieves errno or calls a GetLastSocketError() style function, + * and folds it with APR_FROM_OS_ERROR. + */ + +/** @def apr_set_netos_error(e) + * Reset the last socket error, unfolded from an apr_status_t + * @param e The socket error folded in a prior call to APR_FROM_OS_ERROR() + * @warning This is a macro implementation; the statcode argument may be evaluated + * multiple times. If the statcode was not created by apr_get_os_error + * or APR_FROM_OS_ERROR, the results are undefined. This macro sets + * errno, or calls a WSASetLastError() style function, unfolding + * socketcode with APR_TO_OS_ERROR. + */ + +#endif /* defined(DOXYGEN) */ + +/** + * APR_OS_START_ERROR is where the APR specific error values start. + */ +#define APR_OS_START_ERROR 20000 +/** + * APR_OS_ERRSPACE_SIZE is the maximum number of errors you can fit + * into one of the error/status ranges below -- except for + * APR_OS_START_USERERR, which see. + */ +#define APR_OS_ERRSPACE_SIZE 50000 +/** + * APR_UTIL_ERRSPACE_SIZE is the size of the space that is reserved for + * use within apr-util. This space is reserved above that used by APR + * internally. + * @note This number MUST be smaller than APR_OS_ERRSPACE_SIZE by a + * large enough amount that APR has sufficient room for its + * codes. + */ +#define APR_UTIL_ERRSPACE_SIZE 20000 +/** + * APR_OS_START_STATUS is where the APR specific status codes start. + */ +#define APR_OS_START_STATUS (APR_OS_START_ERROR + APR_OS_ERRSPACE_SIZE) +/** + * APR_UTIL_START_STATUS is where APR-Util starts defining its + * status codes. + */ +#define APR_UTIL_START_STATUS (APR_OS_START_STATUS + \ + (APR_OS_ERRSPACE_SIZE - APR_UTIL_ERRSPACE_SIZE)) +/** + * APR_OS_START_USERERR are reserved for applications that use APR that + * layer their own error codes along with APR's. Note that the + * error immediately following this one is set ten times farther + * away than usual, so that users of apr have a lot of room in + * which to declare custom error codes. + * + * In general applications should try and create unique error codes. To try + * and assist in finding suitable ranges of numbers to use, the following + * ranges are known to be used by the listed applications. If your + * application defines error codes please advise the range of numbers it + * uses to dev@apr.apache.org for inclusion in this list. + * + * Ranges shown are in relation to APR_OS_START_USERERR + * + * Subversion - Defined ranges, of less than 100, at intervals of 5000 + * starting at an offset of 5000, e.g. + * +5000 to 5100, +10000 to 10100 + * + * Apache HTTPD - +2000 to 2999 + */ +#define APR_OS_START_USERERR (APR_OS_START_STATUS + APR_OS_ERRSPACE_SIZE) +/** + * APR_OS_START_USEERR is obsolete, defined for compatibility only. + * Use APR_OS_START_USERERR instead. + */ +#define APR_OS_START_USEERR APR_OS_START_USERERR +/** + * APR_OS_START_CANONERR is where APR versions of errno values are defined + * on systems which don't have the corresponding errno. + */ +#define APR_OS_START_CANONERR (APR_OS_START_USERERR \ + + (APR_OS_ERRSPACE_SIZE * 10)) +/** + * APR_OS_START_EAIERR folds EAI_ error codes from getaddrinfo() into + * apr_status_t values. + */ +#define APR_OS_START_EAIERR (APR_OS_START_CANONERR + APR_OS_ERRSPACE_SIZE) +/** + * APR_OS_START_SYSERR folds platform-specific system error values into + * apr_status_t values. + */ +#define APR_OS_START_SYSERR (APR_OS_START_EAIERR + APR_OS_ERRSPACE_SIZE) + +/** + * @defgroup APR_ERROR_map APR Error Space + *
+ * The following attempts to show the relation of the various constants
+ * used for mapping APR Status codes.
+ *
+ *       0
+ *
+ *  20,000     APR_OS_START_ERROR
+ *
+ *         + APR_OS_ERRSPACE_SIZE (50,000)
+ *
+ *  70,000      APR_OS_START_STATUS
+ *
+ *         + APR_OS_ERRSPACE_SIZE - APR_UTIL_ERRSPACE_SIZE (30,000)
+ *
+ * 100,000      APR_UTIL_START_STATUS
+ *
+ *         + APR_UTIL_ERRSPACE_SIZE (20,000)
+ *
+ * 120,000      APR_OS_START_USERERR
+ *
+ *         + 10 x APR_OS_ERRSPACE_SIZE (50,000 * 10)
+ *
+ * 620,000      APR_OS_START_CANONERR
+ *
+ *         + APR_OS_ERRSPACE_SIZE (50,000)
+ *
+ * 670,000      APR_OS_START_EAIERR
+ *
+ *         + APR_OS_ERRSPACE_SIZE (50,000)
+ *
+ * 720,000      APR_OS_START_SYSERR
+ *
+ * 
+ */ + +/** no error. */ +#define APR_SUCCESS 0 + +/** + * @defgroup APR_Error APR Error Values + *
+ * APR ERROR VALUES
+ * APR_ENOSTAT      APR was unable to perform a stat on the file
+ * APR_ENOPOOL      APR was not provided a pool with which to allocate memory
+ * APR_EBADDATE     APR was given an invalid date
+ * APR_EINVALSOCK   APR was given an invalid socket
+ * APR_ENOPROC      APR was not given a process structure
+ * APR_ENOTIME      APR was not given a time structure
+ * APR_ENODIR       APR was not given a directory structure
+ * APR_ENOLOCK      APR was not given a lock structure
+ * APR_ENOPOLL      APR was not given a poll structure
+ * APR_ENOSOCKET    APR was not given a socket
+ * APR_ENOTHREAD    APR was not given a thread structure
+ * APR_ENOTHDKEY    APR was not given a thread key structure
+ * APR_ENOSHMAVAIL  There is no more shared memory available
+ * APR_EDSOOPEN     APR was unable to open the dso object.  For more
+ *                  information call apr_dso_error().
+ * APR_EGENERAL     General failure (specific information not available)
+ * APR_EBADIP       The specified IP address is invalid
+ * APR_EBADMASK     The specified netmask is invalid
+ * APR_ESYMNOTFOUND Could not find the requested symbol
+ * APR_ENOTENOUGHENTROPY Not enough entropy to continue
+ * 
+ * + *
+ * APR STATUS VALUES
+ * APR_INCHILD        Program is currently executing in the child
+ * APR_INPARENT       Program is currently executing in the parent
+ * APR_DETACH         The thread is detached
+ * APR_NOTDETACH      The thread is not detached
+ * APR_CHILD_DONE     The child has finished executing
+ * APR_CHILD_NOTDONE  The child has not finished executing
+ * APR_TIMEUP         The operation did not finish before the timeout
+ * APR_INCOMPLETE     The operation was incomplete although some processing
+ *                    was performed and the results are partially valid
+ * APR_BADCH          Getopt found an option not in the option string
+ * APR_BADARG         Getopt found an option that is missing an argument
+ *                    and an argument was specified in the option string
+ * APR_EOF            APR has encountered the end of the file
+ * APR_NOTFOUND       APR was unable to find the socket in the poll structure
+ * APR_ANONYMOUS      APR is using anonymous shared memory
+ * APR_FILEBASED      APR is using a file name as the key to the shared memory
+ * APR_KEYBASED       APR is using a shared key as the key to the shared memory
+ * APR_EINIT          Ininitalizer value.  If no option has been found, but
+ *                    the status variable requires a value, this should be used
+ * APR_ENOTIMPL       The APR function has not been implemented on this
+ *                    platform, either because nobody has gotten to it yet,
+ *                    or the function is impossible on this platform.
+ * APR_EMISMATCH      Two passwords do not match.
+ * APR_EABSOLUTE      The given path was absolute.
+ * APR_ERELATIVE      The given path was relative.
+ * APR_EINCOMPLETE    The given path was neither relative nor absolute.
+ * APR_EABOVEROOT     The given path was above the root path.
+ * APR_EBUSY          The given lock was busy.
+ * APR_EPROC_UNKNOWN  The given process wasn't recognized by APR
+ * 
+ * @{ + */ +/** @see APR_STATUS_IS_ENOSTAT */ +#define APR_ENOSTAT (APR_OS_START_ERROR + 1) +/** @see APR_STATUS_IS_ENOPOOL */ +#define APR_ENOPOOL (APR_OS_START_ERROR + 2) +/* empty slot: +3 */ +/** @see APR_STATUS_IS_EBADDATE */ +#define APR_EBADDATE (APR_OS_START_ERROR + 4) +/** @see APR_STATUS_IS_EINVALSOCK */ +#define APR_EINVALSOCK (APR_OS_START_ERROR + 5) +/** @see APR_STATUS_IS_ENOPROC */ +#define APR_ENOPROC (APR_OS_START_ERROR + 6) +/** @see APR_STATUS_IS_ENOTIME */ +#define APR_ENOTIME (APR_OS_START_ERROR + 7) +/** @see APR_STATUS_IS_ENODIR */ +#define APR_ENODIR (APR_OS_START_ERROR + 8) +/** @see APR_STATUS_IS_ENOLOCK */ +#define APR_ENOLOCK (APR_OS_START_ERROR + 9) +/** @see APR_STATUS_IS_ENOPOLL */ +#define APR_ENOPOLL (APR_OS_START_ERROR + 10) +/** @see APR_STATUS_IS_ENOSOCKET */ +#define APR_ENOSOCKET (APR_OS_START_ERROR + 11) +/** @see APR_STATUS_IS_ENOTHREAD */ +#define APR_ENOTHREAD (APR_OS_START_ERROR + 12) +/** @see APR_STATUS_IS_ENOTHDKEY */ +#define APR_ENOTHDKEY (APR_OS_START_ERROR + 13) +/** @see APR_STATUS_IS_EGENERAL */ +#define APR_EGENERAL (APR_OS_START_ERROR + 14) +/** @see APR_STATUS_IS_ENOSHMAVAIL */ +#define APR_ENOSHMAVAIL (APR_OS_START_ERROR + 15) +/** @see APR_STATUS_IS_EBADIP */ +#define APR_EBADIP (APR_OS_START_ERROR + 16) +/** @see APR_STATUS_IS_EBADMASK */ +#define APR_EBADMASK (APR_OS_START_ERROR + 17) +/* empty slot: +18 */ +/** @see APR_STATUS_IS_EDSOPEN */ +#define APR_EDSOOPEN (APR_OS_START_ERROR + 19) +/** @see APR_STATUS_IS_EABSOLUTE */ +#define APR_EABSOLUTE (APR_OS_START_ERROR + 20) +/** @see APR_STATUS_IS_ERELATIVE */ +#define APR_ERELATIVE (APR_OS_START_ERROR + 21) +/** @see APR_STATUS_IS_EINCOMPLETE */ +#define APR_EINCOMPLETE (APR_OS_START_ERROR + 22) +/** @see APR_STATUS_IS_EABOVEROOT */ +#define APR_EABOVEROOT (APR_OS_START_ERROR + 23) +/** @see APR_STATUS_IS_EBADPATH */ +#define APR_EBADPATH (APR_OS_START_ERROR + 24) +/** @see APR_STATUS_IS_EPATHWILD */ +#define APR_EPATHWILD (APR_OS_START_ERROR + 25) +/** @see APR_STATUS_IS_ESYMNOTFOUND */ +#define APR_ESYMNOTFOUND (APR_OS_START_ERROR + 26) +/** @see APR_STATUS_IS_EPROC_UNKNOWN */ +#define APR_EPROC_UNKNOWN (APR_OS_START_ERROR + 27) +/** @see APR_STATUS_IS_ENOTENOUGHENTROPY */ +#define APR_ENOTENOUGHENTROPY (APR_OS_START_ERROR + 28) +/** @} */ + +/** + * @defgroup APR_STATUS_IS Status Value Tests + * @warning For any particular error condition, more than one of these tests + * may match. This is because platform-specific error codes may not + * always match the semantics of the POSIX codes these tests (and the + * corresponding APR error codes) are named after. A notable example + * are the APR_STATUS_IS_ENOENT and APR_STATUS_IS_ENOTDIR tests on + * Win32 platforms. The programmer should always be aware of this and + * adjust the order of the tests accordingly. + * @{ + */ +/** + * APR was unable to perform a stat on the file + * @warning always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_ENOSTAT(s) ((s) == APR_ENOSTAT) +/** + * APR was not provided a pool with which to allocate memory + * @warning always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_ENOPOOL(s) ((s) == APR_ENOPOOL) +/** APR was given an invalid date */ +#define APR_STATUS_IS_EBADDATE(s) ((s) == APR_EBADDATE) +/** APR was given an invalid socket */ +#define APR_STATUS_IS_EINVALSOCK(s) ((s) == APR_EINVALSOCK) +/** APR was not given a process structure */ +#define APR_STATUS_IS_ENOPROC(s) ((s) == APR_ENOPROC) +/** APR was not given a time structure */ +#define APR_STATUS_IS_ENOTIME(s) ((s) == APR_ENOTIME) +/** APR was not given a directory structure */ +#define APR_STATUS_IS_ENODIR(s) ((s) == APR_ENODIR) +/** APR was not given a lock structure */ +#define APR_STATUS_IS_ENOLOCK(s) ((s) == APR_ENOLOCK) +/** APR was not given a poll structure */ +#define APR_STATUS_IS_ENOPOLL(s) ((s) == APR_ENOPOLL) +/** APR was not given a socket */ +#define APR_STATUS_IS_ENOSOCKET(s) ((s) == APR_ENOSOCKET) +/** APR was not given a thread structure */ +#define APR_STATUS_IS_ENOTHREAD(s) ((s) == APR_ENOTHREAD) +/** APR was not given a thread key structure */ +#define APR_STATUS_IS_ENOTHDKEY(s) ((s) == APR_ENOTHDKEY) +/** Generic Error which can not be put into another spot */ +#define APR_STATUS_IS_EGENERAL(s) ((s) == APR_EGENERAL) +/** There is no more shared memory available */ +#define APR_STATUS_IS_ENOSHMAVAIL(s) ((s) == APR_ENOSHMAVAIL) +/** The specified IP address is invalid */ +#define APR_STATUS_IS_EBADIP(s) ((s) == APR_EBADIP) +/** The specified netmask is invalid */ +#define APR_STATUS_IS_EBADMASK(s) ((s) == APR_EBADMASK) +/* empty slot: +18 */ +/** + * APR was unable to open the dso object. + * For more information call apr_dso_error(). + */ +#if defined(WIN32) +#define APR_STATUS_IS_EDSOOPEN(s) ((s) == APR_EDSOOPEN \ + || APR_TO_OS_ERROR(s) == ERROR_MOD_NOT_FOUND) +#else +#define APR_STATUS_IS_EDSOOPEN(s) ((s) == APR_EDSOOPEN) +#endif +/** The given path was absolute. */ +#define APR_STATUS_IS_EABSOLUTE(s) ((s) == APR_EABSOLUTE) +/** The given path was relative. */ +#define APR_STATUS_IS_ERELATIVE(s) ((s) == APR_ERELATIVE) +/** The given path was neither relative nor absolute. */ +#define APR_STATUS_IS_EINCOMPLETE(s) ((s) == APR_EINCOMPLETE) +/** The given path was above the root path. */ +#define APR_STATUS_IS_EABOVEROOT(s) ((s) == APR_EABOVEROOT) +/** The given path was bad. */ +#define APR_STATUS_IS_EBADPATH(s) ((s) == APR_EBADPATH) +/** The given path contained wildcards. */ +#define APR_STATUS_IS_EPATHWILD(s) ((s) == APR_EPATHWILD) +/** Could not find the requested symbol. + * For more information call apr_dso_error(). + */ +#if defined(WIN32) +#define APR_STATUS_IS_ESYMNOTFOUND(s) ((s) == APR_ESYMNOTFOUND \ + || APR_TO_OS_ERROR(s) == ERROR_PROC_NOT_FOUND) +#else +#define APR_STATUS_IS_ESYMNOTFOUND(s) ((s) == APR_ESYMNOTFOUND) +#endif +/** The given process was not recognized by APR. */ +#define APR_STATUS_IS_EPROC_UNKNOWN(s) ((s) == APR_EPROC_UNKNOWN) +/** APR could not gather enough entropy to continue. */ +#define APR_STATUS_IS_ENOTENOUGHENTROPY(s) ((s) == APR_ENOTENOUGHENTROPY) + +/** @} */ + +/** + * @addtogroup APR_Error + * @{ + */ +/** @see APR_STATUS_IS_INCHILD */ +#define APR_INCHILD (APR_OS_START_STATUS + 1) +/** @see APR_STATUS_IS_INPARENT */ +#define APR_INPARENT (APR_OS_START_STATUS + 2) +/** @see APR_STATUS_IS_DETACH */ +#define APR_DETACH (APR_OS_START_STATUS + 3) +/** @see APR_STATUS_IS_NOTDETACH */ +#define APR_NOTDETACH (APR_OS_START_STATUS + 4) +/** @see APR_STATUS_IS_CHILD_DONE */ +#define APR_CHILD_DONE (APR_OS_START_STATUS + 5) +/** @see APR_STATUS_IS_CHILD_NOTDONE */ +#define APR_CHILD_NOTDONE (APR_OS_START_STATUS + 6) +/** @see APR_STATUS_IS_TIMEUP */ +#define APR_TIMEUP (APR_OS_START_STATUS + 7) +/** @see APR_STATUS_IS_INCOMPLETE */ +#define APR_INCOMPLETE (APR_OS_START_STATUS + 8) +/* empty slot: +9 */ +/* empty slot: +10 */ +/* empty slot: +11 */ +/** @see APR_STATUS_IS_BADCH */ +#define APR_BADCH (APR_OS_START_STATUS + 12) +/** @see APR_STATUS_IS_BADARG */ +#define APR_BADARG (APR_OS_START_STATUS + 13) +/** @see APR_STATUS_IS_EOF */ +#define APR_EOF (APR_OS_START_STATUS + 14) +/** @see APR_STATUS_IS_NOTFOUND */ +#define APR_NOTFOUND (APR_OS_START_STATUS + 15) +/* empty slot: +16 */ +/* empty slot: +17 */ +/* empty slot: +18 */ +/** @see APR_STATUS_IS_ANONYMOUS */ +#define APR_ANONYMOUS (APR_OS_START_STATUS + 19) +/** @see APR_STATUS_IS_FILEBASED */ +#define APR_FILEBASED (APR_OS_START_STATUS + 20) +/** @see APR_STATUS_IS_KEYBASED */ +#define APR_KEYBASED (APR_OS_START_STATUS + 21) +/** @see APR_STATUS_IS_EINIT */ +#define APR_EINIT (APR_OS_START_STATUS + 22) +/** @see APR_STATUS_IS_ENOTIMPL */ +#define APR_ENOTIMPL (APR_OS_START_STATUS + 23) +/** @see APR_STATUS_IS_EMISMATCH */ +#define APR_EMISMATCH (APR_OS_START_STATUS + 24) +/** @see APR_STATUS_IS_EBUSY */ +#define APR_EBUSY (APR_OS_START_STATUS + 25) +/** @} */ + +/** + * @addtogroup APR_STATUS_IS + * @{ + */ +/** + * Program is currently executing in the child + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code */ +#define APR_STATUS_IS_INCHILD(s) ((s) == APR_INCHILD) +/** + * Program is currently executing in the parent + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_INPARENT(s) ((s) == APR_INPARENT) +/** + * The thread is detached + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_DETACH(s) ((s) == APR_DETACH) +/** + * The thread is not detached + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_NOTDETACH(s) ((s) == APR_NOTDETACH) +/** + * The child has finished executing + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_CHILD_DONE(s) ((s) == APR_CHILD_DONE) +/** + * The child has not finished executing + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_CHILD_NOTDONE(s) ((s) == APR_CHILD_NOTDONE) +/** + * The operation did not finish before the timeout + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_TIMEUP(s) ((s) == APR_TIMEUP) +/** + * The operation was incomplete although some processing was performed + * and the results are partially valid. + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_INCOMPLETE(s) ((s) == APR_INCOMPLETE) +/* empty slot: +9 */ +/* empty slot: +10 */ +/* empty slot: +11 */ +/** + * Getopt found an option not in the option string + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_BADCH(s) ((s) == APR_BADCH) +/** + * Getopt found an option not in the option string and an argument was + * specified in the option string + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_BADARG(s) ((s) == APR_BADARG) +/** + * APR has encountered the end of the file + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_EOF(s) ((s) == APR_EOF) +/** + * APR was unable to find the socket in the poll structure + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_NOTFOUND(s) ((s) == APR_NOTFOUND) +/* empty slot: +16 */ +/* empty slot: +17 */ +/* empty slot: +18 */ +/** + * APR is using anonymous shared memory + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_ANONYMOUS(s) ((s) == APR_ANONYMOUS) +/** + * APR is using a file name as the key to the shared memory + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_FILEBASED(s) ((s) == APR_FILEBASED) +/** + * APR is using a shared key as the key to the shared memory + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_KEYBASED(s) ((s) == APR_KEYBASED) +/** + * Ininitalizer value. If no option has been found, but + * the status variable requires a value, this should be used + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_EINIT(s) ((s) == APR_EINIT) +/** + * The APR function has not been implemented on this + * platform, either because nobody has gotten to it yet, + * or the function is impossible on this platform. + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_ENOTIMPL(s) ((s) == APR_ENOTIMPL) +/** + * Two passwords do not match. + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_EMISMATCH(s) ((s) == APR_EMISMATCH) +/** + * The given lock was busy + * @warning always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_EBUSY(s) ((s) == APR_EBUSY) + +/** @} */ + +/** + * @addtogroup APR_Error APR Error Values + * @{ + */ +/* APR CANONICAL ERROR VALUES */ +/** @see APR_STATUS_IS_EACCES */ +#ifdef EACCES +#define APR_EACCES EACCES +#else +#define APR_EACCES (APR_OS_START_CANONERR + 1) +#endif + +/** @see APR_STATUS_IS_EEXIST */ +#ifdef EEXIST +#define APR_EEXIST EEXIST +#else +#define APR_EEXIST (APR_OS_START_CANONERR + 2) +#endif + +/** @see APR_STATUS_IS_ENAMETOOLONG */ +#ifdef ENAMETOOLONG +#define APR_ENAMETOOLONG ENAMETOOLONG +#else +#define APR_ENAMETOOLONG (APR_OS_START_CANONERR + 3) +#endif + +/** @see APR_STATUS_IS_ENOENT */ +#ifdef ENOENT +#define APR_ENOENT ENOENT +#else +#define APR_ENOENT (APR_OS_START_CANONERR + 4) +#endif + +/** @see APR_STATUS_IS_ENOTDIR */ +#ifdef ENOTDIR +#define APR_ENOTDIR ENOTDIR +#else +#define APR_ENOTDIR (APR_OS_START_CANONERR + 5) +#endif + +/** @see APR_STATUS_IS_ENOSPC */ +#ifdef ENOSPC +#define APR_ENOSPC ENOSPC +#else +#define APR_ENOSPC (APR_OS_START_CANONERR + 6) +#endif + +/** @see APR_STATUS_IS_ENOMEM */ +#ifdef ENOMEM +#define APR_ENOMEM ENOMEM +#else +#define APR_ENOMEM (APR_OS_START_CANONERR + 7) +#endif + +/** @see APR_STATUS_IS_EMFILE */ +#ifdef EMFILE +#define APR_EMFILE EMFILE +#else +#define APR_EMFILE (APR_OS_START_CANONERR + 8) +#endif + +/** @see APR_STATUS_IS_ENFILE */ +#ifdef ENFILE +#define APR_ENFILE ENFILE +#else +#define APR_ENFILE (APR_OS_START_CANONERR + 9) +#endif + +/** @see APR_STATUS_IS_EBADF */ +#ifdef EBADF +#define APR_EBADF EBADF +#else +#define APR_EBADF (APR_OS_START_CANONERR + 10) +#endif + +/** @see APR_STATUS_IS_EINVAL */ +#ifdef EINVAL +#define APR_EINVAL EINVAL +#else +#define APR_EINVAL (APR_OS_START_CANONERR + 11) +#endif + +/** @see APR_STATUS_IS_ESPIPE */ +#ifdef ESPIPE +#define APR_ESPIPE ESPIPE +#else +#define APR_ESPIPE (APR_OS_START_CANONERR + 12) +#endif + +/** + * @see APR_STATUS_IS_EAGAIN + * @warning use APR_STATUS_IS_EAGAIN instead of just testing this value + */ +#ifdef EAGAIN +#define APR_EAGAIN EAGAIN +#elif defined(EWOULDBLOCK) +#define APR_EAGAIN EWOULDBLOCK +#else +#define APR_EAGAIN (APR_OS_START_CANONERR + 13) +#endif + +/** @see APR_STATUS_IS_EINTR */ +#ifdef EINTR +#define APR_EINTR EINTR +#else +#define APR_EINTR (APR_OS_START_CANONERR + 14) +#endif + +/** @see APR_STATUS_IS_ENOTSOCK */ +#ifdef ENOTSOCK +#define APR_ENOTSOCK ENOTSOCK +#else +#define APR_ENOTSOCK (APR_OS_START_CANONERR + 15) +#endif + +/** @see APR_STATUS_IS_ECONNREFUSED */ +#ifdef ECONNREFUSED +#define APR_ECONNREFUSED ECONNREFUSED +#else +#define APR_ECONNREFUSED (APR_OS_START_CANONERR + 16) +#endif + +/** @see APR_STATUS_IS_EINPROGRESS */ +#ifdef EINPROGRESS +#define APR_EINPROGRESS EINPROGRESS +#else +#define APR_EINPROGRESS (APR_OS_START_CANONERR + 17) +#endif + +/** + * @see APR_STATUS_IS_ECONNABORTED + * @warning use APR_STATUS_IS_ECONNABORTED instead of just testing this value + */ + +#ifdef ECONNABORTED +#define APR_ECONNABORTED ECONNABORTED +#else +#define APR_ECONNABORTED (APR_OS_START_CANONERR + 18) +#endif + +/** @see APR_STATUS_IS_ECONNRESET */ +#ifdef ECONNRESET +#define APR_ECONNRESET ECONNRESET +#else +#define APR_ECONNRESET (APR_OS_START_CANONERR + 19) +#endif + +/** @see APR_STATUS_IS_ETIMEDOUT + * @deprecated */ +#ifdef ETIMEDOUT +#define APR_ETIMEDOUT ETIMEDOUT +#else +#define APR_ETIMEDOUT (APR_OS_START_CANONERR + 20) +#endif + +/** @see APR_STATUS_IS_EHOSTUNREACH */ +#ifdef EHOSTUNREACH +#define APR_EHOSTUNREACH EHOSTUNREACH +#else +#define APR_EHOSTUNREACH (APR_OS_START_CANONERR + 21) +#endif + +/** @see APR_STATUS_IS_ENETUNREACH */ +#ifdef ENETUNREACH +#define APR_ENETUNREACH ENETUNREACH +#else +#define APR_ENETUNREACH (APR_OS_START_CANONERR + 22) +#endif + +/** @see APR_STATUS_IS_EFTYPE */ +#ifdef EFTYPE +#define APR_EFTYPE EFTYPE +#else +#define APR_EFTYPE (APR_OS_START_CANONERR + 23) +#endif + +/** @see APR_STATUS_IS_EPIPE */ +#ifdef EPIPE +#define APR_EPIPE EPIPE +#else +#define APR_EPIPE (APR_OS_START_CANONERR + 24) +#endif + +/** @see APR_STATUS_IS_EXDEV */ +#ifdef EXDEV +#define APR_EXDEV EXDEV +#else +#define APR_EXDEV (APR_OS_START_CANONERR + 25) +#endif + +/** @see APR_STATUS_IS_ENOTEMPTY */ +#ifdef ENOTEMPTY +#define APR_ENOTEMPTY ENOTEMPTY +#else +#define APR_ENOTEMPTY (APR_OS_START_CANONERR + 26) +#endif + +/** @see APR_STATUS_IS_EAFNOSUPPORT */ +#ifdef EAFNOSUPPORT +#define APR_EAFNOSUPPORT EAFNOSUPPORT +#else +#define APR_EAFNOSUPPORT (APR_OS_START_CANONERR + 27) +#endif + +/** @see APR_STATUS_IS_EOPNOTSUPP */ +#ifdef EOPNOTSUPP +#define APR_EOPNOTSUPP EOPNOTSUPP +#else +#define APR_EOPNOTSUPP (APR_OS_START_CANONERR + 28) +#endif + +/** @see APR_STATUS_IS_ERANGE */ +#ifdef ERANGE +#define APR_ERANGE ERANGE +#else +#define APR_ERANGE (APR_OS_START_CANONERR + 29) +#endif + +/** @} */ + +#if defined(OS2) && !defined(DOXYGEN) + +#define APR_FROM_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e + APR_OS_START_SYSERR) +#define APR_TO_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e - APR_OS_START_SYSERR) + +#define INCL_DOSERRORS +#define INCL_DOS + +/* Leave these undefined. + * OS2 doesn't rely on the errno concept. + * The API calls always return a result codes which + * should be filtered through APR_FROM_OS_ERROR(). + * + * #define apr_get_os_error() (APR_FROM_OS_ERROR(GetLastError())) + * #define apr_set_os_error(e) (SetLastError(APR_TO_OS_ERROR(e))) + */ + +/* A special case, only socket calls require this; + */ +#define apr_get_netos_error() (APR_FROM_OS_ERROR(errno)) +#define apr_set_netos_error(e) (errno = APR_TO_OS_ERROR(e)) + +/* And this needs to be greped away for good: + */ +#define APR_OS2_STATUS(e) (APR_FROM_OS_ERROR(e)) + +/* These can't sit in a private header, so in spite of the extra size, + * they need to be made available here. + */ +#define SOCBASEERR 10000 +#define SOCEPERM (SOCBASEERR+1) /* Not owner */ +#define SOCESRCH (SOCBASEERR+3) /* No such process */ +#define SOCEINTR (SOCBASEERR+4) /* Interrupted system call */ +#define SOCENXIO (SOCBASEERR+6) /* No such device or address */ +#define SOCEBADF (SOCBASEERR+9) /* Bad file number */ +#define SOCEACCES (SOCBASEERR+13) /* Permission denied */ +#define SOCEFAULT (SOCBASEERR+14) /* Bad address */ +#define SOCEINVAL (SOCBASEERR+22) /* Invalid argument */ +#define SOCEMFILE (SOCBASEERR+24) /* Too many open files */ +#define SOCEPIPE (SOCBASEERR+32) /* Broken pipe */ +#define SOCEOS2ERR (SOCBASEERR+100) /* OS/2 Error */ +#define SOCEWOULDBLOCK (SOCBASEERR+35) /* Operation would block */ +#define SOCEINPROGRESS (SOCBASEERR+36) /* Operation now in progress */ +#define SOCEALREADY (SOCBASEERR+37) /* Operation already in progress */ +#define SOCENOTSOCK (SOCBASEERR+38) /* Socket operation on non-socket */ +#define SOCEDESTADDRREQ (SOCBASEERR+39) /* Destination address required */ +#define SOCEMSGSIZE (SOCBASEERR+40) /* Message too long */ +#define SOCEPROTOTYPE (SOCBASEERR+41) /* Protocol wrong type for socket */ +#define SOCENOPROTOOPT (SOCBASEERR+42) /* Protocol not available */ +#define SOCEPROTONOSUPPORT (SOCBASEERR+43) /* Protocol not supported */ +#define SOCESOCKTNOSUPPORT (SOCBASEERR+44) /* Socket type not supported */ +#define SOCEOPNOTSUPP (SOCBASEERR+45) /* Operation not supported on socket */ +#define SOCEPFNOSUPPORT (SOCBASEERR+46) /* Protocol family not supported */ +#define SOCEAFNOSUPPORT (SOCBASEERR+47) /* Address family not supported by protocol family */ +#define SOCEADDRINUSE (SOCBASEERR+48) /* Address already in use */ +#define SOCEADDRNOTAVAIL (SOCBASEERR+49) /* Can't assign requested address */ +#define SOCENETDOWN (SOCBASEERR+50) /* Network is down */ +#define SOCENETUNREACH (SOCBASEERR+51) /* Network is unreachable */ +#define SOCENETRESET (SOCBASEERR+52) /* Network dropped connection on reset */ +#define SOCECONNABORTED (SOCBASEERR+53) /* Software caused connection abort */ +#define SOCECONNRESET (SOCBASEERR+54) /* Connection reset by peer */ +#define SOCENOBUFS (SOCBASEERR+55) /* No buffer space available */ +#define SOCEISCONN (SOCBASEERR+56) /* Socket is already connected */ +#define SOCENOTCONN (SOCBASEERR+57) /* Socket is not connected */ +#define SOCESHUTDOWN (SOCBASEERR+58) /* Can't send after socket shutdown */ +#define SOCETOOMANYREFS (SOCBASEERR+59) /* Too many references: can't splice */ +#define SOCETIMEDOUT (SOCBASEERR+60) /* Connection timed out */ +#define SOCECONNREFUSED (SOCBASEERR+61) /* Connection refused */ +#define SOCELOOP (SOCBASEERR+62) /* Too many levels of symbolic links */ +#define SOCENAMETOOLONG (SOCBASEERR+63) /* File name too long */ +#define SOCEHOSTDOWN (SOCBASEERR+64) /* Host is down */ +#define SOCEHOSTUNREACH (SOCBASEERR+65) /* No route to host */ +#define SOCENOTEMPTY (SOCBASEERR+66) /* Directory not empty */ + +/* APR CANONICAL ERROR TESTS */ +#define APR_STATUS_IS_EACCES(s) ((s) == APR_EACCES \ + || (s) == APR_OS_START_SYSERR + ERROR_ACCESS_DENIED \ + || (s) == APR_OS_START_SYSERR + ERROR_SHARING_VIOLATION) +#define APR_STATUS_IS_EEXIST(s) ((s) == APR_EEXIST \ + || (s) == APR_OS_START_SYSERR + ERROR_OPEN_FAILED \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_EXISTS \ + || (s) == APR_OS_START_SYSERR + ERROR_ALREADY_EXISTS \ + || (s) == APR_OS_START_SYSERR + ERROR_ACCESS_DENIED) +#define APR_STATUS_IS_ENAMETOOLONG(s) ((s) == APR_ENAMETOOLONG \ + || (s) == APR_OS_START_SYSERR + ERROR_FILENAME_EXCED_RANGE \ + || (s) == APR_OS_START_SYSERR + SOCENAMETOOLONG) +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_PATH_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_MORE_FILES \ + || (s) == APR_OS_START_SYSERR + ERROR_OPEN_FAILED) +#define APR_STATUS_IS_ENOTDIR(s) ((s) == APR_ENOTDIR) +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC \ + || (s) == APR_OS_START_SYSERR + ERROR_DISK_FULL) +#define APR_STATUS_IS_ENOMEM(s) ((s) == APR_ENOMEM) +#define APR_STATUS_IS_EMFILE(s) ((s) == APR_EMFILE \ + || (s) == APR_OS_START_SYSERR + ERROR_TOO_MANY_OPEN_FILES) +#define APR_STATUS_IS_ENFILE(s) ((s) == APR_ENFILE) +#define APR_STATUS_IS_EBADF(s) ((s) == APR_EBADF \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_HANDLE) +#define APR_STATUS_IS_EINVAL(s) ((s) == APR_EINVAL \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_PARAMETER \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_FUNCTION) +#define APR_STATUS_IS_ESPIPE(s) ((s) == APR_ESPIPE \ + || (s) == APR_OS_START_SYSERR + ERROR_NEGATIVE_SEEK) +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_DATA \ + || (s) == APR_OS_START_SYSERR + SOCEWOULDBLOCK \ + || (s) == APR_OS_START_SYSERR + ERROR_LOCK_VIOLATION) +#define APR_STATUS_IS_EINTR(s) ((s) == APR_EINTR \ + || (s) == APR_OS_START_SYSERR + SOCEINTR) +#define APR_STATUS_IS_ENOTSOCK(s) ((s) == APR_ENOTSOCK \ + || (s) == APR_OS_START_SYSERR + SOCENOTSOCK) +#define APR_STATUS_IS_ECONNREFUSED(s) ((s) == APR_ECONNREFUSED \ + || (s) == APR_OS_START_SYSERR + SOCECONNREFUSED) +#define APR_STATUS_IS_EINPROGRESS(s) ((s) == APR_EINPROGRESS \ + || (s) == APR_OS_START_SYSERR + SOCEINPROGRESS) +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED \ + || (s) == APR_OS_START_SYSERR + SOCECONNABORTED) +#define APR_STATUS_IS_ECONNRESET(s) ((s) == APR_ECONNRESET \ + || (s) == APR_OS_START_SYSERR + SOCECONNRESET) +/* XXX deprecated */ +#define APR_STATUS_IS_ETIMEDOUT(s) ((s) == APR_ETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + SOCETIMEDOUT) +#undef APR_STATUS_IS_TIMEUP +#define APR_STATUS_IS_TIMEUP(s) ((s) == APR_TIMEUP \ + || (s) == APR_OS_START_SYSERR + SOCETIMEDOUT) +#define APR_STATUS_IS_EHOSTUNREACH(s) ((s) == APR_EHOSTUNREACH \ + || (s) == APR_OS_START_SYSERR + SOCEHOSTUNREACH) +#define APR_STATUS_IS_ENETUNREACH(s) ((s) == APR_ENETUNREACH \ + || (s) == APR_OS_START_SYSERR + SOCENETUNREACH) +#define APR_STATUS_IS_EFTYPE(s) ((s) == APR_EFTYPE) +#define APR_STATUS_IS_EPIPE(s) ((s) == APR_EPIPE \ + || (s) == APR_OS_START_SYSERR + ERROR_BROKEN_PIPE \ + || (s) == APR_OS_START_SYSERR + SOCEPIPE) +#define APR_STATUS_IS_EXDEV(s) ((s) == APR_EXDEV \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_SAME_DEVICE) +#define APR_STATUS_IS_ENOTEMPTY(s) ((s) == APR_ENOTEMPTY \ + || (s) == APR_OS_START_SYSERR + ERROR_DIR_NOT_EMPTY \ + || (s) == APR_OS_START_SYSERR + ERROR_ACCESS_DENIED) +#define APR_STATUS_IS_EAFNOSUPPORT(s) ((s) == APR_AFNOSUPPORT \ + || (s) == APR_OS_START_SYSERR + SOCEAFNOSUPPORT) +#define APR_STATUS_IS_EOPNOTSUPP(s) ((s) == APR_EOPNOTSUPP \ + || (s) == APR_OS_START_SYSERR + SOCEOPNOTSUPP) +#define APR_STATUS_IS_ERANGE(s) ((s) == APR_ERANGE) + +/* + Sorry, too tired to wrap this up for OS2... feel free to + fit the following into their best matches. + + { ERROR_NO_SIGNAL_SENT, ESRCH }, + { SOCEALREADY, EALREADY }, + { SOCEDESTADDRREQ, EDESTADDRREQ }, + { SOCEMSGSIZE, EMSGSIZE }, + { SOCEPROTOTYPE, EPROTOTYPE }, + { SOCENOPROTOOPT, ENOPROTOOPT }, + { SOCEPROTONOSUPPORT, EPROTONOSUPPORT }, + { SOCESOCKTNOSUPPORT, ESOCKTNOSUPPORT }, + { SOCEPFNOSUPPORT, EPFNOSUPPORT }, + { SOCEADDRINUSE, EADDRINUSE }, + { SOCEADDRNOTAVAIL, EADDRNOTAVAIL }, + { SOCENETDOWN, ENETDOWN }, + { SOCENETRESET, ENETRESET }, + { SOCENOBUFS, ENOBUFS }, + { SOCEISCONN, EISCONN }, + { SOCENOTCONN, ENOTCONN }, + { SOCESHUTDOWN, ESHUTDOWN }, + { SOCETOOMANYREFS, ETOOMANYREFS }, + { SOCELOOP, ELOOP }, + { SOCEHOSTDOWN, EHOSTDOWN }, + { SOCENOTEMPTY, ENOTEMPTY }, + { SOCEPIPE, EPIPE } +*/ + +#elif defined(WIN32) && !defined(DOXYGEN) /* !defined(OS2) */ + +#define APR_FROM_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e + APR_OS_START_SYSERR) +#define APR_TO_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e - APR_OS_START_SYSERR) + +#define apr_get_os_error() (APR_FROM_OS_ERROR(GetLastError())) +#define apr_set_os_error(e) (SetLastError(APR_TO_OS_ERROR(e))) + +/* A special case, only socket calls require this: + */ +#define apr_get_netos_error() (APR_FROM_OS_ERROR(WSAGetLastError())) +#define apr_set_netos_error(e) (WSASetLastError(APR_TO_OS_ERROR(e))) + +/* APR CANONICAL ERROR TESTS */ +#define APR_STATUS_IS_EACCES(s) ((s) == APR_EACCES \ + || (s) == APR_OS_START_SYSERR + ERROR_ACCESS_DENIED \ + || (s) == APR_OS_START_SYSERR + ERROR_CANNOT_MAKE \ + || (s) == APR_OS_START_SYSERR + ERROR_CURRENT_DIRECTORY \ + || (s) == APR_OS_START_SYSERR + ERROR_DRIVE_LOCKED \ + || (s) == APR_OS_START_SYSERR + ERROR_FAIL_I24 \ + || (s) == APR_OS_START_SYSERR + ERROR_LOCK_VIOLATION \ + || (s) == APR_OS_START_SYSERR + ERROR_LOCK_FAILED \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_LOCKED \ + || (s) == APR_OS_START_SYSERR + ERROR_NETWORK_ACCESS_DENIED \ + || (s) == APR_OS_START_SYSERR + ERROR_SHARING_VIOLATION) +#define APR_STATUS_IS_EEXIST(s) ((s) == APR_EEXIST \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_EXISTS \ + || (s) == APR_OS_START_SYSERR + ERROR_ALREADY_EXISTS) +#define APR_STATUS_IS_ENAMETOOLONG(s) ((s) == APR_ENAMETOOLONG \ + || (s) == APR_OS_START_SYSERR + ERROR_FILENAME_EXCED_RANGE \ + || (s) == APR_OS_START_SYSERR + WSAENAMETOOLONG) +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_PATH_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_OPEN_FAILED \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_MORE_FILES) +#define APR_STATUS_IS_ENOTDIR(s) ((s) == APR_ENOTDIR \ + || (s) == APR_OS_START_SYSERR + ERROR_PATH_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_NETPATH \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_NET_NAME \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_PATHNAME \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_DRIVE \ + || (s) == APR_OS_START_SYSERR + ERROR_DIRECTORY) +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC \ + || (s) == APR_OS_START_SYSERR + ERROR_DISK_FULL) +#define APR_STATUS_IS_ENOMEM(s) ((s) == APR_ENOMEM \ + || (s) == APR_OS_START_SYSERR + ERROR_ARENA_TRASHED \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_ENOUGH_MEMORY \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_BLOCK \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_ENOUGH_QUOTA \ + || (s) == APR_OS_START_SYSERR + ERROR_OUTOFMEMORY) +#define APR_STATUS_IS_EMFILE(s) ((s) == APR_EMFILE \ + || (s) == APR_OS_START_SYSERR + ERROR_TOO_MANY_OPEN_FILES) +#define APR_STATUS_IS_ENFILE(s) ((s) == APR_ENFILE) +#define APR_STATUS_IS_EBADF(s) ((s) == APR_EBADF \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_HANDLE \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_TARGET_HANDLE) +#define APR_STATUS_IS_EINVAL(s) ((s) == APR_EINVAL \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_ACCESS \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_DATA \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_FUNCTION \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_HANDLE \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_PARAMETER \ + || (s) == APR_OS_START_SYSERR + ERROR_NEGATIVE_SEEK) +#define APR_STATUS_IS_ESPIPE(s) ((s) == APR_ESPIPE \ + || (s) == APR_OS_START_SYSERR + ERROR_SEEK_ON_DEVICE \ + || (s) == APR_OS_START_SYSERR + ERROR_NEGATIVE_SEEK) +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_DATA \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_PROC_SLOTS \ + || (s) == APR_OS_START_SYSERR + ERROR_NESTING_NOT_ALLOWED \ + || (s) == APR_OS_START_SYSERR + ERROR_MAX_THRDS_REACHED \ + || (s) == APR_OS_START_SYSERR + ERROR_LOCK_VIOLATION \ + || (s) == APR_OS_START_SYSERR + WSAEWOULDBLOCK) +#define APR_STATUS_IS_EINTR(s) ((s) == APR_EINTR \ + || (s) == APR_OS_START_SYSERR + WSAEINTR) +#define APR_STATUS_IS_ENOTSOCK(s) ((s) == APR_ENOTSOCK \ + || (s) == APR_OS_START_SYSERR + WSAENOTSOCK) +#define APR_STATUS_IS_ECONNREFUSED(s) ((s) == APR_ECONNREFUSED \ + || (s) == APR_OS_START_SYSERR + WSAECONNREFUSED) +#define APR_STATUS_IS_EINPROGRESS(s) ((s) == APR_EINPROGRESS \ + || (s) == APR_OS_START_SYSERR + WSAEINPROGRESS) +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED \ + || (s) == APR_OS_START_SYSERR + WSAECONNABORTED) +#define APR_STATUS_IS_ECONNRESET(s) ((s) == APR_ECONNRESET \ + || (s) == APR_OS_START_SYSERR + ERROR_NETNAME_DELETED \ + || (s) == APR_OS_START_SYSERR + WSAECONNRESET) +/* XXX deprecated */ +#define APR_STATUS_IS_ETIMEDOUT(s) ((s) == APR_ETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WSAETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WAIT_TIMEOUT) +#undef APR_STATUS_IS_TIMEUP +#define APR_STATUS_IS_TIMEUP(s) ((s) == APR_TIMEUP \ + || (s) == APR_OS_START_SYSERR + WSAETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WAIT_TIMEOUT) +#define APR_STATUS_IS_EHOSTUNREACH(s) ((s) == APR_EHOSTUNREACH \ + || (s) == APR_OS_START_SYSERR + WSAEHOSTUNREACH) +#define APR_STATUS_IS_ENETUNREACH(s) ((s) == APR_ENETUNREACH \ + || (s) == APR_OS_START_SYSERR + WSAENETUNREACH) +#define APR_STATUS_IS_EFTYPE(s) ((s) == APR_EFTYPE \ + || (s) == APR_OS_START_SYSERR + ERROR_EXE_MACHINE_TYPE_MISMATCH \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_DLL \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_MODULETYPE \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_EXE_FORMAT \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_EXE_SIGNATURE \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_CORRUPT \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_FORMAT) +#define APR_STATUS_IS_EPIPE(s) ((s) == APR_EPIPE \ + || (s) == APR_OS_START_SYSERR + ERROR_BROKEN_PIPE) +#define APR_STATUS_IS_EXDEV(s) ((s) == APR_EXDEV \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_SAME_DEVICE) +#define APR_STATUS_IS_ENOTEMPTY(s) ((s) == APR_ENOTEMPTY \ + || (s) == APR_OS_START_SYSERR + ERROR_DIR_NOT_EMPTY) +#define APR_STATUS_IS_EAFNOSUPPORT(s) ((s) == APR_EAFNOSUPPORT \ + || (s) == APR_OS_START_SYSERR + WSAEAFNOSUPPORT) +#define APR_STATUS_IS_EOPNOTSUPP(s) ((s) == APR_EOPNOTSUPP \ + || (s) == APR_OS_START_SYSERR + WSAEOPNOTSUPP) +#define APR_STATUS_IS_ERANGE(s) ((s) == APR_ERANGE) + +#elif defined(NETWARE) && defined(USE_WINSOCK) && !defined(DOXYGEN) /* !defined(OS2) && !defined(WIN32) */ + +#define APR_FROM_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e + APR_OS_START_SYSERR) +#define APR_TO_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e - APR_OS_START_SYSERR) + +#define apr_get_os_error() (errno) +#define apr_set_os_error(e) (errno = (e)) + +/* A special case, only socket calls require this: */ +#define apr_get_netos_error() (APR_FROM_OS_ERROR(WSAGetLastError())) +#define apr_set_netos_error(e) (WSASetLastError(APR_TO_OS_ERROR(e))) + +/* APR CANONICAL ERROR TESTS */ +#define APR_STATUS_IS_EACCES(s) ((s) == APR_EACCES) +#define APR_STATUS_IS_EEXIST(s) ((s) == APR_EEXIST) +#define APR_STATUS_IS_ENAMETOOLONG(s) ((s) == APR_ENAMETOOLONG) +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT) +#define APR_STATUS_IS_ENOTDIR(s) ((s) == APR_ENOTDIR) +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC) +#define APR_STATUS_IS_ENOMEM(s) ((s) == APR_ENOMEM) +#define APR_STATUS_IS_EMFILE(s) ((s) == APR_EMFILE) +#define APR_STATUS_IS_ENFILE(s) ((s) == APR_ENFILE) +#define APR_STATUS_IS_EBADF(s) ((s) == APR_EBADF) +#define APR_STATUS_IS_EINVAL(s) ((s) == APR_EINVAL) +#define APR_STATUS_IS_ESPIPE(s) ((s) == APR_ESPIPE) + +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN \ + || (s) == EWOULDBLOCK \ + || (s) == APR_OS_START_SYSERR + WSAEWOULDBLOCK) +#define APR_STATUS_IS_EINTR(s) ((s) == APR_EINTR \ + || (s) == APR_OS_START_SYSERR + WSAEINTR) +#define APR_STATUS_IS_ENOTSOCK(s) ((s) == APR_ENOTSOCK \ + || (s) == APR_OS_START_SYSERR + WSAENOTSOCK) +#define APR_STATUS_IS_ECONNREFUSED(s) ((s) == APR_ECONNREFUSED \ + || (s) == APR_OS_START_SYSERR + WSAECONNREFUSED) +#define APR_STATUS_IS_EINPROGRESS(s) ((s) == APR_EINPROGRESS \ + || (s) == APR_OS_START_SYSERR + WSAEINPROGRESS) +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED \ + || (s) == APR_OS_START_SYSERR + WSAECONNABORTED) +#define APR_STATUS_IS_ECONNRESET(s) ((s) == APR_ECONNRESET \ + || (s) == APR_OS_START_SYSERR + WSAECONNRESET) +/* XXX deprecated */ +#define APR_STATUS_IS_ETIMEDOUT(s) ((s) == APR_ETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WSAETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WAIT_TIMEOUT) +#undef APR_STATUS_IS_TIMEUP +#define APR_STATUS_IS_TIMEUP(s) ((s) == APR_TIMEUP \ + || (s) == APR_OS_START_SYSERR + WSAETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WAIT_TIMEOUT) +#define APR_STATUS_IS_EHOSTUNREACH(s) ((s) == APR_EHOSTUNREACH \ + || (s) == APR_OS_START_SYSERR + WSAEHOSTUNREACH) +#define APR_STATUS_IS_ENETUNREACH(s) ((s) == APR_ENETUNREACH \ + || (s) == APR_OS_START_SYSERR + WSAENETUNREACH) +#define APR_STATUS_IS_ENETDOWN(s) ((s) == APR_OS_START_SYSERR + WSAENETDOWN) +#define APR_STATUS_IS_EFTYPE(s) ((s) == APR_EFTYPE) +#define APR_STATUS_IS_EPIPE(s) ((s) == APR_EPIPE) +#define APR_STATUS_IS_EXDEV(s) ((s) == APR_EXDEV) +#define APR_STATUS_IS_ENOTEMPTY(s) ((s) == APR_ENOTEMPTY) +#define APR_STATUS_IS_EAFNOSUPPORT(s) ((s) == APR_EAFNOSUPPORT \ + || (s) == APR_OS_START_SYSERR + WSAEAFNOSUPPORT) +#define APR_STATUS_IS_EOPNOTSUPP(s) ((s) == APR_EOPNOTSUPP \ + || (s) == APR_OS_START_SYSERR + WSAEOPNOTSUPP) +#define APR_STATUS_IS_ERANGE(s) ((s) == APR_ERANGE) + +#else /* !defined(NETWARE) && !defined(OS2) && !defined(WIN32) */ + +/* + * os error codes are clib error codes + */ +#define APR_FROM_OS_ERROR(e) (e) +#define APR_TO_OS_ERROR(e) (e) + +#define apr_get_os_error() (errno) +#define apr_set_os_error(e) (errno = (e)) + +/* A special case, only socket calls require this: + */ +#define apr_get_netos_error() (errno) +#define apr_set_netos_error(e) (errno = (e)) + +/** + * @addtogroup APR_STATUS_IS + * @{ + */ + +/** permission denied */ +#define APR_STATUS_IS_EACCES(s) ((s) == APR_EACCES) +/** file exists */ +#define APR_STATUS_IS_EEXIST(s) ((s) == APR_EEXIST) +/** path name is too long */ +#define APR_STATUS_IS_ENAMETOOLONG(s) ((s) == APR_ENAMETOOLONG) +/** + * no such file or directory + * @remark + * EMVSCATLG can be returned by the automounter on z/OS for + * paths which do not exist. + */ +#ifdef EMVSCATLG +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT \ + || (s) == EMVSCATLG) +#else +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT) +#endif +/** not a directory */ +#define APR_STATUS_IS_ENOTDIR(s) ((s) == APR_ENOTDIR) +/** no space left on device */ +#ifdef EDQUOT +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC \ + || (s) == EDQUOT) +#else +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC) +#endif +/** not enough memory */ +#define APR_STATUS_IS_ENOMEM(s) ((s) == APR_ENOMEM) +/** too many open files */ +#define APR_STATUS_IS_EMFILE(s) ((s) == APR_EMFILE) +/** file table overflow */ +#define APR_STATUS_IS_ENFILE(s) ((s) == APR_ENFILE) +/** bad file # */ +#define APR_STATUS_IS_EBADF(s) ((s) == APR_EBADF) +/** invalid argument */ +#define APR_STATUS_IS_EINVAL(s) ((s) == APR_EINVAL) +/** illegal seek */ +#define APR_STATUS_IS_ESPIPE(s) ((s) == APR_ESPIPE) + +/** operation would block */ +#if !defined(EWOULDBLOCK) || !defined(EAGAIN) +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN) +#elif (EWOULDBLOCK == EAGAIN) +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN) +#else +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN \ + || (s) == EWOULDBLOCK) +#endif + +/** interrupted system call */ +#define APR_STATUS_IS_EINTR(s) ((s) == APR_EINTR) +/** socket operation on a non-socket */ +#define APR_STATUS_IS_ENOTSOCK(s) ((s) == APR_ENOTSOCK) +/** Connection Refused */ +#define APR_STATUS_IS_ECONNREFUSED(s) ((s) == APR_ECONNREFUSED) +/** operation now in progress */ +#define APR_STATUS_IS_EINPROGRESS(s) ((s) == APR_EINPROGRESS) + +/** + * Software caused connection abort + * @remark + * EPROTO on certain older kernels really means ECONNABORTED, so we need to + * ignore it for them. See discussion in new-httpd archives nh.9701 & nh.9603 + * + * There is potentially a bug in Solaris 2.x x<6, and other boxes that + * implement tcp sockets in userland (i.e. on top of STREAMS). On these + * systems, EPROTO can actually result in a fatal loop. See PR#981 for + * example. It's hard to handle both uses of EPROTO. + */ +#ifdef EPROTO +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED \ + || (s) == EPROTO) +#else +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED) +#endif + +/** Connection Reset by peer */ +#define APR_STATUS_IS_ECONNRESET(s) ((s) == APR_ECONNRESET) +/** Operation timed out + * @deprecated */ +#define APR_STATUS_IS_ETIMEDOUT(s) ((s) == APR_ETIMEDOUT) +/** no route to host */ +#define APR_STATUS_IS_EHOSTUNREACH(s) ((s) == APR_EHOSTUNREACH) +/** network is unreachable */ +#define APR_STATUS_IS_ENETUNREACH(s) ((s) == APR_ENETUNREACH) +/** inappropriate file type or format */ +#define APR_STATUS_IS_EFTYPE(s) ((s) == APR_EFTYPE) +/** broken pipe */ +#define APR_STATUS_IS_EPIPE(s) ((s) == APR_EPIPE) +/** cross device link */ +#define APR_STATUS_IS_EXDEV(s) ((s) == APR_EXDEV) +/** Directory Not Empty */ +#define APR_STATUS_IS_ENOTEMPTY(s) ((s) == APR_ENOTEMPTY || \ + (s) == APR_EEXIST) +/** Address Family not supported */ +#define APR_STATUS_IS_EAFNOSUPPORT(s) ((s) == APR_EAFNOSUPPORT) +/** Socket operation not supported */ +#define APR_STATUS_IS_EOPNOTSUPP(s) ((s) == APR_EOPNOTSUPP) + +/** Numeric value not representable */ +#define APR_STATUS_IS_ERANGE(s) ((s) == APR_ERANGE) +/** @} */ + +#endif /* !defined(NETWARE) && !defined(OS2) && !defined(WIN32) */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_ERRNO_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_escape.h b/c/dependencies/windows/apr/x64/include/apr_escape.h new file mode 100644 index 00000000..ed048c95 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_escape.h @@ -0,0 +1,431 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file apr_escape.h + * @brief APR-UTIL Escaping + */ +#ifndef APR_ESCAPE_H +#define APR_ESCAPE_H +#include "apr.h" +#include "apr_general.h" +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Escaping Escape functions + * @ingroup APR + * @{ + */ + +/* Simple escape/unescape functions. + * + * The design goal of these functions are: + * + * - Avoid unnecessary work. + * + * In most cases the strings passed in do not need to be escaped at all. In + * these cases the original string will be returned. + * + * - Lowest possible memory footprint. + * + * The amount of memory allocated for a given encoding is calculated based + * on the exact amount of memory needed, and not the theoretical worst case + * scenario. + * + */ + +/** + * When passing a string to one of the escape functions, this value can be + * passed to indicate a string-valued key, and have the length computed + * automatically. + */ +#define APR_ESCAPE_STRING (-1) + +/** + * Apply LDAP distinguished name escaping as per RFC4514. + */ +#define APR_ESCAPE_LDAP_DN (0x01) + +/** + * Apply LDAP filter escaping as per RFC4515. + */ +#define APR_ESCAPE_LDAP_FILTER (0x02) + +/** + * Apply both RFC4514 and RFC4515 LDAP escaping. + */ +#define APR_ESCAPE_LDAP_ALL (0x03) + +/** + * Perform shell escaping on the provided string. + * + * Shell escaping causes characters to be prefixed with a '\' character. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_shell(char *escaped, const char *str, + apr_ssize_t slen, apr_size_t *len); + +/** + * Perform shell escaping on the provided string, returning the result + * from the pool. + * + * Shell escaping causes characters to be prefixed with a '\' character. + * + * If no characters were escaped, the original string is returned. + * @param p Pool to allocate from + * @param str The original string + * @return the encoded string, allocated from the pool, or the original + * string if no escaping took place or the string was NULL. + */ +APR_DECLARE(const char *) apr_pescape_shell(apr_pool_t *p, const char *str) + __attribute__((nonnull(1))); + +/** + * Unescapes a URL, leaving reserved characters intact. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param url String to be unescaped + * @param slen The length of the original url, or APR_ESCAPE_STRING + * @param forbid Optional list of forbidden characters, in addition to + * 0x00 + * @param reserved Optional list of reserved characters that will be + * left unescaped + * @param plus If non zero, '+' is converted to ' ' as per + * application/x-www-form-urlencoded encoding + * @param len If set, the length of the escaped string will be returned + * @return APR_SUCCESS on success, APR_NOTFOUND if no characters are + * decoded or the string is NULL, APR_EINVAL if a bad escape sequence is + * found, APR_BADCH if a character on the forbid list is found. + */ +APR_DECLARE(apr_status_t) apr_unescape_url(char *escaped, const char *url, + apr_ssize_t slen, const char *forbid, const char *reserved, int plus, + apr_size_t *len); + +/** + * Unescapes a URL, leaving reserved characters intact, returning the + * result from a pool. + * @param p Pool to allocate from + * @param url String to be unescaped in place + * @param forbid Optional list of forbidden characters, in addition to + * 0x00 + * @param reserved Optional list of reserved characters that will be + * left unescaped + * @param plus If non zero, '+' is converted to ' ' as per + * application/x-www-form-urlencoded encoding + * @return A string allocated from the pool on success, the original string + * if no characters are decoded, or NULL if a bad escape sequence is found + * or if a character on the forbid list is found, or if the original string + * was NULL. + */ +APR_DECLARE(const char *) apr_punescape_url(apr_pool_t *p, const char *url, + const char *forbid, const char *reserved, int plus) + __attribute__((nonnull(1))); + +/** + * Escape a path segment, as defined in RFC1808. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_path_segment(char *escaped, + const char *str, apr_ssize_t slen, apr_size_t *len); + +/** + * Escape a path segment, as defined in RFC1808, returning the result from a + * pool. + * @param p Pool to allocate from + * @param str String to be escaped + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or the string is NULL. + */ +APR_DECLARE(const char *) apr_pescape_path_segment(apr_pool_t *p, + const char *str) __attribute__((nonnull(1))); + +/** + * Converts an OS path to a URL, in an OS dependent way, as defined in RFC1808. + * In all cases if a ':' occurs before the first '/' in the URL, the URL should + * be prefixed with "./" (or the ':' escaped). In the case of Unix, this means + * leaving '/' alone, but otherwise doing what escape_path_segment() does. For + * efficiency reasons, we don't use escape_path_segment(), which is provided for + * reference. Again, RFC 1808 is where this stuff is defined. + * + * If partial is set, os_escape_path() assumes that the path will be appended to + * something with a '/' in it (and thus does not prefix "./"). + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param path The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param partial If non zero, suppresses the prepending of "./" + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or if the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_path(char *escaped, const char *path, + apr_ssize_t slen, int partial, apr_size_t *len); + +/** + * Converts an OS path to a URL, in an OS dependent way, as defined in RFC1808, + * returning the result from a pool. + * + * In all cases if a ':' occurs before the first '/' in the URL, the URL should + * be prefixed with "./" (or the ':' escaped). In the case of Unix, this means + * leaving '/' alone, but otherwise doing what escape_path_segment() does. For + * efficiency reasons, we don't use escape_path_segment(), which is provided for + * reference. Again, RFC 1808 is where this stuff is defined. + * + * If partial is set, os_escape_path() assumes that the path will be appended to + * something with a '/' in it (and thus does not prefix "./"). + * @param p Pool to allocate from + * @param str The original string + * @param partial If non zero, suppresses the prepending of "./" + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or if the string was NULL. + */ +APR_DECLARE(const char *) apr_pescape_path(apr_pool_t *p, const char *str, + int partial) __attribute__((nonnull(1))); + +/** + * Urlencode a string, as defined in + * http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or if the stirng was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_urlencoded(char *escaped, const char *str, + apr_ssize_t slen, apr_size_t *len); + +/** + * Urlencode a string, as defined in + * http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1, returning + * the result from a pool. + * @param p Pool to allocate from + * @param str String to be escaped + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or if the string was NULL. + */ +APR_DECLARE(const char *) apr_pescape_urlencoded(apr_pool_t *p, + const char *str) __attribute__((nonnull(1))); + +/** + * Apply entity encoding to a string. Characters are replaced as follows: + * '<' becomes '\<', '>' becomes '\>', '&' becomes '\&', the + * double quote becomes '\"" and the single quote becomes '\''. + * + * If toasc is not zero, any non ascii character will be encoded as + * '%\#ddd;', where ddd is the decimal code of the character. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param toasc If non zero, encode non ascii characters + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_entity(char *escaped, const char *str, + apr_ssize_t slen, int toasc, apr_size_t *len); + +/** + * Apply entity encoding to a string, returning the result from a pool. + * Characters are replaced as follows: '<' becomes '\<', '>' becomes + * '\>', '&' becomes '\&', the double quote becomes '\"" and the + * single quote becomes '\''. + * @param p Pool to allocate from + * @param str The original string + * @param toasc If non zero, encode non ascii characters + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or the string is NULL. + */ +APR_DECLARE(const char *) apr_pescape_entity(apr_pool_t *p, const char *str, + int toasc) __attribute__((nonnull(1))); + +/** + * Decodes html entities or numeric character references in a string. If + * the string to be unescaped is syntactically incorrect, then the + * following fixups will be made: + * unknown entities will be left undecoded; + * references to unused numeric characters will be deleted. + * In particular, � will not be decoded, but will be deleted. + * @param unescaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_unescape_entity(char *unescaped, const char *str, + apr_ssize_t slen, apr_size_t *len); + +/** + * Decodes html entities or numeric character references in a string. If + * the string to be unescaped is syntactically incorrect, then the + * following fixups will be made: + * unknown entities will be left undecoded; + * references to unused numeric characters will be deleted. + * In particular, � will not be decoded, but will be deleted. + * @param p Pool to allocate from + * @param str The original string + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or the string is NULL. + */ +APR_DECLARE(const char *) apr_punescape_entity(apr_pool_t *p, const char *str) + __attribute__((nonnull(1))); + +/** + * Escape control characters in a string, as performed by the shell's + * 'echo' command. Characters are replaced as follows: + * \\a alert (bell), \\b backspace, \\f form feed, \\n new line, \\r carriage + * return, \\t horizontal tab, \\v vertical tab, \\ backslash. + * + * Any non ascii character will be encoded as '\\xHH', where HH is the hex + * code of the character. + * + * If quote is not zero, the double quote character will also be escaped. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param quote If non zero, encode double quotes + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_echo(char *escaped, const char *str, + apr_ssize_t slen, int quote, apr_size_t *len); + +/** + * Escape control characters in a string, as performed by the shell's + * 'echo' command, and return the results from a pool. Characters are + * replaced as follows: \\a alert (bell), \\b backspace, \\f form feed, + * \\n new line, \\r carriage return, \\t horizontal tab, \\v vertical tab, + * \\ backslash. + * + * Any non ascii character will be encoded as '\\xHH', where HH is the hex + * code of the character. + * + * If quote is not zero, the double quote character will also be escaped. + * @param p Pool to allocate from + * @param str The original string + * @param quote If non zero, encode double quotes + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or the string is NULL. + */ +APR_DECLARE(const char *) apr_pescape_echo(apr_pool_t *p, const char *str, + int quote); + +/** + * Convert binary data to a hex encoding. + * @param dest The destination buffer, can be NULL + * @param src The original buffer + * @param srclen The length of the original buffer + * @param colon If not zero, insert colon characters between hex digits. + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_hex(char *dest, const void *src, + apr_size_t srclen, int colon, apr_size_t *len); + +/** + * Convert binary data to a hex encoding, and return the results from a + * pool. + * @param p Pool to allocate from + * @param src The original buffer + * @param slen The length of the original buffer + * @param colon If not zero, insert colon characters between hex digits. + * @return A zero padded buffer allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *) apr_pescape_hex(apr_pool_t *p, const void *src, + apr_size_t slen, int colon) __attribute__((nonnull(1))); + +/** + * Convert hex encoded string to binary data. + * @param dest The destination buffer, can be NULL + * @param str The original buffer + * @param slen The length of the original buffer + * @param colon If not zero, ignore colon characters between hex digits. + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL, or APR_BADCH + * if a non hex character is present. + */ +APR_DECLARE(apr_status_t) apr_unescape_hex(void *dest, const char *str, + apr_ssize_t slen, int colon, apr_size_t *len); + +/** + * Convert hex encoding to binary data, and return the results from a pool. + * If the colon character appears between pairs of hex digits, it will be + * ignored. + * @param p Pool to allocate from + * @param str The original string + * @param colon If not zero, ignore colon characters between hex digits. + * @param len If present, returns the length of the final buffer + * @return A buffer allocated from the pool on success, or NULL if src was + * NULL, or a bad character was present. + */ +APR_DECLARE(const void *) apr_punescape_hex(apr_pool_t *p, const char *str, + int colon, apr_size_t *len); + +/** + * Apply LDAP escaping to binary data. Characters from RFC4514 and RFC4515 + * are escaped with their hex equivalents. + * @param dest The destination buffer, can be NULL + * @param src The original buffer + * @param srclen The length of the original buffer + * @param flags APR_ESCAPE_LDAP_DN for RFC4514, APR_ESCAPE_LDAP_FILTER for + * RFC4515, APR_ESCAPE_LDAP_ALL for both + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_ldap(char *dest, const void *src, + apr_ssize_t srclen, int flags, apr_size_t *len); + +/** + * Apply LDAP escaping to binary data, and return the results from a + * pool. Characters from RFC4514 and RFC4515 are escaped with their hex + * equivalents. + * @param p Pool to allocate from + * @param src The original buffer + * @param slen The length of the original buffer + * @param flags APR_ESCAPE_LDAP_DN for RFC4514, APR_ESCAPE_LDAP_FILTER for + * RFC4515, APR_ESCAPE_LDAP_ALL for both + * @return A zero padded buffer allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *) apr_pescape_ldap(apr_pool_t *p, const void *src, + apr_ssize_t slen, int flags) __attribute__((nonnull(1))); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ESCAPE_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_escape_test_char.h b/c/dependencies/windows/apr/x64/include/apr_escape_test_char.h new file mode 100644 index 00000000..ad36c615 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_escape_test_char.h @@ -0,0 +1,25 @@ +/* this file is automatically generated by gen_test_char, do not edit. "make include/private/apr_escape_test_char.h" to regenerate. */ +#define T_ESCAPE_SHELL_CMD (1) +#define T_ESCAPE_PATH_SEGMENT (2) +#define T_OS_ESCAPE_PATH (4) +#define T_ESCAPE_ECHO (8) +#define T_ESCAPE_URLENCODED (16) +#define T_ESCAPE_XML (32) +#define T_ESCAPE_LDAP_DN (64) +#define T_ESCAPE_LDAP_FILTER (128) + +static const unsigned char test_char_table[256] = { + 224,222,222,222,222,222,222,222,222,222,223,222,222,223,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,6,16,127,22,17,23,49,17, + 145,145,129,80,80,0,0,18,0,0,0,0,0,0,0,0,0,0,16,87, + 119,16,119,23,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,23,223,23,23,0,23,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,23,23,23,17,222,222,222,222,222,222,222,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222 +}; diff --git a/c/dependencies/windows/apr/x64/include/apr_file_info.h b/c/dependencies/windows/apr/x64/include/apr_file_info.h new file mode 100644 index 00000000..cfddc68d --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_file_info.h @@ -0,0 +1,428 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_FILE_INFO_H +#define APR_FILE_INFO_H + +/** + * @file apr_file_info.h + * @brief APR File Information + */ + +#include "apr.h" +#include "apr_user.h" +#include "apr_pools.h" +#include "apr_tables.h" +#include "apr_time.h" +#include "apr_errno.h" + +#if APR_HAVE_SYS_UIO_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_file_info File Information + * @ingroup APR + * @{ + */ + +/* Many applications use the type member to determine the + * existance of a file or initialization of the file info, + * so the APR_NOFILE value must be distinct from APR_UNKFILE. + */ + +/** apr_filetype_e values for the filetype member of the + * apr_file_info_t structure + * @warning Not all of the filetypes below can be determined. + * For example, a given platform might not correctly report + * a socket descriptor as APR_SOCK if that type isn't + * well-identified on that platform. In such cases where + * a filetype exists but cannot be described by the recognized + * flags below, the filetype will be APR_UNKFILE. If the + * filetype member is not determined, the type will be APR_NOFILE. + */ + +typedef enum { + APR_NOFILE = 0, /**< no file type determined */ + APR_REG, /**< a regular file */ + APR_DIR, /**< a directory */ + APR_CHR, /**< a character device */ + APR_BLK, /**< a block device */ + APR_PIPE, /**< a FIFO / pipe */ + APR_LNK, /**< a symbolic link */ + APR_SOCK, /**< a [unix domain] socket */ + APR_UNKFILE = 127 /**< a file of some other unknown type */ +} apr_filetype_e; + +/** + * @defgroup apr_file_permissions File Permissions flags + * @{ + */ + +#define APR_FPROT_USETID 0x8000 /**< Set user id */ +#define APR_FPROT_UREAD 0x0400 /**< Read by user */ +#define APR_FPROT_UWRITE 0x0200 /**< Write by user */ +#define APR_FPROT_UEXECUTE 0x0100 /**< Execute by user */ + +#define APR_FPROT_GSETID 0x4000 /**< Set group id */ +#define APR_FPROT_GREAD 0x0040 /**< Read by group */ +#define APR_FPROT_GWRITE 0x0020 /**< Write by group */ +#define APR_FPROT_GEXECUTE 0x0010 /**< Execute by group */ + +#define APR_FPROT_WSTICKY 0x2000 /**< Sticky bit */ +#define APR_FPROT_WREAD 0x0004 /**< Read by others */ +#define APR_FPROT_WWRITE 0x0002 /**< Write by others */ +#define APR_FPROT_WEXECUTE 0x0001 /**< Execute by others */ + +#define APR_FPROT_OS_DEFAULT 0x0FFF /**< use OS's default permissions */ + +/* additional permission flags for apr_file_copy and apr_file_append */ +#define APR_FPROT_FILE_SOURCE_PERMS 0x1000 /**< Copy source file's permissions */ + +/* backcompat */ +#define APR_USETID APR_FPROT_USETID /**< @deprecated @see APR_FPROT_USETID */ +#define APR_UREAD APR_FPROT_UREAD /**< @deprecated @see APR_FPROT_UREAD */ +#define APR_UWRITE APR_FPROT_UWRITE /**< @deprecated @see APR_FPROT_UWRITE */ +#define APR_UEXECUTE APR_FPROT_UEXECUTE /**< @deprecated @see APR_FPROT_UEXECUTE */ +#define APR_GSETID APR_FPROT_GSETID /**< @deprecated @see APR_FPROT_GSETID */ +#define APR_GREAD APR_FPROT_GREAD /**< @deprecated @see APR_FPROT_GREAD */ +#define APR_GWRITE APR_FPROT_GWRITE /**< @deprecated @see APR_FPROT_GWRITE */ +#define APR_GEXECUTE APR_FPROT_GEXECUTE /**< @deprecated @see APR_FPROT_GEXECUTE */ +#define APR_WSTICKY APR_FPROT_WSTICKY /**< @deprecated @see APR_FPROT_WSTICKY */ +#define APR_WREAD APR_FPROT_WREAD /**< @deprecated @see APR_FPROT_WREAD */ +#define APR_WWRITE APR_FPROT_WWRITE /**< @deprecated @see APR_FPROT_WWRITE */ +#define APR_WEXECUTE APR_FPROT_WEXECUTE /**< @deprecated @see APR_FPROT_WEXECUTE */ +#define APR_OS_DEFAULT APR_FPROT_OS_DEFAULT /**< @deprecated @see APR_FPROT_OS_DEFAULT */ +#define APR_FILE_SOURCE_PERMS APR_FPROT_FILE_SOURCE_PERMS /**< @deprecated @see APR_FPROT_FILE_SOURCE_PERMS */ + +/** @} */ + + +/** + * Structure for referencing directories. + */ +typedef struct apr_dir_t apr_dir_t; +/** + * Structure for determining file permissions. + */ +typedef apr_int32_t apr_fileperms_t; +#if (defined WIN32) || (defined NETWARE) +/** + * Structure for determining the device the file is on. + */ +typedef apr_uint32_t apr_dev_t; +#else +/** + * Structure for determining the device the file is on. + */ +typedef dev_t apr_dev_t; +#endif + +/** + * @defgroup apr_file_stat Stat Functions + * @{ + */ +/** file info structure */ +typedef struct apr_finfo_t apr_finfo_t; + +#define APR_FINFO_LINK 0x00000001 /**< Stat the link not the file itself if it is a link */ +#define APR_FINFO_MTIME 0x00000010 /**< Modification Time */ +#define APR_FINFO_CTIME 0x00000020 /**< Creation or inode-changed time */ +#define APR_FINFO_ATIME 0x00000040 /**< Access Time */ +#define APR_FINFO_SIZE 0x00000100 /**< Size of the file */ +#define APR_FINFO_CSIZE 0x00000200 /**< Storage size consumed by the file */ +#define APR_FINFO_DEV 0x00001000 /**< Device */ +#define APR_FINFO_INODE 0x00002000 /**< Inode */ +#define APR_FINFO_NLINK 0x00004000 /**< Number of links */ +#define APR_FINFO_TYPE 0x00008000 /**< Type */ +#define APR_FINFO_USER 0x00010000 /**< User */ +#define APR_FINFO_GROUP 0x00020000 /**< Group */ +#define APR_FINFO_UPROT 0x00100000 /**< User protection bits */ +#define APR_FINFO_GPROT 0x00200000 /**< Group protection bits */ +#define APR_FINFO_WPROT 0x00400000 /**< World protection bits */ +#define APR_FINFO_ICASE 0x01000000 /**< if dev is case insensitive */ +#define APR_FINFO_NAME 0x02000000 /**< ->name in proper case */ + +#define APR_FINFO_MIN 0x00008170 /**< type, mtime, ctime, atime, size */ +#define APR_FINFO_IDENT 0x00003000 /**< dev and inode */ +#define APR_FINFO_OWNER 0x00030000 /**< user and group */ +#define APR_FINFO_PROT 0x00700000 /**< all protections */ +#define APR_FINFO_NORM 0x0073b170 /**< an atomic unix apr_stat() */ +#define APR_FINFO_DIRENT 0x02000000 /**< an atomic unix apr_dir_read() */ + +/** + * The file information structure. This is analogous to the POSIX + * stat structure. + */ +struct apr_finfo_t { + /** Allocates memory and closes lingering handles in the specified pool */ + apr_pool_t *pool; + /** The bitmask describing valid fields of this apr_finfo_t structure + * including all available 'wanted' fields and potentially more */ + apr_int32_t valid; + /** The access permissions of the file. Mimics Unix access rights. */ + apr_fileperms_t protection; + /** The type of file. One of APR_REG, APR_DIR, APR_CHR, APR_BLK, APR_PIPE, + * APR_LNK or APR_SOCK. If the type is undetermined, the value is APR_NOFILE. + * If the type cannot be determined, the value is APR_UNKFILE. + */ + apr_filetype_e filetype; + /** The user id that owns the file */ + apr_uid_t user; + /** The group id that owns the file */ + apr_gid_t group; + /** The inode of the file. */ + apr_ino_t inode; + /** The id of the device the file is on. */ + apr_dev_t device; + /** The number of hard links to the file. */ + apr_int32_t nlink; + /** The size of the file */ + apr_off_t size; + /** The storage size consumed by the file */ + apr_off_t csize; + /** The time the file was last accessed */ + apr_time_t atime; + /** The time the file was last modified */ + apr_time_t mtime; + /** The time the file was created, or the inode was last changed */ + apr_time_t ctime; + /** The pathname of the file (possibly unrooted) */ + const char *fname; + /** The file's name (no path) in filesystem case */ + const char *name; + /** Unused */ + struct apr_file_t *filehand; +}; + +/** + * get the specified file's stats. The file is specified by filename, + * instead of using a pre-opened file. + * @param finfo Where to store the information about the file, which is + * never touched if the call fails. + * @param fname The name of the file to stat. + * @param wanted The desired apr_finfo_t fields, as a bit flag of APR_FINFO_ + values + * @param pool the pool to use to allocate the new file. + * + * @note If @c APR_INCOMPLETE is returned all the fields in @a finfo may + * not be filled in, and you need to check the @c finfo->valid bitmask + * to verify that what you're looking for is there. + */ +APR_DECLARE(apr_status_t) apr_stat(apr_finfo_t *finfo, const char *fname, + apr_int32_t wanted, apr_pool_t *pool); + +/** @} */ +/** + * @defgroup apr_dir Directory Manipulation Functions + * @{ + */ + +/** + * Open the specified directory. + * @param new_dir The opened directory descriptor. + * @param dirname The full path to the directory (use / on all systems) + * @param pool The pool to use. + */ +APR_DECLARE(apr_status_t) apr_dir_open(apr_dir_t **new_dir, + const char *dirname, + apr_pool_t *pool); + +/** + * close the specified directory. + * @param thedir the directory descriptor to close. + */ +APR_DECLARE(apr_status_t) apr_dir_close(apr_dir_t *thedir); + +/** + * Read the next entry from the specified directory. + * @param finfo the file info structure and filled in by apr_dir_read + * @param wanted The desired apr_finfo_t fields, as a bit flag of APR_FINFO_ + values + * @param thedir the directory descriptor returned from apr_dir_open + * @remark No ordering is guaranteed for the entries read. + * + * @note If @c APR_INCOMPLETE is returned all the fields in @a finfo may + * not be filled in, and you need to check the @c finfo->valid bitmask + * to verify that what you're looking for is there. When no more + * entries are available, APR_ENOENT is returned. + */ +APR_DECLARE(apr_status_t) apr_dir_read(apr_finfo_t *finfo, apr_int32_t wanted, + apr_dir_t *thedir); + +/** + * Rewind the directory to the first entry. + * @param thedir the directory descriptor to rewind. + */ +APR_DECLARE(apr_status_t) apr_dir_rewind(apr_dir_t *thedir); +/** @} */ + +/** + * @defgroup apr_filepath Filepath Manipulation Functions + * @{ + */ + +/** Cause apr_filepath_merge to fail if addpath is above rootpath + * @bug in APR 0.9 and 1.x, this flag's behavior is undefined + * if the rootpath is NULL or empty. In APR 2.0 this should be + * changed to imply NOTABSOLUTE if the rootpath is NULL or empty. + */ +#define APR_FILEPATH_NOTABOVEROOT 0x01 + +/** internal: Only meaningful with APR_FILEPATH_NOTABOVEROOT */ +#define APR_FILEPATH_SECUREROOTTEST 0x02 + +/** Cause apr_filepath_merge to fail if addpath is above rootpath, + * even given a rootpath /foo/bar and an addpath ../bar/bash + */ +#define APR_FILEPATH_SECUREROOT 0x03 + +/** Fail apr_filepath_merge if the merged path is relative */ +#define APR_FILEPATH_NOTRELATIVE 0x04 + +/** Fail apr_filepath_merge if the merged path is absolute */ +#define APR_FILEPATH_NOTABSOLUTE 0x08 + +/** Return the file system's native path format (e.g. path delimiters + * of ':' on MacOS9, '\' on Win32, etc.) */ +#define APR_FILEPATH_NATIVE 0x10 + +/** Resolve the true case of existing directories and file elements + * of addpath, (resolving any aliases on Win32) and append a proper + * trailing slash if a directory + */ +#define APR_FILEPATH_TRUENAME 0x20 + +/** + * Extract the rootpath from the given filepath + * @param rootpath the root file path returned with APR_SUCCESS or APR_EINCOMPLETE + * @param filepath the pathname to parse for its root component + * @param flags the desired rules to apply, from + *
+ *      APR_FILEPATH_NATIVE    Use native path separators (e.g. '\' on Win32)
+ *      APR_FILEPATH_TRUENAME  Tests that the root exists, and makes it proper
+ * 
+ * @param p the pool to allocate the new path string from + * @remark on return, filepath points to the first non-root character in the + * given filepath. In the simplest example, given a filepath of "/foo", + * returns the rootpath of "/" and filepath points at "foo". This is far + * more complex on other platforms, which will canonicalize the root form + * to a consistant format, given the APR_FILEPATH_TRUENAME flag, and also + * test for the validity of that root (e.g., that a drive d:/ or network + * share //machine/foovol/). + * The function returns APR_ERELATIVE if filepath isn't rooted (an + * error), APR_EINCOMPLETE if the root path is ambiguous (but potentially + * legitimate, e.g. "/" on Windows is incomplete because it doesn't specify + * the drive letter), or APR_EBADPATH if the root is simply invalid. + * APR_SUCCESS is returned if filepath is an absolute path. + */ +APR_DECLARE(apr_status_t) apr_filepath_root(const char **rootpath, + const char **filepath, + apr_int32_t flags, + apr_pool_t *p); + +/** + * Merge additional file path onto the previously processed rootpath + * @param newpath the merged paths returned + * @param rootpath the root file path (NULL uses the current working path) + * @param addpath the path to add to the root path + * @param flags the desired APR_FILEPATH_ rules to apply when merging + * @param p the pool to allocate the new path string from + * @remark if the flag APR_FILEPATH_TRUENAME is given, and the addpath + * contains wildcard characters ('*', '?') on platforms that don't support + * such characters within filenames, the paths will be merged, but the + * result code will be APR_EPATHWILD, and all further segments will not + * reflect the true filenames including the wildcard and following segments. + */ +APR_DECLARE(apr_status_t) apr_filepath_merge(char **newpath, + const char *rootpath, + const char *addpath, + apr_int32_t flags, + apr_pool_t *p); + +/** + * Split a search path into separate components + * @param pathelts the returned components of the search path + * @param liststr the search path (e.g., getenv("PATH")) + * @param p the pool to allocate the array and path components from + * @remark empty path components do not become part of @a pathelts. + * @remark the path separator in @a liststr is system specific; + * e.g., ':' on Unix, ';' on Windows, etc. + */ +APR_DECLARE(apr_status_t) apr_filepath_list_split(apr_array_header_t **pathelts, + const char *liststr, + apr_pool_t *p); + +/** + * Merge a list of search path components into a single search path + * @param liststr the returned search path; may be NULL if @a pathelts is empty + * @param pathelts the components of the search path + * @param p the pool to allocate the search path from + * @remark emtpy strings in the source array are ignored. + * @remark the path separator in @a liststr is system specific; + * e.g., ':' on Unix, ';' on Windows, etc. + */ +APR_DECLARE(apr_status_t) apr_filepath_list_merge(char **liststr, + apr_array_header_t *pathelts, + apr_pool_t *p); + +/** + * Return the default file path (for relative file names) + * @param path the default path string returned + * @param flags optional flag APR_FILEPATH_NATIVE to retrieve the + * default file path in os-native format. + * @param p the pool to allocate the default path string from + */ +APR_DECLARE(apr_status_t) apr_filepath_get(char **path, apr_int32_t flags, + apr_pool_t *p); + +/** + * Set the default file path (for relative file names) + * @param path the default path returned + * @param p the pool to allocate any working storage + */ +APR_DECLARE(apr_status_t) apr_filepath_set(const char *path, apr_pool_t *p); + +/** The FilePath character encoding is unknown */ +#define APR_FILEPATH_ENCODING_UNKNOWN 0 + +/** The FilePath character encoding is locale-dependent */ +#define APR_FILEPATH_ENCODING_LOCALE 1 + +/** The FilePath character encoding is UTF-8 */ +#define APR_FILEPATH_ENCODING_UTF8 2 + +/** + * Determine the encoding used internally by the FilePath functions + * @param style points to a variable which receives the encoding style flag + * @param p the pool to allocate any working storage + * @remark Use apr_os_locale_encoding() and/or apr_os_default_encoding() + * to get the name of the path encoding if it's not UTF-8. + */ +APR_DECLARE(apr_status_t) apr_filepath_encoding(int *style, apr_pool_t *p); +/** @} */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_FILE_INFO_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_file_io.h b/c/dependencies/windows/apr/x64/include/apr_file_io.h new file mode 100644 index 00000000..af931939 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_file_io.h @@ -0,0 +1,1005 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_FILE_IO_H +#define APR_FILE_IO_H + +/** + * @file apr_file_io.h + * @brief APR File I/O Handling + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_time.h" +#include "apr_errno.h" +#include "apr_file_info.h" +#include "apr_inherit.h" + +#define APR_WANT_STDIO /**< for SEEK_* */ +#define APR_WANT_IOVEC /**< for apr_file_writev */ +#include "apr_want.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_file_io File I/O Handling Functions + * @ingroup APR + * @{ + */ + +/** + * @defgroup apr_file_open_flags File Open Flags/Routines + * @{ + */ + +/* Note to implementors: Values in the range 0x00100000--0x80000000 + are reserved for platform-specific values. */ + +#define APR_FOPEN_READ 0x00001 /**< Open the file for reading */ +#define APR_FOPEN_WRITE 0x00002 /**< Open the file for writing */ +#define APR_FOPEN_CREATE 0x00004 /**< Create the file if not there */ +#define APR_FOPEN_APPEND 0x00008 /**< Append to the end of the file */ +#define APR_FOPEN_TRUNCATE 0x00010 /**< Open the file and truncate + to 0 length */ +#define APR_FOPEN_BINARY 0x00020 /**< Open the file in binary mode + (This flag is ignored on UNIX + because it has no meaning)*/ +#define APR_FOPEN_EXCL 0x00040 /**< Open should fail if #APR_FOPEN_CREATE + and file exists. */ +#define APR_FOPEN_BUFFERED 0x00080 /**< Open the file for buffered I/O */ +#define APR_FOPEN_DELONCLOSE 0x00100 /**< Delete the file after close */ +#define APR_FOPEN_XTHREAD 0x00200 /**< Platform dependent tag to open + the file for use across multiple + threads */ +#define APR_FOPEN_SHARELOCK 0x00400 /**< Platform dependent support for + higher level locked read/write + access to support writes across + process/machines */ +#define APR_FOPEN_NOCLEANUP 0x00800 /**< Do not register a cleanup + when the file is opened. The + apr_os_file_t handle in apr_file_t + will not be closed when the pool + is destroyed. */ +#define APR_FOPEN_SENDFILE_ENABLED 0x01000 /**< Advisory flag that this + file should support + apr_socket_sendfile operation */ +#define APR_FOPEN_LARGEFILE 0x04000 /**< Platform dependent flag to enable + * large file support, see WARNING below + */ +#define APR_FOPEN_SPARSE 0x08000 /**< Platform dependent flag to enable + * sparse file support, see WARNING below + */ +#define APR_FOPEN_NONBLOCK 0x40000 /**< Platform dependent flag to enable + * non blocking file io */ + + +/* backcompat */ +#define APR_READ APR_FOPEN_READ /**< @deprecated @see APR_FOPEN_READ */ +#define APR_WRITE APR_FOPEN_WRITE /**< @deprecated @see APR_FOPEN_WRITE */ +#define APR_CREATE APR_FOPEN_CREATE /**< @deprecated @see APR_FOPEN_CREATE */ +#define APR_APPEND APR_FOPEN_APPEND /**< @deprecated @see APR_FOPEN_APPEND */ +#define APR_TRUNCATE APR_FOPEN_TRUNCATE /**< @deprecated @see APR_FOPEN_TRUNCATE */ +#define APR_BINARY APR_FOPEN_BINARY /**< @deprecated @see APR_FOPEN_BINARY */ +#define APR_EXCL APR_FOPEN_EXCL /**< @deprecated @see APR_FOPEN_EXCL */ +#define APR_BUFFERED APR_FOPEN_BUFFERED /**< @deprecated @see APR_FOPEN_BUFFERED */ +#define APR_DELONCLOSE APR_FOPEN_DELONCLOSE /**< @deprecated @see APR_FOPEN_DELONCLOSE */ +#define APR_XTHREAD APR_FOPEN_XTHREAD /**< @deprecated @see APR_FOPEN_XTHREAD */ +#define APR_SHARELOCK APR_FOPEN_SHARELOCK /**< @deprecated @see APR_FOPEN_SHARELOCK */ +#define APR_FILE_NOCLEANUP APR_FOPEN_NOCLEANUP /**< @deprecated @see APR_FOPEN_NOCLEANUP */ +#define APR_SENDFILE_ENABLED APR_FOPEN_SENDFILE_ENABLED /**< @deprecated @see APR_FOPEN_SENDFILE_ENABLED */ +#define APR_LARGEFILE APR_FOPEN_LARGEFILE /**< @deprecated @see APR_FOPEN_LARGEFILE */ + +/** @def APR_FOPEN_LARGEFILE + * @warning APR_FOPEN_LARGEFILE flag only has effect on some + * platforms where sizeof(apr_off_t) == 4. Where implemented, it + * allows opening and writing to a file which exceeds the size which + * can be represented by apr_off_t (2 gigabytes). When a file's size + * does exceed 2Gb, apr_file_info_get() will fail with an error on the + * descriptor, likewise apr_stat()/apr_lstat() will fail on the + * filename. apr_dir_read() will fail with #APR_INCOMPLETE on a + * directory entry for a large file depending on the particular + * APR_FINFO_* flags. Generally, it is not recommended to use this + * flag. + * + * @def APR_FOPEN_SPARSE + * @warning APR_FOPEN_SPARSE may, depending on platform, convert a + * normal file to a sparse file. Some applications may be unable + * to decipher a sparse file, so it's critical that the sparse file + * flag should only be used for files accessed only by APR or other + * applications known to be able to decipher them. APR does not + * guarantee that it will compress the file into sparse segments + * if it was previously created and written without the sparse flag. + * On platforms which do not understand, or on file systems which + * cannot handle sparse files, the flag is ignored by apr_file_open(). + * + * @def APR_FOPEN_NONBLOCK + * @warning APR_FOPEN_NONBLOCK is not implemented on all platforms. + * Callers should be prepared for it to fail with #APR_ENOTIMPL. + */ + +/** @} */ + +/** + * @defgroup apr_file_seek_flags File Seek Flags + * @{ + */ + +/* flags for apr_file_seek */ +/** Set the file position */ +#define APR_SET SEEK_SET +/** Current */ +#define APR_CUR SEEK_CUR +/** Go to end of file */ +#define APR_END SEEK_END +/** @} */ + +/** + * @defgroup apr_file_attrs_set_flags File Attribute Flags + * @{ + */ + +/* flags for apr_file_attrs_set */ +#define APR_FILE_ATTR_READONLY 0x01 /**< File is read-only */ +#define APR_FILE_ATTR_EXECUTABLE 0x02 /**< File is executable */ +#define APR_FILE_ATTR_HIDDEN 0x04 /**< File is hidden */ +/** @} */ + +/** + * @defgroup apr_file_writev{_full} max iovec size + * @{ + */ +#if defined(DOXYGEN) +#define APR_MAX_IOVEC_SIZE 1024 /**< System dependent maximum + size of an iovec array */ +#elif defined(IOV_MAX) +#define APR_MAX_IOVEC_SIZE IOV_MAX +#elif defined(MAX_IOVEC) +#define APR_MAX_IOVEC_SIZE MAX_IOVEC +#else +#define APR_MAX_IOVEC_SIZE 1024 +#endif +/** @} */ + +/** File attributes */ +typedef apr_uint32_t apr_fileattrs_t; + +/** Type to pass as whence argument to apr_file_seek. */ +typedef int apr_seek_where_t; + +/** + * Structure for referencing files. + */ +typedef struct apr_file_t apr_file_t; + +/* File lock types/flags */ +/** + * @defgroup apr_file_lock_types File Lock Types + * @{ + */ + +#define APR_FLOCK_SHARED 1 /**< Shared lock. More than one process + or thread can hold a shared lock + at any given time. Essentially, + this is a "read lock", preventing + writers from establishing an + exclusive lock. */ +#define APR_FLOCK_EXCLUSIVE 2 /**< Exclusive lock. Only one process + may hold an exclusive lock at any + given time. This is analogous to + a "write lock". */ + +#define APR_FLOCK_TYPEMASK 0x000F /**< mask to extract lock type */ +#define APR_FLOCK_NONBLOCK 0x0010 /**< do not block while acquiring the + file lock */ +/** @} */ + +/** + * Open the specified file. + * @param newf The opened file descriptor. + * @param fname The full path to the file (using / on all systems) + * @param flag Or'ed value of: + * @li #APR_FOPEN_READ open for reading + * @li #APR_FOPEN_WRITE open for writing + * @li #APR_FOPEN_CREATE create the file if not there + * @li #APR_FOPEN_APPEND file ptr is set to end prior to all writes + * @li #APR_FOPEN_TRUNCATE set length to zero if file exists + * @li #APR_FOPEN_BINARY not a text file + * @li #APR_FOPEN_BUFFERED buffer the data. Default is non-buffered + * @li #APR_FOPEN_EXCL return error if #APR_FOPEN_CREATE and file exists + * @li #APR_FOPEN_DELONCLOSE delete the file after closing + * @li #APR_FOPEN_XTHREAD Platform dependent tag to open the file + * for use across multiple threads + * @li #APR_FOPEN_SHARELOCK Platform dependent support for higher + * level locked read/write access to support + * writes across process/machines + * @li #APR_FOPEN_NOCLEANUP Do not register a cleanup with the pool + * passed in on the @a pool argument (see below) + * @li #APR_FOPEN_SENDFILE_ENABLED Open with appropriate platform semantics + * for sendfile operations. Advisory only, + * apr_socket_sendfile does not check this flag + * @li #APR_FOPEN_LARGEFILE Platform dependent flag to enable large file + * support, see WARNING below + * @li #APR_FOPEN_SPARSE Platform dependent flag to enable sparse file + * support, see WARNING below + * @li #APR_FOPEN_NONBLOCK Platform dependent flag to enable + * non blocking file io + * @param perm Access permissions for file. + * @param pool The pool to use. + * @remark If perm is #APR_FPROT_OS_DEFAULT and the file is being created, + * appropriate default permissions will be used. + * @remark By default, the returned file descriptor will not be + * inherited by child processes created by apr_proc_create(). This + * can be changed using apr_file_inherit_set(). + */ +APR_DECLARE(apr_status_t) apr_file_open(apr_file_t **newf, const char *fname, + apr_int32_t flag, apr_fileperms_t perm, + apr_pool_t *pool); + +/** + * Close the specified file. + * @param file The file descriptor to close. + */ +APR_DECLARE(apr_status_t) apr_file_close(apr_file_t *file); + +/** + * Delete the specified file. + * @param path The full path to the file (using / on all systems) + * @param pool The pool to use. + * @remark If the file is open, it won't be removed until all + * instances are closed. + */ +APR_DECLARE(apr_status_t) apr_file_remove(const char *path, apr_pool_t *pool); + +/** + * Rename the specified file. + * @param from_path The full path to the original file (using / on all systems) + * @param to_path The full path to the new file (using / on all systems) + * @param pool The pool to use. + * @warning If a file exists at the new location, then it will be + * overwritten. Moving files or directories across devices may not be + * possible. + */ +APR_DECLARE(apr_status_t) apr_file_rename(const char *from_path, + const char *to_path, + apr_pool_t *pool); + +/** + * Create a hard link to the specified file. + * @param from_path The full path to the original file (using / on all systems) + * @param to_path The full path to the new file (using / on all systems) + * @remark Both files must reside on the same device. + */ +APR_DECLARE(apr_status_t) apr_file_link(const char *from_path, + const char *to_path); + +/** + * Copy the specified file to another file. + * @param from_path The full path to the original file (using / on all systems) + * @param to_path The full path to the new file (using / on all systems) + * @param perms Access permissions for the new file if it is created. + * In place of the usual or'd combination of file permissions, the + * value #APR_FPROT_FILE_SOURCE_PERMS may be given, in which case the source + * file's permissions are copied. + * @param pool The pool to use. + * @remark The new file does not need to exist, it will be created if required. + * @warning If the new file already exists, its contents will be overwritten. + */ +APR_DECLARE(apr_status_t) apr_file_copy(const char *from_path, + const char *to_path, + apr_fileperms_t perms, + apr_pool_t *pool); + +/** + * Append the specified file to another file. + * @param from_path The full path to the source file (use / on all systems) + * @param to_path The full path to the destination file (use / on all systems) + * @param perms Access permissions for the destination file if it is created. + * In place of the usual or'd combination of file permissions, the + * value #APR_FPROT_FILE_SOURCE_PERMS may be given, in which case the source + * file's permissions are copied. + * @param pool The pool to use. + * @remark The new file does not need to exist, it will be created if required. + * @remark Note that advanced filesystem permissions such as ACLs are not + * duplicated by this API. The target permissions (including duplicating the + * source file permissions) are assigned only when the target file does not yet + * exist. + */ +APR_DECLARE(apr_status_t) apr_file_append(const char *from_path, + const char *to_path, + apr_fileperms_t perms, + apr_pool_t *pool); + +/** + * Are we at the end of the file + * @param fptr The apr file we are testing. + * @remark Returns #APR_EOF if we are at the end of file, #APR_SUCCESS otherwise. + */ +APR_DECLARE(apr_status_t) apr_file_eof(apr_file_t *fptr); + +/** + * Open standard error as an apr file pointer. + * @param thefile The apr file to use as stderr. + * @param pool The pool to allocate the file out of. + * + * @remark The only reason that the apr_file_open_std* functions exist + * is that you may not always have a stderr/out/in on Windows. This + * is generally a problem with newer versions of Windows and services. + * + * @remark The other problem is that the C library functions generally work + * differently on Windows and Unix. So, by using apr_file_open_std* + * functions, you can get a handle to an APR struct that works with + * the APR functions which are supposed to work identically on all + * platforms. + */ +APR_DECLARE(apr_status_t) apr_file_open_stderr(apr_file_t **thefile, + apr_pool_t *pool); + +/** + * open standard output as an apr file pointer. + * @param thefile The apr file to use as stdout. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_stdout(apr_file_t **thefile, + apr_pool_t *pool); + +/** + * open standard input as an apr file pointer. + * @param thefile The apr file to use as stdin. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_stdin(apr_file_t **thefile, + apr_pool_t *pool); + +/** + * open standard error as an apr file pointer, with flags. + * @param thefile The apr file to use as stderr. + * @param flags The flags to open the file with. Only the + * @li #APR_FOPEN_EXCL + * @li #APR_FOPEN_BUFFERED + * @li #APR_FOPEN_XTHREAD + * @li #APR_FOPEN_SHARELOCK + * @li #APR_FOPEN_SENDFILE_ENABLED + * @li #APR_FOPEN_LARGEFILE + * + * flags should be used. The #APR_FOPEN_WRITE flag will + * be set unconditionally. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_flags_stderr(apr_file_t **thefile, + apr_int32_t flags, + apr_pool_t *pool); + +/** + * open standard output as an apr file pointer, with flags. + * @param thefile The apr file to use as stdout. + * @param flags The flags to open the file with. Only the + * @li #APR_FOPEN_EXCL + * @li #APR_FOPEN_BUFFERED + * @li #APR_FOPEN_XTHREAD + * @li #APR_FOPEN_SHARELOCK + * @li #APR_FOPEN_SENDFILE_ENABLED + * @li #APR_FOPEN_LARGEFILE + * + * flags should be used. The #APR_FOPEN_WRITE flag will + * be set unconditionally. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_flags_stdout(apr_file_t **thefile, + apr_int32_t flags, + apr_pool_t *pool); + +/** + * open standard input as an apr file pointer, with flags. + * @param thefile The apr file to use as stdin. + * @param flags The flags to open the file with. Only the + * @li #APR_FOPEN_EXCL + * @li #APR_FOPEN_BUFFERED + * @li #APR_FOPEN_XTHREAD + * @li #APR_FOPEN_SHARELOCK + * @li #APR_FOPEN_SENDFILE_ENABLED + * @li #APR_FOPEN_LARGEFILE + * + * flags should be used. The #APR_FOPEN_WRITE flag will + * be set unconditionally. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_flags_stdin(apr_file_t **thefile, + apr_int32_t flags, + apr_pool_t *pool); + +/** + * Read data from the specified file. + * @param thefile The file descriptor to read from. + * @param buf The buffer to store the data to. + * @param nbytes On entry, the number of bytes to read; on exit, the number + * of bytes read. + * + * @remark apr_file_read() will read up to the specified number of + * bytes, but never more. If there isn't enough data to fill that + * number of bytes, all of the available data is read. The third + * argument is modified to reflect the number of bytes read. If a + * char was put back into the stream via ungetc, it will be the first + * character returned. + * + * @remark It is not possible for both bytes to be read and an #APR_EOF + * or other error to be returned. #APR_EINTR is never returned. + */ +APR_DECLARE(apr_status_t) apr_file_read(apr_file_t *thefile, void *buf, + apr_size_t *nbytes); + +/** + * Write data to the specified file. + * @param thefile The file descriptor to write to. + * @param buf The buffer which contains the data. + * @param nbytes On entry, the number of bytes to write; on exit, the number + * of bytes written. + * + * @remark apr_file_write() will write up to the specified number of + * bytes, but never more. If the OS cannot write that many bytes, it + * will write as many as it can. The third argument is modified to + * reflect the * number of bytes written. + * + * @remark It is possible for both bytes to be written and an error to + * be returned. #APR_EINTR is never returned. + */ +APR_DECLARE(apr_status_t) apr_file_write(apr_file_t *thefile, const void *buf, + apr_size_t *nbytes); + +/** + * Write data from iovec array to the specified file. + * @param thefile The file descriptor to write to. + * @param vec The array from which to get the data to write to the file. + * @param nvec The number of elements in the struct iovec array. This must + * be smaller than #APR_MAX_IOVEC_SIZE. If it isn't, the function + * will fail with #APR_EINVAL. + * @param nbytes The number of bytes written. + * + * @remark It is possible for both bytes to be written and an error to + * be returned. #APR_EINTR is never returned. + * + * @remark apr_file_writev() is available even if the underlying + * operating system doesn't provide writev(). + */ +APR_DECLARE(apr_status_t) apr_file_writev(apr_file_t *thefile, + const struct iovec *vec, + apr_size_t nvec, apr_size_t *nbytes); + +/** + * Read data from the specified file, ensuring that the buffer is filled + * before returning. + * @param thefile The file descriptor to read from. + * @param buf The buffer to store the data to. + * @param nbytes The number of bytes to read. + * @param bytes_read If non-NULL, this will contain the number of bytes read. + * + * @remark apr_file_read_full() will read up to the specified number of + * bytes, but never more. If there isn't enough data to fill that + * number of bytes, then the process/thread will block until it is + * available or EOF is reached. If a char was put back into the + * stream via ungetc, it will be the first character returned. + * + * @remark It is possible for both bytes to be read and an error to be + * returned. And if *bytes_read is less than nbytes, an accompanying + * error is _always_ returned. + * + * @remark #APR_EINTR is never returned. + */ +APR_DECLARE(apr_status_t) apr_file_read_full(apr_file_t *thefile, void *buf, + apr_size_t nbytes, + apr_size_t *bytes_read); + +/** + * Write data to the specified file, ensuring that all of the data is + * written before returning. + * @param thefile The file descriptor to write to. + * @param buf The buffer which contains the data. + * @param nbytes The number of bytes to write. + * @param bytes_written If non-NULL, set to the number of bytes written. + * + * @remark apr_file_write_full() will write up to the specified number of + * bytes, but never more. If the OS cannot write that many bytes, the + * process/thread will block until they can be written. Exceptional + * error such as "out of space" or "pipe closed" will terminate with + * an error. + * + * @remark It is possible for both bytes to be written and an error to + * be returned. And if *bytes_written is less than nbytes, an + * accompanying error is _always_ returned. + * + * @remark #APR_EINTR is never returned. + */ +APR_DECLARE(apr_status_t) apr_file_write_full(apr_file_t *thefile, + const void *buf, + apr_size_t nbytes, + apr_size_t *bytes_written); + + +/** + * Write data from iovec array to the specified file, ensuring that all of the + * data is written before returning. + * @param thefile The file descriptor to write to. + * @param vec The array from which to get the data to write to the file. + * @param nvec The number of elements in the struct iovec array. This must + * be smaller than #APR_MAX_IOVEC_SIZE. If it isn't, the function + * will fail with #APR_EINVAL. + * @param nbytes The number of bytes written. + * + * @remark apr_file_writev_full() is available even if the underlying + * operating system doesn't provide writev(). + */ +APR_DECLARE(apr_status_t) apr_file_writev_full(apr_file_t *thefile, + const struct iovec *vec, + apr_size_t nvec, + apr_size_t *nbytes); +/** + * Write a character into the specified file. + * @param ch The character to write. + * @param thefile The file descriptor to write to + */ +APR_DECLARE(apr_status_t) apr_file_putc(char ch, apr_file_t *thefile); + +/** + * Read a character from the specified file. + * @param ch The character to read into + * @param thefile The file descriptor to read from + */ +APR_DECLARE(apr_status_t) apr_file_getc(char *ch, apr_file_t *thefile); + +/** + * Put a character back onto a specified stream. + * @param ch The character to write. + * @param thefile The file descriptor to write to + */ +APR_DECLARE(apr_status_t) apr_file_ungetc(char ch, apr_file_t *thefile); + +/** + * Read a line from the specified file + * @param str The buffer to store the string in. + * @param len The length of the string + * @param thefile The file descriptor to read from + * @remark The buffer will be NUL-terminated if any characters are stored. + * The newline at the end of the line will not be stripped. + */ +APR_DECLARE(apr_status_t) apr_file_gets(char *str, int len, + apr_file_t *thefile); + +/** + * Write the string into the specified file. + * @param str The string to write. + * @param thefile The file descriptor to write to + */ +APR_DECLARE(apr_status_t) apr_file_puts(const char *str, apr_file_t *thefile); + +/** + * Flush the file's buffer. + * @param thefile The file descriptor to flush + */ +APR_DECLARE(apr_status_t) apr_file_flush(apr_file_t *thefile); + +/** + * Transfer all file modified data and metadata to disk. + * @param thefile The file descriptor to sync + */ +APR_DECLARE(apr_status_t) apr_file_sync(apr_file_t *thefile); + +/** + * Transfer all file modified data to disk. + * @param thefile The file descriptor to sync + */ +APR_DECLARE(apr_status_t) apr_file_datasync(apr_file_t *thefile); + +/** + * Duplicate the specified file descriptor. + * @param new_file The structure to duplicate into. + * @param old_file The file to duplicate. + * @param p The pool to use for the new file. + * @remark *new_file must point to a valid apr_file_t, or point to NULL. + */ +APR_DECLARE(apr_status_t) apr_file_dup(apr_file_t **new_file, + apr_file_t *old_file, + apr_pool_t *p); + +/** + * Duplicate the specified file descriptor and close the original + * @param new_file The old file that is to be closed and reused + * @param old_file The file to duplicate + * @param p The pool to use for the new file + * + * @remark new_file MUST point at a valid apr_file_t. It cannot be NULL. + */ +APR_DECLARE(apr_status_t) apr_file_dup2(apr_file_t *new_file, + apr_file_t *old_file, + apr_pool_t *p); + +/** + * Move the specified file descriptor to a new pool + * @param new_file Pointer in which to return the new apr_file_t + * @param old_file The file to move + * @param p The pool to which the descriptor is to be moved + * @remark Unlike apr_file_dup2(), this function doesn't do an + * OS dup() operation on the underlying descriptor; it just + * moves the descriptor's apr_file_t wrapper to a new pool. + * @remark The new pool need not be an ancestor of old_file's pool. + * @remark After calling this function, old_file may not be used + */ +APR_DECLARE(apr_status_t) apr_file_setaside(apr_file_t **new_file, + apr_file_t *old_file, + apr_pool_t *p); + +/** + * Give the specified apr file handle a new buffer + * @param thefile The file handle that is to be modified + * @param buffer The buffer + * @param bufsize The size of the buffer + * @remark It is possible to add a buffer to previously unbuffered + * file handles, the #APR_FOPEN_BUFFERED flag will be added to + * the file handle's flags. Likewise, with buffer=NULL and + * bufsize=0 arguments it is possible to make a previously + * buffered file handle unbuffered. + */ +APR_DECLARE(apr_status_t) apr_file_buffer_set(apr_file_t *thefile, + char * buffer, + apr_size_t bufsize); + +/** + * Get the size of any buffer for the specified apr file handle + * @param thefile The file handle + */ +APR_DECLARE(apr_size_t) apr_file_buffer_size_get(apr_file_t *thefile); + +/** + * Move the read/write file offset to a specified byte within a file. + * @param thefile The file descriptor + * @param where How to move the pointer, one of: + * @li #APR_SET -- set the offset to offset + * @li #APR_CUR -- add the offset to the current position + * @li #APR_END -- add the offset to the current file size + * @param offset The offset to move the pointer to. + * @remark The third argument is modified to be the offset the pointer + was actually moved to. + */ +APR_DECLARE(apr_status_t) apr_file_seek(apr_file_t *thefile, + apr_seek_where_t where, + apr_off_t *offset); + +/** + * Create an anonymous pipe. + * @param in The newly created pipe's file for reading. + * @param out The newly created pipe's file for writing. + * @param pool The pool to operate on. + * @remark By default, the returned file descriptors will be inherited + * by child processes created using apr_proc_create(). This can be + * changed using apr_file_inherit_unset(). + * @bug Some platforms cannot toggle between blocking and nonblocking, + * and when passing a pipe as a standard handle to an application which + * does not expect it, a non-blocking stream will fluxor the client app. + * @deprecated @see apr_file_pipe_create_pools() + */ +APR_DECLARE(apr_status_t) apr_file_pipe_create(apr_file_t **in, + apr_file_t **out, + apr_pool_t *pool); + +/** + * Create an anonymous pipe which portably supports async timeout options. + * @param in The newly created pipe's file for reading. + * @param out The newly created pipe's file for writing. + * @param blocking one of these values defined in apr_thread_proc.h; + * @li #APR_FULL_BLOCK + * @li #APR_READ_BLOCK + * @li #APR_WRITE_BLOCK + * @li #APR_FULL_NONBLOCK + * @param pool The pool to operate on. + * @remark By default, the returned file descriptors will be inherited + * by child processes created using apr_proc_create(). This can be + * changed using apr_file_inherit_unset(). + * @remark Some platforms cannot toggle between blocking and nonblocking, + * and when passing a pipe as a standard handle to an application which + * does not expect it, a non-blocking stream will fluxor the client app. + * Use this function rather than apr_file_pipe_create() to create pipes + * where one or both ends require non-blocking semantics. + * @deprecated @see apr_file_pipe_create_pools() + */ +APR_DECLARE(apr_status_t) apr_file_pipe_create_ex(apr_file_t **in, + apr_file_t **out, + apr_int32_t blocking, + apr_pool_t *pool); + +/** + * Create an anonymous pipe which portably supports async timeout options, + * placing each side of the pipe in a different pool. + * @param in The newly created pipe's file for reading. + * @param out The newly created pipe's file for writing. + * @param blocking one of these values defined in apr_thread_proc.h; + * @li #APR_FULL_BLOCK + * @li #APR_READ_BLOCK + * @li #APR_WRITE_BLOCK + * @li #APR_FULL_NONBLOCK + * @param pool_in The pool for the reading pipe. + * @param pool_out The pool for the writing pipe. + * @remark By default, the returned file descriptors will be inherited + * by child processes created using apr_proc_create(). This can be + * changed using apr_file_inherit_unset(). + * @remark Some platforms cannot toggle between blocking and nonblocking, + * and when passing a pipe as a standard handle to an application which + * does not expect it, a non-blocking stream will fluxor the client app. + * Use this function rather than apr_file_pipe_create() to create pipes + * where one or both ends require non-blocking semantics. + */ +APR_DECLARE(apr_status_t) apr_file_pipe_create_pools(apr_file_t **in, + apr_file_t **out, + apr_int32_t blocking, + apr_pool_t *pool_in, + apr_pool_t *pool_out); + +/** + * Create a named pipe. + * @param filename The filename of the named pipe + * @param perm The permissions for the newly created pipe. + * @param pool The pool to operate on. + */ +APR_DECLARE(apr_status_t) apr_file_namedpipe_create(const char *filename, + apr_fileperms_t perm, + apr_pool_t *pool); + +/** + * Get the timeout value for a pipe or manipulate the blocking state. + * @param thepipe The pipe we are getting a timeout for. + * @param timeout The current timeout value in microseconds. + */ +APR_DECLARE(apr_status_t) apr_file_pipe_timeout_get(apr_file_t *thepipe, + apr_interval_time_t *timeout); + +/** + * Set the timeout value for a pipe or manipulate the blocking state. + * @param thepipe The pipe we are setting a timeout on. + * @param timeout The timeout value in microseconds. Values < 0 mean wait + * forever, 0 means do not wait at all. + */ +APR_DECLARE(apr_status_t) apr_file_pipe_timeout_set(apr_file_t *thepipe, + apr_interval_time_t timeout); + +/** file (un)locking functions. */ + +/** + * Establish a lock on the specified, open file. The lock may be advisory + * or mandatory, at the discretion of the platform. The lock applies to + * the file as a whole, rather than a specific range. Locks are established + * on a per-thread/process basis; a second lock by the same thread will not + * block. + * @param thefile The file to lock. + * @param type The type of lock to establish on the file. + */ +APR_DECLARE(apr_status_t) apr_file_lock(apr_file_t *thefile, int type); + +/** + * Remove any outstanding locks on the file. + * @param thefile The file to unlock. + */ +APR_DECLARE(apr_status_t) apr_file_unlock(apr_file_t *thefile); + +/**accessor and general file_io functions. */ + +/** + * return the file name of the current file. + * @param new_path The path of the file. + * @param thefile The currently open file. + */ +APR_DECLARE(apr_status_t) apr_file_name_get(const char **new_path, + apr_file_t *thefile); + +/** + * Return the data associated with the current file. + * @param data The user data associated with the file. + * @param key The key to use for retrieving data associated with this file. + * @param file The currently open file. + */ +APR_DECLARE(apr_status_t) apr_file_data_get(void **data, const char *key, + apr_file_t *file); + +/** + * Set the data associated with the current file. + * @param file The currently open file. + * @param data The user data to associate with the file. + * @param key The key to use for associating data with the file. + * @param cleanup The cleanup routine to use when the file is destroyed. + */ +APR_DECLARE(apr_status_t) apr_file_data_set(apr_file_t *file, void *data, + const char *key, + apr_status_t (*cleanup)(void *)); + +/** + * Write a string to a file using a printf format. + * @param fptr The file to write to. + * @param format The format string + * @param ... The values to substitute in the format string + * @return The number of bytes written + */ +APR_DECLARE_NONSTD(int) apr_file_printf(apr_file_t *fptr, + const char *format, ...) + __attribute__((format(printf,2,3))); + +/** + * set the specified file's permission bits. + * @param fname The file (name) to apply the permissions to. + * @param perms The permission bits to apply to the file. + * + * @warning Some platforms may not be able to apply all of the + * available permission bits; #APR_INCOMPLETE will be returned if some + * permissions are specified which could not be set. + * + * @warning Platforms which do not implement this feature will return + * #APR_ENOTIMPL. + */ +APR_DECLARE(apr_status_t) apr_file_perms_set(const char *fname, + apr_fileperms_t perms); + +/** + * Set attributes of the specified file. + * @param fname The full path to the file (using / on all systems) + * @param attributes Or'd combination of + * @li #APR_FILE_ATTR_READONLY - make the file readonly + * @li #APR_FILE_ATTR_EXECUTABLE - make the file executable + * @li #APR_FILE_ATTR_HIDDEN - make the file hidden + * @param attr_mask Mask of valid bits in attributes. + * @param pool the pool to use. + * @remark This function should be used in preference to explicit manipulation + * of the file permissions, because the operations to provide these + * attributes are platform specific and may involve more than simply + * setting permission bits. + * @warning Platforms which do not implement this feature will return + * #APR_ENOTIMPL. + */ +APR_DECLARE(apr_status_t) apr_file_attrs_set(const char *fname, + apr_fileattrs_t attributes, + apr_fileattrs_t attr_mask, + apr_pool_t *pool); + +/** + * Set the mtime of the specified file. + * @param fname The full path to the file (using / on all systems) + * @param mtime The mtime to apply to the file. + * @param pool The pool to use. + * @warning Platforms which do not implement this feature will return + * #APR_ENOTIMPL. + */ +APR_DECLARE(apr_status_t) apr_file_mtime_set(const char *fname, + apr_time_t mtime, + apr_pool_t *pool); + +/** + * Create a new directory on the file system. + * @param path the path for the directory to be created. (use / on all systems) + * @param perm Permissions for the new directory. + * @param pool the pool to use. + */ +APR_DECLARE(apr_status_t) apr_dir_make(const char *path, apr_fileperms_t perm, + apr_pool_t *pool); + +/** Creates a new directory on the file system, but behaves like + * 'mkdir -p'. Creates intermediate directories as required. No error + * will be reported if PATH already exists. + * @param path the path for the directory to be created. (use / on all systems) + * @param perm Permissions for the new directory. + * @param pool the pool to use. + */ +APR_DECLARE(apr_status_t) apr_dir_make_recursive(const char *path, + apr_fileperms_t perm, + apr_pool_t *pool); + +/** + * Remove directory from the file system. + * @param path the path for the directory to be removed. (use / on all systems) + * @param pool the pool to use. + * @remark Removing a directory which is in-use (e.g., the current working + * directory, or during apr_dir_read, or with an open file) is not portable. + */ +APR_DECLARE(apr_status_t) apr_dir_remove(const char *path, apr_pool_t *pool); + +/** + * get the specified file's stats. + * @param finfo Where to store the information about the file. + * @param wanted The desired apr_finfo_t fields, as a bit flag of APR_FINFO_* values + * @param thefile The file to get information about. + */ +APR_DECLARE(apr_status_t) apr_file_info_get(apr_finfo_t *finfo, + apr_int32_t wanted, + apr_file_t *thefile); + + +/** + * Truncate the file's length to the specified offset + * @param fp The file to truncate + * @param offset The offset to truncate to. + * @remark The read/write file offset is repositioned to offset. + */ +APR_DECLARE(apr_status_t) apr_file_trunc(apr_file_t *fp, apr_off_t offset); + +/** + * Retrieve the flags that were passed into apr_file_open() + * when the file was opened. + * @return apr_int32_t the flags + */ +APR_DECLARE(apr_int32_t) apr_file_flags_get(apr_file_t *f); + +/** + * Get the pool used by the file. + */ +APR_POOL_DECLARE_ACCESSOR(file); + +/** + * Set a file to be inherited by child processes. + * + */ +APR_DECLARE_INHERIT_SET(file); + +/** + * Unset a file from being inherited by child processes. + */ +APR_DECLARE_INHERIT_UNSET(file); + +/** + * Open a temporary file + * @param fp The apr file to use as a temporary file. + * @param templ The template to use when creating a temp file. + * @param flags The flags to open the file with. If this is zero, + * the file is opened with + * #APR_FOPEN_CREATE | #APR_FOPEN_READ | #APR_FOPEN_WRITE | + * #APR_FOPEN_EXCL | #APR_FOPEN_DELONCLOSE + * @param p The pool to allocate the file out of. + * @remark + * This function generates a unique temporary file name from template. + * The last six characters of template must be XXXXXX and these are replaced + * with a string that makes the filename unique. Since it will be modified, + * template must not be a string constant, but should be declared as a character + * array. + * + */ +APR_DECLARE(apr_status_t) apr_file_mktemp(apr_file_t **fp, char *templ, + apr_int32_t flags, apr_pool_t *p); + + +/** + * Find an existing directory suitable as a temporary storage location. + * @param temp_dir The temp directory. + * @param p The pool to use for any necessary allocations. + * @remark + * This function uses an algorithm to search for a directory that an + * an application can use for temporary storage. + * + */ +APR_DECLARE(apr_status_t) apr_temp_dir_get(const char **temp_dir, + apr_pool_t *p); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_FILE_IO_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_fnmatch.h b/c/dependencies/windows/apr/x64/include/apr_fnmatch.h new file mode 100644 index 00000000..e8f6b03c --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_fnmatch.h @@ -0,0 +1,153 @@ +/* + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)fnmatch.h 8.1 (Berkeley) 6/2/93 + */ + +/* This file has been modified by the Apache Software Foundation. */ +#ifndef _APR_FNMATCH_H_ +#define _APR_FNMATCH_H_ + +/** + * @file apr_fnmatch.h + * @brief APR FNMatch Functions + */ + +#include "apr_errno.h" +#include "apr_tables.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_fnmatch Filename Matching Functions + * @ingroup APR + * @{ + */ + +#define APR_FNM_NOMATCH 1 /**< Match failed. */ + +#define APR_FNM_NOESCAPE 0x01 /**< Disable backslash escaping. */ +#define APR_FNM_PATHNAME 0x02 /**< Slash must be matched by slash. */ +#define APR_FNM_PERIOD 0x04 /**< Period must be matched by period. */ +#define APR_FNM_CASE_BLIND 0x08 /**< Compare characters case-insensitively. */ + +/** + * Try to match the string to the given pattern, return APR_SUCCESS if + * match, else return APR_FNM_NOMATCH. Note that there is no such thing as + * an illegal pattern. + * + * With all flags unset, a pattern is interpreted as such: + * + * PATTERN: Backslash followed by any character, including another + * backslash.
+ * MATCHES: That character exactly. + * + *

+ * PATTERN: ?
+ * MATCHES: Any single character. + *

+ * + *

+ * PATTERN: *
+ * MATCHES: Any sequence of zero or more characters. (Note that multiple + * *s in a row are equivalent to one.) + * + * PATTERN: Any character other than \?*[ or a \ at the end of the pattern
+ * MATCHES: That character exactly. (Case sensitive.) + * + * PATTERN: [ followed by a class description followed by ]
+ * MATCHES: A single character described by the class description. + * (Never matches, if the class description reaches until the + * end of the string without a ].) If the first character of + * the class description is ^ or !, the sense of the description + * is reversed. The rest of the class description is a list of + * single characters or pairs of characters separated by -. Any + * of those characters can have a backslash in front of them, + * which is ignored; this lets you use the characters ] and - + * in the character class, as well as ^ and ! at the + * beginning. The pattern matches a single character if it + * is one of the listed characters or falls into one of the + * listed ranges (inclusive, case sensitive). Ranges with + * the first character larger than the second are legal but + * never match. Edge cases: [] never matches, and [^] and [!] + * always match without consuming a character. + * + * Note that these patterns attempt to match the entire string, not + * just find a substring matching the pattern. + * + * @param pattern The pattern to match to + * @param strings The string we are trying to match + * @param flags flags to use in the match. Bitwise OR of: + *

+ *              APR_FNM_NOESCAPE       Disable backslash escaping
+ *              APR_FNM_PATHNAME       Slash must be matched by slash
+ *              APR_FNM_PERIOD         Period must be matched by period
+ *              APR_FNM_CASE_BLIND     Compare characters case-insensitively.
+ * 
+ */ + +APR_DECLARE(apr_status_t) apr_fnmatch(const char *pattern, + const char *strings, int flags); + +/** + * Determine if the given pattern is a regular expression. + * @param pattern The pattern to search for glob characters. + * @return non-zero if pattern has any glob characters in it + */ +APR_DECLARE(int) apr_fnmatch_test(const char *pattern); + +/** + * Find all files that match a specified pattern in a directory. + * @param dir_pattern The pattern to use for finding files, appended + * to the search directory. The pattern is anything following the + * final forward or backward slash in the parameter. If no slash + * is found, the current directory is searched. + * @param result Array to use when storing the results + * @param p The pool to use. + * @return APR_SUCCESS if no processing errors occurred, APR error + * code otherwise + * @remark The returned array may be empty even if APR_SUCCESS was + * returned. + */ +APR_DECLARE(apr_status_t) apr_match_glob(const char *dir_pattern, + apr_array_header_t **result, + apr_pool_t *p); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !_APR_FNMATCH_H_ */ diff --git a/c/dependencies/windows/apr/x64/include/apr_general.h b/c/dependencies/windows/apr/x64/include/apr_general.h new file mode 100644 index 00000000..fa073c85 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_general.h @@ -0,0 +1,244 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_GENERAL_H +#define APR_GENERAL_H + +/** + * @file apr_general.h + * This is collection of oddballs that didn't fit anywhere else, + * and might move to more appropriate headers with the release + * of APR 1.0. + * @brief APR Miscellaneous library routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" + +#if APR_HAVE_SIGNAL_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_general Miscellaneous library routines + * @ingroup APR + * This is collection of oddballs that didn't fit anywhere else, + * and might move to more appropriate headers with the release + * of APR 1.0. + * @{ + */ + +/** FALSE */ +#ifndef FALSE +#define FALSE 0 +#endif +/** TRUE */ +#ifndef TRUE +#define TRUE (!FALSE) +#endif + +/** a space */ +#define APR_ASCII_BLANK '\040' +/** a carrige return */ +#define APR_ASCII_CR '\015' +/** a line feed */ +#define APR_ASCII_LF '\012' +/** a tab */ +#define APR_ASCII_TAB '\011' + +/** signal numbers typedef */ +typedef int apr_signum_t; + +/** + * Finding offsets of elements within structures. + * Taken from the X code... they've sweated portability of this stuff + * so we don't have to. Sigh... + * @param p_type pointer type name + * @param field data field within the structure pointed to + * @return offset + */ + +#if defined(CRAY) || (defined(__arm) && !(defined(LINUX) || defined(__FreeBSD__))) +#ifdef __STDC__ +#define APR_OFFSET(p_type,field) _Offsetof(p_type,field) +#else +#ifdef CRAY2 +#define APR_OFFSET(p_type,field) \ + (sizeof(int)*((unsigned int)&(((p_type)NULL)->field))) + +#else /* !CRAY2 */ + +#define APR_OFFSET(p_type,field) ((unsigned int)&(((p_type)NULL)->field)) + +#endif /* !CRAY2 */ +#endif /* __STDC__ */ +#else /* ! (CRAY || __arm) */ + +#define APR_OFFSET(p_type,field) \ + ((long) (((char *) (&(((p_type)NULL)->field))) - ((char *) NULL))) + +#endif /* !CRAY */ + +/** + * Finding offsets of elements within structures. + * @param s_type structure type name + * @param field data field within the structure + * @return offset + */ +#if defined(offsetof) && !defined(__cplusplus) +#define APR_OFFSETOF(s_type,field) offsetof(s_type,field) +#else +#define APR_OFFSETOF(s_type,field) APR_OFFSET(s_type*,field) +#endif + +#ifndef DOXYGEN + +/* A couple of prototypes for functions in case some platform doesn't + * have it + */ +#if (!APR_HAVE_STRCASECMP) && (APR_HAVE_STRICMP) +#define strcasecmp(s1, s2) stricmp(s1, s2) +#elif (!APR_HAVE_STRCASECMP) +int strcasecmp(const char *a, const char *b); +#endif + +#if (!APR_HAVE_STRNCASECMP) && (APR_HAVE_STRNICMP) +#define strncasecmp(s1, s2, n) strnicmp(s1, s2, n) +#elif (!APR_HAVE_STRNCASECMP) +int strncasecmp(const char *a, const char *b, size_t n); +#endif + +#endif + +/** + * Alignment macros + */ + +/* APR_ALIGN() is only to be used to align on a power of 2 boundary */ +#define APR_ALIGN(size, boundary) \ + (((size) + ((boundary) - 1)) & ~((boundary) - 1)) + +/** Default alignment */ +#define APR_ALIGN_DEFAULT(size) APR_ALIGN(size, 8) + + +/** + * String and memory functions + */ + +/* APR_STRINGIFY is defined here, and also in apr_release.h, so wrap it */ +#ifndef APR_STRINGIFY +/** Properly quote a value as a string in the C preprocessor */ +#define APR_STRINGIFY(n) APR_STRINGIFY_HELPER(n) +/** Helper macro for APR_STRINGIFY */ +#define APR_STRINGIFY_HELPER(n) #n +#endif + +#if (!APR_HAVE_MEMMOVE) +#define memmove(a,b,c) bcopy(b,a,c) +#endif + +#if (!APR_HAVE_MEMCHR) +void *memchr(const void *s, int c, size_t n); +#endif + +/** @} */ + +/** + * @defgroup apr_library Library initialization and termination + * @{ + */ + +/** + * Setup any APR internal data structures. This MUST be the first function + * called for any APR library. It is safe to call apr_initialize several + * times as long as apr_terminate() is called the same number of times. + * @remark See apr_app_initialize() if this is an application, rather than + * a library consumer of apr. + */ +APR_DECLARE(apr_status_t) apr_initialize(void); + +/** + * Set up an application with normalized argc, argv (and optionally env) in + * order to deal with platform-specific oddities, such as Win32 services, + * code pages and signals. This must be the first function called for any + * APR program. + * @param argc Pointer to the argc that may be corrected + * @param argv Pointer to the argv that may be corrected + * @param env Pointer to the env that may be corrected, may be NULL + * @remark See apr_initialize() if this is a library consumer of apr. + * Otherwise, this call is identical to apr_initialize(), and must be closed + * with a call to apr_terminate() at the end of program execution. + */ +APR_DECLARE(apr_status_t) apr_app_initialize(int *argc, + char const * const * *argv, + char const * const * *env); + +/** + * Tear down any APR internal data structures which aren't torn down + * automatically. apr_terminate must be called once for every call to + * apr_initialize() or apr_app_initialize(). + * @remark An APR program must call this function at termination once it + * has stopped using APR services. The APR developers suggest using + * @c atexit(apr_terminate) to ensure this is called. When using APR + * from a language other than C that has problems with the calling + * convention, use apr_terminate2() instead. + * @see apr_terminate2 + */ +APR_DECLARE_NONSTD(void) apr_terminate(void); + +/** + * Tear down any APR internal data structures which aren't torn down + * automatically, same as apr_terminate() + * @remark An APR program must call either the apr_terminate() or apr_terminate2 + * function once it it has finished using APR services. The APR + * developers suggest using @c atexit(apr_terminate) to ensure this is done. + * apr_terminate2 exists to allow non-c language apps to tear down apr, + * while apr_terminate() is recommended from c language applications. + */ +APR_DECLARE(void) apr_terminate2(void); + +/** @} */ + +/** + * @defgroup apr_random Random Functions + * @{ + */ + +#if APR_HAS_RANDOM || defined(DOXYGEN) + +/* TODO: I'm not sure this is the best place to put this prototype...*/ +/** + * Generate random bytes. + * @param buf Buffer to fill with random bytes + * @param length Length of buffer in bytes + */ +APR_DECLARE(apr_status_t) apr_generate_random_bytes(unsigned char * buf, + apr_size_t length); + +#endif +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_GENERAL_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_getopt.h b/c/dependencies/windows/apr/x64/include/apr_getopt.h new file mode 100644 index 00000000..75ad5663 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_getopt.h @@ -0,0 +1,160 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_GETOPT_H +#define APR_GETOPT_H + +/** + * @file apr_getopt.h + * @brief APR Command Arguments (getopt) + */ + +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_getopt Command Argument Parsing + * @ingroup APR + * @{ + */ + +/** + * An @c apr_getopt_t error callback function. + * + * @a arg is this @c apr_getopt_t's @c errarg member. + */ +typedef void (apr_getopt_err_fn_t)(void *arg, const char *err, ...); + +/** @see apr_getopt_t */ +typedef struct apr_getopt_t apr_getopt_t; + +/** + * Structure to store command line argument information. + */ +struct apr_getopt_t { + /** context for processing */ + apr_pool_t *cont; + /** function to print error message (NULL == no messages) */ + apr_getopt_err_fn_t *errfn; + /** user defined first arg to pass to error message */ + void *errarg; + /** index into parent argv vector */ + int ind; + /** character checked for validity */ + int opt; + /** reset getopt */ + int reset; + /** count of arguments */ + int argc; + /** array of pointers to arguments */ + const char **argv; + /** argument associated with option */ + char const* place; + /** set to nonzero to support interleaving options with regular args */ + int interleave; + /** start of non-option arguments skipped for interleaving */ + int skip_start; + /** end of non-option arguments skipped for interleaving */ + int skip_end; +}; + +/** @see apr_getopt_option_t */ +typedef struct apr_getopt_option_t apr_getopt_option_t; + +/** + * Structure used to describe options that getopt should search for. + */ +struct apr_getopt_option_t { + /** long option name, or NULL if option has no long name */ + const char *name; + /** option letter, or a value greater than 255 if option has no letter */ + int optch; + /** nonzero if option takes an argument */ + int has_arg; + /** a description of the option */ + const char *description; +}; + +/** + * Initialize the arguments for parsing by apr_getopt(). + * @param os The options structure created for apr_getopt() + * @param cont The pool to operate on + * @param argc The number of arguments to parse + * @param argv The array of arguments to parse + * @remark Arguments 3 and 4 are most commonly argc and argv from main(argc, argv) + * The (*os)->errfn is initialized to fprintf(stderr... but may be overridden. + */ +APR_DECLARE(apr_status_t) apr_getopt_init(apr_getopt_t **os, apr_pool_t *cont, + int argc, const char * const *argv); + +/** + * Parse the options initialized by apr_getopt_init(). + * @param os The apr_opt_t structure returned by apr_getopt_init() + * @param opts A string of characters that are acceptable options to the + * program. Characters followed by ":" are required to have an + * option associated + * @param option_ch The next option character parsed + * @param option_arg The argument following the option character: + * @return There are four potential status values on exit. They are: + *
+ *             APR_EOF      --  No more options to parse
+ *             APR_BADCH    --  Found a bad option character
+ *             APR_BADARG   --  No argument followed the option flag
+ *             APR_SUCCESS  --  The next option was found.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_getopt(apr_getopt_t *os, const char *opts, + char *option_ch, const char **option_arg); + +/** + * Parse the options initialized by apr_getopt_init(), accepting long + * options beginning with "--" in addition to single-character + * options beginning with "-". + * @param os The apr_getopt_t structure created by apr_getopt_init() + * @param opts A pointer to a list of apr_getopt_option_t structures, which + * can be initialized with { "name", optch, has_args }. has_args + * is nonzero if the option requires an argument. A structure + * with an optch value of 0 terminates the list. + * @param option_ch Receives the value of "optch" from the apr_getopt_option_t + * structure corresponding to the next option matched. + * @param option_arg Receives the argument following the option, if any. + * @return There are four potential status values on exit. They are: + *
+ *             APR_EOF      --  No more options to parse
+ *             APR_BADCH    --  Found a bad option character
+ *             APR_BADARG   --  No argument followed the option flag
+ *             APR_SUCCESS  --  The next option was found.
+ * 
+ * When APR_SUCCESS is returned, os->ind gives the index of the first + * non-option argument. On error, a message will be printed to stdout unless + * os->err is set to 0. If os->interleave is set to nonzero, options can come + * after arguments, and os->argv will be permuted to leave non-option arguments + * at the end (the original argv is unaffected). + */ +APR_DECLARE(apr_status_t) apr_getopt_long(apr_getopt_t *os, + const apr_getopt_option_t *opts, + int *option_ch, + const char **option_arg); +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_GETOPT_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_global_mutex.h b/c/dependencies/windows/apr/x64/include/apr_global_mutex.h new file mode 100644 index 00000000..e3cba23f --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_global_mutex.h @@ -0,0 +1,195 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_GLOBAL_MUTEX_H +#define APR_GLOBAL_MUTEX_H + +/** + * @file apr_global_mutex.h + * @brief APR Global Locking Routines + */ + +#include "apr.h" +#include "apr_proc_mutex.h" /* only for apr_lockmech_e */ +#include "apr_pools.h" +#include "apr_errno.h" +#if APR_PROC_MUTEX_IS_GLOBAL +#include "apr_proc_mutex.h" +#endif +#include "apr_time.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_GlobalMutex Global Locking Routines + * @ingroup APR + * @{ + */ + +#if !APR_PROC_MUTEX_IS_GLOBAL || defined(DOXYGEN) + +/** Opaque global mutex structure. */ +typedef struct apr_global_mutex_t apr_global_mutex_t; + +/* Function definitions */ + +/** + * Create and initialize a mutex that can be used to synchronize both + * processes and threads. Note: There is considerable overhead in using + * this API if only cross-process or cross-thread mutual exclusion is + * required. See apr_proc_mutex.h and apr_thread_mutex.h for more + * specialized lock routines. + * @param mutex the memory address where the newly created mutex will be + * stored. + * @param fname A file name to use if the lock mechanism requires one. This + * argument should always be provided. The lock code itself will + * determine if it should be used. + * @param mech The mechanism to use for the interprocess lock, if any; one of + *
+ *            APR_LOCK_FCNTL
+ *            APR_LOCK_FLOCK
+ *            APR_LOCK_SYSVSEM
+ *            APR_LOCK_POSIXSEM
+ *            APR_LOCK_PROC_PTHREAD
+ *            APR_LOCK_DEFAULT     pick the default mechanism for the platform
+ *            APR_LOCK_DEFAULT_TIMED pick the default timed mechanism
+ * 
+ * @param pool the pool from which to allocate the mutex. + * @warning Check APR_HAS_foo_SERIALIZE defines to see if the platform supports + * APR_LOCK_foo. Only APR_LOCK_DEFAULT is portable. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_create(apr_global_mutex_t **mutex, + const char *fname, + apr_lockmech_e mech, + apr_pool_t *pool); + +/** + * Re-open a mutex in a child process. + * @param mutex The newly re-opened mutex structure. + * @param fname A file name to use if the mutex mechanism requires one. This + * argument should always be provided. The mutex code itself will + * determine if it should be used. This filename should be the + * same one that was passed to apr_global_mutex_create(). + * @param pool The pool to operate on. + * @remark This function must be called to maintain portability, even + * if the underlying lock mechanism does not require it. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_child_init( + apr_global_mutex_t **mutex, + const char *fname, + apr_pool_t *pool); + +/** + * Acquire the lock for the given mutex. If the mutex is already locked, + * the current thread will be put to sleep until the lock becomes available. + * @param mutex the mutex on which to acquire the lock. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_lock(apr_global_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex. If the mutex has already + * been acquired, the call returns immediately with APR_EBUSY. Note: it + * is important that the APR_STATUS_IS_EBUSY(s) macro be used to determine + * if the return value was APR_EBUSY, for portability reasons. + * @param mutex the mutex on which to attempt the lock acquiring. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_trylock(apr_global_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex until timeout expires. + * If the acquisition time outs, the call returns with APR_TIMEUP. + * @param mutex the mutex on which to attempt the lock acquiring. + * @param timeout the relative timeout (microseconds). + * @note A negative or nul timeout means immediate attempt, returning + * APR_TIMEUP without blocking if it the lock is already acquired. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_timedlock(apr_global_mutex_t *mutex, + apr_interval_time_t timeout); + +/** + * Release the lock for the given mutex. + * @param mutex the mutex from which to release the lock. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_unlock(apr_global_mutex_t *mutex); + +/** + * Destroy the mutex and free the memory associated with the lock. + * @param mutex the mutex to destroy. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_destroy(apr_global_mutex_t *mutex); + +/** + * Return the name of the lockfile for the mutex, or NULL + * if the mutex doesn't use a lock file + */ +APR_DECLARE(const char *) apr_global_mutex_lockfile(apr_global_mutex_t *mutex); + +/** + * Get the mechanism of the mutex, as it relates to the actual method + * used for the underlying apr_proc_mutex_t. + * @param mutex the mutex to get the mechanism from. + */ +APR_DECLARE(apr_lockmech_e) apr_global_mutex_mech(apr_global_mutex_t *mutex); + +/** + * Get the mechanism's name of the mutex, as it relates to the actual method + * used for the underlying apr_proc_mutex_t. + * @param mutex the mutex to get the mechanism's name from. + */ +APR_DECLARE(const char *) apr_global_mutex_name(apr_global_mutex_t *mutex); + +/** + * Set mutex permissions. + */ +APR_PERMS_SET_IMPLEMENT(global_mutex); + +/** + * Get the pool used by this global_mutex. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(global_mutex); + +#else /* APR_PROC_MUTEX_IS_GLOBAL */ + +/* Some platforms [e.g. Win32] have cross process locks that are truly + * global locks, since there isn't the concept of cross-process locks. + * Define these platforms in terms of an apr_proc_mutex_t. + */ + +#define apr_global_mutex_t apr_proc_mutex_t +#define apr_global_mutex_create apr_proc_mutex_create +#define apr_global_mutex_child_init apr_proc_mutex_child_init +#define apr_global_mutex_lock apr_proc_mutex_lock +#define apr_global_mutex_trylock apr_proc_mutex_trylock +#define apr_global_mutex_unlock apr_proc_mutex_unlock +#define apr_global_mutex_destroy apr_proc_mutex_destroy +#define apr_global_mutex_lockfile apr_proc_mutex_lockfile +#define apr_global_mutex_mech apr_proc_mutex_mech +#define apr_global_mutex_name apr_proc_mutex_name +#define apr_global_mutex_perms_set apr_proc_mutex_perms_set +#define apr_global_mutex_pool_get apr_proc_mutex_pool_get + +#endif + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ndef APR_GLOBAL_MUTEX_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_hash.h b/c/dependencies/windows/apr/x64/include/apr_hash.h new file mode 100644 index 00000000..2276f84c --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_hash.h @@ -0,0 +1,283 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_HASH_H +#define APR_HASH_H + +/** + * @file apr_hash.h + * @brief APR Hash Tables + */ + +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_hash Hash Tables + * @ingroup APR + * @{ + */ + +/** + * When passing a key to apr_hash_set or apr_hash_get, this value can be + * passed to indicate a string-valued key, and have apr_hash compute the + * length automatically. + * + * @remark apr_hash will use strlen(key) for the length. The NUL terminator + * is not included in the hash value (why throw a constant in?). + * Since the hash table merely references the provided key (rather + * than copying it), apr_hash_this() will return the NUL-term'd key. + */ +#define APR_HASH_KEY_STRING (-1) + +/** + * Abstract type for hash tables. + */ +typedef struct apr_hash_t apr_hash_t; + +/** + * Abstract type for scanning hash tables. + */ +typedef struct apr_hash_index_t apr_hash_index_t; + +/** + * Callback functions for calculating hash values. + * @param key The key. + * @param klen The length of the key, or APR_HASH_KEY_STRING to use the string + * length. If APR_HASH_KEY_STRING then returns the actual key length. + */ +typedef unsigned int (*apr_hashfunc_t)(const char *key, apr_ssize_t *klen); + +/** + * The default hash function. + */ +APR_DECLARE_NONSTD(unsigned int) apr_hashfunc_default(const char *key, + apr_ssize_t *klen); + +/** + * Create a hash table. + * @param pool The pool to allocate the hash table out of + * @return The hash table just created + */ +APR_DECLARE(apr_hash_t *) apr_hash_make(apr_pool_t *pool); + +/** + * Create a hash table with a custom hash function + * @param pool The pool to allocate the hash table out of + * @param hash_func A custom hash function. + * @return The hash table just created + */ +APR_DECLARE(apr_hash_t *) apr_hash_make_custom(apr_pool_t *pool, + apr_hashfunc_t hash_func); + +/** + * Make a copy of a hash table + * @param pool The pool from which to allocate the new hash table + * @param h The hash table to clone + * @return The hash table just created + * @remark Makes a shallow copy + */ +APR_DECLARE(apr_hash_t *) apr_hash_copy(apr_pool_t *pool, + const apr_hash_t *h); + +/** + * Associate a value with a key in a hash table. + * @param ht The hash table + * @param key Pointer to the key + * @param klen Length of the key. Can be APR_HASH_KEY_STRING to use the string length. + * @param val Value to associate with the key + * @remark If the value is NULL the hash entry is deleted. The key is stored as is, + * and so must have a lifetime at least as long as the hash table's pool. + */ +APR_DECLARE(void) apr_hash_set(apr_hash_t *ht, const void *key, + apr_ssize_t klen, const void *val); + +/** + * Look up the value associated with a key in a hash table. + * @param ht The hash table + * @param key Pointer to the key + * @param klen Length of the key. Can be APR_HASH_KEY_STRING to use the string length. + * @return Returns NULL if the key is not present. + */ +APR_DECLARE(void *) apr_hash_get(apr_hash_t *ht, const void *key, + apr_ssize_t klen); + +/** + * Start iterating over the entries in a hash table. + * @param p The pool to allocate the apr_hash_index_t iterator. If this + * pool is NULL, then an internal, non-thread-safe iterator is used. + * @param ht The hash table + * @return The iteration state + * @remark There is no restriction on adding or deleting hash entries during + * an iteration (although the results may be unpredictable unless all you do + * is delete the current entry) and multiple iterations can be in + * progress at the same time. + * + * @par Example: + * + * @code + * int sum_values(apr_pool_t *p, apr_hash_t *ht) + * { + * apr_hash_index_t *hi; + * void *val; + * int sum = 0; + * for (hi = apr_hash_first(p, ht); hi; hi = apr_hash_next(hi)) { + * apr_hash_this(hi, NULL, NULL, &val); + * sum += *(int *)val; + * } + * return sum; + * } + * @endcode + */ +APR_DECLARE(apr_hash_index_t *) apr_hash_first(apr_pool_t *p, apr_hash_t *ht); + +/** + * Continue iterating over the entries in a hash table. + * @param hi The iteration state + * @return a pointer to the updated iteration state. NULL if there are no more + * entries. + */ +APR_DECLARE(apr_hash_index_t *) apr_hash_next(apr_hash_index_t *hi); + +/** + * Get the current entry's details from the iteration state. + * @param hi The iteration state + * @param key Return pointer for the pointer to the key. + * @param klen Return pointer for the key length. + * @param val Return pointer for the associated value. + * @remark The return pointers should point to a variable that will be set to the + * corresponding data, or they may be NULL if the data isn't interesting. + */ +APR_DECLARE(void) apr_hash_this(apr_hash_index_t *hi, const void **key, + apr_ssize_t *klen, void **val); + +/** + * Get the current entry's key from the iteration state. + * @param hi The iteration state + * @return The pointer to the key + */ +APR_DECLARE(const void*) apr_hash_this_key(apr_hash_index_t *hi); + +/** + * Get the current entry's key length from the iteration state. + * @param hi The iteration state + * @return The key length + */ +APR_DECLARE(apr_ssize_t) apr_hash_this_key_len(apr_hash_index_t *hi); + +/** + * Get the current entry's value from the iteration state. + * @param hi The iteration state + * @return The pointer to the value + */ +APR_DECLARE(void*) apr_hash_this_val(apr_hash_index_t *hi); + +/** + * Get the number of key/value pairs in the hash table. + * @param ht The hash table + * @return The number of key/value pairs in the hash table. + */ +APR_DECLARE(unsigned int) apr_hash_count(apr_hash_t *ht); + +/** + * Clear any key/value pairs in the hash table. + * @param ht The hash table + */ +APR_DECLARE(void) apr_hash_clear(apr_hash_t *ht); + +/** + * Merge two hash tables into one new hash table. The values of the overlay + * hash override the values of the base if both have the same key. Both + * hash tables must use the same hash function. + * @param p The pool to use for the new hash table + * @param overlay The table to add to the initial table + * @param base The table that represents the initial values of the new table + * @return A new hash table containing all of the data from the two passed in + */ +APR_DECLARE(apr_hash_t *) apr_hash_overlay(apr_pool_t *p, + const apr_hash_t *overlay, + const apr_hash_t *base); + +/** + * Merge two hash tables into one new hash table. If the same key + * is present in both tables, call the supplied merge function to + * produce a merged value for the key in the new table. Both + * hash tables must use the same hash function. + * @param p The pool to use for the new hash table + * @param h1 The first of the tables to merge + * @param h2 The second of the tables to merge + * @param merger A callback function to merge values, or NULL to + * make values from h1 override values from h2 (same semantics as + * apr_hash_overlay()) + * @param data Client data to pass to the merger function + * @return A new hash table containing all of the data from the two passed in + */ +APR_DECLARE(apr_hash_t *) apr_hash_merge(apr_pool_t *p, + const apr_hash_t *h1, + const apr_hash_t *h2, + void * (*merger)(apr_pool_t *p, + const void *key, + apr_ssize_t klen, + const void *h1_val, + const void *h2_val, + const void *data), + const void *data); + +/** + * Declaration prototype for the iterator callback function of apr_hash_do(). + * + * @param rec The data passed as the first argument to apr_hash_[v]do() + * @param key The key from this iteration of the hash table + * @param klen The key length from this iteration of the hash table + * @param value The value from this iteration of the hash table + * @remark Iteration continues while this callback function returns non-zero. + * To export the callback function for apr_hash_do() it must be declared + * in the _NONSTD convention. + */ +typedef int (apr_hash_do_callback_fn_t)(void *rec, const void *key, + apr_ssize_t klen, + const void *value); + +/** + * Iterate over a hash table running the provided function once for every + * element in the hash table. The @param comp function will be invoked for + * every element in the hash table. + * + * @param comp The function to run + * @param rec The data to pass as the first argument to the function + * @param ht The hash table to iterate over + * @return FALSE if one of the comp() iterations returned zero; TRUE if all + * iterations returned non-zero + * @see apr_hash_do_callback_fn_t + */ +APR_DECLARE(int) apr_hash_do(apr_hash_do_callback_fn_t *comp, + void *rec, const apr_hash_t *ht); + +/** + * Get a pointer to the pool which the hash table was created in + */ +APR_POOL_DECLARE_ACCESSOR(hash); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_HASH_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_hooks.h b/c/dependencies/windows/apr/x64/include/apr_hooks.h new file mode 100644 index 00000000..eee16e3c --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_hooks.h @@ -0,0 +1,358 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_HOOKS_H +#define APR_HOOKS_H + +#include "apu.h" +/* For apr_array_header_t */ +#include "apr_tables.h" + +/** + * @file apr_hooks.h + * @brief Apache hook functions + */ + +#ifdef __cplusplus +extern "C" { +#endif +/** + * @defgroup APR_Util_Hook Hook Functions + * @ingroup APR_Util + * @{ + */ + +/** + * @defgroup apr_hook_probes Hook probe capability + * APR hooks provide a trace probe capability for capturing + * the flow of control and return values with hooks. + * + * In order to use this facility, the application must define + * the symbol APR_HOOK_PROBES_ENABLED and the four APR_HOOK_PROBE_ + * macros described below before including apr_hooks.h in files + * that use the APR_IMPLEMENT_EXTERNAL_HOOK_* macros. + * + * This probe facility is not provided for APR optional hooks. + * @{ + */ + +#ifdef APR_HOOK_PROBES_ENABLED +#define APR_HOOK_INT_DCL_UD void *ud = NULL +#else +/** internal implementation detail to avoid the ud declaration when + * hook probes are not used + */ +#define APR_HOOK_INT_DCL_UD +/** + * User-defined hook probe macro that is invoked when the hook + * is run, before calling any hook functions. + * @param ud A void * user data field that should be filled in by + * this macro, and will be provided to the other hook probe macros. + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param args The argument list to the hook functions, with enclosing + * parens. + */ +#define APR_HOOK_PROBE_ENTRY(ud,ns,name,args) +/** + * User-defined hook probe macro that is invoked after the hook + * has run. + * @param ud A void * user data field that was filled in by the user- + * provided APR_HOOK_PROBE_ENTRY(). + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param rv The return value of the hook, or 0 if the hook is void. + * @param args The argument list to the hook functions, with enclosing + * parens. + */ +#define APR_HOOK_PROBE_RETURN(ud,ns,name,rv,args) +/** + * User-defined hook probe macro that is invoked before calling a + * hook function. + * @param ud A void * user data field that was filled in by the user- + * provided APR_HOOK_PROBE_ENTRY(). + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param src The value of apr_hook_debug_current at the time the function + * was hooked (usually the source file implementing the hook function). + * @param args The argument list to the hook functions, with enclosing + * parens. + */ +#define APR_HOOK_PROBE_INVOKE(ud,ns,name,src,args) +/** + * User-defined hook probe macro that is invoked after calling a + * hook function. + * @param ud A void * user data field that was filled in by the user- + * provided APR_HOOK_PROBE_ENTRY(). + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param src The value of apr_hook_debug_current at the time the function + * was hooked (usually the source file implementing the hook function). + * @param rv The return value of the hook function, or 0 if the hook is void. + * @param args The argument list to the hook functions, with enclosing + * parens. + */ +#define APR_HOOK_PROBE_COMPLETE(ud,ns,name,src,rv,args) +#endif + +/** @} */ + +/** macro to return the prototype of the hook function */ +#define APR_IMPLEMENT_HOOK_GET_PROTO(ns,link,name) \ +link##_DECLARE(apr_array_header_t *) ns##_hook_get_##name(void) + +/** macro to declare the hook correctly */ +#define APR_DECLARE_EXTERNAL_HOOK(ns,link,ret,name,args) \ +typedef ret ns##_HOOK_##name##_t args; \ +link##_DECLARE(void) ns##_hook_##name(ns##_HOOK_##name##_t *pf, \ + const char * const *aszPre, \ + const char * const *aszSucc, int nOrder); \ +link##_DECLARE(ret) ns##_run_##name args; \ +APR_IMPLEMENT_HOOK_GET_PROTO(ns,link,name); \ +typedef struct ns##_LINK_##name##_t \ + { \ + ns##_HOOK_##name##_t *pFunc; \ + const char *szName; \ + const char * const *aszPredecessors; \ + const char * const *aszSuccessors; \ + int nOrder; \ + } ns##_LINK_##name##_t; + +/** macro to declare the hook structure */ +#define APR_HOOK_STRUCT(members) \ +static struct { members } _hooks; + +/** macro to link the hook structure */ +#define APR_HOOK_LINK(name) \ + apr_array_header_t *link_##name; + +/** macro to implement the hook */ +#define APR_IMPLEMENT_EXTERNAL_HOOK_BASE(ns,link,name) \ +link##_DECLARE(void) ns##_hook_##name(ns##_HOOK_##name##_t *pf,const char * const *aszPre, \ + const char * const *aszSucc,int nOrder) \ + { \ + ns##_LINK_##name##_t *pHook; \ + if(!_hooks.link_##name) \ + { \ + _hooks.link_##name=apr_array_make(apr_hook_global_pool,1,sizeof(ns##_LINK_##name##_t)); \ + apr_hook_sort_register(#name,&_hooks.link_##name); \ + } \ + pHook=apr_array_push(_hooks.link_##name); \ + pHook->pFunc=pf; \ + pHook->aszPredecessors=aszPre; \ + pHook->aszSuccessors=aszSucc; \ + pHook->nOrder=nOrder; \ + pHook->szName=apr_hook_debug_current; \ + if(apr_hook_debug_enabled) \ + apr_hook_debug_show(#name,aszPre,aszSucc); \ + } \ + APR_IMPLEMENT_HOOK_GET_PROTO(ns,link,name) \ + { \ + return _hooks.link_##name; \ + } + +/** + * Implement a hook that has no return code, and therefore runs all of the + * registered functions + * @param ns The namespace prefix of the hook functions + * @param link The linkage declaration prefix of the hook + * @param name The name of the hook + * @param args_decl The declaration of the arguments for the hook + * @param args_use The names for the arguments for the hook + * @note The link prefix FOO corresponds to FOO_DECLARE() macros, which + * provide export linkage from the module that IMPLEMENTs the hook, and + * import linkage from external modules that link to the hook's module. + */ +#define APR_IMPLEMENT_EXTERNAL_HOOK_VOID(ns,link,name,args_decl,args_use) \ +APR_IMPLEMENT_EXTERNAL_HOOK_BASE(ns,link,name) \ +link##_DECLARE(void) ns##_run_##name args_decl \ + { \ + ns##_LINK_##name##_t *pHook; \ + int n; \ + APR_HOOK_INT_DCL_UD; \ +\ + APR_HOOK_PROBE_ENTRY(ud, ns, name, args_use); \ +\ + if(_hooks.link_##name) \ + { \ + pHook=(ns##_LINK_##name##_t *)_hooks.link_##name->elts; \ + for(n=0 ; n < _hooks.link_##name->nelts ; ++n) \ + { \ + APR_HOOK_PROBE_INVOKE(ud, ns, name, (char *)pHook[n].szName, args_use); \ + pHook[n].pFunc args_use; \ + APR_HOOK_PROBE_COMPLETE(ud, ns, name, (char *)pHook[n].szName, 0, args_use); \ + } \ + } \ +\ + APR_HOOK_PROBE_RETURN(ud, ns, name, 0, args_use); \ +\ + } + +/* FIXME: note that this returns ok when nothing is run. I suspect it should + really return decline, but that breaks Apache currently - Ben +*/ +/** + * Implement a hook that runs until one of the functions returns something + * other than OK or DECLINE + * @param ns The namespace prefix of the hook functions + * @param link The linkage declaration prefix of the hook + * @param ret Type to return + * @param name The name of the hook + * @param args_decl The declaration of the arguments for the hook + * @param args_use The names for the arguments for the hook + * @param ok Success value + * @param decline Decline value + * @note The link prefix FOO corresponds to FOO_DECLARE() macros, which + * provide export linkage from the module that IMPLEMENTs the hook, and + * import linkage from external modules that link to the hook's module. + */ +#define APR_IMPLEMENT_EXTERNAL_HOOK_RUN_ALL(ns,link,ret,name,args_decl,args_use,ok,decline) \ +APR_IMPLEMENT_EXTERNAL_HOOK_BASE(ns,link,name) \ +link##_DECLARE(ret) ns##_run_##name args_decl \ + { \ + ns##_LINK_##name##_t *pHook; \ + int n; \ + ret rv = ok; \ + APR_HOOK_INT_DCL_UD; \ +\ + APR_HOOK_PROBE_ENTRY(ud, ns, name, args_use); \ +\ + if(_hooks.link_##name) \ + { \ + pHook=(ns##_LINK_##name##_t *)_hooks.link_##name->elts; \ + for(n=0 ; n < _hooks.link_##name->nelts ; ++n) \ + { \ + APR_HOOK_PROBE_INVOKE(ud, ns, name, (char *)pHook[n].szName, args_use); \ + rv=pHook[n].pFunc args_use; \ + APR_HOOK_PROBE_COMPLETE(ud, ns, name, (char *)pHook[n].szName, rv, args_use); \ + if(rv != ok && rv != decline) \ + break; \ + rv = ok; \ + } \ + } \ +\ + APR_HOOK_PROBE_RETURN(ud, ns, name, rv, args_use); \ +\ + return rv; \ + } + + +/** + * Implement a hook that runs until the first function returns something + * other than the value of decline + * @param ns The namespace prefix of the hook functions + * @param link The linkage declaration prefix of the hook + * @param name The name of the hook + * @param ret Type to return + * @param args_decl The declaration of the arguments for the hook + * @param args_use The names for the arguments for the hook + * @param decline Decline value + * @note The link prefix FOO corresponds to FOO_DECLARE() macros, which + * provide export linkage from the module that IMPLEMENTs the hook, and + * import linkage from external modules that link to the hook's module. + */ +#define APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(ns,link,ret,name,args_decl,args_use,decline) \ +APR_IMPLEMENT_EXTERNAL_HOOK_BASE(ns,link,name) \ +link##_DECLARE(ret) ns##_run_##name args_decl \ + { \ + ns##_LINK_##name##_t *pHook; \ + int n; \ + ret rv = decline; \ + APR_HOOK_INT_DCL_UD; \ +\ + APR_HOOK_PROBE_ENTRY(ud, ns, name, args_use); \ +\ + if(_hooks.link_##name) \ + { \ + pHook=(ns##_LINK_##name##_t *)_hooks.link_##name->elts; \ + for(n=0 ; n < _hooks.link_##name->nelts ; ++n) \ + { \ + APR_HOOK_PROBE_INVOKE(ud, ns, name, (char *)pHook[n].szName, args_use); \ + rv=pHook[n].pFunc args_use; \ + APR_HOOK_PROBE_COMPLETE(ud, ns, name, (char *)pHook[n].szName, rv, args_use); \ +\ + if(rv != decline) \ + break; \ + } \ + } \ +\ + APR_HOOK_PROBE_RETURN(ud, ns, name, rv, args_use); \ +\ + return rv; \ + } + + /* Hook orderings */ +/** run this hook first, before ANYTHING */ +#define APR_HOOK_REALLY_FIRST (-10) +/** run this hook first */ +#define APR_HOOK_FIRST 0 +/** run this hook somewhere */ +#define APR_HOOK_MIDDLE 10 +/** run this hook after every other hook which is defined*/ +#define APR_HOOK_LAST 20 +/** run this hook last, after EVERYTHING */ +#define APR_HOOK_REALLY_LAST 30 + +/** + * The global pool used to allocate any memory needed by the hooks. + */ +APU_DECLARE_DATA extern apr_pool_t *apr_hook_global_pool; + +/** + * A global variable to determine if debugging information about the + * hooks functions should be printed. + */ +APU_DECLARE_DATA extern int apr_hook_debug_enabled; + +/** + * The name of the module that is currently registering a function. + */ +APU_DECLARE_DATA extern const char *apr_hook_debug_current; + +/** + * Register a hook function to be sorted. + * @param szHookName The name of the Hook the function is registered for + * @param aHooks The array which stores all of the functions for this hook + */ +APU_DECLARE(void) apr_hook_sort_register(const char *szHookName, + apr_array_header_t **aHooks); +/** + * Sort all of the registered functions for a given hook. + */ +APU_DECLARE(void) apr_hook_sort_all(void); + +/** + * Print all of the information about the current hook. This is used for + * debugging purposes. + * @param szName The name of the hook + * @param aszPre All of the functions in the predecessor array + * @param aszSucc All of the functions in the successor array + */ +APU_DECLARE(void) apr_hook_debug_show(const char *szName, + const char * const *aszPre, + const char * const *aszSucc); + +/** + * Remove all currently registered functions. + */ +APU_DECLARE(void) apr_hook_deregister_all(void); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_HOOKS_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_iconv.h b/c/dependencies/windows/apr/x64/include/apr_iconv.h new file mode 100644 index 00000000..81a0d315 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_iconv.h @@ -0,0 +1,150 @@ +/*- + * Copyright (c) 1999,2000 + * Konstantin Chuguev. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Konstantin Chuguev + * and its contributors. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + */ + +#ifndef APR_ICONV_H +#define APR_ICONV_H + +/** + * @file apr_iconv.h + * @brief APR-iconv substitute iconv library implementation + */ + +#include "apr.h" +#include "apr_pools.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_iconv substitute iconv implementation + * @ingroup APR-iconv + * @{ + */ + +/** + * API_DECLARE_EXPORT is defined when building the libapriconv dynamic + * library, so that all public symbols are exported. + * + * API_DECLARE_STATIC is defined when including the apriconv public headers, + * to provide static linkage when the dynamic library may be unavailable. + * + * API_DECLARE_STATIC and API_DECLARE_EXPORT are left undefined when + * including the apr-iconv public headers, to import and link the symbols + * from the dynamic libapriconv library and assure appropriate indirection + * and calling conventions at compile time. + */ + +#if defined(DOXYGEN) || !defined(WIN32) +/** + * The public apr-iconv functions are declared with API_DECLARE(), so they + * use the most portable calling convention. Public apr-iconv functions + * with variable arguments must use API_DECLARE_NONSTD(). + * + * @deffunc API_DECLARE(rettype) apr_func(args); + */ +#define API_DECLARE(type) type +/** + * The private apr-iconv functions are declared with API_DECLARE_NONSTD(), + * so they use the most optimal C language calling conventions. + * + * @deffunc API_DECLARE(rettype) apr_func(args); + */ +#define API_DECLARE_NONSTD(type) type +/** + * All exported apr-iconv variables are declared with API_DECLARE_DATA + * This assures the appropriate indirection is invoked at compile time. + * + * @deffunc API_DECLARE_DATA type apr_variable; + * @tip extern API_DECLARE_DATA type apr_variable; syntax is required for + * declarations within headers to properly import the variable. + */ +#define API_DECLARE_DATA +#elif defined(API_DECLARE_STATIC) +#define API_DECLARE(type) type __stdcall +#define API_DECLARE_NONSTD(type) type __cdecl +#define API_DECLARE_DATA +#elif defined(API_DECLARE_EXPORT) +#define API_DECLARE(type) __declspec(dllexport) type __stdcall +#define API_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define API_DECLARE_DATA __declspec(dllexport) +#else +#define API_DECLARE(type) __declspec(dllimport) type __stdcall +#define API_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define API_DECLARE_DATA __declspec(dllimport) +#endif + +/* + * apr_iconv_t: charset conversion descriptor type + */ +typedef void *apr_iconv_t; + +/* __BEGIN_DECLS */ + +/** + * Create a conversion descriptor. + * @param to name of charset to convert to. + * @param from name of charset of the input bytes. + * @param pool pool to alloc memory. + * @param cd conversion descriptor created in pool. + */ +API_DECLARE(apr_status_t) apr_iconv_open(const char *to, const char *from, + apr_pool_t *pool, apr_iconv_t *cd); +/** + * Perform character set conversion. + * @param cd conversion descriptor created by apr_iconv_open(). + * @param inbuf input buffer. + * @param inbytesleft bytes to convert. + * @param outbuf output buffer. + * @param outbytesleft space (in bytes) available in outbuf. + * @param translated number of input bytes converted. + */ +API_DECLARE(apr_status_t) apr_iconv(apr_iconv_t cd, + const char **inbuf, apr_size_t *inbytesleft, + char **outbuf, apr_size_t *outbytesleft, + apr_size_t *translated); +/** + * Deallocate descriptor for character set conversion. + * @param cd conversion descriptor. + * @param pool pool used in the apr_iconv_open(). + */ +API_DECLARE(apr_status_t) apr_iconv_close(apr_iconv_t cd, apr_pool_t *pool); + +/* __END_DECLS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_ICONV_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_inherit.h b/c/dependencies/windows/apr/x64/include/apr_inherit.h new file mode 100644 index 00000000..b9fe56fe --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_inherit.h @@ -0,0 +1,51 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_INHERIT_H +#define APR_INHERIT_H + +/** + * @file apr_inherit.h + * @brief APR File Handle Inheritance Helpers + * @remark This internal header includes internal declaration helpers + * for other headers to declare apr_foo_inherit_[un]set functions. + */ + +/** + * Prototype for type-specific declarations of apr_foo_inherit_set + * functions. + * @remark Doxygen unwraps this macro (via doxygen.conf) to provide + * actual help for each specific occurrence of apr_foo_inherit_set. + * @remark the linkage is specified for APR. It would be possible to expand + * the macros to support other linkages. + */ +#define APR_DECLARE_INHERIT_SET(type) \ + APR_DECLARE(apr_status_t) apr_##type##_inherit_set( \ + apr_##type##_t *the##type) + +/** + * Prototype for type-specific declarations of apr_foo_inherit_unset + * functions. + * @remark Doxygen unwraps this macro (via doxygen.conf) to provide + * actual help for each specific occurrence of apr_foo_inherit_unset. + * @remark the linkage is specified for APR. It would be possible to expand + * the macros to support other linkages. + */ +#define APR_DECLARE_INHERIT_UNSET(type) \ + APR_DECLARE(apr_status_t) apr_##type##_inherit_unset( \ + apr_##type##_t *the##type) + +#endif /* ! APR_INHERIT_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_ldap.h b/c/dependencies/windows/apr/x64/include/apr_ldap.h new file mode 100644 index 00000000..c1bd0d4b --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_ldap.h @@ -0,0 +1,197 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_ldap.h is generated from apr_ldap.h.in by configure -- do not edit apr_ldap.h + */ +/** + * @file apr_ldap.h + * @brief APR-UTIL LDAP + */ +#ifndef APU_LDAP_H +#define APU_LDAP_H + +/** + * @defgroup APR_Util_LDAP LDAP + * @ingroup APR_Util + * @{ + */ + +/* this will be defined if LDAP support was compiled into apr-util */ +#define APR_HAS_LDAP 1 + +/* identify the LDAP toolkit used */ +#define APR_HAS_NETSCAPE_LDAPSDK 0 +#define APR_HAS_SOLARIS_LDAPSDK 0 +#define APR_HAS_NOVELL_LDAPSDK 0 +#define APR_HAS_MOZILLA_LDAPSDK 0 +#define APR_HAS_OPENLDAP_LDAPSDK 0 +#define APR_HAS_MICROSOFT_LDAPSDK 1 +#define APR_HAS_TIVOLI_LDAPSDK 0 +#define APR_HAS_ZOS_LDAPSDK 0 +#define APR_HAS_OTHER_LDAPSDK 0 + + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/* + * The following #defines are DEPRECATED and should not be used for + * anything. They remain to maintain binary compatibility. + * The original code defined the OPENLDAP SDK as present regardless + * of what really was there, which was way bogus. In addition, the + * apr_ldap_url_parse*() functions have been rewritten specifically for + * APR, so the APR_HAS_LDAP_URL_PARSE macro is forced to zero. + */ +#if APR_HAS_TIVOLI_LDAPSDK +#define APR_HAS_LDAP_SSL 0 +#else +#define APR_HAS_LDAP_SSL 1 +#endif +#define APR_HAS_LDAP_URL_PARSE 0 + +#if APR_HAS_OPENLDAP_LDAPSDK && !defined(LDAP_DEPRECATED) +/* Ensure that the "deprecated" interfaces are still exposed + * with OpenLDAP >= 2.3; these were exposed by default in earlier + * releases. */ +#define LDAP_DEPRECATED 1 +#endif + +/* + * Include the standard LDAP header files. + */ + +#include + + +/* + * Detected standard functions + */ +#define APR_HAS_LDAPSSL_CLIENT_INIT 0 +#define APR_HAS_LDAPSSL_CLIENT_DEINIT 0 +#define APR_HAS_LDAPSSL_ADD_TRUSTED_CERT 0 +#define APR_HAS_LDAP_START_TLS_S 0 +#define APR_HAS_LDAP_SSLINIT 1 +#define APR_HAS_LDAPSSL_INIT 0 +#define APR_HAS_LDAPSSL_INSTALL_ROUTINES 0 + + +/* + * Make sure the secure LDAP port is defined + */ +#ifndef LDAPS_PORT +#define LDAPS_PORT 636 /* ldaps:/// default LDAP over TLS port */ +#endif + + +/* + * For ldap function calls that input a size limit on the number of returned elements + * Some SDKs do not have the define for LDAP_DEFAULT_LIMIT (-1) or LDAP_NO_LIMIT (0) + * LDAP_DEFAULT_LIMIT is preferred as it allows inheritance from whatever the SDK + * or process is configured for. + */ +#ifdef LDAP_DEFAULT_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_DEFAULT_LIMIT +#else +#ifdef LDAP_NO_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_NO_LIMIT +#endif +#endif + +#ifndef APR_LDAP_SIZELIMIT +#define APR_LDAP_SIZELIMIT 0 /* equivalent to LDAP_NO_LIMIT, and what goes on the wire */ +#endif + +/* + * z/OS is missing some defines + */ +#ifndef LDAP_VERSION_MAX +#define LDAP_VERSION_MAX LDAP_VERSION +#endif +#if APR_HAS_ZOS_LDAPSDK +#define LDAP_VENDOR_NAME "IBM z/OS" +#endif + +/* Note: Macros defining const casting has been removed in APR v1.0, + * pending real support for LDAP v2.0 toolkits. + * + * In the mean time, please use an LDAP v3.0 toolkit. + */ +#if LDAP_VERSION_MAX <= 2 +#error Support for LDAP v2.0 toolkits has been removed from apr-util. Please use an LDAP v3.0 toolkit. +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * This structure allows the C LDAP API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apr_ldap_err_t { + const char *reason; + const char *msg; + int rc; +} apr_ldap_err_t; + +#ifdef __cplusplus +} +#endif + +/* The MS SDK returns LDAP_UNAVAILABLE when the backend has closed the connection + * between LDAP calls. Protect with APR_HAS_MICROSOFT_LDAPSDK in case someone + * manually chooses another SDK on Windows + */ +#if APR_HAS_MICROSOFT_LDAPSDK +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN \ + || (s) == LDAP_UNAVAILABLE) +#else +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN) +#endif + +/* These symbols are not actually exported in a DSO build, but mapped into + * a private exported function array for apr_ldap_stub to bind dynamically. + * Rename them appropriately to protect the global namespace. + */ +#ifdef APU_DSO_LDAP_BUILD + +#define apr_ldap_info apr__ldap_info +#define apr_ldap_init apr__ldap_init +#define apr_ldap_ssl_init apr__ldap_ssl_init +#define apr_ldap_ssl_deinit apr__ldap_ssl_deinit +#define apr_ldap_get_option apr__ldap_get_option +#define apr_ldap_set_option apr__ldap_set_option +#define apr_ldap_rebind_init apr__ldap_rebind_init +#define apr_ldap_rebind_add apr__ldap_rebind_add +#define apr_ldap_rebind_remove apr__ldap_rebind_remove + +#define APU_DECLARE_LDAP(type) type +#else +#define APU_DECLARE_LDAP(type) APU_DECLARE(type) +#endif + +#include "apr_ldap_url.h" +#include "apr_ldap_init.h" +#include "apr_ldap_option.h" +#include "apr_ldap_rebind.h" + +/** @} */ +#endif /* APR_HAS_LDAP */ +#endif /* APU_LDAP_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_ldap.h.in b/c/dependencies/windows/apr/x64/include/apr_ldap.h.in new file mode 100644 index 00000000..6c62d601 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_ldap.h.in @@ -0,0 +1,197 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_ldap.h is generated from apr_ldap.h.in by configure -- do not edit apr_ldap.h + */ +/** + * @file apr_ldap.h + * @brief APR-UTIL LDAP + */ +#ifndef APU_LDAP_H +#define APU_LDAP_H + +/** + * @defgroup APR_Util_LDAP LDAP + * @ingroup APR_Util + * @{ + */ + +/* this will be defined if LDAP support was compiled into apr-util */ +#define APR_HAS_LDAP @apu_has_ldap@ + +/* identify the LDAP toolkit used */ +#define APR_HAS_NETSCAPE_LDAPSDK @apu_has_ldap_netscape@ +#define APR_HAS_SOLARIS_LDAPSDK @apu_has_ldap_solaris@ +#define APR_HAS_NOVELL_LDAPSDK @apu_has_ldap_novell@ +#define APR_HAS_MOZILLA_LDAPSDK @apu_has_ldap_mozilla@ +#define APR_HAS_OPENLDAP_LDAPSDK @apu_has_ldap_openldap@ +#define APR_HAS_MICROSOFT_LDAPSDK @apu_has_ldap_microsoft@ +#define APR_HAS_TIVOLI_LDAPSDK @apu_has_ldap_tivoli@ +#define APR_HAS_ZOS_LDAPSDK @apu_has_ldap_zos@ +#define APR_HAS_OTHER_LDAPSDK @apu_has_ldap_other@ + + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/* + * The following #defines are DEPRECATED and should not be used for + * anything. They remain to maintain binary compatibility. + * The original code defined the OPENLDAP SDK as present regardless + * of what really was there, which was way bogus. In addition, the + * apr_ldap_url_parse*() functions have been rewritten specifically for + * APR, so the APR_HAS_LDAP_URL_PARSE macro is forced to zero. + */ +#if APR_HAS_TIVOLI_LDAPSDK +#define APR_HAS_LDAP_SSL 0 +#else +#define APR_HAS_LDAP_SSL 1 +#endif +#define APR_HAS_LDAP_URL_PARSE 0 + +#if APR_HAS_OPENLDAP_LDAPSDK && !defined(LDAP_DEPRECATED) +/* Ensure that the "deprecated" interfaces are still exposed + * with OpenLDAP >= 2.3; these were exposed by default in earlier + * releases. */ +#define LDAP_DEPRECATED 1 +#endif + +/* + * Include the standard LDAP header files. + */ + +@lber_h@ +@ldap_h@ +@ldap_ssl_h@ + + +/* + * Detected standard functions + */ +#define APR_HAS_LDAPSSL_CLIENT_INIT @apu_has_ldapssl_client_init@ +#define APR_HAS_LDAPSSL_CLIENT_DEINIT @apu_has_ldapssl_client_deinit@ +#define APR_HAS_LDAPSSL_ADD_TRUSTED_CERT @apu_has_ldapssl_add_trusted_cert@ +#define APR_HAS_LDAP_START_TLS_S @apu_has_ldap_start_tls_s@ +#define APR_HAS_LDAP_SSLINIT @apu_has_ldap_sslinit@ +#define APR_HAS_LDAPSSL_INIT @apu_has_ldapssl_init@ +#define APR_HAS_LDAPSSL_INSTALL_ROUTINES @apu_has_ldapssl_install_routines@ + +/* + * Make sure the secure LDAP port is defined + */ +#ifndef LDAPS_PORT +#define LDAPS_PORT 636 /* ldaps:/// default LDAP over TLS port */ +#endif + +/* + * For ldap function calls that input a size limit on the number of returned elements + * Some SDKs do not have the define for LDAP_DEFAULT_LIMIT (-1) or LDAP_NO_LIMIT (0) + * LDAP_DEFAULT_LIMIT is preferred as it allows inheritance from whatever the SDK + * or process is configured for. + */ +#ifdef LDAP_DEFAULT_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_DEFAULT_LIMIT +#else +#ifdef LDAP_NO_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_NO_LIMIT +#endif +#endif + +#ifndef APR_LDAP_SIZELIMIT +#define APR_LDAP_SIZELIMIT 0 /* equivalent to LDAP_NO_LIMIT, and what goes on the wire */ +#endif + +/* + * z/OS is missing some defines + */ +#ifndef LDAP_VERSION_MAX +#define LDAP_VERSION_MAX LDAP_VERSION +#endif +#if APR_HAS_ZOS_LDAPSDK +#define LDAP_VENDOR_NAME "IBM z/OS" +#endif + +/* Note: Macros defining const casting has been removed in APR v1.0, + * pending real support for LDAP v2.0 toolkits. + * + * In the mean time, please use an LDAP v3.0 toolkit. + */ +#if LDAP_VERSION_MAX <= 2 +#error Support for LDAP v2.0 toolkits has been removed from apr-util. Please use an LDAP v3.0 toolkit. +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * This structure allows the C LDAP API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apr_ldap_err_t { + const char *reason; + const char *msg; + int rc; +} apr_ldap_err_t; + +#ifdef __cplusplus +} +#endif + +/* The MS SDK returns LDAP_UNAVAILABLE when the backend has closed the connection + * between LDAP calls. Protect with APR_HAS_MICROSOFT_LDAPSDK in case someone + * manually chooses another SDK on Windows + */ +#if APR_HAS_MICROSOFT_LDAPSDK +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN \ + || (s) == LDAP_UNAVAILABLE) +#else +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN) +#endif + +/* These symbols are not actually exported in a DSO build, but mapped into + * a private exported function array for apr_ldap_stub to bind dynamically. + * Rename them appropriately to protect the global namespace. + */ +#ifdef APU_DSO_LDAP_BUILD + +#define apr_ldap_info apr__ldap_info +#define apr_ldap_init apr__ldap_init +#define apr_ldap_ssl_init apr__ldap_ssl_init +#define apr_ldap_ssl_deinit apr__ldap_ssl_deinit +#define apr_ldap_get_option apr__ldap_get_option +#define apr_ldap_set_option apr__ldap_set_option +#define apr_ldap_rebind_init apr__ldap_rebind_init +#define apr_ldap_rebind_add apr__ldap_rebind_add +#define apr_ldap_rebind_remove apr__ldap_rebind_remove + +#define APU_DECLARE_LDAP(type) type +#else +#define APU_DECLARE_LDAP(type) APU_DECLARE(type) +#endif + +#include "apr_ldap_url.h" +#include "apr_ldap_init.h" +#include "apr_ldap_option.h" +#include "apr_ldap_rebind.h" + +#endif /* APR_HAS_LDAP */ +/** @} */ +#endif /* APU_LDAP_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_ldap.hnw b/c/dependencies/windows/apr/x64/include/apr_ldap.hnw new file mode 100644 index 00000000..2148c90f --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_ldap.hnw @@ -0,0 +1,158 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_ldap.h is generated from apr_ldap.h.in by configure -- do not edit apr_ldap.h + */ +/** + * @file apr_ldap.h + * @brief APR-UTIL LDAP + */ +#ifndef APU_LDAP_H +#define APU_LDAP_H + +/** + * @defgroup APR_Util_LDAP LDAP + * @ingroup APR_Util + * @{ + */ + +/* this will be defined if LDAP support was compiled into apr-util */ +#define APR_HAS_LDAP 1 + +/* identify the LDAP toolkit used */ +#define APR_HAS_NETSCAPE_LDAPSDK 0 +#define APR_HAS_SOLARIS_LDAPSDK 0 +#define APR_HAS_NOVELL_LDAPSDK 1 +#define APR_HAS_MOZILLA_LDAPSDK 0 +#define APR_HAS_OPENLDAP_LDAPSDK 0 +#define APR_HAS_MICROSOFT_LDAPSDK 0 +#define APR_HAS_OTHER_LDAPSDK 0 + + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/* + * The following #defines are DEPRECATED and should not be used for + * anything. They remain to maintain binary compatibility. + * The original code defined the OPENLDAP SDK as present regardless + * of what really was there, which was way bogus. In addition, the + * apr_ldap_url_parse*() functions have been rewritten specifically for + * APR, so the APR_HAS_LDAP_URL_PARSE macro is forced to zero. + */ +#define APR_HAS_LDAP_SSL 1 +#define APR_HAS_LDAP_URL_PARSE 0 + + +/* + * Include the standard LDAP header files. + */ + +#ifdef GENEXPORTS +#define LDAP_VERSION_MAX 3 +#define LDAP_INSUFFICIENT_ACCESS +#else +#include +#include +#if APR_HAS_LDAP_SSL +#include +#endif +#endif + + +/* + * Detected standard functions + */ +#define APR_HAS_LDAPSSL_CLIENT_INIT 1 +#define APR_HAS_LDAPSSL_CLIENT_DEINIT 1 +#define APR_HAS_LDAPSSL_ADD_TRUSTED_CERT 1 +#define APR_HAS_LDAP_START_TLS_S 0 +#define APR_HAS_LDAP_SSLINIT 0 +#define APR_HAS_LDAPSSL_INIT 1 +#define APR_HAS_LDAPSSL_INSTALL_ROUTINES 0 + + +/* + * Make sure the secure LDAP port is defined + */ +#ifndef LDAPS_PORT +#define LDAPS_PORT 636 /* ldaps:/// default LDAP over TLS port */ +#endif + + +/* Note: Macros defining const casting has been removed in APR v1.0, + * pending real support for LDAP v2.0 toolkits. + * + * In the mean time, please use an LDAP v3.0 toolkit. + */ +#if LDAP_VERSION_MAX <= 2 +#error Support for LDAP v2.0 toolkits has been removed from apr-util. Please use an LDAP v3.0 toolkit. +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * This structure allows the C LDAP API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apr_ldap_err_t { + const char *reason; + const char *msg; + int rc; +} apr_ldap_err_t; + +#ifdef __cplusplus +} +#endif + +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN) + +/* These symbols are not actually exported in a DSO build, but mapped into + * a private exported function array for apr_ldap_stub to bind dynamically. + * Rename them appropriately to protect the global namespace. + */ +#ifdef APU_DSO_LDAP_BUILD + +#define apr_ldap_info apr__ldap_info +#define apr_ldap_init apr__ldap_init +#define apr_ldap_ssl_init apr__ldap_ssl_init +#define apr_ldap_ssl_deinit apr__ldap_ssl_deinit +#define apr_ldap_get_option apr__ldap_get_option +#define apr_ldap_set_option apr__ldap_set_option +#define apr_ldap_rebind_init apr__ldap_rebind_init +#define apr_ldap_rebind_add apr__ldap_rebind_add +#define apr_ldap_rebind_remove apr__ldap_rebind_remove + +#define APU_DECLARE_LDAP(type) type +#else +#define APU_DECLARE_LDAP(type) APU_DECLARE(type) +#endif + +#include "apr_ldap_url.h" +#include "apr_ldap_init.h" +#include "apr_ldap_option.h" +#include "apr_ldap_rebind.h" + +/** @} */ +#endif /* APR_HAS_LDAP */ +#endif /* APU_LDAP_H */ + diff --git a/c/dependencies/windows/apr/x64/include/apr_ldap.hw b/c/dependencies/windows/apr/x64/include/apr_ldap.hw new file mode 100644 index 00000000..fcef8b17 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_ldap.hw @@ -0,0 +1,197 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_ldap.h is generated from apr_ldap.h.in by configure -- do not edit apr_ldap.h + */ +/** + * @file apr_ldap.h + * @brief APR-UTIL LDAP + */ +#ifndef APU_LDAP_H +#define APU_LDAP_H + +/** + * @defgroup APR_Util_LDAP LDAP + * @ingroup APR_Util + * @{ + */ + +/* this will be defined if LDAP support was compiled into apr-util */ +#define APR_HAS_LDAP 1 + +/* identify the LDAP toolkit used */ +#define APR_HAS_NETSCAPE_LDAPSDK 0 +#define APR_HAS_SOLARIS_LDAPSDK 0 +#define APR_HAS_NOVELL_LDAPSDK 0 +#define APR_HAS_MOZILLA_LDAPSDK 0 +#define APR_HAS_OPENLDAP_LDAPSDK 0 +#define APR_HAS_MICROSOFT_LDAPSDK 1 +#define APR_HAS_TIVOLI_LDAPSDK 0 +#define APR_HAS_ZOS_LDAPSDK 0 +#define APR_HAS_OTHER_LDAPSDK 0 + + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/* + * The following #defines are DEPRECATED and should not be used for + * anything. They remain to maintain binary compatibility. + * The original code defined the OPENLDAP SDK as present regardless + * of what really was there, which was way bogus. In addition, the + * apr_ldap_url_parse*() functions have been rewritten specifically for + * APR, so the APR_HAS_LDAP_URL_PARSE macro is forced to zero. + */ +#if APR_HAS_TIVOLI_LDAPSDK +#define APR_HAS_LDAP_SSL 0 +#else +#define APR_HAS_LDAP_SSL 1 +#endif +#define APR_HAS_LDAP_URL_PARSE 0 + +#if APR_HAS_OPENLDAP_LDAPSDK && !defined(LDAP_DEPRECATED) +/* Ensure that the "deprecated" interfaces are still exposed + * with OpenLDAP >= 2.3; these were exposed by default in earlier + * releases. */ +#define LDAP_DEPRECATED 1 +#endif + +/* + * Include the standard LDAP header files. + */ + +#include + + +/* + * Detected standard functions + */ +#define APR_HAS_LDAPSSL_CLIENT_INIT 0 +#define APR_HAS_LDAPSSL_CLIENT_DEINIT 0 +#define APR_HAS_LDAPSSL_ADD_TRUSTED_CERT 0 +#define APR_HAS_LDAP_START_TLS_S 0 +#define APR_HAS_LDAP_SSLINIT 1 +#define APR_HAS_LDAPSSL_INIT 0 +#define APR_HAS_LDAPSSL_INSTALL_ROUTINES 0 + + +/* + * Make sure the secure LDAP port is defined + */ +#ifndef LDAPS_PORT +#define LDAPS_PORT 636 /* ldaps:/// default LDAP over TLS port */ +#endif + + +/* + * For ldap function calls that input a size limit on the number of returned elements + * Some SDKs do not have the define for LDAP_DEFAULT_LIMIT (-1) or LDAP_NO_LIMIT (0) + * LDAP_DEFAULT_LIMIT is preferred as it allows inheritance from whatever the SDK + * or process is configured for. + */ +#ifdef LDAP_DEFAULT_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_DEFAULT_LIMIT +#else +#ifdef LDAP_NO_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_NO_LIMIT +#endif +#endif + +#ifndef APR_LDAP_SIZELIMIT +#define APR_LDAP_SIZELIMIT 0 /* equivalent to LDAP_NO_LIMIT, and what goes on the wire */ +#endif + +/* + * z/OS is missing some defines + */ +#ifndef LDAP_VERSION_MAX +#define LDAP_VERSION_MAX LDAP_VERSION +#endif +#if APR_HAS_ZOS_LDAPSDK +#define LDAP_VENDOR_NAME "IBM z/OS" +#endif + +/* Note: Macros defining const casting has been removed in APR v1.0, + * pending real support for LDAP v2.0 toolkits. + * + * In the mean time, please use an LDAP v3.0 toolkit. + */ +#if LDAP_VERSION_MAX <= 2 +#error Support for LDAP v2.0 toolkits has been removed from apr-util. Please use an LDAP v3.0 toolkit. +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * This structure allows the C LDAP API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apr_ldap_err_t { + const char *reason; + const char *msg; + int rc; +} apr_ldap_err_t; + +#ifdef __cplusplus +} +#endif + +/* The MS SDK returns LDAP_UNAVAILABLE when the backend has closed the connection + * between LDAP calls. Protect with APR_HAS_MICROSOFT_LDAPSDK in case someone + * manually chooses another SDK on Windows + */ +#if APR_HAS_MICROSOFT_LDAPSDK +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN \ + || (s) == LDAP_UNAVAILABLE) +#else +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN) +#endif + +/* These symbols are not actually exported in a DSO build, but mapped into + * a private exported function array for apr_ldap_stub to bind dynamically. + * Rename them appropriately to protect the global namespace. + */ +#ifdef APU_DSO_LDAP_BUILD + +#define apr_ldap_info apr__ldap_info +#define apr_ldap_init apr__ldap_init +#define apr_ldap_ssl_init apr__ldap_ssl_init +#define apr_ldap_ssl_deinit apr__ldap_ssl_deinit +#define apr_ldap_get_option apr__ldap_get_option +#define apr_ldap_set_option apr__ldap_set_option +#define apr_ldap_rebind_init apr__ldap_rebind_init +#define apr_ldap_rebind_add apr__ldap_rebind_add +#define apr_ldap_rebind_remove apr__ldap_rebind_remove + +#define APU_DECLARE_LDAP(type) type +#else +#define APU_DECLARE_LDAP(type) APU_DECLARE(type) +#endif + +#include "apr_ldap_url.h" +#include "apr_ldap_init.h" +#include "apr_ldap_option.h" +#include "apr_ldap_rebind.h" + +/** @} */ +#endif /* APR_HAS_LDAP */ +#endif /* APU_LDAP_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_ldap.hwc b/c/dependencies/windows/apr/x64/include/apr_ldap.hwc new file mode 100644 index 00000000..4d07b296 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_ldap.hwc @@ -0,0 +1,197 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_ldap.h is generated from apr_ldap.h.in by configure -- do not edit apr_ldap.h + */ +/** + * @file apr_ldap.h + * @brief APR-UTIL LDAP + */ +#ifndef APU_LDAP_H +#define APU_LDAP_H + +/** + * @defgroup APR_Util_LDAP LDAP + * @ingroup APR_Util + * @{ + */ + +/* this will be defined if LDAP support was compiled into apr-util */ +#define APR_HAS_LDAP @apr_has_ldap_10@ + +/* identify the LDAP toolkit used */ +#define APR_HAS_NETSCAPE_LDAPSDK 0 +#define APR_HAS_SOLARIS_LDAPSDK 0 +#define APR_HAS_NOVELL_LDAPSDK 0 +#define APR_HAS_MOZILLA_LDAPSDK 0 +#define APR_HAS_OPENLDAP_LDAPSDK 0 +#define APR_HAS_MICROSOFT_LDAPSDK 1 +#define APR_HAS_TIVOLI_LDAPSDK 0 +#define APR_HAS_ZOS_LDAPSDK 0 +#define APR_HAS_OTHER_LDAPSDK 0 + + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/* + * The following #defines are DEPRECATED and should not be used for + * anything. They remain to maintain binary compatibility. + * The original code defined the OPENLDAP SDK as present regardless + * of what really was there, which was way bogus. In addition, the + * apr_ldap_url_parse*() functions have been rewritten specifically for + * APR, so the APR_HAS_LDAP_URL_PARSE macro is forced to zero. + */ +#if APR_HAS_TIVOLI_LDAPSDK +#define APR_HAS_LDAP_SSL 0 +#else +#define APR_HAS_LDAP_SSL 1 +#endif +#define APR_HAS_LDAP_URL_PARSE 0 + +#if APR_HAS_OPENLDAP_LDAPSDK && !defined(LDAP_DEPRECATED) +/* Ensure that the "deprecated" interfaces are still exposed + * with OpenLDAP >= 2.3; these were exposed by default in earlier + * releases. */ +#define LDAP_DEPRECATED 1 +#endif + +/* + * Include the standard LDAP header files. + */ + +#include + + +/* + * Detected standard functions + */ +#define APR_HAS_LDAPSSL_CLIENT_INIT 0 +#define APR_HAS_LDAPSSL_CLIENT_DEINIT 0 +#define APR_HAS_LDAPSSL_ADD_TRUSTED_CERT 0 +#define APR_HAS_LDAP_START_TLS_S 0 +#define APR_HAS_LDAP_SSLINIT 1 +#define APR_HAS_LDAPSSL_INIT 0 +#define APR_HAS_LDAPSSL_INSTALL_ROUTINES 0 + + +/* + * Make sure the secure LDAP port is defined + */ +#ifndef LDAPS_PORT +#define LDAPS_PORT 636 /* ldaps:/// default LDAP over TLS port */ +#endif + + +/* + * For ldap function calls that input a size limit on the number of returned elements + * Some SDKs do not have the define for LDAP_DEFAULT_LIMIT (-1) or LDAP_NO_LIMIT (0) + * LDAP_DEFAULT_LIMIT is preferred as it allows inheritance from whatever the SDK + * or process is configured for. + */ +#ifdef LDAP_DEFAULT_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_DEFAULT_LIMIT +#else +#ifdef LDAP_NO_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_NO_LIMIT +#endif +#endif + +#ifndef APR_LDAP_SIZELIMIT +#define APR_LDAP_SIZELIMIT 0 /* equivalent to LDAP_NO_LIMIT, and what goes on the wire */ +#endif + +/* + * z/OS is missing some defines + */ +#ifndef LDAP_VERSION_MAX +#define LDAP_VERSION_MAX LDAP_VERSION +#endif +#if APR_HAS_ZOS_LDAPSDK +#define LDAP_VENDOR_NAME "IBM z/OS" +#endif + +/* Note: Macros defining const casting has been removed in APR v1.0, + * pending real support for LDAP v2.0 toolkits. + * + * In the mean time, please use an LDAP v3.0 toolkit. + */ +#if LDAP_VERSION_MAX <= 2 +#error Support for LDAP v2.0 toolkits has been removed from apr-util. Please use an LDAP v3.0 toolkit. +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * This structure allows the C LDAP API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apr_ldap_err_t { + const char *reason; + const char *msg; + int rc; +} apr_ldap_err_t; + +#ifdef __cplusplus +} +#endif + +/* The MS SDK returns LDAP_UNAVAILABLE when the backend has closed the connection + * between LDAP calls. Protect with APR_HAS_MICROSOFT_LDAPSDK in case someone + * manually chooses another SDK on Windows + */ +#if APR_HAS_MICROSOFT_LDAPSDK +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN \ + || (s) == LDAP_UNAVAILABLE) +#else +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN) +#endif + +/* These symbols are not actually exported in a DSO build, but mapped into + * a private exported function array for apr_ldap_stub to bind dynamically. + * Rename them appropriately to protect the global namespace. + */ +#ifdef APU_DSO_LDAP_BUILD + +#define apr_ldap_info apr__ldap_info +#define apr_ldap_init apr__ldap_init +#define apr_ldap_ssl_init apr__ldap_ssl_init +#define apr_ldap_ssl_deinit apr__ldap_ssl_deinit +#define apr_ldap_get_option apr__ldap_get_option +#define apr_ldap_set_option apr__ldap_set_option +#define apr_ldap_rebind_init apr__ldap_rebind_init +#define apr_ldap_rebind_add apr__ldap_rebind_add +#define apr_ldap_rebind_remove apr__ldap_rebind_remove + +#define APU_DECLARE_LDAP(type) type +#else +#define APU_DECLARE_LDAP(type) APU_DECLARE(type) +#endif + +#include "apr_ldap_url.h" +#include "apr_ldap_init.h" +#include "apr_ldap_option.h" +#include "apr_ldap_rebind.h" + +/** @} */ +#endif /* APR_HAS_LDAP */ +#endif /* APU_LDAP_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_ldap_init.h b/c/dependencies/windows/apr/x64/include/apr_ldap_init.h new file mode 100644 index 00000000..aeb6d9bb --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_ldap_init.h @@ -0,0 +1,165 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_ldap_init.h + * @brief APR-UTIL LDAP ldap_init() functions + */ +#ifndef APR_LDAP_INIT_H +#define APR_LDAP_INIT_H + +/** + * @addtogroup APR_Util_LDAP + * @{ + */ + +#include "apr_ldap.h" + +#if APR_HAS_LDAP + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + + +/** + * Macro to detect security related return values. + */ +#if defined(LDAP_INSUFFICIENT_ACCESS) +#define APU_LDAP_INSUFFICIENT_ACCESS LDAP_INSUFFICIENT_ACCESS +#elif defined(LDAP_INSUFFICIENT_RIGHTS) +#define APU_LDAP_INSUFFICIENT_ACCESS LDAP_INSUFFICIENT_RIGHTS +#elif defined(APR_HAS_MICROSOFT_LDAPSDK) +/* The macros above fail to contemplate that LDAP_RETCODE values + * may be represented by an enum. autoconf tests would be much + * more robust. + */ +#define APU_LDAP_INSUFFICIENT_ACCESS LDAP_INSUFFICIENT_RIGHTS +#else +#error The security return codes must be added to support this LDAP toolkit. +#endif + +#if defined(LDAP_SECURITY_ERROR) +#define APU_LDAP_SECURITY_ERROR LDAP_SECURITY_ERROR +#else +#define APU_LDAP_SECURITY_ERROR(n) \ + (LDAP_INAPPROPRIATE_AUTH == n) ? 1 \ + : (LDAP_INVALID_CREDENTIALS == n) ? 1 \ + : (APU_LDAP_INSUFFICIENT_ACCESS == n) ? 1 \ + : 0 +#endif + + +/** + * APR LDAP SSL Initialise function + * + * This function initialises SSL on the underlying LDAP toolkit + * if this is necessary. + * + * If a CA certificate is provided, this is set, however the setting + * of certificates via this method has been deprecated and will be removed in + * APR v2.0. + * + * The apr_ldap_set_option() function with the APR_LDAP_OPT_TLS_CERT option + * should be used instead to set certificates. + * + * If SSL support is not available on this platform, or a problem + * was encountered while trying to set the certificate, the function + * will return APR_EGENERAL. Further LDAP specific error information + * can be found in result_err. + * @param pool The pool to use + * @param cert_auth_file The name of the certificate to use, can be NULL + * @param cert_file_type The type of certificate specified. See the + * apr_ldap_set_option() APR_LDAP_OPT_TLS_CERT option for details. + * @param result_err The returned result + */ +APU_DECLARE_LDAP(int) apr_ldap_ssl_init(apr_pool_t *pool, + const char *cert_auth_file, + int cert_file_type, + apr_ldap_err_t **result_err); + +/** + * APR LDAP SSL De-Initialise function + * + * This function tears down any SSL certificate setup previously + * set using apr_ldap_ssl_init(). It should be called to clean + * up if a graceful restart of a service is attempted. + * @todo currently we do not check whether apr_ldap_ssl_init() + * has been called first - we probably should. + */ +APU_DECLARE_LDAP(int) apr_ldap_ssl_deinit(void); + +/** + * APR LDAP initialise function + * + * This function is responsible for initialising an LDAP + * connection in a toolkit independant way. It does the + * job of ldap_init() from the C api. + * + * It handles both the SSL and non-SSL case, and attempts + * to hide the complexity setup from the user. This function + * assumes that any certificate setup necessary has already + * been done. + * + * If SSL or STARTTLS needs to be enabled, and the underlying + * toolkit supports it, the following values are accepted for + * secure: + * + * APR_LDAP_NONE: No encryption + * APR_LDAP_SSL: SSL encryption (ldaps://) + * APR_LDAP_STARTTLS: Force STARTTLS on ldap:// + * @remark The Novell toolkit is only able to set the SSL mode via this + * function. To work around this limitation, set the SSL mode here if no + * per connection client certificates are present, otherwise set secure + * APR_LDAP_NONE here, then set the per connection client certificates, + * followed by setting the SSL mode via apr_ldap_set_option(). As Novell + * does not support per connection client certificates, this problem is + * worked around while still being compatible with other LDAP toolkits. + * @param pool The pool to use + * @param ldap The LDAP handle + * @param hostname The name of the host to connect to. This can be either a + * DNS name, or an IP address. + * @param portno The port to connect to + * @param secure The security mode to set + * @param result_err The returned result + */ +APU_DECLARE_LDAP(int) apr_ldap_init(apr_pool_t *pool, + LDAP **ldap, + const char *hostname, + int portno, + int secure, + apr_ldap_err_t **result_err); + +/** + * APR LDAP info function + * + * This function returns a string describing the LDAP toolkit + * currently in use. The string is placed inside result_err->reason. + * @param pool The pool to use + * @param result_err The returned result + */ +APU_DECLARE_LDAP(int) apr_ldap_info(apr_pool_t *pool, + apr_ldap_err_t **result_err); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_HAS_LDAP */ + +/** @} */ + +#endif /* APR_LDAP_URL_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_ldap_option.h b/c/dependencies/windows/apr/x64/include/apr_ldap_option.h new file mode 100644 index 00000000..0ff8a862 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_ldap_option.h @@ -0,0 +1,254 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_ldap_option.h + * @brief APR-UTIL LDAP ldap_*_option() functions + */ +#ifndef APR_LDAP_OPTION_H +#define APR_LDAP_OPTION_H + +/** + * @addtogroup APR_Util_LDAP + * @{ + */ + +#include "apr_ldap.h" + +#if APR_HAS_LDAP + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* + * The following defines handle the different TLS certificate + * options available. If these options are missing, APR will try and + * emulate support for this using the deprecated ldap_start_tls_s() + * function. + */ +/** + * Set SSL mode to one of APR_LDAP_NONE, APR_LDAP_SSL, APR_LDAP_STARTTLS + * or APR_LDAP_STOPTLS. + */ +#define APR_LDAP_OPT_TLS 0x6fff +/** + * Set zero or more CA certificates, client certificates or private + * keys globally, or per connection (where supported). + */ +#define APR_LDAP_OPT_TLS_CERT 0x6ffe +/** + * Set the LDAP library to no verify the server certificate. This means + * all servers are considered trusted. + */ +#define APR_LDAP_OPT_VERIFY_CERT 0x6ffd +/** + * Set the LDAP library to indicate if referrals should be chased during + * LDAP searches. + */ +#define APR_LDAP_OPT_REFERRALS 0x6ffc +/** + * Set the LDAP library to indicate a maximum number of referral hops to + * chase before giving up on the search. + */ +#define APR_LDAP_OPT_REFHOPLIMIT 0x6ffb + +/** + * Structures for the apr_set_option() cases + */ + +/** + * APR_LDAP_OPT_TLS_CERT + * + * This structure includes possible options to set certificates on + * system initialisation. Different SDKs have different certificate + * requirements, and to achieve this multiple certificates must be + * specified at once passed as an (apr_array_header_t *). + * + * Netscape: + * Needs the CA cert database (cert7.db), the client cert database (key3.db) + * and the security module file (secmod.db) set at the system initialisation + * time. Three types are supported: APR_LDAP_CERT7_DB, APR_LDAP_KEY3_DB and + * APR_LDAP_SECMOD. + * + * To specify a client cert connection, a certificate nickname needs to be + * provided with a type of APR_LDAP_CERT. + * int ldapssl_enable_clientauth( LDAP *ld, char *keynickname, + * char *keypasswd, char *certnickname ); + * keynickname is currently not used, and should be set to "" + * + * Novell: + * Needs CA certificates and client certificates set at system initialisation + * time. Three types are supported: APR_LDAP_CA*, APR_LDAP_CERT* and + * APR_LDAP_KEY*. + * + * Certificates cannot be specified per connection. + * + * The functions used are: + * ldapssl_add_trusted_cert(serverTrustedRoot, serverTrustedRootEncoding); + * Clients certs and keys are set at system initialisation time with + * int ldapssl_set_client_cert ( + * void *cert, + * int type + * void *password); + * type can be LDAPSSL_CERT_FILETYPE_B64 or LDAPSSL_CERT_FILETYPE_DER + * ldapssl_set_client_private_key(clientPrivateKey, + * clientPrivateKeyEncoding, + * clientPrivateKeyPassword); + * + * OpenSSL: + * Needs one or more CA certificates to be set at system initialisation time + * with a type of APR_LDAP_CA*. + * + * May have one or more client certificates set per connection with a type of + * APR_LDAP_CERT*, and keys with APR_LDAP_KEY*. + */ +/** CA certificate type unknown */ +#define APR_LDAP_CA_TYPE_UNKNOWN 0 +/** binary DER encoded CA certificate */ +#define APR_LDAP_CA_TYPE_DER 1 +/** PEM encoded CA certificate */ +#define APR_LDAP_CA_TYPE_BASE64 2 +/** Netscape/Mozilla cert7.db CA certificate database */ +#define APR_LDAP_CA_TYPE_CERT7_DB 3 +/** Netscape/Mozilla secmod file */ +#define APR_LDAP_CA_TYPE_SECMOD 4 +/** Client certificate type unknown */ +#define APR_LDAP_CERT_TYPE_UNKNOWN 5 +/** binary DER encoded client certificate */ +#define APR_LDAP_CERT_TYPE_DER 6 +/** PEM encoded client certificate */ +#define APR_LDAP_CERT_TYPE_BASE64 7 +/** Netscape/Mozilla key3.db client certificate database */ +#define APR_LDAP_CERT_TYPE_KEY3_DB 8 +/** Netscape/Mozilla client certificate nickname */ +#define APR_LDAP_CERT_TYPE_NICKNAME 9 +/** Private key type unknown */ +#define APR_LDAP_KEY_TYPE_UNKNOWN 10 +/** binary DER encoded private key */ +#define APR_LDAP_KEY_TYPE_DER 11 +/** PEM encoded private key */ +#define APR_LDAP_KEY_TYPE_BASE64 12 +/** PKCS#12 encoded client certificate */ +#define APR_LDAP_CERT_TYPE_PFX 13 +/** PKCS#12 encoded private key */ +#define APR_LDAP_KEY_TYPE_PFX 14 +/** Openldap directory full of base64-encoded cert + * authorities with hashes in corresponding .0 directory + */ +#define APR_LDAP_CA_TYPE_CACERTDIR_BASE64 15 + + +/** + * Certificate structure. + * + * This structure is used to store certificate details. An array of + * these structures is passed to apr_ldap_set_option() to set CA + * and client certificates. + * @param type Type of certificate APR_LDAP_*_TYPE_* + * @param path Path, file or nickname of the certificate + * @param password Optional password, can be NULL + */ +typedef struct apr_ldap_opt_tls_cert_t apr_ldap_opt_tls_cert_t; +struct apr_ldap_opt_tls_cert_t { + int type; + const char *path; + const char *password; +}; + +/** + * APR_LDAP_OPT_TLS + * + * This sets the SSL level on the LDAP handle. + * + * Netscape/Mozilla: + * Supports SSL, but not STARTTLS + * SSL is enabled by calling ldapssl_install_routines(). + * + * Novell: + * Supports SSL and STARTTLS. + * SSL is enabled by calling ldapssl_install_routines(). Note that calling + * other ldap functions before ldapssl_install_routines() may cause this + * function to fail. + * STARTTLS is enabled by calling ldapssl_start_tls_s() after calling + * ldapssl_install_routines() (check this). + * + * OpenLDAP: + * Supports SSL and supports STARTTLS, but none of this is documented: + * http://www.openldap.org/lists/openldap-software/200409/msg00618.html + * Documentation for both SSL support and STARTTLS has been deleted from + * the OpenLDAP documentation and website. + */ + +/** No encryption */ +#define APR_LDAP_NONE 0 +/** SSL encryption (ldaps://) */ +#define APR_LDAP_SSL 1 +/** TLS encryption (STARTTLS) */ +#define APR_LDAP_STARTTLS 2 +/** end TLS encryption (STOPTLS) */ +#define APR_LDAP_STOPTLS 3 + +/** + * APR LDAP get option function + * + * This function gets option values from a given LDAP session if + * one was specified. It maps to the native ldap_get_option() function. + * @param pool The pool to use + * @param ldap The LDAP handle + * @param option The LDAP_OPT_* option to return + * @param outvalue The value returned (if any) + * @param result_err The apr_ldap_err_t structure contained detailed results + * of the operation. + */ +APU_DECLARE_LDAP(int) apr_ldap_get_option(apr_pool_t *pool, + LDAP *ldap, + int option, + void *outvalue, + apr_ldap_err_t **result_err); + +/** + * APR LDAP set option function + * + * This function sets option values to a given LDAP session if + * one was specified. It maps to the native ldap_set_option() function. + * + * Where an option is not supported by an LDAP toolkit, this function + * will try and apply legacy functions to achieve the same effect, + * depending on the platform. + * @param pool The pool to use + * @param ldap The LDAP handle + * @param option The LDAP_OPT_* option to set + * @param invalue The value to set + * @param result_err The apr_ldap_err_t structure contained detailed results + * of the operation. + */ +APU_DECLARE_LDAP(int) apr_ldap_set_option(apr_pool_t *pool, + LDAP *ldap, + int option, + const void *invalue, + apr_ldap_err_t **result_err); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_HAS_LDAP */ + +/** @} */ + +#endif /* APR_LDAP_OPTION_H */ + diff --git a/c/dependencies/windows/apr/x64/include/apr_ldap_rebind.h b/c/dependencies/windows/apr/x64/include/apr_ldap_rebind.h new file mode 100644 index 00000000..342a17c3 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_ldap_rebind.h @@ -0,0 +1,98 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The APR LDAP rebind functions provide an implementation of + * a rebind procedure that can be used to allow clients to chase referrals, + * using the same credentials used to log in originally. + * + * Use of this implementation is optional. + * + * @file apr_ldap_rebind.h + * @brief Apache LDAP library + */ + +#ifndef APU_LDAP_REBIND_H +#define APU_LDAP_REBIND_H + +/** + * @addtogroup APR_Util_LDAP + * @{ + **/ + +#if defined(DOXYGEN) +#include "apr_ldap.h" +#endif + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/** + * APR LDAP initialize rebind lock + * + * This function creates the lock for controlling access to the xref list.. + * @param pool Pool to use when creating the xref_lock. + */ +APU_DECLARE_LDAP(apr_status_t) apr_ldap_rebind_init(apr_pool_t *pool); + + +/** + * APR LDAP rebind_add function + * + * This function creates a cross reference entry for the specified ldap + * connection. The rebind callback function will look up this ldap + * connection so it can retrieve the bindDN and bindPW for use in any + * binds while referrals are being chased. + * + * This function will add the callback to the LDAP handle passed in. + * + * A cleanup is registered within the pool provided to remove this + * entry when the pool is removed. Alternatively apr_ldap_rebind_remove() + * can be called to explicitly remove the entry at will. + * + * @param pool The pool to use + * @param ld The LDAP connectionhandle + * @param bindDN The bind DN to be used for any binds while chasing + * referrals on this ldap connection. + * @param bindPW The bind Password to be used for any binds while + * chasing referrals on this ldap connection. + */ +APU_DECLARE_LDAP(apr_status_t) apr_ldap_rebind_add(apr_pool_t *pool, + LDAP *ld, + const char *bindDN, + const char *bindPW); + +/** + * APR LDAP rebind_remove function + * + * This function removes the rebind cross reference entry for the + * specified ldap connection. + * + * If not explicitly removed, this function will be called automatically + * when the pool is cleaned up. + * + * @param ld The LDAP connectionhandle + */ +APU_DECLARE_LDAP(apr_status_t) apr_ldap_rebind_remove(LDAP *ld); + +#endif /* APR_HAS_LDAP */ + +/** @} */ + +#endif /* APU_LDAP_REBIND_H */ + diff --git a/c/dependencies/windows/apr/x64/include/apr_ldap_url.h b/c/dependencies/windows/apr/x64/include/apr_ldap_url.h new file mode 100644 index 00000000..a71f5b3c --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_ldap_url.h @@ -0,0 +1,120 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_ldap_url.h + * @brief APR-UTIL LDAP ldap_init() functions + */ +#ifndef APR_LDAP_URL_H +#define APR_LDAP_URL_H + +/** + * @addtogroup APR_Util_LDAP + * @{ + */ + +#if defined(DOXYGEN) +#include "apr_ldap.h" +#endif + +#if APR_HAS_LDAP + +#include "apu.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** Structure to access an exploded LDAP URL */ +typedef struct apr_ldap_url_desc_t { + struct apr_ldap_url_desc_t *lud_next; + char *lud_scheme; + char *lud_host; + int lud_port; + char *lud_dn; + char **lud_attrs; + int lud_scope; + char *lud_filter; + char **lud_exts; + int lud_crit_exts; +} apr_ldap_url_desc_t; + +#ifndef APR_LDAP_URL_SUCCESS +#define APR_LDAP_URL_SUCCESS 0x00 /* Success */ +#define APR_LDAP_URL_ERR_MEM 0x01 /* can't allocate memory space */ +#define APR_LDAP_URL_ERR_PARAM 0x02 /* parameter is bad */ +#define APR_LDAP_URL_ERR_BADSCHEME 0x03 /* URL doesn't begin with "ldap[si]://" */ +#define APR_LDAP_URL_ERR_BADENCLOSURE 0x04 /* URL is missing trailing ">" */ +#define APR_LDAP_URL_ERR_BADURL 0x05 /* URL is bad */ +#define APR_LDAP_URL_ERR_BADHOST 0x06 /* host port is bad */ +#define APR_LDAP_URL_ERR_BADATTRS 0x07 /* bad (or missing) attributes */ +#define APR_LDAP_URL_ERR_BADSCOPE 0x08 /* scope string is invalid (or missing) */ +#define APR_LDAP_URL_ERR_BADFILTER 0x09 /* bad or missing filter */ +#define APR_LDAP_URL_ERR_BADEXTS 0x0a /* bad or missing extensions */ +#endif + +/** + * Is this URL an ldap url? ldap:// + * @param url The url to test + */ +APU_DECLARE(int) apr_ldap_is_ldap_url(const char *url); + +/** + * Is this URL an SSL ldap url? ldaps:// + * @param url The url to test + */ +APU_DECLARE(int) apr_ldap_is_ldaps_url(const char *url); + +/** + * Is this URL an ldap socket url? ldapi:// + * @param url The url to test + */ +APU_DECLARE(int) apr_ldap_is_ldapi_url(const char *url); + +/** + * Parse an LDAP URL. + * @param pool The pool to use + * @param url_in The URL to parse + * @param ludpp The structure to return the exploded URL + * @param result_err The result structure of the operation + */ +APU_DECLARE(int) apr_ldap_url_parse_ext(apr_pool_t *pool, + const char *url_in, + apr_ldap_url_desc_t **ludpp, + apr_ldap_err_t **result_err); + +/** + * Parse an LDAP URL. + * @param pool The pool to use + * @param url_in The URL to parse + * @param ludpp The structure to return the exploded URL + * @param result_err The result structure of the operation + */ +APU_DECLARE(int) apr_ldap_url_parse(apr_pool_t *pool, + const char *url_in, + apr_ldap_url_desc_t **ludpp, + apr_ldap_err_t **result_err); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_HAS_LDAP */ + +/** @} */ + +#endif /* APR_LDAP_URL_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_lib.h b/c/dependencies/windows/apr/x64/include/apr_lib.h new file mode 100644 index 00000000..466e8185 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_lib.h @@ -0,0 +1,241 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_LIB_H +#define APR_LIB_H + +/** + * @file apr_lib.h + * This is collection of oddballs that didn't fit anywhere else, + * and might move to more appropriate headers with the release + * of APR 1.0. + * @brief APR general purpose library routines + */ + +#include "apr.h" +#include "apr_errno.h" + +#if APR_HAVE_CTYPE_H +#include +#endif +#if APR_HAVE_STDARG_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_lib General Purpose Library Routines + * @ingroup APR + * This is collection of oddballs that didn't fit anywhere else, + * and might move to more appropriate headers with the release + * of APR 1.0. + * @{ + */ + +/** A constant representing a 'large' string. */ +#define HUGE_STRING_LEN 8192 + +/* + * Define the structures used by the APR general-purpose library. + */ + +/** @see apr_vformatter_buff_t */ +typedef struct apr_vformatter_buff_t apr_vformatter_buff_t; + +/** + * Structure used by the variable-formatter routines. + */ +struct apr_vformatter_buff_t { + /** The current position */ + char *curpos; + /** The end position of the format string */ + char *endpos; +}; + +/** + * return the final element of the pathname + * @param pathname The path to get the final element of + * @return the final element of the path + * @remark + *
+ * For example:
+ *                 "/foo/bar/gum"    -> "gum"
+ *                 "/foo/bar/gum/"   -> ""
+ *                 "gum"             -> "gum"
+ *                 "bs\\path\\stuff" -> "stuff"
+ * 
+ */ +APR_DECLARE(const char *) apr_filepath_name_get(const char *pathname); + +/** + * apr_killpg + * Small utility macros to make things easier to read. Not usually a + * goal, to be sure.. + */ + +#ifdef WIN32 +#define apr_killpg(x, y) +#else /* WIN32 */ +#ifdef NO_KILLPG +#define apr_killpg(x, y) (kill (-(x), (y))) +#else /* NO_KILLPG */ +#define apr_killpg(x, y) (killpg ((x), (y))) +#endif /* NO_KILLPG */ +#endif /* WIN32 */ + +/** + * apr_vformatter() is a generic printf-style formatting routine + * with some extensions. + * @param flush_func The function to call when the buffer is full + * @param c The buffer to write to + * @param fmt The format string + * @param ap The arguments to use to fill out the format string. + * + * @remark + *
+ * The extensions are:
+ *
+ * - %%pA takes a struct in_addr *, and prints it as a.b.c.d
+ * - %%pI takes an apr_sockaddr_t * and prints it as a.b.c.d:port or
+ * \[ipv6-address\]:port
+ * - %%pT takes an apr_os_thread_t * and prints it in decimal
+ * ('0' is printed if !APR_HAS_THREADS)
+ * - %%pt takes an apr_os_thread_t * and prints it in hexadecimal
+ * ('0' is printed if !APR_HAS_THREADS)
+ * - %%pm takes an apr_status_t * and prints the appropriate error
+ * string (from apr_strerror) corresponding to that error code.
+ * - %%pp takes a void * and outputs it in hex
+ * - %%pB takes a apr_uint32_t * as bytes and outputs it's apr_strfsize
+ * - %%pF same as above, but takes a apr_off_t *
+ * - %%pS same as above, but takes a apr_size_t *
+ *
+ * %%pA, %%pI, %%pT, %%pp are available from APR 1.0.0 onwards (and in 0.9.x).
+ * %%pt is only available from APR 1.2.0 onwards.
+ * %%pm, %%pB, %%pF and %%pS are only available from APR 1.3.0 onwards.
+ *
+ * The %%p hacks are to force gcc's printf warning code to skip
+ * over a pointer argument without complaining.  This does
+ * mean that the ANSI-style %%p (output a void * in hex format) won't
+ * work as expected at all, but that seems to be a fair trade-off
+ * for the increased robustness of having printf-warnings work.
+ *
+ * Additionally, apr_vformatter allows for arbitrary output methods
+ * using the apr_vformatter_buff and flush_func.
+ *
+ * The apr_vformatter_buff has two elements curpos and endpos.
+ * curpos is where apr_vformatter will write the next byte of output.
+ * It proceeds writing output to curpos, and updating curpos, until
+ * either the end of output is reached, or curpos == endpos (i.e. the
+ * buffer is full).
+ *
+ * If the end of output is reached, apr_vformatter returns the
+ * number of bytes written.
+ *
+ * When the buffer is full, the flush_func is called.  The flush_func
+ * can return -1 to indicate that no further output should be attempted,
+ * and apr_vformatter will return immediately with -1.  Otherwise
+ * the flush_func should flush the buffer in whatever manner is
+ * appropriate, re apr_pool_t nitialize curpos and endpos, and return 0.
+ *
+ * Note that flush_func is only invoked as a result of attempting to
+ * write another byte at curpos when curpos >= endpos.  So for
+ * example, it's possible when the output exactly matches the buffer
+ * space available that curpos == endpos will be true when
+ * apr_vformatter returns.
+ *
+ * apr_vformatter does not call out to any other code, it is entirely
+ * self-contained.  This allows the callers to do things which are
+ * otherwise "unsafe".  For example, apr_psprintf uses the "scratch"
+ * space at the unallocated end of a block, and doesn't actually
+ * complete the allocation until apr_vformatter returns.  apr_psprintf
+ * would be completely broken if apr_vformatter were to call anything
+ * that used this same pool.  Similarly http_bprintf() uses the "scratch"
+ * space at the end of its output buffer, and doesn't actually note
+ * that the space is in use until it either has to flush the buffer
+ * or until apr_vformatter returns.
+ * 
+ */ +APR_DECLARE(int) apr_vformatter(int (*flush_func)(apr_vformatter_buff_t *b), + apr_vformatter_buff_t *c, const char *fmt, + va_list ap); + +/** + * Display a prompt and read in the password from stdin. + * @param prompt The prompt to display + * @param pwbuf Buffer to store the password + * @param bufsize The length of the password buffer. + * @remark If the password entered must be truncated to fit in + * the provided buffer, APR_ENAMETOOLONG will be returned. + * Note that the bufsize paramater is passed by reference for no + * reason; its value will never be modified by the apr_password_get() + * function. + */ +APR_DECLARE(apr_status_t) apr_password_get(const char *prompt, char *pwbuf, + apr_size_t *bufsize); + +/** @} */ + +/** + * @defgroup apr_ctype ctype functions + * These macros allow correct support of 8-bit characters on systems which + * support 8-bit characters. Pretty dumb how the cast is required, but + * that's legacy libc for ya. These new macros do not support EOF like + * the standard macros do. Tough. + * @{ + */ +/** @see isalnum */ +#define apr_isalnum(c) (isalnum(((unsigned char)(c)))) +/** @see isalpha */ +#define apr_isalpha(c) (isalpha(((unsigned char)(c)))) +/** @see iscntrl */ +#define apr_iscntrl(c) (iscntrl(((unsigned char)(c)))) +/** @see isdigit */ +#define apr_isdigit(c) (isdigit(((unsigned char)(c)))) +/** @see isgraph */ +#define apr_isgraph(c) (isgraph(((unsigned char)(c)))) +/** @see islower*/ +#define apr_islower(c) (islower(((unsigned char)(c)))) +/** @see isascii */ +#ifdef isascii +#define apr_isascii(c) (isascii(((unsigned char)(c)))) +#else +#define apr_isascii(c) (((c) & ~0x7f)==0) +#endif +/** @see isprint */ +#define apr_isprint(c) (isprint(((unsigned char)(c)))) +/** @see ispunct */ +#define apr_ispunct(c) (ispunct(((unsigned char)(c)))) +/** @see isspace */ +#define apr_isspace(c) (isspace(((unsigned char)(c)))) +/** @see isupper */ +#define apr_isupper(c) (isupper(((unsigned char)(c)))) +/** @see isxdigit */ +#define apr_isxdigit(c) (isxdigit(((unsigned char)(c)))) +/** @see tolower */ +#define apr_tolower(c) (tolower(((unsigned char)(c)))) +/** @see toupper */ +#define apr_toupper(c) (toupper(((unsigned char)(c)))) + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_LIB_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_md4.h b/c/dependencies/windows/apr/x64/include/apr_md4.h new file mode 100644 index 00000000..43fb33e3 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_md4.h @@ -0,0 +1,135 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* This is derived from material copyright RSA Data Security, Inc. + * Their notice is reproduced below in its entirety. + * + * Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All + * rights reserved. + * + * License to copy and use this software is granted provided that it + * is identified as the "RSA Data Security, Inc. MD4 Message-Digest + * Algorithm" in all material mentioning or referencing this software + * or this function. + * + * License is also granted to make and use derivative works provided + * that such works are identified as "derived from the RSA Data + * Security, Inc. MD4 Message-Digest Algorithm" in all material + * mentioning or referencing the derived work. + * + * RSA Data Security, Inc. makes no representations concerning either + * the merchantability of this software or the suitability of this + * software for any particular purpose. It is provided "as is" + * without express or implied warranty of any kind. + * + * These notices must be retained in any copies of any part of this + * documentation and/or software. + */ + +#ifndef APR_MD4_H +#define APR_MD4_H + +#include "apu.h" +#include "apr_xlate.h" +/** + * @file apr_md4.h + * @brief APR-UTIL MD4 Library + */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_MD4 MD4 Library + * @ingroup APR_Util + * @{ + */ + +/** The digestsize for MD4 */ +#define APR_MD4_DIGESTSIZE 16 + +/** @see apr_md4_ctx_t */ +typedef struct apr_md4_ctx_t apr_md4_ctx_t; + +/** MD4 context. */ +struct apr_md4_ctx_t { + /** state (ABCD) */ + apr_uint32_t state[4]; + /** number of bits, modulo 2^64 (lsb first) */ + apr_uint32_t count[2]; + /** input buffer */ + unsigned char buffer[64]; +#if APR_HAS_XLATE + /** translation handle */ + apr_xlate_t *xlate; +#endif +}; + +/** + * MD4 Initialize. Begins an MD4 operation, writing a new context. + * @param context The MD4 context to initialize. + */ +APU_DECLARE(apr_status_t) apr_md4_init(apr_md4_ctx_t *context); + +#if APR_HAS_XLATE +/** + * MDr4 translation setup. Provides the APR translation handle to be used + * for translating the content before calculating the digest. + * @param context The MD4 content to set the translation for. + * @param xlate The translation handle to use for this MD4 context + */ +APU_DECLARE(apr_status_t) apr_md4_set_xlate(apr_md4_ctx_t *context, + apr_xlate_t *xlate); +#else +#define apr_md4_set_xlate(context, xlate) APR_ENOTIMPL +#endif + +/** + * MD4 block update operation. Continue an MD4 message-digest operation, + * processing another message block, and updating the context. + * @param context The MD4 content to update. + * @param input next message block to update + * @param inputLen The length of the next message block + */ +APU_DECLARE(apr_status_t) apr_md4_update(apr_md4_ctx_t *context, + const unsigned char *input, + apr_size_t inputLen); + +/** + * MD4 finalization. Ends an MD4 message-digest operation, writing the + * message digest and zeroing the context + * @param digest The final MD4 digest + * @param context The MD4 content we are finalizing. + */ +APU_DECLARE(apr_status_t) apr_md4_final( + unsigned char digest[APR_MD4_DIGESTSIZE], + apr_md4_ctx_t *context); + +/** + * MD4 digest computation + * @param digest The MD4 digest + * @param input message block to use + * @param inputLen The length of the message block + */ +APU_DECLARE(apr_status_t) apr_md4(unsigned char digest[APR_MD4_DIGESTSIZE], + const unsigned char *input, + apr_size_t inputLen); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_MD4_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_md5.h b/c/dependencies/windows/apr/x64/include/apr_md5.h new file mode 100644 index 00000000..e0202dfd --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_md5.h @@ -0,0 +1,176 @@ +/* + * This is work is derived from material Copyright RSA Data Security, Inc. + * + * The RSA copyright statement and Licence for that original material is + * included below. This is followed by the Apache copyright statement and + * licence for the modifications made to that material. + */ + +/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All + rights reserved. + + License to copy and use this software is granted provided that it + is identified as the "RSA Data Security, Inc. MD5 Message-Digest + Algorithm" in all material mentioning or referencing this software + or this function. + + License is also granted to make and use derivative works provided + that such works are identified as "derived from the RSA Data + Security, Inc. MD5 Message-Digest Algorithm" in all material + mentioning or referencing the derived work. + + RSA Data Security, Inc. makes no representations concerning either + the merchantability of this software or the suitability of this + software for any particular purpose. It is provided "as is" + without express or implied warranty of any kind. + + These notices must be retained in any copies of any part of this + documentation and/or software. + */ + +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_MD5_H +#define APR_MD5_H + +#include "apu.h" +#include "apr_xlate.h" + +#ifdef __cplusplus +extern "C" { +#endif +/** + * @file apr_md5.h + * @brief APR MD5 Routines + */ + +/** + * @defgroup APR_MD5 MD5 Routines + * @ingroup APR + * @{ + */ + +/** The MD5 digest size */ +#define APR_MD5_DIGESTSIZE 16 + +/** @see apr_md5_ctx_t */ +typedef struct apr_md5_ctx_t apr_md5_ctx_t; + +/** MD5 context. */ +struct apr_md5_ctx_t { + /** state (ABCD) */ + apr_uint32_t state[4]; + /** number of bits, modulo 2^64 (lsb first) */ + apr_uint32_t count[2]; + /** input buffer */ + unsigned char buffer[64]; + /** translation handle + * ignored if xlate is unsupported + */ + apr_xlate_t *xlate; +}; + +/** + * MD5 Initialize. Begins an MD5 operation, writing a new context. + * @param context The MD5 context to initialize. + */ +APU_DECLARE(apr_status_t) apr_md5_init(apr_md5_ctx_t *context); + +/** + * MD5 translation setup. Provides the APR translation handle to be used + * for translating the content before calculating the digest. + * @param context The MD5 content to set the translation for. + * @param xlate The translation handle to use for this MD5 context + */ +APU_DECLARE(apr_status_t) apr_md5_set_xlate(apr_md5_ctx_t *context, + apr_xlate_t *xlate); + +/** + * MD5 block update operation. Continue an MD5 message-digest operation, + * processing another message block, and updating the context. + * @param context The MD5 content to update. + * @param input next message block to update + * @param inputLen The length of the next message block + */ +APU_DECLARE(apr_status_t) apr_md5_update(apr_md5_ctx_t *context, + const void *input, + apr_size_t inputLen); + +/** + * MD5 finalization. Ends an MD5 message-digest operation, writing the + * message digest and zeroing the context + * @param digest The final MD5 digest + * @param context The MD5 content we are finalizing. + */ +APU_DECLARE(apr_status_t) apr_md5_final(unsigned char digest[APR_MD5_DIGESTSIZE], + apr_md5_ctx_t *context); + +/** + * MD5 in one step + * @param digest The final MD5 digest + * @param input The message block to use + * @param inputLen The length of the message block + */ +APU_DECLARE(apr_status_t) apr_md5(unsigned char digest[APR_MD5_DIGESTSIZE], + const void *input, + apr_size_t inputLen); + +/** + * Encode a password using an MD5 algorithm + * @param password The password to encode + * @param salt The salt string to use for the encoding + * @param result The string to store the encoded password in + * @param nbytes The size of the result buffer + */ +APU_DECLARE(apr_status_t) apr_md5_encode(const char *password, const char *salt, + char *result, apr_size_t nbytes); + +/** + * Encode a password using the bcrypt algorithm + * @param password The password to encode + * @param count The cost of the encoding, possible values are 4 to 31 + * @param salt Pointer to binary data to be used as salt for the encoding + * @param salt_len The size of the salt data (must be >= 16) + * @param out The string to store the encoded password in + * @param out_len The size of the result buffer (must be >= 61) + */ +APU_DECLARE(apr_status_t) apr_bcrypt_encode(const char *pw, + unsigned int count, + const unsigned char *salt, + apr_size_t salt_len, + char *out, apr_size_t out_len); + +/** + * Validate hashes created by APR-supported algorithms: md5, bcrypt, and sha1. + * hashes created by crypt are supported only on platforms that provide + * crypt(3), so don't rely on that function unless you know that your + * application will be run only on platforms that support it. On platforms + * that don't support crypt(3), this falls back to a clear text string + * comparison. + * @param passwd The password to validate + * @param hash The password to validate against + */ +APU_DECLARE(apr_status_t) apr_password_validate(const char *passwd, + const char *hash); + + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_MD5_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_memcache.h b/c/dependencies/windows/apr/x64/include/apr_memcache.h new file mode 100644 index 00000000..82878825 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_memcache.h @@ -0,0 +1,444 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_MEMCACHE_H +#define APR_MEMCACHE_H + +/** + * @file apr_memcache.h + * @brief Client interface for memcached + * @remark To use this interface you must have a separate memcached + * server running. See the memcached website at http://www.danga.com/memcached/ + * for more information. + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_time.h" +#include "apr_strings.h" +#include "apr_network_io.h" +#include "apr_ring.h" +#include "apr_buckets.h" +#include "apr_reslist.h" +#include "apr_hash.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_Util_MC Memcached Client Routines + * @ingroup APR_Util + * @{ + */ + +/** Specifies the status of a memcached server */ +typedef enum +{ + APR_MC_SERVER_LIVE, /**< Server is alive and responding to requests */ + APR_MC_SERVER_DEAD /**< Server is not responding to requests */ +} apr_memcache_server_status_t; + +/** Opaque memcache client connection object */ +typedef struct apr_memcache_conn_t apr_memcache_conn_t; + +/** Memcache Server Info Object */ +typedef struct apr_memcache_server_t apr_memcache_server_t; +struct apr_memcache_server_t +{ + const char *host; /**< Hostname of this Server */ + apr_port_t port; /**< Port of this Server */ + apr_memcache_server_status_t status; /**< @see apr_memcache_server_status_t */ +#if APR_HAS_THREADS || defined(DOXYGEN) + apr_reslist_t *conns; /**< Resource list of actual client connections */ +#else + apr_memcache_conn_t *conn; +#endif + apr_pool_t *p; /** Pool to use for private allocations */ +#if APR_HAS_THREADS + apr_thread_mutex_t *lock; +#endif + apr_time_t btime; +}; + +/* Custom hash callback function prototype, user for server selection. +* @param baton user selected baton +* @param data data to hash +* @param data_len length of data +*/ +typedef apr_uint32_t (*apr_memcache_hash_func)(void *baton, + const char *data, + const apr_size_t data_len); + +typedef struct apr_memcache_t apr_memcache_t; + +/* Custom Server Select callback function prototype. +* @param baton user selected baton +* @param mc memcache instance, use mc->live_servers to select a node +* @param hash hash of the selected key. +*/ +typedef apr_memcache_server_t* (*apr_memcache_server_func)(void *baton, + apr_memcache_t *mc, + const apr_uint32_t hash); + +/** Container for a set of memcached servers */ +struct apr_memcache_t +{ + apr_uint32_t flags; /**< Flags, Not currently used */ + apr_uint16_t nalloc; /**< Number of Servers Allocated */ + apr_uint16_t ntotal; /**< Number of Servers Added */ + apr_memcache_server_t **live_servers; /**< Array of Servers */ + apr_pool_t *p; /** Pool to use for allocations */ + void *hash_baton; + apr_memcache_hash_func hash_func; + void *server_baton; + apr_memcache_server_func server_func; +}; + +/** Returned Data from a multiple get */ +typedef struct +{ + apr_status_t status; + const char* key; + apr_size_t len; + char *data; + apr_uint16_t flags; +} apr_memcache_value_t; + +/** + * Creates a crc32 hash used to split keys between servers + * @param mc The memcache client object to use + * @param data Data to be hashed + * @param data_len Length of the data to use + * @return crc32 hash of data + * @remark The crc32 hash is not compatible with old memcached clients. + */ +APU_DECLARE(apr_uint32_t) apr_memcache_hash(apr_memcache_t *mc, + const char *data, + const apr_size_t data_len); + +/** + * Pure CRC32 Hash. Used by some clients. + */ +APU_DECLARE(apr_uint32_t) apr_memcache_hash_crc32(void *baton, + const char *data, + const apr_size_t data_len); + +/** + * hash compatible with the standard Perl Client. + */ +APU_DECLARE(apr_uint32_t) apr_memcache_hash_default(void *baton, + const char *data, + const apr_size_t data_len); + +/** + * Picks a server based on a hash + * @param mc The memcache client object to use + * @param hash Hashed value of a Key + * @return server that controls specified hash + * @see apr_memcache_hash + */ +APU_DECLARE(apr_memcache_server_t *) apr_memcache_find_server_hash(apr_memcache_t *mc, + const apr_uint32_t hash); + +/** + * server selection compatible with the standard Perl Client. + */ +APU_DECLARE(apr_memcache_server_t *) apr_memcache_find_server_hash_default(void *baton, + apr_memcache_t *mc, + const apr_uint32_t hash); + +/** + * Adds a server to a client object + * @param mc The memcache client object to use + * @param server Server to add + * @remark Adding servers is not thread safe, and should be done once at startup. + * @warning Changing servers after startup may cause keys to go to + * different servers. + */ +APU_DECLARE(apr_status_t) apr_memcache_add_server(apr_memcache_t *mc, + apr_memcache_server_t *server); + + +/** + * Finds a Server object based on a hostname/port pair + * @param mc The memcache client object to use + * @param host Hostname of the server + * @param port Port of the server + * @return Server with matching Hostname and Port, or NULL if none was found. + */ +APU_DECLARE(apr_memcache_server_t *) apr_memcache_find_server(apr_memcache_t *mc, + const char *host, + apr_port_t port); + +/** + * Enables a Server for use again + * @param mc The memcache client object to use + * @param ms Server to Activate + */ +APU_DECLARE(apr_status_t) apr_memcache_enable_server(apr_memcache_t *mc, + apr_memcache_server_t *ms); + + +/** + * Disable a Server + * @param mc The memcache client object to use + * @param ms Server to Disable + */ +APU_DECLARE(apr_status_t) apr_memcache_disable_server(apr_memcache_t *mc, + apr_memcache_server_t *ms); + +/** + * Creates a new Server Object + * @param p Pool to use + * @param host hostname of the server + * @param port port of the server + * @param min minimum number of client sockets to open + * @param smax soft maximum number of client connections to open + * @param max hard maximum number of client connections + * @param ttl time to live in microseconds of a client connection + * @param ns location of the new server object + * @see apr_reslist_create + * @remark min, smax, and max are only used when APR_HAS_THREADS + */ +APU_DECLARE(apr_status_t) apr_memcache_server_create(apr_pool_t *p, + const char *host, + apr_port_t port, + apr_uint32_t min, + apr_uint32_t smax, + apr_uint32_t max, + apr_uint32_t ttl, + apr_memcache_server_t **ns); +/** + * Creates a new memcached client object + * @param p Pool to use + * @param max_servers maximum number of servers + * @param flags Not currently used + * @param mc location of the new memcache client object + */ +APU_DECLARE(apr_status_t) apr_memcache_create(apr_pool_t *p, + apr_uint16_t max_servers, + apr_uint32_t flags, + apr_memcache_t **mc); + +/** + * Gets a value from the server, allocating the value out of p + * @param mc client to use + * @param p Pool to use + * @param key null terminated string containing the key + * @param baton location of the allocated value + * @param len length of data at baton + * @param flags any flags set by the client for this key + * @return + */ +APU_DECLARE(apr_status_t) apr_memcache_getp(apr_memcache_t *mc, + apr_pool_t *p, + const char* key, + char **baton, + apr_size_t *len, + apr_uint16_t *flags); + + +/** + * Add a key to a hash for a multiget query + * if the hash (*value) is NULL it will be created + * @param data_pool pool from where the hash and their items are created from + * @param key null terminated string containing the key + * @param values hash of keys and values that this key will be added to + * @return + */ +APU_DECLARE(void) apr_memcache_add_multget_key(apr_pool_t *data_pool, + const char* key, + apr_hash_t **values); + +/** + * Gets multiple values from the server, allocating the values out of p + * @param mc client to use + * @param temp_pool Pool used for temporary allocations. May be cleared inside this + * call. + * @param data_pool Pool used to allocate data for the returned values. + * @param values hash of apr_memcache_value_t keyed by strings, contains the + * result of the multiget call. + * @return + */ +APU_DECLARE(apr_status_t) apr_memcache_multgetp(apr_memcache_t *mc, + apr_pool_t *temp_pool, + apr_pool_t *data_pool, + apr_hash_t *values); + +/** + * Sets a value by key on the server + * @param mc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param timeout time in seconds for the data to live on the server + * @param flags any flags set by the client for this key + */ +APU_DECLARE(apr_status_t) apr_memcache_set(apr_memcache_t *mc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint32_t timeout, + apr_uint16_t flags); + +/** + * Adds value by key on the server + * @param mc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param timeout time for the data to live on the server + * @param flags any flags set by the client for this key + * @return APR_SUCCESS if the key was added, APR_EEXIST if the key + * already exists on the server. + */ +APU_DECLARE(apr_status_t) apr_memcache_add(apr_memcache_t *mc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint32_t timeout, + apr_uint16_t flags); + +/** + * Replaces value by key on the server + * @param mc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param timeout time for the data to live on the server + * @param flags any flags set by the client for this key + * @return APR_SUCCESS if the key was added, APR_EEXIST if the key + * did not exist on the server. + */ +APU_DECLARE(apr_status_t) apr_memcache_replace(apr_memcache_t *mc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint32_t timeout, + apr_uint16_t flags); +/** + * Deletes a key from a server + * @param mc client to use + * @param key null terminated string containing the key + * @param timeout time for the delete to stop other clients from adding + */ +APU_DECLARE(apr_status_t) apr_memcache_delete(apr_memcache_t *mc, + const char *key, + apr_uint32_t timeout); + +/** + * Increments a value + * @param mc client to use + * @param key null terminated string containing the key + * @param n number to increment by + * @param nv new value after incrementing + */ +APU_DECLARE(apr_status_t) apr_memcache_incr(apr_memcache_t *mc, + const char *key, + apr_int32_t n, + apr_uint32_t *nv); + +/** + * Decrements a value + * @param mc client to use + * @param key null terminated string containing the key + * @param n number to decrement by + * @param new_value new value after decrementing + */ +APU_DECLARE(apr_status_t) apr_memcache_decr(apr_memcache_t *mc, + const char *key, + apr_int32_t n, + apr_uint32_t *new_value); + +/** + * Query a server's version + * @param ms server to query + * @param p Pool to allocate answer from + * @param baton location to store server version string + * @param len length of the server version string + */ +APU_DECLARE(apr_status_t) apr_memcache_version(apr_memcache_server_t *ms, + apr_pool_t *p, + char **baton); + +typedef struct +{ + /** Version string of this server */ + const char *version; + /** Process id of this server process */ + apr_uint32_t pid; + /** Number of seconds this server has been running */ + apr_uint32_t uptime; + /** current UNIX time according to the server */ + apr_time_t time; + /** The size of a pointer on the current machine */ + apr_uint32_t pointer_size; + /** Accumulated user time for this process */ + apr_time_t rusage_user; + /** Accumulated system time for this process */ + apr_time_t rusage_system; + /** Current number of items stored by the server */ + apr_uint32_t curr_items; + /** Total number of items stored by this server */ + apr_uint32_t total_items; + /** Current number of bytes used by this server to store items */ + apr_uint64_t bytes; + /** Number of open connections */ + apr_uint32_t curr_connections; + /** Total number of connections opened since the server started running */ + apr_uint32_t total_connections; + /** Number of connection structures allocated by the server */ + apr_uint32_t connection_structures; + /** Cumulative number of retrieval requests */ + apr_uint32_t cmd_get; + /** Cumulative number of storage requests */ + apr_uint32_t cmd_set; + /** Number of keys that have been requested and found present */ + apr_uint32_t get_hits; + /** Number of items that have been requested and not found */ + apr_uint32_t get_misses; + /** Number of items removed from cache because they passed their + expiration time */ + apr_uint64_t evictions; + /** Total number of bytes read by this server */ + apr_uint64_t bytes_read; + /** Total number of bytes sent by this server */ + apr_uint64_t bytes_written; + /** Number of bytes this server is allowed to use for storage. */ + apr_uint32_t limit_maxbytes; + /** Number of threads the server is running (if built with threading) */ + apr_uint32_t threads; +} apr_memcache_stats_t; + +/** + * Query a server for statistics + * @param ms server to query + * @param p Pool to allocate answer from + * @param stats location of the new statistics structure + */ +APU_DECLARE(apr_status_t) apr_memcache_stats(apr_memcache_server_t *ms, + apr_pool_t *p, + apr_memcache_stats_t **stats); + + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_MEMCACHE_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_mmap.h b/c/dependencies/windows/apr/x64/include/apr_mmap.h new file mode 100644 index 00000000..c14de192 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_mmap.h @@ -0,0 +1,171 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_MMAP_H +#define APR_MMAP_H + +/** + * @file apr_mmap.h + * @brief APR MMAP routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_ring.h" +#include "apr_file_io.h" /* for apr_file_t */ + +#ifdef BEOS +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_mmap MMAP (Memory Map) Routines + * @ingroup APR + * @{ + */ + +/** MMap opened for reading */ +#define APR_MMAP_READ 1 +/** MMap opened for writing */ +#define APR_MMAP_WRITE 2 + +/** @see apr_mmap_t */ +typedef struct apr_mmap_t apr_mmap_t; + +/** + * @remark + * As far as I can tell the only really sane way to store an MMAP is as a + * void * and a length. BeOS requires this area_id, but that's just a little + * something extra. I am exposing this type, because it doesn't make much + * sense to keep it private, and opening it up makes some stuff easier in + * Apache. + */ +/** The MMAP structure */ +struct apr_mmap_t { + /** The pool the mmap structure was allocated out of. */ + apr_pool_t *cntxt; +#ifdef BEOS + /** An area ID. Only valid on BeOS */ + area_id area; +#endif +#ifdef WIN32 + /** The handle of the file mapping */ + HANDLE mhandle; + /** The start of the real memory page area (mapped view) */ + void *mv; + /** The physical start, size and offset */ + apr_off_t pstart; + apr_size_t psize; + apr_off_t poffset; +#endif + /** The start of the memory mapped area */ + void *mm; + /** The amount of data in the mmap */ + apr_size_t size; + /** ring of apr_mmap_t's that reference the same + * mmap'ed region; acts in place of a reference count */ + APR_RING_ENTRY(apr_mmap_t) link; +}; + +#if APR_HAS_MMAP || defined(DOXYGEN) + +/** @def APR_MMAP_THRESHOLD + * Files have to be at least this big before they're mmap()d. This is to deal + * with systems where the expense of doing an mmap() and an munmap() outweighs + * the benefit for small files. It shouldn't be set lower than 1. + */ +#ifdef MMAP_THRESHOLD +# define APR_MMAP_THRESHOLD MMAP_THRESHOLD +#else +# ifdef SUNOS4 +# define APR_MMAP_THRESHOLD (8*1024) +# else +# define APR_MMAP_THRESHOLD 1 +# endif /* SUNOS4 */ +#endif /* MMAP_THRESHOLD */ + +/** @def APR_MMAP_LIMIT + * Maximum size of MMap region + */ +#ifdef MMAP_LIMIT +# define APR_MMAP_LIMIT MMAP_LIMIT +#else +# define APR_MMAP_LIMIT (4*1024*1024) +#endif /* MMAP_LIMIT */ + +/** Can this file be MMaped */ +#define APR_MMAP_CANDIDATE(filelength) \ + ((filelength >= APR_MMAP_THRESHOLD) && (filelength < APR_MMAP_LIMIT)) + +/* Function definitions */ + +/** + * Create a new mmap'ed file out of an existing APR file. + * @param newmmap The newly created mmap'ed file. + * @param file The file to turn into an mmap. + * @param offset The offset into the file to start the data pointer at. + * @param size The size of the file + * @param flag bit-wise or of: + *
+ *          APR_MMAP_READ       MMap opened for reading
+ *          APR_MMAP_WRITE      MMap opened for writing
+ * 
+ * @param cntxt The pool to use when creating the mmap. + */ +APR_DECLARE(apr_status_t) apr_mmap_create(apr_mmap_t **newmmap, + apr_file_t *file, apr_off_t offset, + apr_size_t size, apr_int32_t flag, + apr_pool_t *cntxt); + +/** + * Duplicate the specified MMAP. + * @param new_mmap The structure to duplicate into. + * @param old_mmap The mmap to duplicate. + * @param p The pool to use for new_mmap. + */ +APR_DECLARE(apr_status_t) apr_mmap_dup(apr_mmap_t **new_mmap, + apr_mmap_t *old_mmap, + apr_pool_t *p); + +/** + * Remove a mmap'ed. + * @param mm The mmap'ed file. + */ +APR_DECLARE(apr_status_t) apr_mmap_delete(apr_mmap_t *mm); + +/** + * Move the pointer into the mmap'ed file to the specified offset. + * @param addr The pointer to the offset specified. + * @param mm The mmap'ed file. + * @param offset The offset to move to. + */ +APR_DECLARE(apr_status_t) apr_mmap_offset(void **addr, apr_mmap_t *mm, + apr_off_t offset); + +#endif /* APR_HAS_MMAP */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_MMAP_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_network_io.h b/c/dependencies/windows/apr/x64/include/apr_network_io.h new file mode 100644 index 00000000..7d6957bc --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_network_io.h @@ -0,0 +1,951 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_NETWORK_IO_H +#define APR_NETWORK_IO_H +/** + * @file apr_network_io.h + * @brief APR Network library + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_file_io.h" +#include "apr_errno.h" +#include "apr_inherit.h" +#include "apr_perms_set.h" + +#if APR_HAVE_NETINET_IN_H +#include +#endif +#if APR_HAVE_SYS_UN_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_network_io Network Routines + * @ingroup APR + * @{ + */ + +#ifndef APR_MAX_SECS_TO_LINGER +/** Maximum seconds to linger */ +#define APR_MAX_SECS_TO_LINGER 30 +#endif + +#ifndef APRMAXHOSTLEN +/** Maximum hostname length */ +#define APRMAXHOSTLEN 256 +#endif + +#ifndef APR_ANYADDR +/** Default 'any' address */ +#define APR_ANYADDR "0.0.0.0" +#endif + +/** + * @defgroup apr_sockopt Socket option definitions + * @{ + */ +#define APR_SO_LINGER 1 /**< Linger */ +#define APR_SO_KEEPALIVE 2 /**< Keepalive */ +#define APR_SO_DEBUG 4 /**< Debug */ +#define APR_SO_NONBLOCK 8 /**< Non-blocking IO */ +#define APR_SO_REUSEADDR 16 /**< Reuse addresses */ +#define APR_SO_SNDBUF 64 /**< Send buffer */ +#define APR_SO_RCVBUF 128 /**< Receive buffer */ +#define APR_SO_DISCONNECTED 256 /**< Disconnected */ +#define APR_TCP_NODELAY 512 /**< For SCTP sockets, this is mapped + * to STCP_NODELAY internally. + */ +#define APR_TCP_NOPUSH 1024 /**< No push */ +#define APR_RESET_NODELAY 2048 /**< This flag is ONLY set internally + * when we set APR_TCP_NOPUSH with + * APR_TCP_NODELAY set to tell us that + * APR_TCP_NODELAY should be turned on + * again when NOPUSH is turned off + */ +#define APR_INCOMPLETE_READ 4096 /**< Set on non-blocking sockets + * (timeout != 0) on which the + * previous read() did not fill a buffer + * completely. the next apr_socket_recv() + * will first call select()/poll() rather than + * going straight into read(). (Can also + * be set by an application to force a + * select()/poll() call before the next + * read, in cases where the app expects + * that an immediate read would fail.) + */ +#define APR_INCOMPLETE_WRITE 8192 /**< like APR_INCOMPLETE_READ, but for write + * @see APR_INCOMPLETE_READ + */ +#define APR_IPV6_V6ONLY 16384 /**< Don't accept IPv4 connections on an + * IPv6 listening socket. + */ +#define APR_TCP_DEFER_ACCEPT 32768 /**< Delay accepting of new connections + * until data is available. + * @see apr_socket_accept_filter + */ +#define APR_SO_BROADCAST 65536 /**< Allow broadcast + */ +#define APR_SO_FREEBIND 131072 /**< Allow binding to addresses not owned + * by any interface + */ + +/** @} */ + +/** Define what type of socket shutdown should occur. */ +typedef enum { + APR_SHUTDOWN_READ, /**< no longer allow read request */ + APR_SHUTDOWN_WRITE, /**< no longer allow write requests */ + APR_SHUTDOWN_READWRITE /**< no longer allow read or write requests */ +} apr_shutdown_how_e; + +#define APR_IPV4_ADDR_OK 0x01 /**< @see apr_sockaddr_info_get() */ +#define APR_IPV6_ADDR_OK 0x02 /**< @see apr_sockaddr_info_get() */ + +#if (!APR_HAVE_IN_ADDR) +/** + * We need to make sure we always have an in_addr type, so APR will just + * define it ourselves, if the platform doesn't provide it. + */ +struct in_addr { + apr_uint32_t s_addr; /**< storage to hold the IP# */ +}; +#endif + +/** @def APR_INADDR_NONE + * Not all platforms have a real INADDR_NONE. This macro replaces + * INADDR_NONE on all platforms. + */ +#ifdef INADDR_NONE +#define APR_INADDR_NONE INADDR_NONE +#else +#define APR_INADDR_NONE ((unsigned int) 0xffffffff) +#endif + +/** + * @def APR_INET + * Not all platforms have these defined, so we'll define them here + * The default values come from FreeBSD 4.1.1 + */ +#define APR_INET AF_INET +/** @def APR_UNSPEC + * Let the system decide which address family to use + */ +#ifdef AF_UNSPEC +#define APR_UNSPEC AF_UNSPEC +#else +#define APR_UNSPEC 0 +#endif +#if APR_HAVE_IPV6 +/** @def APR_INET6 +* IPv6 Address Family. Not all platforms may have this defined. +*/ + +#define APR_INET6 AF_INET6 +#endif + +#if APR_HAVE_SOCKADDR_UN +#if defined (AF_UNIX) +#define APR_UNIX AF_UNIX +#elif defined(AF_LOCAL) +#define APR_UNIX AF_LOCAL +#else +#error "Neither AF_UNIX nor AF_LOCAL is defined" +#endif +#else /* !APR_HAVE_SOCKADDR_UN */ +#if defined (AF_UNIX) +#define APR_UNIX AF_UNIX +#elif defined(AF_LOCAL) +#define APR_UNIX AF_LOCAL +#else +/* TODO: Use a smarter way to detect unique APR_UNIX value */ +#define APR_UNIX 1234 +#endif +#endif + +/** + * @defgroup IP_Proto IP Protocol Definitions for use when creating sockets + * @{ + */ +#define APR_PROTO_TCP 6 /**< TCP */ +#define APR_PROTO_UDP 17 /**< UDP */ +#define APR_PROTO_SCTP 132 /**< SCTP */ +/** @} */ + +/** + * Enum used to denote either the local and remote endpoint of a + * connection. + */ +typedef enum { + APR_LOCAL, /**< Socket information for local end of connection */ + APR_REMOTE /**< Socket information for remote end of connection */ +} apr_interface_e; + +/** + * The specific declaration of inet_addr's ... some platforms fall back + * inet_network (this is not good, but necessary) + */ + +#if APR_HAVE_INET_ADDR +#define apr_inet_addr inet_addr +#elif APR_HAVE_INET_NETWORK /* only DGUX, as far as I know */ +/** + * @warning + * not generally safe... inet_network() and inet_addr() perform + * different functions */ +#define apr_inet_addr inet_network +#endif + +/** A structure to represent sockets */ +typedef struct apr_socket_t apr_socket_t; +/** + * A structure to encapsulate headers and trailers for apr_socket_sendfile + */ +typedef struct apr_hdtr_t apr_hdtr_t; +/** A structure to represent in_addr */ +typedef struct in_addr apr_in_addr_t; +/** A structure to represent an IP subnet */ +typedef struct apr_ipsubnet_t apr_ipsubnet_t; + +/** @remark use apr_uint16_t just in case some system has a short that isn't 16 bits... */ +typedef apr_uint16_t apr_port_t; + +/** @remark It's defined here as I think it should all be platform safe... + * @see apr_sockaddr_t + */ +typedef struct apr_sockaddr_t apr_sockaddr_t; +/** + * APRs socket address type, used to ensure protocol independence + */ +struct apr_sockaddr_t { + /** The pool to use... */ + apr_pool_t *pool; + /** The hostname */ + char *hostname; + /** Either a string of the port number or the service name for the port */ + char *servname; + /** The numeric port */ + apr_port_t port; + /** The family */ + apr_int32_t family; + /** How big is the sockaddr we're using? */ + apr_socklen_t salen; + /** How big is the ip address structure we're using? */ + int ipaddr_len; + /** How big should the address buffer be? 16 for v4 or 46 for v6 + * used in inet_ntop... */ + int addr_str_len; + /** This points to the IP address structure within the appropriate + * sockaddr structure. */ + void *ipaddr_ptr; + /** If multiple addresses were found by apr_sockaddr_info_get(), this + * points to a representation of the next address. */ + apr_sockaddr_t *next; + /** Union of either IPv4 or IPv6 sockaddr. */ + union { + /** IPv4 sockaddr structure */ + struct sockaddr_in sin; +#if APR_HAVE_IPV6 + /** IPv6 sockaddr structure */ + struct sockaddr_in6 sin6; +#endif +#if APR_HAVE_SA_STORAGE + /** Placeholder to ensure that the size of this union is not + * dependent on whether APR_HAVE_IPV6 is defined. */ + struct sockaddr_storage sas; +#endif +#if APR_HAVE_SOCKADDR_UN + /** Unix domain socket sockaddr structure */ + struct sockaddr_un unx; +#endif + } sa; +}; + +#if APR_HAS_SENDFILE +/** + * Support reusing the socket on platforms which support it (from disconnect, + * specifically Win32. + * @remark Optional flag passed into apr_socket_sendfile() + */ +#define APR_SENDFILE_DISCONNECT_SOCKET 1 +#endif + +/** A structure to encapsulate headers and trailers for apr_socket_sendfile */ +struct apr_hdtr_t { + /** An iovec to store the headers sent before the file. */ + struct iovec* headers; + /** number of headers in the iovec */ + int numheaders; + /** An iovec to store the trailers sent after the file. */ + struct iovec* trailers; + /** number of trailers in the iovec */ + int numtrailers; +}; + +/* function definitions */ + +/** + * Create a socket. + * @param new_sock The new socket that has been set up. + * @param family The address family of the socket (e.g., APR_INET). + * @param type The type of the socket (e.g., SOCK_STREAM). + * @param protocol The protocol of the socket (e.g., APR_PROTO_TCP). + * @param cont The pool for the apr_socket_t and associated storage. + * @note The pool will be used by various functions that operate on the + * socket. The caller must ensure that it is not used by other threads + * at the same time. + */ +APR_DECLARE(apr_status_t) apr_socket_create(apr_socket_t **new_sock, + int family, int type, + int protocol, + apr_pool_t *cont); + +/** + * Shutdown either reading, writing, or both sides of a socket. + * @param thesocket The socket to close + * @param how How to shutdown the socket. One of: + *
+ *            APR_SHUTDOWN_READ         no longer allow read requests
+ *            APR_SHUTDOWN_WRITE        no longer allow write requests
+ *            APR_SHUTDOWN_READWRITE    no longer allow read or write requests 
+ * 
+ * @see apr_shutdown_how_e + * @remark This does not actually close the socket descriptor, it just + * controls which calls are still valid on the socket. + */ +APR_DECLARE(apr_status_t) apr_socket_shutdown(apr_socket_t *thesocket, + apr_shutdown_how_e how); + +/** + * Close a socket. + * @param thesocket The socket to close + */ +APR_DECLARE(apr_status_t) apr_socket_close(apr_socket_t *thesocket); + +/** + * Bind the socket to its associated port + * @param sock The socket to bind + * @param sa The socket address to bind to + * @remark This may be where we will find out if there is any other process + * using the selected port. + */ +APR_DECLARE(apr_status_t) apr_socket_bind(apr_socket_t *sock, + apr_sockaddr_t *sa); + +/** + * Listen to a bound socket for connections. + * @param sock The socket to listen on + * @param backlog The number of outstanding connections allowed in the sockets + * listen queue. If this value is less than zero, the listen + * queue size is set to zero. + */ +APR_DECLARE(apr_status_t) apr_socket_listen(apr_socket_t *sock, + apr_int32_t backlog); + +/** + * Accept a new connection request + * @param new_sock A copy of the socket that is connected to the socket that + * made the connection request. This is the socket which should + * be used for all future communication. + * @param sock The socket we are listening on. + * @param connection_pool The pool for the new socket. + * @note The pool will be used by various functions that operate on the + * socket. The caller must ensure that it is not used by other threads + * at the same time. + */ +APR_DECLARE(apr_status_t) apr_socket_accept(apr_socket_t **new_sock, + apr_socket_t *sock, + apr_pool_t *connection_pool); + +/** + * Issue a connection request to a socket either on the same machine + * or a different one. + * @param sock The socket we wish to use for our side of the connection + * @param sa The address of the machine we wish to connect to. + */ +APR_DECLARE(apr_status_t) apr_socket_connect(apr_socket_t *sock, + apr_sockaddr_t *sa); + +/** + * Determine whether the receive part of the socket has been closed by + * the peer (such that a subsequent call to apr_socket_read would + * return APR_EOF), if the socket's receive buffer is empty. This + * function does not block waiting for I/O. + * + * @param sock The socket to check + * @param atreadeof If APR_SUCCESS is returned, *atreadeof is set to + * non-zero if a subsequent read would return APR_EOF + * @return an error is returned if it was not possible to determine the + * status, in which case *atreadeof is not changed. + */ +APR_DECLARE(apr_status_t) apr_socket_atreadeof(apr_socket_t *sock, + int *atreadeof); + +/** + * Create apr_sockaddr_t from hostname, address family, and port. + * @param sa The new apr_sockaddr_t. + * @param hostname The hostname or numeric address string to resolve/parse, or + * NULL to build an address that corresponds to 0.0.0.0 or :: + * or in case of APR_UNIX family it is absolute socket filename. + * @param family The address family to use, or APR_UNSPEC if the system should + * decide. + * @param port The port number. + * @param flags Special processing flags: + *
+ *       APR_IPV4_ADDR_OK          first query for IPv4 addresses; only look
+ *                                 for IPv6 addresses if the first query failed;
+ *                                 only valid if family is APR_UNSPEC and hostname
+ *                                 isn't NULL; mutually exclusive with
+ *                                 APR_IPV6_ADDR_OK
+ *       APR_IPV6_ADDR_OK          first query for IPv6 addresses; only look
+ *                                 for IPv4 addresses if the first query failed;
+ *                                 only valid if family is APR_UNSPEC and hostname
+ *                                 isn't NULL and APR_HAVE_IPV6; mutually exclusive
+ *                                 with APR_IPV4_ADDR_OK
+ * 
+ * @param p The pool for the apr_sockaddr_t and associated storage. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_info_get(apr_sockaddr_t **sa, + const char *hostname, + apr_int32_t family, + apr_port_t port, + apr_int32_t flags, + apr_pool_t *p); + +/** + * Copy apr_sockaddr_t src to dst on pool p. + * @param dst The destination apr_sockaddr_t. + * @param src The source apr_sockaddr_t. + * @param p The pool for the apr_sockaddr_t and associated storage. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_info_copy(apr_sockaddr_t **dst, + const apr_sockaddr_t *src, + apr_pool_t *p); + +/* Set the zone of an IPv6 link-local address object. + * @param sa Socket address object + * @param zone_id Zone ID (textual "eth0" or numeric "3"). + * @return Returns APR_EBADIP for non-IPv6 socket or an IPv6 address + * which isn't link-local. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_zone_set(apr_sockaddr_t *sa, + const char *zone_id); + + +/* Retrieve the zone of an IPv6 link-local address object. + * @param sa Socket address object + * @param name If non-NULL, set to the textual representation of the zone id + * @param id If non-NULL, set to the integer zone id + * @param p Pool from which *name is allocated if used. + * @return Returns APR_EBADIP for non-IPv6 socket or socket without any zone id + * set, or other error if the interface could not be mapped to a name. + * @remark Both name and id may be NULL, neither are modified if + * non-NULL in error cases. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_zone_get(const apr_sockaddr_t *sa, + const char **name, + apr_uint32_t *id, + apr_pool_t *p); + +/** + * Look up the host name from an apr_sockaddr_t. + * @param hostname The hostname. + * @param sa The apr_sockaddr_t. + * @param flags Special processing flags. + * @remark Results can vary significantly between platforms + * when processing wildcard socket addresses. + */ +APR_DECLARE(apr_status_t) apr_getnameinfo(char **hostname, + apr_sockaddr_t *sa, + apr_int32_t flags); + +/** + * Parse hostname/IP address with scope id and port. + * + * Any of the following strings are accepted: + * 8080 (just the port number) + * www.apache.org (just the hostname) + * www.apache.org:8080 (hostname and port number) + * [fe80::1]:80 (IPv6 numeric address string only) + * [fe80::1%eth0] (IPv6 numeric address string and scope id) + * + * Invalid strings: + * (empty string) + * [abc] (not valid IPv6 numeric address string) + * abc:65536 (invalid port number) + * + * @param addr The new buffer containing just the hostname. On output, *addr + * will be NULL if no hostname/IP address was specfied. + * @param scope_id The new buffer containing just the scope id. On output, + * *scope_id will be NULL if no scope id was specified. + * @param port The port number. On output, *port will be 0 if no port was + * specified. + * ### FIXME: 0 is a legal port (per RFC 1700). this should + * ### return something besides zero if the port is missing. + * @param str The input string to be parsed. + * @param p The pool from which *addr and *scope_id are allocated. + * @remark If scope id shouldn't be allowed, check for scope_id != NULL in + * addition to checking the return code. If addr/hostname should be + * required, check for addr == NULL in addition to checking the + * return code. + */ +APR_DECLARE(apr_status_t) apr_parse_addr_port(char **addr, + char **scope_id, + apr_port_t *port, + const char *str, + apr_pool_t *p); + +/** + * Get name of the current machine + * @param buf A buffer to store the hostname in. + * @param len The maximum length of the hostname that can be stored in the + * buffer provided. The suggested length is APRMAXHOSTLEN + 1. + * @param cont The pool to use. + * @remark If the buffer was not large enough, an error will be returned. + */ +APR_DECLARE(apr_status_t) apr_gethostname(char *buf, int len, apr_pool_t *cont); + +/** + * Return the data associated with the current socket + * @param data The user data associated with the socket. + * @param key The key to associate with the user data. + * @param sock The currently open socket. + */ +APR_DECLARE(apr_status_t) apr_socket_data_get(void **data, const char *key, + apr_socket_t *sock); + +/** + * Set the data associated with the current socket. + * @param sock The currently open socket. + * @param data The user data to associate with the socket. + * @param key The key to associate with the data. + * @param cleanup The cleanup to call when the socket is destroyed. + */ +APR_DECLARE(apr_status_t) apr_socket_data_set(apr_socket_t *sock, void *data, + const char *key, + apr_status_t (*cleanup)(void*)); + +/** + * Send data over a network. + * @param sock The socket to send the data over. + * @param buf The buffer which contains the data to be sent. + * @param len On entry, the number of bytes to send; on exit, the number + * of bytes sent. + * @remark + *
+ * This functions acts like a blocking write by default.  To change 
+ * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK
+ * socket option.
+ *
+ * It is possible for both bytes to be sent and an error to be returned.
+ *
+ * APR_EINTR is never returned.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_socket_send(apr_socket_t *sock, const char *buf, + apr_size_t *len); + +/** + * Send multiple buffers over a network. + * @param sock The socket to send the data over. + * @param vec The array of iovec structs containing the data to send + * @param nvec The number of iovec structs in the array + * @param len Receives the number of bytes actually written + * @remark + *
+ * This functions acts like a blocking write by default.  To change 
+ * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK
+ * socket option.
+ * The number of bytes actually sent is stored in argument 4.
+ *
+ * It is possible for both bytes to be sent and an error to be returned.
+ *
+ * APR_EINTR is never returned.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_socket_sendv(apr_socket_t *sock, + const struct iovec *vec, + apr_int32_t nvec, apr_size_t *len); + +/** + * @param sock The socket to send from + * @param where The apr_sockaddr_t describing where to send the data + * @param flags The flags to use + * @param buf The data to send + * @param len The length of the data to send + */ +APR_DECLARE(apr_status_t) apr_socket_sendto(apr_socket_t *sock, + apr_sockaddr_t *where, + apr_int32_t flags, const char *buf, + apr_size_t *len); + +/** + * Read data from a socket. On success, the address of the peer from + * which the data was sent is copied into the @a from parameter, and the + * @a len parameter is updated to give the number of bytes written to + * @a buf. + * + * @param from Updated with the address from which the data was received + * @param sock The socket to use + * @param flags The flags to use + * @param buf The buffer to use + * @param len The length of the available buffer + */ + +APR_DECLARE(apr_status_t) apr_socket_recvfrom(apr_sockaddr_t *from, + apr_socket_t *sock, + apr_int32_t flags, char *buf, + apr_size_t *len); + +#if APR_HAS_SENDFILE || defined(DOXYGEN) + +/** + * Send a file from an open file descriptor to a socket, along with + * optional headers and trailers + * @param sock The socket to which we're writing + * @param file The open file from which to read + * @param hdtr A structure containing the headers and trailers to send + * @param offset Offset into the file where we should begin writing + * @param len (input) - Number of bytes to send from the file + * (output) - Number of bytes actually sent, + * including headers, file, and trailers + * @param flags APR flags that are mapped to OS specific flags + * @remark This functions acts like a blocking write by default. To change + * this behavior, use apr_socket_timeout_set() or the + * APR_SO_NONBLOCK socket option. + * The number of bytes actually sent is stored in the len parameter. + * The offset parameter is passed by reference for no reason; its + * value will never be modified by the apr_socket_sendfile() function. + */ +APR_DECLARE(apr_status_t) apr_socket_sendfile(apr_socket_t *sock, + apr_file_t *file, + apr_hdtr_t *hdtr, + apr_off_t *offset, + apr_size_t *len, + apr_int32_t flags); + +#endif /* APR_HAS_SENDFILE */ + +/** + * Read data from a network. + * @param sock The socket to read the data from. + * @param buf The buffer to store the data in. + * @param len On entry, the number of bytes to receive; on exit, the number + * of bytes received. + * @remark + *
+ * This functions acts like a blocking read by default.  To change 
+ * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK
+ * socket option.
+ * The number of bytes actually received is stored in argument 3.
+ *
+ * It is possible for both bytes to be received and an APR_EOF or
+ * other error to be returned.
+ *
+ * APR_EINTR is never returned.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_socket_recv(apr_socket_t *sock, + char *buf, apr_size_t *len); + +/** + * Setup socket options for the specified socket + * @param sock The socket to set up. + * @param opt The option we would like to configure. One of: + *
+ *            APR_SO_DEBUG      --  turn on debugging information 
+ *            APR_SO_KEEPALIVE  --  keep connections active
+ *            APR_SO_LINGER     --  lingers on close if data is present
+ *            APR_SO_NONBLOCK   --  Turns blocking on/off for socket
+ *                                  When this option is enabled, use
+ *                                  the APR_STATUS_IS_EAGAIN() macro to
+ *                                  see if a send or receive function
+ *                                  could not transfer data without
+ *                                  blocking.
+ *            APR_SO_REUSEADDR  --  The rules used in validating addresses
+ *                                  supplied to bind should allow reuse
+ *                                  of local addresses.
+ *            APR_SO_SNDBUF     --  Set the SendBufferSize
+ *            APR_SO_RCVBUF     --  Set the ReceiveBufferSize
+ *            APR_SO_FREEBIND   --  Allow binding to non-local IP address.
+ * 
+ * @param on Value for the option. + */ +APR_DECLARE(apr_status_t) apr_socket_opt_set(apr_socket_t *sock, + apr_int32_t opt, apr_int32_t on); + +/** + * Setup socket timeout for the specified socket + * @param sock The socket to set up. + * @param t Value for the timeout. + *
+ *   t > 0  -- read and write calls return APR_TIMEUP if specified time
+ *             elapsess with no data read or written
+ *   t == 0 -- read and write calls never block
+ *   t < 0  -- read and write calls block
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_socket_timeout_set(apr_socket_t *sock, + apr_interval_time_t t); + +/** + * Query socket options for the specified socket + * @param sock The socket to query + * @param opt The option we would like to query. One of: + *
+ *            APR_SO_DEBUG      --  turn on debugging information 
+ *            APR_SO_KEEPALIVE  --  keep connections active
+ *            APR_SO_LINGER     --  lingers on close if data is present
+ *            APR_SO_NONBLOCK   --  Turns blocking on/off for socket
+ *            APR_SO_REUSEADDR  --  The rules used in validating addresses
+ *                                  supplied to bind should allow reuse
+ *                                  of local addresses.
+ *            APR_SO_SNDBUF     --  Set the SendBufferSize
+ *            APR_SO_RCVBUF     --  Set the ReceiveBufferSize
+ *            APR_SO_DISCONNECTED -- Query the disconnected state of the socket.
+ *                                  (Currently only used on Windows)
+ * 
+ * @param on Socket option returned on the call. + */ +APR_DECLARE(apr_status_t) apr_socket_opt_get(apr_socket_t *sock, + apr_int32_t opt, apr_int32_t *on); + +/** + * Query socket timeout for the specified socket + * @param sock The socket to query + * @param t Socket timeout returned from the query. + */ +APR_DECLARE(apr_status_t) apr_socket_timeout_get(apr_socket_t *sock, + apr_interval_time_t *t); + +/** + * Query the specified socket if at the OOB/Urgent data mark + * @param sock The socket to query + * @param atmark Is set to true if socket is at the OOB/urgent mark, + * otherwise is set to false. + */ +APR_DECLARE(apr_status_t) apr_socket_atmark(apr_socket_t *sock, + int *atmark); + +/** + * Return an address associated with a socket; either the address to + * which the socket is bound locally or the address of the peer + * to which the socket is connected. + * @param sa The returned apr_sockaddr_t. + * @param which Whether to retrieve the local or remote address + * @param sock The socket to use + */ +APR_DECLARE(apr_status_t) apr_socket_addr_get(apr_sockaddr_t **sa, + apr_interface_e which, + apr_socket_t *sock); + +/** + * Return the IP address (in numeric address string format) in + * an APR socket address. APR will allocate storage for the IP address + * string from the pool of the apr_sockaddr_t. + * @param addr The IP address. + * @param sockaddr The socket address to reference. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_ip_get(char **addr, + apr_sockaddr_t *sockaddr); + +/** + * Write the IP address (in numeric address string format) of the APR + * socket address @a sockaddr into the buffer @a buf (of size @a buflen). + * @param sockaddr The socket address to reference. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_ip_getbuf(char *buf, apr_size_t buflen, + apr_sockaddr_t *sockaddr); + +/** + * See if the IP addresses in two APR socket addresses are + * equivalent. Appropriate logic is present for comparing + * IPv4-mapped IPv6 addresses with IPv4 addresses. + * + * @param addr1 One of the APR socket addresses. + * @param addr2 The other APR socket address. + * @remark The return value will be non-zero if the addresses + * are equivalent. + */ +APR_DECLARE(int) apr_sockaddr_equal(const apr_sockaddr_t *addr1, + const apr_sockaddr_t *addr2); + +/** + * See if the IP address in an APR socket address refers to the wildcard + * address for the protocol family (e.g., INADDR_ANY for IPv4). + * + * @param addr The APR socket address to examine. + * @remark The return value will be non-zero if the address is + * initialized and is the wildcard address. + */ +APR_DECLARE(int) apr_sockaddr_is_wildcard(const apr_sockaddr_t *addr); + +/** +* Return the type of the socket. +* @param sock The socket to query. +* @param type The returned type (e.g., SOCK_STREAM). +*/ +APR_DECLARE(apr_status_t) apr_socket_type_get(apr_socket_t *sock, + int *type); + +/** + * Given an apr_sockaddr_t and a service name, set the port for the service + * @param sockaddr The apr_sockaddr_t that will have its port set + * @param servname The name of the service you wish to use + */ +APR_DECLARE(apr_status_t) apr_getservbyname(apr_sockaddr_t *sockaddr, + const char *servname); +/** + * Build an ip-subnet representation from an IP address and optional netmask or + * number-of-bits. + * @param ipsub The new ip-subnet representation + * @param ipstr The input IP address string + * @param mask_or_numbits The input netmask or number-of-bits string, or NULL + * @param p The pool to allocate from + */ +APR_DECLARE(apr_status_t) apr_ipsubnet_create(apr_ipsubnet_t **ipsub, + const char *ipstr, + const char *mask_or_numbits, + apr_pool_t *p); + +/** + * Test the IP address in an apr_sockaddr_t against a pre-built ip-subnet + * representation. + * @param ipsub The ip-subnet representation + * @param sa The socket address to test + * @return non-zero if the socket address is within the subnet, 0 otherwise + */ +APR_DECLARE(int) apr_ipsubnet_test(apr_ipsubnet_t *ipsub, apr_sockaddr_t *sa); + +#if APR_HAS_SO_ACCEPTFILTER || defined(DOXYGEN) +/** + * Set an OS level accept filter. + * @param sock The socket to put the accept filter on. + * @param name The accept filter + * @param args Any extra args to the accept filter. Passing NULL here removes + * the accept filter. + * @bug name and args should have been declared as const char *, as they are in + * APR 2.0 + */ +apr_status_t apr_socket_accept_filter(apr_socket_t *sock, char *name, + char *args); +#endif + +/** + * Return the protocol of the socket. + * @param sock The socket to query. + * @param protocol The returned protocol (e.g., APR_PROTO_TCP). + */ +APR_DECLARE(apr_status_t) apr_socket_protocol_get(apr_socket_t *sock, + int *protocol); + +/** + * Get the pool used by the socket. + */ +APR_POOL_DECLARE_ACCESSOR(socket); + +/** + * Set a socket to be inherited by child processes. + */ +APR_DECLARE_INHERIT_SET(socket); + +/** + * Unset a socket from being inherited by child processes. + */ +APR_DECLARE_INHERIT_UNSET(socket); + +/** + * Set socket permissions. + */ +APR_PERMS_SET_IMPLEMENT(socket); + +/** + * @defgroup apr_mcast IP Multicast + * @{ + */ + +/** + * Join a Multicast Group + * @param sock The socket to join a multicast group + * @param join The address of the multicast group to join + * @param iface Address of the interface to use. If NULL is passed, the + * default multicast interface will be used. (OS Dependent) + * @param source Source Address to accept transmissions from (non-NULL + * implies Source-Specific Multicast) + */ +APR_DECLARE(apr_status_t) apr_mcast_join(apr_socket_t *sock, + apr_sockaddr_t *join, + apr_sockaddr_t *iface, + apr_sockaddr_t *source); + +/** + * Leave a Multicast Group. All arguments must be the same as + * apr_mcast_join. + * @param sock The socket to leave a multicast group + * @param addr The address of the multicast group to leave + * @param iface Address of the interface to use. If NULL is passed, the + * default multicast interface will be used. (OS Dependent) + * @param source Source Address to accept transmissions from (non-NULL + * implies Source-Specific Multicast) + */ +APR_DECLARE(apr_status_t) apr_mcast_leave(apr_socket_t *sock, + apr_sockaddr_t *addr, + apr_sockaddr_t *iface, + apr_sockaddr_t *source); + +/** + * Set the Multicast Time to Live (ttl) for a multicast transmission. + * @param sock The socket to set the multicast ttl + * @param ttl Time to live to Assign. 0-255, default=1 + * @remark If the TTL is 0, packets will only be seen by sockets on + * the local machine, and only when multicast loopback is enabled. + */ +APR_DECLARE(apr_status_t) apr_mcast_hops(apr_socket_t *sock, + apr_byte_t ttl); + +/** + * Toggle IP Multicast Loopback + * @param sock The socket to set multicast loopback + * @param opt 0=disable, 1=enable + */ +APR_DECLARE(apr_status_t) apr_mcast_loopback(apr_socket_t *sock, + apr_byte_t opt); + + +/** + * Set the Interface to be used for outgoing Multicast Transmissions. + * @param sock The socket to set the multicast interface on + * @param iface Address of the interface to use for Multicast + */ +APR_DECLARE(apr_status_t) apr_mcast_interface(apr_socket_t *sock, + apr_sockaddr_t *iface); + +/** @} */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_NETWORK_IO_H */ + diff --git a/c/dependencies/windows/apr/x64/include/apr_optional.h b/c/dependencies/windows/apr/x64/include/apr_optional.h new file mode 100644 index 00000000..3301d66e --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_optional.h @@ -0,0 +1,92 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_OPTIONAL_H +#define APR_OPTIONAL_H + +#include "apu.h" +/** + * @file apr_optional.h + * @brief APR-UTIL registration of functions exported by modules + */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Opt Optional Functions + * @ingroup APR_Util + * + * Typesafe registration and retrieval of functions that may not be present + * (i.e. functions exported by optional modules) + * @{ + */ + +/** + * The type of an optional function. + * @param name The name of the function + */ +#define APR_OPTIONAL_FN_TYPE(name) apr_OFN_##name##_t + +/** + * Declare an optional function. + * @param ret The return type of the function + * @param name The name of the function + * @param args The function arguments (including brackets) + */ +#define APR_DECLARE_OPTIONAL_FN(ret,name,args) \ +typedef ret (APR_OPTIONAL_FN_TYPE(name)) args + +/** + * XXX: This doesn't belong here, then! + * Private function! DO NOT USE! + * @internal + */ + +typedef void (apr_opt_fn_t)(void); +/** @internal */ +APU_DECLARE_NONSTD(void) apr_dynamic_fn_register(const char *szName, + apr_opt_fn_t *pfn); + +/** + * Register an optional function. This can be later retrieved, type-safely, by + * name. Like all global functions, the name must be unique. Note that, + * confusingly but correctly, the function itself can be static! + * @param name The name of the function + */ +#define APR_REGISTER_OPTIONAL_FN(name) do { \ + APR_OPTIONAL_FN_TYPE(name) *apu__opt = name; \ + apr_dynamic_fn_register(#name,(apr_opt_fn_t *)apu__opt); \ +} while (0) + +/** @internal + * Private function! DO NOT USE! + */ +APU_DECLARE(apr_opt_fn_t *) apr_dynamic_fn_retrieve(const char *szName); + +/** + * Retrieve an optional function. Returns NULL if the function is not present. + * @param name The name of the function + */ +#define APR_RETRIEVE_OPTIONAL_FN(name) \ + (APR_OPTIONAL_FN_TYPE(name) *)apr_dynamic_fn_retrieve(#name) + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_OPTIONAL_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_optional_hooks.h b/c/dependencies/windows/apr/x64/include/apr_optional_hooks.h new file mode 100644 index 00000000..8265f03f --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_optional_hooks.h @@ -0,0 +1,117 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file apr_optional_hooks.h + * @brief Apache optional hook functions + */ + + +#ifndef APR_OPTIONAL_HOOK_H +#define APR_OPTIONAL_HOOK_H + +#include "apr_tables.h" + +#ifdef __cplusplus +extern "C" { +#endif +/** + * @defgroup APR_Util_OPT_HOOK Optional Hook Functions + * @ingroup APR_Util_Hook + * @{ + */ +/** + * Function to implement the APR_OPTIONAL_HOOK Macro + * @internal + * @see APR_OPTIONAL_HOOK + * + * @param szName The name of the hook + * @param pfn A pointer to a function that will be called + * @param aszPre a NULL-terminated array of strings that name modules whose hooks should precede this one + * @param aszSucc a NULL-terminated array of strings that name modules whose hooks should succeed this one + * @param nOrder an integer determining order before honouring aszPre and aszSucc (for example HOOK_MIDDLE) + */ + + +APU_DECLARE(void) apr_optional_hook_add(const char *szName,void (*pfn)(void), + const char * const *aszPre, + const char * const *aszSucc, + int nOrder); + +/** + * Hook to an optional hook. + * + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param pfn A pointer to a function that will be called + * @param aszPre a NULL-terminated array of strings that name modules whose hooks should precede this one + * @param aszSucc a NULL-terminated array of strings that name modules whose hooks should succeed this one + * @param nOrder an integer determining order before honouring aszPre and aszSucc (for example HOOK_MIDDLE) + */ + +#define APR_OPTIONAL_HOOK(ns,name,pfn,aszPre,aszSucc,nOrder) do { \ + ns##_HOOK_##name##_t *apu__hook = pfn; \ + apr_optional_hook_add(#name,(void (*)(void))apu__hook,aszPre, aszSucc, nOrder); \ +} while (0) + +/** + * @internal + * @param szName - the name of the function + * @return the hook structure for a given hook + */ +APU_DECLARE(apr_array_header_t *) apr_optional_hook_get(const char *szName); + +/** + * Implement an optional hook that runs until one of the functions + * returns something other than OK or DECLINE. + * + * @param ns The namespace prefix of the hook functions + * @param link The linkage declaration prefix of the hook + * @param ret The type of the return value of the hook + * @param ret The type of the return value of the hook + * @param name The name of the hook + * @param args_decl The declaration of the arguments for the hook + * @param args_use The names for the arguments for the hook + * @param ok Success value + * @param decline Decline value + */ +#define APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(ns,link,ret,name,args_decl,args_use,ok,decline) \ +link##_DECLARE(ret) ns##_run_##name args_decl \ + { \ + ns##_LINK_##name##_t *pHook; \ + int n; \ + ret rv; \ + apr_array_header_t *pHookArray=apr_optional_hook_get(#name); \ +\ + if(!pHookArray) \ + return ok; \ +\ + pHook=(ns##_LINK_##name##_t *)pHookArray->elts; \ + for(n=0 ; n < pHookArray->nelts ; ++n) \ + { \ + rv=(pHook[n].pFunc)args_use; \ +\ + if(rv != ok && rv != decline) \ + return rv; \ + } \ + return ok; \ + } + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_OPTIONAL_HOOK_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_perms_set.h b/c/dependencies/windows/apr/x64/include/apr_perms_set.h new file mode 100644 index 00000000..92a1362b --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_perms_set.h @@ -0,0 +1,65 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_PERMS_SET_H +#define APR_PERMS_SET_H + +/** + * @file apr_perms_set.h + * @brief APR Process Locking Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_user.h" +#include "apr_file_info.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_perms_set Object permission set functions + * @ingroup APR + * @{ + */ + +/** Permission set callback function. */ +typedef apr_status_t (apr_perms_setfn_t)(void *object, apr_fileperms_t perms, + apr_uid_t uid, apr_gid_t gid); + +#define APR_PERMS_SET_IMPLEMENT(type) \ + APR_DECLARE(apr_status_t) apr_##type##_perms_set \ + (void *the##type, apr_fileperms_t perms, \ + apr_uid_t uid, apr_gid_t gid) + +#define APR_PERMS_SET_ENOTIMPL(type) \ + APR_DECLARE(apr_status_t) apr_##type##_perms_set \ + (void *the##type, apr_fileperms_t perms, \ + apr_uid_t uid, apr_gid_t gid) \ + { return APR_ENOTIMPL ; } + +#define APR_PERMS_SET_FN(type) apr_##type##_perms_set + + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_PERMS_SET */ diff --git a/c/dependencies/windows/apr/x64/include/apr_poll.h b/c/dependencies/windows/apr/x64/include/apr_poll.h new file mode 100644 index 00000000..482d6ee1 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_poll.h @@ -0,0 +1,446 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_POLL_H +#define APR_POLL_H +/** + * @file apr_poll.h + * @brief APR Poll interface + */ +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_inherit.h" +#include "apr_file_io.h" +#include "apr_network_io.h" + +#if APR_HAVE_NETINET_IN_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_poll Poll Routines + * @ingroup APR + * @{ + */ + +/** + * @defgroup pollopts Poll options + * @ingroup apr_poll + * @{ + */ +#define APR_POLLIN 0x001 /**< Can read without blocking */ +#define APR_POLLPRI 0x002 /**< Priority data available */ +#define APR_POLLOUT 0x004 /**< Can write without blocking */ +#define APR_POLLERR 0x010 /**< Pending error */ +#define APR_POLLHUP 0x020 /**< Hangup occurred */ +#define APR_POLLNVAL 0x040 /**< Descriptor invalid */ +/** @} */ + +/** + * @defgroup pollflags Pollset Flags + * @ingroup apr_poll + * @{ + */ +#define APR_POLLSET_THREADSAFE 0x001 /**< Adding or removing a descriptor is + * thread-safe + */ +#define APR_POLLSET_NOCOPY 0x002 /**< Descriptors passed to apr_pollset_add() + * are not copied + */ +#define APR_POLLSET_WAKEABLE 0x004 /**< Poll operations are interruptable by + * apr_pollset_wakeup() or apr_pollcb_wakeup() + */ +#define APR_POLLSET_NODEFAULT 0x010 /**< Do not try to use the default method if + * the specified non-default method cannot be + * used + */ +/** @} */ + +/** + * Pollset Methods + */ +typedef enum { + APR_POLLSET_DEFAULT, /**< Platform default poll method */ + APR_POLLSET_SELECT, /**< Poll uses select method */ + APR_POLLSET_KQUEUE, /**< Poll uses kqueue method */ + APR_POLLSET_PORT, /**< Poll uses Solaris event port method */ + APR_POLLSET_EPOLL, /**< Poll uses epoll method */ + APR_POLLSET_POLL, /**< Poll uses poll method */ + APR_POLLSET_AIO_MSGQ /**< Poll uses z/OS asio method */ +} apr_pollset_method_e; + +/** Used in apr_pollfd_t to determine what the apr_descriptor is */ +typedef enum { + APR_NO_DESC, /**< nothing here */ + APR_POLL_SOCKET, /**< descriptor refers to a socket */ + APR_POLL_FILE, /**< descriptor refers to a file */ + APR_POLL_LASTDESC /**< @deprecated descriptor is the last one in the list */ +} apr_datatype_e ; + +/** Union of either an APR file or socket. */ +typedef union { + apr_file_t *f; /**< file */ + apr_socket_t *s; /**< socket */ +} apr_descriptor; + +/** @see apr_pollfd_t */ +typedef struct apr_pollfd_t apr_pollfd_t; + +/** Poll descriptor set. */ +struct apr_pollfd_t { + apr_pool_t *p; /**< associated pool */ + apr_datatype_e desc_type; /**< descriptor type */ + apr_int16_t reqevents; /**< requested events */ + apr_int16_t rtnevents; /**< returned events */ + apr_descriptor desc; /**< @see apr_descriptor */ + void *client_data; /**< allows app to associate context */ +}; + + +/* General-purpose poll API for arbitrarily large numbers of + * file descriptors + */ + +/** Opaque structure used for pollset API */ +typedef struct apr_pollset_t apr_pollset_t; + +/** + * Set up a pollset object + * @param pollset The pointer in which to return the newly created object + * @param size The maximum number of descriptors that this pollset can hold + * @param p The pool from which to allocate the pollset + * @param flags Optional flags to modify the operation of the pollset. + * + * @remark If flags contains APR_POLLSET_THREADSAFE, then a pollset is + * created on which it is safe to make concurrent calls to + * apr_pollset_add(), apr_pollset_remove() and apr_pollset_poll() + * from separate threads. This feature is only supported on some + * platforms; the apr_pollset_create() call will fail with + * APR_ENOTIMPL on platforms where it is not supported. + * @remark If flags contains APR_POLLSET_WAKEABLE, then a pollset is + * created with an additional internal pipe object used for the + * apr_pollset_wakeup() call. The actual size of pollset is + * in that case @a size + 1. This feature is only supported on some + * platforms; the apr_pollset_create() call will fail with + * APR_ENOTIMPL on platforms where it is not supported. + * @remark If flags contains APR_POLLSET_NOCOPY, then the apr_pollfd_t + * structures passed to apr_pollset_add() are not copied and + * must have a lifetime at least as long as the pollset. + * @remark Some poll methods (including APR_POLLSET_KQUEUE, + * APR_POLLSET_PORT, and APR_POLLSET_EPOLL) do not have a + * fixed limit on the size of the pollset. For these methods, + * the size parameter controls the maximum number of + * descriptors that will be returned by a single call to + * apr_pollset_poll(). + */ +APR_DECLARE(apr_status_t) apr_pollset_create(apr_pollset_t **pollset, + apr_uint32_t size, + apr_pool_t *p, + apr_uint32_t flags); + +/** + * Set up a pollset object + * @param pollset The pointer in which to return the newly created object + * @param size The maximum number of descriptors that this pollset can hold + * @param p The pool from which to allocate the pollset + * @param flags Optional flags to modify the operation of the pollset. + * @param method Poll method to use. See #apr_pollset_method_e. If this + * method cannot be used, the default method will be used unless the + * APR_POLLSET_NODEFAULT flag has been specified. + * + * @remark If flags contains APR_POLLSET_THREADSAFE, then a pollset is + * created on which it is safe to make concurrent calls to + * apr_pollset_add(), apr_pollset_remove() and apr_pollset_poll() + * from separate threads. This feature is only supported on some + * platforms; the apr_pollset_create_ex() call will fail with + * APR_ENOTIMPL on platforms where it is not supported. + * @remark If flags contains APR_POLLSET_WAKEABLE, then a pollset is + * created with additional internal pipe object used for the + * apr_pollset_wakeup() call. The actual size of pollset is + * in that case size + 1. This feature is only supported on some + * platforms; the apr_pollset_create_ex() call will fail with + * APR_ENOTIMPL on platforms where it is not supported. + * @remark If flags contains APR_POLLSET_NOCOPY, then the apr_pollfd_t + * structures passed to apr_pollset_add() are not copied and + * must have a lifetime at least as long as the pollset. + * @remark Some poll methods (including APR_POLLSET_KQUEUE, + * APR_POLLSET_PORT, and APR_POLLSET_EPOLL) do not have a + * fixed limit on the size of the pollset. For these methods, + * the size parameter controls the maximum number of + * descriptors that will be returned by a single call to + * apr_pollset_poll(). + */ +APR_DECLARE(apr_status_t) apr_pollset_create_ex(apr_pollset_t **pollset, + apr_uint32_t size, + apr_pool_t *p, + apr_uint32_t flags, + apr_pollset_method_e method); + +/** + * Destroy a pollset object + * @param pollset The pollset to destroy + */ +APR_DECLARE(apr_status_t) apr_pollset_destroy(apr_pollset_t *pollset); + +/** + * Add a socket or file descriptor to a pollset + * @param pollset The pollset to which to add the descriptor + * @param descriptor The descriptor to add + * @remark If you set client_data in the descriptor, that value + * will be returned in the client_data field whenever this + * descriptor is signalled in apr_pollset_poll(). + * @remark If the pollset has been created with APR_POLLSET_THREADSAFE + * and thread T1 is blocked in a call to apr_pollset_poll() for + * this same pollset that is being modified via apr_pollset_add() + * in thread T2, the currently executing apr_pollset_poll() call in + * T1 will either: (1) automatically include the newly added descriptor + * in the set of descriptors it is watching or (2) return immediately + * with APR_EINTR. Option (1) is recommended, but option (2) is + * allowed for implementations where option (1) is impossible + * or impractical. + * @remark If the pollset has been created with APR_POLLSET_NOCOPY, the + * apr_pollfd_t structure referenced by descriptor will not be copied + * and must have a lifetime at least as long as the pollset. + * @remark Do not add the same socket or file descriptor to the same pollset + * multiple times, even if the requested events differ for the + * different calls to apr_pollset_add(). If the events of interest + * for a descriptor change, you must first remove the descriptor + * from the pollset with apr_pollset_remove(), then add it again + * specifying all requested events. + */ +APR_DECLARE(apr_status_t) apr_pollset_add(apr_pollset_t *pollset, + const apr_pollfd_t *descriptor); + +/** + * Remove a descriptor from a pollset + * @param pollset The pollset from which to remove the descriptor + * @param descriptor The descriptor to remove + * @remark If the descriptor is not found, APR_NOTFOUND is returned. + * @remark If the pollset has been created with APR_POLLSET_THREADSAFE + * and thread T1 is blocked in a call to apr_pollset_poll() for + * this same pollset that is being modified via apr_pollset_remove() + * in thread T2, the currently executing apr_pollset_poll() call in + * T1 will either: (1) automatically exclude the newly added descriptor + * in the set of descriptors it is watching or (2) return immediately + * with APR_EINTR. Option (1) is recommended, but option (2) is + * allowed for implementations where option (1) is impossible + * or impractical. + * @remark apr_pollset_remove() cannot be used to remove a subset of requested + * events for a descriptor. The reqevents field in the apr_pollfd_t + * parameter must contain the same value when removing as when adding. + */ +APR_DECLARE(apr_status_t) apr_pollset_remove(apr_pollset_t *pollset, + const apr_pollfd_t *descriptor); + +/** + * Block for activity on the descriptor(s) in a pollset + * @param pollset The pollset to use + * @param timeout The amount of time in microseconds to wait. This is a + * maximum, not a minimum. If a descriptor is signalled, the + * function will return before this time. If timeout is + * negative, the function will block until a descriptor is + * signalled or until apr_pollset_wakeup() has been called. + * @param num Number of signalled descriptors (output parameter) + * @param descriptors Array of signalled descriptors (output parameter) + * @remark APR_EINTR will be returned if the pollset has been created with + * APR_POLLSET_WAKEABLE, apr_pollset_wakeup() has been called while + * waiting for activity, and there were no signalled descriptors at the + * time of the wakeup call. + * @remark Multiple signalled conditions for the same descriptor may be reported + * in one or more returned apr_pollfd_t structures, depending on the + * implementation. + */ +APR_DECLARE(apr_status_t) apr_pollset_poll(apr_pollset_t *pollset, + apr_interval_time_t timeout, + apr_int32_t *num, + const apr_pollfd_t **descriptors); + +/** + * Interrupt the blocked apr_pollset_poll() call. + * @param pollset The pollset to use + * @remark If the pollset was not created with APR_POLLSET_WAKEABLE the + * return value is APR_EINIT. + */ +APR_DECLARE(apr_status_t) apr_pollset_wakeup(apr_pollset_t *pollset); + +/** + * Poll the descriptors in the poll structure + * @param aprset The poll structure we will be using. + * @param numsock The number of descriptors we are polling + * @param nsds The number of descriptors signalled (output parameter) + * @param timeout The amount of time in microseconds to wait. This is a + * maximum, not a minimum. If a descriptor is signalled, the + * function will return before this time. If timeout is + * negative, the function will block until a descriptor is + * signalled or until apr_pollset_wakeup() has been called. + * @remark The number of descriptors signalled is returned in the third argument. + * This is a blocking call, and it will not return until either a + * descriptor has been signalled or the timeout has expired. + * @remark The rtnevents field in the apr_pollfd_t array will only be filled- + * in if the return value is APR_SUCCESS. + */ +APR_DECLARE(apr_status_t) apr_poll(apr_pollfd_t *aprset, apr_int32_t numsock, + apr_int32_t *nsds, + apr_interval_time_t timeout); + +/** + * Return a printable representation of the pollset method. + * @param pollset The pollset to use + */ +APR_DECLARE(const char *) apr_pollset_method_name(apr_pollset_t *pollset); + +/** + * Return a printable representation of the default pollset method + * (APR_POLLSET_DEFAULT). + */ +APR_DECLARE(const char *) apr_poll_method_defname(void); + +/** Opaque structure used for pollcb API */ +typedef struct apr_pollcb_t apr_pollcb_t; + +/** + * Set up a pollcb object + * @param pollcb The pointer in which to return the newly created object + * @param size The maximum number of descriptors that a single _poll can return. + * @param p The pool from which to allocate the pollcb + * @param flags Optional flags to modify the operation of the pollcb. + * + * @remark If flags contains APR_POLLSET_WAKEABLE, then a pollcb is + * created with an additional internal pipe object used for the + * apr_pollcb_wakeup() call. The actual size of pollcb is + * in that case @a size + 1. + * @remark Pollcb is only supported on some platforms; the apr_pollcb_create() + * call will fail with APR_ENOTIMPL on platforms where it is not supported. + */ +APR_DECLARE(apr_status_t) apr_pollcb_create(apr_pollcb_t **pollcb, + apr_uint32_t size, + apr_pool_t *p, + apr_uint32_t flags); + +/** + * Set up a pollcb object + * @param pollcb The pointer in which to return the newly created object + * @param size The maximum number of descriptors that a single _poll can return. + * @param p The pool from which to allocate the pollcb + * @param flags Optional flags to modify the operation of the pollcb. + * @param method Poll method to use. See #apr_pollset_method_e. If this + * method cannot be used, the default method will be used unless the + * APR_POLLSET_NODEFAULT flag has been specified. + * + * @remark If flags contains APR_POLLSET_WAKEABLE, then a pollcb is + * created with an additional internal pipe object used for the + * apr_pollcb_wakeup() call. The actual size of pollcb is + * in that case @a size + 1. + * @remark Pollcb is only supported on some platforms; the apr_pollcb_create_ex() + * call will fail with APR_ENOTIMPL on platforms where it is not supported. + */ +APR_DECLARE(apr_status_t) apr_pollcb_create_ex(apr_pollcb_t **pollcb, + apr_uint32_t size, + apr_pool_t *p, + apr_uint32_t flags, + apr_pollset_method_e method); + +/** + * Add a socket or file descriptor to a pollcb + * @param pollcb The pollcb to which to add the descriptor + * @param descriptor The descriptor to add + * @remark If you set client_data in the descriptor, that value will be + * returned in the client_data field whenever this descriptor is + * signalled in apr_pollcb_poll(). + * @remark Unlike the apr_pollset API, the descriptor is not copied, and users + * must retain the memory used by descriptor, as the same pointer will + * be returned to them from apr_pollcb_poll. + * @remark Do not add the same socket or file descriptor to the same pollcb + * multiple times, even if the requested events differ for the + * different calls to apr_pollcb_add(). If the events of interest + * for a descriptor change, you must first remove the descriptor + * from the pollcb with apr_pollcb_remove(), then add it again + * specifying all requested events. + */ +APR_DECLARE(apr_status_t) apr_pollcb_add(apr_pollcb_t *pollcb, + apr_pollfd_t *descriptor); +/** + * Remove a descriptor from a pollcb + * @param pollcb The pollcb from which to remove the descriptor + * @param descriptor The descriptor to remove + * @remark If the descriptor is not found, APR_NOTFOUND is returned. + * @remark apr_pollcb_remove() cannot be used to remove a subset of requested + * events for a descriptor. The reqevents field in the apr_pollfd_t + * parameter must contain the same value when removing as when adding. + */ +APR_DECLARE(apr_status_t) apr_pollcb_remove(apr_pollcb_t *pollcb, + apr_pollfd_t *descriptor); + +/** + * Function prototype for pollcb handlers + * @param baton Opaque baton passed into apr_pollcb_poll() + * @param descriptor Contains the notification for an active descriptor. + * The @a rtnevents member describes which events were triggered + * for this descriptor. + * @remark If the pollcb handler does not return APR_SUCCESS, the apr_pollcb_poll() + * call returns with the handler's return value. + */ +typedef apr_status_t (*apr_pollcb_cb_t)(void *baton, apr_pollfd_t *descriptor); + +/** + * Block for activity on the descriptor(s) in a pollcb + * @param pollcb The pollcb to use + * @param timeout The amount of time in microseconds to wait. This is a + * maximum, not a minimum. If a descriptor is signalled, the + * function will return before this time. If timeout is + * negative, the function will block until a descriptor is + * signalled or until apr_pollcb_wakeup() has been called. + * @param func Callback function to call for each active descriptor. + * @param baton Opaque baton passed to the callback function. + * @remark Multiple signalled conditions for the same descriptor may be reported + * in one or more calls to the callback function, depending on the + * implementation. + * @remark APR_EINTR will be returned if the pollset has been created with + * APR_POLLSET_WAKEABLE and apr_pollcb_wakeup() has been called while + * waiting for activity. + */ +APR_DECLARE(apr_status_t) apr_pollcb_poll(apr_pollcb_t *pollcb, + apr_interval_time_t timeout, + apr_pollcb_cb_t func, + void *baton); + +/** + * Interrupt the blocked apr_pollcb_poll() call. + * @param pollcb The pollcb to use + * @remark If the pollcb was not created with APR_POLLSET_WAKEABLE the + * return value is APR_EINIT. + */ +APR_DECLARE(apr_status_t) apr_pollcb_wakeup(apr_pollcb_t *pollcb); + +/** + * Return a printable representation of the pollcb method. + * @param pollcb The pollcb to use + */ +APR_DECLARE(const char *) apr_pollcb_method_name(apr_pollcb_t *pollcb); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_POLL_H */ + diff --git a/c/dependencies/windows/apr/x64/include/apr_pools.h b/c/dependencies/windows/apr/x64/include/apr_pools.h new file mode 100644 index 00000000..783c9c42 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_pools.h @@ -0,0 +1,815 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_POOLS_H +#define APR_POOLS_H + +/** + * @file apr_pools.h + * @brief APR memory allocation + * + * Resource allocation routines... + * + * designed so that we don't have to keep track of EVERYTHING so that + * it can be explicitly freed later (a fundamentally unsound strategy --- + * particularly in the presence of die()). + * + * Instead, we maintain pools, and allocate items (both memory and I/O + * handlers) from the pools --- currently there are two, one for + * per-transaction info, and one for config info. When a transaction is + * over, we can delete everything in the per-transaction apr_pool_t without + * fear, and without thinking too hard about it either. + * + * Note that most operations on pools are not thread-safe: a single pool + * should only be accessed by a single thread at any given time. The one + * exception to this rule is creating a subpool of a given pool: one or more + * threads can safely create subpools at the same time that another thread + * accesses the parent pool. + */ + +#include "apr.h" +#include "apr_errno.h" +#include "apr_general.h" /* for APR_STRINGIFY */ +#define APR_WANT_MEMFUNC /**< for no good reason? */ +#include "apr_want.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_pools Memory Pool Functions + * @ingroup APR + * @{ + */ + +/** The fundamental pool type */ +typedef struct apr_pool_t apr_pool_t; + + +/** + * Declaration helper macro to construct apr_foo_pool_get()s. + * + * This standardized macro is used by opaque (APR) data types to return + * the apr_pool_t that is associated with the data type. + * + * APR_POOL_DECLARE_ACCESSOR() is used in a header file to declare the + * accessor function. A typical usage and result would be: + *
+ *    APR_POOL_DECLARE_ACCESSOR(file);
+ * becomes:
+ *    APR_DECLARE(apr_pool_t *) apr_file_pool_get(const apr_file_t *thefile);
+ * 
+ * @remark Doxygen unwraps this macro (via doxygen.conf) to provide + * actual help for each specific occurrence of apr_foo_pool_get. + * @remark the linkage is specified for APR. It would be possible to expand + * the macros to support other linkages. + */ +#define APR_POOL_DECLARE_ACCESSOR(type) \ + APR_DECLARE(apr_pool_t *) apr_##type##_pool_get \ + (const apr_##type##_t *the##type) + +/** + * Implementation helper macro to provide apr_foo_pool_get()s. + * + * In the implementation, the APR_POOL_IMPLEMENT_ACCESSOR() is used to + * actually define the function. It assumes the field is named "pool". + */ +#define APR_POOL_IMPLEMENT_ACCESSOR(type) \ + APR_DECLARE(apr_pool_t *) apr_##type##_pool_get \ + (const apr_##type##_t *the##type) \ + { return the##type->pool; } + + +/** + * Pool debug levels + * + *
+ * | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
+ * ---------------------------------
+ * |   |   |   |   |   |   |   | x |  General debug code enabled (useful in
+ *                                    combination with --with-efence).
+ *
+ * |   |   |   |   |   |   | x |   |  Verbose output on stderr (report
+ *                                    CREATE, CLEAR, DESTROY).
+ *
+ * |   |   |   | x |   |   |   |   |  Verbose output on stderr (report
+ *                                    PALLOC, PCALLOC).
+ *
+ * |   |   |   |   |   | x |   |   |  Lifetime checking. On each use of a
+ *                                    pool, check its lifetime.  If the pool
+ *                                    is out of scope, abort().
+ *                                    In combination with the verbose flag
+ *                                    above, it will output LIFE in such an
+ *                                    event prior to aborting.
+ *
+ * |   |   |   |   | x |   |   |   |  Pool owner checking.  On each use of a
+ *                                    pool, check if the current thread is the
+ *                                    pool's owner.  If not, abort().  In
+ *                                    combination with the verbose flag above,
+ *                                    it will output OWNER in such an event
+ *                                    prior to aborting.  Use the debug
+ *                                    function apr_pool_owner_set() to switch
+ *                                    a pool's ownership.
+ *
+ * When no debug level was specified, assume general debug mode.
+ * If level 0 was specified, debugging is switched off.
+ * 
+ */ +#if defined(APR_POOL_DEBUG) +/* If APR_POOL_DEBUG is blank, we get 1; if it is a number, we get -1. */ +#if (APR_POOL_DEBUG - APR_POOL_DEBUG -1 == 1) +#undef APR_POOL_DEBUG +#define APR_POOL_DEBUG 1 +#endif +#else +#define APR_POOL_DEBUG 0 +#endif + +/** the place in the code where the particular function was called */ +#define APR_POOL__FILE_LINE__ __FILE__ ":" APR_STRINGIFY(__LINE__) + + + +/** A function that is called when allocation fails. */ +typedef int (*apr_abortfunc_t)(int retcode); + +/* + * APR memory structure manipulators (pools, tables, and arrays). + */ + +/* + * Initialization + */ + +/** + * Setup all of the internal structures required to use pools + * @remark Programs do NOT need to call this directly. APR will call this + * automatically from apr_initialize. + * @internal + */ +APR_DECLARE(apr_status_t) apr_pool_initialize(void); + +/** + * Tear down all of the internal structures required to use pools + * @remark Programs do NOT need to call this directly. APR will call this + * automatically from apr_terminate. + * @internal + */ +APR_DECLARE(void) apr_pool_terminate(void); + + +/* + * Pool creation/destruction + */ + +#include "apr_allocator.h" + +/** + * Create a new pool. + * @param newpool The pool we have just created. + * @param parent The parent pool. If this is NULL, the new pool is a root + * pool. If it is non-NULL, the new pool will inherit all + * of its parent pool's attributes, except the apr_pool_t will + * be a sub-pool. + * @param abort_fn A function to use if the pool cannot allocate more memory. + * @param allocator The allocator to use with the new pool. If NULL the + * allocator of the parent pool will be used. + * @remark This function is thread-safe, in the sense that multiple threads + * can safely create subpools of the same parent pool concurrently. + * Similarly, a subpool can be created by one thread at the same + * time that another thread accesses the parent pool. + */ +APR_DECLARE(apr_status_t) apr_pool_create_ex(apr_pool_t **newpool, + apr_pool_t *parent, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +/** + * Create a new pool. + * @deprecated @see apr_pool_create_unmanaged_ex. + */ +APR_DECLARE(apr_status_t) apr_pool_create_core_ex(apr_pool_t **newpool, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator); + +/** + * Create a new unmanaged pool. + * @param newpool The pool we have just created. + * @param abort_fn A function to use if the pool cannot allocate more memory. + * @param allocator The allocator to use with the new pool. If NULL a + * new allocator will be created with the new pool as owner. + * @remark An unmanaged pool is a special pool without a parent; it will + * NOT be destroyed upon apr_terminate. It must be explicitly + * destroyed by calling apr_pool_destroy, to prevent memory leaks. + * Use of this function is discouraged, think twice about whether + * you really really need it. + * @warning Any child cleanups registered against the new pool, or + * against sub-pools thereof, will not be executed during an + * invocation of apr_proc_create(), so resources created in an + * "unmanaged" pool hierarchy will leak to child processes. + */ +APR_DECLARE(apr_status_t) apr_pool_create_unmanaged_ex(apr_pool_t **newpool, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +/** + * Debug version of apr_pool_create_ex. + * @param newpool @see apr_pool_create. + * @param parent @see apr_pool_create. + * @param abort_fn @see apr_pool_create. + * @param allocator @see apr_pool_create. + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @remark Only available when APR_POOL_DEBUG is defined. + * Call this directly if you have your apr_pool_create_ex + * calls in a wrapper function and wish to override + * the file_line argument to reflect the caller of + * your wrapper function. If you do not have + * apr_pool_create_ex in a wrapper, trust the macro + * and don't call apr_pool_create_ex_debug directly. + */ +APR_DECLARE(apr_status_t) apr_pool_create_ex_debug(apr_pool_t **newpool, + apr_pool_t *parent, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pool_create_ex(newpool, parent, abort_fn, allocator) \ + apr_pool_create_ex_debug(newpool, parent, abort_fn, allocator, \ + APR_POOL__FILE_LINE__) +#endif + +/** + * Debug version of apr_pool_create_core_ex. + * @deprecated @see apr_pool_create_unmanaged_ex_debug. + */ +APR_DECLARE(apr_status_t) apr_pool_create_core_ex_debug(apr_pool_t **newpool, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator, + const char *file_line); + +/** + * Debug version of apr_pool_create_unmanaged_ex. + * @param newpool @see apr_pool_create_unmanaged. + * @param abort_fn @see apr_pool_create_unmanaged. + * @param allocator @see apr_pool_create_unmanaged. + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @remark Only available when APR_POOL_DEBUG is defined. + * Call this directly if you have your apr_pool_create_unmanaged_ex + * calls in a wrapper function and wish to override + * the file_line argument to reflect the caller of + * your wrapper function. If you do not have + * apr_pool_create_core_ex in a wrapper, trust the macro + * and don't call apr_pool_create_core_ex_debug directly. + */ +APR_DECLARE(apr_status_t) apr_pool_create_unmanaged_ex_debug(apr_pool_t **newpool, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pool_create_core_ex(newpool, abort_fn, allocator) \ + apr_pool_create_unmanaged_ex_debug(newpool, abort_fn, allocator, \ + APR_POOL__FILE_LINE__) + +#define apr_pool_create_unmanaged_ex(newpool, abort_fn, allocator) \ + apr_pool_create_unmanaged_ex_debug(newpool, abort_fn, allocator, \ + APR_POOL__FILE_LINE__) + +#endif + +/** + * Create a new pool. + * @param newpool The pool we have just created. + * @param parent The parent pool. If this is NULL, the new pool is a root + * pool. If it is non-NULL, the new pool will inherit all + * of its parent pool's attributes, except the apr_pool_t will + * be a sub-pool. + * @remark This function is thread-safe, in the sense that multiple threads + * can safely create subpools of the same parent pool concurrently. + * Similarly, a subpool can be created by one thread at the same + * time that another thread accesses the parent pool. + */ +#if defined(DOXYGEN) +APR_DECLARE(apr_status_t) apr_pool_create(apr_pool_t **newpool, + apr_pool_t *parent); +#else +#if APR_POOL_DEBUG +#define apr_pool_create(newpool, parent) \ + apr_pool_create_ex_debug(newpool, parent, NULL, NULL, \ + APR_POOL__FILE_LINE__) +#else +#define apr_pool_create(newpool, parent) \ + apr_pool_create_ex(newpool, parent, NULL, NULL) +#endif +#endif + +/** + * Create a new unmanaged pool. + * @param newpool The pool we have just created. + */ +#if defined(DOXYGEN) +APR_DECLARE(apr_status_t) apr_pool_create_core(apr_pool_t **newpool); +APR_DECLARE(apr_status_t) apr_pool_create_unmanaged(apr_pool_t **newpool); +#else +#if APR_POOL_DEBUG +#define apr_pool_create_core(newpool) \ + apr_pool_create_unmanaged_ex_debug(newpool, NULL, NULL, \ + APR_POOL__FILE_LINE__) +#define apr_pool_create_unmanaged(newpool) \ + apr_pool_create_unmanaged_ex_debug(newpool, NULL, NULL, \ + APR_POOL__FILE_LINE__) +#else +#define apr_pool_create_core(newpool) \ + apr_pool_create_unmanaged_ex(newpool, NULL, NULL) +#define apr_pool_create_unmanaged(newpool) \ + apr_pool_create_unmanaged_ex(newpool, NULL, NULL) +#endif +#endif + +/** + * Find the pool's allocator + * @param pool The pool to get the allocator from. + */ +APR_DECLARE(apr_allocator_t *) apr_pool_allocator_get(apr_pool_t *pool) + __attribute__((nonnull(1))); + +/** + * Clear all memory in the pool and run all the cleanups. This also destroys all + * subpools. + * @param p The pool to clear + * @remark This does not actually free the memory, it just allows the pool + * to re-use this memory for the next allocation. + * @see apr_pool_destroy() + */ +APR_DECLARE(void) apr_pool_clear(apr_pool_t *p) __attribute__((nonnull(1))); + +/** + * Debug version of apr_pool_clear. + * @param p See: apr_pool_clear. + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @remark Only available when APR_POOL_DEBUG is defined. + * Call this directly if you have your apr_pool_clear + * calls in a wrapper function and wish to override + * the file_line argument to reflect the caller of + * your wrapper function. If you do not have + * apr_pool_clear in a wrapper, trust the macro + * and don't call apr_pool_destroy_clear directly. + */ +APR_DECLARE(void) apr_pool_clear_debug(apr_pool_t *p, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pool_clear(p) \ + apr_pool_clear_debug(p, APR_POOL__FILE_LINE__) +#endif + +/** + * Destroy the pool. This takes similar action as apr_pool_clear() and then + * frees all the memory. + * @param p The pool to destroy + * @remark This will actually free the memory + */ +APR_DECLARE(void) apr_pool_destroy(apr_pool_t *p) __attribute__((nonnull(1))); + +/** + * Debug version of apr_pool_destroy. + * @param p See: apr_pool_destroy. + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @remark Only available when APR_POOL_DEBUG is defined. + * Call this directly if you have your apr_pool_destroy + * calls in a wrapper function and wish to override + * the file_line argument to reflect the caller of + * your wrapper function. If you do not have + * apr_pool_destroy in a wrapper, trust the macro + * and don't call apr_pool_destroy_debug directly. + */ +APR_DECLARE(void) apr_pool_destroy_debug(apr_pool_t *p, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pool_destroy(p) \ + apr_pool_destroy_debug(p, APR_POOL__FILE_LINE__) +#endif + + +/* + * Memory allocation + */ + +/** + * Allocate a block of memory from a pool + * @param p The pool to allocate from + * @param size The amount of memory to allocate + * @return The allocated memory + */ +APR_DECLARE(void *) apr_palloc(apr_pool_t *p, apr_size_t size) +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) + __attribute__((alloc_size(2))) +#endif + __attribute__((nonnull(1))); + +/** + * Debug version of apr_palloc + * @param p See: apr_palloc + * @param size See: apr_palloc + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @return See: apr_palloc + */ +APR_DECLARE(void *) apr_palloc_debug(apr_pool_t *p, apr_size_t size, + const char *file_line) +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) + __attribute__((alloc_size(2))) +#endif + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_palloc(p, size) \ + apr_palloc_debug(p, size, APR_POOL__FILE_LINE__) +#endif + +/** + * Allocate a block of memory from a pool and set all of the memory to 0 + * @param p The pool to allocate from + * @param size The amount of memory to allocate + * @return The allocated memory + */ +#if defined(DOXYGEN) +APR_DECLARE(void *) apr_pcalloc(apr_pool_t *p, apr_size_t size); +#elif !APR_POOL_DEBUG +#define apr_pcalloc(p, size) memset(apr_palloc(p, size), 0, size) +#endif + +/** + * Debug version of apr_pcalloc + * @param p See: apr_pcalloc + * @param size See: apr_pcalloc + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @return See: apr_pcalloc + */ +APR_DECLARE(void *) apr_pcalloc_debug(apr_pool_t *p, apr_size_t size, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pcalloc(p, size) \ + apr_pcalloc_debug(p, size, APR_POOL__FILE_LINE__) +#endif + + +/* + * Pool Properties + */ + +/** + * Set the function to be called when an allocation failure occurs. + * @remark If the program wants APR to exit on a memory allocation error, + * then this function can be called to set the callback to use (for + * performing cleanup and then exiting). If this function is not called, + * then APR will return an error and expect the calling program to + * deal with the error accordingly. + */ +APR_DECLARE(void) apr_pool_abort_set(apr_abortfunc_t abortfunc, + apr_pool_t *pool) + __attribute__((nonnull(2))); + +/** + * Get the abort function associated with the specified pool. + * @param pool The pool for retrieving the abort function. + * @return The abort function for the given pool. + */ +APR_DECLARE(apr_abortfunc_t) apr_pool_abort_get(apr_pool_t *pool) + __attribute__((nonnull(1))); + +/** + * Get the parent pool of the specified pool. + * @param pool The pool for retrieving the parent pool. + * @return The parent of the given pool. + */ +APR_DECLARE(apr_pool_t *) apr_pool_parent_get(apr_pool_t *pool) + __attribute__((nonnull(1))); + +/** + * Determine if pool a is an ancestor of pool b. + * @param a The pool to search + * @param b The pool to search for + * @return True if a is an ancestor of b, NULL is considered an ancestor + * of all pools. + * @remark if compiled with APR_POOL_DEBUG, this function will also + * return true if A is a pool which has been guaranteed by the caller + * (using apr_pool_join) to have a lifetime at least as long as some + * ancestor of pool B. + */ +APR_DECLARE(int) apr_pool_is_ancestor(apr_pool_t *a, apr_pool_t *b); + +/** + * Tag a pool (give it a name) + * @param pool The pool to tag + * @param tag The tag + */ +APR_DECLARE(void) apr_pool_tag(apr_pool_t *pool, const char *tag) + __attribute__((nonnull(1))); + + +/* + * User data management + */ + +/** + * Set the data associated with the current pool + * @param data The user data associated with the pool. + * @param key The key to use for association + * @param cleanup The cleanup program to use to cleanup the data (NULL if none) + * @param pool The current pool + * @warning The data to be attached to the pool should have a life span + * at least as long as the pool it is being attached to. + * + * Users of APR must take EXTREME care when choosing a key to + * use for their data. It is possible to accidentally overwrite + * data by choosing a key that another part of the program is using. + * Therefore it is advised that steps are taken to ensure that unique + * keys are used for all of the userdata objects in a particular pool + * (the same key in two different pools or a pool and one of its + * subpools is okay) at all times. Careful namespace prefixing of + * key names is a typical way to help ensure this uniqueness. + * + */ +APR_DECLARE(apr_status_t) apr_pool_userdata_set(const void *data, + const char *key, + apr_status_t (*cleanup)(void *), + apr_pool_t *pool) + __attribute__((nonnull(2,4))); + +/** + * Set the data associated with the current pool + * @param data The user data associated with the pool. + * @param key The key to use for association + * @param cleanup The cleanup program to use to cleanup the data (NULL if none) + * @param pool The current pool + * @note same as apr_pool_userdata_set(), except that this version doesn't + * make a copy of the key (this function is useful, for example, when + * the key is a string literal) + * @warning This should NOT be used if the key could change addresses by + * any means between the apr_pool_userdata_setn() call and a + * subsequent apr_pool_userdata_get() on that key, such as if a + * static string is used as a userdata key in a DSO and the DSO could + * be unloaded and reloaded between the _setn() and the _get(). You + * MUST use apr_pool_userdata_set() in such cases. + * @warning More generally, the key and the data to be attached to the + * pool should have a life span at least as long as the pool itself. + * + */ +APR_DECLARE(apr_status_t) apr_pool_userdata_setn( + const void *data, const char *key, + apr_status_t (*cleanup)(void *), + apr_pool_t *pool) + __attribute__((nonnull(2,4))); + +/** + * Return the data associated with the current pool. + * @param data The user data associated with the pool. + * @param key The key for the data to retrieve + * @param pool The current pool. + */ +APR_DECLARE(apr_status_t) apr_pool_userdata_get(void **data, const char *key, + apr_pool_t *pool) + __attribute__((nonnull(1,2,3))); + + +/** + * @defgroup PoolCleanup Pool Cleanup Functions + * + * Cleanups are performed in the reverse order they were registered. That is: + * Last In, First Out. A cleanup function can safely allocate memory from + * the pool that is being cleaned up. It can also safely register additional + * cleanups which will be run LIFO, directly after the current cleanup + * terminates. Cleanups have to take caution in calling functions that + * create subpools. Subpools, created during cleanup will NOT automatically + * be cleaned up. In other words, cleanups are to clean up after themselves. + * + * @{ + */ + +/** + * Register a function to be called when a pool is cleared or destroyed + * @param p The pool to register the cleanup with + * @param data The data to pass to the cleanup function. + * @param plain_cleanup The function to call when the pool is cleared + * or destroyed + * @param child_cleanup The function to call when a child process is about + * to exec - this function is called in the child, obviously! + */ +APR_DECLARE(void) apr_pool_cleanup_register( + apr_pool_t *p, const void *data, + apr_status_t (*plain_cleanup)(void *), + apr_status_t (*child_cleanup)(void *)) + __attribute__((nonnull(3,4))); + +/** + * Register a function to be called when a pool is cleared or destroyed. + * + * Unlike apr_pool_cleanup_register which registers a cleanup + * that is called AFTER all subpools are destroyed, this function registers + * a function that will be called before any of the subpools are destroyed. + * + * @param p The pool to register the cleanup with + * @param data The data to pass to the cleanup function. + * @param plain_cleanup The function to call when the pool is cleared + * or destroyed + */ +APR_DECLARE(void) apr_pool_pre_cleanup_register( + apr_pool_t *p, const void *data, + apr_status_t (*plain_cleanup)(void *)) + __attribute__((nonnull(3))); + +/** + * Remove a previously registered cleanup function. + * + * The cleanup most recently registered with @a p having the same values of + * @a data and @a cleanup will be removed. + * + * @param p The pool to remove the cleanup from + * @param data The data of the registered cleanup + * @param cleanup The function to remove from cleanup + * @remarks For some strange reason only the plain_cleanup is handled by this + * function + */ +APR_DECLARE(void) apr_pool_cleanup_kill(apr_pool_t *p, const void *data, + apr_status_t (*cleanup)(void *)) + __attribute__((nonnull(3))); + +/** + * Replace the child cleanup function of a previously registered cleanup. + * + * The cleanup most recently registered with @a p having the same values of + * @a data and @a plain_cleanup will have the registered child cleanup + * function replaced with @a child_cleanup. + * + * @param p The pool of the registered cleanup + * @param data The data of the registered cleanup + * @param plain_cleanup The plain cleanup function of the registered cleanup + * @param child_cleanup The function to register as the child cleanup + */ +APR_DECLARE(void) apr_pool_child_cleanup_set( + apr_pool_t *p, const void *data, + apr_status_t (*plain_cleanup)(void *), + apr_status_t (*child_cleanup)(void *)) + __attribute__((nonnull(3,4))); + +/** + * Run the specified cleanup function immediately and unregister it. + * + * The cleanup most recently registered with @a p having the same values of + * @a data and @a cleanup will be removed and @a cleanup will be called + * with @a data as the argument. + * + * @param p The pool to remove the cleanup from + * @param data The data to remove from cleanup + * @param cleanup The function to remove from cleanup + */ +APR_DECLARE(apr_status_t) apr_pool_cleanup_run(apr_pool_t *p, void *data, + apr_status_t (*cleanup)(void *)) + __attribute__((nonnull(3))); + +/** + * An empty cleanup function. + * + * Passed to apr_pool_cleanup_register() when no cleanup is required. + * + * @param data The data to cleanup, will not be used by this function. + */ +APR_DECLARE_NONSTD(apr_status_t) apr_pool_cleanup_null(void *data); + +/** + * Run all registered child cleanups, in preparation for an exec() + * call in a forked child -- close files, etc., but *don't* flush I/O + * buffers, *don't* wait for subprocesses, and *don't* free any + * memory. + */ +APR_DECLARE(void) apr_pool_cleanup_for_exec(void); + +/** @} */ + +/** + * @defgroup PoolDebug Pool Debugging functions. + * + * pools have nested lifetimes -- sub_pools are destroyed when the + * parent pool is cleared. We allow certain liberties with operations + * on things such as tables (and on other structures in a more general + * sense) where we allow the caller to insert values into a table which + * were not allocated from the table's pool. The table's data will + * remain valid as long as all the pools from which its values are + * allocated remain valid. + * + * For example, if B is a sub pool of A, and you build a table T in + * pool B, then it's safe to insert data allocated in A or B into T + * (because B lives at most as long as A does, and T is destroyed when + * B is cleared/destroyed). On the other hand, if S is a table in + * pool A, it is safe to insert data allocated in A into S, but it + * is *not safe* to insert data allocated from B into S... because + * B can be cleared/destroyed before A is (which would leave dangling + * pointers in T's data structures). + * + * In general we say that it is safe to insert data into a table T + * if the data is allocated in any ancestor of T's pool. This is the + * basis on which the APR_POOL_DEBUG code works -- it tests these ancestor + * relationships for all data inserted into tables. APR_POOL_DEBUG also + * provides tools (apr_pool_find, and apr_pool_is_ancestor) for other + * folks to implement similar restrictions for their own data + * structures. + * + * However, sometimes this ancestor requirement is inconvenient -- + * sometimes it's necessary to create a sub pool where the sub pool is + * guaranteed to have the same lifetime as the parent pool. This is a + * guarantee implemented by the *caller*, not by the pool code. That + * is, the caller guarantees they won't destroy the sub pool + * individually prior to destroying the parent pool. + * + * In this case the caller must call apr_pool_join() to indicate this + * guarantee to the APR_POOL_DEBUG code. + * + * These functions are only implemented when #APR_POOL_DEBUG is set. + * + * @{ + */ +#if APR_POOL_DEBUG || defined(DOXYGEN) +/** + * Guarantee that a subpool has the same lifetime as the parent. + * @param p The parent pool + * @param sub The subpool + */ +APR_DECLARE(void) apr_pool_join(apr_pool_t *p, apr_pool_t *sub) + __attribute__((nonnull(2))); + +/** + * Find a pool from something allocated in it. + * @param mem The thing allocated in the pool + * @return The pool it is allocated in + */ +APR_DECLARE(apr_pool_t *) apr_pool_find(const void *mem); + +/** + * Report the number of bytes currently in the pool + * @param p The pool to inspect + * @param recurse Recurse/include the subpools' sizes + * @return The number of bytes + */ +APR_DECLARE(apr_size_t) apr_pool_num_bytes(apr_pool_t *p, int recurse) + __attribute__((nonnull(1))); + +/** + * Lock a pool + * @param pool The pool to lock + * @param flag The flag + */ +APR_DECLARE(void) apr_pool_lock(apr_pool_t *pool, int flag); + +/* @} */ + +#else /* APR_POOL_DEBUG or DOXYGEN */ + +#ifdef apr_pool_join +#undef apr_pool_join +#endif +#define apr_pool_join(a,b) + +#ifdef apr_pool_lock +#undef apr_pool_lock +#endif +#define apr_pool_lock(pool, lock) + +#endif /* APR_POOL_DEBUG or DOXYGEN */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_POOLS_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_portable.h b/c/dependencies/windows/apr/x64/include/apr_portable.h new file mode 100644 index 00000000..f56997e4 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_portable.h @@ -0,0 +1,549 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* This header file is where you should put ANY platform specific information. + * This should be the only header file that programs need to include that + * actually has platform dependent code which refers to the . + */ +#ifndef APR_PORTABLE_H +#define APR_PORTABLE_H +/** + * @file apr_portable.h + * @brief APR Portability Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" +#include "apr_network_io.h" +#include "apr_errno.h" +#include "apr_global_mutex.h" +#include "apr_proc_mutex.h" +#include "apr_time.h" +#include "apr_dso.h" +#include "apr_shm.h" + +#if APR_HAVE_DIRENT_H +#include +#endif +#if APR_HAVE_FCNTL_H +#include +#endif +#if APR_HAVE_PTHREAD_H +#include +#endif +#if APR_HAVE_SEMAPHORE_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_portabile Portability Routines + * @ingroup APR + * @{ + */ + +#ifdef WIN32 +/* The primitives for Windows types */ +typedef HANDLE apr_os_file_t; +typedef HANDLE apr_os_dir_t; +typedef SOCKET apr_os_sock_t; +typedef HANDLE apr_os_proc_mutex_t; +typedef HANDLE apr_os_thread_t; +typedef HANDLE apr_os_proc_t; +typedef DWORD apr_os_threadkey_t; +typedef FILETIME apr_os_imp_time_t; +typedef SYSTEMTIME apr_os_exp_time_t; +typedef HANDLE apr_os_dso_handle_t; +typedef HANDLE apr_os_shm_t; + +#elif defined(OS2) +typedef HFILE apr_os_file_t; +typedef HDIR apr_os_dir_t; +typedef int apr_os_sock_t; +typedef HMTX apr_os_proc_mutex_t; +typedef TID apr_os_thread_t; +typedef PID apr_os_proc_t; +typedef PULONG apr_os_threadkey_t; +typedef struct timeval apr_os_imp_time_t; +typedef struct tm apr_os_exp_time_t; +typedef HMODULE apr_os_dso_handle_t; +typedef void* apr_os_shm_t; + +#elif defined(__BEOS__) +#include +#include + +struct apr_os_proc_mutex_t { + sem_id sem; + int32 ben; +}; + +typedef int apr_os_file_t; +typedef DIR apr_os_dir_t; +typedef int apr_os_sock_t; +typedef struct apr_os_proc_mutex_t apr_os_proc_mutex_t; +typedef thread_id apr_os_thread_t; +typedef thread_id apr_os_proc_t; +typedef int apr_os_threadkey_t; +typedef struct timeval apr_os_imp_time_t; +typedef struct tm apr_os_exp_time_t; +typedef image_id apr_os_dso_handle_t; +typedef void* apr_os_shm_t; + +#elif defined(NETWARE) +typedef int apr_os_file_t; +typedef DIR apr_os_dir_t; +typedef int apr_os_sock_t; +typedef NXMutex_t apr_os_proc_mutex_t; +typedef NXThreadId_t apr_os_thread_t; +typedef long apr_os_proc_t; +typedef NXKey_t apr_os_threadkey_t; +typedef struct timeval apr_os_imp_time_t; +typedef struct tm apr_os_exp_time_t; +typedef void * apr_os_dso_handle_t; +typedef void* apr_os_shm_t; + +#else +/* Any other OS should go above this one. This is the lowest common + * denominator typedefs for all UNIX-like systems. :) + */ + +/** Basic OS process mutex structure. */ +struct apr_os_proc_mutex_t { +#if APR_HAS_SYSVSEM_SERIALIZE || APR_HAS_FCNTL_SERIALIZE || APR_HAS_FLOCK_SERIALIZE + /** Value used for SYS V Semaphore, FCNTL and FLOCK serialization */ + int crossproc; +#endif +#if APR_HAS_PROC_PTHREAD_SERIALIZE + /** Value used for PTHREAD serialization */ + pthread_mutex_t *pthread_interproc; +#endif +#if APR_HAS_THREADS + /* If no threads, no need for thread locks */ +#if APR_USE_PTHREAD_SERIALIZE + /** This value is currently unused within APR and Apache */ + pthread_mutex_t *intraproc; +#endif +#endif +#if APR_HAS_POSIXSEM_SERIALIZE + /** Value used for POSIX semaphores serialization */ + sem_t *psem_interproc; +#endif +}; + +typedef int apr_os_file_t; /**< native file */ +typedef DIR apr_os_dir_t; /**< native dir */ +typedef int apr_os_sock_t; /**< native dir */ +typedef struct apr_os_proc_mutex_t apr_os_proc_mutex_t; /**< native process + * mutex + */ +#if APR_HAS_THREADS && APR_HAVE_PTHREAD_H +typedef pthread_t apr_os_thread_t; /**< native thread */ +typedef pthread_key_t apr_os_threadkey_t; /**< native thread address + * space */ +#endif +typedef pid_t apr_os_proc_t; /**< native pid */ +typedef struct timeval apr_os_imp_time_t; /**< native timeval */ +typedef struct tm apr_os_exp_time_t; /**< native tm */ +/** @var apr_os_dso_handle_t + * native dso types + */ +#if defined(HPUX) || defined(HPUX10) || defined(HPUX11) +#include +typedef shl_t apr_os_dso_handle_t; +#elif defined(DARWIN) +#include +typedef NSModule apr_os_dso_handle_t; +#else +typedef void * apr_os_dso_handle_t; +#endif +typedef void* apr_os_shm_t; /**< native SHM */ + +#endif + +/** + * @typedef apr_os_sock_info_t + * @brief alias for local OS socket + */ +/** + * everything APR needs to know about an active socket to construct + * an APR socket from it; currently, this is platform-independent + */ +struct apr_os_sock_info_t { + apr_os_sock_t *os_sock; /**< always required */ + struct sockaddr *local; /**< NULL if not yet bound */ + struct sockaddr *remote; /**< NULL if not connected */ + int family; /**< always required (APR_INET, APR_INET6, etc.) */ + int type; /**< always required (SOCK_STREAM, SOCK_DGRAM, etc.) */ + int protocol; /**< 0 or actual protocol (APR_PROTO_SCTP, APR_PROTO_TCP, etc.) */ +}; + +typedef struct apr_os_sock_info_t apr_os_sock_info_t; + +#if APR_PROC_MUTEX_IS_GLOBAL || defined(DOXYGEN) +/** Opaque global mutex type */ +#define apr_os_global_mutex_t apr_os_proc_mutex_t +/** @return apr_os_global_mutex */ +#define apr_os_global_mutex_get apr_os_proc_mutex_get +#else + /** Thread and process mutex for those platforms where process mutexes + * are not held in threads. + */ + struct apr_os_global_mutex_t { + apr_pool_t *pool; + apr_proc_mutex_t *proc_mutex; +#if APR_HAS_THREADS + apr_thread_mutex_t *thread_mutex; +#endif /* APR_HAS_THREADS */ + }; + typedef struct apr_os_global_mutex_t apr_os_global_mutex_t; + +APR_DECLARE(apr_status_t) apr_os_global_mutex_get(apr_os_global_mutex_t *ospmutex, + apr_global_mutex_t *pmutex); +#endif + + +/** + * convert the file from apr type to os specific type. + * @param thefile The os specific file we are converting to + * @param file The apr file to convert. + * @remark On Unix, it is only possible to get a file descriptor from + * an apr file type. + */ +APR_DECLARE(apr_status_t) apr_os_file_get(apr_os_file_t *thefile, + apr_file_t *file); + +/** + * convert the dir from apr type to os specific type. + * @param thedir The os specific dir we are converting to + * @param dir The apr dir to convert. + */ +APR_DECLARE(apr_status_t) apr_os_dir_get(apr_os_dir_t **thedir, + apr_dir_t *dir); + +/** + * Convert the socket from an apr type to an OS specific socket + * @param thesock The socket to convert. + * @param sock The os specific equivalent of the apr socket.. + */ +APR_DECLARE(apr_status_t) apr_os_sock_get(apr_os_sock_t *thesock, + apr_socket_t *sock); + +/** + * Convert the proc mutex from apr type to os specific type + * @param ospmutex The os specific proc mutex we are converting to. + * @param pmutex The apr proc mutex to convert. + */ +APR_DECLARE(apr_status_t) apr_os_proc_mutex_get(apr_os_proc_mutex_t *ospmutex, + apr_proc_mutex_t *pmutex); + +/** + * Convert the proc mutex from apr type to os specific type, also + * providing the mechanism used by the apr mutex. + * @param ospmutex The os specific proc mutex we are converting to. + * @param pmutex The apr proc mutex to convert. + * @param mech The mechanism used by the apr proc mutex (if not NULL). + * @remark Allows for disambiguation for platforms with multiple mechanisms + * available. + */ +APR_DECLARE(apr_status_t) apr_os_proc_mutex_get_ex(apr_os_proc_mutex_t *ospmutex, + apr_proc_mutex_t *pmutex, + apr_lockmech_e *mech); + +/** + * Get the exploded time in the platforms native format. + * @param ostime the native time format + * @param aprtime the time to convert + */ +APR_DECLARE(apr_status_t) apr_os_exp_time_get(apr_os_exp_time_t **ostime, + apr_time_exp_t *aprtime); + +/** + * Get the imploded time in the platforms native format. + * @param ostime the native time format + * @param aprtime the time to convert + */ +APR_DECLARE(apr_status_t) apr_os_imp_time_get(apr_os_imp_time_t **ostime, + apr_time_t *aprtime); + +/** + * convert the shm from apr type to os specific type. + * @param osshm The os specific shm representation + * @param shm The apr shm to convert. + */ +APR_DECLARE(apr_status_t) apr_os_shm_get(apr_os_shm_t *osshm, + apr_shm_t *shm); + +#if APR_HAS_THREADS || defined(DOXYGEN) +/** + * @defgroup apr_os_thread Thread portability Routines + * @{ + */ +/** + * convert the thread to os specific type from apr type. + * @param thethd The apr thread to convert + * @param thd The os specific thread we are converting to + */ +APR_DECLARE(apr_status_t) apr_os_thread_get(apr_os_thread_t **thethd, + apr_thread_t *thd); + +/** + * convert the thread private memory key to os specific type from an apr type. + * @param thekey The apr handle we are converting from. + * @param key The os specific handle we are converting to. + */ +APR_DECLARE(apr_status_t) apr_os_threadkey_get(apr_os_threadkey_t *thekey, + apr_threadkey_t *key); + +/** + * convert the thread from os specific type to apr type. + * @param thd The apr thread we are converting to. + * @param thethd The os specific thread to convert + * @param cont The pool to use if it is needed. + */ +APR_DECLARE(apr_status_t) apr_os_thread_put(apr_thread_t **thd, + apr_os_thread_t *thethd, + apr_pool_t *cont); + +/** + * convert the thread private memory key from os specific type to apr type. + * @param key The apr handle we are converting to. + * @param thekey The os specific handle to convert + * @param cont The pool to use if it is needed. + */ +APR_DECLARE(apr_status_t) apr_os_threadkey_put(apr_threadkey_t **key, + apr_os_threadkey_t *thekey, + apr_pool_t *cont); +/** + * Get the thread ID + */ +APR_DECLARE(apr_os_thread_t) apr_os_thread_current(void); + +/** + * Compare two thread id's + * @param tid1 1st Thread ID to compare + * @param tid2 2nd Thread ID to compare + * @return non-zero if the two threads are equal, zero otherwise + */ +APR_DECLARE(int) apr_os_thread_equal(apr_os_thread_t tid1, + apr_os_thread_t tid2); + +/** @} */ +#endif /* APR_HAS_THREADS */ + +/** + * convert the file from os specific type to apr type. + * @param file The apr file we are converting to. + * @param thefile The os specific file to convert + * @param flags The flags that were used to open this file. + * @param cont The pool to use if it is needed. + * @remark On Unix, it is only possible to put a file descriptor into + * an apr file type. + */ +APR_DECLARE(apr_status_t) apr_os_file_put(apr_file_t **file, + apr_os_file_t *thefile, + apr_int32_t flags, apr_pool_t *cont); + +/** + * convert the file from os specific type to apr type. + * @param file The apr file we are converting to. + * @param thefile The os specific pipe to convert + * @param cont The pool to use if it is needed. + * @remark On Unix, it is only possible to put a file descriptor into + * an apr file type. + */ +APR_DECLARE(apr_status_t) apr_os_pipe_put(apr_file_t **file, + apr_os_file_t *thefile, + apr_pool_t *cont); + +/** + * convert the file from os specific type to apr type. + * @param file The apr file we are converting to. + * @param thefile The os specific pipe to convert + * @param register_cleanup A cleanup will be registered on the apr_file_t + * to issue apr_file_close(). + * @param cont The pool to use if it is needed. + * @remark On Unix, it is only possible to put a file descriptor into + * an apr file type. + */ +APR_DECLARE(apr_status_t) apr_os_pipe_put_ex(apr_file_t **file, + apr_os_file_t *thefile, + int register_cleanup, + apr_pool_t *cont); + +/** + * convert the dir from os specific type to apr type. + * @param dir The apr dir we are converting to. + * @param thedir The os specific dir to convert + * @param cont The pool to use when creating to apr directory. + */ +APR_DECLARE(apr_status_t) apr_os_dir_put(apr_dir_t **dir, + apr_os_dir_t *thedir, + apr_pool_t *cont); + +/** + * Convert a socket from the os specific type to the APR type. If + * sock points to NULL, a socket will be created from the pool + * provided. If **sock does not point to NULL, the structure pointed + * to by sock will be reused and updated with the given socket. + * @param sock The pool to use. + * @param thesock The socket to convert to. + * @param cont The socket we are converting to an apr type. + * @remark If it is a true socket, it is best to call apr_os_sock_make() + * and provide APR with more information about the socket. + */ +APR_DECLARE(apr_status_t) apr_os_sock_put(apr_socket_t **sock, + apr_os_sock_t *thesock, + apr_pool_t *cont); + +/** + * Create a socket from an existing descriptor and local and remote + * socket addresses. + * @param apr_sock The new socket that has been set up + * @param os_sock_info The os representation of the socket handle and + * other characteristics of the socket + * @param cont The pool to use + * @remark If you only know the descriptor/handle or if it isn't really + * a true socket, use apr_os_sock_put() instead. + */ +APR_DECLARE(apr_status_t) apr_os_sock_make(apr_socket_t **apr_sock, + apr_os_sock_info_t *os_sock_info, + apr_pool_t *cont); + +/** + * Convert the proc mutex from os specific type to apr type + * @param pmutex The apr proc mutex we are converting to. + * @param ospmutex The os specific proc mutex to convert. + * @param cont The pool to use if it is needed. + */ +APR_DECLARE(apr_status_t) apr_os_proc_mutex_put(apr_proc_mutex_t **pmutex, + apr_os_proc_mutex_t *ospmutex, + apr_pool_t *cont); + +/** + * Convert the proc mutex from os specific type to apr type, using the + * specified mechanism. + * @param pmutex The apr proc mutex we are converting to. + * @param ospmutex The os specific proc mutex to convert. + * @param mech The apr mutex locking mechanism + * @param register_cleanup Whether to destroy the os mutex with the apr + * one (either on explicit destroy or pool cleanup). + * @param cont The pool to use if it is needed. + * @remark Allows for disambiguation for platforms with multiple mechanisms + * available. + */ +APR_DECLARE(apr_status_t) apr_os_proc_mutex_put_ex(apr_proc_mutex_t **pmutex, + apr_os_proc_mutex_t *ospmutex, + apr_lockmech_e mech, + int register_cleanup, + apr_pool_t *cont); + +/** + * Put the imploded time in the APR format. + * @param aprtime the APR time format + * @param ostime the time to convert + * @param cont the pool to use if necessary + */ +APR_DECLARE(apr_status_t) apr_os_imp_time_put(apr_time_t *aprtime, + apr_os_imp_time_t **ostime, + apr_pool_t *cont); + +/** + * Put the exploded time in the APR format. + * @param aprtime the APR time format + * @param ostime the time to convert + * @param cont the pool to use if necessary + */ +APR_DECLARE(apr_status_t) apr_os_exp_time_put(apr_time_exp_t *aprtime, + apr_os_exp_time_t **ostime, + apr_pool_t *cont); + +/** + * convert the shared memory from os specific type to apr type. + * @param shm The apr shm representation of osshm + * @param osshm The os specific shm identity + * @param cont The pool to use if it is needed. + * @remark On fork()ed architectures, this is typically nothing more than + * the memory block mapped. On non-fork architectures, this is typically + * some internal handle to pass the mapping from process to process. + */ +APR_DECLARE(apr_status_t) apr_os_shm_put(apr_shm_t **shm, + apr_os_shm_t *osshm, + apr_pool_t *cont); + + +#if APR_HAS_DSO || defined(DOXYGEN) +/** + * @defgroup apr_os_dso DSO (Dynamic Loading) Portability Routines + * @{ + */ +/** + * convert the dso handle from os specific to apr + * @param dso The apr handle we are converting to + * @param thedso the os specific handle to convert + * @param pool the pool to use if it is needed + */ +APR_DECLARE(apr_status_t) apr_os_dso_handle_put(apr_dso_handle_t **dso, + apr_os_dso_handle_t thedso, + apr_pool_t *pool); + +/** + * convert the apr dso handle into an os specific one + * @param aprdso The apr dso handle to convert + * @param dso The os specific dso to return + */ +APR_DECLARE(apr_status_t) apr_os_dso_handle_get(apr_os_dso_handle_t *dso, + apr_dso_handle_t *aprdso); + +/** @} */ +#endif /* APR_HAS_DSO */ + + +#if APR_HAS_OS_UUID +/** + * Private: apr-util's apr_uuid module when supported by the platform + */ +APR_DECLARE(apr_status_t) apr_os_uuid_get(unsigned char *uuid_data); +#endif + + +/** + * Get the name of the system default character set. + * @param pool the pool to allocate the name from, if needed + */ +APR_DECLARE(const char*) apr_os_default_encoding(apr_pool_t *pool); + + +/** + * Get the name of the current locale character set. + * @param pool the pool to allocate the name from, if needed + * @remark Defers to apr_os_default_encoding() if the current locale's + * data can't be retrieved on this system. + */ +APR_DECLARE(const char*) apr_os_locale_encoding(apr_pool_t *pool); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_PORTABLE_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_proc_mutex.h b/c/dependencies/windows/apr/x64/include/apr_proc_mutex.h new file mode 100644 index 00000000..418c9504 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_proc_mutex.h @@ -0,0 +1,192 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_PROC_MUTEX_H +#define APR_PROC_MUTEX_H + +/** + * @file apr_proc_mutex.h + * @brief APR Process Locking Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_perms_set.h" +#include "apr_time.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_proc_mutex Process Locking Routines + * @ingroup APR + * @{ + */ + +/** + * Enumerated potential types for APR process locking methods + * @warning Check APR_HAS_foo_SERIALIZE defines to see if the platform supports + * APR_LOCK_foo. Only APR_LOCK_DEFAULT is portable. + */ +typedef enum { + APR_LOCK_FCNTL, /**< fcntl() */ + APR_LOCK_FLOCK, /**< flock() */ + APR_LOCK_SYSVSEM, /**< System V Semaphores */ + APR_LOCK_PROC_PTHREAD, /**< POSIX pthread process-based locking */ + APR_LOCK_POSIXSEM, /**< POSIX semaphore process-based locking */ + APR_LOCK_DEFAULT, /**< Use the default process lock */ + APR_LOCK_DEFAULT_TIMED /**< Use the default process timed lock */ +} apr_lockmech_e; + +/** Opaque structure representing a process mutex. */ +typedef struct apr_proc_mutex_t apr_proc_mutex_t; + +/* Function definitions */ + +/** + * Create and initialize a mutex that can be used to synchronize processes. + * @param mutex the memory address where the newly created mutex will be + * stored. + * @param fname A file name to use if the lock mechanism requires one. This + * argument should always be provided. The lock code itself will + * determine if it should be used. + * @param mech The mechanism to use for the interprocess lock, if any; one of + *
+ *            APR_LOCK_FCNTL
+ *            APR_LOCK_FLOCK
+ *            APR_LOCK_SYSVSEM
+ *            APR_LOCK_POSIXSEM
+ *            APR_LOCK_PROC_PTHREAD
+ *            APR_LOCK_DEFAULT     pick the default mechanism for the platform
+ * 
+ * @param pool the pool from which to allocate the mutex. + * @see apr_lockmech_e + * @warning Check APR_HAS_foo_SERIALIZE defines to see if the platform supports + * APR_LOCK_foo. Only APR_LOCK_DEFAULT is portable. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_create(apr_proc_mutex_t **mutex, + const char *fname, + apr_lockmech_e mech, + apr_pool_t *pool); + +/** + * Re-open a mutex in a child process. + * @param mutex The newly re-opened mutex structure. + * @param fname A file name to use if the mutex mechanism requires one. This + * argument should always be provided. The mutex code itself will + * determine if it should be used. This filename should be the + * same one that was passed to apr_proc_mutex_create(). + * @param pool The pool to operate on. + * @remark This function must be called to maintain portability, even + * if the underlying lock mechanism does not require it. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_child_init(apr_proc_mutex_t **mutex, + const char *fname, + apr_pool_t *pool); + +/** + * Acquire the lock for the given mutex. If the mutex is already locked, + * the current thread will be put to sleep until the lock becomes available. + * @param mutex the mutex on which to acquire the lock. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_lock(apr_proc_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex. If the mutex has already + * been acquired, the call returns immediately with APR_EBUSY. Note: it + * is important that the APR_STATUS_IS_EBUSY(s) macro be used to determine + * if the return value was APR_EBUSY, for portability reasons. + * @param mutex the mutex on which to attempt the lock acquiring. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_trylock(apr_proc_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex until timeout expires. + * If the acquisition time outs, the call returns with APR_TIMEUP. + * @param mutex the mutex on which to attempt the lock acquiring. + * @param timeout the relative timeout (microseconds). + * @note A negative or nul timeout means immediate attempt, returning + * APR_TIMEUP without blocking if it the lock is already acquired. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_timedlock(apr_proc_mutex_t *mutex, + apr_interval_time_t timeout); + +/** + * Release the lock for the given mutex. + * @param mutex the mutex from which to release the lock. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_unlock(apr_proc_mutex_t *mutex); + +/** + * Destroy the mutex and free the memory associated with the lock. + * @param mutex the mutex to destroy. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_destroy(apr_proc_mutex_t *mutex); + +/** + * Destroy the mutex and free the memory associated with the lock. + * @param mutex the mutex to destroy. + * @note This function is generally used to kill a cleanup on an already + * created mutex + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_cleanup(void *mutex); + +/** + * Return the name of the lockfile for the mutex, or NULL + * if the mutex doesn't use a lock file + */ + +APR_DECLARE(const char *) apr_proc_mutex_lockfile(apr_proc_mutex_t *mutex); + +/** + * Get the mechanism of the mutex, as it relates to the actual method + * used for the underlying apr_proc_mutex_t. + * @param mutex the mutex to get the mechanism from. + */ +APR_DECLARE(apr_lockmech_e) apr_proc_mutex_mech(apr_proc_mutex_t *mutex); + +/** + * Get the mechanism's name of the mutex, as it relates to the actual method + * used for the underlying apr_proc_mutex_t. + * @param mutex the mutex to get the mechanism's name from. + */ +APR_DECLARE(const char *) apr_proc_mutex_name(apr_proc_mutex_t *mutex); + +/** + * Display the name of the default mutex: APR_LOCK_DEFAULT + */ +APR_DECLARE(const char *) apr_proc_mutex_defname(void); + +/** + * Set mutex permissions. + */ +APR_PERMS_SET_IMPLEMENT(proc_mutex); + +/** + * Get the pool used by this proc_mutex. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(proc_mutex); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_PROC_MUTEX_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_queue.h b/c/dependencies/windows/apr/x64/include/apr_queue.h new file mode 100644 index 00000000..a3a41704 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_queue.h @@ -0,0 +1,138 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_QUEUE_H +#define APR_QUEUE_H + +/** + * @file apr_queue.h + * @brief Thread Safe FIFO bounded queue + * @note Since most implementations of the queue are backed by a condition + * variable implementation, it isn't available on systems without threads. + * Although condition variables are sometimes available without threads. + */ + +#include "apu.h" +#include "apr_errno.h" +#include "apr_pools.h" + +#if APR_HAS_THREADS + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_Util_FIFO Thread Safe FIFO bounded queue + * @ingroup APR_Util + * @{ + */ + +/** + * opaque structure + */ +typedef struct apr_queue_t apr_queue_t; + +/** + * create a FIFO queue + * @param queue The new queue + * @param queue_capacity maximum size of the queue + * @param a pool to allocate queue from + */ +APU_DECLARE(apr_status_t) apr_queue_create(apr_queue_t **queue, + unsigned int queue_capacity, + apr_pool_t *a); + +/** + * push/add an object to the queue, blocking if the queue is already full + * + * @param queue the queue + * @param data the data + * @returns APR_EINTR the blocking was interrupted (try again) + * @returns APR_EOF the queue has been terminated + * @returns APR_SUCCESS on a successful push + */ +APU_DECLARE(apr_status_t) apr_queue_push(apr_queue_t *queue, void *data); + +/** + * pop/get an object from the queue, blocking if the queue is already empty + * + * @param queue the queue + * @param data the data + * @returns APR_EINTR the blocking was interrupted (try again) + * @returns APR_EOF if the queue has been terminated + * @returns APR_SUCCESS on a successful pop + */ +APU_DECLARE(apr_status_t) apr_queue_pop(apr_queue_t *queue, void **data); + +/** + * push/add an object to the queue, returning immediately if the queue is full + * + * @param queue the queue + * @param data the data + * @returns APR_EINTR the blocking operation was interrupted (try again) + * @returns APR_EAGAIN the queue is full + * @returns APR_EOF the queue has been terminated + * @returns APR_SUCCESS on a successful push + */ +APU_DECLARE(apr_status_t) apr_queue_trypush(apr_queue_t *queue, void *data); + +/** + * pop/get an object to the queue, returning immediately if the queue is empty + * + * @param queue the queue + * @param data the data + * @returns APR_EINTR the blocking operation was interrupted (try again) + * @returns APR_EAGAIN the queue is empty + * @returns APR_EOF the queue has been terminated + * @returns APR_SUCCESS on a successful pop + */ +APU_DECLARE(apr_status_t) apr_queue_trypop(apr_queue_t *queue, void **data); + +/** + * returns the size of the queue. + * + * @warning this is not threadsafe, and is intended for reporting/monitoring + * of the queue. + * @param queue the queue + * @returns the size of the queue + */ +APU_DECLARE(unsigned int) apr_queue_size(apr_queue_t *queue); + +/** + * interrupt all the threads blocking on this queue. + * + * @param queue the queue + */ +APU_DECLARE(apr_status_t) apr_queue_interrupt_all(apr_queue_t *queue); + +/** + * terminate the queue, sending an interrupt to all the + * blocking threads + * + * @param queue the queue + */ +APU_DECLARE(apr_status_t) apr_queue_term(apr_queue_t *queue); + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif /* APR_HAS_THREADS */ + +#endif /* APRQUEUE_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_random.h b/c/dependencies/windows/apr/x64/include/apr_random.h new file mode 100644 index 00000000..29154358 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_random.h @@ -0,0 +1,153 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_RANDOM_H +#define APR_RANDOM_H + +/** + * @file apr_random.h + * @brief APR PRNG routines + */ + +#include "apr_pools.h" +#include "apr_thread_proc.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_random PRNG Routines + * @ingroup APR + * @{ + */ + +typedef struct apr_crypto_hash_t apr_crypto_hash_t; + +typedef void apr_crypto_hash_init_t(apr_crypto_hash_t *hash); +typedef void apr_crypto_hash_add_t(apr_crypto_hash_t *hash, const void *data, + apr_size_t bytes); +typedef void apr_crypto_hash_finish_t(apr_crypto_hash_t *hash, + unsigned char *result); + + +/* FIXME: make this opaque */ +struct apr_crypto_hash_t { + apr_crypto_hash_init_t *init; + apr_crypto_hash_add_t *add; + apr_crypto_hash_finish_t *finish; + apr_size_t size; + void *data; +}; + +/** + * Allocate and initialize the SHA-256 context + * @param p The pool to allocate from + */ +APR_DECLARE(apr_crypto_hash_t *) apr_crypto_sha256_new(apr_pool_t *p); + +/** Opaque PRNG structure. */ +typedef struct apr_random_t apr_random_t; + +/** + * Initialize a PRNG state + * @param g The PRNG state + * @param p The pool to allocate from + * @param pool_hash Pool hash functions + * @param key_hash Key hash functions + * @param prng_hash PRNG hash functions + */ +APR_DECLARE(void) apr_random_init(apr_random_t *g, apr_pool_t *p, + apr_crypto_hash_t *pool_hash, + apr_crypto_hash_t *key_hash, + apr_crypto_hash_t *prng_hash); +/** + * Allocate and initialize (apr_crypto_sha256_new) a new PRNG state. + * @param p The pool to allocate from + */ +APR_DECLARE(apr_random_t *) apr_random_standard_new(apr_pool_t *p); + +/** + * Mix the randomness pools. + * @param g The PRNG state + * @param entropy_ Entropy buffer + * @param bytes Length of entropy_ in bytes + */ +APR_DECLARE(void) apr_random_add_entropy(apr_random_t *g, + const void *entropy_, + apr_size_t bytes); +/** + * Generate cryptographically insecure random bytes. + * @param g The RNG state + * @param random Buffer to fill with random bytes + * @param bytes Length of buffer in bytes + */ +APR_DECLARE(apr_status_t) apr_random_insecure_bytes(apr_random_t *g, + void *random, + apr_size_t bytes); + +/** + * Generate cryptographically secure random bytes. + * @param g The RNG state + * @param random Buffer to fill with random bytes + * @param bytes Length of buffer in bytes + */ +APR_DECLARE(apr_status_t) apr_random_secure_bytes(apr_random_t *g, + void *random, + apr_size_t bytes); +/** + * Ensures that E bits of conditional entropy are mixed into the PRNG + * before any further randomness is extracted. + * @param g The RNG state + */ +APR_DECLARE(void) apr_random_barrier(apr_random_t *g); + +/** + * Return APR_SUCCESS if the cryptographic PRNG has been seeded with + * enough data, APR_ENOTENOUGHENTROPY otherwise. + * @param r The RNG state + */ +APR_DECLARE(apr_status_t) apr_random_secure_ready(apr_random_t *r); + +/** + * Return APR_SUCCESS if the PRNG has been seeded with enough data, + * APR_ENOTENOUGHENTROPY otherwise. + * @param r The PRNG state + */ +APR_DECLARE(apr_status_t) apr_random_insecure_ready(apr_random_t *r); + +/** + * Mix the randomness pools after forking. + * @param proc The resulting process handle from apr_proc_fork() + * @remark Call this in the child after forking to mix the randomness + * pools. Note that its generally a bad idea to fork a process with a + * real PRNG in it - better to have the PRNG externally and get the + * randomness from there. However, if you really must do it, then you + * should supply all your entropy to all the PRNGs - don't worry, they + * won't produce the same output. + * @remark Note that apr_proc_fork() calls this for you, so only weird + * applications need ever call it themselves. + * @internal + */ +APR_DECLARE(void) apr_random_after_fork(apr_proc_t *proc); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_RANDOM_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_redis.h b/c/dependencies/windows/apr/x64/include/apr_redis.h new file mode 100644 index 00000000..66a828b0 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_redis.h @@ -0,0 +1,459 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_redis.h + * @brief Client interface for redis + * @remark To use this interface you must have a separate redis + * for more information. + */ + +#ifndef APR_REDIS_H +#define APR_REDIS_H + +#include "apr.h" +#include "apr_pools.h" +#include "apr_time.h" +#include "apr_strings.h" +#include "apr_network_io.h" +#include "apr_ring.h" +#include "apr_buckets.h" +#include "apr_reslist.h" +#include "apr_hash.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#ifndef RC_DEFAULT_SERVER_PORT +#define RC_DEFAULT_SERVER_PORT 6379 +#endif + +#ifndef RC_DEFAULT_SERVER_MIN +#define RC_DEFAULT_SERVER_MIN 0 +#endif + +#ifndef RC_DEFAULT_SERVER_SMAX +#define RC_DEFAULT_SERVER_SMAX 1 +#endif + +#ifndef RC_DEFAULT_SERVER_TTL +#define RC_DEFAULT_SERVER_TTL 600 +#endif + +/** + * @defgroup APR_Util_RC Redis Client Routines + * @ingroup APR_Util + * @{ + */ + +/** Specifies the status of a redis server */ +typedef enum +{ + APR_RC_SERVER_LIVE, /**< Server is alive and responding to requests */ + APR_RC_SERVER_DEAD /**< Server is not responding to requests */ +} apr_redis_server_status_t; + +/** Opaque redis client connection object */ +typedef struct apr_redis_conn_t apr_redis_conn_t; + +/** Redis Server Info Object */ +typedef struct apr_redis_server_t apr_redis_server_t; +struct apr_redis_server_t +{ + const char *host; /**< Hostname of this Server */ + apr_port_t port; /**< Port of this Server */ + apr_redis_server_status_t status; /**< @see apr_redis_server_status_t */ +#if APR_HAS_THREADS || defined(DOXYGEN) + apr_reslist_t *conns; /**< Resource list of actual client connections */ +#else + apr_redis_conn_t *conn; +#endif + apr_pool_t *p; /** Pool to use for private allocations */ +#if APR_HAS_THREADS + apr_thread_mutex_t *lock; +#endif + apr_time_t btime; + apr_uint32_t rwto; + struct + { + int major; + int minor; + int patch; + char *number; + } version; +}; + +typedef struct apr_redis_t apr_redis_t; + +/* Custom hash callback function prototype, user for server selection. +* @param baton user selected baton +* @param data data to hash +* @param data_len length of data +*/ +typedef apr_uint32_t (*apr_redis_hash_func)(void *baton, + const char *data, + const apr_size_t data_len); +/* Custom Server Select callback function prototype. +* @param baton user selected baton +* @param rc redis instance, use rc->live_servers to select a node +* @param hash hash of the selected key. +*/ +typedef apr_redis_server_t* (*apr_redis_server_func)(void *baton, + apr_redis_t *rc, + const apr_uint32_t hash); + +/** Container for a set of redis servers */ +struct apr_redis_t +{ + apr_uint32_t flags; /**< Flags, Not currently used */ + apr_uint16_t nalloc; /**< Number of Servers Allocated */ + apr_uint16_t ntotal; /**< Number of Servers Added */ + apr_redis_server_t **live_servers; /**< Array of Servers */ + apr_pool_t *p; /** Pool to use for allocations */ + void *hash_baton; + apr_redis_hash_func hash_func; + void *server_baton; + apr_redis_server_func server_func; +}; + +/** + * Creates a crc32 hash used to split keys between servers + * @param rc The redis client object to use + * @param data Data to be hashed + * @param data_len Length of the data to use + * @return crc32 hash of data + * @remark The crc32 hash is not compatible with old redisd clients. + */ +APU_DECLARE(apr_uint32_t) apr_redis_hash(apr_redis_t *rc, + const char *data, + const apr_size_t data_len); + +/** + * Pure CRC32 Hash. Used by some clients. + */ +APU_DECLARE(apr_uint32_t) apr_redis_hash_crc32(void *baton, + const char *data, + const apr_size_t data_len); + +/** + * hash compatible with the standard Perl Client. + */ +APU_DECLARE(apr_uint32_t) apr_redis_hash_default(void *baton, + const char *data, + const apr_size_t data_len); + +/** + * Picks a server based on a hash + * @param rc The redis client object to use + * @param hash Hashed value of a Key + * @return server that controls specified hash + * @see apr_redis_hash + */ +APU_DECLARE(apr_redis_server_t *) apr_redis_find_server_hash(apr_redis_t *rc, + const apr_uint32_t hash); + +/** + * server selection compatible with the standard Perl Client. + */ +APU_DECLARE(apr_redis_server_t *) apr_redis_find_server_hash_default(void *baton, + apr_redis_t *rc, + const apr_uint32_t hash); + +/** + * Adds a server to a client object + * @param rc The redis client object to use + * @param server Server to add + * @remark Adding servers is not thread safe, and should be done once at startup. + * @warning Changing servers after startup may cause keys to go to + * different servers. + */ +APU_DECLARE(apr_status_t) apr_redis_add_server(apr_redis_t *rc, + apr_redis_server_t *server); + + +/** + * Finds a Server object based on a hostname/port pair + * @param rc The redis client object to use + * @param host Hostname of the server + * @param port Port of the server + * @return Server with matching Hostname and Port, or NULL if none was found. + */ +APU_DECLARE(apr_redis_server_t *) apr_redis_find_server(apr_redis_t *rc, + const char *host, + apr_port_t port); + +/** + * Enables a Server for use again + * @param rc The redis client object to use + * @param rs Server to Activate + */ +APU_DECLARE(apr_status_t) apr_redis_enable_server(apr_redis_t *rc, + apr_redis_server_t *rs); + + +/** + * Disable a Server + * @param rc The redis client object to use + * @param rs Server to Disable + */ +APU_DECLARE(apr_status_t) apr_redis_disable_server(apr_redis_t *rc, + apr_redis_server_t *rs); + +/** + * Creates a new Server Object + * @param p Pool to use + * @param host hostname of the server + * @param port port of the server + * @param min minimum number of client sockets to open + * @param smax soft maximum number of client connections to open + * @param max hard maximum number of client connections + * @param ttl time to live in microseconds of a client connection + * @param rwto r/w timeout value in seconds of a client connection + * @param ns location of the new server object + * @see apr_reslist_create + * @remark min, smax, and max are only used when APR_HAS_THREADS + */ +APU_DECLARE(apr_status_t) apr_redis_server_create(apr_pool_t *p, + const char *host, + apr_port_t port, + apr_uint32_t min, + apr_uint32_t smax, + apr_uint32_t max, + apr_uint32_t ttl, + apr_uint32_t rwto, + apr_redis_server_t **ns); +/** + * Creates a new redisd client object + * @param p Pool to use + * @param max_servers maximum number of servers + * @param flags Not currently used + * @param rc location of the new redis client object + */ +APU_DECLARE(apr_status_t) apr_redis_create(apr_pool_t *p, + apr_uint16_t max_servers, + apr_uint32_t flags, + apr_redis_t **rc); + +/** + * Gets a value from the server, allocating the value out of p + * @param rc client to use + * @param p Pool to use + * @param key null terminated string containing the key + * @param baton location of the allocated value + * @param len length of data at baton + * @param flags any flags set by the client for this key + * @return + */ +APU_DECLARE(apr_status_t) apr_redis_getp(apr_redis_t *rc, + apr_pool_t *p, + const char* key, + char **baton, + apr_size_t *len, + apr_uint16_t *flags); + +/** + * Sets a value by key on the server + * @param rc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param flags any flags set by the client for this key + */ +APU_DECLARE(apr_status_t) apr_redis_set(apr_redis_t *rc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint16_t flags); + +/** + * Sets a value by key on the server + * @param rc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param timeout time in seconds for the data to live on the server + * @param flags any flags set by the client for this key + */ +APU_DECLARE(apr_status_t) apr_redis_setex(apr_redis_t *rc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint32_t timeout, + apr_uint16_t flags); + +/** + * Deletes a key from a server + * @param rc client to use + * @param key null terminated string containing the key + * @param timeout time for the delete to stop other clients from adding + */ +APU_DECLARE(apr_status_t) apr_redis_delete(apr_redis_t *rc, + const char *key, + apr_uint32_t timeout); + +/** + * Query a server's version + * @param rs server to query + * @param p Pool to allocate answer from + * @param baton location to store server version string + */ +APU_DECLARE(apr_status_t) apr_redis_version(apr_redis_server_t *rs, + apr_pool_t *p, + char **baton); + +/** + * Query a server's INFO + * @param rs server to query + * @param p Pool to allocate answer from + * @param baton location to store server INFO response string + */ +APU_DECLARE(apr_status_t) apr_redis_info(apr_redis_server_t *rs, + apr_pool_t *p, + char **baton); + +/** + * Increments a value + * @param rc client to use + * @param key null terminated string containing the key + * @param inc number to increment by + * @param new_value new value after incrementing + */ +APU_DECLARE(apr_status_t) apr_redis_incr(apr_redis_t *rc, + const char *key, + apr_int32_t inc, + apr_uint32_t *new_value); +/** + * Decrements a value + * @param rc client to use + * @param key null terminated string containing the key + * @param inc number to decrement by + * @param new_value new value after decrementing + */ +APU_DECLARE(apr_status_t) apr_redis_decr(apr_redis_t *rc, + const char *key, + apr_int32_t inc, + apr_uint32_t *new_value); + + +/** + * Pings the server + * @param rs Server to ping + */ +APU_DECLARE(apr_status_t) apr_redis_ping(apr_redis_server_t *rs); + +/** + * Gets multiple values from the server, allocating the values out of p + * @param rc client to use + * @param temp_pool Pool used for temporary allocations. May be cleared inside this + * call. + * @param data_pool Pool used to allocate data for the returned values. + * @param values hash of apr_redis_value_t keyed by strings, contains the + * result of the multiget call. + * @return + */ +APU_DECLARE(apr_status_t) apr_redis_multgetp(apr_redis_t *rc, + apr_pool_t *temp_pool, + apr_pool_t *data_pool, + apr_hash_t *values); + +typedef enum +{ + APR_RS_SERVER_MASTER, /**< Server is a master */ + APR_RS_SERVER_SLAVE, /**< Server is a slave */ + APR_RS_SERVER_UNKNOWN /**< Server role is unknown */ +} apr_redis_server_role_t; + +typedef struct +{ +/* # Server */ + /** Major version number of this server */ + apr_uint32_t major; + /** Minor version number of this server */ + apr_uint32_t minor; + /** Patch version number of this server */ + apr_uint32_t patch; + /** Process id of this server process */ + apr_uint32_t process_id; + /** Number of seconds this server has been running */ + apr_uint32_t uptime_in_seconds; + /** Bitsize of the arch on the current machine */ + apr_uint32_t arch_bits; + +/* # Clients */ + /** Number of connected clients */ + apr_uint32_t connected_clients; + /** Number of blocked clients */ + apr_uint32_t blocked_clients; + +/* # Memory */ + /** Max memory of this server */ + apr_uint64_t maxmemory; + /** Amount of used memory */ + apr_uint64_t used_memory; + /** Total memory available on this server */ + apr_uint64_t total_system_memory; + +/* # Stats */ + /** Total connections received */ + apr_uint64_t total_connections_received; + /** Total commands processed */ + apr_uint64_t total_commands_processed; + /** Total commands rejected */ + apr_uint64_t rejected_connections; + /** Total net input bytes */ + apr_uint64_t total_net_input_bytes; + /** Total net output bytes */ + apr_uint64_t total_net_output_bytes; + /** Keyspace hits */ + apr_uint64_t keyspace_hits; + /** Keyspace misses */ + apr_uint64_t keyspace_misses; + +/* # Replication */ + /** Role */ + apr_redis_server_role_t role; + /** Number of connected slave */ + apr_uint32_t connected_slaves; + +/* # CPU */ + /** Accumulated CPU user time for this process */ + apr_uint32_t used_cpu_sys; + /** Accumulated CPU system time for this process */ + apr_uint32_t used_cpu_user; + +/* # Cluster */ + /** Is cluster enabled */ + apr_uint32_t cluster_enabled; +} apr_redis_stats_t; + +/** + * Query a server for statistics + * @param rs server to query + * @param p Pool to allocate answer from + * @param stats location of the new statistics structure + */ +APU_DECLARE(apr_status_t) apr_redis_stats(apr_redis_server_t *rs, + apr_pool_t *p, + apr_redis_stats_t **stats); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_REDIS_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_reslist.h b/c/dependencies/windows/apr/x64/include/apr_reslist.h new file mode 100644 index 00000000..02a8192b --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_reslist.h @@ -0,0 +1,183 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_RESLIST_H +#define APR_RESLIST_H + +/** + * @file apr_reslist.h + * @brief APR-UTIL Resource List Routines + */ + +#include "apr.h" +#include "apu.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_time.h" + +/** + * @defgroup APR_Util_RL Resource List Routines + * @ingroup APR_Util + * @{ + */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** Opaque resource list object */ +typedef struct apr_reslist_t apr_reslist_t; + +/* Generic constructor called by resource list when it needs to create a + * resource. + * @param resource opaque resource + * @param params flags + * @param pool Pool + */ +typedef apr_status_t (*apr_reslist_constructor)(void **resource, void *params, + apr_pool_t *pool); + +/* Generic destructor called by resource list when it needs to destroy a + * resource. + * @param resource opaque resource + * @param params flags + * @param pool Pool + */ +typedef apr_status_t (*apr_reslist_destructor)(void *resource, void *params, + apr_pool_t *pool); + +/* Cleanup order modes */ +#define APR_RESLIST_CLEANUP_DEFAULT 0 /**< default pool cleanup */ +#define APR_RESLIST_CLEANUP_FIRST 1 /**< use pool pre cleanup */ + +/** + * Create a new resource list with the following parameters: + * @param reslist An address where the pointer to the new resource + * list will be stored. + * @param min Allowed minimum number of available resources. Zero + * creates new resources only when needed. + * @param smax Resources will be destroyed during reslist maintenance to + * meet this maximum restriction as they expire (reach their ttl). + * @param hmax Absolute maximum limit on the number of total resources. + * @param ttl If non-zero, sets the maximum amount of time in microseconds an + * unused resource is valid. Any resource which has exceeded this + * time will be destroyed, either when encountered by + * apr_reslist_acquire() or during reslist maintenance. + * @param con Constructor routine that is called to create a new resource. + * @param de Destructor routine that is called to destroy an expired resource. + * @param params Passed to constructor and deconstructor + * @param pool The pool from which to create this resource list. Also the + * same pool that is passed to the constructor and destructor + * routines. + * @remark If APR has been compiled without thread support, hmax will be + * automatically set to 1 and values of min and smax will be forced to + * 1 for any non-zero value. + */ +APU_DECLARE(apr_status_t) apr_reslist_create(apr_reslist_t **reslist, + int min, int smax, int hmax, + apr_interval_time_t ttl, + apr_reslist_constructor con, + apr_reslist_destructor de, + void *params, + apr_pool_t *pool); + +/** + * Destroy the given resource list and all resources controlled by + * this list. + * FIXME: Should this block until all resources become available, + * or maybe just destroy all the free ones, or maybe destroy + * them even though they might be in use by something else? + * Currently it will abort if there are resources that haven't + * been released, so there is an assumption that all resources + * have been released to the list before calling this function. + * @param reslist The reslist to destroy + */ +APU_DECLARE(apr_status_t) apr_reslist_destroy(apr_reslist_t *reslist); + +/** + * Retrieve a resource from the list, creating a new one if necessary. + * If we have met our maximum number of resources, we will block + * until one becomes available. + * @param reslist The resource list. + * @param resource An address where the pointer to the resource + * will be stored. + */ +APU_DECLARE(apr_status_t) apr_reslist_acquire(apr_reslist_t *reslist, + void **resource); + +/** + * Return a resource back to the list of available resources. + * @param reslist The resource list. + * @param resource The resource to return to the list. + */ +APU_DECLARE(apr_status_t) apr_reslist_release(apr_reslist_t *reslist, + void *resource); + +/** + * Set the timeout the acquire will wait for a free resource + * when the maximum number of resources is exceeded. + * @param reslist The resource list. + * @param timeout Timeout to wait. The zero waits forever. + */ +APU_DECLARE(void) apr_reslist_timeout_set(apr_reslist_t *reslist, + apr_interval_time_t timeout); + +/** + * Return the number of outstanding resources. + * @param reslist The resource list. + */ +APU_DECLARE(apr_uint32_t) apr_reslist_acquired_count(apr_reslist_t *reslist); + +/** + * Invalidate a resource in the pool - e.g. a database connection + * that returns a "lost connection" error and can't be restored. + * Use this instead of apr_reslist_release if the resource is bad. + * @param reslist The resource list. + * @param resource The resource to invalidate. + */ +APU_DECLARE(apr_status_t) apr_reslist_invalidate(apr_reslist_t *reslist, + void *resource); + +/** + * Perform routine maintenance on the resource list. This call + * may instantiate new resources or expire old resources. + * @param reslist The resource list. + */ +APU_DECLARE(apr_status_t) apr_reslist_maintain(apr_reslist_t *reslist); + +/** + * Set reslist cleanup order. + * @param reslist The resource list. + * @param mode Cleanup order mode + *
+ *           APR_RESLIST_CLEANUP_DEFAULT  default pool cleanup order
+ *           APR_RESLIST_CLEANUP_FIRST    use pool pre cleanup
+ * 
+ * @remark If APR_RESLIST_CLEANUP_FIRST is used the destructors will + * be called before child pools of the pool used to create the reslist + * are destroyed. This allows to explicitly destroy the child pools + * inside reslist destructors. + */ +APU_DECLARE(void) apr_reslist_cleanup_order_set(apr_reslist_t *reslist, + apr_uint32_t mode); + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif /* ! APR_RESLIST_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_ring.h b/c/dependencies/windows/apr/x64/include/apr_ring.h new file mode 100644 index 00000000..eec735fc --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_ring.h @@ -0,0 +1,513 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * This code draws heavily from the 4.4BSD macros + * and Dean Gaudet's "splim/ring.h". + * + * + * + * We'd use Dean's code directly if we could guarantee the + * availability of inline functions. + */ + +#ifndef APR_RING_H +#define APR_RING_H + +/** + * @file apr_ring.h + * @brief APR Rings + */ + +/* + * for offsetof() + */ +#include "apr_general.h" + +/** + * @defgroup apr_ring Ring Macro Implementations + * @ingroup APR + * A ring is a kind of doubly-linked list that can be manipulated + * without knowing where its head is. + * @{ + */ + +/** + * The Ring Element + * + * A ring element struct is linked to the other elements in the ring + * through its ring entry field, e.g. + *
+ *      struct my_element_t {
+ *          APR_RING_ENTRY(my_element_t) link;
+ *          int foo;
+ *          char *bar;
+ *      };
+ * 
+ * + * An element struct may be put on more than one ring if it has more + * than one APR_RING_ENTRY field. Each APR_RING_ENTRY has a corresponding + * APR_RING_HEAD declaration. + * + * @warning For strict C standards compliance you should put the APR_RING_ENTRY + * first in the element struct unless the head is always part of a larger + * object with enough earlier fields to accommodate the offsetof() used + * to compute the ring sentinel below. You can usually ignore this caveat. + */ +#define APR_RING_ENTRY(elem) \ + struct { \ + struct elem * volatile next; \ + struct elem * volatile prev; \ + } + +/** + * The Ring Head + * + * Each ring is managed via its head, which is a struct declared like this: + *
+ *      APR_RING_HEAD(my_ring_t, my_element_t);
+ *      struct my_ring_t ring, *ringp;
+ * 
+ * + * This struct looks just like the element link struct so that we can + * be sure that the typecasting games will work as expected. + * + * The first element in the ring is next after the head, and the last + * element is just before the head. + */ +#define APR_RING_HEAD(head, elem) \ + struct head { \ + struct elem * volatile next; \ + struct elem * volatile prev; \ + } + +/** + * The Ring Sentinel + * + * This is the magic pointer value that occurs before the first and + * after the last elements in the ring, computed from the address of + * the ring's head. The head itself isn't an element, but in order to + * get rid of all the special cases when dealing with the ends of the + * ring, we play typecasting games to make it look like one. + * + * Here is a diagram to illustrate the arrangements of the next and + * prev pointers of each element in a single ring. Note that they point + * to the start of each element, not to the APR_RING_ENTRY structure. + * + *
+ *     +->+------+<-+  +->+------+<-+  +->+------+<-+
+ *     |  |struct|  |  |  |struct|  |  |  |struct|  |
+ *    /   | elem |   \/   | elem |   \/   | elem |  \
+ * ...    |      |   /\   |      |   /\   |      |   ...
+ *        +------+  |  |  +------+  |  |  +------+
+ *   ...--|prev  |  |  +--|ring  |  |  +--|prev  |
+ *        |  next|--+     | entry|--+     |  next|--...
+ *        +------+        +------+        +------+
+ *        | etc. |        | etc. |        | etc. |
+ *        :      :        :      :        :      :
+ * 
+ * + * The APR_RING_HEAD is nothing but a bare APR_RING_ENTRY. The prev + * and next pointers in the first and last elements don't actually + * point to the head, they point to a phantom place called the + * sentinel. Its value is such that last->next->next == first because + * the offset from the sentinel to the head's next pointer is the same + * as the offset from the start of an element to its next pointer. + * This also works in the opposite direction. + * + *
+ *        last                            first
+ *     +->+------+<-+  +->sentinel<-+  +->+------+<-+
+ *     |  |struct|  |  |            |  |  |struct|  |
+ *    /   | elem |   \/              \/   | elem |  \
+ * ...    |      |   /\              /\   |      |   ...
+ *        +------+  |  |  +------+  |  |  +------+
+ *   ...--|prev  |  |  +--|ring  |  |  +--|prev  |
+ *        |  next|--+     |  head|--+     |  next|--...
+ *        +------+        +------+        +------+
+ *        | etc. |                        | etc. |
+ *        :      :                        :      :
+ * 
+ * + * Note that the offset mentioned above is different for each kind of + * ring that the element may be on, and each kind of ring has a unique + * name for its APR_RING_ENTRY in each element, and has its own type + * for its APR_RING_HEAD. + * + * Note also that if the offset is non-zero (which is required if an + * element has more than one APR_RING_ENTRY), the unreality of the + * sentinel may have bad implications on very perverse implementations + * of C -- see the warning in APR_RING_ENTRY. + * + * @param hp The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SENTINEL(hp, elem, link) \ + (struct elem *)((char *)(&(hp)->next) - APR_OFFSETOF(struct elem, link)) + +/** + * The first element of the ring + * @param hp The head of the ring + */ +#define APR_RING_FIRST(hp) (hp)->next +/** + * The last element of the ring + * @param hp The head of the ring + */ +#define APR_RING_LAST(hp) (hp)->prev +/** + * The next element in the ring + * @param ep The current element + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_NEXT(ep, link) (ep)->link.next +/** + * The previous element in the ring + * @param ep The current element + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_PREV(ep, link) (ep)->link.prev + + +/** + * Initialize a ring + * @param hp The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INIT(hp, elem, link) do { \ + APR_RING_FIRST((hp)) = APR_RING_SENTINEL((hp), elem, link); \ + APR_RING_LAST((hp)) = APR_RING_SENTINEL((hp), elem, link); \ + } while (0) + +/** + * Determine if a ring is empty + * @param hp The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + * @return true or false + */ +#define APR_RING_EMPTY(hp, elem, link) \ + (APR_RING_FIRST((hp)) == APR_RING_SENTINEL((hp), elem, link)) + +/** + * Initialize a singleton element + * @param ep The element + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_ELEM_INIT(ep, link) do { \ + APR_RING_NEXT((ep), link) = (ep); \ + APR_RING_PREV((ep), link) = (ep); \ + } while (0) + + +/** + * Splice the sequence ep1..epN into the ring before element lep + * (..lep.. becomes ..ep1..epN..lep..) + * @warning This doesn't work for splicing before the first element or on + * empty rings... see APR_RING_SPLICE_HEAD for one that does + * @param lep Element in the ring to splice before + * @param ep1 First element in the sequence to splice in + * @param epN Last element in the sequence to splice in + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SPLICE_BEFORE(lep, ep1, epN, link) do { \ + APR_RING_NEXT((epN), link) = (lep); \ + APR_RING_PREV((ep1), link) = APR_RING_PREV((lep), link); \ + APR_RING_NEXT(APR_RING_PREV((lep), link), link) = (ep1); \ + APR_RING_PREV((lep), link) = (epN); \ + } while (0) + +/** + * Splice the sequence ep1..epN into the ring after element lep + * (..lep.. becomes ..lep..ep1..epN..) + * @warning This doesn't work for splicing after the last element or on + * empty rings... see APR_RING_SPLICE_TAIL for one that does + * @param lep Element in the ring to splice after + * @param ep1 First element in the sequence to splice in + * @param epN Last element in the sequence to splice in + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SPLICE_AFTER(lep, ep1, epN, link) do { \ + APR_RING_PREV((ep1), link) = (lep); \ + APR_RING_NEXT((epN), link) = APR_RING_NEXT((lep), link); \ + APR_RING_PREV(APR_RING_NEXT((lep), link), link) = (epN); \ + APR_RING_NEXT((lep), link) = (ep1); \ + } while (0) + +/** + * Insert the element nep into the ring before element lep + * (..lep.. becomes ..nep..lep..) + * @warning This doesn't work for inserting before the first element or on + * empty rings... see APR_RING_INSERT_HEAD for one that does + * @param lep Element in the ring to insert before + * @param nep Element to insert + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INSERT_BEFORE(lep, nep, link) \ + APR_RING_SPLICE_BEFORE((lep), (nep), (nep), link) + +/** + * Insert the element nep into the ring after element lep + * (..lep.. becomes ..lep..nep..) + * @warning This doesn't work for inserting after the last element or on + * empty rings... see APR_RING_INSERT_TAIL for one that does + * @param lep Element in the ring to insert after + * @param nep Element to insert + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INSERT_AFTER(lep, nep, link) \ + APR_RING_SPLICE_AFTER((lep), (nep), (nep), link) + + +/** + * Splice the sequence ep1..epN into the ring before the first element + * (..hp.. becomes ..hp..ep1..epN..) + * @param hp Head of the ring + * @param ep1 First element in the sequence to splice in + * @param epN Last element in the sequence to splice in + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SPLICE_HEAD(hp, ep1, epN, elem, link) \ + APR_RING_SPLICE_AFTER(APR_RING_SENTINEL((hp), elem, link), \ + (ep1), (epN), link) + +/** + * Splice the sequence ep1..epN into the ring after the last element + * (..hp.. becomes ..ep1..epN..hp..) + * @param hp Head of the ring + * @param ep1 First element in the sequence to splice in + * @param epN Last element in the sequence to splice in + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SPLICE_TAIL(hp, ep1, epN, elem, link) \ + APR_RING_SPLICE_BEFORE(APR_RING_SENTINEL((hp), elem, link), \ + (ep1), (epN), link) + +/** + * Insert the element nep into the ring before the first element + * (..hp.. becomes ..hp..nep..) + * @param hp Head of the ring + * @param nep Element to insert + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INSERT_HEAD(hp, nep, elem, link) \ + APR_RING_SPLICE_HEAD((hp), (nep), (nep), elem, link) + +/** + * Insert the element nep into the ring after the last element + * (..hp.. becomes ..nep..hp..) + * @param hp Head of the ring + * @param nep Element to insert + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INSERT_TAIL(hp, nep, elem, link) \ + APR_RING_SPLICE_TAIL((hp), (nep), (nep), elem, link) + +/** + * Concatenate ring h2 onto the end of ring h1, leaving h2 empty. + * @param h1 Head of the ring to concatenate onto + * @param h2 Head of the ring to concatenate + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_CONCAT(h1, h2, elem, link) do { \ + if (!APR_RING_EMPTY((h2), elem, link)) { \ + APR_RING_SPLICE_BEFORE(APR_RING_SENTINEL((h1), elem, link), \ + APR_RING_FIRST((h2)), \ + APR_RING_LAST((h2)), link); \ + APR_RING_INIT((h2), elem, link); \ + } \ + } while (0) + +/** + * Prepend ring h2 onto the beginning of ring h1, leaving h2 empty. + * @param h1 Head of the ring to prepend onto + * @param h2 Head of the ring to prepend + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_PREPEND(h1, h2, elem, link) do { \ + if (!APR_RING_EMPTY((h2), elem, link)) { \ + APR_RING_SPLICE_AFTER(APR_RING_SENTINEL((h1), elem, link), \ + APR_RING_FIRST((h2)), \ + APR_RING_LAST((h2)), link); \ + APR_RING_INIT((h2), elem, link); \ + } \ + } while (0) + +/** + * Unsplice a sequence of elements from a ring + * @warning The unspliced sequence is left with dangling pointers at either end + * @param ep1 First element in the sequence to unsplice + * @param epN Last element in the sequence to unsplice + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_UNSPLICE(ep1, epN, link) do { \ + APR_RING_NEXT(APR_RING_PREV((ep1), link), link) = \ + APR_RING_NEXT((epN), link); \ + APR_RING_PREV(APR_RING_NEXT((epN), link), link) = \ + APR_RING_PREV((ep1), link); \ + } while (0) + +/** + * Remove a single element from a ring + * @warning The unspliced element is left with dangling pointers at either end + * @param ep Element to remove + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_REMOVE(ep, link) \ + APR_RING_UNSPLICE((ep), (ep), link) + +/** + * Iterate over a ring + * @param ep The current element + * @param head The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_FOREACH(ep, head, elem, link) \ + for (ep = APR_RING_FIRST(head); \ + ep != APR_RING_SENTINEL(head, elem, link); \ + ep = APR_RING_NEXT(ep, link)) + +/** + * Iterate over a ring safe against removal of the current element + * @param ep1 The current element + * @param ep2 Iteration cursor + * @param head The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_FOREACH_SAFE(ep1, ep2, head, elem, link) \ + for (ep1 = APR_RING_FIRST(head), ep2 = APR_RING_NEXT(ep1, link); \ + ep1 != APR_RING_SENTINEL(head, elem, link); \ + ep1 = ep2, ep2 = APR_RING_NEXT(ep1, link)) + +/* Debugging tools: */ + +#ifdef APR_RING_DEBUG +#include +#include + +#define APR_RING_CHECK_ONE(msg, ptr) \ + fprintf(stderr, "*** %s %p\n", msg, ptr) + +#define APR_RING_CHECK(hp, elem, link, msg) \ + APR_RING_CHECK_ELEM(APR_RING_SENTINEL(hp, elem, link), elem, link, msg) + +#define APR_RING_CHECK_ELEM(ep, elem, link, msg) do { \ + struct elem *start = (ep); \ + struct elem *here = start; \ + fprintf(stderr, "*** ring check start -- %s\n", msg); \ + do { \ + fprintf(stderr, "\telem %p\n", here); \ + fprintf(stderr, "\telem->next %p\n", \ + APR_RING_NEXT(here, link)); \ + fprintf(stderr, "\telem->prev %p\n", \ + APR_RING_PREV(here, link)); \ + fprintf(stderr, "\telem->next->prev %p\n", \ + APR_RING_PREV(APR_RING_NEXT(here, link), link)); \ + fprintf(stderr, "\telem->prev->next %p\n", \ + APR_RING_NEXT(APR_RING_PREV(here, link), link)); \ + if (APR_RING_PREV(APR_RING_NEXT(here, link), link) != here) { \ + fprintf(stderr, "\t*** elem->next->prev != elem\n"); \ + break; \ + } \ + if (APR_RING_NEXT(APR_RING_PREV(here, link), link) != here) { \ + fprintf(stderr, "\t*** elem->prev->next != elem\n"); \ + break; \ + } \ + here = APR_RING_NEXT(here, link); \ + } while (here != start); \ + fprintf(stderr, "*** ring check end\n"); \ + } while (0) + +#define APR_RING_CHECK_CONSISTENCY(hp, elem, link) \ + APR_RING_CHECK_ELEM_CONSISTENCY(APR_RING_SENTINEL(hp, elem, link),\ + elem, link) + +#define APR_RING_CHECK_ELEM_CONSISTENCY(ep, elem, link) do { \ + struct elem *start = (ep); \ + struct elem *here = start; \ + do { \ + assert(APR_RING_PREV(APR_RING_NEXT(here, link), link) == here); \ + assert(APR_RING_NEXT(APR_RING_PREV(here, link), link) == here); \ + here = APR_RING_NEXT(here, link); \ + } while (here != start); \ + } while (0) + +#else +/** + * Print a single pointer value to STDERR + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param msg Descriptive message + * @param ptr Pointer value to print + */ +#define APR_RING_CHECK_ONE(msg, ptr) +/** + * Dump all ring pointers to STDERR, starting with the head and looping all + * the way around the ring back to the head. Aborts if an inconsistency + * is found. + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param hp Head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + * @param msg Descriptive message + */ +#define APR_RING_CHECK(hp, elem, link, msg) +/** + * Loops around a ring and checks all the pointers for consistency. Pops + * an assertion if any inconsistency is found. Same idea as APR_RING_CHECK() + * except that it's silent if all is well. + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param hp Head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_CHECK_CONSISTENCY(hp, elem, link) +/** + * Dump all ring pointers to STDERR, starting with the given element and + * looping all the way around the ring back to that element. Aborts if + * an inconsistency is found. + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param ep The element + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + * @param msg Descriptive message + */ +#define APR_RING_CHECK_ELEM(ep, elem, link, msg) +/** + * Loops around a ring, starting with the given element, and checks all + * the pointers for consistency. Pops an assertion if any inconsistency + * is found. Same idea as APR_RING_CHECK_ELEM() except that it's silent + * if all is well. + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param ep The element + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_CHECK_ELEM_CONSISTENCY(ep, elem, link) +#endif + +/** @} */ + +#endif /* !APR_RING_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_rmm.h b/c/dependencies/windows/apr/x64/include/apr_rmm.h new file mode 100644 index 00000000..976fe9c5 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_rmm.h @@ -0,0 +1,137 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_RMM_H +#define APR_RMM_H +/** + * @file apr_rmm.h + * @brief APR-UTIL Relocatable Memory Management Routines + */ +/** + * @defgroup APR_Util_RMM Relocatable Memory Management Routines + * @ingroup APR_Util + * @{ + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apu.h" +#include "apr_anylock.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** Structure to access Relocatable, Managed Memory */ +typedef struct apr_rmm_t apr_rmm_t; + +/** Fundamental allocation unit, within a specific apr_rmm_t */ +typedef apr_size_t apr_rmm_off_t; + +/** + * Initialize a relocatable memory block to be managed by the apr_rmm API. + * @param rmm The relocatable memory block + * @param lock An apr_anylock_t of the appropriate type of lock, or NULL + * if no locking is required. + * @param membuf The block of relocatable memory to be managed + * @param memsize The size of relocatable memory block to be managed + * @param cont The pool to use for local storage and management + * @remark Both @param membuf and @param memsize must be aligned + * (for instance using APR_ALIGN_DEFAULT). + */ +APU_DECLARE(apr_status_t) apr_rmm_init(apr_rmm_t **rmm, apr_anylock_t *lock, + void *membuf, apr_size_t memsize, + apr_pool_t *cont); + +/** + * Destroy a managed memory block. + * @param rmm The relocatable memory block to destroy + */ +APU_DECLARE(apr_status_t) apr_rmm_destroy(apr_rmm_t *rmm); + +/** + * Attach to a relocatable memory block already managed by the apr_rmm API. + * @param rmm The relocatable memory block + * @param lock An apr_anylock_t of the appropriate type of lock + * @param membuf The block of relocatable memory already under management + * @param cont The pool to use for local storage and management + */ +APU_DECLARE(apr_status_t) apr_rmm_attach(apr_rmm_t **rmm, apr_anylock_t *lock, + void *membuf, apr_pool_t *cont); + +/** + * Detach from the managed block of memory. + * @param rmm The relocatable memory block to detach from + */ +APU_DECLARE(apr_status_t) apr_rmm_detach(apr_rmm_t *rmm); + +/** + * Allocate memory from the block of relocatable memory. + * @param rmm The relocatable memory block + * @param reqsize How much memory to allocate + */ +APU_DECLARE(apr_rmm_off_t) apr_rmm_malloc(apr_rmm_t *rmm, apr_size_t reqsize); + +/** + * Realloc memory from the block of relocatable memory. + * @param rmm The relocatable memory block + * @param entity The memory allocation to realloc + * @param reqsize The new size + */ +APU_DECLARE(apr_rmm_off_t) apr_rmm_realloc(apr_rmm_t *rmm, void *entity, apr_size_t reqsize); + +/** + * Allocate memory from the block of relocatable memory and initialize it to zero. + * @param rmm The relocatable memory block + * @param reqsize How much memory to allocate + */ +APU_DECLARE(apr_rmm_off_t) apr_rmm_calloc(apr_rmm_t *rmm, apr_size_t reqsize); + +/** + * Free allocation returned by apr_rmm_malloc or apr_rmm_calloc. + * @param rmm The relocatable memory block + * @param entity The memory allocation to free + */ +APU_DECLARE(apr_status_t) apr_rmm_free(apr_rmm_t *rmm, apr_rmm_off_t entity); + +/** + * Retrieve the physical address of a relocatable allocation of memory + * @param rmm The relocatable memory block + * @param entity The memory allocation to free + * @return address The address, aligned with APR_ALIGN_DEFAULT. + */ +APU_DECLARE(void *) apr_rmm_addr_get(apr_rmm_t *rmm, apr_rmm_off_t entity); + +/** + * Compute the offset of a relocatable allocation of memory + * @param rmm The relocatable memory block + * @param entity The physical address to convert to an offset + */ +APU_DECLARE(apr_rmm_off_t) apr_rmm_offset_get(apr_rmm_t *rmm, void *entity); + +/** + * Compute the required overallocation of memory needed to fit n allocs + * @param n The number of alloc/calloc regions desired + */ +APU_DECLARE(apr_size_t) apr_rmm_overhead_get(int n); + +#ifdef __cplusplus +} +#endif +/** @} */ +#endif /* ! APR_RMM_H */ + diff --git a/c/dependencies/windows/apr/x64/include/apr_sdbm.h b/c/dependencies/windows/apr/x64/include/apr_sdbm.h new file mode 100644 index 00000000..5759508b --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_sdbm.h @@ -0,0 +1,176 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * sdbm - ndbm work-alike hashed database library + * based on Per-Ake Larson's Dynamic Hashing algorithms. BIT 18 (1978). + * author: oz@nexus.yorku.ca + * status: ex-public domain + */ + +#ifndef APR_SDBM_H +#define APR_SDBM_H + +#include "apu.h" +#include "apr_errno.h" +#include "apr_file_io.h" /* for apr_fileperms_t */ + +/** + * @file apr_sdbm.h + * @brief apr-util SDBM library + */ +/** + * @defgroup APR_Util_DBM_SDBM SDBM library + * @ingroup APR_Util_DBM + * @{ + */ + +/** + * Structure for referencing an sdbm + */ +typedef struct apr_sdbm_t apr_sdbm_t; + +/** + * Structure for referencing the datum record within an sdbm + */ +typedef struct { + /** pointer to the data stored/retrieved */ + char *dptr; + /** size of data */ + /* apr_ssize_t for release 2.0??? */ + int dsize; +} apr_sdbm_datum_t; + +/* The extensions used for the database files */ +/** SDBM Directory file extension */ +#define APR_SDBM_DIRFEXT ".dir" +/** SDBM page file extension */ +#define APR_SDBM_PAGFEXT ".pag" + +/* flags to sdbm_store */ +#define APR_SDBM_INSERT 0 /**< Insert */ +#define APR_SDBM_REPLACE 1 /**< Replace */ +#define APR_SDBM_INSERTDUP 2 /**< Insert with duplicates */ + +/** + * Open an sdbm database by file name + * @param db The newly opened database + * @param name The sdbm file to open + * @param mode The flag values (APR_READ and APR_BINARY flags are implicit) + *
+ *           APR_WRITE          open for read-write access
+ *           APR_CREATE         create the sdbm if it does not exist
+ *           APR_TRUNCATE       empty the contents of the sdbm
+ *           APR_EXCL           fail for APR_CREATE if the file exists
+ *           APR_DELONCLOSE     delete the sdbm when closed
+ *           APR_SHARELOCK      support locking across process/machines
+ * 
+ * @param perms Permissions to apply to if created + * @param p The pool to use when creating the sdbm + * @remark The sdbm name is not a true file name, as sdbm appends suffixes + * for seperate data and index files. + */ +APU_DECLARE(apr_status_t) apr_sdbm_open(apr_sdbm_t **db, const char *name, + apr_int32_t mode, + apr_fileperms_t perms, apr_pool_t *p); + +/** + * Close an sdbm file previously opened by apr_sdbm_open + * @param db The database to close + */ +APU_DECLARE(apr_status_t) apr_sdbm_close(apr_sdbm_t *db); + +/** + * Lock an sdbm database for concurency of multiple operations + * @param db The database to lock + * @param type The lock type + *
+ *           APR_FLOCK_SHARED
+ *           APR_FLOCK_EXCLUSIVE
+ * 
+ * @remark Calls to apr_sdbm_lock may be nested. All apr_sdbm functions + * perform implicit locking. Since an APR_FLOCK_SHARED lock cannot be + * portably promoted to an APR_FLOCK_EXCLUSIVE lock, apr_sdbm_store and + * apr_sdbm_delete calls will fail if an APR_FLOCK_SHARED lock is held. + * The apr_sdbm_lock call requires the database to be opened with the + * APR_SHARELOCK mode value. + */ +APU_DECLARE(apr_status_t) apr_sdbm_lock(apr_sdbm_t *db, int type); + +/** + * Release an sdbm lock previously aquired by apr_sdbm_lock + * @param db The database to unlock + */ +APU_DECLARE(apr_status_t) apr_sdbm_unlock(apr_sdbm_t *db); + +/** + * Fetch an sdbm record value by key + * @param db The database + * @param value The value datum retrieved for this record + * @param key The key datum to find this record + */ +APU_DECLARE(apr_status_t) apr_sdbm_fetch(apr_sdbm_t *db, + apr_sdbm_datum_t *value, + apr_sdbm_datum_t key); + +/** + * Store an sdbm record value by key + * @param db The database + * @param key The key datum to store this record by + * @param value The value datum to store in this record + * @param opt The method used to store the record + *
+ *           APR_SDBM_INSERT     return an error if the record exists
+ *           APR_SDBM_REPLACE    overwrite any existing record for key
+ * 
+ */ +APU_DECLARE(apr_status_t) apr_sdbm_store(apr_sdbm_t *db, apr_sdbm_datum_t key, + apr_sdbm_datum_t value, int opt); + +/** + * Delete an sdbm record value by key + * @param db The database + * @param key The key datum of the record to delete + * @remark It is not an error to delete a non-existent record. + */ +APU_DECLARE(apr_status_t) apr_sdbm_delete(apr_sdbm_t *db, + const apr_sdbm_datum_t key); + +/** + * Retrieve the first record key from a dbm + * @param db The database + * @param key The key datum of the first record + * @remark The keys returned are not ordered. To traverse the list of keys + * for an sdbm opened with APR_SHARELOCK, the caller must use apr_sdbm_lock + * prior to retrieving the first record, and hold the lock until after the + * last call to apr_sdbm_nextkey. + */ +APU_DECLARE(apr_status_t) apr_sdbm_firstkey(apr_sdbm_t *db, apr_sdbm_datum_t *key); + +/** + * Retrieve the next record key from an sdbm + * @param db The database + * @param key The key datum of the next record + */ +APU_DECLARE(apr_status_t) apr_sdbm_nextkey(apr_sdbm_t *db, apr_sdbm_datum_t *key); + +/** + * Returns true if the sdbm database opened for read-only access + * @param db The database to test + */ +APU_DECLARE(int) apr_sdbm_rdonly(apr_sdbm_t *db); +/** @} */ +#endif /* APR_SDBM_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_sha1.h b/c/dependencies/windows/apr/x64/include/apr_sha1.h new file mode 100644 index 00000000..2a4edf36 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_sha1.h @@ -0,0 +1,121 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* NIST Secure Hash Algorithm + * heavily modified by Uwe Hollerbach uh@alumni.caltech edu + * from Peter C. Gutmann's implementation as found in + * Applied Cryptography by Bruce Schneier + * This code is hereby placed in the public domain + */ + +#ifndef APR_SHA1_H +#define APR_SHA1_H + +#include "apu.h" +#include "apr_general.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_sha1.h + * @brief APR-UTIL SHA1 library + */ + +/** size of the SHA1 DIGEST */ +#define APR_SHA1_DIGESTSIZE 20 + +/** + * Define the Magic String prefix that identifies a password as being + * hashed using our algorithm. + */ +#define APR_SHA1PW_ID "{SHA}" + +/** length of the SHA Password */ +#define APR_SHA1PW_IDLEN 5 + +/** @see apr_sha1_ctx_t */ +typedef struct apr_sha1_ctx_t apr_sha1_ctx_t; + +/** + * SHA1 context structure + */ +struct apr_sha1_ctx_t { + /** message digest */ + apr_uint32_t digest[5]; + /** 64-bit bit counts */ + apr_uint32_t count_lo, count_hi; + /** SHA data buffer */ + apr_uint32_t data[16]; + /** unprocessed amount in data */ + int local; +}; + +/** + * Provide a means to SHA1 crypt/encode a plaintext password in a way which + * makes password file compatible with those commonly use in netscape web + * and ldap installations. + * @param clear The plaintext password + * @param len The length of the plaintext password + * @param out The encrypted/encoded password + * @note SHA1 support is useful for migration purposes, but is less + * secure than Apache's password format, since Apache's (MD5) + * password format uses a random eight character salt to generate + * one of many possible hashes for the same password. Netscape + * uses plain SHA1 without a salt, so the same password + * will always generate the same hash, making it easier + * to break since the search space is smaller. + */ +APU_DECLARE(void) apr_sha1_base64(const char *clear, int len, char *out); + +/** + * Initialize the SHA digest + * @param context The SHA context to initialize + */ +APU_DECLARE(void) apr_sha1_init(apr_sha1_ctx_t *context); + +/** + * Update the SHA digest + * @param context The SHA1 context to update + * @param input The buffer to add to the SHA digest + * @param inputLen The length of the input buffer + */ +APU_DECLARE(void) apr_sha1_update(apr_sha1_ctx_t *context, const char *input, + unsigned int inputLen); + +/** + * Update the SHA digest with binary data + * @param context The SHA1 context to update + * @param input The buffer to add to the SHA digest + * @param inputLen The length of the input buffer + */ +APU_DECLARE(void) apr_sha1_update_binary(apr_sha1_ctx_t *context, + const unsigned char *input, + unsigned int inputLen); + +/** + * Finish computing the SHA digest + * @param digest the output buffer in which to store the digest + * @param context The context to finalize + */ +APU_DECLARE(void) apr_sha1_final(unsigned char digest[APR_SHA1_DIGESTSIZE], + apr_sha1_ctx_t *context); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_SHA1_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_shm.h b/c/dependencies/windows/apr/x64/include/apr_shm.h new file mode 100644 index 00000000..635c654b --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_shm.h @@ -0,0 +1,229 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_SHM_H +#define APR_SHM_H + +/** + * @file apr_shm.h + * @brief APR Shared Memory Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_perms_set.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_shm Shared Memory Routines + * @ingroup APR + * @{ + */ + +/** + * Private, platform-specific data struture representing a shared memory + * segment. + */ +typedef struct apr_shm_t apr_shm_t; + +/** + * Create and make accessible a shared memory segment with default + * properties. + * @param m The shared memory structure to create. + * @param reqsize The desired size of the segment. + * @param filename The file to use for shared memory on platforms that + * require it. + * @param pool the pool from which to allocate the shared memory + * structure. + * @remark A note about Anonymous vs. Named shared memory segments: + * Not all plaforms support anonymous shared memory segments, but in + * some cases it is prefered over other types of shared memory + * implementations. Passing a NULL 'file' parameter to this function + * will cause the subsystem to use anonymous shared memory segments. + * If such a system is not available, APR_ENOTIMPL is returned. + * @remark A note about allocation sizes: + * On some platforms it is necessary to store some metainformation + * about the segment within the actual segment. In order to supply + * the caller with the requested size it may be necessary for the + * implementation to request a slightly greater segment length + * from the subsystem. In all cases, the apr_shm_baseaddr_get() + * function will return the first usable byte of memory. + * + */ +APR_DECLARE(apr_status_t) apr_shm_create(apr_shm_t **m, + apr_size_t reqsize, + const char *filename, + apr_pool_t *pool); + +/** + * Special processing flags for apr_shm_create_ex() and apr_shm_attach_ex(). + */ +#define APR_SHM_NS_LOCAL 1 /* Create or attach to named shared memory + * segment in the "Local" namespace on + * Windows. (Ignored on other platforms.) + * By default, the "Global" namespace is + * used for privileged processes and the + * "Local" namespace is used otherwise. + */ +#define APR_SHM_NS_GLOBAL 2 /* Create or attach to named shared memory + * segment in the "Global" namespace on + * Windows. (Ignored on other platforms.) + */ + +/** + * Create and make accessible a shared memory segment with platform- + * specific processing. + * @param m The shared memory structure to create. + * @param reqsize The desired size of the segment. + * @param filename The file to use for shared memory on platforms that + * require it. + * @param pool the pool from which to allocate the shared memory + * structure. + * @param flags mask of APR_SHM_* (defined above) + * @remark A note about Anonymous vs. Named shared memory segments: + * Not all plaforms support anonymous shared memory segments, but in + * some cases it is prefered over other types of shared memory + * implementations. Passing a NULL 'file' parameter to this function + * will cause the subsystem to use anonymous shared memory segments. + * If such a system is not available, APR_ENOTIMPL is returned. + * @remark A note about allocation sizes: + * On some platforms it is necessary to store some metainformation + * about the segment within the actual segment. In order to supply + * the caller with the requested size it may be necessary for the + * implementation to request a slightly greater segment length + * from the subsystem. In all cases, the apr_shm_baseaddr_get() + * function will return the first usable byte of memory. + * + */ +APR_DECLARE(apr_status_t) apr_shm_create_ex(apr_shm_t **m, + apr_size_t reqsize, + const char *filename, + apr_pool_t *pool, + apr_int32_t flags); + +/** + * Remove named resource associated with a shared memory segment, + * preventing attachments to the resource, but not destroying it. + * @param filename The filename associated with shared-memory segment which + * needs to be removed + * @param pool The pool used for file operations + * @remark This function is only supported on platforms which support + * name-based shared memory segments, and will return APR_ENOTIMPL on + * platforms without such support. Removing the file while the shm + * is in use is not entirely portable, caller may use this to enhance + * obscurity of the resource, but be prepared for the call to fail, + * and for concurrent attempts to create a resource of the same name + * to also fail. The pool cleanup of apr_shm_create (apr_shm_destroy) + * also removes the named resource. + */ +APR_DECLARE(apr_status_t) apr_shm_remove(const char *filename, + apr_pool_t *pool); + +/** + * Delete named resource associated with a shared memory segment, + * preventing attachments to the resource. + * @param m The shared memory segment structure to delete. + * @remark This function is only supported on platforms which support + * name-based shared memory segments, and will return APR_ENOTIMPL on + * platforms without such support. Removing the file while the shm + * is in use is not entirely portable, caller may use this to enhance + * obscurity of the resource, but be prepared for the call to fail, + * and for concurrent attempts to create a resource of the same name + * to also fail. The pool cleanup of apr_shm_create (apr_shm_destroy) + * also removes the named resource. + */ +APR_DECLARE(apr_status_t) apr_shm_delete(apr_shm_t *m); + +/** + * Destroy a shared memory segment and associated memory. + * @param m The shared memory segment structure to destroy. + */ +APR_DECLARE(apr_status_t) apr_shm_destroy(apr_shm_t *m); + +/** + * Attach to a shared memory segment that was created + * by another process. + * @param m The shared memory structure to create. + * @param filename The file used to create the original segment. + * (This MUST match the original filename.) + * @param pool the pool from which to allocate the shared memory + * structure for this process. + */ +APR_DECLARE(apr_status_t) apr_shm_attach(apr_shm_t **m, + const char *filename, + apr_pool_t *pool); + +/** + * Attach to a shared memory segment that was created + * by another process, with platform-specific processing. + * @param m The shared memory structure to create. + * @param filename The file used to create the original segment. + * (This MUST match the original filename.) + * @param pool the pool from which to allocate the shared memory + * structure for this process. + * @param flags mask of APR_SHM_* (defined above) + */ +APR_DECLARE(apr_status_t) apr_shm_attach_ex(apr_shm_t **m, + const char *filename, + apr_pool_t *pool, + apr_int32_t flags); + +/** + * Detach from a shared memory segment without destroying it. + * @param m The shared memory structure representing the segment + * to detach from. + */ +APR_DECLARE(apr_status_t) apr_shm_detach(apr_shm_t *m); + +/** + * Retrieve the base address of the shared memory segment. + * NOTE: This address is only usable within the callers address + * space, since this API does not guarantee that other attaching + * processes will maintain the same address mapping. + * @param m The shared memory segment from which to retrieve + * the base address. + * @return address, aligned by APR_ALIGN_DEFAULT. + */ +APR_DECLARE(void *) apr_shm_baseaddr_get(const apr_shm_t *m); + +/** + * Retrieve the length of a shared memory segment in bytes. + * @param m The shared memory segment from which to retrieve + * the segment length. + */ +APR_DECLARE(apr_size_t) apr_shm_size_get(const apr_shm_t *m); + +/** + * Set shared memory permissions. + */ +APR_PERMS_SET_IMPLEMENT(shm); + +/** + * Get the pool used by this shared memory segment. + */ +APR_POOL_DECLARE_ACCESSOR(shm); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_SHM_T */ diff --git a/c/dependencies/windows/apr/x64/include/apr_signal.h b/c/dependencies/windows/apr/x64/include/apr_signal.h new file mode 100644 index 00000000..20631333 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_signal.h @@ -0,0 +1,109 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_SIGNAL_H +#define APR_SIGNAL_H + +/** + * @file apr_signal.h + * @brief APR Signal Handling + */ + +#include "apr.h" +#include "apr_pools.h" + +#if APR_HAVE_SIGNAL_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_signal Signal Handling + * @ingroup APR + * @{ + */ + +#if APR_HAVE_SIGACTION || defined(DOXYGEN) + +#if defined(DARWIN) && !defined(__cplusplus) && !defined(_ANSI_SOURCE) +/* work around Darwin header file bugs + * http://www.opensource.apple.com/bugs/X/BSD%20Kernel/2657228.html + */ +#undef SIG_DFL +#undef SIG_IGN +#undef SIG_ERR +#define SIG_DFL (void (*)(int))0 +#define SIG_IGN (void (*)(int))1 +#define SIG_ERR (void (*)(int))-1 +#endif + +/** Function prototype for signal handlers */ +typedef void apr_sigfunc_t(int); + +/** + * Set the signal handler function for a given signal + * @param signo The signal (eg... SIGWINCH) + * @param func the function to get called + */ +APR_DECLARE(apr_sigfunc_t *) apr_signal(int signo, apr_sigfunc_t * func); + +#if defined(SIG_IGN) && !defined(SIG_ERR) +#define SIG_ERR ((apr_sigfunc_t *) -1) +#endif + +#else /* !APR_HAVE_SIGACTION */ +#define apr_signal(a, b) signal(a, b) +#endif + + +/** + * Get the description for a specific signal number + * @param signum The signal number + * @return The description of the signal + */ +APR_DECLARE(const char *) apr_signal_description_get(int signum); + +/** + * APR-private function for initializing the signal package + * @internal + * @param pglobal The internal, global pool + */ +void apr_signal_init(apr_pool_t *pglobal); + +/** + * Block the delivery of a particular signal + * @param signum The signal number + * @return status + */ +APR_DECLARE(apr_status_t) apr_signal_block(int signum); + +/** + * Enable the delivery of a particular signal + * @param signum The signal number + * @return status + */ +APR_DECLARE(apr_status_t) apr_signal_unblock(int signum); + +/** @} */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* APR_SIGNAL_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_siphash.h b/c/dependencies/windows/apr/x64/include/apr_siphash.h new file mode 100644 index 00000000..42aa8874 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_siphash.h @@ -0,0 +1,148 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + SipHash reference C implementation + Copyright (c) 2012-2014 Jean-Philippe Aumasson + + Copyright (c) 2012-2014 Daniel J. Bernstein + To the extent possible under law, the author(s) have dedicated all copyright + and related and neighboring rights to this software to the public domain + worldwide. This software is distributed without any warranty. + You should have received a copy of the CC0 Public Domain Dedication along + with this software. If not, see + . + */ + +#ifndef APR_SIPHASH_H +#define APR_SIPHASH_H + +#include "apr.h" +#include "apu.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_siphash.h + * @brief APR-UTIL siphash library + * "SipHash-c-d is a family of pseudorandom functions (a.k.a. keyed + * hash functions) optimized for speed on short messages", designed by + * Jean-Philippe Aumasson and Daniel J. Bernstein. It generates a 64bit + * hash (or MAC) from the message and a 128bit key. + * See http://cr.yp.to/siphash/siphash-20120620.pdf for the details, + * c is the number of compression rounds, d the number of finalization + * rounds; we also define fast implementations for c = 2 with d = 4 (aka + * siphash-2-4), and c = 4 with d = 8 (aka siphash-4-8), as recommended + * parameters per the authors. + */ + +/** size of the siphash digest */ +#define APR_SIPHASH_DSIZE 8 + +/** size of the siphash key */ +#define APR_SIPHASH_KSIZE 16 + + +/** + * @brief Computes SipHash-c-d, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key. + * @param src The message + * @param len The length of the message + * @param key The secret key + * @param c The number of compression rounds + * @param d The number of finalization rounds + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(apr_uint64_t) apr_siphash(const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE], + unsigned int c, unsigned int d); + +/** + * @brief Computes SipHash-c-d, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key, into a possibly + * unaligned buffer (using the little endian representation as defined by the + * authors for interoperabilty) usable as a MAC. + * @param out The output buffer (or MAC) + * @param src The message + * @param len The length of the message + * @param key The secret key + * @param c The number of compression rounds + * @param d The number of finalization rounds + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(void) apr_siphash_auth(unsigned char out[APR_SIPHASH_DSIZE], + const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE], + unsigned int c, unsigned int d); + +/** + * @brief Computes SipHash-2-4, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key. + * @param src The message to hash + * @param len The length of the message + * @param key The secret key + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(apr_uint64_t) apr_siphash24(const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE]); + +/** + * @brief Computes SipHash-2-4, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key, into a possibly + * unaligned buffer (using the little endian representation as defined by the + * authors for interoperabilty) usable as a MAC. + * @param out The output buffer (or MAC) + * @param src The message + * @param len The length of the message + * @param key The secret key + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(void) apr_siphash24_auth(unsigned char out[APR_SIPHASH_DSIZE], + const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE]); + +/** + * @brief Computes SipHash-4-8, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key. + * @param src The message + * @param len The length of the message + * @param key The secret key + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(apr_uint64_t) apr_siphash48(const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE]); + +/** + * @brief Computes SipHash-4-8, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key, into a possibly + * unaligned buffer (using the little endian representation as defined by the + * authors for interoperabilty) usable as a MAC. + * @param out The output buffer (or MAC) + * @param src The message + * @param len The length of the message + * @param key The secret key + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(void) apr_siphash48_auth(unsigned char out[APR_SIPHASH_DSIZE], + const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE]); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_SIPHASH_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_skiplist.h b/c/dependencies/windows/apr/x64/include/apr_skiplist.h new file mode 100644 index 00000000..eeab10bf --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_skiplist.h @@ -0,0 +1,381 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_SKIPLIST_H +#define APR_SKIPLIST_H +/** + * @file apr_skiplist.h + * @brief APR skip list implementation + */ + +#include "apr.h" +#include "apr_portable.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_skiplist Skip list implementation + * Refer to http://en.wikipedia.org/wiki/Skip_list for information + * about the purpose of and ideas behind skip lists. + * @ingroup APR + * @{ + */ + +/** + * apr_skiplist_compare is the function type that must be implemented + * per object type that is used in a skip list for comparisons to maintain + * order + * */ +typedef int (*apr_skiplist_compare) (void *, void *); + +/** + * apr_skiplist_freefunc is the function type that must be implemented + * to handle elements as they are removed from a skip list. + */ +typedef void (*apr_skiplist_freefunc) (void *); + +/** Opaque structure used to represent the skip list */ +struct apr_skiplist; +/** Opaque structure used to represent the skip list */ +typedef struct apr_skiplist apr_skiplist; + +/** + * Opaque structure used to represent abstract nodes in the skip list + * (an abstraction above the raw elements which are collected in the + * skip list). + */ +struct apr_skiplistnode; +/** Opaque structure */ +typedef struct apr_skiplistnode apr_skiplistnode; + +/** + * Allocate memory using the same mechanism as the skip list. + * @param sl The skip list + * @param size The amount to allocate + * @remark If a pool was provided to apr_skiplist_init(), memory will + * be allocated from the pool or from a free list maintained with + * the skip list. Otherwise, memory will be allocated using the + * C standard library heap functions. + */ +APR_DECLARE(void *) apr_skiplist_alloc(apr_skiplist *sl, size_t size); + +/** + * Free memory using the same mechanism as the skip list. + * @param sl The skip list + * @param mem The object to free + * @remark If a pool was provided to apr_skiplist_init(), memory will + * be added to a free list maintained with the skip list and be available + * to operations on the skip list or to other calls to apr_skiplist_alloc(). + * Otherwise, memory will be freed using the C standard library heap + * functions. + */ +APR_DECLARE(void) apr_skiplist_free(apr_skiplist *sl, void *mem); + +/** + * Allocate a new skip list + * @param sl The pointer in which to return the newly created skip list + * @param p The pool from which to allocate the skip list (optional). + * @remark Unlike most APR functions, a pool is optional. If no pool + * is provided, the C standard library heap functions will be used instead. + */ +APR_DECLARE(apr_status_t) apr_skiplist_init(apr_skiplist **sl, apr_pool_t *p); + +/** + * Set the comparison functions to be used for searching the skip list. + * @param sl The skip list + * @param XXX1 FIXME + * @param XXX2 FIXME + * + * @remark If existing comparison functions are being replaced, the index + * will be replaced during this call. That is a potentially expensive + * operation. + */ +APR_DECLARE(void) apr_skiplist_set_compare(apr_skiplist *sl, apr_skiplist_compare XXX1, + apr_skiplist_compare XXX2); + +/** + * Set the indexing functions to the specified comparison functions and + * rebuild the index. + * @param sl The skip list + * @param XXX1 FIXME + * @param XXX2 FIXME + * + * @remark If an index already exists, it will not be replaced and the + * comparison functions will not be changed. + */ +APR_DECLARE(void) apr_skiplist_add_index(apr_skiplist *sl, apr_skiplist_compare XXX1, + apr_skiplist_compare XXX2); + +/** + * Return the list maintained by the skip list abstraction. + * @param sl The skip list + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_getlist(apr_skiplist *sl); + +/** + * Return the next matching element in the skip list using the specified + * comparison function. + * @param sl The skip list + * @param data The value to search for + * @param iter A pointer to the returned skip list node representing the element + * found + * @param func The comparison function to use + */ +APR_DECLARE(void *) apr_skiplist_find_compare(apr_skiplist *sl, + void *data, + apr_skiplistnode **iter, + apr_skiplist_compare func); + +/** + * Return the next matching element in the skip list using the current comparison + * function. + * @param sl The skip list + * @param data The value to search for + * @param iter A pointer to the returned skip list node representing the element + * found + */ +APR_DECLARE(void *) apr_skiplist_find(apr_skiplist *sl, void *data, apr_skiplistnode **iter); + +/** + * Return the last matching element in the skip list using the specified + * comparison function. + * @param sl The skip list + * @param data The value to search for + * @param iter A pointer to the returned skip list node representing the element + * found + * @param comp The comparison function to use + */ +APR_DECLARE(void *) apr_skiplist_last_compare(apr_skiplist *sl, void *data, + apr_skiplistnode **iter, + apr_skiplist_compare comp); + +/** + * Return the last matching element in the skip list using the current comparison + * function. + * @param sl The skip list + * @param data The value to search for + * @param iter A pointer to the returned skip list node representing the element + * found + */ +APR_DECLARE(void *) apr_skiplist_last(apr_skiplist *sl, void *data, + apr_skiplistnode **iter); + +/** + * Return the next element in the skip list. + * @param sl The skip list + * @param iter On entry, a pointer to the skip list node to start with; on return, + * a pointer to the skip list node representing the element returned + * @remark If iter points to a NULL value on entry, NULL will be returned. + */ +APR_DECLARE(void *) apr_skiplist_next(apr_skiplist *sl, apr_skiplistnode **iter); + +/** + * Return the previous element in the skip list. + * @param sl The skip list + * @param iter On entry, a pointer to the skip list node to start with; on return, + * a pointer to the skip list node representing the element returned + * @remark If iter points to a NULL value on entry, NULL will be returned. + */ +APR_DECLARE(void *) apr_skiplist_previous(apr_skiplist *sl, apr_skiplistnode **iter); + +/** + * Return the element of the skip list node + * @param iter The skip list node + */ +APR_DECLARE(void *) apr_skiplist_element(apr_skiplistnode *iter); + +/** + * Insert an element into the skip list using the specified comparison function + * if it does not already exist. + * @param sl The skip list + * @param data The element to insert + * @param comp The comparison function to use for placement into the skip list + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_insert_compare(apr_skiplist *sl, + void *data, apr_skiplist_compare comp); + +/** + * Insert an element into the skip list using the existing comparison function + * if it does not already exist. + * @param sl The skip list + * @param data The element to insert + * @remark If no comparison function has been set for the skip list, the element + * will not be inserted and NULL will be returned. + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_insert(apr_skiplist* sl, void *data); + +/** + * Add an element into the skip list using the specified comparison function + * allowing for duplicates. + * @param sl The skip list + * @param data The element to add + * @param comp The comparison function to use for placement into the skip list + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_add_compare(apr_skiplist *sl, + void *data, apr_skiplist_compare comp); + +/** + * Add an element into the skip list using the existing comparison function + * allowing for duplicates. + * @param sl The skip list + * @param data The element to insert + * @remark If no comparison function has been set for the skip list, the element + * will not be inserted and NULL will be returned. + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_add(apr_skiplist* sl, void *data); + +/** + * Add an element into the skip list using the specified comparison function + * removing the existing duplicates. + * @param sl The skip list + * @param data The element to insert + * @param comp The comparison function to use for placement into the skip list + * @param myfree A function to be called for each removed duplicate + * @remark If no comparison function has been set for the skip list, the element + * will not be inserted, none will be replaced, and NULL will be returned. + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_replace_compare(apr_skiplist *sl, + void *data, apr_skiplist_freefunc myfree, + apr_skiplist_compare comp); + +/** + * Add an element into the skip list using the existing comparison function + * removing the existing duplicates. + * @param sl The skip list + * @param data The element to insert + * @param myfree A function to be called for each removed duplicate + * @remark If no comparison function has been set for the skip list, the element + * will not be inserted, none will be replaced, and NULL will be returned. + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_replace(apr_skiplist *sl, + void *data, apr_skiplist_freefunc myfree); + +/** + * Remove a node from the skip list. + * @param sl The skip list + * @param iter The skip list node to remove + * @param myfree A function to be called for the removed element + */ +APR_DECLARE(int) apr_skiplist_remove_node(apr_skiplist *sl, + apr_skiplistnode *iter, + apr_skiplist_freefunc myfree); + +/** + * Remove an element from the skip list using the specified comparison function for + * locating the element. In the case of duplicates, the 1st entry will be removed. + * @param sl The skip list + * @param data The element to remove + * @param myfree A function to be called for each removed element + * @param comp The comparison function to use for placement into the skip list + * @remark If the element is not found, 0 will be returned. Otherwise, the heightXXX + * will be returned. + */ +APR_DECLARE(int) apr_skiplist_remove_compare(apr_skiplist *sl, void *data, + apr_skiplist_freefunc myfree, apr_skiplist_compare comp); + +/** + * Remove an element from the skip list using the existing comparison function for + * locating the element. In the case of duplicates, the 1st entry will be removed. + * @param sl The skip list + * @param data The element to remove + * @param myfree A function to be called for each removed element + * @remark If the element is not found, 0 will be returned. Otherwise, the heightXXX + * will be returned. + * @remark If no comparison function has been set for the skip list, the element + * will not be removed and 0 will be returned. + */ +APR_DECLARE(int) apr_skiplist_remove(apr_skiplist *sl, void *data, apr_skiplist_freefunc myfree); + +/** + * Remove all elements from the skip list. + * @param sl The skip list + * @param myfree A function to be called for each removed element + */ +APR_DECLARE(void) apr_skiplist_remove_all(apr_skiplist *sl, apr_skiplist_freefunc myfree); + +/** + * Remove each element from the skip list. + * @param sl The skip list + * @param myfree A function to be called for each removed element + */ +APR_DECLARE(void) apr_skiplist_destroy(apr_skiplist *sl, apr_skiplist_freefunc myfree); + +/** + * Return the first element in the skip list, removing the element from the skip list. + * @param sl The skip list + * @param myfree A function to be called for the removed element + * @remark NULL will be returned if there are no elements + */ +APR_DECLARE(void *) apr_skiplist_pop(apr_skiplist *sl, apr_skiplist_freefunc myfree); + +/** + * Return the first element in the skip list, leaving the element in the skip list. + * @param sl The skip list + * @remark NULL will be returned if there are no elements + */ +APR_DECLARE(void *) apr_skiplist_peek(apr_skiplist *sl); + +/** + * Return the size of the list (number of elements), in O(1). + * @param sl The skip list + */ +APR_DECLARE(size_t) apr_skiplist_size(const apr_skiplist *sl); + +/** + * Return the height of the list (number of skip paths), in O(1). + * @param sl The skip list + */ +APR_DECLARE(int) apr_skiplist_height(const apr_skiplist *sl); + +/** + * Return the predefined maximum height of the skip list. + * @param sl The skip list + */ +APR_DECLARE(int) apr_skiplist_preheight(const apr_skiplist *sl); + +/** + * Set a predefined maximum height for the skip list. + * @param sl The skip list + * @param to The preheight to set, or a nul/negative value to disable. + * @remark When a preheight is used, the height of each inserted element is + * computed randomly up to this preheight instead of the current skip list's + * height plus one used by the default implementation. Using a preheight can + * probably ensure more fairness with long living elements (since with an + * adaptative height, former elements may have been created with a low height, + * hence a longest path to reach them while the skip list grows). On the other + * hand, the default behaviour (preheight <= 0) with a growing and decreasing + * maximum height is more adaptative/suitable for short living values. + * @note Should be called before any insertion/add. + */ +APR_DECLARE(void) apr_skiplist_set_preheight(apr_skiplist *sl, int to); + +/** + * Merge two skip lists. XXX SEMANTICS + * @param sl1 One of two skip lists to be merged + * @param sl2 The other of two skip lists to be merged + */ +APR_DECLARE(apr_skiplist *) apr_skiplist_merge(apr_skiplist *sl1, apr_skiplist *sl2); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_SKIPLIST_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_strings.h b/c/dependencies/windows/apr/x64/include/apr_strings.h new file mode 100644 index 00000000..d5f8719d --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_strings.h @@ -0,0 +1,380 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* Portions of this file are covered by */ +/* -*- mode: c; c-file-style: "k&r" -*- + + strnatcmp.c -- Perform 'natural order' comparisons of strings in C. + Copyright (C) 2000 by Martin Pool + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef APR_STRINGS_H +#define APR_STRINGS_H + +/** + * @file apr_strings.h + * @brief APR Strings library + */ + +#include "apr.h" +#include "apr_errno.h" +#include "apr_pools.h" +#define APR_WANT_IOVEC +#include "apr_want.h" + +#if APR_HAVE_STDARG_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_strings String routines + * @ingroup APR + * @{ + */ + +/** + * Do a natural order comparison of two strings. + * @param a The first string to compare + * @param b The second string to compare + * @return Either <0, 0, or >0. If the first string is less than the second + * this returns <0, if they are equivalent it returns 0, and if the + * first string is greater than second string it retuns >0. + */ +APR_DECLARE(int) apr_strnatcmp(char const *a, char const *b); + +/** + * Do a natural order comparison of two strings ignoring the case of the + * strings. + * @param a The first string to compare + * @param b The second string to compare + * @return Either <0, 0, or >0. If the first string is less than the second + * this returns <0, if they are equivalent it returns 0, and if the + * first string is greater than second string it retuns >0. + */ +APR_DECLARE(int) apr_strnatcasecmp(char const *a, char const *b); + +/** + * duplicate a string into memory allocated out of a pool + * @param p The pool to allocate out of + * @param s The string to duplicate + * @return The new string or NULL if s == NULL + */ +APR_DECLARE(char *) apr_pstrdup(apr_pool_t *p, const char *s); + +/** + * Create a null-terminated string by making a copy of a sequence + * of characters and appending a null byte + * @param p The pool to allocate out of + * @param s The block of characters to duplicate + * @param n The number of characters to duplicate + * @return The new string or NULL if s == NULL + * @remark This is a faster alternative to apr_pstrndup(), for use + * when you know that the string being duplicated really + * has 'n' or more characters. If the string might contain + * fewer characters, use apr_pstrndup(). + */ +APR_DECLARE(char *) apr_pstrmemdup(apr_pool_t *p, const char *s, apr_size_t n) +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) + __attribute__((alloc_size(3))) +#endif + ; + +/** + * Duplicate at most n characters of a string into memory allocated + * out of a pool; the new string will be NUL-terminated + * @param p The pool to allocate out of + * @param s The string to duplicate + * @param n The maximum number of characters to duplicate + * @return The new string or NULL if s == NULL + * @remark The amount of memory allocated from the pool is the length + * of the returned string including the NUL terminator + */ +APR_DECLARE(char *) apr_pstrndup(apr_pool_t *p, const char *s, apr_size_t n); + +/** + * Duplicate a block of memory. + * + * @param p The pool to allocate from + * @param m The memory to duplicate + * @param n The number of bytes to duplicate + * @return The new block of memory or NULL if m == NULL + */ +APR_DECLARE(void *) apr_pmemdup(apr_pool_t *p, const void *m, apr_size_t n) +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) + __attribute__((alloc_size(3))) +#endif + ; + +/** + * Concatenate multiple strings, allocating memory out a pool + * @param p The pool to allocate out of + * @param ... The strings to concatenate. The final string must be NULL + * @return The new string + */ +APR_DECLARE_NONSTD(char *) apr_pstrcat(apr_pool_t *p, ...) +#if defined(__GNUC__) && __GNUC__ >= 4 + __attribute__((sentinel)) +#endif + ; + +/** + * Concatenate multiple strings specified in a writev-style vector + * @param p The pool from which to allocate + * @param vec The strings to concatenate + * @param nvec The number of strings to concatenate + * @param nbytes (output) strlen of new string (pass in NULL to omit) + * @return The new string + */ +APR_DECLARE(char *) apr_pstrcatv(apr_pool_t *p, const struct iovec *vec, + apr_size_t nvec, apr_size_t *nbytes); + +/** + * printf-style style printing routine. The data is output to a string + * allocated from a pool + * @param p The pool to allocate out of + * @param fmt The format of the string + * @param ap The arguments to use while printing the data + * @return The new string + */ +APR_DECLARE(char *) apr_pvsprintf(apr_pool_t *p, const char *fmt, va_list ap); + +/** + * printf-style style printing routine. The data is output to a string + * allocated from a pool + * @param p The pool to allocate out of + * @param fmt The format of the string + * @param ... The arguments to use while printing the data + * @return The new string + */ +APR_DECLARE_NONSTD(char *) apr_psprintf(apr_pool_t *p, const char *fmt, ...) + __attribute__((format(printf,2,3))); + +/** + * Copy up to dst_size characters from src to dst; does not copy + * past a NUL terminator in src, but always terminates dst with a NUL + * regardless. + * @param dst The destination string + * @param src The source string + * @param dst_size The space available in dst; dst always receives + * NUL termination, so if src is longer than + * dst_size, the actual number of characters copied is + * dst_size - 1. + * @return Pointer to the NUL terminator of the destination string, dst + * @remark + *
+ * Note the differences between this function and strncpy():
+ *  1) strncpy() doesn't always NUL terminate; apr_cpystrn() does.
+ *  2) strncpy() pads the destination string with NULs, which is often 
+ *     unnecessary; apr_cpystrn() does not.
+ *  3) strncpy() returns a pointer to the beginning of the dst string;
+ *     apr_cpystrn() returns a pointer to the NUL terminator of dst, 
+ *     to allow a check for truncation.
+ * 
+ */ +APR_DECLARE(char *) apr_cpystrn(char *dst, const char *src, + apr_size_t dst_size); + +/** + * Remove all whitespace from a string + * @param dest The destination string. It is okay to modify the string + * in place. Namely dest == src + * @param src The string to rid the spaces from. + * @return A pointer to the destination string's null terminator. + */ +APR_DECLARE(char *) apr_collapse_spaces(char *dest, const char *src); + +/** + * Convert the arguments to a program from one string to an array of + * strings terminated by a NULL pointer + * @param arg_str The arguments to convert + * @param argv_out Output location. This is a pointer to an array of strings. + * @param token_context Pool to use. + */ +APR_DECLARE(apr_status_t) apr_tokenize_to_argv(const char *arg_str, + char ***argv_out, + apr_pool_t *token_context); + +/** + * Split a string into separate null-terminated tokens. The tokens are + * delimited in the string by one or more characters from the sep + * argument. + * @param str The string to separate; this should be specified on the + * first call to apr_strtok() for a given string, and NULL + * on subsequent calls. + * @param sep The set of delimiters + * @param last State saved by apr_strtok() between calls. + * @return The next token from the string + * @note the 'last' state points to the trailing NUL char of the final + * token, otherwise it points to the character following the current + * token (all successive or empty occurances of sep are skiped on the + * subsequent call to apr_strtok). Therefore it is possible to avoid + * a strlen() determination, with the following logic; + * toklen = last - retval; if (*last) --toklen; + */ +APR_DECLARE(char *) apr_strtok(char *str, const char *sep, char **last); + +/** + * @defgroup APR_Strings_Snprintf snprintf implementations + * @warning + * These are snprintf implementations based on apr_vformatter(). + * + * Note that various standards and implementations disagree on the return + * value of snprintf, and side-effects due to %n in the formatting string. + * apr_snprintf (and apr_vsnprintf) behaves as follows: + * + * Process the format string until the entire string is exhausted, or + * the buffer fills. If the buffer fills then stop processing immediately + * (so no further %n arguments are processed), and return the buffer + * length. In all cases the buffer is NUL terminated. It will return the + * number of characters inserted into the buffer, not including the + * terminating NUL. As a special case, if len is 0, apr_snprintf will + * return the number of characters that would have been inserted if + * the buffer had been infinite (in this case, *buffer can be NULL) + * + * In no event does apr_snprintf return a negative number. + * @{ + */ + +/** + * snprintf routine based on apr_vformatter. This means it understands the + * same extensions. + * @param buf The buffer to write to + * @param len The size of the buffer + * @param format The format string + * @param ... The arguments to use to fill out the format string. + */ +APR_DECLARE_NONSTD(int) apr_snprintf(char *buf, apr_size_t len, + const char *format, ...) + __attribute__((format(printf,3,4))); + +/** + * vsnprintf routine based on apr_vformatter. This means it understands the + * same extensions. + * @param buf The buffer to write to + * @param len The size of the buffer + * @param format The format string + * @param ap The arguments to use to fill out the format string. + */ +APR_DECLARE(int) apr_vsnprintf(char *buf, apr_size_t len, const char *format, + va_list ap); +/** @} */ + +/** + * create a string representation of an int, allocated from a pool + * @param p The pool from which to allocate + * @param n The number to format + * @return The string representation of the number + */ +APR_DECLARE(char *) apr_itoa(apr_pool_t *p, int n); + +/** + * create a string representation of a long, allocated from a pool + * @param p The pool from which to allocate + * @param n The number to format + * @return The string representation of the number + */ +APR_DECLARE(char *) apr_ltoa(apr_pool_t *p, long n); + +/** + * create a string representation of an apr_off_t, allocated from a pool + * @param p The pool from which to allocate + * @param n The number to format + * @return The string representation of the number + */ +APR_DECLARE(char *) apr_off_t_toa(apr_pool_t *p, apr_off_t n); + +/** + * Convert a numeric string into an apr_off_t numeric value. + * @param offset The value of the parsed string. + * @param buf The string to parse. It may contain optional whitespace, + * followed by an optional '+' (positive, default) or '-' (negative) + * character, followed by an optional '0x' prefix if base is 0 or 16, + * followed by numeric digits appropriate for base. + * @param end A pointer to the end of the valid character in buf. If + * not NULL, it is set to the first invalid character in buf. + * @param base A numeric base in the range between 2 and 36 inclusive, + * or 0. If base is zero, buf will be treated as base ten unless its + * digits are prefixed with '0x', in which case it will be treated as + * base 16. + * @bug *end breaks type safety; where *buf is const, *end needs to be + * declared as const in APR 2.0 + */ +APR_DECLARE(apr_status_t) apr_strtoff(apr_off_t *offset, const char *buf, + char **end, int base); + +/** + * parse a numeric string into a 64-bit numeric value + * @param buf The string to parse. It may contain optional whitespace, + * followed by an optional '+' (positive, default) or '-' (negative) + * character, followed by an optional '0x' prefix if base is 0 or 16, + * followed by numeric digits appropriate for base. + * @param end A pointer to the end of the valid character in buf. If + * not NULL, it is set to the first invalid character in buf. + * @param base A numeric base in the range between 2 and 36 inclusive, + * or 0. If base is zero, buf will be treated as base ten unless its + * digits are prefixed with '0x', in which case it will be treated as + * base 16. + * @return The numeric value of the string. On overflow, errno is set + * to ERANGE. On success, errno is set to 0. + */ +APR_DECLARE(apr_int64_t) apr_strtoi64(const char *buf, char **end, int base); + +/** + * parse a base-10 numeric string into a 64-bit numeric value. + * Equivalent to apr_strtoi64(buf, (char**)NULL, 10). + * @param buf The string to parse + * @return The numeric value of the string. On overflow, errno is set + * to ERANGE. On success, errno is set to 0. + */ +APR_DECLARE(apr_int64_t) apr_atoi64(const char *buf); + +/** + * Format a binary size (magnitiudes are 2^10 rather than 10^3) from an apr_off_t, + * as bytes, K, M, T, etc, to a four character compacted human readable string. + * @param size The size to format + * @param buf The 5 byte text buffer (counting the trailing null) + * @return The buf passed to apr_strfsize() + * @remark All negative sizes report ' - ', apr_strfsize only formats positive values. + */ +APR_DECLARE(char *) apr_strfsize(apr_off_t size, char *buf); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_STRINGS_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_strmatch.h b/c/dependencies/windows/apr/x64/include/apr_strmatch.h new file mode 100644 index 00000000..53fadad5 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_strmatch.h @@ -0,0 +1,81 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_STRMATCH_H +#define APR_STRMATCH_H +/** + * @file apr_strmatch.h + * @brief APR-UTIL string matching routines + */ + +#include "apu.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_StrMatch String matching routines + * @ingroup APR_Util + * @{ + */ + +/** @see apr_strmatch_pattern */ +typedef struct apr_strmatch_pattern apr_strmatch_pattern; + +/** + * Precompiled search pattern + */ +struct apr_strmatch_pattern { + /** Function called to compare */ + const char *(*compare)(const apr_strmatch_pattern *this_pattern, + const char *s, apr_size_t slen); + const char *pattern; /**< Current pattern */ + apr_size_t length; /**< Current length */ + void *context; /**< hook to add precomputed metadata */ +}; + +#if defined(DOXYGEN) +/** + * Search for a precompiled pattern within a string + * @param pattern The pattern + * @param s The string in which to search for the pattern + * @param slen The length of s (excluding null terminator) + * @return A pointer to the first instance of the pattern in s, or + * NULL if not found + */ +APU_DECLARE(const char *) apr_strmatch(const apr_strmatch_pattern *pattern, + const char *s, apr_size_t slen); +#else +#define apr_strmatch(pattern, s, slen) (*((pattern)->compare))((pattern), (s), (slen)) +#endif + +/** + * Precompile a pattern for matching using the Boyer-Moore-Horspool algorithm + * @param p The pool from which to allocate the pattern + * @param s The pattern string + * @param case_sensitive Whether the matching should be case-sensitive + * @return a pointer to the compiled pattern, or NULL if compilation fails + */ +APU_DECLARE(const apr_strmatch_pattern *) apr_strmatch_precompile(apr_pool_t *p, const char *s, int case_sensitive); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_STRMATCH_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_support.h b/c/dependencies/windows/apr/x64/include/apr_support.h new file mode 100644 index 00000000..79c8cb47 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_support.h @@ -0,0 +1,57 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_SUPPORT_H +#define APR_SUPPORT_H + +/** + * @file apr_support.h + * @brief APR Support functions + */ + +#include "apr.h" +#include "apr_network_io.h" +#include "apr_file_io.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_support Internal APR support functions + * @ingroup APR + * @{ + */ + +/** + * Wait for IO to occur or timeout. + * + * @param f The file to wait on. + * @param s The socket to wait on if @a f is @c NULL. + * @param for_read If non-zero wait for data to be available to read, + * otherwise wait for data to be able to be written. + * @return APR_TIMEUP if we run out of time. + */ +apr_status_t apr_wait_for_io_or_timeout(apr_file_t *f, apr_socket_t *s, + int for_read); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_SUPPORT_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_tables.h b/c/dependencies/windows/apr/x64/include/apr_tables.h new file mode 100644 index 00000000..27974c0e --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_tables.h @@ -0,0 +1,507 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_TABLES_H +#define APR_TABLES_H + +/** + * @file apr_tables.h + * @brief APR Table library + */ + +#include "apr.h" +#include "apr_pools.h" + +#if APR_HAVE_STDARG_H +#include /* for va_list */ +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_tables Table and Array Functions + * @ingroup APR + * Arrays are used to store data which is referenced sequentially or + * as a stack. Functions are provided to push and pop individual + * elements as well as to operate on the entire array. + * + * Tables are used to store data which can be referenced by key. + * Limited capabilities are provided for tables with multiple elements + * which share a key; while key lookup will return only a single + * element, iteration is available. Additionally, a table can be + * compressed to resolve duplicates. + * + * Both arrays and tables may store string or binary data; some features, + * such as concatenation or merging of elements, work only for string + * data. + * @{ + */ + +/** the table abstract data type */ +typedef struct apr_table_t apr_table_t; + +/** @see apr_array_header_t */ +typedef struct apr_array_header_t apr_array_header_t; + +/** An opaque array type */ +struct apr_array_header_t { + /** The pool the array is allocated out of */ + apr_pool_t *pool; + /** The amount of memory allocated for each element of the array */ + int elt_size; + /** The number of active elements in the array */ + int nelts; + /** The number of elements allocated in the array */ + int nalloc; + /** The elements in the array */ + char *elts; +}; + +/** + * The (opaque) structure for string-content tables. + */ +typedef struct apr_table_entry_t apr_table_entry_t; + +/** The type for each entry in a string-content table */ +struct apr_table_entry_t { + /** The key for the current table entry */ + char *key; /* maybe NULL in future; + * check when iterating thru table_elts + */ + /** The value for the current table entry */ + char *val; + + /** A checksum for the key, for use by the apr_table internals */ + apr_uint32_t key_checksum; +}; + +/** + * Get the elements from a table. + * @param t The table + * @return An array containing the contents of the table + */ +APR_DECLARE(const apr_array_header_t *) apr_table_elts(const apr_table_t *t); + +/** + * Determine if the table is empty (either NULL or having no elements). + * @param t The table to check + * @return True if empty, False otherwise + */ +APR_DECLARE(int) apr_is_empty_table(const apr_table_t *t); + +/** + * Determine if the array is empty (either NULL or having no elements). + * @param a The array to check + * @return True if empty, False otherwise + */ +APR_DECLARE(int) apr_is_empty_array(const apr_array_header_t *a); + +/** + * Create an array. + * @param p The pool to allocate the memory out of + * @param nelts the number of elements in the initial array + * @param elt_size The size of each element in the array. + * @return The new array + */ +APR_DECLARE(apr_array_header_t *) apr_array_make(apr_pool_t *p, + int nelts, int elt_size); + +/** + * Add a new element to an array (as a first-in, last-out stack). + * @param arr The array to add an element to. + * @return Location for the new element in the array. + * @remark If there are no free spots in the array, then this function will + * allocate new space for the new element. + */ +APR_DECLARE(void *) apr_array_push(apr_array_header_t *arr); + +/** A helper macro for accessing a member of an APR array. + * + * @param ary the array + * @param i the index into the array to return + * @param type the type of the objects stored in the array + * + * @return the item at index i + */ +#define APR_ARRAY_IDX(ary,i,type) (((type *)(ary)->elts)[i]) + +/** A helper macro for pushing elements into an APR array. + * + * @param ary the array + * @param type the type of the objects stored in the array + * + * @return the location where the new object should be placed + */ +#define APR_ARRAY_PUSH(ary,type) (*((type *)apr_array_push(ary))) + +/** + * Remove an element from an array (as a first-in, last-out stack). + * @param arr The array to remove an element from. + * @return Location of the element in the array. + * @remark If there are no elements in the array, NULL is returned. + */ +APR_DECLARE(void *) apr_array_pop(apr_array_header_t *arr); + +/** + * Remove all elements from an array. + * @param arr The array to remove all elements from. + * @remark As the underlying storage is allocated from a pool, no + * memory is freed by this operation, but is available for reuse. + */ +APR_DECLARE(void) apr_array_clear(apr_array_header_t *arr); + +/** + * Concatenate two arrays together. + * @param dst The destination array, and the one to go first in the combined + * array + * @param src The source array to add to the destination array + */ +APR_DECLARE(void) apr_array_cat(apr_array_header_t *dst, + const apr_array_header_t *src); + +/** + * Copy the entire array. + * @param p The pool to allocate the copy of the array out of + * @param arr The array to copy + * @return An exact copy of the array passed in + * @remark The alternate apr_array_copy_hdr() copies only the header, and arranges + * for the elements to be copied if (and only if) the code subsequently + * does a push or arraycat. + */ +APR_DECLARE(apr_array_header_t *) apr_array_copy(apr_pool_t *p, + const apr_array_header_t *arr); +/** + * Copy the headers of the array, and arrange for the elements to be copied if + * and only if the code subsequently does a push or arraycat. + * @param p The pool to allocate the copy of the array out of + * @param arr The array to copy + * @return An exact copy of the array passed in + * @remark The alternate apr_array_copy() copies the *entire* array. + */ +APR_DECLARE(apr_array_header_t *) apr_array_copy_hdr(apr_pool_t *p, + const apr_array_header_t *arr); + +/** + * Append one array to the end of another, creating a new array in the process. + * @param p The pool to allocate the new array out of + * @param first The array to put first in the new array. + * @param second The array to put second in the new array. + * @return A new array containing the data from the two arrays passed in. +*/ +APR_DECLARE(apr_array_header_t *) apr_array_append(apr_pool_t *p, + const apr_array_header_t *first, + const apr_array_header_t *second); + +/** + * Generate a new string from the apr_pool_t containing the concatenated + * sequence of substrings referenced as elements within the array. The string + * will be empty if all substrings are empty or null, or if there are no + * elements in the array. If sep is non-NUL, it will be inserted between + * elements as a separator. + * @param p The pool to allocate the string out of + * @param arr The array to generate the string from + * @param sep The separator to use + * @return A string containing all of the data in the array. + */ +APR_DECLARE(char *) apr_array_pstrcat(apr_pool_t *p, + const apr_array_header_t *arr, + const char sep); + +/** + * Make a new table. + * @param p The pool to allocate the pool out of + * @param nelts The number of elements in the initial table. + * @return The new table. + * @warning This table can only store text data + */ +APR_DECLARE(apr_table_t *) apr_table_make(apr_pool_t *p, int nelts); + +/** + * Create a new table and copy another table into it. + * @param p The pool to allocate the new table out of + * @param t The table to copy + * @return A copy of the table passed in + * @warning The table keys and respective values are not copied + */ +APR_DECLARE(apr_table_t *) apr_table_copy(apr_pool_t *p, + const apr_table_t *t); + +/** + * Create a new table whose contents are deep copied from the given + * table. A deep copy operation copies all fields, and makes copies + * of dynamically allocated memory pointed to by the fields. + * @param p The pool to allocate the new table out of + * @param t The table to clone + * @return A deep copy of the table passed in + */ +APR_DECLARE(apr_table_t *) apr_table_clone(apr_pool_t *p, + const apr_table_t *t); + +/** + * Delete all of the elements from a table. + * @param t The table to clear + */ +APR_DECLARE(void) apr_table_clear(apr_table_t *t); + +/** + * Get the value associated with a given key from the table. After this call, + * the data is still in the table. + * @param t The table to search for the key + * @param key The key to search for (case does not matter) + * @return The value associated with the key, or NULL if the key does not exist. + */ +APR_DECLARE(const char *) apr_table_get(const apr_table_t *t, const char *key); + +/** + * Get values associated with a given key from the table. If more than one + * value exists, return a comma separated list of values. After this call, the + * data is still in the table. + * @param p The pool to allocate the combined value from, if necessary + * @param t The table to search for the key + * @param key The key to search for (case does not matter) + * @return The value associated with the key, or NULL if the key does not exist. + */ +APR_DECLARE(const char *) apr_table_getm(apr_pool_t *p, const apr_table_t *t, + const char *key); + +/** + * Add a key/value pair to a table. If another element already exists with the + * same key, this will overwrite the old data. + * @param t The table to add the data to. + * @param key The key to use (case does not matter) + * @param val The value to add + * @remark When adding data, this function makes a copy of both the key and the + * value. + */ +APR_DECLARE(void) apr_table_set(apr_table_t *t, const char *key, + const char *val); + +/** + * Add a key/value pair to a table. If another element already exists with the + * same key, this will overwrite the old data. + * @param t The table to add the data to. + * @param key The key to use (case does not matter) + * @param val The value to add + * @warning When adding data, this function does not make a copy of the key or + * the value, so care should be taken to ensure that the values will + * not change after they have been added.. + */ +APR_DECLARE(void) apr_table_setn(apr_table_t *t, const char *key, + const char *val); + +/** + * Remove data from the table. + * @param t The table to remove data from + * @param key The key of the data being removed (case does not matter) + */ +APR_DECLARE(void) apr_table_unset(apr_table_t *t, const char *key); + +/** + * Add data to a table by merging the value with data that has already been + * stored. The merging is done by concatenating the two values, separated + * by the string ", ". + * @param t The table to search for the data + * @param key The key to merge data for (case does not matter) + * @param val The data to add + * @remark If the key is not found, then this function acts like apr_table_add() + */ +APR_DECLARE(void) apr_table_merge(apr_table_t *t, const char *key, + const char *val); + +/** + * Add data to a table by merging the value with data that has already been + * stored. The merging is done by concatenating the two values, separated + * by the string ", ". + * @param t The table to search for the data + * @param key The key to merge data for (case does not matter) + * @param val The data to add + * @remark If the key is not found, then this function acts like apr_table_addn() + */ +APR_DECLARE(void) apr_table_mergen(apr_table_t *t, const char *key, + const char *val); + +/** + * Add data to a table, regardless of whether there is another element with the + * same key. + * @param t The table to add to + * @param key The key to use + * @param val The value to add. + * @remark When adding data, this function makes a copy of both the key and the + * value. + */ +APR_DECLARE(void) apr_table_add(apr_table_t *t, const char *key, + const char *val); + +/** + * Add data to a table, regardless of whether there is another element with the + * same key. + * @param t The table to add to + * @param key The key to use + * @param val The value to add. + * @remark When adding data, this function does not make a copy of the key or the + * value, so care should be taken to ensure that the values will not + * change after they have been added. + */ +APR_DECLARE(void) apr_table_addn(apr_table_t *t, const char *key, + const char *val); + +/** + * Merge two tables into one new table. + * @param p The pool to use for the new table + * @param overlay The first table to put in the new table + * @param base The table to add at the end of the new table + * @return A new table containing all of the data from the two passed in + */ +APR_DECLARE(apr_table_t *) apr_table_overlay(apr_pool_t *p, + const apr_table_t *overlay, + const apr_table_t *base); + +/** + * Declaration prototype for the iterator callback function of apr_table_do() + * and apr_table_vdo(). + * @param rec The data passed as the first argument to apr_table_[v]do() + * @param key The key from this iteration of the table + * @param value The value from this iteration of the table + * @remark Iteration continues while this callback function returns non-zero. + * To export the callback function for apr_table_[v]do() it must be declared + * in the _NONSTD convention. + * @see apr_table_do @see apr_table_vdo + */ +typedef int (apr_table_do_callback_fn_t)(void *rec, const char *key, + const char *value); + +/** + * Iterate over a table running the provided function once for every + * element in the table. The varargs array must be a list of zero or + * more (char *) keys followed by a NULL pointer. If zero keys are + * given, the @param comp function will be invoked for every element + * in the table. Otherwise, the function is invoked only for those + * elements matching the keys specified. + * + * If an invocation of the comp function returns zero, + * iteration will continue using the next specified key, if any. + * + * @param comp The function to run + * @param rec The data to pass as the first argument to the function + * @param t The table to iterate over + * @param ... A varargs array of zero or more (char *) keys followed by NULL + * @return FALSE if one of the comp() iterations returned zero; TRUE if all + * iterations returned non-zero + * @see apr_table_do_callback_fn_t @see apr_table_vdo + */ +APR_DECLARE_NONSTD(int) apr_table_do(apr_table_do_callback_fn_t *comp, + void *rec, const apr_table_t *t, ...) +#if defined(__GNUC__) && __GNUC__ >= 4 + __attribute__((sentinel)) +#endif + ; + +/** + * Iterate over a table running the provided function once for every + * element in the table. The vp varargs parameter must be a + * list of zero or more (char *) keys followed by a NULL pointer. If + * zero keys are given, the @param comp function will be invoked for + * every element in the table. Otherwise, the function is invoked + * only for those elements matching the keys specified. + * + * If an invocation of the comp function returns zero, + * iteration will continue using the next specified key, if any. + * + * @param comp The function to run + * @param rec The data to pass as the first argument to the function + * @param t The table to iterate over + * @param vp List of zero or more (char *) keys followed by NULL + * @return FALSE if one of the comp() iterations returned zero; TRUE if all + * iterations returned non-zero + * @see apr_table_do_callback_fn_t @see apr_table_do + */ +APR_DECLARE(int) apr_table_vdo(apr_table_do_callback_fn_t *comp, + void *rec, const apr_table_t *t, va_list vp); + +/** flag for overlap to use apr_table_setn */ +#define APR_OVERLAP_TABLES_SET (0) +/** flag for overlap to use apr_table_mergen */ +#define APR_OVERLAP_TABLES_MERGE (1) +/** flag for overlap to use apr_table_addn */ +#define APR_OVERLAP_TABLES_ADD (2) +/** + * For each element in table b, either use setn or mergen to add the data + * to table a. Which method is used is determined by the flags passed in. + * @param a The table to add the data to. + * @param b The table to iterate over, adding its data to table a + * @param flags How to add the table to table a. One of: + * APR_OVERLAP_TABLES_SET Use apr_table_setn + * APR_OVERLAP_TABLES_MERGE Use apr_table_mergen + * APR_OVERLAP_TABLES_ADD Use apr_table_addn + * @remark When merging duplicates, the two values are concatenated, + * separated by the string ", ". + * @remark This function is highly optimized, and uses less memory and CPU cycles + * than a function that just loops through table b calling other functions. + */ +/** + * Conceptually, apr_table_overlap does this: + * + *
+ *  apr_array_header_t *barr = apr_table_elts(b);
+ *  apr_table_entry_t *belt = (apr_table_entry_t *)barr->elts;
+ *  int i;
+ *
+ *  for (i = 0; i < barr->nelts; ++i) {
+ *      if (flags & APR_OVERLAP_TABLES_MERGE) {
+ *          apr_table_mergen(a, belt[i].key, belt[i].val);
+ *      }
+ *      else if (flags & APR_OVERLAP_TABLES_ADD) {
+ *          apr_table_addn(a, belt[i].key, belt[i].val);
+ *      }
+ *      else {
+ *          apr_table_setn(a, belt[i].key, belt[i].val);
+ *      }
+ *  }
+ * 
+ * + * Except that it is more efficient (less space and cpu-time) especially + * when b has many elements. + * + * Notice the assumptions on the keys and values in b -- they must be + * in an ancestor of a's pool. In practice b and a are usually from + * the same pool. + */ + +APR_DECLARE(void) apr_table_overlap(apr_table_t *a, const apr_table_t *b, + unsigned flags); + +/** + * Eliminate redundant entries in a table by either overwriting + * or merging duplicates. + * + * @param t Table. + * @param flags APR_OVERLAP_TABLES_MERGE to merge, or + * APR_OVERLAP_TABLES_SET to overwrite, or + * APR_OVERLAP_TABLES_ADD to add + * @remark When merging duplicates, the two values are concatenated, + * separated by the string ", ". + */ +APR_DECLARE(void) apr_table_compress(apr_table_t *t, unsigned flags); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_TABLES_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_thread_cond.h b/c/dependencies/windows/apr/x64/include/apr_thread_cond.h new file mode 100644 index 00000000..199f1ded --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_thread_cond.h @@ -0,0 +1,139 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_THREAD_COND_H +#define APR_THREAD_COND_H + +/** + * @file apr_thread_cond.h + * @brief APR Condition Variable Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_time.h" +#include "apr_thread_mutex.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#if APR_HAS_THREADS || defined(DOXYGEN) + +/** + * @defgroup apr_thread_cond Condition Variable Routines + * @ingroup APR + * @{ + */ + +/** Opaque structure for thread condition variables */ +typedef struct apr_thread_cond_t apr_thread_cond_t; + +/** + * Note: destroying a condition variable (or likewise, destroying or + * clearing the pool from which a condition variable was allocated) if + * any threads are blocked waiting on it gives undefined results. + */ + +/** + * Create and initialize a condition variable that can be used to signal + * and schedule threads in a single process. + * @param cond the memory address where the newly created condition variable + * will be stored. + * @param pool the pool from which to allocate the condition. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_create(apr_thread_cond_t **cond, + apr_pool_t *pool); + +/** + * Put the active calling thread to sleep until signaled to wake up. Each + * condition variable must be associated with a mutex, and that mutex must + * be locked before calling this function, or the behavior will be + * undefined. As the calling thread is put to sleep, the given mutex + * will be simultaneously released; and as this thread wakes up the lock + * is again simultaneously acquired. + * @param cond the condition variable on which to block. + * @param mutex the mutex that must be locked upon entering this function, + * is released while the thread is asleep, and is again acquired before + * returning from this function. + * @remark Spurious wakeups may occur. Before and after every call to wait on + * a condition variable, the caller should test whether the condition is already + * met. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_wait(apr_thread_cond_t *cond, + apr_thread_mutex_t *mutex); + +/** + * Put the active calling thread to sleep until signaled to wake up or + * the timeout is reached. Each condition variable must be associated + * with a mutex, and that mutex must be locked before calling this + * function, or the behavior will be undefined. As the calling thread + * is put to sleep, the given mutex will be simultaneously released; + * and as this thread wakes up the lock is again simultaneously acquired. + * @param cond the condition variable on which to block. + * @param mutex the mutex that must be locked upon entering this function, + * is released while the thread is asleep, and is again acquired before + * returning from this function. + * @param timeout The amount of time in microseconds to wait. This is + * a maximum, not a minimum. If the condition is signaled, we + * will wake up before this time, otherwise the error APR_TIMEUP + * is returned. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_timedwait(apr_thread_cond_t *cond, + apr_thread_mutex_t *mutex, + apr_interval_time_t timeout); + +/** + * Signals a single thread, if one exists, that is blocking on the given + * condition variable. That thread is then scheduled to wake up and acquire + * the associated mutex. Although it is not required, if predictable scheduling + * is desired, that mutex must be locked while calling this function. + * @param cond the condition variable on which to produce the signal. + * @remark If no threads are waiting on the condition variable, nothing happens. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_signal(apr_thread_cond_t *cond); + +/** + * Signals all threads blocking on the given condition variable. + * Each thread that was signaled is then scheduled to wake up and acquire + * the associated mutex. This will happen in a serialized manner. + * @param cond the condition variable on which to produce the broadcast. + * @remark If no threads are waiting on the condition variable, nothing happens. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_broadcast(apr_thread_cond_t *cond); + +/** + * Destroy the condition variable and free the associated memory. + * @param cond the condition variable to destroy. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_destroy(apr_thread_cond_t *cond); + +/** + * Get the pool used by this thread_cond. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(thread_cond); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_THREAD_COND_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_thread_mutex.h b/c/dependencies/windows/apr/x64/include/apr_thread_mutex.h new file mode 100644 index 00000000..8eb61729 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_thread_mutex.h @@ -0,0 +1,123 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_THREAD_MUTEX_H +#define APR_THREAD_MUTEX_H + +/** + * @file apr_thread_mutex.h + * @brief APR Thread Mutex Routines + */ + +#include "apr.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#if APR_HAS_THREADS || defined(DOXYGEN) + +/** + * @defgroup apr_thread_mutex Thread Mutex Routines + * @ingroup APR + * @{ + */ + +/** Opaque thread-local mutex structure */ +typedef struct apr_thread_mutex_t apr_thread_mutex_t; + +#define APR_THREAD_MUTEX_DEFAULT 0x0 /**< platform-optimal lock behavior */ +#define APR_THREAD_MUTEX_NESTED 0x1 /**< enable nested (recursive) locks */ +#define APR_THREAD_MUTEX_UNNESTED 0x2 /**< disable nested locks */ +#define APR_THREAD_MUTEX_TIMED 0x4 /**< enable timed locks */ + +/* Delayed the include to avoid a circular reference */ +#include "apr_pools.h" +#include "apr_time.h" + +/** + * Create and initialize a mutex that can be used to synchronize threads. + * @param mutex the memory address where the newly created mutex will be + * stored. + * @param flags Or'ed value of: + *
+ *           APR_THREAD_MUTEX_DEFAULT   platform-optimal lock behavior.
+ *           APR_THREAD_MUTEX_NESTED    enable nested (recursive) locks.
+ *           APR_THREAD_MUTEX_UNNESTED  disable nested locks (non-recursive).
+ * 
+ * @param pool the pool from which to allocate the mutex. + * @warning Be cautious in using APR_THREAD_MUTEX_DEFAULT. While this is the + * most optimal mutex based on a given platform's performance characteristics, + * it will behave as either a nested or an unnested lock. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_create(apr_thread_mutex_t **mutex, + unsigned int flags, + apr_pool_t *pool); +/** + * Acquire the lock for the given mutex. If the mutex is already locked, + * the current thread will be put to sleep until the lock becomes available. + * @param mutex the mutex on which to acquire the lock. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_lock(apr_thread_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex. If the mutex has already + * been acquired, the call returns immediately with APR_EBUSY. Note: it + * is important that the APR_STATUS_IS_EBUSY(s) macro be used to determine + * if the return value was APR_EBUSY, for portability reasons. + * @param mutex the mutex on which to attempt the lock acquiring. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_trylock(apr_thread_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex until timeout expires. + * If the acquisition time outs, the call returns with APR_TIMEUP. + * @param mutex the mutex on which to attempt the lock acquiring. + * @param timeout the relative timeout (microseconds). + * @note A timeout negative or nul means immediate attempt, returning + * APR_TIMEUP without blocking if it the lock is already acquired. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_timedlock(apr_thread_mutex_t *mutex, + apr_interval_time_t timeout); + +/** + * Release the lock for the given mutex. + * @param mutex the mutex from which to release the lock. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_unlock(apr_thread_mutex_t *mutex); + +/** + * Destroy the mutex and free the memory associated with the lock. + * @param mutex the mutex to destroy. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_destroy(apr_thread_mutex_t *mutex); + +/** + * Get the pool used by this thread_mutex. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(thread_mutex); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_THREAD_MUTEX_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_thread_pool.h b/c/dependencies/windows/apr/x64/include/apr_thread_pool.h new file mode 100644 index 00000000..cbf382b3 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_thread_pool.h @@ -0,0 +1,299 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +#ifndef APU_THREAD_POOL_H +#define APU_THREAD_POOL_H + +#include "apu.h" +#include "apr_thread_proc.h" + +/** + * @file apr_thread_pool.h + * @brief APR Thread Pool Library + + * @remarks This library implements a thread pool using apr_thread_t. A thread + * pool is a set of threads that can be created in advance or on demand until a + * maximum number. When a task is scheduled, the thread pool will find an idle + * thread to handle the task. In case all existing threads are busy and the + * number of tasks in the queue is higher than the adjustable threshold, the + * pool will try to create a new thread to serve the task if the maximum number + * has not been reached. Otherwise, the task will be put into a queue based on + * priority, which can be valued from 0 to 255, with higher values being served + * first. If there are tasks with the same priority, the new task might be put at + * the top or at the bottom - it depends on which function is used to put the task. + * + * @remarks There may be the case where the thread pool can use up to the maximum + * number of threads at peak load, but having those threads idle afterwards. A + * maximum number of idle threads can be set so that the extra idling threads will + * be terminated to save system resources. + */ +#if APR_HAS_THREADS + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_Util_TP Thread Pool routines + * @ingroup APR_Util + * @{ + */ + +/** Opaque Thread Pool structure. */ +typedef struct apr_thread_pool apr_thread_pool_t; + +#define APR_THREAD_TASK_PRIORITY_LOWEST 0 +#define APR_THREAD_TASK_PRIORITY_LOW 63 +#define APR_THREAD_TASK_PRIORITY_NORMAL 127 +#define APR_THREAD_TASK_PRIORITY_HIGH 191 +#define APR_THREAD_TASK_PRIORITY_HIGHEST 255 + +/** + * Create a thread pool + * @param me The pointer in which to return the newly created apr_thread_pool + * object, or NULL if thread pool creation fails. + * @param init_threads The number of threads to be created initially, this number + * will also be used as the initial value for the maximum number of idle threads. + * @param max_threads The maximum number of threads that can be created + * @param pool The pool to use + * @return APR_SUCCESS if the thread pool was created successfully. Otherwise, + * the error code. + */ +APU_DECLARE(apr_status_t) apr_thread_pool_create(apr_thread_pool_t **me, + apr_size_t init_threads, + apr_size_t max_threads, + apr_pool_t *pool); + +/** + * Destroy the thread pool and stop all the threads + * @return APR_SUCCESS if all threads are stopped. + */ +APU_DECLARE(apr_status_t) apr_thread_pool_destroy(apr_thread_pool_t *me); + +/** + * Schedule a task to the bottom of the tasks of same priority. + * @param me The thread pool + * @param func The task function + * @param param The parameter for the task function + * @param priority The priority of the task. + * @param owner Owner of this task. + * @return APR_SUCCESS if the task had been scheduled successfully + */ +APU_DECLARE(apr_status_t) apr_thread_pool_push(apr_thread_pool_t *me, + apr_thread_start_t func, + void *param, + apr_byte_t priority, + void *owner); +/** + * Schedule a task to be run after a delay + * @param me The thread pool + * @param func The task function + * @param param The parameter for the task function + * @param time Time in microseconds + * @param owner Owner of this task. + * @return APR_SUCCESS if the task had been scheduled successfully + */ +APU_DECLARE(apr_status_t) apr_thread_pool_schedule(apr_thread_pool_t *me, + apr_thread_start_t func, + void *param, + apr_interval_time_t time, + void *owner); + +/** + * Schedule a task to the top of the tasks of same priority. + * @param me The thread pool + * @param func The task function + * @param param The parameter for the task function + * @param priority The priority of the task. + * @param owner Owner of this task. + * @return APR_SUCCESS if the task had been scheduled successfully + */ +APU_DECLARE(apr_status_t) apr_thread_pool_top(apr_thread_pool_t *me, + apr_thread_start_t func, + void *param, + apr_byte_t priority, + void *owner); + +/** + * Cancel tasks submitted by the owner. If there is any task from the owner that + * is currently running, the function will spin until the task finished. + * @param me The thread pool + * @param owner Owner of the task + * @return APR_SUCCESS if the task has been cancelled successfully + * @note The task function should not be calling cancel, otherwise the function + * may get stuck forever. The function assert if it detect such a case. + */ +APU_DECLARE(apr_status_t) apr_thread_pool_tasks_cancel(apr_thread_pool_t *me, + void *owner); + +/** + * Get the current number of tasks waiting in the queue + * @param me The thread pool + * @return Number of tasks in the queue + */ +APU_DECLARE(apr_size_t) apr_thread_pool_tasks_count(apr_thread_pool_t *me); + +/** + * Get the current number of scheduled tasks waiting in the queue + * @param me The thread pool + * @return Number of scheduled tasks in the queue + */ +APU_DECLARE(apr_size_t) apr_thread_pool_scheduled_tasks_count(apr_thread_pool_t *me); + +/** + * Get the current number of threads + * @param me The thread pool + * @return Total number of threads + */ +APU_DECLARE(apr_size_t) apr_thread_pool_threads_count(apr_thread_pool_t *me); + +/** + * Get the current number of busy threads + * @param me The thread pool + * @return Number of busy threads + */ +APU_DECLARE(apr_size_t) apr_thread_pool_busy_count(apr_thread_pool_t *me); + +/** + * Get the current number of idle threads + * @param me The thread pool + * @return Number of idle threads + */ +APU_DECLARE(apr_size_t) apr_thread_pool_idle_count(apr_thread_pool_t *me); + +/** + * Access function for the maximum number of idle threads. Number of current + * idle threads will be reduced to the new limit. + * @param me The thread pool + * @param cnt The number + * @return The number of threads that were stopped. + */ +APU_DECLARE(apr_size_t) apr_thread_pool_idle_max_set(apr_thread_pool_t *me, + apr_size_t cnt); + +/** + * Get number of tasks that have run + * @param me The thread pool + * @return Number of tasks that have run + */ +APU_DECLARE(apr_size_t) + apr_thread_pool_tasks_run_count(apr_thread_pool_t * me); + +/** + * Get high water mark of the number of tasks waiting to run + * @param me The thread pool + * @return High water mark of tasks waiting to run + */ +APU_DECLARE(apr_size_t) + apr_thread_pool_tasks_high_count(apr_thread_pool_t * me); + +/** + * Get high water mark of the number of threads + * @param me The thread pool + * @return High water mark of threads in thread pool + */ +APU_DECLARE(apr_size_t) + apr_thread_pool_threads_high_count(apr_thread_pool_t * me); + +/** + * Get the number of idle threads that were destroyed after timing out + * @param me The thread pool + * @return Number of idle threads that timed out + */ +APU_DECLARE(apr_size_t) + apr_thread_pool_threads_idle_timeout_count(apr_thread_pool_t * me); + +/** + * Access function for the maximum number of idle threads + * @param me The thread pool + * @return The current maximum number + */ +APU_DECLARE(apr_size_t) apr_thread_pool_idle_max_get(apr_thread_pool_t *me); + +/** + * Access function for the maximum number of threads. + * @param me The thread pool + * @param cnt Number of threads + * @return The original maximum number of threads + */ +APU_DECLARE(apr_size_t) apr_thread_pool_thread_max_set(apr_thread_pool_t *me, + apr_size_t cnt); + +/** + * Access function for the maximum wait time (in microseconds) of an + * idling thread that exceeds the maximum number of idling threads. + * A non-zero value allows for the reaping of idling threads to shrink + * over time. Which helps reduce thrashing. + * @param me The thread pool + * @param timeout The number of microseconds an idle thread should wait + * till it reaps itself + * @return The original maximum wait time + */ +APU_DECLARE(apr_interval_time_t) + apr_thread_pool_idle_wait_set(apr_thread_pool_t * me, + apr_interval_time_t timeout); + +/** + * Access function for the maximum wait time (in microseconds) of an + * idling thread that exceeds the maximum number of idling threads + * @param me The thread pool + * @return The current maximum wait time + */ +APU_DECLARE(apr_interval_time_t) + apr_thread_pool_idle_wait_get(apr_thread_pool_t * me); + +/** + * Access function for the maximum number of threads + * @param me The thread pool + * @return The current maximum number + */ +APU_DECLARE(apr_size_t) apr_thread_pool_thread_max_get(apr_thread_pool_t *me); + +/** + * Access function for the threshold of tasks in queue to trigger a new thread. + * @param me The thread pool + * @param cnt The new threshold + * @return The original threshold + */ +APU_DECLARE(apr_size_t) apr_thread_pool_threshold_set(apr_thread_pool_t *me, + apr_size_t val); + +/** + * Access function for the threshold of tasks in queue to trigger a new thread. + * @param me The thread pool + * @return The current threshold + */ +APU_DECLARE(apr_size_t) apr_thread_pool_threshold_get(apr_thread_pool_t * me); + +/** + * Get owner of the task currently been executed by the thread. + * @param thd The thread is executing a task + * @param owner Pointer to receive owner of the task. + * @return APR_SUCCESS if the owner is retrieved successfully + */ +APU_DECLARE(apr_status_t) apr_thread_pool_task_owner_get(apr_thread_t *thd, + void **owner); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_HAS_THREADS */ +#endif /* !APR_THREAD_POOL_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_thread_proc.h b/c/dependencies/windows/apr/x64/include/apr_thread_proc.h new file mode 100644 index 00000000..ea3c43f9 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_thread_proc.h @@ -0,0 +1,846 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_THREAD_PROC_H +#define APR_THREAD_PROC_H + +/** + * @file apr_thread_proc.h + * @brief APR Thread and Process Library + */ + +#include "apr.h" +#include "apr_file_io.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_perms_set.h" + +#if APR_HAVE_STRUCT_RLIMIT +#include +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_thread_proc Threads and Process Functions + * @ingroup APR + * @{ + */ + +typedef enum { + APR_SHELLCMD, /**< use the shell to invoke the program */ + APR_PROGRAM, /**< invoke the program directly, no copied env */ + APR_PROGRAM_ENV, /**< invoke the program, replicating our environment */ + APR_PROGRAM_PATH, /**< find program on PATH, use our environment */ + APR_SHELLCMD_ENV /**< use the shell to invoke the program, + * replicating our environment + */ +} apr_cmdtype_e; + +typedef enum { + APR_WAIT, /**< wait for the specified process to finish */ + APR_NOWAIT /**< do not wait -- just see if it has finished */ +} apr_wait_how_e; + +/* I am specifically calling out the values so that the macros below make + * more sense. Yes, I know I don't need to, but I am hoping this makes what + * I am doing more clear. If you want to add more reasons to exit, continue + * to use bitmasks. + */ +typedef enum { + APR_PROC_EXIT = 1, /**< process exited normally */ + APR_PROC_SIGNAL = 2, /**< process exited due to a signal */ + APR_PROC_SIGNAL_CORE = 4 /**< process exited and dumped a core file */ +} apr_exit_why_e; + +/** did we exit the process */ +#define APR_PROC_CHECK_EXIT(x) (x & APR_PROC_EXIT) +/** did we get a signal */ +#define APR_PROC_CHECK_SIGNALED(x) (x & APR_PROC_SIGNAL) +/** did we get core */ +#define APR_PROC_CHECK_CORE_DUMP(x) (x & APR_PROC_SIGNAL_CORE) + +/** @see apr_procattr_io_set */ +#define APR_NO_PIPE 0 +/** @see apr_procattr_io_set and apr_file_pipe_create_ex */ +#define APR_FULL_BLOCK 1 +/** @see apr_procattr_io_set and apr_file_pipe_create_ex */ +#define APR_FULL_NONBLOCK 2 +/** @see apr_procattr_io_set */ +#define APR_PARENT_BLOCK 3 +/** @see apr_procattr_io_set */ +#define APR_CHILD_BLOCK 4 +/** @see apr_procattr_io_set */ +#define APR_NO_FILE 8 + +/** @see apr_file_pipe_create_ex */ +#define APR_READ_BLOCK 3 +/** @see apr_file_pipe_create_ex */ +#define APR_WRITE_BLOCK 4 + +/** @see apr_procattr_io_set + * @note Win32 only effective with version 1.2.12, portably introduced in 1.3.0 + */ +#define APR_NO_FILE 8 + +/** @see apr_procattr_limit_set */ +#define APR_LIMIT_CPU 0 +/** @see apr_procattr_limit_set */ +#define APR_LIMIT_MEM 1 +/** @see apr_procattr_limit_set */ +#define APR_LIMIT_NPROC 2 +/** @see apr_procattr_limit_set */ +#define APR_LIMIT_NOFILE 3 + +/** + * @defgroup APR_OC Other Child Flags + * @{ + */ +#define APR_OC_REASON_DEATH 0 /**< child has died, caller must call + * unregister still */ +#define APR_OC_REASON_UNWRITABLE 1 /**< write_fd is unwritable */ +#define APR_OC_REASON_RESTART 2 /**< a restart is occurring, perform + * any necessary cleanup (including + * sending a special signal to child) + */ +#define APR_OC_REASON_UNREGISTER 3 /**< unregister has been called, do + * whatever is necessary (including + * kill the child) */ +#define APR_OC_REASON_LOST 4 /**< somehow the child exited without + * us knowing ... buggy os? */ +#define APR_OC_REASON_RUNNING 5 /**< a health check is occurring, + * for most maintainence functions + * this is a no-op. + */ +/** @} */ + +/** The APR process type */ +typedef struct apr_proc_t { + /** The process ID */ + pid_t pid; + /** Parent's side of pipe to child's stdin */ + apr_file_t *in; + /** Parent's side of pipe to child's stdout */ + apr_file_t *out; + /** Parent's side of pipe to child's stdouterr */ + apr_file_t *err; +#if APR_HAS_PROC_INVOKED || defined(DOXYGEN) + /** Diagnositics/debugging string of the command invoked for + * this process [only present if APR_HAS_PROC_INVOKED is true] + * @remark Only enabled on Win32 by default. + * @bug This should either always or never be present in release + * builds - since it breaks binary compatibility. We may enable + * it always in APR 1.0 yet leave it undefined in most cases. + */ + char *invoked; +#endif +#if defined(WIN32) || defined(DOXYGEN) + /** (Win32 only) Creator's handle granting access to the process + * @remark This handle is closed and reset to NULL in every case + * corresponding to a waitpid() on Unix which returns the exit status. + * Therefore Win32 correspond's to Unix's zombie reaping characteristics + * and avoids potential handle leaks. + */ + HANDLE hproc; +#endif +} apr_proc_t; + +/** + * The prototype for APR child errfn functions. (See the description + * of apr_procattr_child_errfn_set() for more information.) + * It is passed the following parameters: + * @param pool Pool associated with the apr_proc_t. If your child + * error function needs user data, associate it with this + * pool. + * @param err APR error code describing the error + * @param description Text description of type of processing which failed + */ +typedef void (apr_child_errfn_t)(apr_pool_t *proc, apr_status_t err, + const char *description); + +/** Opaque Thread structure. */ +typedef struct apr_thread_t apr_thread_t; + +/** Opaque Thread attributes structure. */ +typedef struct apr_threadattr_t apr_threadattr_t; + +/** Opaque Process attributes structure. */ +typedef struct apr_procattr_t apr_procattr_t; + +/** Opaque control variable for one-time atomic variables. */ +typedef struct apr_thread_once_t apr_thread_once_t; + +/** Opaque thread private address space. */ +typedef struct apr_threadkey_t apr_threadkey_t; + +/** Opaque record of child process. */ +typedef struct apr_other_child_rec_t apr_other_child_rec_t; + +/** + * The prototype for any APR thread worker functions. + */ +typedef void *(APR_THREAD_FUNC *apr_thread_start_t)(apr_thread_t*, void*); + +typedef enum { + APR_KILL_NEVER, /**< process is never killed (i.e., never sent + * any signals), but it will be reaped if it exits + * before the pool is cleaned up */ + APR_KILL_ALWAYS, /**< process is sent SIGKILL on apr_pool_t cleanup */ + APR_KILL_AFTER_TIMEOUT, /**< SIGTERM, wait 3 seconds, SIGKILL */ + APR_JUST_WAIT, /**< wait forever for the process to complete */ + APR_KILL_ONLY_ONCE /**< send SIGTERM and then wait */ +} apr_kill_conditions_e; + +/* Thread Function definitions */ + +#if APR_HAS_THREADS + +/** + * Create and initialize a new threadattr variable + * @param new_attr The newly created threadattr. + * @param cont The pool to use + */ +APR_DECLARE(apr_status_t) apr_threadattr_create(apr_threadattr_t **new_attr, + apr_pool_t *cont); + +/** + * Set if newly created threads should be created in detached state. + * @param attr The threadattr to affect + * @param on Non-zero if detached threads should be created. + */ +APR_DECLARE(apr_status_t) apr_threadattr_detach_set(apr_threadattr_t *attr, + apr_int32_t on); + +/** + * Get the detach state for this threadattr. + * @param attr The threadattr to reference + * @return APR_DETACH if threads are to be detached, or APR_NOTDETACH + * if threads are to be joinable. + */ +APR_DECLARE(apr_status_t) apr_threadattr_detach_get(apr_threadattr_t *attr); + +/** + * Set the stack size of newly created threads. + * @param attr The threadattr to affect + * @param stacksize The stack size in bytes + */ +APR_DECLARE(apr_status_t) apr_threadattr_stacksize_set(apr_threadattr_t *attr, + apr_size_t stacksize); + +/** + * Set the stack guard area size of newly created threads. + * @param attr The threadattr to affect + * @param guardsize The stack guard area size in bytes + * @note Thread library implementations commonly use a "guard area" + * after each thread's stack which is not readable or writable such that + * stack overflows cause a segfault; this consumes e.g. 4K of memory + * and increases memory management overhead. Setting the guard area + * size to zero hence trades off reliable behaviour on stack overflow + * for performance. */ +APR_DECLARE(apr_status_t) apr_threadattr_guardsize_set(apr_threadattr_t *attr, + apr_size_t guardsize); + +/** + * Create a new thread of execution + * @param new_thread The newly created thread handle. + * @param attr The threadattr to use to determine how to create the thread + * @param func The function to start the new thread in + * @param data Any data to be passed to the starting function + * @param cont The pool to use + */ +APR_DECLARE(apr_status_t) apr_thread_create(apr_thread_t **new_thread, + apr_threadattr_t *attr, + apr_thread_start_t func, + void *data, apr_pool_t *cont); + +/** + * stop the current thread + * @param thd The thread to stop + * @param retval The return value to pass back to any thread that cares + */ +APR_DECLARE(apr_status_t) apr_thread_exit(apr_thread_t *thd, + apr_status_t retval); + +/** + * block until the desired thread stops executing. + * @param retval The return value from the dead thread. + * @param thd The thread to join + */ +APR_DECLARE(apr_status_t) apr_thread_join(apr_status_t *retval, + apr_thread_t *thd); + +/** + * force the current thread to yield the processor + */ +APR_DECLARE(void) apr_thread_yield(void); + +/** + * Initialize the control variable for apr_thread_once. If this isn't + * called, apr_initialize won't work. + * @param control The control variable to initialize + * @param p The pool to allocate data from. + */ +APR_DECLARE(apr_status_t) apr_thread_once_init(apr_thread_once_t **control, + apr_pool_t *p); + +/** + * Run the specified function one time, regardless of how many threads + * call it. + * @param control The control variable. The same variable should + * be passed in each time the function is tried to be + * called. This is how the underlying functions determine + * if the function has ever been called before. + * @param func The function to call. + */ +APR_DECLARE(apr_status_t) apr_thread_once(apr_thread_once_t *control, + void (*func)(void)); + +/** + * detach a thread + * @param thd The thread to detach + */ +APR_DECLARE(apr_status_t) apr_thread_detach(apr_thread_t *thd); + +/** + * Return user data associated with the current thread. + * @param data The user data associated with the thread. + * @param key The key to associate with the data + * @param thread The currently open thread. + */ +APR_DECLARE(apr_status_t) apr_thread_data_get(void **data, const char *key, + apr_thread_t *thread); + +/** + * Set user data associated with the current thread. + * @param data The user data to associate with the thread. + * @param key The key to use for associating the data with the thread + * @param cleanup The cleanup routine to use when the thread is destroyed. + * @param thread The currently open thread. + */ +APR_DECLARE(apr_status_t) apr_thread_data_set(void *data, const char *key, + apr_status_t (*cleanup) (void *), + apr_thread_t *thread); + +/** + * Create and initialize a new thread private address space + * @param key The thread private handle. + * @param dest The destructor to use when freeing the private memory. + * @param cont The pool to use + */ +APR_DECLARE(apr_status_t) apr_threadkey_private_create(apr_threadkey_t **key, + void (*dest)(void *), + apr_pool_t *cont); + +/** + * Get a pointer to the thread private memory + * @param new_mem The data stored in private memory + * @param key The handle for the desired thread private memory + */ +APR_DECLARE(apr_status_t) apr_threadkey_private_get(void **new_mem, + apr_threadkey_t *key); + +/** + * Set the data to be stored in thread private memory + * @param priv The data to be stored in private memory + * @param key The handle for the desired thread private memory + */ +APR_DECLARE(apr_status_t) apr_threadkey_private_set(void *priv, + apr_threadkey_t *key); + +/** + * Free the thread private memory + * @param key The handle for the desired thread private memory + */ +APR_DECLARE(apr_status_t) apr_threadkey_private_delete(apr_threadkey_t *key); + +/** + * Return the pool associated with the current threadkey. + * @param data The user data associated with the threadkey. + * @param key The key associated with the data + * @param threadkey The currently open threadkey. + */ +APR_DECLARE(apr_status_t) apr_threadkey_data_get(void **data, const char *key, + apr_threadkey_t *threadkey); + +/** + * Return the pool associated with the current threadkey. + * @param data The data to set. + * @param key The key to associate with the data. + * @param cleanup The cleanup routine to use when the file is destroyed. + * @param threadkey The currently open threadkey. + */ +APR_DECLARE(apr_status_t) apr_threadkey_data_set(void *data, const char *key, + apr_status_t (*cleanup) (void *), + apr_threadkey_t *threadkey); + +#endif + +/** + * Create and initialize a new procattr variable + * @param new_attr The newly created procattr. + * @param cont The pool to use + */ +APR_DECLARE(apr_status_t) apr_procattr_create(apr_procattr_t **new_attr, + apr_pool_t *cont); + +/** + * Determine if any of stdin, stdout, or stderr should be linked to pipes + * when starting a child process. + * @param attr The procattr we care about. + * @param in Should stdin be a pipe back to the parent? + * @param out Should stdout be a pipe back to the parent? + * @param err Should stderr be a pipe back to the parent? + * @note If APR_NO_PIPE, there will be no special channel, the child + * inherits the parent's corresponding stdio stream. If APR_NO_FILE is + * specified, that corresponding stream is closed in the child (and will + * be INVALID_HANDLE_VALUE when inspected on Win32). This can have ugly + * side effects, as the next file opened in the child on Unix will fall + * into the stdio stream fd slot! + */ +APR_DECLARE(apr_status_t) apr_procattr_io_set(apr_procattr_t *attr, + apr_int32_t in, apr_int32_t out, + apr_int32_t err); + +/** + * Set the child_in and/or parent_in values to existing apr_file_t values. + * @param attr The procattr we care about. + * @param child_in apr_file_t value to use as child_in. Must be a valid file. + * @param parent_in apr_file_t value to use as parent_in. Must be a valid file. + * @remark This is NOT a required initializer function. This is + * useful if you have already opened a pipe (or multiple files) + * that you wish to use, perhaps persistently across multiple + * process invocations - such as a log file. You can save some + * extra function calls by not creating your own pipe since this + * creates one in the process space for you. + * @bug Note that calling this function with two NULL files on some platforms + * creates an APR_FULL_BLOCK pipe, but this behavior is neither portable nor + * is it supported. @see apr_procattr_io_set instead for simple pipes. + */ +APR_DECLARE(apr_status_t) apr_procattr_child_in_set(struct apr_procattr_t *attr, + apr_file_t *child_in, + apr_file_t *parent_in); + +/** + * Set the child_out and parent_out values to existing apr_file_t values. + * @param attr The procattr we care about. + * @param child_out apr_file_t value to use as child_out. Must be a valid file. + * @param parent_out apr_file_t value to use as parent_out. Must be a valid file. + * @remark This is NOT a required initializer function. This is + * useful if you have already opened a pipe (or multiple files) + * that you wish to use, perhaps persistently across multiple + * process invocations - such as a log file. + * @bug Note that calling this function with two NULL files on some platforms + * creates an APR_FULL_BLOCK pipe, but this behavior is neither portable nor + * is it supported. @see apr_procattr_io_set instead for simple pipes. + */ +APR_DECLARE(apr_status_t) apr_procattr_child_out_set(struct apr_procattr_t *attr, + apr_file_t *child_out, + apr_file_t *parent_out); + +/** + * Set the child_err and parent_err values to existing apr_file_t values. + * @param attr The procattr we care about. + * @param child_err apr_file_t value to use as child_err. Must be a valid file. + * @param parent_err apr_file_t value to use as parent_err. Must be a valid file. + * @remark This is NOT a required initializer function. This is + * useful if you have already opened a pipe (or multiple files) + * that you wish to use, perhaps persistently across multiple + * process invocations - such as a log file. + * @bug Note that calling this function with two NULL files on some platforms + * creates an APR_FULL_BLOCK pipe, but this behavior is neither portable nor + * is it supported. @see apr_procattr_io_set instead for simple pipes. + */ +APR_DECLARE(apr_status_t) apr_procattr_child_err_set(struct apr_procattr_t *attr, + apr_file_t *child_err, + apr_file_t *parent_err); + +/** + * Set which directory the child process should start executing in. + * @param attr The procattr we care about. + * @param dir Which dir to start in. By default, this is the same dir as + * the parent currently resides in, when the createprocess call + * is made. + */ +APR_DECLARE(apr_status_t) apr_procattr_dir_set(apr_procattr_t *attr, + const char *dir); + +/** + * Set what type of command the child process will call. + * @param attr The procattr we care about. + * @param cmd The type of command. One of: + *
+ *            APR_SHELLCMD     --  Anything that the shell can handle
+ *            APR_PROGRAM      --  Executable program   (default) 
+ *            APR_PROGRAM_ENV  --  Executable program, copy environment
+ *            APR_PROGRAM_PATH --  Executable program on PATH, copy env
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_procattr_cmdtype_set(apr_procattr_t *attr, + apr_cmdtype_e cmd); + +/** + * Determine if the child should start in detached state. + * @param attr The procattr we care about. + * @param detach Should the child start in detached state? Default is no. + */ +APR_DECLARE(apr_status_t) apr_procattr_detach_set(apr_procattr_t *attr, + apr_int32_t detach); + +#if APR_HAVE_STRUCT_RLIMIT +/** + * Set the Resource Utilization limits when starting a new process. + * @param attr The procattr we care about. + * @param what Which limit to set, one of: + *
+ *                 APR_LIMIT_CPU
+ *                 APR_LIMIT_MEM
+ *                 APR_LIMIT_NPROC
+ *                 APR_LIMIT_NOFILE
+ * 
+ * @param limit Value to set the limit to. + */ +APR_DECLARE(apr_status_t) apr_procattr_limit_set(apr_procattr_t *attr, + apr_int32_t what, + struct rlimit *limit); +#endif + +/** + * Specify an error function to be called in the child process if APR + * encounters an error in the child prior to running the specified program. + * @param attr The procattr describing the child process to be created. + * @param errfn The function to call in the child process. + * @remark At the present time, it will only be called from apr_proc_create() + * on platforms where fork() is used. It will never be called on other + * platforms, on those platforms apr_proc_create() will return the error + * in the parent process rather than invoke the callback in the now-forked + * child process. + */ +APR_DECLARE(apr_status_t) apr_procattr_child_errfn_set(apr_procattr_t *attr, + apr_child_errfn_t *errfn); + +/** + * Specify that apr_proc_create() should do whatever it can to report + * failures to the caller of apr_proc_create(), rather than find out in + * the child. + * @param attr The procattr describing the child process to be created. + * @param chk Flag to indicate whether or not extra work should be done + * to try to report failures to the caller. + * @remark This flag only affects apr_proc_create() on platforms where + * fork() is used. This leads to extra overhead in the calling + * process, but that may help the application handle such + * errors more gracefully. + */ +APR_DECLARE(apr_status_t) apr_procattr_error_check_set(apr_procattr_t *attr, + apr_int32_t chk); + +/** + * Determine if the child should start in its own address space or using the + * current one from its parent + * @param attr The procattr we care about. + * @param addrspace Should the child start in its own address space? Default + * is no on NetWare and yes on other platforms. + */ +APR_DECLARE(apr_status_t) apr_procattr_addrspace_set(apr_procattr_t *attr, + apr_int32_t addrspace); + +/** + * Set the username used for running process + * @param attr The procattr we care about. + * @param username The username used + * @param password User password if needed. Password is needed on WIN32 + * or any other platform having + * APR_PROCATTR_USER_SET_REQUIRES_PASSWORD set. + */ +APR_DECLARE(apr_status_t) apr_procattr_user_set(apr_procattr_t *attr, + const char *username, + const char *password); + +/** + * Set the group used for running process + * @param attr The procattr we care about. + * @param groupname The group name used + */ +APR_DECLARE(apr_status_t) apr_procattr_group_set(apr_procattr_t *attr, + const char *groupname); + + +/** + * Register permission set function + * @param attr The procattr we care about. + * @param perms_set_fn Permission set callback + * @param data Data to pass to permission callback function + * @param perms Permissions to set + */ +APR_DECLARE(apr_status_t) apr_procattr_perms_set_register(apr_procattr_t *attr, + apr_perms_setfn_t *perms_set_fn, + void *data, + apr_fileperms_t perms); + +#if APR_HAS_FORK +/** + * This is currently the only non-portable call in APR. This executes + * a standard unix fork. + * @param proc The resulting process handle. + * @param cont The pool to use. + * @remark returns APR_INCHILD for the child, and APR_INPARENT for the parent + * or an error. + */ +APR_DECLARE(apr_status_t) apr_proc_fork(apr_proc_t *proc, apr_pool_t *cont); +#endif + +/** + * Create a new process and execute a new program within that process. + * @param new_proc The resulting process handle. + * @param progname The program to run + * @param args the arguments to pass to the new program. The first + * one should be the program name. + * @param env The new environment table for the new process. This + * should be a list of NULL-terminated strings. This argument + * is ignored for APR_PROGRAM_ENV, APR_PROGRAM_PATH, and + * APR_SHELLCMD_ENV types of commands. + * @param attr the procattr we should use to determine how to create the new + * process + * @param pool The pool to use. + * @note This function returns without waiting for the new process to terminate; + * use apr_proc_wait for that. + */ +APR_DECLARE(apr_status_t) apr_proc_create(apr_proc_t *new_proc, + const char *progname, + const char * const *args, + const char * const *env, + apr_procattr_t *attr, + apr_pool_t *pool); + +/** + * Wait for a child process to die + * @param proc The process handle that corresponds to the desired child process + * @param exitcode The returned exit status of the child, if a child process + * dies, or the signal that caused the child to die. + * On platforms that don't support obtaining this information, + * the status parameter will be returned as APR_ENOTIMPL. + * @param exitwhy Why the child died, the bitwise or of: + *
+ *            APR_PROC_EXIT         -- process terminated normally
+ *            APR_PROC_SIGNAL       -- process was killed by a signal
+ *            APR_PROC_SIGNAL_CORE  -- process was killed by a signal, and
+ *                                     generated a core dump.
+ * 
+ * @param waithow How should we wait. One of: + *
+ *            APR_WAIT   -- block until the child process dies.
+ *            APR_NOWAIT -- return immediately regardless of if the 
+ *                          child is dead or not.
+ * 
+ * @remark The child's status is in the return code to this process. It is one of: + *
+ *            APR_CHILD_DONE     -- child is no longer running.
+ *            APR_CHILD_NOTDONE  -- child is still running.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_proc_wait(apr_proc_t *proc, + int *exitcode, apr_exit_why_e *exitwhy, + apr_wait_how_e waithow); + +/** + * Wait for any current child process to die and return information + * about that child. + * @param proc Pointer to NULL on entry, will be filled out with child's + * information + * @param exitcode The returned exit status of the child, if a child process + * dies, or the signal that caused the child to die. + * On platforms that don't support obtaining this information, + * the status parameter will be returned as APR_ENOTIMPL. + * @param exitwhy Why the child died, the bitwise or of: + *
+ *            APR_PROC_EXIT         -- process terminated normally
+ *            APR_PROC_SIGNAL       -- process was killed by a signal
+ *            APR_PROC_SIGNAL_CORE  -- process was killed by a signal, and
+ *                                     generated a core dump.
+ * 
+ * @param waithow How should we wait. One of: + *
+ *            APR_WAIT   -- block until the child process dies.
+ *            APR_NOWAIT -- return immediately regardless of if the 
+ *                          child is dead or not.
+ * 
+ * @param p Pool to allocate child information out of. + * @bug Passing proc as a *proc rather than **proc was an odd choice + * for some platforms... this should be revisited in 1.0 + */ +APR_DECLARE(apr_status_t) apr_proc_wait_all_procs(apr_proc_t *proc, + int *exitcode, + apr_exit_why_e *exitwhy, + apr_wait_how_e waithow, + apr_pool_t *p); + +#define APR_PROC_DETACH_FOREGROUND 0 /**< Do not detach */ +#define APR_PROC_DETACH_DAEMONIZE 1 /**< Detach */ + +/** + * Detach the process from the controlling terminal. + * @param daemonize set to non-zero if the process should daemonize + * and become a background process, else it will + * stay in the foreground. + */ +APR_DECLARE(apr_status_t) apr_proc_detach(int daemonize); + +/** + * Register an other_child -- a child associated to its registered + * maintence callback. This callback is invoked when the process + * dies, is disconnected or disappears. + * @param proc The child process to register. + * @param maintenance maintenance is a function that is invoked with a + * reason and the data pointer passed here. + * @param data Opaque context data passed to the maintenance function. + * @param write_fd An fd that is probed for writing. If it is ever unwritable + * then the maintenance is invoked with reason + * OC_REASON_UNWRITABLE. + * @param p The pool to use for allocating memory. + * @bug write_fd duplicates the proc->out stream, it's really redundant + * and should be replaced in the APR 1.0 API with a bitflag of which + * proc->in/out/err handles should be health checked. + * @bug no platform currently tests the pipes health. + */ +APR_DECLARE(void) apr_proc_other_child_register(apr_proc_t *proc, + void (*maintenance) (int reason, + void *, + int status), + void *data, apr_file_t *write_fd, + apr_pool_t *p); + +/** + * Stop watching the specified other child. + * @param data The data to pass to the maintenance function. This is + * used to find the process to unregister. + * @warning Since this can be called by a maintenance function while we're + * scanning the other_children list, all scanners should protect + * themself by loading ocr->next before calling any maintenance + * function. + */ +APR_DECLARE(void) apr_proc_other_child_unregister(void *data); + +/** + * Notify the maintenance callback of a registered other child process + * that application has detected an event, such as death. + * @param proc The process to check + * @param reason The reason code to pass to the maintenance function + * @param status The status to pass to the maintenance function + * @remark An example of code using this behavior; + *
+ * rv = apr_proc_wait_all_procs(&proc, &exitcode, &status, APR_WAIT, p);
+ * if (APR_STATUS_IS_CHILD_DONE(rv)) {
+ * \#if APR_HAS_OTHER_CHILD
+ *     if (apr_proc_other_child_alert(&proc, APR_OC_REASON_DEATH, status)
+ *             == APR_SUCCESS) {
+ *         ;  (already handled)
+ *     }
+ *     else
+ * \#endif
+ *         [... handling non-otherchild processes death ...]
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_proc_other_child_alert(apr_proc_t *proc, + int reason, + int status); + +/** + * Test one specific other child processes and invoke the maintenance callback + * with the appropriate reason code, if still running, or the appropriate reason + * code if the process is no longer healthy. + * @param ocr The registered other child + * @param reason The reason code (e.g. APR_OC_REASON_RESTART) if still running + */ +APR_DECLARE(void) apr_proc_other_child_refresh(apr_other_child_rec_t *ocr, + int reason); + +/** + * Test all registered other child processes and invoke the maintenance callback + * with the appropriate reason code, if still running, or the appropriate reason + * code if the process is no longer healthy. + * @param reason The reason code (e.g. APR_OC_REASON_RESTART) to running processes + */ +APR_DECLARE(void) apr_proc_other_child_refresh_all(int reason); + +/** + * Terminate a process. + * @param proc The process to terminate. + * @param sig How to kill the process. + */ +APR_DECLARE(apr_status_t) apr_proc_kill(apr_proc_t *proc, int sig); + +/** + * Register a process to be killed when a pool dies. + * @param a The pool to use to define the processes lifetime + * @param proc The process to register + * @param how How to kill the process, one of: + *
+ *         APR_KILL_NEVER         -- process is never sent any signals
+ *         APR_KILL_ALWAYS        -- process is sent SIGKILL on apr_pool_t cleanup
+ *         APR_KILL_AFTER_TIMEOUT -- SIGTERM, wait 3 seconds, SIGKILL
+ *         APR_JUST_WAIT          -- wait forever for the process to complete
+ *         APR_KILL_ONLY_ONCE     -- send SIGTERM and then wait
+ * 
+ */ +APR_DECLARE(void) apr_pool_note_subprocess(apr_pool_t *a, apr_proc_t *proc, + apr_kill_conditions_e how); + +#if APR_HAS_THREADS + +#if (APR_HAVE_SIGWAIT || APR_HAVE_SIGSUSPEND) && !defined(OS2) + +/** + * Setup the process for a single thread to be used for all signal handling. + * @warning This must be called before any threads are created + */ +APR_DECLARE(apr_status_t) apr_setup_signal_thread(void); + +/** + * Make the current thread listen for signals. This thread will loop + * forever, calling a provided function whenever it receives a signal. That + * functions should return 1 if the signal has been handled, 0 otherwise. + * @param signal_handler The function to call when a signal is received + * apr_status_t apr_signal_thread((int)(*signal_handler)(int signum)) + * @note Synchronous signals like SIGABRT/SIGSEGV/SIGBUS/... are ignored by + * apr_signal_thread() and thus can't be waited by this function (they remain + * handled by the operating system or its native signals interface). + * @remark In APR version 1.6 and ealier, SIGUSR2 was part of these ignored + * signals and thus was never passed in to the signal_handler. From APR 1.7 + * this is no more the case so SIGUSR2 can be handled in signal_handler and + * acted upon like the other asynchronous signals. + */ +APR_DECLARE(apr_status_t) apr_signal_thread(int(*signal_handler)(int signum)); + +#endif /* (APR_HAVE_SIGWAIT || APR_HAVE_SIGSUSPEND) && !defined(OS2) */ + +/** + * Get the child-pool used by the thread from the thread info. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(thread); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_THREAD_PROC_H */ + diff --git a/c/dependencies/windows/apr/x64/include/apr_thread_rwlock.h b/c/dependencies/windows/apr/x64/include/apr_thread_rwlock.h new file mode 100644 index 00000000..0bd958fb --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_thread_rwlock.h @@ -0,0 +1,129 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_THREAD_RWLOCK_H +#define APR_THREAD_RWLOCK_H + +/** + * @file apr_thread_rwlock.h + * @brief APR Reader/Writer Lock Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#if APR_HAS_THREADS + +/** + * @defgroup apr_thread_rwlock Reader/Writer Lock Routines + * @ingroup APR + * @{ + */ + +/** Opaque read-write thread-safe lock. */ +typedef struct apr_thread_rwlock_t apr_thread_rwlock_t; + +/** + * Note: The following operations have undefined results: unlocking a + * read-write lock which is not locked in the calling thread; write + * locking a read-write lock which is already locked by the calling + * thread; destroying a read-write lock more than once; clearing or + * destroying the pool from which a locked read-write lock is + * allocated. + */ + +/** + * Create and initialize a read-write lock that can be used to synchronize + * threads. + * @param rwlock the memory address where the newly created readwrite lock + * will be stored. + * @param pool the pool from which to allocate the mutex. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_create(apr_thread_rwlock_t **rwlock, + apr_pool_t *pool); +/** + * Acquire a shared-read lock on the given read-write lock. This will allow + * multiple threads to enter the same critical section while they have acquired + * the read lock. + * @param rwlock the read-write lock on which to acquire the shared read. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_rdlock(apr_thread_rwlock_t *rwlock); + +/** + * Attempt to acquire the shared-read lock on the given read-write lock. This + * is the same as apr_thread_rwlock_rdlock(), only that the function fails + * if there is another thread holding the write lock, or if there are any + * write threads blocking on the lock. If the function fails for this case, + * APR_EBUSY will be returned. Note: it is important that the + * APR_STATUS_IS_EBUSY(s) macro be used to determine if the return value was + * APR_EBUSY, for portability reasons. + * @param rwlock the rwlock on which to attempt the shared read. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_tryrdlock(apr_thread_rwlock_t *rwlock); + +/** + * Acquire an exclusive-write lock on the given read-write lock. This will + * allow only one single thread to enter the critical sections. If there + * are any threads currently holding the read-lock, this thread is put to + * sleep until it can have exclusive access to the lock. + * @param rwlock the read-write lock on which to acquire the exclusive write. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_wrlock(apr_thread_rwlock_t *rwlock); + +/** + * Attempt to acquire the exclusive-write lock on the given read-write lock. + * This is the same as apr_thread_rwlock_wrlock(), only that the function fails + * if there is any other thread holding the lock (for reading or writing), + * in which case the function will return APR_EBUSY. Note: it is important + * that the APR_STATUS_IS_EBUSY(s) macro be used to determine if the return + * value was APR_EBUSY, for portability reasons. + * @param rwlock the rwlock on which to attempt the exclusive write. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_trywrlock(apr_thread_rwlock_t *rwlock); + +/** + * Release either the read or write lock currently held by the calling thread + * associated with the given read-write lock. + * @param rwlock the read-write lock to be released (unlocked). + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_unlock(apr_thread_rwlock_t *rwlock); + +/** + * Destroy the read-write lock and free the associated memory. + * @param rwlock the rwlock to destroy. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_destroy(apr_thread_rwlock_t *rwlock); + +/** + * Get the pool used by this thread_rwlock. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(thread_rwlock); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_THREAD_RWLOCK_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_time.h b/c/dependencies/windows/apr/x64/include/apr_time.h new file mode 100644 index 00000000..b0efd791 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_time.h @@ -0,0 +1,237 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_TIME_H +#define APR_TIME_H + +/** + * @file apr_time.h + * @brief APR Time Library + */ + +#include "apr.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_time Time Routines + * @ingroup APR + * @{ + */ + +/** month names */ +APR_DECLARE_DATA extern const char apr_month_snames[12][4]; +/** day names */ +APR_DECLARE_DATA extern const char apr_day_snames[7][4]; + + +/** number of microseconds since 00:00:00 January 1, 1970 UTC */ +typedef apr_int64_t apr_time_t; + + +/** mechanism to properly type apr_time_t literals */ +#define APR_TIME_C(val) APR_INT64_C(val) + +/** mechanism to properly print apr_time_t values */ +#define APR_TIME_T_FMT APR_INT64_T_FMT + +/** intervals for I/O timeouts, in microseconds */ +typedef apr_int64_t apr_interval_time_t; +/** short interval for I/O timeouts, in microseconds */ +typedef apr_int32_t apr_short_interval_time_t; + +/** number of microseconds per second */ +#define APR_USEC_PER_SEC APR_TIME_C(1000000) + +/** @return apr_time_t as a second */ +#define apr_time_sec(time) ((time) / APR_USEC_PER_SEC) + +/** @return apr_time_t as a usec */ +#define apr_time_usec(time) ((time) % APR_USEC_PER_SEC) + +/** @return apr_time_t as a msec */ +#define apr_time_msec(time) (((time) / 1000) % 1000) + +/** @return apr_time_t as a msec */ +#define apr_time_as_msec(time) ((time) / 1000) + +/** @return milliseconds as an apr_time_t */ +#define apr_time_from_msec(msec) ((apr_time_t)(msec) * 1000) + +/** @return seconds as an apr_time_t */ +#define apr_time_from_sec(sec) ((apr_time_t)(sec) * APR_USEC_PER_SEC) + +/** @return a second and usec combination as an apr_time_t */ +#define apr_time_make(sec, usec) ((apr_time_t)(sec) * APR_USEC_PER_SEC \ + + (apr_time_t)(usec)) + +/** + * @return the current time + */ +APR_DECLARE(apr_time_t) apr_time_now(void); + +/** @see apr_time_exp_t */ +typedef struct apr_time_exp_t apr_time_exp_t; + +/** + * a structure similar to ANSI struct tm with the following differences: + * - tm_usec isn't an ANSI field + * - tm_gmtoff isn't an ANSI field (it's a BSDism) + */ +struct apr_time_exp_t { + /** microseconds past tm_sec */ + apr_int32_t tm_usec; + /** (0-61) seconds past tm_min */ + apr_int32_t tm_sec; + /** (0-59) minutes past tm_hour */ + apr_int32_t tm_min; + /** (0-23) hours past midnight */ + apr_int32_t tm_hour; + /** (1-31) day of the month */ + apr_int32_t tm_mday; + /** (0-11) month of the year */ + apr_int32_t tm_mon; + /** year since 1900 */ + apr_int32_t tm_year; + /** (0-6) days since Sunday */ + apr_int32_t tm_wday; + /** (0-365) days since January 1 */ + apr_int32_t tm_yday; + /** daylight saving time */ + apr_int32_t tm_isdst; + /** seconds east of UTC */ + apr_int32_t tm_gmtoff; +}; + +/* Delayed the include to avoid a circular reference */ +#include "apr_pools.h" + +/** + * Convert an ansi time_t to an apr_time_t + * @param result the resulting apr_time_t + * @param input the time_t to convert + */ +APR_DECLARE(apr_status_t) apr_time_ansi_put(apr_time_t *result, + time_t input); + +/** + * Convert a time to its human readable components using an offset + * from GMT. + * @param result the exploded time + * @param input the time to explode + * @param offs the number of seconds offset to apply + */ +APR_DECLARE(apr_status_t) apr_time_exp_tz(apr_time_exp_t *result, + apr_time_t input, + apr_int32_t offs); + +/** + * Convert a time to its human readable components (GMT). + * @param result the exploded time + * @param input the time to explode + */ +APR_DECLARE(apr_status_t) apr_time_exp_gmt(apr_time_exp_t *result, + apr_time_t input); + +/** + * Convert a time to its human readable components in the local timezone. + * @param result the exploded time + * @param input the time to explode + */ +APR_DECLARE(apr_status_t) apr_time_exp_lt(apr_time_exp_t *result, + apr_time_t input); + +/** + * Convert time value from human readable format to a numeric apr_time_t + * (elapsed microseconds since the epoch). + * @param result the resulting imploded time + * @param input the input exploded time + */ +APR_DECLARE(apr_status_t) apr_time_exp_get(apr_time_t *result, + apr_time_exp_t *input); + +/** + * Convert time value from human readable format to a numeric apr_time_t that + * always represents GMT. + * @param result the resulting imploded time + * @param input the input exploded time + */ +APR_DECLARE(apr_status_t) apr_time_exp_gmt_get(apr_time_t *result, + apr_time_exp_t *input); + +/** + * Sleep for the specified number of micro-seconds. + * @param t desired amount of time to sleep. + * @warning May sleep for longer than the specified time. + */ +APR_DECLARE(void) apr_sleep(apr_interval_time_t t); + +/** length of a RFC822 Date */ +#define APR_RFC822_DATE_LEN (30) +/** + * apr_rfc822_date formats dates in the RFC822 + * format in an efficient manner. It is a fixed length + * format which requires APR_RFC822_DATA_LEN bytes of storage, + * including the trailing NUL terminator. + * @param date_str String to write to. + * @param t the time to convert + */ +APR_DECLARE(apr_status_t) apr_rfc822_date(char *date_str, apr_time_t t); + +/** length of a CTIME date */ +#define APR_CTIME_LEN (25) +/** + * apr_ctime formats dates in the ctime() format + * in an efficient manner. It is a fixed length format + * and requires APR_CTIME_LEN bytes of storage including + * the trailing NUL terminator. + * Unlike ANSI/ISO C ctime(), apr_ctime() does not include + * a \\n at the end of the string. + * @param date_str String to write to. + * @param t the time to convert + */ +APR_DECLARE(apr_status_t) apr_ctime(char *date_str, apr_time_t t); + +/** + * Formats the exploded time according to the format specified + * @param s string to write to + * @param retsize The length of the returned string + * @param max The maximum length of the string + * @param format The format for the time string + * @param tm The time to convert + */ +APR_DECLARE(apr_status_t) apr_strftime(char *s, apr_size_t *retsize, + apr_size_t max, const char *format, + apr_time_exp_t *tm); + +/** + * Improve the clock resolution for the lifetime of the given pool. + * Generally this is only desirable on benchmarking and other very + * time-sensitive applications, and has no impact on most platforms. + * @param p The pool to associate the finer clock resolution + */ +APR_DECLARE(void) apr_time_clock_hires(apr_pool_t *p); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_TIME_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_uri.h b/c/dependencies/windows/apr/x64/include/apr_uri.h new file mode 100644 index 00000000..02908a9d --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_uri.h @@ -0,0 +1,178 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_uri.h: External Interface of apr_uri.c + */ + +/** + * @file apr_uri.h + * @brief APR-UTIL URI Routines + */ + +#ifndef APR_URI_H +#define APR_URI_H + +#include "apu.h" + +#include "apr_network_io.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_URI URI + * @ingroup APR_Util + * @{ + */ + +#define APR_URI_FTP_DEFAULT_PORT 21 /**< default FTP port */ +#define APR_URI_SSH_DEFAULT_PORT 22 /**< default SSH port */ +#define APR_URI_TELNET_DEFAULT_PORT 23 /**< default telnet port */ +#define APR_URI_GOPHER_DEFAULT_PORT 70 /**< default Gopher port */ +#define APR_URI_HTTP_DEFAULT_PORT 80 /**< default HTTP port */ +#define APR_URI_POP_DEFAULT_PORT 110 /**< default POP port */ +#define APR_URI_NNTP_DEFAULT_PORT 119 /**< default NNTP port */ +#define APR_URI_IMAP_DEFAULT_PORT 143 /**< default IMAP port */ +#define APR_URI_PROSPERO_DEFAULT_PORT 191 /**< default Prospero port */ +#define APR_URI_WAIS_DEFAULT_PORT 210 /**< default WAIS port */ +#define APR_URI_LDAP_DEFAULT_PORT 389 /**< default LDAP port */ +#define APR_URI_HTTPS_DEFAULT_PORT 443 /**< default HTTPS port */ +#define APR_URI_RTSP_DEFAULT_PORT 554 /**< default RTSP port */ +#define APR_URI_SNEWS_DEFAULT_PORT 563 /**< default SNEWS port */ +#define APR_URI_ACAP_DEFAULT_PORT 674 /**< default ACAP port */ +#define APR_URI_NFS_DEFAULT_PORT 2049 /**< default NFS port */ +#define APR_URI_TIP_DEFAULT_PORT 3372 /**< default TIP port */ +#define APR_URI_SIP_DEFAULT_PORT 5060 /**< default SIP port */ + +/** Flags passed to unparse_uri_components(): */ +/** suppress "scheme://user\@site:port" */ +#define APR_URI_UNP_OMITSITEPART (1U<<0) +/** Just omit user */ +#define APR_URI_UNP_OMITUSER (1U<<1) +/** Just omit password */ +#define APR_URI_UNP_OMITPASSWORD (1U<<2) +/** omit "user:password\@" part */ +#define APR_URI_UNP_OMITUSERINFO (APR_URI_UNP_OMITUSER | \ + APR_URI_UNP_OMITPASSWORD) +/** Show plain text password (default: show XXXXXXXX) */ +#define APR_URI_UNP_REVEALPASSWORD (1U<<3) +/** Show "scheme://user\@site:port" only */ +#define APR_URI_UNP_OMITPATHINFO (1U<<4) +/** Omit the "?queryarg" from the path */ +#define APR_URI_UNP_OMITQUERY (1U<<5) + +/** @see apr_uri_t */ +typedef struct apr_uri_t apr_uri_t; + +/** + * A structure to encompass all of the fields in a uri + */ +struct apr_uri_t { + /** scheme ("http"/"ftp"/...) */ + char *scheme; + /** combined [user[:password]\@]host[:port] */ + char *hostinfo; + /** user name, as in http://user:passwd\@host:port/ */ + char *user; + /** password, as in http://user:passwd\@host:port/ */ + char *password; + /** hostname from URI (or from Host: header) */ + char *hostname; + /** port string (integer representation is in "port") */ + char *port_str; + /** the request path (or NULL if only scheme://host was given) */ + char *path; + /** Everything after a '?' in the path, if present */ + char *query; + /** Trailing "#fragment" string, if present */ + char *fragment; + + /** structure returned from gethostbyname() */ + struct hostent *hostent; + + /** The port number, numeric, valid only if port_str != NULL */ + apr_port_t port; + + /** has the structure been initialized */ + unsigned is_initialized:1; + + /** has the DNS been looked up yet */ + unsigned dns_looked_up:1; + /** has the dns been resolved yet */ + unsigned dns_resolved:1; +}; + +/* apr_uri.c */ +/** + * Return the default port for a given scheme. The schemes recognized are + * http, ftp, https, gopher, wais, nntp, snews, and prospero + * @param scheme_str The string that contains the current scheme + * @return The default port for this scheme + */ +APU_DECLARE(apr_port_t) apr_uri_port_of_scheme(const char *scheme_str); + +/** + * Unparse a apr_uri_t structure to an URI string. Optionally + * suppress the password for security reasons. + * @param p The pool to allocate out of + * @param uptr All of the parts of the uri + * @param flags How to unparse the uri. One of: + *
+ *    APR_URI_UNP_OMITSITEPART        Suppress "scheme://user\@site:port" 
+ *    APR_URI_UNP_OMITUSER            Just omit user 
+ *    APR_URI_UNP_OMITPASSWORD        Just omit password 
+ *    APR_URI_UNP_OMITUSERINFO        Omit "user:password\@" part
+ *    APR_URI_UNP_REVEALPASSWORD      Show plain text password (default: show XXXXXXXX)
+ *    APR_URI_UNP_OMITPATHINFO        Show "scheme://user\@site:port" only 
+ *    APR_URI_UNP_OMITQUERY           Omit "?queryarg" or "#fragment" 
+ * 
+ * @return The uri as a string + */ +APU_DECLARE(char *) apr_uri_unparse(apr_pool_t *p, + const apr_uri_t *uptr, + unsigned flags); + +/** + * Parse a given URI, fill in all supplied fields of a apr_uri_t + * structure. This eliminates the necessity of extracting host, port, + * path, query info repeatedly in the modules. + * @param p The pool to allocate out of + * @param uri The uri to parse + * @param uptr The apr_uri_t to fill out + * @return APR_SUCCESS for success or error code + */ +APU_DECLARE(apr_status_t) apr_uri_parse(apr_pool_t *p, const char *uri, + apr_uri_t *uptr); + +/** + * Special case for CONNECT parsing: it comes with the hostinfo part only + * @param p The pool to allocate out of + * @param hostinfo The hostinfo string to parse + * @param uptr The apr_uri_t to fill out + * @return APR_SUCCESS for success or error code + */ +APU_DECLARE(apr_status_t) apr_uri_parse_hostinfo(apr_pool_t *p, + const char *hostinfo, + apr_uri_t *uptr); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_URI_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_user.h b/c/dependencies/windows/apr/x64/include/apr_user.h new file mode 100644 index 00000000..0e0a3ac5 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_user.h @@ -0,0 +1,158 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_USER_H +#define APR_USER_H + +/** + * @file apr_user.h + * @brief APR User ID Services + */ + +#include "apr.h" +#include "apr_errno.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_user User and Group ID Services + * @ingroup APR + * @{ + */ + +/** + * Structure for determining user ownership. + */ +#ifdef WIN32 +typedef PSID apr_uid_t; +#else +typedef uid_t apr_uid_t; +#endif + +/** + * Structure for determining group ownership. + */ +#ifdef WIN32 +typedef PSID apr_gid_t; +#else +typedef gid_t apr_gid_t; +#endif + +#if APR_HAS_USER + +/** + * Get the userid (and groupid) of the calling process + * @param userid Returns the user id + * @param groupid Returns the user's group id + * @param p The pool from which to allocate working space + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_uid_current(apr_uid_t *userid, + apr_gid_t *groupid, + apr_pool_t *p); + +/** + * Get the user name for a specified userid + * @param username Pointer to new string containing user name (on output) + * @param userid The userid + * @param p The pool from which to allocate the string + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_uid_name_get(char **username, apr_uid_t userid, + apr_pool_t *p); + +/** + * Get the userid (and groupid) for the specified username + * @param userid Returns the user id + * @param groupid Returns the user's group id + * @param username The username to look up + * @param p The pool from which to allocate working space + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_uid_get(apr_uid_t *userid, apr_gid_t *groupid, + const char *username, apr_pool_t *p); + +/** + * Get the home directory for the named user + * @param dirname Pointer to new string containing directory name (on output) + * @param username The named user + * @param p The pool from which to allocate the string + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_uid_homepath_get(char **dirname, + const char *username, + apr_pool_t *p); + +/** + * Compare two user identifiers for equality. + * @param left One uid to test + * @param right Another uid to test + * @return APR_SUCCESS if the apr_uid_t structures identify the same user, + * APR_EMISMATCH if not, APR_BADARG if an apr_uid_t is invalid. + * @remark This function is available only if APR_HAS_USER is defined. + */ +#if defined(WIN32) +APR_DECLARE(apr_status_t) apr_uid_compare(apr_uid_t left, apr_uid_t right); +#else +#define apr_uid_compare(left,right) (((left) == (right)) ? APR_SUCCESS : APR_EMISMATCH) +#endif + +/** + * Get the group name for a specified groupid + * @param groupname Pointer to new string containing group name (on output) + * @param groupid The groupid + * @param p The pool from which to allocate the string + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_gid_name_get(char **groupname, + apr_gid_t groupid, apr_pool_t *p); + +/** + * Get the groupid for a specified group name + * @param groupid Pointer to the group id (on output) + * @param groupname The group name to look up + * @param p The pool from which to allocate the string + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_gid_get(apr_gid_t *groupid, + const char *groupname, apr_pool_t *p); + +/** + * Compare two group identifiers for equality. + * @param left One gid to test + * @param right Another gid to test + * @return APR_SUCCESS if the apr_gid_t structures identify the same group, + * APR_EMISMATCH if not, APR_BADARG if an apr_gid_t is invalid. + * @remark This function is available only if APR_HAS_USER is defined. + */ +#if defined(WIN32) +APR_DECLARE(apr_status_t) apr_gid_compare(apr_gid_t left, apr_gid_t right); +#else +#define apr_gid_compare(left,right) (((left) == (right)) ? APR_SUCCESS : APR_EMISMATCH) +#endif + +#endif /* ! APR_HAS_USER */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_USER_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_uuid.h b/c/dependencies/windows/apr/x64/include/apr_uuid.h new file mode 100644 index 00000000..5312a9f6 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_uuid.h @@ -0,0 +1,76 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_uuid.h + * @brief APR UUID library + */ +#ifndef APR_UUID_H +#define APR_UUID_H + +#include "apu.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_UUID UUID Handling + * @ingroup APR + * @{ + */ + +/** + * we represent a UUID as a block of 16 bytes. + */ + +typedef struct { + unsigned char data[16]; /**< the actual UUID */ +} apr_uuid_t; + +/** UUIDs are formatted as: 00112233-4455-6677-8899-AABBCCDDEEFF */ +#define APR_UUID_FORMATTED_LENGTH 36 + + +/** + * Generate and return a (new) UUID + * @param uuid The resulting UUID + */ +APU_DECLARE(void) apr_uuid_get(apr_uuid_t *uuid); + +/** + * Format a UUID into a string, following the standard format + * @param buffer The buffer to place the formatted UUID string into. It must + * be at least APR_UUID_FORMATTED_LENGTH + 1 bytes long to hold + * the formatted UUID and a null terminator + * @param uuid The UUID to format + */ +APU_DECLARE(void) apr_uuid_format(char *buffer, const apr_uuid_t *uuid); + +/** + * Parse a standard-format string into a UUID + * @param uuid The resulting UUID + * @param uuid_str The formatted UUID + */ +APU_DECLARE(apr_status_t) apr_uuid_parse(apr_uuid_t *uuid, const char *uuid_str); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_UUID_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_version.h b/c/dependencies/windows/apr/x64/include/apr_version.h new file mode 100644 index 00000000..e96de383 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_version.h @@ -0,0 +1,164 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_VERSION_H +#define APR_VERSION_H + +/** + * @file apr_version.h + * @brief APR Versioning Interface + * + * APR's Version + * + * There are several different mechanisms for accessing the version. There + * is a string form, and a set of numbers; in addition, there are constants + * which can be compiled into your application, and you can query the library + * being used for its actual version. + * + * Note that it is possible for an application to detect that it has been + * compiled against a different version of APR by use of the compile-time + * constants and the use of the run-time query function. + * + * APR version numbering follows the guidelines specified in: + * + * http://apr.apache.org/versioning.html + */ + + +#define APR_COPYRIGHT "Copyright (c) 2000-2019 The Apache Software " \ + "Foundation or its licensors, as applicable." + +/* The numeric compile-time version constants. These constants are the + * authoritative version numbers for APR. + */ + +/** major version + * Major API changes that could cause compatibility problems for older + * programs such as structure size changes. No binary compatibility is + * possible across a change in the major version. + */ +#define APR_MAJOR_VERSION 1 + +/** minor version + * Minor API changes that do not cause binary compatibility problems. + * Reset to 0 when upgrading APR_MAJOR_VERSION + */ +#define APR_MINOR_VERSION 7 + +/** patch level + * The Patch Level never includes API changes, simply bug fixes. + * Reset to 0 when upgrading APR_MINOR_VERSION + */ +#define APR_PATCH_VERSION 0 + +/** + * The symbol APR_IS_DEV_VERSION is only defined for internal, + * "development" copies of APR. It is undefined for released versions + * of APR. + */ +/* #undef APR_IS_DEV_VERSION */ + +/** + * Check at compile time if the APR version is at least a certain + * level. + * @param major The major version component of the version checked + * for (e.g., the "1" of "1.3.0"). + * @param minor The minor version component of the version checked + * for (e.g., the "3" of "1.3.0"). + * @param patch The patch level component of the version checked + * for (e.g., the "0" of "1.3.0"). + * @remark This macro is available with APR versions starting with + * 1.3.0. + */ +#define APR_VERSION_AT_LEAST(major,minor,patch) \ +(((major) < APR_MAJOR_VERSION) \ + || ((major) == APR_MAJOR_VERSION && (minor) < APR_MINOR_VERSION) \ + || ((major) == APR_MAJOR_VERSION && (minor) == APR_MINOR_VERSION && (patch) <= APR_PATCH_VERSION)) + +#if defined(APR_IS_DEV_VERSION) || defined(DOXYGEN) +/** Internal: string form of the "is dev" flag */ +#ifndef APR_IS_DEV_STRING +#define APR_IS_DEV_STRING "-dev" +#endif +#else +#define APR_IS_DEV_STRING "" +#endif + +/* APR_STRINGIFY is defined here, and also in apr_general.h, so wrap it */ +#ifndef APR_STRINGIFY +/** Properly quote a value as a string in the C preprocessor */ +#define APR_STRINGIFY(n) APR_STRINGIFY_HELPER(n) +/** Helper macro for APR_STRINGIFY */ +#define APR_STRINGIFY_HELPER(n) #n +#endif + +/** The formatted string of APR's version */ +#define APR_VERSION_STRING \ + APR_STRINGIFY(APR_MAJOR_VERSION) "." \ + APR_STRINGIFY(APR_MINOR_VERSION) "." \ + APR_STRINGIFY(APR_PATCH_VERSION) \ + APR_IS_DEV_STRING + +/** An alternative formatted string of APR's version */ +/* macro for Win32 .rc files using numeric csv representation */ +#define APR_VERSION_STRING_CSV APR_MAJOR_VERSION ##, \ + ##APR_MINOR_VERSION ##, \ + ##APR_PATCH_VERSION + + +#ifndef APR_VERSION_ONLY + +/* The C language API to access the version at run time, + * as opposed to compile time. APR_VERSION_ONLY may be defined + * externally when preprocessing apr_version.h to obtain strictly + * the C Preprocessor macro declarations. + */ + +#include "apr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The numeric version information is broken out into fields within this + * structure. + */ +typedef struct { + int major; /**< major number */ + int minor; /**< minor number */ + int patch; /**< patch number */ + int is_dev; /**< is development (1 or 0) */ +} apr_version_t; + +/** + * Return APR's version information information in a numeric form. + * + * @param pvsn Pointer to a version structure for returning the version + * information. + */ +APR_DECLARE(void) apr_version(apr_version_t *pvsn); + +/** Return APR's version information as a string. */ +APR_DECLARE(const char *) apr_version_string(void); + +#ifdef __cplusplus +} +#endif + +#endif /* ndef APR_VERSION_ONLY */ + +#endif /* ndef APR_VERSION_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_want.h b/c/dependencies/windows/apr/x64/include/apr_want.h new file mode 100644 index 00000000..2863b001 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_want.h @@ -0,0 +1,124 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr.h" /* configuration data */ +/** + * @file apr_want.h + * @brief APR Standard Headers Support + * + *
+ * Features:
+ *
+ *   APR_WANT_STRFUNC:  strcmp, strcat, strcpy, etc
+ *   APR_WANT_MEMFUNC:  memcmp, memcpy, etc
+ *   APR_WANT_STDIO:     and related bits
+ *   APR_WANT_IOVEC:    struct iovec
+ *   APR_WANT_BYTEFUNC: htons, htonl, ntohl, ntohs
+ *
+ * Typical usage:
+ *
+ *   \#define APR_WANT_STRFUNC
+ *   \#define APR_WANT_MEMFUNC
+ *   \#include "apr_want.h"
+ *
+ * The appropriate headers will be included.
+ *
+ * Note: it is safe to use this in a header (it won't interfere with other
+ *       headers' or source files' use of apr_want.h)
+ * 
+ */ + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_STRFUNC + +#if APR_HAVE_STRING_H +#include +#endif +#if APR_HAVE_STRINGS_H +#include +#endif + +#undef APR_WANT_STRFUNC +#endif + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_MEMFUNC + +#if APR_HAVE_STRING_H +#include +#endif + +#undef APR_WANT_MEMFUNC +#endif + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_STDIO + +#if APR_HAVE_STDIO_H +#include +#endif + +#undef APR_WANT_STDIO +#endif + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_IOVEC + +#if APR_HAVE_IOVEC + +#if APR_HAVE_SYS_UIO_H +#include +#endif + +#else + +#ifndef APR_IOVEC_DEFINED +#define APR_IOVEC_DEFINED +struct iovec +{ + void *iov_base; + size_t iov_len; +}; +#endif /* !APR_IOVEC_DEFINED */ + +#endif /* APR_HAVE_IOVEC */ + +#undef APR_WANT_IOVEC +#endif + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_BYTEFUNC + +/* Single Unix says they are in arpa/inet.h. Linux has them in + * netinet/in.h. FreeBSD has them in arpa/inet.h but requires that + * netinet/in.h be included first. + */ +#if APR_HAVE_NETINET_IN_H +#include +#endif +#if APR_HAVE_ARPA_INET_H +#include +#endif + +#undef APR_WANT_BYTEFUNC +#endif + +/* --------------------------------------------------------------------- */ diff --git a/c/dependencies/windows/apr/x64/include/apr_xlate.h b/c/dependencies/windows/apr/x64/include/apr_xlate.h new file mode 100644 index 00000000..32636685 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_xlate.h @@ -0,0 +1,163 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_XLATE_H +#define APR_XLATE_H + +#include "apu.h" +#include "apr_pools.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @file apr_xlate.h + * @brief APR I18N translation library + */ + +/** + * @defgroup APR_XLATE I18N translation library + * @ingroup APR + * @{ + */ +/** Opaque translation buffer */ +typedef struct apr_xlate_t apr_xlate_t; + +/** + * Set up for converting text from one charset to another. + * @param convset The handle to be filled in by this function + * @param topage The name of the target charset + * @param frompage The name of the source charset + * @param pool The pool to use + * @remark + * Specify APR_DEFAULT_CHARSET for one of the charset + * names to indicate the charset of the source code at + * compile time. This is useful if there are literal + * strings in the source code which must be translated + * according to the charset of the source code. + * APR_DEFAULT_CHARSET is not useful if the source code + * of the caller was not encoded in the same charset as + * APR at compile time. + * + * @remark + * Specify APR_LOCALE_CHARSET for one of the charset + * names to indicate the charset of the current locale. + * + * @remark + * Return APR_EINVAL if unable to procure a convset, or APR_ENOTIMPL + * if charset transcoding is not available in this instance of + * apr-util at all (i.e., APR_HAS_XLATE is undefined). + */ +APU_DECLARE(apr_status_t) apr_xlate_open(apr_xlate_t **convset, + const char *topage, + const char *frompage, + apr_pool_t *pool); + +/** + * This is to indicate the charset of the sourcecode at compile time + * names to indicate the charset of the source code at + * compile time. This is useful if there are literal + * strings in the source code which must be translated + * according to the charset of the source code. + */ +#define APR_DEFAULT_CHARSET (const char *)0 +/** + * To indicate charset names of the current locale + */ +#define APR_LOCALE_CHARSET (const char *)1 + +/** + * Find out whether or not the specified conversion is single-byte-only. + * @param convset The handle allocated by apr_xlate_open, specifying the + * parameters of conversion + * @param onoff Output: whether or not the conversion is single-byte-only + * @remark + * Return APR_ENOTIMPL if charset transcoding is not available + * in this instance of apr-util (i.e., APR_HAS_XLATE is undefined). + */ +APU_DECLARE(apr_status_t) apr_xlate_sb_get(apr_xlate_t *convset, int *onoff); + +/** + * Convert a buffer of text from one codepage to another. + * @param convset The handle allocated by apr_xlate_open, specifying + * the parameters of conversion + * @param inbuf The address of the source buffer + * @param inbytes_left Input: the amount of input data to be translated + * Output: the amount of input data not yet translated + * @param outbuf The address of the destination buffer + * @param outbytes_left Input: the size of the output buffer + * Output: the amount of the output buffer not yet used + * @remark + * Returns APR_ENOTIMPL if charset transcoding is not available + * in this instance of apr-util (i.e., APR_HAS_XLATE is undefined). + * Returns APR_INCOMPLETE if the input buffer ends in an incomplete + * multi-byte character. + * + * To correctly terminate the output buffer for some multi-byte + * character set encodings, a final call must be made to this function + * after the complete input string has been converted, passing + * the inbuf and inbytes_left parameters as NULL. (Note that this + * mode only works from version 1.1.0 onwards) + */ +APU_DECLARE(apr_status_t) apr_xlate_conv_buffer(apr_xlate_t *convset, + const char *inbuf, + apr_size_t *inbytes_left, + char *outbuf, + apr_size_t *outbytes_left); + +/* @see apr_file_io.h the comment in apr_file_io.h about this hack */ +#ifdef APR_NOT_DONE_YET +/** + * The purpose of apr_xlate_conv_char is to translate one character + * at a time. This needs to be written carefully so that it works + * with double-byte character sets. + * @param convset The handle allocated by apr_xlate_open, specifying the + * parameters of conversion + * @param inchar The character to convert + * @param outchar The converted character + */ +APU_DECLARE(apr_status_t) apr_xlate_conv_char(apr_xlate_t *convset, + char inchar, char outchar); +#endif + +/** + * Convert a single-byte character from one charset to another. + * @param convset The handle allocated by apr_xlate_open, specifying the + * parameters of conversion + * @param inchar The single-byte character to convert. + * @warning This only works when converting between single-byte character sets. + * -1 will be returned if the conversion can't be performed. + */ +APU_DECLARE(apr_int32_t) apr_xlate_conv_byte(apr_xlate_t *convset, + unsigned char inchar); + +/** + * Close a codepage translation handle. + * @param convset The codepage translation handle to close + * @remark + * Return APR_ENOTIMPL if charset transcoding is not available + * in this instance of apr-util (i.e., APR_HAS_XLATE is undefined). + */ +APU_DECLARE(apr_status_t) apr_xlate_close(apr_xlate_t *convset); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_XLATE_H */ diff --git a/c/dependencies/windows/apr/x64/include/apr_xml.h b/c/dependencies/windows/apr/x64/include/apr_xml.h new file mode 100644 index 00000000..87a696cc --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apr_xml.h @@ -0,0 +1,358 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file apr_xml.h + * @brief APR-UTIL XML Library + */ +#ifndef APR_XML_H +#define APR_XML_H + +/** + * @defgroup APR_Util_XML XML + * @ingroup APR_Util + * @{ + */ +#include "apr_pools.h" +#include "apr_tables.h" +#include "apr_file_io.h" + +#include "apu.h" +#if APR_CHARSET_EBCDIC +#include "apr_xlate.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @package Apache XML library + */ + +/* -------------------------------------------------------------------- */ + +/* ### these will need to move at some point to a more logical spot */ + +/** @see apr_text */ +typedef struct apr_text apr_text; + +/** Structure to keep a linked list of pieces of text */ +struct apr_text { + /** The current piece of text */ + const char *text; + /** a pointer to the next piece of text */ + struct apr_text *next; +}; + +/** @see apr_text_header */ +typedef struct apr_text_header apr_text_header; + +/** A list of pieces of text */ +struct apr_text_header { + /** The first piece of text in the list */ + apr_text *first; + /** The last piece of text in the list */ + apr_text *last; +}; + +/** + * Append a piece of text to the end of a list + * @param p The pool to allocate out of + * @param hdr The text header to append to + * @param text The new text to append + */ +APU_DECLARE(void) apr_text_append(apr_pool_t *p, apr_text_header *hdr, + const char *text); + + +/* -------------------------------------------------------------------- +** +** XML PARSING +*/ + +/* +** Qualified namespace values +** +** APR_XML_NS_DAV_ID +** We always insert the "DAV:" namespace URI at the head of the +** namespace array. This means that it will always be at ID==0, +** making it much easier to test for. +** +** APR_XML_NS_NONE +** This special ID is used for two situations: +** +** 1) The namespace prefix begins with "xml" (and we do not know +** what it means). Namespace prefixes with "xml" (any case) as +** their first three characters are reserved by the XML Namespaces +** specification for future use. mod_dav will pass these through +** unchanged. When this identifier is used, the prefix is LEFT in +** the element/attribute name. Downstream processing should not +** prepend another prefix. +** +** 2) The element/attribute does not have a namespace. +** +** a) No prefix was used, and a default namespace has not been +** defined. +** b) No prefix was used, and the default namespace was specified +** to mean "no namespace". This is done with a namespace +** declaration of: xmlns="" +** (this declaration is typically used to override a previous +** specification for the default namespace) +** +** In these cases, we need to record that the elem/attr has no +** namespace so that we will not attempt to prepend a prefix. +** All namespaces that are used will have a prefix assigned to +** them -- mod_dav will never set or use the default namespace +** when generating XML. This means that "no prefix" will always +** mean "no namespace". +** +** In both cases, the XML generation will avoid prepending a prefix. +** For the first case, this means the original prefix/name will be +** inserted into the output stream. For the latter case, it means +** the name will have no prefix, and since we never define a default +** namespace, this means it will have no namespace. +** +** Note: currently, mod_dav understands the "xmlns" prefix and the +** "xml:lang" attribute. These are handled specially (they aren't +** left within the XML tree), so the APR_XML_NS_NONE value won't ever +** really apply to these values. +*/ +#define APR_XML_NS_DAV_ID 0 /**< namespace ID for "DAV:" */ +#define APR_XML_NS_NONE -10 /**< no namespace for this elem/attr */ + +#define APR_XML_NS_ERROR_BASE -100 /**< used only during processing */ +/** Is this namespace an error? */ +#define APR_XML_NS_IS_ERROR(e) ((e) <= APR_XML_NS_ERROR_BASE) + +/** @see apr_xml_attr */ +typedef struct apr_xml_attr apr_xml_attr; +/** @see apr_xml_elem */ +typedef struct apr_xml_elem apr_xml_elem; +/** @see apr_xml_doc */ +typedef struct apr_xml_doc apr_xml_doc; + +/** apr_xml_attr: holds a parsed XML attribute */ +struct apr_xml_attr { + /** attribute name */ + const char *name; + /** index into namespace array */ + int ns; + + /** attribute value */ + const char *value; + + /** next attribute */ + struct apr_xml_attr *next; +}; + +/** apr_xml_elem: holds a parsed XML element */ +struct apr_xml_elem { + /** element name */ + const char *name; + /** index into namespace array */ + int ns; + /** xml:lang for attrs/contents */ + const char *lang; + + /** cdata right after start tag */ + apr_text_header first_cdata; + /** cdata after MY end tag */ + apr_text_header following_cdata; + + /** parent element */ + struct apr_xml_elem *parent; + /** next (sibling) element */ + struct apr_xml_elem *next; + /** first child element */ + struct apr_xml_elem *first_child; + /** first attribute */ + struct apr_xml_attr *attr; + + /* used only during parsing */ + /** last child element */ + struct apr_xml_elem *last_child; + /** namespaces scoped by this elem */ + struct apr_xml_ns_scope *ns_scope; + + /* used by modules during request processing */ + /** Place for modules to store private data */ + void *priv; +}; + +/** Is this XML element empty? */ +#define APR_XML_ELEM_IS_EMPTY(e) ((e)->first_child == NULL && \ + (e)->first_cdata.first == NULL) + +/** apr_xml_doc: holds a parsed XML document */ +struct apr_xml_doc { + /** root element */ + apr_xml_elem *root; + /** array of namespaces used */ + apr_array_header_t *namespaces; +}; + +/** Opaque XML parser structure */ +typedef struct apr_xml_parser apr_xml_parser; + +/** + * Create an XML parser + * @param pool The pool for allocating the parser and the parse results. + * @return The new parser. + */ +APU_DECLARE(apr_xml_parser *) apr_xml_parser_create(apr_pool_t *pool); + +/** + * Parse a File, producing a xml_doc + * @param p The pool for allocating the parse results. + * @param parser A pointer to *parser (needed so calling function can get + * errors), will be set to NULL on successful completion. + * @param ppdoc A pointer to *apr_xml_doc (which has the parsed results in it) + * @param xmlfd A file to read from. + * @param buffer_length Buffer length which would be suitable + * @return Any errors found during parsing. + */ +APU_DECLARE(apr_status_t) apr_xml_parse_file(apr_pool_t *p, + apr_xml_parser **parser, + apr_xml_doc **ppdoc, + apr_file_t *xmlfd, + apr_size_t buffer_length); + + +/** + * Feed input into the parser + * @param parser The XML parser for parsing this data. + * @param data The data to parse. + * @param len The length of the data. + * @return Any errors found during parsing. + * @remark Use apr_xml_parser_geterror() to get more error information. + */ +APU_DECLARE(apr_status_t) apr_xml_parser_feed(apr_xml_parser *parser, + const char *data, + apr_size_t len); + +/** + * Terminate the parsing and return the result + * @param parser The XML parser for parsing this data. + * @param pdoc The resulting parse information. May be NULL to simply + * terminate the parsing without fetching the info. + * @return Any errors found during the final stage of parsing. + * @remark Use apr_xml_parser_geterror() to get more error information. + */ +APU_DECLARE(apr_status_t) apr_xml_parser_done(apr_xml_parser *parser, + apr_xml_doc **pdoc); + +/** + * Fetch additional error information from the parser. + * @param parser The XML parser to query for errors. + * @param errbuf A buffer for storing error text. + * @param errbufsize The length of the error text buffer. + * @return The error buffer + */ +APU_DECLARE(char *) apr_xml_parser_geterror(apr_xml_parser *parser, + char *errbuf, + apr_size_t errbufsize); + + +/** + * Converts an XML element tree to flat text + * @param p The pool to allocate out of + * @param elem The XML element to convert + * @param style How to covert the XML. One of: + *
+ *     APR_XML_X2T_FULL                start tag, contents, end tag 
+ *     APR_XML_X2T_INNER               contents only 
+ *     APR_XML_X2T_LANG_INNER          xml:lang + inner contents 
+ *     APR_XML_X2T_FULL_NS_LANG        FULL + ns defns + xml:lang 
+ *     APR_XML_X2T_PARSED              original prefixes
+ * 
+ * @param namespaces The namespace of the current XML element + * @param ns_map Namespace mapping + * @param pbuf Buffer to put the converted text into + * @param psize Size of the converted text + */ +APU_DECLARE(void) apr_xml_to_text(apr_pool_t *p, const apr_xml_elem *elem, + int style, apr_array_header_t *namespaces, + int *ns_map, const char **pbuf, + apr_size_t *psize); + +/* style argument values: */ +#define APR_XML_X2T_FULL 0 /**< start tag, contents, end tag */ +#define APR_XML_X2T_INNER 1 /**< contents only */ +#define APR_XML_X2T_LANG_INNER 2 /**< xml:lang + inner contents */ +#define APR_XML_X2T_FULL_NS_LANG 3 /**< FULL + ns defns + xml:lang */ +#define APR_XML_X2T_PARSED 4 /**< original prefixes */ + +/** + * empty XML element + * @param p The pool to allocate out of + * @param elem The XML element to empty + * @return the string that was stored in the XML element + */ +APU_DECLARE(const char *) apr_xml_empty_elem(apr_pool_t *p, + const apr_xml_elem *elem); + +/** + * quote an XML string + * Replace '\<', '\>', and '\&' with '\<', '\>', and '\&'. + * @param p The pool to allocate out of + * @param s The string to quote + * @param quotes If quotes is true, then replace '"' with '\"'. + * @return The quoted string + * @note If the string does not contain special characters, it is not + * duplicated into the pool and the original string is returned. + */ +APU_DECLARE(const char *) apr_xml_quote_string(apr_pool_t *p, const char *s, + int quotes); + +/** + * Quote an XML element + * @param p The pool to allocate out of + * @param elem The element to quote + */ +APU_DECLARE(void) apr_xml_quote_elem(apr_pool_t *p, apr_xml_elem *elem); + +/* manage an array of unique URIs: apr_xml_insert_uri() and APR_XML_URI_ITEM() */ + +/** + * return the URI's (existing) index, or insert it and return a new index + * @param uri_array array to insert into + * @param uri The uri to insert + * @return int The uri's index + */ +APU_DECLARE(int) apr_xml_insert_uri(apr_array_header_t *uri_array, + const char *uri); + +/** Get the URI item for this XML element */ +#define APR_XML_GET_URI_ITEM(ary, i) (((const char * const *)(ary)->elts)[i]) + +#if APR_CHARSET_EBCDIC +/** + * Convert parsed tree in EBCDIC + * @param p The pool to allocate out of + * @param pdoc The apr_xml_doc to convert. + * @param xlate The translation handle to use. + * @return Any errors found during conversion. + */ +APU_DECLARE(apr_status_t) apr_xml_parser_convert_doc(apr_pool_t *p, + apr_xml_doc *pdoc, + apr_xlate_t *convset); +#endif + +#ifdef __cplusplus +} +#endif +/** @} */ +#endif /* APR_XML_H */ diff --git a/c/dependencies/windows/apr/x64/include/apu.h b/c/dependencies/windows/apr/x64/include/apu.h new file mode 100644 index 00000000..21fbedff --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apu.h @@ -0,0 +1,146 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apu.h is duplicated from apu.hw at build time -- do not edit apu.h + */ +/* @file apu.h + * @brief APR-Utility main file + */ +/** + * @defgroup APR_Util APR Utility Functions + * @{ + */ + + +#ifndef APU_H +#define APU_H + +/** + * APU_DECLARE_EXPORT is defined when building the APR-UTIL dynamic library, + * so that all public symbols are exported. + * + * APU_DECLARE_STATIC is defined when including the APR-UTIL public headers, + * to provide static linkage when the dynamic library may be unavailable. + * + * APU_DECLARE_STATIC and APU_DECLARE_EXPORT are left undefined when + * including the APR-UTIL public headers, to import and link the symbols from + * the dynamic APR-UTIL library and assure appropriate indirection and calling + * conventions at compile time. + */ + +/* Make sure we have our platform identifier macro defined we ask for later. + */ +#if defined(_WIN32) && !defined(WIN32) +#define WIN32 1 +#endif + +#if defined(DOXYGEN) || !defined(WIN32) +/** + * The public APR-UTIL functions are declared with APU_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APU_DECLARE_NONSTD(). + * + * @fn APU_DECLARE(rettype) apr_func(args); + */ +#define APU_DECLARE(type) type +/** + * The public APR-UTIL functions using variable arguments are declared with + * APU_DECLARE_NONSTD(), as they must use the C language calling convention. + * + * @fn APU_DECLARE_NONSTD(rettype) apr_func(args, ...); + */ +#define APU_DECLARE_NONSTD(type) type +/** + * The public APR-UTIL variables are declared with APU_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * + * @fn APU_DECLARE_DATA type apr_variable; + * @note extern APU_DECLARE_DATA type apr_variable; syntax is required for + * declarations within headers to properly import the variable. + */ +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_STATIC) +#define APU_DECLARE(type) type __stdcall +#define APU_DECLARE_NONSTD(type) type __cdecl +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_EXPORT) +#define APU_DECLARE(type) __declspec(dllexport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllexport) +#else +#define APU_DECLARE(type) __declspec(dllimport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllimport) +#endif + +#if !defined(WIN32) || defined(APU_MODULE_DECLARE_STATIC) +/** + * Declare a dso module's exported module structure as APU_MODULE_DECLARE_DATA. + * + * Unless APU_MODULE_DECLARE_STATIC is defined at compile time, symbols + * declared with APU_MODULE_DECLARE_DATA are always exported. + * @code + * module APU_MODULE_DECLARE_DATA mod_tag + * @endcode + */ +#define APU_MODULE_DECLARE_DATA +#else +#define APU_MODULE_DECLARE_DATA __declspec(dllexport) +#endif + +/* + * we always have SDBM (it's in our codebase) + */ +#define APU_HAVE_SDBM 1 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_GDBM 0 +#define APU_HAVE_NDBM 0 +#define APU_HAVE_DB 0 + +#if APU_HAVE_DB +#define APU_HAVE_DB_VERSION 0 +#endif +#endif + +/* + * we always enable dynamic driver loads within apr_dbd + * Win32 always has odbc (it's always installed) + */ +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_PGSQL 0 +#define APU_HAVE_MYSQL 0 +#define APU_HAVE_SQLITE3 0 +#define APU_HAVE_SQLITE2 0 +#define APU_HAVE_ORACLE 0 +#define APU_HAVE_ODBC 1 +#endif + +#define APU_HAVE_CRYPTO 0 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_OPENSSL 0 +#define APU_HAVE_NSS 0 +#define APU_HAVE_COMMONCRYPTO 0 +#endif + +#define APU_HAVE_APR_ICONV 1 +#define APU_HAVE_ICONV 0 +#define APR_HAS_XLATE (APU_HAVE_APR_ICONV || APU_HAVE_ICONV) + +#endif /* APU_H */ +/** @} */ diff --git a/c/dependencies/windows/apr/x64/include/apu.h.in b/c/dependencies/windows/apr/x64/include/apu.h.in new file mode 100644 index 00000000..0781a6a0 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apu.h.in @@ -0,0 +1,128 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apu.h is generated from apu.h.in by configure -- do not edit apu.h + */ +/* @file apu.h + * @brief APR-Utility main file + */ +/** + * @defgroup APR_Util APR Utility Functions + * @{ + */ + + +#ifndef APU_H +#define APU_H + +/** + * APU_DECLARE_EXPORT is defined when building the APR-UTIL dynamic library, + * so that all public symbols are exported. + * + * APU_DECLARE_STATIC is defined when including the APR-UTIL public headers, + * to provide static linkage when the dynamic library may be unavailable. + * + * APU_DECLARE_STATIC and APU_DECLARE_EXPORT are left undefined when + * including the APR-UTIL public headers, to import and link the symbols from + * the dynamic APR-UTIL library and assure appropriate indirection and calling + * conventions at compile time. + */ + +#if defined(DOXYGEN) || !defined(WIN32) +/** + * The public APR-UTIL functions are declared with APU_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APU_DECLARE_NONSTD(). + * + * @fn APU_DECLARE(rettype) apr_func(args); + */ +#define APU_DECLARE(type) type +/** + * The public APR-UTIL functions using variable arguments are declared with + * APU_DECLARE_NONSTD(), as they must use the C language calling convention. + * + * @fn APU_DECLARE_NONSTD(rettype) apr_func(args, ...); + */ +#define APU_DECLARE_NONSTD(type) type +/** + * The public APR-UTIL variables are declared with APU_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * + * @fn APU_DECLARE_DATA type apr_variable; + * @note APU_DECLARE_DATA extern type apr_variable; syntax is required for + * declarations within headers to properly import the variable. + */ +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_STATIC) +#define APU_DECLARE(type) type __stdcall +#define APU_DECLARE_NONSTD(type) type __cdecl +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_EXPORT) +#define APU_DECLARE(type) __declspec(dllexport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllexport) +#else +#define APU_DECLARE(type) __declspec(dllimport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllimport) +#endif + +#if !defined(WIN32) || defined(APU_MODULE_DECLARE_STATIC) +/** + * Declare a dso module's exported module structure as APU_MODULE_DECLARE_DATA. + * + * Unless APU_MODULE_DECLARE_STATIC is defined at compile time, symbols + * declared with APU_MODULE_DECLARE_DATA are always exported. + * @code + * module APU_MODULE_DECLARE_DATA mod_tag + * @endcode + */ +#define APU_MODULE_DECLARE_DATA +#else +#define APU_MODULE_DECLARE_DATA __declspec(dllexport) +#endif + +/* + * we always have SDBM (it's in our codebase) + */ +#define APU_HAVE_SDBM @apu_have_sdbm@ +#define APU_HAVE_GDBM @apu_have_gdbm@ +#define APU_HAVE_NDBM @apu_have_ndbm@ +#define APU_HAVE_DB @apu_have_db@ + +#if APU_HAVE_DB +#define APU_HAVE_DB_VERSION @apu_db_version@ +#endif + +#define APU_HAVE_PGSQL @apu_have_pgsql@ +#define APU_HAVE_MYSQL @apu_have_mysql@ +#define APU_HAVE_SQLITE3 @apu_have_sqlite3@ +#define APU_HAVE_SQLITE2 @apu_have_sqlite2@ +#define APU_HAVE_ORACLE @apu_have_oracle@ +#define APU_HAVE_ODBC @apu_have_odbc@ + +#define APU_HAVE_CRYPTO @apu_have_crypto@ +#define APU_HAVE_OPENSSL @apu_have_openssl@ +#define APU_HAVE_NSS @apu_have_nss@ +#define APU_HAVE_COMMONCRYPTO @apu_have_commoncrypto@ + +#define APU_HAVE_APR_ICONV @have_apr_iconv@ +#define APU_HAVE_ICONV @have_iconv@ +#define APR_HAS_XLATE (APU_HAVE_APR_ICONV || APU_HAVE_ICONV) + +#endif /* APU_H */ +/** @} */ diff --git a/c/dependencies/windows/apr/x64/include/apu.hnw b/c/dependencies/windows/apr/x64/include/apu.hnw new file mode 100644 index 00000000..12e73818 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apu.hnw @@ -0,0 +1,124 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Note: This is a NetWare specific version of apu.h. It is renamed to + * apu.h at the start of a NetWare build. + */ +/* @file apu.h + * @brief APR-Utility main file + */ + +#ifdef NETWARE +#ifndef APU_H +#define APU_H +/** + * @defgroup APR_Util APR Utility Functions + * @{ + */ + + +/** + * APU_DECLARE_EXPORT is defined when building the APR-UTIL dynamic library, + * so that all public symbols are exported. + * + * APU_DECLARE_STATIC is defined when including the APR-UTIL public headers, + * to provide static linkage when the dynamic library may be unavailable. + * + * APU_DECLARE_STATIC and APU_DECLARE_EXPORT are left undefined when + * including the APR-UTIL public headers, to import and link the symbols from + * the dynamic APR-UTIL library and assure appropriate indirection and calling + * conventions at compile time. + */ + +/** + * The public APR-UTIL functions are declared with APU_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APU_DECLARE_NONSTD(). + * + * @fn APU_DECLARE(rettype) apr_func(args); + */ +#define APU_DECLARE(type) type +/** + * The public APR-UTIL functions using variable arguments are declared with + * APU_DECLARE_NONSTD(), as they must use the C language calling convention. + * + * @fn APU_DECLARE_NONSTD(rettype) apr_func(args, ...); + */ +#define APU_DECLARE_NONSTD(type) type +/** + * The public APR-UTIL variables are declared with APU_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * + * @fn APU_DECLARE_DATA type apr_variable; + * @note APU_DECLARE_DATA extern type apr_variable; syntax is required for + * declarations within headers to properly import the variable. + */ +#define APU_DECLARE_DATA + +/** + * Declare a dso module's exported module structure as APU_MODULE_DECLARE_DATA. + * + * Unless APU_MODULE_DECLARE_STATIC is defined at compile time, symbols + * declared with APU_MODULE_DECLARE_DATA are always exported. + * @code + * module APU_MODULE_DECLARE_DATA mod_tag + * @endcode + */ +#define APU_MODULE_DECLARE_DATA + +/* + * we always have SDBM (it's in our codebase) + */ +#define APU_HAVE_SDBM 1 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_GDBM 0 +#define APU_HAVE_NDBM 0 +#define APU_HAVE_DB 0 + +#if APU_HAVE_DB +#define APU_HAVE_DB_VERSION 0 +#endif +#endif + +/* + * we always enable dynamic driver loads within apr_dbd + */ +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_PGSQL 0 +#define APU_HAVE_MYSQL 0 +#define APU_HAVE_SQLITE3 0 +#define APU_HAVE_SQLITE2 0 +#define APU_HAVE_ORACLE 0 +#define APU_HAVE_ODBC 0 +#endif + +#define APU_HAVE_CRYPTO 0 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_OPENSSL 0 +#define APU_HAVE_NSS 0 +#define APU_HAVE_COMMONCRYPTO 0 +#endif + +#define APU_HAVE_APR_ICONV 0 +#define APU_HAVE_ICONV 1 +#define APR_HAS_XLATE (APU_HAVE_APR_ICONV || APU_HAVE_ICONV) + +#endif /* APU_H */ +#endif /* NETWARE */ + diff --git a/c/dependencies/windows/apr/x64/include/apu.hw b/c/dependencies/windows/apr/x64/include/apu.hw new file mode 100644 index 00000000..a501d5d7 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apu.hw @@ -0,0 +1,146 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apu.h is duplicated from apu.hw at build time -- do not edit apu.h + */ +/* @file apu.h + * @brief APR-Utility main file + */ +/** + * @defgroup APR_Util APR Utility Functions + * @{ + */ + + +#ifndef APU_H +#define APU_H + +/** + * APU_DECLARE_EXPORT is defined when building the APR-UTIL dynamic library, + * so that all public symbols are exported. + * + * APU_DECLARE_STATIC is defined when including the APR-UTIL public headers, + * to provide static linkage when the dynamic library may be unavailable. + * + * APU_DECLARE_STATIC and APU_DECLARE_EXPORT are left undefined when + * including the APR-UTIL public headers, to import and link the symbols from + * the dynamic APR-UTIL library and assure appropriate indirection and calling + * conventions at compile time. + */ + +/* Make sure we have our platform identifier macro defined we ask for later. + */ +#if defined(_WIN32) && !defined(WIN32) +#define WIN32 1 +#endif + +#if defined(DOXYGEN) || !defined(WIN32) +/** + * The public APR-UTIL functions are declared with APU_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APU_DECLARE_NONSTD(). + * + * @fn APU_DECLARE(rettype) apr_func(args); + */ +#define APU_DECLARE(type) type +/** + * The public APR-UTIL functions using variable arguments are declared with + * APU_DECLARE_NONSTD(), as they must use the C language calling convention. + * + * @fn APU_DECLARE_NONSTD(rettype) apr_func(args, ...); + */ +#define APU_DECLARE_NONSTD(type) type +/** + * The public APR-UTIL variables are declared with APU_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * + * @fn APU_DECLARE_DATA type apr_variable; + * @note extern APU_DECLARE_DATA type apr_variable; syntax is required for + * declarations within headers to properly import the variable. + */ +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_STATIC) +#define APU_DECLARE(type) type __stdcall +#define APU_DECLARE_NONSTD(type) type __cdecl +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_EXPORT) +#define APU_DECLARE(type) __declspec(dllexport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllexport) +#else +#define APU_DECLARE(type) __declspec(dllimport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllimport) +#endif + +#if !defined(WIN32) || defined(APU_MODULE_DECLARE_STATIC) +/** + * Declare a dso module's exported module structure as APU_MODULE_DECLARE_DATA. + * + * Unless APU_MODULE_DECLARE_STATIC is defined at compile time, symbols + * declared with APU_MODULE_DECLARE_DATA are always exported. + * @code + * module APU_MODULE_DECLARE_DATA mod_tag + * @endcode + */ +#define APU_MODULE_DECLARE_DATA +#else +#define APU_MODULE_DECLARE_DATA __declspec(dllexport) +#endif + +/* + * we always have SDBM (it's in our codebase) + */ +#define APU_HAVE_SDBM 1 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_GDBM 0 +#define APU_HAVE_NDBM 0 +#define APU_HAVE_DB 0 + +#if APU_HAVE_DB +#define APU_HAVE_DB_VERSION 0 +#endif +#endif + +/* + * we always enable dynamic driver loads within apr_dbd + * Win32 always has odbc (it's always installed) + */ +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_PGSQL 0 +#define APU_HAVE_MYSQL 0 +#define APU_HAVE_SQLITE3 0 +#define APU_HAVE_SQLITE2 0 +#define APU_HAVE_ORACLE 0 +#define APU_HAVE_ODBC 1 +#endif + +#define APU_HAVE_CRYPTO 0 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_OPENSSL 0 +#define APU_HAVE_NSS 0 +#define APU_HAVE_COMMONCRYPTO 0 +#endif + +#define APU_HAVE_APR_ICONV 1 +#define APU_HAVE_ICONV 0 +#define APR_HAS_XLATE (APU_HAVE_APR_ICONV || APU_HAVE_ICONV) + +#endif /* APU_H */ +/** @} */ diff --git a/c/dependencies/windows/apr/x64/include/apu.hwc b/c/dependencies/windows/apr/x64/include/apu.hwc new file mode 100644 index 00000000..a663ec3e --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apu.hwc @@ -0,0 +1,145 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apu.h is duplicated from apu.hwc at build time -- do not edit apu.h + */ +/* @file apu.h + * @brief APR-Utility main file + */ +/** + * @defgroup APR_Util APR Utility Functions + * @{ + */ + + +#ifndef APU_H +#define APU_H + +/** + * APU_DECLARE_EXPORT is defined when building the APR-UTIL dynamic library, + * so that all public symbols are exported. + * + * APU_DECLARE_STATIC is defined when including the APR-UTIL public headers, + * to provide static linkage when the dynamic library may be unavailable. + * + * APU_DECLARE_STATIC and APU_DECLARE_EXPORT are left undefined when + * including the APR-UTIL public headers, to import and link the symbols from + * the dynamic APR-UTIL library and assure appropriate indirection and calling + * conventions at compile time. + */ + +/* Make sure we have our platform identifier macro defined we ask for later. + */ +#if defined(_WIN32) && !defined(WIN32) +#define WIN32 1 +#endif + +#if defined(DOXYGEN) || !defined(WIN32) +/** + * The public APR-UTIL functions are declared with APU_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APU_DECLARE_NONSTD(). + * + * @fn APU_DECLARE(rettype) apr_func(args); + */ +#define APU_DECLARE(type) type +/** + * The public APR-UTIL functions using variable arguments are declared with + * APU_DECLARE_NONSTD(), as they must use the C language calling convention. + * + * @fn APU_DECLARE_NONSTD(rettype) apr_func(args, ...); + */ +#define APU_DECLARE_NONSTD(type) type +/** + * The public APR-UTIL variables are declared with APU_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * + * @fn APU_DECLARE_DATA type apr_variable; + * @note extern APU_DECLARE_DATA type apr_variable; syntax is required for + * declarations within headers to properly import the variable. + */ +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_STATIC) +#define APU_DECLARE(type) type __stdcall +#define APU_DECLARE_NONSTD(type) type __cdecl +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_EXPORT) +#define APU_DECLARE(type) __declspec(dllexport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllexport) +#else +#define APU_DECLARE(type) __declspec(dllimport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllimport) +#endif + +#if !defined(WIN32) || defined(APU_MODULE_DECLARE_STATIC) +/** + * Declare a dso module's exported module structure as APU_MODULE_DECLARE_DATA. + * + * Unless APU_MODULE_DECLARE_STATIC is defined at compile time, symbols + * declared with APU_MODULE_DECLARE_DATA are always exported. + * @code + * module APU_MODULE_DECLARE_DATA mod_tag + * @endcode + */ +#define APU_MODULE_DECLARE_DATA +#else +#define APU_MODULE_DECLARE_DATA __declspec(dllexport) +#endif + +/* + * we always have SDBM (it's in our codebase) + */ +#define APU_HAVE_SDBM 1 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_GDBM 0 +#define APU_HAVE_NDBM 0 +#define APU_HAVE_DB 0 + +#if APU_HAVE_DB +#define APU_HAVE_DB_VERSION 0 +#endif +#endif + +/* + * we always enable dynamic driver loads within apr_dbd + * Win32 always has odbc (it's always installed) + */ +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_PGSQL 0 +#define APU_HAVE_MYSQL 0 +#define APU_HAVE_SQLITE3 0 +#define APU_HAVE_SQLITE2 0 +#define APU_HAVE_ORACLE 0 +#define APU_HAVE_ODBC 1 +#endif + +#define APU_HAVE_CRYPTO @apu_have_crypto_10@ + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_OPENSSL 0 +#define APU_HAVE_NSS 0 +#endif + +#define APU_HAVE_APR_ICONV @apu_have_apr_iconv_10@ +#define APU_HAVE_ICONV 0 +#define APR_HAS_XLATE (APU_HAVE_APR_ICONV || APU_HAVE_ICONV) + +#endif /* APU_H */ +/** @} */ diff --git a/c/dependencies/windows/apr/x64/include/apu_errno.h b/c/dependencies/windows/apr/x64/include/apu_errno.h new file mode 100644 index 00000000..c0a8ec7d --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apu_errno.h @@ -0,0 +1,173 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APU_ERRNO_H +#define APU_ERRNO_H + +/** + * @file apu_errno.h + * @brief APR-Util Error Codes + */ + +#include "apr.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apu_errno Error Codes + * @ingroup APR_Util + * @{ + */ + +/** + * @defgroup APR_Util_Error APR_Util Error Values + *
+ * APU ERROR VALUES
+ * APR_ENOKEY         The key provided was empty or NULL
+ * APR_ENOIV          The initialisation vector provided was NULL
+ * APR_EKEYTYPE       The key type was not recognised
+ * APR_ENOSPACE       The buffer supplied was not big enough
+ * APR_ECRYPT         An error occurred while encrypting or decrypting
+ * APR_EPADDING       Padding was not supported
+ * APR_EKEYLENGTH     The key length was incorrect
+ * APR_ENOCIPHER      The cipher provided was not recognised
+ * APR_ENODIGEST      The digest provided was not recognised
+ * APR_ENOENGINE      The engine provided was not recognised
+ * APR_EINITENGINE    The engine could not be initialised
+ * APR_EREINIT        Underlying crypto has already been initialised
+ * 
+ * + *
+ * APR STATUS VALUES
+ * APR_INCHILD        Program is currently executing in the child
+ * 
+ * @{ + */ +/** @see APR_STATUS_IS_ENOKEY */ +#define APR_ENOKEY (APR_UTIL_START_STATUS + 1) +/** @see APR_STATUS_IS_ENOIV */ +#define APR_ENOIV (APR_UTIL_START_STATUS + 2) +/** @see APR_STATUS_IS_EKEYTYPE */ +#define APR_EKEYTYPE (APR_UTIL_START_STATUS + 3) +/** @see APR_STATUS_IS_ENOSPACE */ +#define APR_ENOSPACE (APR_UTIL_START_STATUS + 4) +/** @see APR_STATUS_IS_ECRYPT */ +#define APR_ECRYPT (APR_UTIL_START_STATUS + 5) +/** @see APR_STATUS_IS_EPADDING */ +#define APR_EPADDING (APR_UTIL_START_STATUS + 6) +/** @see APR_STATUS_IS_EKEYLENGTH */ +#define APR_EKEYLENGTH (APR_UTIL_START_STATUS + 7) +/** @see APR_STATUS_IS_ENOCIPHER */ +#define APR_ENOCIPHER (APR_UTIL_START_STATUS + 8) +/** @see APR_STATUS_IS_ENODIGEST */ +#define APR_ENODIGEST (APR_UTIL_START_STATUS + 9) +/** @see APR_STATUS_IS_ENOENGINE */ +#define APR_ENOENGINE (APR_UTIL_START_STATUS + 10) +/** @see APR_STATUS_IS_EINITENGINE */ +#define APR_EINITENGINE (APR_UTIL_START_STATUS + 11) +/** @see APR_STATUS_IS_EREINIT */ +#define APR_EREINIT (APR_UTIL_START_STATUS + 12) +/** @} */ + +/** + * @defgroup APU_STATUS_IS Status Value Tests + * @warning For any particular error condition, more than one of these tests + * may match. This is because platform-specific error codes may not + * always match the semantics of the POSIX codes these tests (and the + * corresponding APR error codes) are named after. A notable example + * are the APR_STATUS_IS_ENOENT and APR_STATUS_IS_ENOTDIR tests on + * Win32 platforms. The programmer should always be aware of this and + * adjust the order of the tests accordingly. + * @{ + */ + +/** @} */ + +/** + * @addtogroup APR_Util_Error + * @{ + */ +/** + * The key was empty or not provided + */ +#define APR_STATUS_IS_ENOKEY(s) ((s) == APR_ENOKEY) +/** + * The initialisation vector was not provided + */ +#define APR_STATUS_IS_ENOIV(s) ((s) == APR_ENOIV) +/** + * The key type was not recognised + */ +#define APR_STATUS_IS_EKEYTYPE(s) ((s) == APR_EKEYTYPE) +/** + * The buffer provided was not big enough + */ +#define APR_STATUS_IS_ENOSPACE(s) ((s) == APR_ENOSPACE) +/** + * An error occurred while encrypting or decrypting + */ +#define APR_STATUS_IS_ECRYPT(s) ((s) == APR_ECRYPT) +/** + * An error occurred while padding + */ +#define APR_STATUS_IS_EPADDING(s) ((s) == APR_EPADDING) +/** + * An error occurred with the key length + */ +#define APR_STATUS_IS_EKEYLENGTH(s) ((s) == APR_EKEYLENGTH) +/** + * The cipher provided was not recognised + */ +#define APR_STATUS_IS_ENOCIPHER(s) ((s) == APR_ENOCIPHER) +/** + * The digest provided was not recognised + */ +#define APR_STATUS_IS_ENODIGEST(s) ((s) == APR_ENODIGEST) +/** + * The engine provided was not recognised + */ +#define APR_STATUS_IS_ENOENGINE(s) ((s) == APR_ENOENGINE) +/** + * The engine could not be initialised + */ +#define APR_STATUS_IS_EINITENGINE(s) ((s) == APR_EINITENGINE) +/** + * Crypto has already been initialised + */ +#define APR_STATUS_IS_EREINIT(s) ((s) == APR_EREINIT) +/** @} */ + +/** + * This structure allows the underlying API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apu_err_t { + const char *reason; + const char *msg; + int rc; +} apu_err_t; + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APU_ERRNO_H */ diff --git a/c/dependencies/windows/apr/x64/include/apu_version.h b/c/dependencies/windows/apr/x64/include/apu_version.h new file mode 100644 index 00000000..e4fb2e64 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apu_version.h @@ -0,0 +1,139 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APU_VERSION_H +#define APU_VERSION_H + +/** + * @file apu_version.h + * @brief APR-util Versioning Interface + * + * APR-util's Version + * + * There are several different mechanisms for accessing the version. There + * is a string form, and a set of numbers; in addition, there are constants + * which can be compiled into your application, and you can query the library + * being used for its actual version. + * + * Note that it is possible for an application to detect that it has been + * compiled against a different version of APU by use of the compile-time + * constants and the use of the run-time query function. + * + * APU version numbering follows the guidelines specified in: + * + * http://apr.apache.org/versioning.html + */ + + +#define APU_COPYRIGHT "Copyright (c) 2000-2016 The Apache Software " \ + "Foundation or its licensors, as applicable." + +/* The numeric compile-time version constants. These constants are the + * authoritative version numbers for APU. + */ + +/** major version + * Major API changes that could cause compatibility problems for older + * programs such as structure size changes. No binary compatibility is + * possible across a change in the major version. + */ +#define APU_MAJOR_VERSION 1 + +/** minor version + * Minor API changes that do not cause binary compatibility problems. + * Reset to 0 when upgrading APU_MAJOR_VERSION + */ +#define APU_MINOR_VERSION 6 + +/** patch level + * The Patch Level never includes API changes, simply bug fixes. + * Reset to 0 when upgrading APR_MINOR_VERSION + */ +#define APU_PATCH_VERSION 1 + +/** + * The symbol APU_IS_DEV_VERSION is only defined for internal, + * "development" copies of APU. It is undefined for released versions + * of APU. + */ +/* #undef APU_IS_DEV_VERSION */ + + +#if defined(APU_IS_DEV_VERSION) || defined(DOXYGEN) +/** Internal: string form of the "is dev" flag */ +#ifndef APU_IS_DEV_STRING +#define APU_IS_DEV_STRING "-dev" +#endif +#else +#define APU_IS_DEV_STRING "" +#endif + + +#ifndef APU_STRINGIFY +/** Properly quote a value as a string in the C preprocessor */ +#define APU_STRINGIFY(n) APU_STRINGIFY_HELPER(n) +/** Helper macro for APU_STRINGIFY */ +#define APU_STRINGIFY_HELPER(n) #n +#endif + +/** The formatted string of APU's version */ +#define APU_VERSION_STRING \ + APU_STRINGIFY(APU_MAJOR_VERSION) "." \ + APU_STRINGIFY(APU_MINOR_VERSION) "." \ + APU_STRINGIFY(APU_PATCH_VERSION) \ + APU_IS_DEV_STRING + +/** An alternative formatted string of APR's version */ +/* macro for Win32 .rc files using numeric csv representation */ +#define APU_VERSION_STRING_CSV APU_MAJOR_VERSION ##, \ + ##APU_MINOR_VERSION ##, \ + ##APU_PATCH_VERSION + + +#ifndef APU_VERSION_ONLY + +/* The C language API to access the version at run time, + * as opposed to compile time. APU_VERSION_ONLY may be defined + * externally when preprocessing apr_version.h to obtain strictly + * the C Preprocessor macro declarations. + */ + +#include "apr_version.h" + +#include "apu.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Return APR-util's version information information in a numeric form. + * + * @param pvsn Pointer to a version structure for returning the version + * information. + */ +APU_DECLARE(void) apu_version(apr_version_t *pvsn); + +/** Return APU's version information as a string. */ +APU_DECLARE(const char *) apu_version_string(void); + +#ifdef __cplusplus +} +#endif + +#endif /* ndef APU_VERSION_ONLY */ + +#endif /* ndef APU_VERSION_H */ diff --git a/c/dependencies/windows/apr/x64/include/apu_want.h b/c/dependencies/windows/apr/x64/include/apu_want.h new file mode 100644 index 00000000..8bb56ce7 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apu_want.h @@ -0,0 +1,52 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apu.h" /* configuration data */ + +/** + * @file apu_want.h + * @brief APR Standard Headers Support + * + *
+ * Features:
+ *
+ *   APU_WANT_DB:       
+ *
+ * Typical usage:
+ *
+ *   #define APU_WANT_DB
+ *   #include "apu_want.h"
+ *
+ * The appropriate headers will be included.
+ *
+ * Note: it is safe to use this in a header (it won't interfere with other
+ *       headers' or source files' use of apu_want.h)
+ * 
+ */ + +/* --------------------------------------------------------------------- */ + +#ifdef APU_WANT_DB + +#if APU_HAVE_DB +/* win32 note.. you will need to change this for db1 */ +#include +#endif + +#undef APU_WANT_DB +#endif + +/* --------------------------------------------------------------------- */ diff --git a/c/dependencies/windows/apr/x64/include/apu_want.h.in b/c/dependencies/windows/apr/x64/include/apu_want.h.in new file mode 100644 index 00000000..81297a75 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apu_want.h.in @@ -0,0 +1,51 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apu.h" /* configuration data */ + +/** + * @file apu_want.h + * @brief APR Standard Headers Support + * + *
+ * Features:
+ *
+ *   APU_WANT_DB:       <@apu_db_header@>
+ *
+ * Typical usage:
+ *
+ *   #define APU_WANT_DB
+ *   #include "apu_want.h"
+ *
+ * The appropriate headers will be included.
+ *
+ * Note: it is safe to use this in a header (it won't interfere with other
+ *       headers' or source files' use of apu_want.h)
+ * 
+ */ + +/* --------------------------------------------------------------------- */ + +#ifdef APU_WANT_DB + +#if APU_HAVE_DB +#include <@apu_db_header@> +#endif + +#undef APU_WANT_DB +#endif + +/* --------------------------------------------------------------------- */ diff --git a/c/dependencies/windows/apr/x64/include/apu_want.hnw b/c/dependencies/windows/apr/x64/include/apu_want.hnw new file mode 100644 index 00000000..5d6edd3c --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apu_want.hnw @@ -0,0 +1,52 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apu.h" /* configuration data */ + +/** + * @file apu_want.h + * @brief APR Standard Headers Support + * + *
+ * Features:
+ *
+ *   APU_WANT_DB:       <@apu_db_header>
+ *
+ * Typical usage:
+ *
+ *   #define APU_WANT_DB
+ *   #include "apu_want.h"
+ *
+ * The appropriate headers will be included.
+ *
+ * Note: it is safe to use this in a header (it won't interfere with other
+ *       headers' or source files' use of apu_want.h)
+ * 
+ */ + +/* --------------------------------------------------------------------- */ + +#ifdef APU_WANT_DB + +#if APU_HAVE_DB +/* win32 note.. you will need to change this for db1 */ +#include +#endif + +#undef APU_WANT_DB +#endif + +/* --------------------------------------------------------------------- */ diff --git a/c/dependencies/windows/apr/x64/include/apu_want.hw b/c/dependencies/windows/apr/x64/include/apu_want.hw new file mode 100644 index 00000000..03b6ea98 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/apu_want.hw @@ -0,0 +1,52 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apu.h" /* configuration data */ + +/** + * @file apu_want.h + * @brief APR Standard Headers Support + * + *
+ * Features:
+ *
+ *   APU_WANT_DB:       
+ *
+ * Typical usage:
+ *
+ *   #define APU_WANT_DB
+ *   #include "apu_want.h"
+ *
+ * The appropriate headers will be included.
+ *
+ * Note: it is safe to use this in a header (it won't interfere with other
+ *       headers' or source files' use of apu_want.h)
+ * 
+ */ + +/* --------------------------------------------------------------------- */ + +#ifdef APU_WANT_DB + +#if APU_HAVE_DB +/* win32 note.. you will need to change this for db1 */ +#include +#endif + +#undef APU_WANT_DB +#endif + +/* --------------------------------------------------------------------- */ diff --git a/c/dependencies/windows/apr/x64/include/arch/aix/apr_arch_dso.h b/c/dependencies/windows/apr/x64/include/arch/aix/apr_arch_dso.h new file mode 100644 index 00000000..d1cac684 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/aix/apr_arch_dso.h @@ -0,0 +1,41 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_dso.h" +#include "apr.h" + +#if APR_HAS_DSO + +void *dlopen(const char *path, int mode); +void *dlsym(void *handle, const char *symbol); +const char *dlerror(void); +int dlclose(void *handle); + +struct apr_dso_handle_t { + apr_pool_t *pool; + void *handle; + const char *errormsg; +}; + +#endif + +#endif diff --git a/c/dependencies/windows/apr/x64/include/arch/apr_private_common.h b/c/dependencies/windows/apr/x64/include/arch/apr_private_common.h new file mode 100644 index 00000000..ec850c65 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/apr_private_common.h @@ -0,0 +1,41 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * This file contains private declarations common to all architectures. + */ + +#ifndef APR_PRIVATE_COMMON_H +#define APR_PRIVATE_COMMON_H + +#include "apr_pools.h" +#include "apr_tables.h" + +apr_status_t apr_filepath_list_split_impl(apr_array_header_t **pathelts, + const char *liststr, + char separator, + apr_pool_t *p); + +apr_status_t apr_filepath_list_merge_impl(char **liststr, + apr_array_header_t *pathelts, + char separator, + apr_pool_t *p); + +/* temporary defines to handle 64bit compile mismatches */ +#define APR_INT_TRUNC_CAST int +#define APR_UINT32_TRUNC_CAST apr_uint32_t + +#endif /*APR_PRIVATE_COMMON_H*/ diff --git a/c/dependencies/windows/apr/x64/include/arch/beos/apr_arch_dso.h b/c/dependencies/windows/apr/x64/include/arch/beos/apr_arch_dso.h new file mode 100644 index 00000000..fbc5c2ff --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/beos/apr_arch_dso.h @@ -0,0 +1,41 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_dso.h" +#include "apr.h" +#include +#include + +#if APR_HAS_DSO + +struct apr_dso_handle_t { + image_id handle; /* Handle to the DSO loaded */ + apr_pool_t *pool; + const char *errormsg; /* if the load fails, we have an error + * message here :) + */ +}; + +#endif + +#endif diff --git a/c/dependencies/windows/apr/x64/include/arch/beos/apr_arch_proc_mutex.h b/c/dependencies/windows/apr/x64/include/arch/beos/apr_arch_proc_mutex.h new file mode 100644 index 00000000..c60d8c62 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/beos/apr_arch_proc_mutex.h @@ -0,0 +1,36 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PROC_MUTEX_H +#define PROC_MUTEX_H + +#include "apr_pools.h" +#include "apr_proc_mutex.h" +#include "apr_file_io.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_portable.h" + +struct apr_proc_mutex_t { + apr_pool_t *pool; + + /* Our lock :) */ + sem_id Lock; + int32 LockCount; +}; + +#endif /* PROC_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/beos/apr_arch_thread_cond.h b/c/dependencies/windows/apr/x64/include/arch/beos/apr_arch_thread_cond.h new file mode 100644 index 00000000..c9420b53 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/beos/apr_arch_thread_cond.h @@ -0,0 +1,46 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_COND_H +#define THREAD_COND_H + +#include +#include "apr_pools.h" +#include "apr_thread_cond.h" +#include "apr_file_io.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_portable.h" +#include "apr_ring.h" + +struct waiter_t { + APR_RING_ENTRY(waiter_t) link; + sem_id sem; +}; + +struct apr_thread_cond_t { + apr_pool_t *pool; + sem_id lock; + apr_thread_mutex_t *condlock; + thread_id owner; + /* active list */ + APR_RING_HEAD(active_list, waiter_t) alist; + /* free list */ + APR_RING_HEAD(free_list, waiter_t) flist; +}; + +#endif /* THREAD_COND_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/beos/apr_arch_thread_mutex.h b/c/dependencies/windows/apr/x64/include/arch/beos/apr_arch_thread_mutex.h new file mode 100644 index 00000000..bb7d4ae8 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/beos/apr_arch_thread_mutex.h @@ -0,0 +1,42 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_MUTEX_H +#define THREAD_MUTEX_H + +#include +#include "apr_pools.h" +#include "apr_thread_mutex.h" +#include "apr_file_io.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_portable.h" + +struct apr_thread_mutex_t { + apr_pool_t *pool; + + /* Our lock :) */ + sem_id Lock; + int32 LockCount; + + /* If we nest locks we need these... */ + int nested; + apr_os_thread_t owner; + int owner_ref; +}; + +#endif /* THREAD_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/beos/apr_arch_thread_rwlock.h b/c/dependencies/windows/apr/x64/include/arch/beos/apr_arch_thread_rwlock.h new file mode 100644 index 00000000..694b0d50 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/beos/apr_arch_thread_rwlock.h @@ -0,0 +1,45 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_RWLOCK_H +#define THREAD_RWLOCK_H + +#include +#include "apr_pools.h" +#include "apr_thread_rwlock.h" +#include "apr_file_io.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_portable.h" + +struct apr_thread_rwlock_t { + apr_pool_t *pool; + + /* Our lock :) */ + sem_id Lock; + int32 LockCount; + /* Read/Write lock stuff */ + sem_id Read; + int32 ReadCount; + sem_id Write; + int32 WriteCount; + int32 Nested; + + thread_id writer; +}; + +#endif /* THREAD_RWLOCK_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/beos/apr_arch_threadproc.h b/c/dependencies/windows/apr/x64/include/arch/beos/apr_arch_threadproc.h new file mode 100644 index 00000000..13de0536 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/beos/apr_arch_threadproc.h @@ -0,0 +1,95 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr_thread_proc.h" +#include "apr_arch_file_io.h" +#include "apr_file_io.h" +#include "apr_thread_proc.h" +#include "apr_general.h" +#include "apr_portable.h" +#include +#include +#include +#include +#include + +#ifndef THREAD_PROC_H +#define THREAD_PROC_H + +#define SHELL_PATH "/bin/sh" + +#define PTHREAD_CANCEL_AYNCHRONOUS CANCEL_ASYNCH; +#define PTHREAD_CANCEL_DEFERRED CANCEL_DEFER; + +#define PTHREAD_CANCEL_ENABLE CANCEL_ENABLE; +#define PTHREAD_CANCEL_DISABLE CANCEL_DISABLE; + +#define BEOS_MAX_DATAKEYS 128 + +struct apr_thread_t { + apr_pool_t *pool; + thread_id td; + void *data; + apr_thread_start_t func; + apr_status_t exitval; +}; + +struct apr_threadattr_t { + apr_pool_t *pool; + int32 attr; + int detached; + int joinable; +}; + +struct apr_threadkey_t { + apr_pool_t *pool; + int32 key; +}; + +struct beos_private_data { + const void ** data; + int count; + volatile thread_id td; +}; + +struct beos_key { + int assigned; + int count; + sem_id lock; + int32 ben_lock; + void (* destructor) (void *); +}; + +struct apr_procattr_t { + apr_pool_t *pool; + apr_file_t *parent_in; + apr_file_t *child_in; + apr_file_t *parent_out; + apr_file_t *child_out; + apr_file_t *parent_err; + apr_file_t *child_err; + char *currdir; + apr_int32_t cmdtype; + apr_int32_t detached; +}; + +struct apr_thread_once_t { + sem_id sem; + int hit; +}; + +#endif /* ! THREAD_PROC_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_dso.h b/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_dso.h new file mode 100644 index 00000000..ea0fe8c2 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_dso.h @@ -0,0 +1,43 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_dso.h" +#include "apr.h" + +#include + +typedef struct sym_list sym_list; + +struct sym_list { + sym_list *next; + char *symbol; +}; + +struct apr_dso_handle_t { + apr_pool_t *pool; + void *handle; + const char *errormsg; + sym_list *symbols; + char *path; +}; + +#endif diff --git a/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_file_io.h b/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_file_io.h new file mode 100644 index 00000000..8bd2a72c --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_file_io.h @@ -0,0 +1,176 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FILE_IO_H +#define FILE_IO_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_tables.h" +#include "apr_file_io.h" +#include "apr_file_info.h" +#include "apr_errno.h" +#include "apr_lib.h" +#include "apr_poll.h" + +/* System headers the file I/O library needs */ +#if APR_HAVE_FCNTL_H +#include +#endif +#if APR_HAVE_SYS_TYPES_H +#include +#endif +#if APR_HAVE_ERRNO_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#if APR_HAVE_STRINGS_H +#include +#endif +#if APR_HAVE_DIRENT_H +#include +#endif +#ifdef HAVE_SYS_STAT_H +#include +#endif +#if APR_HAVE_UNISTD_H +#include +#endif +#if APR_HAVE_STDIO_H +#include +#endif +#if APR_HAVE_STDLIB_H +#include +#endif +#if APR_HAVE_SYS_UIO_H +#include +#endif +#if APR_HAVE_SYS_TIME_H +#include +#endif + +#include + +/* End System headers */ + +#define APR_FILE_DEFAULT_BUFSIZE 4096 +/* For backwards compat */ +#define APR_FILE_BUFSIZE APR_FILE_DEFAULT_BUFSIZE + +#if APR_HAS_THREADS +#define file_lock(f) do { \ + if ((f)->thlock) \ + apr_thread_mutex_lock((f)->thlock); \ + } while (0) +#define file_unlock(f) do { \ + if ((f)->thlock) \ + apr_thread_mutex_unlock((f)->thlock); \ + } while (0) +#else +#define file_lock(f) do {} while (0) +#define file_unlock(f) do {} while (0) +#endif + +#if APR_HAS_LARGE_FILES +#define lseek(f,o,w) lseek64(f,o,w) +#define ftruncate(f,l) ftruncate64(f,l) +#endif + +typedef struct stat struct_stat; + +struct apr_file_t { + apr_pool_t *pool; + int filedes; + char *fname; + apr_int32_t flags; + int eof_hit; + int is_pipe; + apr_interval_time_t timeout; + int buffered; + enum {BLK_UNKNOWN, BLK_OFF, BLK_ON } blocking; + int ungetchar; /* Last char provided by an unget op. (-1 = no char)*/ + + /* if there is a timeout set, then this pollset is used */ + apr_pollset_t *pollset; + + /* Stuff for buffered mode */ + char *buffer; + apr_size_t bufpos; /* Read/Write position in buffer */ + apr_size_t bufsize; /* The buffer size */ + apr_off_t dataRead; /* amount of valid data read into buffer */ + int direction; /* buffer being used for 0 = read, 1 = write */ + apr_off_t filePtr; /* position in file of handle */ +#if APR_HAS_THREADS + struct apr_thread_mutex_t *thlock; +#endif +}; + +struct apr_dir_t { + apr_pool_t *pool; + char *dirname; + DIR *dirstruct; + struct dirent *entry; +}; + +typedef struct apr_stat_entry_t apr_stat_entry_t; + +struct apr_stat_entry_t { + struct stat info; + char *casedName; + apr_time_t expire; + NXPathCtx_t pathCtx; +}; + +#define MAX_SERVER_NAME 64 +#define MAX_VOLUME_NAME 64 +#define MAX_PATH_NAME 256 +#define MAX_FILE_NAME 256 + +#define DRIVE_ONLY 1 + +/* If the user passes d: vs. D: (or //mach/share vs. //MACH/SHARE), + * we need to fold the case to canonical form. This function is + * supposed to do so. + */ +apr_status_t filepath_root_case(char **rootpath, char *root, apr_pool_t *p); + +/* This function check to see of the given path includes a drive/volume + * specifier. If the _only_ parameter is set to DRIVE_ONLY then it + * check to see of the path only contains a drive/volume specifier and + * nothing else. + */ +apr_status_t filepath_has_drive(const char *rootpath, int only, apr_pool_t *p); + +/* This function compares the drive/volume specifiers for each given path. + * It returns zero if they match or non-zero if not. + */ +apr_status_t filepath_compare_drive(const char *path1, const char *path2, apr_pool_t *p); + +apr_status_t apr_unix_file_cleanup(void *); +apr_status_t apr_unix_child_file_cleanup(void *); + +mode_t apr_unix_perms2mode(apr_fileperms_t perms); +apr_fileperms_t apr_unix_mode2perms(mode_t mode); + +apr_status_t apr_file_flush_locked(apr_file_t *thefile); +apr_status_t apr_file_info_get_locked(apr_finfo_t *finfo, apr_int32_t wanted, + apr_file_t *thefile); + +#endif /* ! FILE_IO_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_global_mutex.h b/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_global_mutex.h new file mode 100644 index 00000000..4167d378 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_global_mutex.h @@ -0,0 +1,29 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GLOBAL_MUTEX_H +#define GLOBAL_MUTEX_H + +#include "apr_global_mutex.h" +#include "apr_thread_mutex.h" + +struct apr_global_mutex_t { + apr_pool_t *pool; + apr_thread_mutex_t *mutex; +}; + +#endif /* GLOBAL_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_internal_time.h b/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_internal_time.h new file mode 100644 index 00000000..59f10672 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_internal_time.h @@ -0,0 +1,26 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIME_INTERNAL_H +#define TIME_INTERNAL_H + +#include "apr.h" + +#define TZONE (*___timezone()) + +void apr_netware_setup_time(void); + +#endif /* TIME_INTERNAL_H */ diff --git a/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_networkio.h b/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_networkio.h new file mode 100644 index 00000000..63f17abe --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_networkio.h @@ -0,0 +1,31 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETWORK_IO_H + +#ifdef USE_WINSOCK +/* Making sure that we include the correct networkio.h since the + the project file is configured to first look for headers in + arch/netware and then arch/unix. But in this specific case we + want arch/win32. +*/ +#include <../win32/apr_arch_networkio.h> +#else +#include <../unix/apr_arch_networkio.h> +#endif + +#endif /* ! NETWORK_IO_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_pre_nw.h b/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_pre_nw.h new file mode 100644 index 00000000..7380e118 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_pre_nw.h @@ -0,0 +1,57 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef __pre_nw__ +#define __pre_nw__ + +#include + +#ifndef __GNUC__ +#pragma precompile_target "precomp.mch" +#endif + +#define NETWARE + +#define N_PLAT_NLM + +#define FAR +#define far + +/* no-op for Codewarrior C compiler; a functions are cdecl + by default */ +#define cdecl + +/* if we have wchar_t enabled in C++, predefine this type to avoid + a conflict in Novell's header files */ +#ifndef __GNUC__ +#ifndef DOXYGEN +#if (__option(cplusplus) && __option(wchar_type)) +#define _WCHAR_T +#endif +#endif +#endif + +/* C9X defintion used by MSL C++ library */ +#define DECIMAL_DIG 17 + +/* some code may want to use the MS convention for long long */ +#ifndef __int64 +#define __int64 long long +#endif + +#endif + + + diff --git a/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_proc_mutex.h b/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_proc_mutex.h new file mode 100644 index 00000000..7a634c2e --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_proc_mutex.h @@ -0,0 +1,29 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PROC_MUTEX_H +#define PROC_MUTEX_H + +#include "apr_proc_mutex.h" +#include "apr_thread_mutex.h" + +struct apr_proc_mutex_t { + apr_pool_t *pool; + apr_thread_mutex_t *mutex; +}; + +#endif /* PROC_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_thread_cond.h b/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_thread_cond.h new file mode 100644 index 00000000..b11a5f86 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_thread_cond.h @@ -0,0 +1,29 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_COND_H +#define THREAD_COND_H + +#include "apr_thread_cond.h" +#include + +struct apr_thread_cond_t { + apr_pool_t *pool; + NXCond_t *cond; +}; + +#endif /* THREAD_COND_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_thread_mutex.h b/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_thread_mutex.h new file mode 100644 index 00000000..18702fc7 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_thread_mutex.h @@ -0,0 +1,32 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_MUTEX_H +#define THREAD_MUTEX_H + +#include "apr_thread_mutex.h" +#include "apr_thread_cond.h" +#include + +struct apr_thread_mutex_t { + apr_pool_t *pool; + NXMutex_t *mutex; + apr_thread_cond_t *cond; + int locked, num_waiters; +}; + +#endif /* THREAD_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_thread_rwlock.h b/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_thread_rwlock.h new file mode 100644 index 00000000..d2dbd42f --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_thread_rwlock.h @@ -0,0 +1,29 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_RWLOCK_H +#define THREAD_RWLOCK_H + +#include "apr_thread_rwlock.h" +#include + +struct apr_thread_rwlock_t { + apr_pool_t *pool; + NXRwLock_t *rwlock; +}; + +#endif /* THREAD_RWLOCK_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_threadproc.h b/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_threadproc.h new file mode 100644 index 00000000..2fee2c00 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/netware/apr_arch_threadproc.h @@ -0,0 +1,80 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" + +#include + +#ifndef THREAD_PROC_H +#define THREAD_PROC_H + +#define SHELL_PATH "" +#define APR_DEFAULT_STACK_SIZE 65536 + +struct apr_thread_t { + apr_pool_t *pool; + NXContext_t ctx; + NXThreadId_t td; + char *thread_name; + apr_int32_t cancel; + apr_int32_t cancel_how; + void *data; + apr_thread_start_t func; + apr_status_t exitval; +}; + +struct apr_threadattr_t { + apr_pool_t *pool; + apr_size_t stack_size; + apr_int32_t detach; + char *thread_name; +}; + +struct apr_threadkey_t { + apr_pool_t *pool; + NXKey_t key; +}; + +struct apr_procattr_t { + apr_pool_t *pool; + apr_file_t *parent_in; + apr_file_t *child_in; + apr_file_t *parent_out; + apr_file_t *child_out; + apr_file_t *parent_err; + apr_file_t *child_err; + char *currdir; + apr_int32_t cmdtype; + apr_int32_t detached; + apr_int32_t addrspace; +}; + +struct apr_thread_once_t { + unsigned long value; +}; + +/* +struct apr_proc_t { + apr_pool_t *pool; + pid_t pid; + apr_procattr_t *attr; +}; +*/ + +#endif /* ! THREAD_PROC_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/netware/apr_private.h b/c/dependencies/windows/apr/x64/include/arch/netware/apr_private.h new file mode 100644 index 00000000..04f336de --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/netware/apr_private.h @@ -0,0 +1,205 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Note: + * This is the netware-specific autoconf-like config file + * which unix creates at ./configure time. + */ + +#ifdef NETWARE + +#ifndef APR_PRIVATE_H +#define APR_PRIVATE_H + +/* Pick up publicly advertised headers and symbols before the + * APR internal private headers and symbols + */ +#include + +/* Pick up privately consumed headers */ +#include + +/* Include alloca.h to get compiler-dependent defines */ +#include + +#include +#include +#include +#include +#include +#include +#include + +/* Use this section to define all of the HAVE_FOO_H + * that are required to build properly. + */ +#define HAVE_DLFCN_H 1 +#define HAVE_LIMITS_H 1 +#define HAVE_SIGNAL_H 1 +#define HAVE_STDDEF_H 1 +#define HAVE_STDLIB_H 1 +#ifndef USE_WINSOCK +#define HAVE_SYS_SELECT_H 1 +#define HAVE_WRITEV 1 +#endif +#define HAVE_SYS_STAT_H 1 +#define HAVE_SYS_MMAN_H 1 +#define HAVE_FCNTL_H 1 +#define HAVE_ICONV_H 1 +#define HAVE_UTIME_H 1 + +#define HAVE_STRICMP 1 +#define HAVE_STRNICMP 1 +#define HAVE_STRDUP 1 +#define HAVE_STRSTR 1 +#define HAVE_MEMCHR 1 +#define HAVE_CALLOC 1 +#define HAVE_UTIME 1 + +#define HAVE_GETENV 1 +#define HAVE_SETENV 1 +#define HAVE_UNSETENV 1 + +#define HAVE_WRITEV 1 + +#define HAVE_GETPASS_R 1 +/* + * Hack around older NDKs which have only the getpassword() function, + * a threadsafe, API-equivalent of getpass_r(). + */ +#if (CURRENT_NDK_THRESHOLD < 709060000) +#define getpass_r getpassword +#endif + +/*#define DSO_USE_DLFCN */ + +#ifdef NW_BUILD_IPV6 +#define HAVE_GETADDRINFO 1 +#define HAVE_GETNAMEINFO 1 +#endif + +/* 1 is used for SIGABRT on netware */ +/* 2 is used for SIGFPE on netware */ +/* 3 is used for SIGILL on netware */ +/* 4 is used for SIGINT on netware */ +/* 5 is used for SIGSEGV on netware */ +/* 6 is used for SIGTERM on netware */ +/* 7 is used for SIGPOLL on netware */ + +#if (CURRENT_NDK_THRESHOLD < 306030000) +#define SIGKILL 11 +#define SIGALRM 13 +#define SIGCHLD 14 +#define SIGCONT 15 +#define SIGHUP 16 +#define SIGPIPE 17 +#define SIGQUIT 18 +#define SIGSTOP 19 +#define SIGTSTP 20 +#define SIGTTIN 21 +#define SIGTTOU 22 +#define SIGUSR1 23 +#define SIGUSR2 24 +#endif + +#define SIGTRAP 25 +#define SIGIOT 26 +#define SIGSTKFLT 28 +#define SIGURG 29 +#define SIGXCPU 30 +#define SIGXFSZ 31 +#define SIGVTALRM 32 +#define SIGPROF 33 +#define SIGWINCH 34 +#define SIGIO 35 + +#if (CURRENT_NDK_THRESHOLD < 406230000) +#undef SA_NOCLDSTOP +#define SA_NOCLDSTOP 0x00000001 +#endif +#ifndef SIGBUS +#define SIGBUS SIGSEGV +#endif + +#define _getch getcharacter + +#define SIZEOF_SHORT 2 +#define SIZEOF_INT 4 +#define SIZEOF_LONGLONG 8 +#define SIZEOF_CHAR 1 +#define SIZEOF_SSIZE_T SIZEOF_INT + +void netware_pool_proc_cleanup(); + +/* NLM registration routines for managing which NLMs + are using the library. */ +int register_NLM(void *NLMHandle); +int unregister_NLM(void *NLMHandle); + +/* Application global data management */ +extern int gLibId; +extern void *gLibHandle; + +typedef struct app_data { + int initialized; + void* gPool; + void* gs_aHooksToSort; + void* gs_phOptionalHooks; + void* gs_phOptionalFunctions; + void* gs_nlmhandle; + rtag_t gs_startup_rtag; + rtag_t gs_socket_rtag; + rtag_t gs_lookup_rtag; + rtag_t gs_event_rtag; + rtag_t gs_pcp_rtag; + void* gs_ldap_xref_lock; + void* gs_xref_head; +} APP_DATA; + +int setGlobalPool(void *data); +void* getGlobalPool(); +int setStatCache(void *data); +void* getStatCache(); + +/* Redefine malloc to use the library malloc call so + that all of the memory resources will be owned + and can be shared by the library. */ +#undef malloc +#define malloc(x) library_malloc(gLibHandle,x) +#ifndef __MWERKS__ +#define _alloca alloca +#endif + +/* 64-bit integer conversion function */ +#define APR_INT64_STRFN strtoll + +#if APR_HAS_LARGE_FILES +#define APR_OFF_T_STRFN strtoll +#else +#define APR_OFF_T_STRFN strtol +#endif + +/* used to check DWORD overflow for 64bit compiles */ +#define APR_DWORD_MAX 0xFFFFFFFFUL + +/* + * Include common private declarations. + */ +#include "../apr_private_common.h" + +#endif /*APR_PRIVATE_H*/ +#endif /*NETWARE*/ diff --git a/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_dso.h b/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_dso.h new file mode 100644 index 00000000..2bda6b7c --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_dso.h @@ -0,0 +1,37 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_dso.h" +#include "apr.h" + +#if APR_HAS_DSO + +struct apr_dso_handle_t { + apr_pool_t *cont; /* Context for returning error strings */ + HMODULE handle; /* Handle to the DSO loaded */ + apr_status_t load_error; + char *failed_module; +}; + +#endif + +#endif diff --git a/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_file_io.h b/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_file_io.h new file mode 100644 index 00000000..79a57964 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_file_io.h @@ -0,0 +1,86 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FILE_IO_H +#define FILE_IO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_thread_mutex.h" +#include "apr_file_io.h" +#include "apr_file_info.h" +#include "apr_errno.h" +#include "apr_poll.h" + +/* We have an implementation of mkstemp but it's not very multi-threading + * friendly & is part of the POSIX emulation rather than native so don't + * use it. + */ +#undef HAVE_MKSTEMP + +#define APR_FILE_DEFAULT_BUFSIZE 4096 +#define APR_FILE_BUFSIZE APR_FILE_DEFAULT_BUFSIZE + +struct apr_file_t { + apr_pool_t *pool; + HFILE filedes; + char * fname; + int isopen; + int buffered; + int eof_hit; + apr_int32_t flags; + int timeout; + int pipe; + HEV pipeSem; + enum { BLK_UNKNOWN, BLK_OFF, BLK_ON } blocking; + + /* Stuff for buffered mode */ + char *buffer; + apr_size_t bufsize; /* Read/Write position in buffer */ + apr_size_t bufpos; /* Read/Write position in buffer */ + unsigned long dataRead; /* amount of valid data read into buffer */ + int direction; /* buffer being used for 0 = read, 1 = write */ + unsigned long filePtr; /* position in file of handle */ + apr_thread_mutex_t *mutex; /* mutex semaphore, must be owned to access + the above fields */ +}; + +struct apr_dir_t { + apr_pool_t *pool; + char *dirname; + ULONG handle; + FILEFINDBUF3 entry; + int validentry; +}; + +apr_status_t apr_file_cleanup(void *); +apr_status_t apr_os2_time_to_apr_time(apr_time_t *result, FDATE os2date, + FTIME os2time); +apr_status_t apr_apr_time_to_os2_time(FDATE *os2date, FTIME *os2time, + apr_time_t aprtime); + +/* see win32/fileio.h for description of these */ +extern const char c_is_fnchar[256]; + +#define IS_FNCHAR(c) c_is_fnchar[(unsigned char)c] + +apr_status_t filepath_root_test(char *path, apr_pool_t *p); +apr_status_t filepath_drive_get(char **rootpath, char drive, + apr_int32_t flags, apr_pool_t *p); +apr_status_t filepath_root_case(char **rootpath, char *root, apr_pool_t *p); + +#endif /* ! FILE_IO_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_inherit.h b/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_inherit.h new file mode 100644 index 00000000..494772ac --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_inherit.h @@ -0,0 +1,50 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INHERIT_H +#define INHERIT_H + +#include "apr_inherit.h" + +#define APR_INHERIT (1 << 24) /* Must not conflict with other bits */ + +#define APR_IMPLEMENT_INHERIT_SET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_set(apr_##name##_t *the##name) \ +{ \ + int rv; \ + ULONG state; \ + if (((rv = DosQueryFHState(attr->parent_err->filedes, &state)) \ + != 0) || \ + ((rv = DosSetFHState(attr->parent_err->filedes, \ + state & ~OPEN_FLAGS_NOINHERIT)) != 0)) \ + return APR_FROM_OS_ERROR(rv); \ + return APR_SUCCESS; \ +} + +#define APR_IMPLEMENT_INHERIT_UNSET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_unset(apr_##name##_t *the##name)\ +{ \ + int rv; \ + ULONG state; \ + if (((rv = DosQueryFHState(attr->parent_err->filedes, &state)) \ + != 0) || \ + ((rv = DosSetFHState(attr->parent_err->filedes, \ + state | OPEN_FLAGS_NOINHERIT)) != 0)) \ + return APR_FROM_OS_ERROR(rv); \ + return APR_SUCCESS; \ +} + +#endif /* ! INHERIT_H */ diff --git a/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_networkio.h b/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_networkio.h new file mode 100644 index 00000000..10c6de81 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_networkio.h @@ -0,0 +1,76 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETWORK_IO_H +#define NETWORK_IO_H + +#include "apr_private.h" +#include "apr_network_io.h" +#include "apr_general.h" +#include "apr_arch_os2calls.h" +#include "apr_poll.h" + +#if APR_HAVE_NETDB_H +#include +#endif + +typedef struct sock_userdata_t sock_userdata_t; +struct sock_userdata_t { + sock_userdata_t *next; + const char *key; + void *data; +}; + +struct apr_socket_t { + apr_pool_t *pool; + int socketdes; + int type; + int protocol; + apr_sockaddr_t *local_addr; + apr_sockaddr_t *remote_addr; + apr_interval_time_t timeout; + int nonblock; + int local_port_unknown; + int local_interface_unknown; + int remote_addr_unknown; + apr_int32_t options; + apr_int32_t inherit; + sock_userdata_t *userdata; + + /* if there is a timeout set, then this pollset is used */ + apr_pollset_t *pollset; +}; + +/* Error codes returned from sock_errno() */ +#define SOCBASEERR 10000 +#define SOCEPERM (SOCBASEERR+1) /* Not owner */ +#define SOCESRCH (SOCBASEERR+3) /* No such process */ +#define SOCEINTR (SOCBASEERR+4) /* Interrupted system call */ +#define SOCENXIO (SOCBASEERR+6) /* No such device or address */ +#define SOCEBADF (SOCBASEERR+9) /* Bad file number */ +#define SOCEACCES (SOCBASEERR+13) /* Permission denied */ +#define SOCEFAULT (SOCBASEERR+14) /* Bad address */ +#define SOCEINVAL (SOCBASEERR+22) /* Invalid argument */ +#define SOCEMFILE (SOCBASEERR+24) /* Too many open files */ +#define SOCEPIPE (SOCBASEERR+32) /* Broken pipe */ +#define SOCEOS2ERR (SOCBASEERR+100) /* OS/2 Error */ + +const char *apr_inet_ntop(int af, const void *src, char *dst, apr_size_t size); +int apr_inet_pton(int af, const char *src, void *dst); +void apr_sockaddr_vars_set(apr_sockaddr_t *, int, apr_port_t); + +#endif /* ! NETWORK_IO_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_os2calls.h b/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_os2calls.h new file mode 100644 index 00000000..3c739bfd --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_os2calls.h @@ -0,0 +1,59 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr_errno.h" +#include +#include + +extern int (*apr_os2_socket)(int, int, int); +extern int (*apr_os2_select)(int *, int, int, int, long); +extern int (*apr_os2_sock_errno)(); +extern int (*apr_os2_accept)(int, struct sockaddr *, int *); +extern int (*apr_os2_bind)(int, struct sockaddr *, int); +extern int (*apr_os2_connect)(int, struct sockaddr *, int); +extern int (*apr_os2_getpeername)(int, struct sockaddr *, int *); +extern int (*apr_os2_getsockname)(int, struct sockaddr *, int *); +extern int (*apr_os2_getsockopt)(int, int, int, char *, int *); +extern int (*apr_os2_ioctl)(int, int, caddr_t, int); +extern int (*apr_os2_listen)(int, int); +extern int (*apr_os2_recv)(int, char *, int, int); +extern int (*apr_os2_send)(int, const char *, int, int); +extern int (*apr_os2_setsockopt)(int, int, int, char *, int); +extern int (*apr_os2_shutdown)(int, int); +extern int (*apr_os2_soclose)(int); +extern int (*apr_os2_writev)(int, struct iovec *, int); +extern int (*apr_os2_sendto)(int, const char *, int, int, const struct sockaddr *, int); +extern int (*apr_os2_recvfrom)(int, char *, int, int, struct sockaddr *, int *); + +#define socket apr_os2_socket +#define select apr_os2_select +#define sock_errno apr_os2_sock_errno +#define accept apr_os2_accept +#define bind apr_os2_bind +#define connect apr_os2_connect +#define getpeername apr_os2_getpeername +#define getsockname apr_os2_getsockname +#define getsockopt apr_os2_getsockopt +#define ioctl apr_os2_ioctl +#define listen apr_os2_listen +#define recv apr_os2_recv +#define send apr_os2_send +#define setsockopt apr_os2_setsockopt +#define shutdown apr_os2_shutdown +#define soclose apr_os2_soclose +#define writev apr_os2_writev +#define sendto apr_os2_sendto +#define recvfrom apr_os2_recvfrom diff --git a/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_proc_mutex.h b/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_proc_mutex.h new file mode 100644 index 00000000..8caf3369 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_proc_mutex.h @@ -0,0 +1,31 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PROC_MUTEX_H +#define PROC_MUTEX_H + +#include "apr_proc_mutex.h" +#include "apr_file_io.h" + +struct apr_proc_mutex_t { + apr_pool_t *pool; + HMTX hMutex; + TID owner; + int lock_count; +}; + +#endif /* PROC_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_thread_cond.h b/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_thread_cond.h new file mode 100644 index 00000000..aa0a7ca6 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_thread_cond.h @@ -0,0 +1,33 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_COND_H +#define THREAD_COND_H + +#include "apr_thread_cond.h" +#include "apr_file_io.h" + +struct apr_thread_cond_t { + apr_pool_t *pool; + HEV semaphore; + HMTX mutex; + unsigned long num_waiting; + unsigned long num_wake; + unsigned long generation; +}; + +#endif /* THREAD_COND_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_thread_mutex.h b/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_thread_mutex.h new file mode 100644 index 00000000..3ae2a41d --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_thread_mutex.h @@ -0,0 +1,29 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_MUTEX_H +#define THREAD_MUTEX_H + +#include "apr_thread_mutex.h" +#include "apr_file_io.h" + +struct apr_thread_mutex_t { + apr_pool_t *pool; + HMTX hMutex; +}; + +#endif /* THREAD_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_thread_rwlock.h b/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_thread_rwlock.h new file mode 100644 index 00000000..7187d5cb --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_thread_rwlock.h @@ -0,0 +1,31 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_RWLOCK_H +#define THREAD_RWLOCK_H + +#include "apr_thread_rwlock.h" +#include "apr_file_io.h" + +struct apr_thread_rwlock_t { + apr_pool_t *pool; + int readers; + HMTX write_lock; + HEV read_done; +}; + +#endif /* THREAD_RWLOCK_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_threadproc.h b/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_threadproc.h new file mode 100644 index 00000000..c8017adb --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/os2/apr_arch_threadproc.h @@ -0,0 +1,67 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr_thread_proc.h" +#include "apr_file_io.h" + +#ifndef THREAD_PROC_H +#define THREAD_PROC_H + +#define APR_THREADATTR_DETACHED 1 + +#define SHELL_PATH "cmd.exe" +#define APR_THREAD_STACKSIZE 65536 + +struct apr_threadattr_t { + apr_pool_t *pool; + unsigned long attr; + apr_size_t stacksize; +}; + +struct apr_thread_t { + apr_pool_t *pool; + struct apr_threadattr_t *attr; + unsigned long tid; + apr_thread_start_t func; + void *data; + apr_status_t exitval; +}; + +struct apr_threadkey_t { + apr_pool_t *pool; + unsigned long *key; +}; + +struct apr_procattr_t { + apr_pool_t *pool; + apr_file_t *parent_in; + apr_file_t *child_in; + apr_file_t *parent_out; + apr_file_t *child_out; + apr_file_t *parent_err; + apr_file_t *child_err; + char *currdir; + apr_int32_t cmdtype; + apr_int32_t detached; +}; + +struct apr_thread_once_t { + unsigned long sem; + char hit; +}; + +#endif /* ! THREAD_PROC_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/os390/apr_arch_dso.h b/c/dependencies/windows/apr/x64/include/arch/os390/apr_arch_dso.h new file mode 100644 index 00000000..4263297b --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/os390/apr_arch_dso.h @@ -0,0 +1,39 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_dso.h" +#include "apr.h" + +#if APR_HAS_DSO + +#include + +struct apr_dso_handle_t { + dllhandle *handle; /* Handle to the DSO loaded */ + int failing_errno; /* Don't save the buffer returned by + strerror(); it gets reused */ + apr_pool_t *pool; +}; + +#endif + +#endif diff --git a/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_atomic.h b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_atomic.h new file mode 100644 index 00000000..559257de --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_atomic.h @@ -0,0 +1,53 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ATOMIC_H +#define ATOMIC_H + +#include "apr.h" +#include "apr_pools.h" +#include "apr_private.h" +#include "apr_atomic.h" + +#if defined(USE_ATOMICS_GENERIC) +/* noop */ +#elif HAVE_ATOMIC_BUILTINS +# define USE_ATOMICS_BUILTINS +#elif defined(SOLARIS2) && SOLARIS2 >= 10 +# define USE_ATOMICS_SOLARIS +# define NEED_ATOMICS_GENERIC64 +#elif defined(__GNUC__) && defined(__STRICT_ANSI__) +/* force use of generic atomics if building e.g. with -std=c89, which + * doesn't allow inline asm */ +# define USE_ATOMICS_GENERIC +#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) +# define USE_ATOMICS_IA32 +# define NEED_ATOMICS_GENERIC64 +#elif defined(__GNUC__) && (defined(__PPC__) || defined(__ppc__)) +# define USE_ATOMICS_PPC +# define NEED_ATOMICS_GENERIC64 +#elif defined(__GNUC__) && (defined(__s390__) || defined(__s390x__)) +# define USE_ATOMICS_S390 +# define NEED_ATOMICS_GENERIC64 +#else +# define USE_ATOMICS_GENERIC +#endif + +#if defined(USE_ATOMICS_GENERIC) || defined (NEED_ATOMICS_GENERIC64) +apr_status_t apr__atomic_generic64_init(apr_pool_t *p); +#endif + +#endif /* ATOMIC_H */ diff --git a/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_dso.h b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_dso.h new file mode 100644 index 00000000..d82182d4 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_dso.h @@ -0,0 +1,63 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_dso.h" +#include "apr.h" + +#if APR_HAS_DSO + +#ifdef HAVE_MACH_O_DYLD_H +#include +#endif + +#ifdef HAVE_DLFCN_H +#include +#endif + +#ifdef HAVE_DL_H +#include +#endif + +#ifndef RTLD_NOW +#define RTLD_NOW 1 +#endif + +#ifndef RTLD_GLOBAL +#define RTLD_GLOBAL 0 +#endif + +#if (defined(__DragonFly__) ||\ + defined(__FreeBSD__) ||\ + defined(__OpenBSD__) ||\ + defined(__NetBSD__) ) && !defined(__ELF__) +#define DLSYM_NEEDS_UNDERSCORE +#endif + +struct apr_dso_handle_t { + apr_pool_t *pool; + void *handle; + const char *errormsg; +}; + +#endif + +#endif diff --git a/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_file_io.h b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_file_io.h new file mode 100644 index 00000000..77a90917 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_file_io.h @@ -0,0 +1,174 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FILE_IO_H +#define FILE_IO_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_tables.h" +#include "apr_file_io.h" +#include "apr_file_info.h" +#include "apr_errno.h" +#include "apr_lib.h" +#include "apr_thread_mutex.h" +#ifndef WAITIO_USES_POLL +#include "apr_poll.h" +#endif + +/* System headers the file I/O library needs */ +#if APR_HAVE_FCNTL_H +#include +#endif +#if APR_HAVE_SYS_TYPES_H +#include +#endif +#if APR_HAVE_ERRNO_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#if APR_HAVE_STRINGS_H +#include +#endif +#if APR_HAVE_DIRENT_H +#include +#endif +#ifdef HAVE_SYS_STAT_H +#include +#endif +#if APR_HAVE_UNISTD_H +#include +#endif +#if APR_HAVE_STDIO_H +#include +#endif +#if APR_HAVE_STDLIB_H +#include +#endif +#if APR_HAVE_SYS_UIO_H +#include +#endif +#if APR_HAVE_SYS_TIME_H +#include +#endif +#ifdef BEOS +#include +#endif +/* Hunting down DEV_BSIZE if not from dirent.h, sys/stat.h etc */ +#ifdef HAVE_SYS_PARAM_H +#include +#endif + +#if BEOS_BONE +# ifndef BONE7 + /* prior to BONE/7 fd_set & select were defined in sys/socket.h */ +# include +# else + /* Be moved the fd_set stuff and also the FIONBIO definition... */ +# include +# endif +#endif +/* End System headers */ + +#define APR_FILE_DEFAULT_BUFSIZE 4096 +/* For backwards-compat */ +#define APR_FILE_BUFSIZE APR_FILE_DEFAULT_BUFSIZE + +struct apr_file_t { + apr_pool_t *pool; + int filedes; + char *fname; + apr_int32_t flags; + int eof_hit; + int is_pipe; + apr_interval_time_t timeout; + int buffered; + enum {BLK_UNKNOWN, BLK_OFF, BLK_ON } blocking; + int ungetchar; /* Last char provided by an unget op. (-1 = no char)*/ +#ifndef WAITIO_USES_POLL + /* if there is a timeout set, then this pollset is used */ + apr_pollset_t *pollset; +#endif + /* Stuff for buffered mode */ + char *buffer; + apr_size_t bufpos; /* Read/Write position in buffer */ + apr_size_t bufsize; /* The size of the buffer */ + unsigned long dataRead; /* amount of valid data read into buffer */ + int direction; /* buffer being used for 0 = read, 1 = write */ + apr_off_t filePtr; /* position in file of handle */ +#if APR_HAS_THREADS + struct apr_thread_mutex_t *thlock; +#endif +}; + +#if APR_HAS_THREADS +#define file_lock(f) do { \ + if ((f)->thlock) \ + apr_thread_mutex_lock((f)->thlock); \ + } while (0) +#define file_unlock(f) do { \ + if ((f)->thlock) \ + apr_thread_mutex_unlock((f)->thlock); \ + } while (0) +#else +#define file_lock(f) do {} while (0) +#define file_unlock(f) do {} while (0) +#endif + +#if APR_HAS_LARGE_FILES && defined(_LARGEFILE64_SOURCE) +#define stat(f,b) stat64(f,b) +#define lstat(f,b) lstat64(f,b) +#define fstat(f,b) fstat64(f,b) +#define lseek(f,o,w) lseek64(f,o,w) +#define ftruncate(f,l) ftruncate64(f,l) +typedef struct stat64 struct_stat; +#else +typedef struct stat struct_stat; +#endif + +/* readdir64_r is only used in specific cases: */ +#if APR_HAS_THREADS && defined(_POSIX_THREAD_SAFE_FUNCTIONS) \ + && !defined(READDIR_IS_THREAD_SAFE) && defined(HAVE_READDIR64_R) +#define APR_USE_READDIR64_R +#endif + +struct apr_dir_t { + apr_pool_t *pool; + char *dirname; + DIR *dirstruct; +#ifdef APR_USE_READDIR64_R + struct dirent64 *entry; +#else + struct dirent *entry; +#endif +}; + +apr_status_t apr_unix_file_cleanup(void *); +apr_status_t apr_unix_child_file_cleanup(void *); + +mode_t apr_unix_perms2mode(apr_fileperms_t perms); +apr_fileperms_t apr_unix_mode2perms(mode_t mode); + +apr_status_t apr_file_flush_locked(apr_file_t *thefile); +apr_status_t apr_file_info_get_locked(apr_finfo_t *finfo, apr_int32_t wanted, + apr_file_t *thefile); + + +#endif /* ! FILE_IO_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_global_mutex.h b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_global_mutex.h new file mode 100644 index 00000000..3add9ecf --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_global_mutex.h @@ -0,0 +1,37 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GLOBAL_MUTEX_H +#define GLOBAL_MUTEX_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_global_mutex.h" +#include "apr_arch_proc_mutex.h" +#include "apr_arch_thread_mutex.h" + +struct apr_global_mutex_t { + apr_pool_t *pool; + apr_proc_mutex_t *proc_mutex; +#if APR_HAS_THREADS + apr_thread_mutex_t *thread_mutex; +#endif /* APR_HAS_THREADS */ +}; + +#endif /* GLOBAL_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_inherit.h b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_inherit.h new file mode 100644 index 00000000..21543c1e --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_inherit.h @@ -0,0 +1,64 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INHERIT_H +#define INHERIT_H + +#include "apr_inherit.h" + +#define APR_INHERIT (1 << 24) /* Must not conflict with other bits */ + +#define APR_IMPLEMENT_INHERIT_SET(name, flag, pool, cleanup) \ +apr_status_t apr_##name##_inherit_set(apr_##name##_t *the##name) \ +{ \ + if (the##name->flag & APR_FOPEN_NOCLEANUP) \ + return APR_EINVAL; \ + if (!(the##name->flag & APR_INHERIT)) { \ + int flags = fcntl(the##name->name##des, F_GETFD); \ + if (flags == -1) \ + return errno; \ + flags &= ~(FD_CLOEXEC); \ + if (fcntl(the##name->name##des, F_SETFD, flags) == -1) \ + return errno; \ + the##name->flag |= APR_INHERIT; \ + apr_pool_child_cleanup_set(the##name->pool, \ + (void *)the##name, \ + cleanup, apr_pool_cleanup_null); \ + } \ + return APR_SUCCESS; \ +} + +#define APR_IMPLEMENT_INHERIT_UNSET(name, flag, pool, cleanup) \ +apr_status_t apr_##name##_inherit_unset(apr_##name##_t *the##name) \ +{ \ + if (the##name->flag & APR_FOPEN_NOCLEANUP) \ + return APR_EINVAL; \ + if (the##name->flag & APR_INHERIT) { \ + int flags; \ + if ((flags = fcntl(the##name->name##des, F_GETFD)) == -1) \ + return errno; \ + flags |= FD_CLOEXEC; \ + if (fcntl(the##name->name##des, F_SETFD, flags) == -1) \ + return errno; \ + the##name->flag &= ~APR_INHERIT; \ + apr_pool_child_cleanup_set(the##name->pool, \ + (void *)the##name, \ + cleanup, cleanup); \ + } \ + return APR_SUCCESS; \ +} + +#endif /* ! INHERIT_H */ diff --git a/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_internal_time.h b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_internal_time.h new file mode 100644 index 00000000..6e12c674 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_internal_time.h @@ -0,0 +1,24 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIME_INTERNAL_H +#define TIME_INTERNAL_H + +#include "apr.h" + +void apr_unix_setup_time(void); + +#endif /* TIME_INTERNAL_H */ diff --git a/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_misc.h b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_misc.h new file mode 100644 index 00000000..82351250 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_misc.h @@ -0,0 +1,67 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MISC_H +#define MISC_H + +#include "apr.h" +#include "apr_portable.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_getopt.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" +#include "apr_errno.h" +#include "apr_getopt.h" + +#if APR_HAVE_STDIO_H +#include +#endif +#if APR_HAVE_SIGNAL_H +#include +#endif +#if APR_HAVE_PTHREAD_H +#include +#endif + +#if APR_HAVE_STDLIB_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif + +#ifdef BEOS +#include +#endif + +struct apr_other_child_rec_t { + apr_pool_t *p; + struct apr_other_child_rec_t *next; + apr_proc_t *proc; + void (*maintenance) (int, void *, int); + void *data; + apr_os_file_t write_fd; +}; + +#if defined(WIN32) || defined(NETWARE) +#define WSAHighByte 2 +#define WSALowByte 0 +#endif + +#endif /* ! MISC_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_networkio.h b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_networkio.h new file mode 100644 index 00000000..5f3189d9 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_networkio.h @@ -0,0 +1,145 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETWORK_IO_H +#define NETWORK_IO_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_network_io.h" +#include "apr_errno.h" +#include "apr_general.h" +#include "apr_lib.h" +#ifndef WAITIO_USES_POLL +#include "apr_poll.h" +#endif + +/* System headers the network I/O library needs */ +#if APR_HAVE_SYS_TYPES_H +#include +#endif +#if APR_HAVE_SYS_UIO_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#endif +#if APR_HAVE_ERRNO_H +#include +#endif +#if APR_HAVE_SYS_TIME_H +#include +#endif +#if APR_HAVE_UNISTD_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#if APR_HAVE_NETINET_TCP_H +#include +#endif +#if APR_HAVE_NETINET_SCTP_UIO_H +#include +#endif +#if APR_HAVE_NETINET_SCTP_H +#include +#endif +#if APR_HAVE_NETINET_IN_H +#include +#endif +#if APR_HAVE_ARPA_INET_H +#include +#endif +#if APR_HAVE_SYS_SOCKET_H +#include +#endif +#if APR_HAVE_SYS_SOCKIO_H +#include +#endif +#if APR_HAVE_NETDB_H +#include +#endif +#if APR_HAVE_FCNTL_H +#include +#endif +#if APR_HAVE_SYS_SENDFILE_H +#include +#endif +#if APR_HAVE_SYS_IOCTL_H +#include +#endif +/* End System Headers */ + +#ifndef HAVE_POLLIN +#define POLLIN 1 +#define POLLPRI 2 +#define POLLOUT 4 +#define POLLERR 8 +#define POLLHUP 16 +#define POLLNVAL 32 +#endif + +typedef struct sock_userdata_t sock_userdata_t; +struct sock_userdata_t { + sock_userdata_t *next; + const char *key; + void *data; +}; + +struct apr_socket_t { + apr_pool_t *pool; + int socketdes; + int type; + int protocol; + apr_sockaddr_t *local_addr; + apr_sockaddr_t *remote_addr; + apr_interval_time_t timeout; +#ifndef HAVE_POLL + int connected; +#endif +#if APR_HAVE_SOCKADDR_UN + int bound; +#endif + int local_port_unknown; + int local_interface_unknown; + int remote_addr_unknown; + apr_int32_t options; + apr_int32_t inherit; + sock_userdata_t *userdata; +#ifndef WAITIO_USES_POLL + /* if there is a timeout set, then this pollset is used */ + apr_pollset_t *pollset; +#endif +}; + +const char *apr_inet_ntop(int af, const void *src, char *dst, apr_size_t size); +int apr_inet_pton(int af, const char *src, void *dst); +void apr_sockaddr_vars_set(apr_sockaddr_t *, int, apr_port_t); + +#define apr_is_option_set(skt, option) \ + (((skt)->options & (option)) == (option)) + +#define apr_set_option(skt, option, on) \ + do { \ + if (on) \ + (skt)->options |= (option); \ + else \ + (skt)->options &= ~(option); \ + } while (0) + +#endif /* ! NETWORK_IO_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_poll_private.h b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_poll_private.h new file mode 100644 index 00000000..ff813123 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_poll_private.h @@ -0,0 +1,189 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ARCH_POLL_PRIVATE_H +#define APR_ARCH_POLL_PRIVATE_H + +#if HAVE_POLL_H +#include +#endif + +#if HAVE_SYS_POLL_H +#include +#endif + +#ifdef HAVE_PORT_CREATE +#include +#include +#endif + +#ifdef HAVE_KQUEUE +#include +#include +#include +#endif + +#ifdef HAVE_EPOLL +#include +#endif + +#ifdef NETWARE +#define HAS_SOCKETS(dt) (dt == APR_POLL_SOCKET) ? 1 : 0 +#define HAS_PIPES(dt) (dt == APR_POLL_FILE) ? 1 : 0 +#endif + +#if defined(HAVE_AIO_H) && defined(HAVE_AIO_MSGQ) +#define _AIO_OS390 /* enable a bunch of z/OS aio.h definitions */ +#include /* aiocb */ +#endif + +/* Choose the best method platform specific to use in apr_pollset */ +#ifdef HAVE_KQUEUE +#define POLLSET_USES_KQUEUE +#define POLLSET_DEFAULT_METHOD APR_POLLSET_KQUEUE +#elif defined(HAVE_PORT_CREATE) +#define POLLSET_USES_PORT +#define POLLSET_DEFAULT_METHOD APR_POLLSET_PORT +#elif defined(HAVE_EPOLL) +#define POLLSET_USES_EPOLL +#define POLLSET_DEFAULT_METHOD APR_POLLSET_EPOLL +#elif defined(HAVE_AIO_MSGQ) +#define POLLSET_USES_AIO_MSGQ +#define POLLSET_DEFAULT_METHOD APR_POLLSET_AIO_MSGQ +#elif defined(HAVE_POLL) +#define POLLSET_USES_POLL +#define POLLSET_DEFAULT_METHOD APR_POLLSET_POLL +#else +#define POLLSET_USES_SELECT +#define POLLSET_DEFAULT_METHOD APR_POLLSET_SELECT +#endif + +#ifdef WIN32 +#define POLL_USES_SELECT +#undef POLLSET_DEFAULT_METHOD +#define POLLSET_DEFAULT_METHOD APR_POLLSET_SELECT +#else +#ifdef HAVE_POLL +#define POLL_USES_POLL +#else +#define POLL_USES_SELECT +#endif +#endif + +#if defined(POLLSET_USES_KQUEUE) || defined(POLLSET_USES_EPOLL) || defined(POLLSET_USES_PORT) || defined(POLLSET_USES_AIO_MSGQ) + +#include "apr_ring.h" + +#if APR_HAS_THREADS +#include "apr_thread_mutex.h" +#define pollset_lock_rings() \ + if (pollset->flags & APR_POLLSET_THREADSAFE) \ + apr_thread_mutex_lock(pollset->p->ring_lock); +#define pollset_unlock_rings() \ + if (pollset->flags & APR_POLLSET_THREADSAFE) \ + apr_thread_mutex_unlock(pollset->p->ring_lock); +#else +#define pollset_lock_rings() +#define pollset_unlock_rings() +#endif + +typedef struct pfd_elem_t pfd_elem_t; + +struct pfd_elem_t { + APR_RING_ENTRY(pfd_elem_t) link; + apr_pollfd_t pfd; +#ifdef HAVE_PORT_CREATE + int on_query_ring; +#endif +}; + +#endif + +typedef struct apr_pollset_private_t apr_pollset_private_t; +typedef struct apr_pollset_provider_t apr_pollset_provider_t; +typedef struct apr_pollcb_provider_t apr_pollcb_provider_t; + +struct apr_pollset_t +{ + apr_pool_t *pool; + apr_uint32_t nelts; + apr_uint32_t nalloc; + apr_uint32_t flags; + /* Pipe descriptors used for wakeup */ + apr_file_t *wakeup_pipe[2]; + apr_pollfd_t wakeup_pfd; + apr_pollset_private_t *p; + const apr_pollset_provider_t *provider; +}; + +typedef union { +#if defined(HAVE_EPOLL) + struct epoll_event *epoll; +#endif +#if defined(HAVE_PORT_CREATE) + port_event_t *port; +#endif +#if defined(HAVE_KQUEUE) + struct kevent *ke; +#endif +#if defined(HAVE_POLL) + struct pollfd *ps; +#endif + void *undef; +} apr_pollcb_pset; + +struct apr_pollcb_t { + apr_pool_t *pool; + apr_uint32_t nelts; + apr_uint32_t nalloc; + apr_uint32_t flags; + /* Pipe descriptors used for wakeup */ + apr_file_t *wakeup_pipe[2]; + apr_pollfd_t wakeup_pfd; + int fd; + apr_pollcb_pset pollset; + apr_pollfd_t **copyset; + const apr_pollcb_provider_t *provider; +}; + +struct apr_pollset_provider_t { + apr_status_t (*create)(apr_pollset_t *, apr_uint32_t, apr_pool_t *, apr_uint32_t); + apr_status_t (*add)(apr_pollset_t *, const apr_pollfd_t *); + apr_status_t (*remove)(apr_pollset_t *, const apr_pollfd_t *); + apr_status_t (*poll)(apr_pollset_t *, apr_interval_time_t, apr_int32_t *, const apr_pollfd_t **); + apr_status_t (*cleanup)(apr_pollset_t *); + const char *name; +}; + +struct apr_pollcb_provider_t { + apr_status_t (*create)(apr_pollcb_t *, apr_uint32_t, apr_pool_t *, apr_uint32_t); + apr_status_t (*add)(apr_pollcb_t *, apr_pollfd_t *); + apr_status_t (*remove)(apr_pollcb_t *, apr_pollfd_t *); + apr_status_t (*poll)(apr_pollcb_t *, apr_interval_time_t, apr_pollcb_cb_t, void *); + apr_status_t (*cleanup)(apr_pollcb_t *); + const char *name; +}; + +/* + * Private functions used for the implementation of both apr_pollcb_* and + * apr_pollset_* + */ +apr_status_t apr_poll_create_wakeup_pipe(apr_pool_t *pool, apr_pollfd_t *pfd, + apr_file_t **wakeup_pipe); +apr_status_t apr_poll_close_wakeup_pipe(apr_file_t **wakeup_pipe); +void apr_poll_drain_wakeup_pipe(apr_file_t **wakeup_pipe); + +#endif /* APR_ARCH_POLL_PRIVATE_H */ diff --git a/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_proc_mutex.h b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_proc_mutex.h new file mode 100644 index 00000000..cfa0049f --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_proc_mutex.h @@ -0,0 +1,121 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PROC_MUTEX_H +#define PROC_MUTEX_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_proc_mutex.h" +#include "apr_pools.h" +#include "apr_portable.h" +#include "apr_file_io.h" +#include "apr_arch_file_io.h" +#include "apr_time.h" + +/* System headers required by Locks library */ +#if APR_HAVE_SYS_TYPES_H +#include +#endif +#if APR_HAVE_STDIO_H +#include +#endif +#if APR_HAVE_FCNTL_H +#include +#endif + +#ifdef HAVE_SYS_IPC_H +#include +#endif +#ifdef HAVE_SYS_SEM_H +#include +#endif +#ifdef HAVE_SYS_FILE_H +#include +#endif +#if APR_HAVE_STDLIB_H +#include +#endif +#if APR_HAVE_UNISTD_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#ifdef HAVE_SYS_MMAN_H +#include +#endif +#if APR_HAVE_PTHREAD_H +#include +#endif +/* End System Headers */ + +struct apr_proc_mutex_unix_lock_methods_t { + unsigned int flags; + apr_status_t (*create)(apr_proc_mutex_t *, const char *); + apr_status_t (*acquire)(apr_proc_mutex_t *); + apr_status_t (*tryacquire)(apr_proc_mutex_t *); + apr_status_t (*timedacquire)(apr_proc_mutex_t *, apr_interval_time_t); + apr_status_t (*release)(apr_proc_mutex_t *); + apr_status_t (*cleanup)(void *); + apr_status_t (*child_init)(apr_proc_mutex_t **, apr_pool_t *, const char *); + apr_status_t (*perms_set)(apr_proc_mutex_t *, apr_fileperms_t, apr_uid_t, apr_gid_t); + apr_lockmech_e mech; + const char *name; +}; +typedef struct apr_proc_mutex_unix_lock_methods_t apr_proc_mutex_unix_lock_methods_t; + +/* bit values for flags field in apr_unix_lock_methods_t */ +#define APR_PROCESS_LOCK_MECH_IS_GLOBAL 1 + +#if !APR_HAVE_UNION_SEMUN && defined(APR_HAS_SYSVSEM_SERIALIZE) +union semun { + int val; + struct semid_ds *buf; + unsigned short *array; +}; +#endif + +struct apr_proc_mutex_t { + apr_pool_t *pool; + const apr_proc_mutex_unix_lock_methods_t *meth; + int curr_locked; + char *fname; + + apr_os_proc_mutex_t os; /* Native mutex holder. */ + +#if APR_HAS_FCNTL_SERIALIZE || APR_HAS_FLOCK_SERIALIZE + apr_file_t *interproc; /* For apr_file_ calls on native fd. */ + int interproc_closing; /* whether the native fd is opened/closed with + * 'interproc' or apr_os_file_put()ed (hence + * needing an an explicit close for consistency + * with other methods). + */ +#endif +#if APR_HAS_PROC_PTHREAD_SERIALIZE + int pthread_refcounting; /* Whether the native mutex is refcounted or + * apr_os_proc_mutex_put()ed, which makes + * refcounting impossible/undesirable. + */ +#endif +}; + +void apr_proc_mutex_unix_setup_lock(void); + +#endif /* PROC_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_shm.h b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_shm.h new file mode 100644 index 00000000..e9d25cad --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_shm.h @@ -0,0 +1,74 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SHM_H +#define SHM_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_shm.h" +#include "apr_pools.h" +#include "apr_file_io.h" +#include "apr_network_io.h" +#include "apr_portable.h" + +#if APR_HAVE_UNISTD_H +#include +#endif +#ifdef HAVE_SYS_MMAN_H +#include +#endif +#ifdef HAVE_SYS_IPC_H +#include +#endif +#ifdef HAVE_SYS_MUTEX_H +#include +#endif +#ifdef HAVE_SYS_SHM_H +#include +#endif +#if !defined(SHM_R) +#define SHM_R 0400 +#endif +#if !defined(SHM_W) +#define SHM_W 0200 +#endif +#ifdef HAVE_SYS_FILE_H +#include +#endif + +/* Not all systems seem to have MAP_FAILED defined, but it should always + * just be (void *)-1. */ +#ifndef MAP_FAILED +#define MAP_FAILED ((void *)-1) +#endif + +struct apr_shm_t { + apr_pool_t *pool; + void *base; /* base real address */ + void *usable; /* base usable address */ + apr_size_t reqsize; /* requested segment size */ + apr_size_t realsize; /* actual segment size */ + const char *filename; /* NULL if anonymous */ +#if APR_USE_SHMEM_SHMGET || APR_USE_SHMEM_SHMGET_ANON + int shmid; /* shmem ID returned from shmget() */ + key_t shmkey; /* shmem key IPC_ANON or returned from ftok() */ +#endif +}; + +#endif /* SHM_H */ diff --git a/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_thread_cond.h b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_thread_cond.h new file mode 100644 index 00000000..5c2b51d1 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_thread_cond.h @@ -0,0 +1,42 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_COND_H +#define THREAD_COND_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_thread_mutex.h" +#include "apr_thread_cond.h" +#include "apr_pools.h" + +#if APR_HAVE_PTHREAD_H +#include +#endif + +/* XXX: Should we have a better autoconf search, something like + * APR_HAS_PTHREAD_COND? -aaron */ +#if APR_HAS_THREADS +struct apr_thread_cond_t { + apr_pool_t *pool; + pthread_cond_t cond; +}; +#endif + +#endif /* THREAD_COND_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_thread_mutex.h b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_thread_mutex.h new file mode 100644 index 00000000..4fe46c3b --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_thread_mutex.h @@ -0,0 +1,42 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_MUTEX_H +#define THREAD_MUTEX_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_thread_mutex.h" +#include "apr_thread_cond.h" +#include "apr_portable.h" +#include "apr_atomic.h" + +#if APR_HAVE_PTHREAD_H +#include +#endif + +#if APR_HAS_THREADS +struct apr_thread_mutex_t { + apr_pool_t *pool; + pthread_mutex_t mutex; + apr_thread_cond_t *cond; + int locked, num_waiters; +}; +#endif + +#endif /* THREAD_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_thread_rwlock.h b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_thread_rwlock.h new file mode 100644 index 00000000..2cb43af6 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_thread_rwlock.h @@ -0,0 +1,49 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_RWLOCK_H +#define THREAD_RWLOCK_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_thread_rwlock.h" +#include "apr_pools.h" + +#if APR_HAVE_PTHREAD_H +/* this gives us pthread_rwlock_t */ +#include +#endif + +#if APR_HAS_THREADS +#ifdef HAVE_PTHREAD_RWLOCKS + +struct apr_thread_rwlock_t { + apr_pool_t *pool; + pthread_rwlock_t rwlock; +}; + +#else + +struct apr_thread_rwlock_t { + apr_pool_t *pool; +}; +#endif + +#endif + +#endif /* THREAD_RWLOCK_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_threadproc.h b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_threadproc.h new file mode 100644 index 00000000..7a3b3c09 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/unix/apr_arch_threadproc.h @@ -0,0 +1,119 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr.h" +#include "apr_private.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" +#include "apr_arch_file_io.h" +#include "apr_perms_set.h" + +/* System headers required for thread/process library */ +#if APR_HAVE_PTHREAD_H +#include +#endif +#ifdef HAVE_SYS_RESOURCE_H +#include +#endif +#if APR_HAVE_SIGNAL_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#if APR_HAVE_SYS_WAIT_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#ifdef HAVE_SCHED_H +#include +#endif +/* End System Headers */ + + +#ifndef THREAD_PROC_H +#define THREAD_PROC_H + +#define SHELL_PATH "/bin/sh" + +#if APR_HAS_THREADS + +struct apr_thread_t { + apr_pool_t *pool; + pthread_t *td; + void *data; + apr_thread_start_t func; + apr_status_t exitval; +}; + +struct apr_threadattr_t { + apr_pool_t *pool; + pthread_attr_t attr; +}; + +struct apr_threadkey_t { + apr_pool_t *pool; + pthread_key_t key; +}; + +struct apr_thread_once_t { + pthread_once_t once; +}; + +#endif + +typedef struct apr_procattr_pscb_t apr_procattr_pscb_t; +struct apr_procattr_pscb_t { + struct apr_procattr_pscb_t *next; + apr_perms_setfn_t *perms_set_fn; + apr_fileperms_t perms; + const void *data; +}; + +struct apr_procattr_t { + apr_pool_t *pool; + apr_file_t *parent_in; + apr_file_t *child_in; + apr_file_t *parent_out; + apr_file_t *child_out; + apr_file_t *parent_err; + apr_file_t *child_err; + char *currdir; + apr_int32_t cmdtype; + apr_int32_t detached; +#ifdef RLIMIT_CPU + struct rlimit *limit_cpu; +#endif +#if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS) + struct rlimit *limit_mem; +#endif +#ifdef RLIMIT_NPROC + struct rlimit *limit_nproc; +#endif +#ifdef RLIMIT_NOFILE + struct rlimit *limit_nofile; +#endif + apr_child_errfn_t *errfn; + apr_int32_t errchk; + apr_uid_t uid; + apr_gid_t gid; + apr_procattr_pscb_t *perms_set_callbacks; +}; + +#endif /* ! THREAD_PROC_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_atime.h b/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_atime.h new file mode 100644 index 00000000..35f2041a --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_atime.h @@ -0,0 +1,63 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ATIME_H +#define ATIME_H + +#include "apr_private.h" +#include "apr_time.h" +#if APR_HAVE_TIME_H +#include +#endif + +struct atime_t { + apr_pool_t *cntxt; + apr_time_t currtime; + SYSTEMTIME *explodedtime; +}; + + +/* Number of micro-seconds between the beginning of the Windows epoch + * (Jan. 1, 1601) and the Unix epoch (Jan. 1, 1970) + */ +#define APR_DELTA_EPOCH_IN_USEC APR_TIME_C(11644473600000000); + + +static APR_INLINE void FileTimeToAprTime(apr_time_t *result, FILETIME *input) +{ + /* Convert FILETIME one 64 bit number so we can work with it. */ + *result = input->dwHighDateTime; + *result = (*result) << 32; + *result |= input->dwLowDateTime; + *result /= 10; /* Convert from 100 nano-sec periods to micro-seconds. */ + *result -= APR_DELTA_EPOCH_IN_USEC; /* Convert from Windows epoch to Unix epoch */ + return; +} + + +static APR_INLINE void AprTimeToFileTime(LPFILETIME pft, apr_time_t t) +{ + LONGLONG ll; + t += APR_DELTA_EPOCH_IN_USEC; + ll = t * 10; + pft->dwLowDateTime = (DWORD)ll; + pft->dwHighDateTime = (DWORD) (ll >> 32); + return; +} + + +#endif /* ! ATIME_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_dso.h b/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_dso.h new file mode 100644 index 00000000..e2e4e40f --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_dso.h @@ -0,0 +1,36 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_dso.h" +#include "apr.h" + +#if APR_HAS_DSO + +struct apr_dso_handle_t { + apr_pool_t *cont; + void *handle; + apr_status_t load_error; +}; + +#endif + +#endif diff --git a/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_file_io.h b/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_file_io.h new file mode 100644 index 00000000..9fb8df19 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_file_io.h @@ -0,0 +1,266 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FILE_IO_H +#define FILE_IO_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_pools.h" +#include "apr_general.h" +#include "apr_tables.h" +#include "apr_thread_mutex.h" +#include "apr_file_io.h" +#include "apr_file_info.h" +#include "apr_errno.h" +#include "apr_arch_misc.h" +#include "apr_poll.h" + +#ifdef HAVE_SYS_STAT_H +#include +#endif +#if APR_HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_FCNTL_H +#include +#endif +#ifdef HAVE_TIME_H +#include +#endif +#if APR_HAVE_DIRENT_H +#include +#endif +#ifdef HAVE_MALLOC_H +#include +#endif + +#if APR_HAS_UNICODE_FS +#include "arch/win32/apr_arch_utf8.h" +#include + +/* Helper functions for the WinNT ApiW() functions. APR treats all + * resource identifiers (files, etc) by their UTF-8 name, to provide + * access to all named identifiers. [UTF-8 completely maps Unicode + * into char type strings.] + * + * The _path flavors below provide us fast mappings of the + * Unicode filename //?/D:/path and //?/UNC/mach/share/path mappings, + * which allow unlimited (well, 32000 wide character) length names. + * These prefixes may appear in Unicode, but must not appear in the + * Ascii API calls. So we tack them on in utf8_to_unicode_path, and + * strip them right back off in unicode_to_utf8_path. + */ +apr_status_t utf8_to_unicode_path(apr_wchar_t* dststr, apr_size_t dstchars, + const char* srcstr); +apr_status_t unicode_to_utf8_path(char* dststr, apr_size_t dstchars, + const apr_wchar_t* srcstr); + +#endif /* APR_HAS_UNICODE_FS */ + +/* Another Helper functions for the WinNT ApiW() functions. We need to + * derive some 'resource' names (max length 255 characters, prefixed with + * Global/ or Local/ on WinNT) from something that looks like a filename. + * Since 'resource' names never contain slashes, convert these to '_'s + * and return the appropriate char* or wchar* for ApiA or ApiW calls. + */ + +void *res_name_from_filename(const char *file, int global, apr_pool_t *pool); + +#define APR_FILE_MAX MAX_PATH + +#define APR_FILE_DEFAULT_BUFSIZE 4096 +/* For backwards-compat */ +#define APR_FILE_BUFSIZE APR_FILE_DEFAULT_BUFSIZE + +/* obscure ommissions from msvc's sys/stat.h */ +#ifdef _MSC_VER +#define S_IFIFO _S_IFIFO /* pipe */ +#define S_IFBLK 0060000 /* Block Special */ +#define S_IFLNK 0120000 /* Symbolic Link */ +#define S_IFSOCK 0140000 /* Socket */ +#define S_IFWHT 0160000 /* Whiteout */ +#endif + +/* Internal Flags for apr_file_open */ +#define APR_OPENINFO 0x00100000 /* Open without READ or WRITE access */ +#define APR_OPENLINK 0x00200000 /* Open a link itself, if supported */ +#define APR_READCONTROL 0x00400000 /* Read the file's owner/perms */ +#define APR_WRITECONTROL 0x00800000 /* Modify the file's owner/perms */ +/* #define APR_INHERIT 0x01000000 -- Defined in apr_arch_inherit.h! */ +#define APR_STDIN_FLAG 0x02000000 /* Obtained via apr_file_open_stdin() */ +#define APR_STDOUT_FLAG 0x04000000 /* Obtained via apr_file_open_stdout() */ +#define APR_STDERR_FLAG 0x06000000 /* Obtained via apr_file_open_stderr() */ +#define APR_STD_FLAGS (APR_STDIN_FLAG | APR_STDOUT_FLAG | APR_STDERR_FLAG) +#define APR_WRITEATTRS 0x08000000 /* Modify the file's attributes */ + +/* Entries missing from the MSVC 5.0 Win32 SDK: + */ +#ifndef FILE_ATTRIBUTE_DEVICE +#define FILE_ATTRIBUTE_DEVICE 0x00000040 +#endif +#ifndef FILE_ATTRIBUTE_REPARSE_POINT +#define FILE_ATTRIBUTE_REPARSE_POINT 0x00000400 +#endif +#ifndef FILE_FLAG_OPEN_NO_RECALL +#define FILE_FLAG_OPEN_NO_RECALL 0x00100000 +#endif +#ifndef FILE_FLAG_OPEN_REPARSE_POINT +#define FILE_FLAG_OPEN_REPARSE_POINT 0x00200000 +#endif +#ifndef TRUSTEE_IS_WELL_KNOWN_GROUP +#define TRUSTEE_IS_WELL_KNOWN_GROUP 5 +#endif + +/* Information bits available from the WIN32 FindFirstFile function */ +#define APR_FINFO_WIN32_DIR (APR_FINFO_NAME | APR_FINFO_TYPE \ + | APR_FINFO_CTIME | APR_FINFO_ATIME \ + | APR_FINFO_MTIME | APR_FINFO_SIZE) + +/* Sneak the Readonly bit through finfo->protection for internal use _only_ */ +#define APR_FREADONLY 0x10000000 + +/* Private function for apr_stat/lstat/getfileinfo/dir_read */ +int fillin_fileinfo(apr_finfo_t *finfo, WIN32_FILE_ATTRIBUTE_DATA *wininfo, + int byhandle, int finddata, const char *fname, + apr_int32_t wanted); + +/* Private function that extends apr_stat/lstat/getfileinfo/dir_read */ +apr_status_t more_finfo(apr_finfo_t *finfo, const void *ufile, + apr_int32_t wanted, int whatfile); + +/* whatfile types for the ufile arg */ +#define MORE_OF_HANDLE 0 +#define MORE_OF_FSPEC 1 +#define MORE_OF_WFSPEC 2 + +/* quick run-down of fields in windows' apr_file_t structure that may have + * obvious uses. + * fname -- the filename as passed to the open call. + * dwFileAttricutes -- Attributes used to open the file. + * append -- Windows doesn't support the append concept when opening files. + * APR needs to keep track of this, and always make sure we append + * correctly when writing to a file with this flag set TRUE. + */ + +/* for apr_poll.c */ +#define filedes filehand + +struct apr_file_t { + apr_pool_t *pool; + HANDLE filehand; + BOOLEAN pipe; /* Is this a pipe of a file? */ + OVERLAPPED *pOverlapped; + apr_interval_time_t timeout; + apr_int32_t flags; + + /* File specific info */ + apr_finfo_t *finfo; + char *fname; + DWORD dwFileAttributes; + int eof_hit; + BOOLEAN buffered; /* Use buffered I/O? */ + int ungetchar; /* Last char provided by an unget op. (-1 = no char) */ + int append; + + /* Stuff for buffered mode */ + char *buffer; + apr_size_t bufpos; /* Read/Write position in buffer */ + apr_size_t bufsize; /* The size of the buffer */ + apr_size_t dataRead; /* amount of valid data read into buffer */ + int direction; /* buffer being used for 0 = read, 1 = write */ + apr_off_t filePtr; /* position in file of handle */ + apr_thread_mutex_t *mutex; /* mutex semaphore, must be owned to access + * the above fields */ + +#if APR_FILES_AS_SOCKETS + /* if there is a timeout set, then this pollset is used */ + apr_pollset_t *pollset; +#endif + /* Pipe specific info */ +}; + +struct apr_dir_t { + apr_pool_t *pool; + HANDLE dirhand; + apr_size_t rootlen; + char *dirname; + char *name; + union { +#if APR_HAS_UNICODE_FS + struct { + WIN32_FIND_DATAW *entry; + } w; +#endif +#if APR_HAS_ANSI_FS + struct { + WIN32_FIND_DATAA *entry; + } n; +#endif + }; + int bof; +}; + +/* There are many goofy characters the filesystem can't accept + * or can confound the cmd.exe shell. Here's the list + * [declared in filesys.c] + */ +extern const char apr_c_is_fnchar[256]; + +#define IS_FNCHAR(c) (apr_c_is_fnchar[(unsigned char)(c)] & 1) +#define IS_SHCHAR(c) ((apr_c_is_fnchar[(unsigned char)(c)] & 2) == 2) + + +/* If the user passes APR_FILEPATH_TRUENAME to either + * apr_filepath_root or apr_filepath_merge, this fn determines + * that the root really exists. It's expensive, wouldn't want + * to do this too frequenly. + */ +apr_status_t filepath_root_test(char *path, apr_pool_t *p); + + +/* The apr_filepath_merge wants to canonicalize the cwd to the + * addpath if the user passes NULL as the old root path (this + * isn't true of an empty string "", which won't be concatenated. + * + * But we need to figure out what the cwd of a given volume is, + * when the user passes D:foo. This fn will determine D:'s cwd. + * + * If flags includes the bit APR_FILEPATH_NATIVE, the path returned + * is in the os-native format. + */ +apr_status_t filepath_drive_get(char **rootpath, char drive, + apr_int32_t flags, apr_pool_t *p); + + +/* If the user passes d: vs. D: (or //mach/share vs. //MACH/SHARE), + * we need to fold the case to canonical form. This function is + * supposed to do so. + */ +apr_status_t filepath_root_case(char **rootpath, char *root, apr_pool_t *p); + + +apr_status_t file_cleanup(void *); + +extern apr_status_t +apr_file_socket_pipe_create(apr_file_t **in, + apr_file_t **out, + apr_pool_t *p); + +extern apr_status_t +apr_file_socket_pipe_close(apr_file_t *file); + +#endif /* ! FILE_IO_H */ diff --git a/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_inherit.h b/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_inherit.h new file mode 100644 index 00000000..8969af66 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_inherit.h @@ -0,0 +1,123 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INHERIT_H +#define INHERIT_H + +#include "apr_inherit.h" + +#define APR_INHERIT (1 << 24) /* Must not conflict with other bits */ + +#if APR_HAS_UNICODE_FS && APR_HAS_ANSI_FS +/* !defined(_WIN32_WCE) is implicit here */ + +#define APR_IMPLEMENT_INHERIT_SET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_set(apr_##name##_t *the##name) \ +{ \ + IF_WIN_OS_IS_UNICODE \ + { \ +/* if (!SetHandleInformation(the##name->filehand, \ + * HANDLE_FLAG_INHERIT, \ + * HANDLE_FLAG_INHERIT)) \ + * return apr_get_os_error(); \ + */ } \ + ELSE_WIN_OS_IS_ANSI \ + { \ + HANDLE temp, hproc = GetCurrentProcess(); \ + if (!DuplicateHandle(hproc, the##name->filehand, \ + hproc, &temp, 0, TRUE, \ + DUPLICATE_SAME_ACCESS)) \ + return apr_get_os_error(); \ + CloseHandle(the##name->filehand); \ + the##name->filehand = temp; \ + } \ + return APR_SUCCESS; \ +} + +#define APR_IMPLEMENT_INHERIT_UNSET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_unset(apr_##name##_t *the##name)\ +{ \ + IF_WIN_OS_IS_UNICODE \ + { \ +/* if (!SetHandleInformation(the##name->filehand, \ + * HANDLE_FLAG_INHERIT, 0)) \ + * return apr_get_os_error(); \ + */ } \ + ELSE_WIN_OS_IS_ANSI \ + { \ + HANDLE temp, hproc = GetCurrentProcess(); \ + if (!DuplicateHandle(hproc, the##name->filehand, \ + hproc, &temp, 0, FALSE, \ + DUPLICATE_SAME_ACCESS)) \ + return apr_get_os_error(); \ + CloseHandle(the##name->filehand); \ + the##name->filehand = temp; \ + } \ + return APR_SUCCESS; \ +} + +#elif APR_HAS_ANSI_FS || defined(_WIN32_WCE) + +#define APR_IMPLEMENT_INHERIT_SET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_set(apr_##name##_t *the##name) \ +{ \ + HANDLE temp, hproc = GetCurrentProcess(); \ + if (!DuplicateHandle(hproc, the##name->filehand, \ + hproc, &temp, 0, TRUE, \ + DUPLICATE_SAME_ACCESS)) \ + return apr_get_os_error(); \ + CloseHandle(the##name->filehand); \ + the##name->filehand = temp; \ + return APR_SUCCESS; \ +} + +#define APR_IMPLEMENT_INHERIT_UNSET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_unset(apr_##name##_t *the##name)\ +{ \ + HANDLE temp, hproc = GetCurrentProcess(); \ + if (!DuplicateHandle(hproc, the##name->filehand, \ + hproc, &temp, 0, FALSE, \ + DUPLICATE_SAME_ACCESS)) \ + return apr_get_os_error(); \ + CloseHandle(the##name->filehand); \ + the##name->filehand = temp; \ + return APR_SUCCESS; \ +} + +#else /* APR_HAS_UNICODE_FS && !APR_HAS_ANSI_FS && !defined(_WIN32_WCE) */ + +#define APR_IMPLEMENT_INHERIT_SET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_set(apr_##name##_t *the##name) \ +{ \ +/* if (!SetHandleInformation(the##name->filehand, \ + * HANDLE_FLAG_INHERIT, \ + * HANDLE_FLAG_INHERIT)) \ + * return apr_get_os_error(); \ + */ return APR_SUCCESS; \ +} + +#define APR_IMPLEMENT_INHERIT_UNSET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_unset(apr_##name##_t *the##name)\ +{ \ +/* if (!SetHandleInformation(the##name->filehand, \ + * HANDLE_FLAG_INHERIT, 0)) \ + * return apr_get_os_error(); \ + */ return APR_SUCCESS; \ +} + +#endif /* defined(APR_HAS_UNICODE_FS) */ + +#endif /* ! INHERIT_H */ diff --git a/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_misc.h b/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_misc.h new file mode 100644 index 00000000..15312adf --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_misc.h @@ -0,0 +1,509 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MISC_H +#define MISC_H + +#include "apr.h" +#include "apr_portable.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_getopt.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" +#include "apr_errno.h" +#include "apr_getopt.h" + +#if APR_HAVE_STDIO_H +#include +#endif +#if APR_HAVE_SIGNAL_H +#include +#endif +#if APR_HAVE_PTHREAD_H +#include +#endif +#if APR_HAVE_STDLIB_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#ifndef _WIN32_WCE +#include +#endif + +#if defined(HAVE_IF_INDEXTONAME) && defined(_MSC_VER) +#include +#endif + +struct apr_other_child_rec_t { + apr_pool_t *p; + struct apr_other_child_rec_t *next; + apr_proc_t *proc; + void (*maintenance) (int, void *, int); + void *data; + apr_os_file_t write_fd; +}; + +#define WSAHighByte 2 +#define WSALowByte 0 + +/* start.c and apr_app.c helpers and communication within misc.c + * + * They are not for public consumption, although apr_app_init_complete + * must be an exported symbol to avoid reinitialization. + */ +extern int APR_DECLARE_DATA apr_app_init_complete; + +int apr_wastrtoastr(char const * const * *retarr, + wchar_t const * const *arr, int args); + +/* Platform specific designation of run time os version. + * Gaps allow for specific service pack levels that + * export new kernel or winsock functions or behavior. + */ +typedef enum { + APR_WIN_UNK = 0, + APR_WIN_UNSUP = 1, + APR_WIN_95 = 10, + APR_WIN_95_B = 11, + APR_WIN_95_OSR2 = 12, + APR_WIN_98 = 14, + APR_WIN_98_SE = 16, + APR_WIN_ME = 18, + + APR_WIN_UNICODE = 20, /* Prior versions support only narrow chars */ + + APR_WIN_CE_3 = 23, /* CE is an odd beast, not supporting */ + /* some pre-NT features, such as the */ + APR_WIN_NT = 30, /* narrow charset APIs (fooA fns), while */ + APR_WIN_NT_3_5 = 35, /* not supporting some NT-family features. */ + APR_WIN_NT_3_51 = 36, + + APR_WIN_NT_4 = 40, + APR_WIN_NT_4_SP2 = 42, + APR_WIN_NT_4_SP3 = 43, + APR_WIN_NT_4_SP4 = 44, + APR_WIN_NT_4_SP5 = 45, + APR_WIN_NT_4_SP6 = 46, + + APR_WIN_2000 = 50, + APR_WIN_2000_SP1 = 51, + APR_WIN_2000_SP2 = 52, + APR_WIN_XP = 60, + APR_WIN_XP_SP1 = 61, + APR_WIN_XP_SP2 = 62, + APR_WIN_2003 = 70, + APR_WIN_VISTA = 80, + APR_WIN_7 = 90 +} apr_oslevel_e; + +extern APR_DECLARE_DATA apr_oslevel_e apr_os_level; + +apr_status_t apr_get_oslevel(apr_oslevel_e *); + +/* The APR_HAS_ANSI_FS symbol is PRIVATE, and internal to APR. + * APR only supports char data for filenames. Like most applications, + * characters >127 are essentially undefined. APR_HAS_UNICODE_FS lets + * the application know that utf-8 is the encoding method of APR, and + * only incidently hints that we have Wide OS calls. + * + * APR_HAS_ANSI_FS is simply an OS flag to tell us all calls must be + * the unicode eqivilant. + */ + +#if defined(_WIN32_WCE) || defined(WINNT) +#define APR_HAS_ANSI_FS 0 +#else +#define APR_HAS_ANSI_FS 1 +#endif + +/* IF_WIN_OS_IS_UNICODE / ELSE_WIN_OS_IS_ANSI help us keep the code trivial + * where have runtime tests for unicode-ness, that aren't needed in any + * build which supports only WINNT or WCE. + */ +#if APR_HAS_ANSI_FS && APR_HAS_UNICODE_FS +#define IF_WIN_OS_IS_UNICODE if (apr_os_level >= APR_WIN_UNICODE) +#define ELSE_WIN_OS_IS_ANSI else +#else /* APR_HAS_UNICODE_FS */ +#define IF_WIN_OS_IS_UNICODE +#define ELSE_WIN_OS_IS_ANSI +#endif /* WINNT */ + +#if defined(_MSC_VER) && !defined(_WIN32_WCE) +#include "crtdbg.h" + +static APR_INLINE void* apr_malloc_dbg(size_t size, const char* filename, + int linenumber) +{ + return _malloc_dbg(size, _CRT_BLOCK, filename, linenumber); +} + +static APR_INLINE void* apr_realloc_dbg(void* userData, size_t newSize, + const char* filename, int linenumber) +{ + return _realloc_dbg(userData, newSize, _CRT_BLOCK, filename, linenumber); +} + +#else + +static APR_INLINE void* apr_malloc_dbg(size_t size, const char* filename, + int linenumber) +{ + return malloc(size); +} + +static APR_INLINE void* apr_realloc_dbg(void* userData, size_t newSize, + const char* filename, int linenumber) +{ + return realloc(userData, newSize); +} + +#endif /* ! _MSC_VER */ + +typedef enum { + DLL_WINBASEAPI = 0, /* kernel32 From WinBase.h */ + DLL_WINADVAPI = 1, /* advapi32 From WinBase.h */ + DLL_WINSOCKAPI = 2, /* mswsock From WinSock.h */ + DLL_WINSOCK2API = 3, /* ws2_32 From WinSock2.h */ + DLL_SHSTDAPI = 4, /* shell32 From ShellAPI.h */ + DLL_NTDLL = 5, /* ntdll From our real kernel */ + DLL_IPHLPAPI = 6, /* Iphlpapi From Iphlpapi.h */ + DLL_defined = 7 /* must define as last idx_ + 1 */ +} apr_dlltoken_e; + +FARPROC apr_load_dll_func(apr_dlltoken_e fnLib, char *fnName, int ordinal); + +/* The apr_load_dll_func call WILL return 0 set error to + * ERROR_INVALID_FUNCTION if the function cannot be loaded + */ +#define APR_DECLARE_LATE_DLL_FUNC(lib, rettype, calltype, fn, ord, args, names) \ + typedef rettype (calltype *apr_winapi_fpt_##fn) args; \ + static apr_winapi_fpt_##fn apr_winapi_pfn_##fn = NULL; \ + static int apr_winapi_chk_##fn = 0; \ + static APR_INLINE int apr_winapi_ld_##fn(void) \ + { if (apr_winapi_pfn_##fn) return 1; \ + if (apr_winapi_chk_##fn ++) return 0; \ + if (!apr_winapi_pfn_##fn) \ + apr_winapi_pfn_##fn = (apr_winapi_fpt_##fn) \ + apr_load_dll_func(lib, #fn, ord); \ + if (apr_winapi_pfn_##fn) return 1; else return 0; }; \ + static APR_INLINE rettype apr_winapi_##fn args \ + { if (apr_winapi_ld_##fn()) \ + return (*(apr_winapi_pfn_##fn)) names; \ + else { SetLastError(ERROR_INVALID_FUNCTION); return 0;} }; \ + +#define APR_HAVE_LATE_DLL_FUNC(fn) apr_winapi_ld_##fn() + +/* Provide late bound declarations of every API function missing from + * one or more supported releases of the Win32 API + * + * lib is the enumerated token from apr_dlltoken_e, and must correspond + * to the string table entry in start.c used by the apr_load_dll_func(). + * Token names (attempt to) follow Windows.h declarations prefixed by DLL_ + * in order to facilitate comparison. Use the exact declaration syntax + * and names from Windows.h to prevent ambigutity and bugs. + * + * rettype and calltype follow the original declaration in Windows.h + * fn is the true function name - beware Ansi/Unicode #defined macros + * ord is the ordinal within the library, use 0 if it varies between versions + * args is the parameter list following the original declaration, in parens + * names is the parameter list sans data types, enclosed in parens + * + * #undef/re#define the Ansi/Unicode generic name to abate confusion + * In the case of non-text functions, simply #define the original name + */ + +#if !defined(_WIN32_WCE) && !defined(WINNT) +/* This group is available to all versions of WINNT 4.0 SP6 and later */ + +#ifdef GetFileAttributesExA +#undef GetFileAttributesExA +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, GetFileAttributesExA, 0, ( + IN LPCSTR lpFileName, + IN GET_FILEEX_INFO_LEVELS fInfoLevelId, + OUT LPVOID lpFileInformation), + (lpFileName, fInfoLevelId, lpFileInformation)); +#define GetFileAttributesExA apr_winapi_GetFileAttributesExA +#undef GetFileAttributesEx +#define GetFileAttributesEx apr_winapi_GetFileAttributesExA + +#ifdef GetFileAttributesExW +#undef GetFileAttributesExW +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, GetFileAttributesExW, 0, ( + IN LPCWSTR lpFileName, + IN GET_FILEEX_INFO_LEVELS fInfoLevelId, + OUT LPVOID lpFileInformation), + (lpFileName, fInfoLevelId, lpFileInformation)); +#define GetFileAttributesExW apr_winapi_GetFileAttributesExW + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, CancelIo, 0, ( + IN HANDLE hFile), + (hFile)); +#define CancelIo apr_winapi_CancelIo + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, TryEnterCriticalSection, 0, ( + LPCRITICAL_SECTION lpCriticalSection), + (lpCriticalSection)); +#define TryEnterCriticalSection apr_winapi_TryEnterCriticalSection + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, SwitchToThread, 0, ( + void), + ()); +#define SwitchToThread apr_winapi_SwitchToThread + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINADVAPI, BOOL, WINAPI, GetEffectiveRightsFromAclW, 0, ( + IN PACL pacl, + IN PTRUSTEE_W pTrustee, + OUT PACCESS_MASK pAccessRights), + (pacl, pTrustee, pAccessRights)); +#define GetEffectiveRightsFromAclW apr_winapi_GetEffectiveRightsFromAclW + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINADVAPI, BOOL, WINAPI, GetNamedSecurityInfoW, 0, ( + IN LPWSTR pObjectName, + IN SE_OBJECT_TYPE ObjectType, + IN SECURITY_INFORMATION SecurityInfo, + OUT PSID *ppsidOwner, + OUT PSID *ppsidGroup, + OUT PACL *ppDacl, + OUT PACL *ppSacl, + OUT PSECURITY_DESCRIPTOR *ppSecurityDescriptor), + (pObjectName, ObjectType, SecurityInfo, ppsidOwner, ppsidGroup, + ppDacl, ppSacl, ppSecurityDescriptor)); +#define GetNamedSecurityInfoW apr_winapi_GetNamedSecurityInfoW + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINADVAPI, BOOL, WINAPI, GetNamedSecurityInfoA, 0, ( + IN LPSTR pObjectName, + IN SE_OBJECT_TYPE ObjectType, + IN SECURITY_INFORMATION SecurityInfo, + OUT PSID *ppsidOwner, + OUT PSID *ppsidGroup, + OUT PACL *ppDacl, + OUT PACL *ppSacl, + OUT PSECURITY_DESCRIPTOR *ppSecurityDescriptor), + (pObjectName, ObjectType, SecurityInfo, ppsidOwner, ppsidGroup, + ppDacl, ppSacl, ppSecurityDescriptor)); +#define GetNamedSecurityInfoA apr_winapi_GetNamedSecurityInfoA +#undef GetNamedSecurityInfo +#define GetNamedSecurityInfo apr_winapi_GetNamedSecurityInfoA + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINADVAPI, BOOL, WINAPI, GetSecurityInfo, 0, ( + IN HANDLE handle, + IN SE_OBJECT_TYPE ObjectType, + IN SECURITY_INFORMATION SecurityInfo, + OUT PSID *ppsidOwner, + OUT PSID *ppsidGroup, + OUT PACL *ppDacl, + OUT PACL *ppSacl, + OUT PSECURITY_DESCRIPTOR *ppSecurityDescriptor), + (handle, ObjectType, SecurityInfo, ppsidOwner, ppsidGroup, + ppDacl, ppSacl, ppSecurityDescriptor)); +#define GetSecurityInfo apr_winapi_GetSecurityInfo + +APR_DECLARE_LATE_DLL_FUNC(DLL_SHSTDAPI, LPWSTR *, WINAPI, CommandLineToArgvW, 0, ( + LPCWSTR lpCmdLine, + int *pNumArgs), + (lpCmdLine, pNumArgs)); +#define CommandLineToArgvW apr_winapi_CommandLineToArgvW + +#endif /* !defined(_WIN32_WCE) && !defined(WINNT) */ + +#if !defined(_WIN32_WCE) +/* This group is NOT available to all versions of WinNT, + * these we must always look up + */ + +#ifdef GetCompressedFileSizeA +#undef GetCompressedFileSizeA +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, DWORD, WINAPI, GetCompressedFileSizeA, 0, ( + IN LPCSTR lpFileName, + OUT LPDWORD lpFileSizeHigh), + (lpFileName, lpFileSizeHigh)); +#define GetCompressedFileSizeA apr_winapi_GetCompressedFileSizeA +#undef GetCompressedFileSize +#define GetCompressedFileSize apr_winapi_GetCompressedFileSizeA + +#ifdef GetCompressedFileSizeW +#undef GetCompressedFileSizeW +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, DWORD, WINAPI, GetCompressedFileSizeW, 0, ( + IN LPCWSTR lpFileName, + OUT LPDWORD lpFileSizeHigh), + (lpFileName, lpFileSizeHigh)); +#define GetCompressedFileSizeW apr_winapi_GetCompressedFileSizeW + + +APR_DECLARE_LATE_DLL_FUNC(DLL_NTDLL, LONG, WINAPI, NtQueryTimerResolution, 0, ( + ULONG *pMaxRes, /* Minimum NS Resolution */ + ULONG *pMinRes, /* Maximum NS Resolution */ + ULONG *pCurRes), /* Current NS Resolution */ + (pMaxRes, pMinRes, pCurRes)); +#define QueryTimerResolution apr_winapi_NtQueryTimerResolution + +APR_DECLARE_LATE_DLL_FUNC(DLL_NTDLL, LONG, WINAPI, NtSetTimerResolution, 0, ( + ULONG ReqRes, /* Requested NS Clock Resolution */ + BOOL Acquire, /* Aquire (1) or Release (0) our interest */ + ULONG *pNewRes), /* The NS Clock Resolution granted */ + (ReqRes, Acquire, pNewRes)); +#define SetTimerResolution apr_winapi_NtSetTimerResolution + +typedef struct PBI { + LONG ExitStatus; + PVOID PebBaseAddress; + apr_uintptr_t AffinityMask; + LONG BasePriority; + apr_uintptr_t UniqueProcessId; + apr_uintptr_t InheritedFromUniqueProcessId; +} PBI, *PPBI; + +APR_DECLARE_LATE_DLL_FUNC(DLL_NTDLL, LONG, WINAPI, NtQueryInformationProcess, 0, ( + HANDLE hProcess, /* Obvious */ + INT info, /* Use 0 for PBI documented above */ + PVOID pPI, /* The PIB buffer */ + ULONG LenPI, /* Use sizeof(PBI) */ + ULONG *pSizePI), /* returns pPI buffer used (may pass NULL) */ + (hProcess, info, pPI, LenPI, pSizePI)); +#define QueryInformationProcess apr_winapi_NtQueryInformationProcess + +APR_DECLARE_LATE_DLL_FUNC(DLL_NTDLL, LONG, WINAPI, NtQueryObject, 0, ( + HANDLE hObject, /* Obvious */ + INT info, /* Use 0 for PBI documented above */ + PVOID pOI, /* The PIB buffer */ + ULONG LenOI, /* Use sizeof(PBI) */ + ULONG *pSizeOI), /* returns pPI buffer used (may pass NULL) */ + (hObject, info, pOI, LenOI, pSizeOI)); +#define QueryObject apr_winapi_NtQueryObject + +typedef struct IOSB { + union { + UINT Status; + PVOID reserved; + }; + apr_uintptr_t Information; /* Varies by op, consumed buffer size for FSI below */ +} IOSB, *PIOSB; + +typedef struct FSI { + LONGLONG AllocationSize; + LONGLONG EndOfFile; + ULONG NumberOfLinks; + BOOL DeletePending; + BOOL Directory; +} FSI, *PFSI; + +APR_DECLARE_LATE_DLL_FUNC(DLL_NTDLL, LONG, WINAPI, ZwQueryInformationFile, 0, ( + HANDLE hObject, /* Obvious */ + PVOID pIOSB, /* Point to the IOSB buffer for detailed return results */ + PVOID pFI, /* The buffer, using FIB above */ + ULONG LenFI, /* Use sizeof(FI) */ + ULONG info), /* Use 5 for FSI documented above*/ + (hObject, pIOSB, pFI, LenFI, info)); +#define ZwQueryInformationFile apr_winapi_ZwQueryInformationFile + +#ifdef CreateToolhelp32Snapshot +#undef CreateToolhelp32Snapshot +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, HANDLE, WINAPI, CreateToolhelp32Snapshot, 0, ( + DWORD dwFlags, + DWORD th32ProcessID), + (dwFlags, th32ProcessID)); +#define CreateToolhelp32Snapshot apr_winapi_CreateToolhelp32Snapshot + +#ifdef Process32FirstW +#undef Process32FirstW +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, Process32FirstW, 0, ( + HANDLE hSnapshot, + LPPROCESSENTRY32W lppe), + (hSnapshot, lppe)); +#define Process32FirstW apr_winapi_Process32FirstW + +#ifdef Process32NextW +#undef Process32NextW +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, Process32NextW, 0, ( + HANDLE hSnapshot, + LPPROCESSENTRY32W lppe), + (hSnapshot, lppe)); +#define Process32NextW apr_winapi_Process32NextW + +#if !defined(POLLERR) +/* Event flag definitions for WSAPoll(). */ +#define POLLRDNORM 0x0100 +#define POLLRDBAND 0x0200 +#define POLLIN (POLLRDNORM | POLLRDBAND) +#define POLLPRI 0x0400 + +#define POLLWRNORM 0x0010 +#define POLLOUT (POLLWRNORM) +#define POLLWRBAND 0x0020 + +#define POLLERR 0x0001 +#define POLLHUP 0x0002 +#define POLLNVAL 0x0004 + +typedef struct pollfd { + SOCKET fd; + SHORT events; + SHORT revents; + +} WSAPOLLFD, *PWSAPOLLFD, FAR *LPWSAPOLLFD; + +#endif /* !defined(POLLERR) */ +#ifdef WSAPoll +#undef WSAPoll +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINSOCK2API, int, WSAAPI, WSAPoll, 0, ( + IN OUT LPWSAPOLLFD fdArray, + IN ULONG fds, + IN INT timeout), + (fdArray, fds, timeout)); +#define WSAPoll apr_winapi_WSAPoll +#define HAVE_POLL 1 + +#ifdef SetDllDirectoryW +#undef SetDllDirectoryW +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, SetDllDirectoryW, 0, ( + IN LPCWSTR lpPathName), + (lpPathName)); +#define SetDllDirectoryW apr_winapi_SetDllDirectoryW + +#ifdef if_nametoindex +#undef if_nametoindex +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_IPHLPAPI, NET_IFINDEX, WINAPI, if_nametoindex, 0, ( + IN PCSTR InterfaceName), + (InterfaceName)); +#define if_nametoindex apr_winapi_if_nametoindex + +#ifdef if_indextoname +#undef if_indextoname +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_IPHLPAPI, PCHAR, NETIOAPI_API_, if_indextoname, 0, ( + NET_IFINDEX InterfaceIndex, + PCHAR InterfaceName), + (InterfaceIndex, InterfaceName)); +#define if_indextoname apr_winapi_if_indextoname + +#endif /* !defined(_WIN32_WCE) */ + +#endif /* ! MISC_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_networkio.h b/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_networkio.h new file mode 100644 index 00000000..04be5559 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_networkio.h @@ -0,0 +1,90 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETWORK_IO_H +#define NETWORK_IO_H + +#include "apr_network_io.h" +#include "apr_general.h" +#include "apr_poll.h" + +typedef struct sock_userdata_t sock_userdata_t; +struct sock_userdata_t { + sock_userdata_t *next; + const char *key; + void *data; +}; + +struct apr_socket_t { + apr_pool_t *pool; + SOCKET socketdes; + int type; /* SOCK_STREAM, SOCK_DGRAM */ + int protocol; + apr_sockaddr_t *local_addr; + apr_sockaddr_t *remote_addr; + int timeout_ms; /* MUST MATCH if timeout > 0 */ + apr_interval_time_t timeout; + apr_int32_t disconnected; + int local_port_unknown; + int local_interface_unknown; + int remote_addr_unknown; + apr_int32_t options; + apr_int32_t inherit; +#if APR_HAS_SENDFILE + /* As of 07.20.04, the overlapped structure is only used by + * apr_socket_sendfile and that's where it will be allocated + * and initialized. + */ + OVERLAPPED *overlapped; +#endif + sock_userdata_t *userdata; + + /* if there is a timeout set, then this pollset is used */ + apr_pollset_t *pollset; +}; + +#ifdef _WIN32_WCE +#ifndef WSABUF +typedef struct _WSABUF { + u_long len; /* the length of the buffer */ + char FAR * buf; /* the pointer to the buffer */ +} WSABUF, FAR * LPWSABUF; +#endif +#else +#ifdef _MSC_VER +#define HAVE_STRUCT_IPMREQ +#endif +#endif + +apr_status_t status_from_res_error(int); + +const char *apr_inet_ntop(int af, const void *src, char *dst, apr_size_t size); +int apr_inet_pton(int af, const char *src, void *dst); +void apr_sockaddr_vars_set(apr_sockaddr_t *, int, apr_port_t); + +#define apr_is_option_set(skt, option) \ + (((skt)->options & (option)) == (option)) + +#define apr_set_option(skt, option, on) \ + do { \ + if (on) \ + (skt)->options |= (option); \ + else \ + (skt)->options &= ~(option); \ + } while (0) + +#endif /* ! NETWORK_IO_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_proc_mutex.h b/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_proc_mutex.h new file mode 100644 index 00000000..4e3e3993 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_proc_mutex.h @@ -0,0 +1,29 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PROC_MUTEX_H +#define PROC_MUTEX_H + +#include "apr_proc_mutex.h" + +struct apr_proc_mutex_t { + apr_pool_t *pool; + HANDLE handle; + const char *fname; +}; + +#endif /* PROC_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_thread_cond.h b/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_thread_cond.h new file mode 100644 index 00000000..c7f69f80 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_thread_cond.h @@ -0,0 +1,32 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_COND_H +#define THREAD_COND_H + +#include "apr_thread_cond.h" + +struct apr_thread_cond_t { + apr_pool_t *pool; + HANDLE semaphore; + CRITICAL_SECTION csection; + unsigned long num_waiting; + unsigned long num_wake; + unsigned long generation; +}; + +#endif /* THREAD_COND_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_thread_mutex.h b/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_thread_mutex.h new file mode 100644 index 00000000..13d3c1cb --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_thread_mutex.h @@ -0,0 +1,40 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_MUTEX_H +#define THREAD_MUTEX_H + +#include "apr_pools.h" + +typedef enum thread_mutex_type { + thread_mutex_critical_section, + thread_mutex_unnested_event, + thread_mutex_nested_mutex +} thread_mutex_type; + +/* handle applies only to unnested_event on all platforms + * and nested_mutex on Win9x only. Otherwise critical_section + * is used for NT nexted mutexes providing optimal performance. + */ +struct apr_thread_mutex_t { + apr_pool_t *pool; + thread_mutex_type type; + HANDLE handle; + CRITICAL_SECTION section; +}; + +#endif /* THREAD_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_thread_rwlock.h b/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_thread_rwlock.h new file mode 100644 index 00000000..1177e529 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_thread_rwlock.h @@ -0,0 +1,30 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_RWLOCK_H +#define THREAD_RWLOCK_H + +#include "apr_thread_rwlock.h" + +struct apr_thread_rwlock_t { + apr_pool_t *pool; + HANDLE write_mutex; + HANDLE read_event; + LONG readers; +}; + +#endif /* THREAD_RWLOCK_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_threadproc.h b/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_threadproc.h new file mode 100644 index 00000000..d3ce9c51 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_threadproc.h @@ -0,0 +1,74 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr_private.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" + +#ifndef THREAD_PROC_H +#define THREAD_PROC_H + +#define SHELL_PATH "cmd.exe" + +struct apr_thread_t { + apr_pool_t *pool; + HANDLE td; + apr_int32_t cancel; + apr_int32_t cancel_how; + void *data; + apr_thread_start_t func; + apr_status_t exitval; +}; + +struct apr_threadattr_t { + apr_pool_t *pool; + apr_int32_t detach; + apr_size_t stacksize; +}; + +struct apr_threadkey_t { + apr_pool_t *pool; + DWORD key; +}; + +struct apr_procattr_t { + apr_pool_t *pool; + apr_file_t *parent_in; + apr_file_t *child_in; + apr_file_t *parent_out; + apr_file_t *child_out; + apr_file_t *parent_err; + apr_file_t *child_err; + char *currdir; + apr_int32_t cmdtype; + apr_int32_t detached; + apr_child_errfn_t *errfn; + apr_int32_t errchk; +#ifndef _WIN32_WCE + HANDLE user_token; + LPSECURITY_ATTRIBUTES sa; + LPVOID sd; +#endif +}; + +struct apr_thread_once_t { + long value; +}; + +extern apr_status_t apr_threadproc_init(apr_pool_t *pool); + +#endif /* ! THREAD_PROC_H */ + diff --git a/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_utf8.h b/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_utf8.h new file mode 100644 index 00000000..84f8bf77 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/win32/apr_arch_utf8.h @@ -0,0 +1,56 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef UTF8_H +#define UTF8_H + +#include "apr.h" +#include "apr_lib.h" +#include "apr_errno.h" + +/* If we ever support anything more exciting than char... this could move. + */ +typedef apr_uint16_t apr_wchar_t; + +/** + * An APR internal function for fast utf-8 octet-encoded Unicode conversion + * to the ucs-2 wide Unicode format. This function is used for filename and + * other resource conversions for platforms providing native Unicode support. + * + * @tip Only the errors APR_EINVAL and APR_INCOMPLETE may occur, the former + * when the character code is invalid (in or out of context) and the later + * when more characters were expected, but insufficient characters remain. + */ +APR_DECLARE(apr_status_t) apr_conv_utf8_to_ucs2(const char *in, + apr_size_t *inbytes, + apr_wchar_t *out, + apr_size_t *outwords); + +/** + * An APR internal function for fast ucs-2 wide Unicode format conversion to + * the utf-8 octet-encoded Unicode. This function is used for filename and + * other resource conversions for platforms providing native Unicode support. + * + * @tip Only the errors APR_EINVAL and APR_INCOMPLETE may occur, the former + * when the character code is invalid (in or out of context) and the later + * when more words were expected, but insufficient words remain. + */ +APR_DECLARE(apr_status_t) apr_conv_ucs2_to_utf8(const apr_wchar_t *in, + apr_size_t *inwords, + char *out, + apr_size_t *outbytes); + +#endif /* def UTF8_H */ diff --git a/c/dependencies/windows/apr/x64/include/arch/win32/apr_dbg_win32_handles.h b/c/dependencies/windows/apr/x64/include/arch/win32/apr_dbg_win32_handles.h new file mode 100644 index 00000000..471cd66d --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/win32/apr_dbg_win32_handles.h @@ -0,0 +1,217 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_DBG_WIN32_HANDLES_H +#define APR_DBG_WIN32_HANDLES_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* USAGE: + * + * Add the following include to apr_private.h for internal debugging, + * or copy this header into apr/include add the include below to apr.h + * for really global debugging; + * + * #include "apr_dbg_win32_handles.h" + * + * apr_dbg_log is the crux of this function ... it uses Win32 API and + * no apr calls itself to log all activity to a file named for the + * executing application with a .pid suffix. Ergo several instances + * may be executing and logged at once. + * + * HANDLE apr_dbg_log(char* fn, HANDLE ha, char* fl, int ln, int nh + * [, HANDLE *hv, char *dsc...]) + * + * returns: the handle passed in ha, which is cast back to the real return type. + * + * formats one line into the debug log file if nh is zero; + * ha (hex) seq(hex) tid(hex) fn fl ln + * xxxxxxxx xxxxxxxx xxxxxxxx func() sourcefile:lineno + * The macro apr_dbg_rv makes this simple to implement for many APIs + * that simply take args that don't interest us, and return a handle. + * + * formats multiple lines (nh) into the debug log file for each hv/dsc pair + * (nh must correspond to the number of pairs); + * hv (hex) seq(hex) tid(hex) fn dsc fl ln + * xxxxxxxx xxxxxxxx xxxxxxxx func(arg) sourcefile:lineno + * In this later usage, hv is the still the return value but is not + * treated as a handle. + */ + +APR_DECLARE_NONSTD(HANDLE) apr_dbg_log(char* fn, HANDLE ha, char* fl, int ln, + int nh,/* HANDLE *hv, char *dsc */...); + +#define apr_dbg_rv(fn, args) (apr_dbg_log(#fn,(fn) args,__FILE__,__LINE__,0)) + +#define CloseHandle(h) \ + ((BOOL)apr_dbg_log("CloseHandle", \ + (HANDLE)(CloseHandle)(h), \ + __FILE__,__LINE__,1, \ + &(h),"")) + +#define CreateEventA(sd,b1,b2,nm) apr_dbg_rv(CreateEventA,(sd,b1,b2,nm)) +#define CreateEventW(sd,b1,b2,nm) apr_dbg_rv(CreateEventW,(sd,b1,b2,nm)) + +#define CreateFileA(nm,d1,d2,sd,d3,d4,h) apr_dbg_rv(CreateFileA,(nm,d1,d2,sd,d3,d4,h)) +#define CreateFileW(nm,d1,d2,sd,d3,d4,h) apr_dbg_rv(CreateFileW,(nm,d1,d2,sd,d3,d4,h)) + +#define CreateFileMappingA(fh,sd,d1,d2,d3,nm) apr_dbg_rv(CreateFileMappingA,(fh,sd,d1,d2,d3,nm)) +#define CreateFileMappingW(fh,sd,d1,d2,d3,nm) apr_dbg_rv(CreateFileMappingW,(fh,sd,d1,d2,d3,nm)) + +#define CreateMutexA(sd,b,nm) apr_dbg_rv(CreateMutexA,(sd,b,nm)) +#define CreateMutexW(sd,b,nm) apr_dbg_rv(CreateMutexW,(sd,b,nm)) + +#define CreateIoCompletionPort(h1,h2,pd1,d2) apr_dbg_rv(CreateIoCompletionPort,(h1,h2,pd1,d2)) + +#define CreateNamedPipeA(nm,d1,d2,d3,d4,d5,d6,sd) apr_dbg_rv(CreateNamedPipeA,(nm,d1,d2,d3,d4,d5,d6,sd)) +#define CreateNamedPipeW(nm,d1,d2,d3,d4,d5,d6,sd) apr_dbg_rv(CreateNamedPipeW,(nm,d1,d2,d3,d4,d5,d6,sd)) + +#define CreatePipe(ph1,ph2,sd,d) \ + ((BOOL)apr_dbg_log("CreatePipe", \ + (HANDLE)(CreatePipe)(ph1,ph2,sd,d), \ + __FILE__,__LINE__,2, \ + (ph1),"hRead", \ + (ph2),"hWrite")) + +#define CreateProcessA(s1,s2,sd1,sd2,b,d1,s3,s4,pd2,hr) \ + ((BOOL)apr_dbg_log("CreateProcessA", \ + (HANDLE)(CreateProcessA)(s1,s2,sd1,sd2,b,d1,s3,s4,pd2,hr), \ + __FILE__,__LINE__,2, \ + &((hr)->hProcess),"hProcess", \ + &((hr)->hThread),"hThread")) +#define CreateProcessW(s1,s2,sd1,sd2,b,d1,s3,s4,pd2,hr) \ + ((BOOL)apr_dbg_log("CreateProcessW", \ + (HANDLE)(CreateProcessW)(s1,s2,sd1,sd2,b,d1,s3,s4,pd2,hr), \ + __FILE__,__LINE__,2, \ + &((hr)->hProcess),"hProcess", \ + &((hr)->hThread),"hThread")) + +#define CreateSemaphoreA(sd,d1,d2,nm) apr_dbg_rv(CreateSemaphoreA,(sd,d1,d2,nm)) +#define CreateSemaphoreW(sd,d1,d2,nm) apr_dbg_rv(CreateSemaphoreW,(sd,d1,d2,nm)) + +#define CreateThread(sd,d1,fn,pv,d2,pd3) apr_dbg_rv(CreateThread,(sd,d1,fn,pv,d2,pd3)) + +#define DeregisterEventSource(h) \ + ((BOOL)apr_dbg_log("DeregisterEventSource", \ + (HANDLE)(DeregisterEventSource)(h), \ + __FILE__,__LINE__,1, \ + &(h),"")) + +#define DuplicateHandle(h1,h2,h3,ph4,d1,b,d2) \ + ((BOOL)apr_dbg_log("DuplicateHandle", \ + (HANDLE)(DuplicateHandle)(h1,h2,h3,ph4,d1,b,d2), \ + __FILE__,__LINE__,2, \ + (ph4),((h3)==GetCurrentProcess()) \ + ? "Target" : "EXTERN Target", \ + &(h2),((h1)==GetCurrentProcess()) \ + ? "Source" : "EXTERN Source")) + +#define GetCurrentProcess() \ + (apr_dbg_log("GetCurrentProcess", \ + (GetCurrentProcess)(),__FILE__,__LINE__,0)) + +#define GetCurrentThread() \ + (apr_dbg_log("GetCurrentThread", \ + (GetCurrentThread)(),__FILE__,__LINE__,0)) + +#define GetModuleHandleA(nm) apr_dbg_rv(GetModuleHandleA,(nm)) +#define GetModuleHandleW(nm) apr_dbg_rv(GetModuleHandleW,(nm)) + +#define GetStdHandle(d) apr_dbg_rv(GetStdHandle,(d)) + +#define LoadLibraryA(nm) apr_dbg_rv(LoadLibraryA,(nm)) +#define LoadLibraryW(nm) apr_dbg_rv(LoadLibraryW,(nm)) + +#define LoadLibraryExA(nm,h,d) apr_dbg_rv(LoadLibraryExA,(nm,h,d)) +#define LoadLibraryExW(nm,h,d) apr_dbg_rv(LoadLibraryExW,(nm,h,d)) + +#define OpenEventA(d,b,nm) apr_dbg_rv(OpenEventA,(d,b,nm)) +#define OpenEventW(d,b,nm) apr_dbg_rv(OpenEventW,(d,b,nm)) + +#define OpenFileMappingA(d,b,nm) apr_dbg_rv(OpenFileMappingA,(d,b,nm)) +#define OpenFileMappingW(d,b,nm) apr_dbg_rv(OpenFileMappingW,(d,b,nm)) + +#define RegisterEventSourceA(s1,s2) apr_dbg_rv(RegisterEventSourceA,(s1,s2)) +#define RegisterEventSourceW(s1,s2) apr_dbg_rv(RegisterEventSourceW,(s1,s2)) + +#define SetEvent(h) \ + ((BOOL)apr_dbg_log("SetEvent", \ + (HANDLE)(SetEvent)(h), \ + __FILE__,__LINE__,1, \ + &(h),"")) + +#define SetStdHandle(d,h) \ + ((BOOL)apr_dbg_log("SetStdHandle", \ + (HANDLE)(SetStdHandle)(d,h), \ + __FILE__,__LINE__,1,&(h),"")) + +#define socket(i1,i2,i3) \ + ((SOCKET)apr_dbg_log("socket", \ + (HANDLE)(socket)(i1,i2,i3), \ + __FILE__,__LINE__,0)) + +#define WaitForSingleObject(h,d) \ + ((DWORD)apr_dbg_log("WaitForSingleObject", \ + (HANDLE)(WaitForSingleObject)(h,d), \ + __FILE__,__LINE__,1,&(h),"Signaled")) + +#define WaitForSingleObjectEx(h,d,b) \ + ((DWORD)apr_dbg_log("WaitForSingleObjectEx", \ + (HANDLE)(WaitForSingleObjectEx)(h,d,b), \ + __FILE__,__LINE__,1,&(h),"Signaled")) + +#define WaitForMultipleObjects(d1,ah,b,d2) \ + ((DWORD)apr_dbg_log("WaitForMultipleObjects", \ + (HANDLE)(WaitForMultipleObjects)(d1,ah,b,d2), \ + __FILE__,__LINE__,1,ah,"Signaled")) + +#define WaitForMultipleObjectsEx(d1,ah,b1,d2,b2) \ + ((DWORD)apr_dbg_log("WaitForMultipleObjectsEx", \ + (HANDLE)(WaitForMultipleObjectsEx)(d1,ah,b1,d2,b2), \ + __FILE__,__LINE__,1,ah,"Signaled")) + +#define WSASocketA(i1,i2,i3,pi,g,dw) \ + ((SOCKET)apr_dbg_log("WSASocketA", \ + (HANDLE)(WSASocketA)(i1,i2,i3,pi,g,dw), \ + __FILE__,__LINE__,0)) + +#define WSASocketW(i1,i2,i3,pi,g,dw) \ + ((SOCKET)apr_dbg_log("WSASocketW", \ + (HANDLE)(WSASocketW)(i1,i2,i3,pi,g,dw), \ + __FILE__,__LINE__,0)) + +#define closesocket(sh) \ + ((int)apr_dbg_log("closesocket", \ + (HANDLE)(closesocket)(sh), \ + __FILE__,__LINE__,1,&(sh),"")) + +#define _beginthread(fn,d,pv) \ + ((unsigned long)apr_dbg_log("_beginthread", \ + (HANDLE)(_beginthread)(fn,d,pv), \ + __FILE__,__LINE__,0)) + +#define _beginthreadex(sd,d1,fn,pv,d2,pd3) \ + ((unsigned long)apr_dbg_log("_beginthreadex", \ + (HANDLE)(_beginthreadex)(sd,d1,fn,pv,d2,pd3), \ + __FILE__,__LINE__,0)) + +#ifdef __cplusplus +} +#endif + +#endif /* !defined(APR_DBG_WIN32_HANDLES_H) */ diff --git a/c/dependencies/windows/apr/x64/include/arch/win32/apr_private.h b/c/dependencies/windows/apr/x64/include/arch/win32/apr_private.h new file mode 100644 index 00000000..c631ad43 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/arch/win32/apr_private.h @@ -0,0 +1,175 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Note: + * This is the windows specific autoconf-like config file + * which unix would create at build time. + */ + +#ifdef WIN32 + +#ifndef APR_PRIVATE_H +#define APR_PRIVATE_H + +/* Include the public APR symbols, include our idea of the 'right' + * subset of the Windows.h header. This saves us repetition. + */ +#include "apr.h" + +/* + * Add a _very_few_ declarations missing from the restricted set of headers + * (If this list becomes extensive, re-enable the required headers above!) + * winsock headers were excluded by WIN32_LEAN_AND_MEAN, so include them now + */ +#ifndef SW_HIDE +#define SW_HIDE 0 +#endif + +/* For the misc.h late-loaded dynamic symbols, we need some obscure types + * Avoid dragging in wtypes.h unless it's absolutely necessary [generally + * not with APR itself, until some GUI-related security is introduced.] + */ +#ifndef _WIN32_WCE +#define HAVE_ACLAPI 1 +#ifdef __wtypes_h__ +#include +#else +#define __wtypes_h__ +#include +#undef __wtypes_h__ +#endif +#else +#define HAVE_ACLAPI 0 +#endif + +#if APR_HAVE_SYS_TYPES_H +#include +#endif +#if APR_HAVE_STDDEF_H +#include +#endif +#include +#if APR_HAVE_TIME_H +#include +#endif + +/* Use this section to define all of the HAVE_FOO_H + * that are required to build properly. + */ +#define HAVE_LIMITS_H 1 +#define HAVE_MALLOC_H 1 +#define HAVE_SIGNAL_H 1 +/* #define HAVE_STDDEF_H 1 why not? */ +#define HAVE_STDLIB_H 1 + +#define HAVE_STRICMP 1 +#define HAVE_STRNICMP 1 +#define HAVE_STRDUP 1 +#define HAVE_STRSTR 1 +#define HAVE_MEMCHR 1 + +#define SIGHUP 1 +/* 2 is used for SIGINT on windows */ +#define SIGQUIT 3 +/* 4 is used for SIGILL on windows */ +#define SIGTRAP 5 +#define SIGIOT 6 +#define SIGBUS 7 +/* 8 is used for SIGFPE on windows */ +#define SIGKILL 9 +#define SIGUSR1 10 +/* 11 is used for SIGSEGV on windows */ +#define SIGUSR2 12 +#define SIGPIPE 13 +#define SIGALRM 14 +/* 15 is used for SIGTERM on windows */ +#define SIGSTKFLT 16 +#define SIGCHLD 17 +#define SIGCONT 18 +#define SIGSTOP 19 +#define SIGTSTP 20 +/* 21 is used for SIGBREAK on windows */ +/* 22 is used for SIGABRT on windows */ +#define SIGTTIN 23 +#define SIGTTOU 24 +#define SIGURG 25 +#define SIGXCPU 26 +#define SIGXFSZ 27 +#define SIGVTALRM 28 +#define SIGPROF 29 +#define SIGWINCH 30 +#define SIGIO 31 + +/* APR COMPATABILITY FUNCTIONS + * This section should be used to define functions and + * macros which are need to make Windows features look + * like POSIX features. + */ +typedef void (Sigfunc)(int); + +#define sleep(t) Sleep((t) * 1000) + +#define SIZEOF_SHORT 2 +#define SIZEOF_INT 4 +#define SIZEOF_LONGLONG 8 +#define SIZEOF_CHAR 1 +#define SIZEOF_SSIZE_T SIZEOF_INT + +unsigned __stdcall SignalHandling(void *); +int thread_ready(void); + +#if !APR_HAVE_ERRNO_H +APR_DECLARE_DATA int errno; +#define ENOSPC 1 +#endif + +#if APR_HAVE_IPV6 +#define HAVE_GETADDRINFO 1 +#define HAVE_GETNAMEINFO 1 +#define HAVE_IF_INDEXTONAME 1 +#define HAVE_IF_NAMETOINDEX 1 +#endif + +/* MSVC 7.0 introduced _strtoi64 */ +#if _MSC_VER >= 1300 && _INTEGRAL_MAX_BITS >= 64 && !defined(_WIN32_WCE) +#define APR_INT64_STRFN _strtoi64 +#endif + +#if APR_HAS_LARGE_FILES +#ifdef APR_INT64_STRFN +#define APR_OFF_T_STRFN APR_INT64_STRFN +#else +#define APR_OFF_T_STRFN apr_strtoi64 +#endif +#else +#if defined(_WIN32_WCE) +#define APR_OFF_T_STRFN strtol +#else +#define APR_OFF_T_STRFN strtoi +#endif +#endif + +/* used to check for DWORD overflow in 64bit compiles */ +#define APR_DWORD_MAX 0xFFFFFFFFUL + +/* + * Include common private declarations. + */ +#include "../apr_private_common.h" + +#endif /*APR_PRIVATE_H*/ +#endif /*WIN32*/ diff --git a/c/dependencies/windows/apr/x64/include/private/apr_crypto_internal.h b/c/dependencies/windows/apr/x64/include/private/apr_crypto_internal.h new file mode 100644 index 00000000..1ea838bf --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/private/apr_crypto_internal.h @@ -0,0 +1,297 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_CRYPTO_INTERNAL_H +#define APR_CRYPTO_INTERNAL_H + +#include + +#include "apr_crypto.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if APU_HAVE_CRYPTO + +struct apr_crypto_driver_t { + + /** name */ + const char *name; + + /** + * @brief: allow driver to perform once-only initialisation. + * Called once only. + * @param pool The pool to register the cleanup in. + * @param params Optional init parameter string. + * @param rc Driver-specific additional error code + */ + apr_status_t (*init)(apr_pool_t *pool, const char *params, + const apu_err_t **result); + + /** + * @brief Create a context for supporting encryption. Keys, certificates, + * algorithms and other parameters will be set per context. More than + * one context can be created at one time. A cleanup will be automatically + * registered with the given pool to guarantee a graceful shutdown. + * @param f - context pointer will be written here + * @param provider - provider to use + * @param params - array of key parameters + * @param pool - process pool + * @return APR_ENOENGINE when the engine specified does not exist. APR_EINITENGINE + * if the engine cannot be initialised. + */ + apr_status_t (*make)(apr_crypto_t **f, const apr_crypto_driver_t *provider, + const char *params, apr_pool_t *pool); + + /** + * @brief Get a hash table of key types, keyed by the name of the type against + * a pointer to apr_crypto_block_key_type_t. + * + * @param types - hashtable of key types keyed to constants. + * @param f - encryption context + * @return APR_SUCCESS for success + */ + apr_status_t (*get_block_key_types)(apr_hash_t **types, + const apr_crypto_t *f); + + /** + * @brief Get a hash table of key modes, keyed by the name of the mode against + * a pointer to apr_crypto_block_key_mode_t. + * + * @param modes - hashtable of key modes keyed to constants. + * @param f - encryption context + * @return APR_SUCCESS for success + */ + apr_status_t (*get_block_key_modes)(apr_hash_t **modes, + const apr_crypto_t *f); + + /** + * @brief Create a key from the given passphrase. By default, the PBKDF2 + * algorithm is used to generate the key from the passphrase. It is expected + * that the same pass phrase will generate the same key, regardless of the + * backend crypto platform used. The key is cleaned up when the context + * is cleaned, and may be reused with multiple encryption or decryption + * operations. + * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If + * *key is not NULL, *key must point at a previously created structure. + * @param key The key returned, see note. + * @param ivSize The size of the initialisation vector will be returned, based + * on whether an IV is relevant for this type of crypto. + * @param pass The passphrase to use. + * @param passLen The passphrase length in bytes + * @param salt The salt to use. + * @param saltLen The salt length in bytes + * @param type 3DES_192, AES_128, AES_192, AES_256. + * @param mode Electronic Code Book / Cipher Block Chaining. + * @param doPad Pad if necessary. + * @param iterations Iteration count + * @param f The context to use. + * @param p The pool to use. + * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend + * error occurred while generating the key. APR_ENOCIPHER if the type or mode + * is not supported by the particular backend. APR_EKEYTYPE if the key type is + * not known. APR_EPADDING if padding was requested but is not supported. + * APR_ENOTIMPL if not implemented. + */ + apr_status_t (*passphrase)(apr_crypto_key_t **key, apr_size_t *ivSize, + const char *pass, apr_size_t passLen, const unsigned char * salt, + apr_size_t saltLen, const apr_crypto_block_key_type_e type, + const apr_crypto_block_key_mode_e mode, const int doPad, + const int iterations, const apr_crypto_t *f, apr_pool_t *p); + + /** + * @brief Initialise a context for encrypting arbitrary data using the given key. + * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If + * *ctx is not NULL, *ctx must point at a previously created structure. + * @param ctx The block context returned, see note. + * @param iv Optional initialisation vector. If the buffer pointed to is NULL, + * an IV will be created at random, in space allocated from the pool. + * If the buffer pointed to is not NULL, the IV in the buffer will be + * used. + * @param key The key structure. + * @param blockSize The block size of the cipher. + * @param p The pool to use. + * @return Returns APR_ENOIV if an initialisation vector is required but not specified. + * Returns APR_EINIT if the backend failed to initialise the context. Returns + * APR_ENOTIMPL if not implemented. + */ + apr_status_t (*block_encrypt_init)(apr_crypto_block_t **ctx, + const unsigned char **iv, const apr_crypto_key_t *key, + apr_size_t *blockSize, apr_pool_t *p); + + /** + * @brief Encrypt data provided by in, write it to out. + * @note The number of bytes written will be written to outlen. If + * out is NULL, outlen will contain the maximum size of the + * buffer needed to hold the data, including any data + * generated by apr_crypto_block_encrypt_finish below. If *out points + * to NULL, a buffer sufficiently large will be created from + * the pool provided. If *out points to a not-NULL value, this + * value will be used as a buffer instead. + * @param out Address of a buffer to which data will be written, + * see note. + * @param outlen Length of the output will be written here. + * @param in Address of the buffer to read. + * @param inlen Length of the buffer to read. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if + * not implemented. + */ + apr_status_t (*block_encrypt)(unsigned char **out, apr_size_t *outlen, + const unsigned char *in, apr_size_t inlen, apr_crypto_block_t *ctx); + + /** + * @brief Encrypt final data block, write it to out. + * @note If necessary the final block will be written out after being + * padded. Typically the final block will be written to the + * same buffer used by apr_crypto_block_encrypt, offset by the + * number of bytes returned as actually written by the + * apr_crypto_block_encrypt() call. After this call, the context + * is cleaned and can be reused by apr_crypto_block_encrypt_init(). + * @param out Address of a buffer to which data will be written. This + * buffer must already exist, and is usually the same + * buffer used by apr_evp_crypt(). See note. + * @param outlen Length of the output will be written here. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. + * @return APR_EPADDING if padding was enabled and the block was incorrectly + * formatted. + * @return APR_ENOTIMPL if not implemented. + */ + apr_status_t (*block_encrypt_finish)(unsigned char *out, + apr_size_t *outlen, apr_crypto_block_t *ctx); + + /** + * @brief Initialise a context for decrypting arbitrary data using the given key. + * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If + * *ctx is not NULL, *ctx must point at a previously created structure. + * @param ctx The block context returned, see note. + * @param blockSize The block size of the cipher. + * @param iv Optional initialisation vector. If the buffer pointed to is NULL, + * an IV will be created at random, in space allocated from the pool. + * If the buffer is not NULL, the IV in the buffer will be used. + * @param key The key structure. + * @param p The pool to use. + * @return Returns APR_ENOIV if an initialisation vector is required but not specified. + * Returns APR_EINIT if the backend failed to initialise the context. Returns + * APR_ENOTIMPL if not implemented. + */ + apr_status_t (*block_decrypt_init)(apr_crypto_block_t **ctx, + apr_size_t *blockSize, const unsigned char *iv, + const apr_crypto_key_t *key, apr_pool_t *p); + + /** + * @brief Decrypt data provided by in, write it to out. + * @note The number of bytes written will be written to outlen. If + * out is NULL, outlen will contain the maximum size of the + * buffer needed to hold the data, including any data + * generated by apr_crypto_block_decrypt_finish below. If *out points + * to NULL, a buffer sufficiently large will be created from + * the pool provided. If *out points to a not-NULL value, this + * value will be used as a buffer instead. + * @param out Address of a buffer to which data will be written, + * see note. + * @param outlen Length of the output will be written here. + * @param in Address of the buffer to read. + * @param inlen Length of the buffer to read. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if + * not implemented. + */ + apr_status_t (*block_decrypt)(unsigned char **out, apr_size_t *outlen, + const unsigned char *in, apr_size_t inlen, apr_crypto_block_t *ctx); + + /** + * @brief Decrypt final data block, write it to out. + * @note If necessary the final block will be written out after being + * padded. Typically the final block will be written to the + * same buffer used by apr_crypto_block_decrypt, offset by the + * number of bytes returned as actually written by the + * apr_crypto_block_decrypt() call. After this call, the context + * is cleaned and can be reused by apr_crypto_block_decrypt_init(). + * @param out Address of a buffer to which data will be written. This + * buffer must already exist, and is usually the same + * buffer used by apr_evp_crypt(). See note. + * @param outlen Length of the output will be written here. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. + * @return APR_EPADDING if padding was enabled and the block was incorrectly + * formatted. + * @return APR_ENOTIMPL if not implemented. + */ + apr_status_t (*block_decrypt_finish)(unsigned char *out, + apr_size_t *outlen, apr_crypto_block_t *ctx); + + /** + * @brief Clean encryption / decryption context. + * @note After cleanup, a context is free to be reused if necessary. + * @param ctx The block context to use. + * @return Returns APR_ENOTIMPL if not supported. + */ + apr_status_t (*block_cleanup)(apr_crypto_block_t *ctx); + + /** + * @brief Clean encryption / decryption context. + * @note After cleanup, a context is free to be reused if necessary. + * @param f The context to use. + * @return Returns APR_ENOTIMPL if not supported. + */ + apr_status_t (*cleanup)(apr_crypto_t *f); + + /** + * @brief Clean encryption / decryption context. + * @note After cleanup, a context is free to be reused if necessary. + * @return Returns APR_ENOTIMPL if not supported. + */ + apr_status_t (*shutdown)(void); + + /** + * @brief: fetch the most recent error from this driver. + * @param result - the result structure + * @param f - context pointer + * @return APR_SUCCESS for success. + */ + apr_status_t (*error)(const apu_err_t **result, const apr_crypto_t *f); + + /** + * @brief Create a key from the provided secret or passphrase. The key is cleaned + * up when the context is cleaned, and may be reused with multiple encryption + * or decryption operations. + * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If + * *key is not NULL, *key must point at a previously created structure. + * @param key The key returned, see note. + * @param rec The key record, from which the key will be derived. + * @param f The context to use. + * @param p The pool to use. + * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend + * error occurred while generating the key. APR_ENOCIPHER if the type or mode + * is not supported by the particular backend. APR_EKEYTYPE if the key type is + * not known. APR_EPADDING if padding was requested but is not supported. + * APR_ENOTIMPL if not implemented. + */ + apr_status_t (*key)(apr_crypto_key_t **key, const apr_crypto_key_rec_t *rec, + const apr_crypto_t *f, apr_pool_t *p); + +}; + +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/c/dependencies/windows/apr/x64/include/private/apr_dbd_internal.h b/c/dependencies/windows/apr/x64/include/private/apr_dbd_internal.h new file mode 100644 index 00000000..671ffb21 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/private/apr_dbd_internal.h @@ -0,0 +1,365 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* Overview of what this is and does: + * http://www.apache.org/~niq/dbd.html + */ + +#ifndef APR_DBD_INTERNAL_H +#define APR_DBD_INTERNAL_H + +#include + +#include "apr_dbd.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define TXN_IGNORE_ERRORS(t) \ + ((t) && ((t)->mode & APR_DBD_TRANSACTION_IGNORE_ERRORS)) +#define TXN_NOTICE_ERRORS(t) \ + ((t) && !((t)->mode & APR_DBD_TRANSACTION_IGNORE_ERRORS)) + +#define TXN_DO_COMMIT(t) (!((t)->mode & APR_DBD_TRANSACTION_ROLLBACK)) +#define TXN_DO_ROLLBACK(t) ((t)->mode & APR_DBD_TRANSACTION_ROLLBACK) + +#define TXN_MODE_BITS \ + (APR_DBD_TRANSACTION_ROLLBACK|APR_DBD_TRANSACTION_IGNORE_ERRORS) + +struct apr_dbd_driver_t { + /** name */ + const char *name; + + /** init: allow driver to perform once-only initialisation. + * Called once only. May be NULL + */ + void (*init)(apr_pool_t *pool); + + /** native_handle: return the native database handle of the underlying db + * + * @param handle - apr_dbd handle + * @return - native handle + */ + void *(*native_handle)(apr_dbd_t *handle); + + /** open: obtain a database connection from the server rec. + * Must be explicitly closed when you're finished with it. + * WARNING: only use this when you need a connection with + * a lifetime other than a request + * + * @param pool - a pool to use for error messages (if any). + * @param params - connection parameters. + * @param error - descriptive error. + * @return database handle, or NULL on error. + */ + apr_dbd_t *(*open)(apr_pool_t *pool, const char *params, + const char **error); + + /** check_conn: check status of a database connection + * + * @param pool - a pool to use for error messages (if any). + * @param handle - the connection to check + * @return APR_SUCCESS or error + */ + apr_status_t (*check_conn)(apr_pool_t *pool, apr_dbd_t *handle); + + /** close: close/release a connection obtained from open() + * + * @param handle - the connection to release + * @return APR_SUCCESS or error + */ + apr_status_t (*close)(apr_dbd_t *handle); + + /** set_dbname: select database name. May be a no-op if not supported. + * + * @param pool - working pool + * @param handle - the connection + * @param name - the database to select + * @return 0 for success or error code + */ + int (*set_dbname)(apr_pool_t* pool, apr_dbd_t *handle, const char *name); + + /** transaction: start a transaction. May be a no-op. + * + * @param pool - a pool to use for error messages (if any). + * @param handle - the connection + * @param trans - ptr to a transaction. May be null on entry + * @return 0 for success or error code + */ + int (*start_transaction)(apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_transaction_t **trans); + + /** end_transaction: end a transaction + * (commit on success, rollback on error). + * May be a no-op. + * + * @param trans - the transaction. + * @return 0 for success or error code + */ + int (*end_transaction)(apr_dbd_transaction_t *trans); + + /** query: execute an SQL query that doesn't return a result set + * + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the SQL statement to execute + * @return 0 for success or error code + */ + int (*query)(apr_dbd_t *handle, int *nrows, const char *statement); + + /** select: execute an SQL query that returns a result set + * + * @param pool - pool to allocate the result set + * @param handle - the connection + * @param res - pointer to result set pointer. May point to NULL on entry + * @param statement - the SQL statement to execute + * @param random - 1 to support random access to results (seek any row); + * 0 to support only looping through results in order + * (async access - faster) + * @return 0 for success or error code + */ + int (*select)(apr_pool_t *pool, apr_dbd_t *handle, apr_dbd_results_t **res, + const char *statement, int random); + + /** num_cols: get the number of columns in a results set + * + * @param res - result set. + * @return number of columns + */ + int (*num_cols)(apr_dbd_results_t *res); + + /** num_tuples: get the number of rows in a results set + * of a synchronous select + * + * @param res - result set. + * @return number of rows, or -1 if the results are asynchronous + */ + int (*num_tuples)(apr_dbd_results_t *res); + + /** get_row: get a row from a result set + * + * @param pool - pool to allocate the row + * @param res - result set pointer + * @param row - pointer to row pointer. May point to NULL on entry + * @param rownum - row number, or -1 for "next row". Ignored if random + * access is not supported. + * @return 0 for success, -1 for rownum out of range or data finished + */ + int (*get_row)(apr_pool_t *pool, apr_dbd_results_t *res, + apr_dbd_row_t **row, int rownum); + + /** get_entry: get an entry from a row + * + * @param row - row pointer + * @param col - entry number + * @param val - entry to fill + * @return 0 for success, -1 for no data, +1 for general error + */ + const char* (*get_entry)(const apr_dbd_row_t *row, int col); + + /** error: get current error message (if any) + * + * @param handle - the connection + * @param errnum - error code from operation that returned an error + * @return the database current error message, or message for errnum + * (implementation-dependent whether errnum is ignored) + */ + const char *(*error)(apr_dbd_t *handle, int errnum); + + /** escape: escape a string so it is safe for use in query/select + * + * @param pool - pool to alloc the result from + * @param string - the string to escape + * @param handle - the connection + * @return the escaped, safe string + */ + const char *(*escape)(apr_pool_t *pool, const char *string, + apr_dbd_t *handle); + + /** prepare: prepare a statement + * + * @param pool - pool to alloc the result from + * @param handle - the connection + * @param query - the SQL query + * @param label - A label for the prepared statement. + * use NULL for temporary prepared statements + * (eg within a Request in httpd) + * @param nargs - number of parameters in the query + * @param nvals - number of values passed in p[b]query/select + * @param types - pointer to an array with types of parameters + * @param statement - statement to prepare. May point to null on entry. + * @return 0 for success or error code + */ + int (*prepare)(apr_pool_t *pool, apr_dbd_t *handle, const char *query, + const char *label, int nargs, int nvals, + apr_dbd_type_e *types, apr_dbd_prepared_t **statement); + + /** pvquery: query using a prepared statement + args + * + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param args - args to prepared statement + * @return 0 for success or error code + */ + int (*pvquery)(apr_pool_t *pool, apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, va_list args); + + /** pvselect: select using a prepared statement + args + * + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param args - args to prepared statement + * @return 0 for success or error code + */ + int (*pvselect)(apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, int random, va_list args); + + /** pquery: query using a prepared statement + args + * + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param args - args to prepared statement + * @return 0 for success or error code + */ + int (*pquery)(apr_pool_t *pool, apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, const char **args); + + /** pselect: select using a prepared statement + args + * + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param args - args to prepared statement + * @return 0 for success or error code + */ + int (*pselect)(apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, apr_dbd_prepared_t *statement, + int random, const char **args); + + + /** get_name: get a column title from a result set + * + * @param res - result set pointer + * @param col - entry number + * @return param name, or NULL if col is out of bounds. + */ + const char* (*get_name)(const apr_dbd_results_t *res, int col); + + /** transaction_mode_get: get the mode of transaction + * + * @param trans - the transaction. + * @return mode of transaction + */ + int (*transaction_mode_get)(apr_dbd_transaction_t *trans); + + /** transaction_mode_set: get the mode of transaction + * + * @param trans - the transaction. + * @param mode - new mode of the transaction + * @return the mode of transaction in force after the call + */ + int (*transaction_mode_set)(apr_dbd_transaction_t *trans, int mode); + + /** format of prepared statement parameters */ + const char *pformat; + + /** pvbquery: query using a prepared statement + binary args + * + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ + int (*pvbquery)(apr_pool_t *pool, apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, va_list args); + + /** pvbselect: select using a prepared statement + binary args + * + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ + int (*pvbselect)(apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, int random, va_list args); + + /** pbquery: query using a prepared statement + binary args + * + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ + int (*pbquery)(apr_pool_t *pool, apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement,const void **args); + + /** pbselect: select using a prepared statement + binary args + * + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ + int (*pbselect)(apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, apr_dbd_prepared_t *statement, + int random, const void **args); + + /** datum_get: get a binary entry from a row + * + * @param row - row pointer + * @param col - entry number + * @param type - type of data to get + * @param data - pointer to data, allocated by the caller + * @return APR_SUCCESS, an error code on error or if col is out of bounds + */ + apr_status_t (*datum_get)(const apr_dbd_row_t *row, int col, + apr_dbd_type_e type, void *data); +}; + +/* Export mutex lock/unlock for drivers that need it + * deprecated; create a per-dbd mutex within the (*init) function + * to avoid blocking other providers running on other threads + */ +APU_DECLARE(apr_status_t) apr_dbd_mutex_lock(void); +APU_DECLARE(apr_status_t) apr_dbd_mutex_unlock(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/c/dependencies/windows/apr/x64/include/private/apr_dbd_odbc_v2.h b/c/dependencies/windows/apr/x64/include/private/apr_dbd_odbc_v2.h new file mode 100644 index 00000000..b8da7b18 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/private/apr_dbd_odbc_v2.h @@ -0,0 +1,119 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/* ONLY USED FOR ODBC Version 2 -DODBCV2 +* +* Re-define everything to work (more-or-less) in an ODBC V2 environment +* Random access to retrieved rows is not supported - i.e. calls to apr_dbd_select() cannot +* have a 'random' argument of 1. apr_dbd_get_row() must always pass rownum as 0 (get next row) +* +*/ + +#define SQLHANDLE SQLHENV /* Presumes that ENV, DBC, and STMT handles are all the same datatype */ +#define SQL_NULL_HANDLE 0 +#define SQL_HANDLE_STMT 1 +#define SQL_HANDLE_DBC 2 +#define SQL_HANDLE_ENV 3 +#define SQL_NO_DATA SQL_NO_DATA_FOUND + +#ifndef SQL_SUCCEEDED +#define SQL_SUCCEEDED(rc) (((rc)&(~1))==0) +#endif + +#undef SQLSetEnvAttr +#define SQLSetEnvAttr(henv, Attribute, Value, StringLength) (0) + +#undef SQLAllocHandle +#define SQLAllocHandle(type, parent, hndl) \ +( (type == SQL_HANDLE_STMT) ? SQLAllocStmt(parent, hndl) \ + : (type == SQL_HANDLE_ENV) ? SQLAllocEnv(hndl) \ + : SQLAllocConnect(parent, hndl) \ +) + +#undef SQLFreeHandle +#define SQLFreeHandle(type, hndl) \ +( (type == SQL_HANDLE_STMT) ? SQLFreeStmt(hndl, SQL_DROP) \ + : (type == SQL_HANDLE_ENV) ? SQLFreeEnv(hndl) \ + : SQLFreeConnect(hndl) \ +) + +#undef SQLGetDiagRec +#define SQLGetDiagRec(type, h, i, state, native, buffer, bufsize, reslen) \ + SQLError( (type == SQL_HANDLE_ENV) ? h : NULL, \ + (type == SQL_HANDLE_DBC) ? h : NULL, \ + (type == SQL_HANDLE_STMT) ? h : NULL, \ + state, native, buffer, bufsize, reslen) + +#undef SQLCloseCursor +#define SQLCloseCursor(stmt) SQLFreeStmt(stmt, SQL_CLOSE) + +#undef SQLGetConnectAttr +#define SQLGetConnectAttr(hdbc, fOption, ValuePtr, BufferLength, NULL) \ + SQLGetConnectOption(hdbc, fOption, ValuePtr) + +#undef SQLSetConnectAttr +#define SQLSetConnectAttr(hdbc, fOption, ValuePtr, BufferLength) \ + SQLSetConnectOption(hdbc, fOption, (SQLUINTEGER) ValuePtr) + +#undef SQLSetStmtAttr +#define SQLSetStmtAttr(hstmt, fOption, ValuePtr, BufferLength) (0); return APR_ENOTIMPL; + +#undef SQLEndTran +#define SQLEndTran(hType, hdbc,type) SQLTransact(henv, hdbc, type) + +#undef SQLFetchScroll +#define SQLFetchScroll(stmt, orient, rownum) (0); return APR_ENOTIMPL; + +#define SQL_DESC_TYPE SQL_COLUMN_TYPE +#define SQL_DESC_CONCISE_TYPE SQL_COLUMN_TYPE +#define SQL_DESC_DISPLAY_SIZE SQL_COLUMN_DISPLAY_SIZE +#define SQL_DESC_OCTET_LENGTH SQL_COLUMN_LENGTH +#define SQL_DESC_UNSIGNED SQL_COLUMN_UNSIGNED + +#undef SQLColAttribute +#define SQLColAttribute(s, c, f, a, l, m, n) SQLColAttributes(s, c, f, a, l, m, n) + +#define SQL_ATTR_ACCESS_MODE SQL_ACCESS_MODE +#define SQL_ATTR_AUTOCOMMIT SQL_AUTOCOMMIT +#define SQL_ATTR_CONNECTION_TIMEOUT 113 +#define SQL_ATTR_CURRENT_CATALOG SQL_CURRENT_QUALIFIER +#define SQL_ATTR_DISCONNECT_BEHAVIOR 114 +#define SQL_ATTR_ENLIST_IN_DTC 1207 +#define SQL_ATTR_ENLIST_IN_XA 1208 + +#define SQL_ATTR_CONNECTION_DEAD 1209 +#define SQL_CD_TRUE 1L /* Connection is closed/dead */ +#define SQL_CD_FALSE 0L /* Connection is open/available */ + +#define SQL_ATTR_LOGIN_TIMEOUT SQL_LOGIN_TIMEOUT +#define SQL_ATTR_ODBC_CURSORS SQL_ODBC_CURSORS +#define SQL_ATTR_PACKET_SIZE SQL_PACKET_SIZE +#define SQL_ATTR_QUIET_MODE SQL_QUIET_MODE +#define SQL_ATTR_TRACE SQL_OPT_TRACE +#define SQL_ATTR_TRACEFILE SQL_OPT_TRACEFILE +#define SQL_ATTR_TRANSLATE_LIB SQL_TRANSLATE_DLL +#define SQL_ATTR_TRANSLATE_OPTION SQL_TRANSLATE_OPTION +#define SQL_ATTR_TXN_ISOLATION SQL_TXN_ISOLATION + +#define SQL_ATTR_CURSOR_SCROLLABLE -1 + +#define SQL_C_SBIGINT (SQL_BIGINT+SQL_SIGNED_OFFSET) /* SIGNED BIGINT */ +#define SQL_C_UBIGINT (SQL_BIGINT+SQL_UNSIGNED_OFFSET) /* UNSIGNED BIGINT */ + +#define SQL_FALSE 0 +#define SQL_TRUE 1 + diff --git a/c/dependencies/windows/apr/x64/include/private/apr_dbm_private.h b/c/dependencies/windows/apr/x64/include/private/apr_dbm_private.h new file mode 100644 index 00000000..020d3a6b --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/private/apr_dbm_private.h @@ -0,0 +1,121 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_DBM_PRIVATE_H +#define APR_DBM_PRIVATE_H + +#include "apr.h" +#include "apr_errno.h" +#include "apr_pools.h" +#include "apr_dbm.h" +#include "apr_file_io.h" + +#include "apu.h" + +/* ### for now, include the DBM selection; this will go away once we start + ### building and linking all of the DBMs at once. */ +#include "apu_select_dbm.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** @internal */ + +/** + * Most DBM libraries take a POSIX mode for creating files. Don't trust + * the mode_t type, some platforms may not support it, int is safe. + */ +APU_DECLARE(int) apr_posix_perms2mode(apr_fileperms_t perm); + +/** + * Structure to describe the operations of the DBM + */ +typedef struct { + /** The name of the DBM Type */ + const char *name; + + /** Open the DBM */ + apr_status_t (*open)(apr_dbm_t **pdb, const char *pathname, + apr_int32_t mode, apr_fileperms_t perm, + apr_pool_t *pool); + + /** Close the DBM */ + void (*close)(apr_dbm_t *dbm); + + /** Fetch a dbm record value by key */ + apr_status_t (*fetch)(apr_dbm_t *dbm, apr_datum_t key, + apr_datum_t * pvalue); + + /** Store a dbm record value by key */ + apr_status_t (*store)(apr_dbm_t *dbm, apr_datum_t key, apr_datum_t value); + + /** Delete a dbm record value by key */ + apr_status_t (*del)(apr_dbm_t *dbm, apr_datum_t key); + + /** Search for a key within the dbm */ + int (*exists)(apr_dbm_t *dbm, apr_datum_t key); + + /** Retrieve the first record key from a dbm */ + apr_status_t (*firstkey)(apr_dbm_t *dbm, apr_datum_t * pkey); + + /** Retrieve the next record key from a dbm */ + apr_status_t (*nextkey)(apr_dbm_t *dbm, apr_datum_t * pkey); + + /** Proactively toss any memory associated with the apr_datum_t. */ + void (*freedatum)(apr_dbm_t *dbm, apr_datum_t data); + + /** Get the names that the DBM will use for a given pathname. */ + void (*getusednames)(apr_pool_t *pool, + const char *pathname, + const char **used1, + const char **used2); + +} apr_dbm_type_t; + + +/** + * The actual DBM + */ +struct apr_dbm_t +{ + /** Associated pool */ + apr_pool_t *pool; + + /** pointer to DB Implementation Specific data */ + void *file; + + /** Current integer error code */ + int errcode; + /** Current string error code */ + const char *errmsg; + + /** the type of DBM */ + const apr_dbm_type_t *type; +}; + + +/* Declare all of the DBM provider tables */ +APU_MODULE_DECLARE_DATA extern const apr_dbm_type_t apr_dbm_type_sdbm; +APU_MODULE_DECLARE_DATA extern const apr_dbm_type_t apr_dbm_type_gdbm; +APU_MODULE_DECLARE_DATA extern const apr_dbm_type_t apr_dbm_type_ndbm; +APU_MODULE_DECLARE_DATA extern const apr_dbm_type_t apr_dbm_type_db; + +#ifdef __cplusplus +} +#endif + +#endif /* APR_DBM_PRIVATE_H */ diff --git a/c/dependencies/windows/apr/x64/include/private/apr_encode_private.h b/c/dependencies/windows/apr/x64/include/private/apr_encode_private.h new file mode 100644 index 00000000..8db2e016 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/private/apr_encode_private.h @@ -0,0 +1,84 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_encode_private.h + * @brief APR-UTIL Encoding Private + */ +#ifndef APR_ENCODE_PRIVATE_H +#define APR_ENCODE_PRIVATE_H + +#include "apr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Encode_Private + * @ingroup APR_Util + * @{ + */ + +#if APR_CHARSET_EBCDIC + static int convert_a2e[256] = { + 0x00, 0x01, 0x02, 0x03, 0x37, 0x2D, 0x2E, 0x2F, 0x16, 0x05, 0x15, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, + 0x10, 0x11, 0x12, 0x13, 0x3C, 0x3D, 0x32, 0x26, 0x18, 0x19, 0x3F, 0x27, 0x1C, 0x1D, 0x1E, 0x1F, + 0x40, 0x5A, 0x7F, 0x7B, 0x5B, 0x6C, 0x50, 0x7D, 0x4D, 0x5D, 0x5C, 0x4E, 0x6B, 0x60, 0x4B, 0x61, + 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0x7A, 0x5E, 0x4C, 0x7E, 0x6E, 0x6F, + 0x7C, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, + 0xD7, 0xD8, 0xD9, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xAD, 0xE0, 0xBD, 0x5F, 0x6D, + 0x79, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, + 0x97, 0x98, 0x99, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xC0, 0x4F, 0xD0, 0xA1, 0x07, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x06, 0x17, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x09, 0x0A, 0x1B, + 0x30, 0x31, 0x1A, 0x33, 0x34, 0x35, 0x36, 0x08, 0x38, 0x39, 0x3A, 0x3B, 0x04, 0x14, 0x3E, 0xFF, + 0x41, 0xAA, 0x4A, 0xB1, 0x9F, 0xB2, 0x6A, 0xB5, 0xBB, 0xB4, 0x9A, 0x8A, 0xB0, 0xCA, 0xAF, 0xBC, + 0x90, 0x8F, 0xEA, 0xFA, 0xBE, 0xA0, 0xB6, 0xB3, 0x9D, 0xDA, 0x9B, 0x8B, 0xB7, 0xB8, 0xB9, 0xAB, + 0x64, 0x65, 0x62, 0x66, 0x63, 0x67, 0x9E, 0x68, 0x74, 0x71, 0x72, 0x73, 0x78, 0x75, 0x76, 0x77, + 0xAC, 0x69, 0xED, 0xEE, 0xEB, 0xEF, 0xEC, 0xBF, 0x80, 0xFD, 0xFE, 0xFB, 0xFC, 0xBA, 0xAE, 0x59, + 0x44, 0x45, 0x42, 0x46, 0x43, 0x47, 0x9C, 0x48, 0x54, 0x51, 0x52, 0x53, 0x58, 0x55, 0x56, 0x57, + 0x8C, 0x49, 0xCD, 0xCE, 0xCB, 0xCF, 0xCC, 0xE1, 0x70, 0xDD, 0xDE, 0xDB, 0xDC, 0x8D, 0x8E, 0xDF}; + + static int convert_e2a[256] = { + 0x00, 0x01, 0x02, 0x03, 0x9C, 0x09, 0x86, 0x7F, 0x97, 0x8D, 0x8E, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, + 0x10, 0x11, 0x12, 0x13, 0x9D, 0x0A, 0x08, 0x87, 0x18, 0x19, 0x92, 0x8F, 0x1C, 0x1D, 0x1E, 0x1F, + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x17, 0x1B, 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x05, 0x06, 0x07, + 0x90, 0x91, 0x16, 0x93, 0x94, 0x95, 0x96, 0x04, 0x98, 0x99, 0x9A, 0x9B, 0x14, 0x15, 0x9E, 0x1A, + 0x20, 0xA0, 0xE2, 0xE4, 0xE0, 0xE1, 0xE3, 0xE5, 0xE7, 0xF1, 0xA2, 0x2E, 0x3C, 0x28, 0x2B, 0x7C, + 0x26, 0xE9, 0xEA, 0xEB, 0xE8, 0xED, 0xEE, 0xEF, 0xEC, 0xDF, 0x21, 0x24, 0x2A, 0x29, 0x3B, 0x5E, + 0x2D, 0x2F, 0xC2, 0xC4, 0xC0, 0xC1, 0xC3, 0xC5, 0xC7, 0xD1, 0xA6, 0x2C, 0x25, 0x5F, 0x3E, 0x3F, + 0xF8, 0xC9, 0xCA, 0xCB, 0xC8, 0xCD, 0xCE, 0xCF, 0xCC, 0x60, 0x3A, 0x23, 0x40, 0x27, 0x3D, 0x22, + 0xD8, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xAB, 0xBB, 0xF0, 0xFD, 0xFE, 0xB1, + 0xB0, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0xAA, 0xBA, 0xE6, 0xB8, 0xC6, 0xA4, + 0xB5, 0x7E, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0xA1, 0xBF, 0xD0, 0x5B, 0xDE, 0xAE, + 0xAC, 0xA3, 0xA5, 0xB7, 0xA9, 0xA7, 0xB6, 0xBC, 0xBD, 0xBE, 0xDD, 0xA8, 0xAF, 0x5D, 0xB4, 0xD7, + 0x7B, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0xAD, 0xF4, 0xF6, 0xF2, 0xF3, 0xF5, + 0x7D, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0xB9, 0xFB, 0xFC, 0xF9, 0xFA, 0xFF, + 0x5C, 0xF7, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0xB2, 0xD4, 0xD6, 0xD2, 0xD3, 0xD5, + 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0xB3, 0xDB, 0xDC, 0xD9, 0xDA, 0x9F}; +#define decode ENCODE_TO_ASCII(ch) convert_e2a[(unsigned char)ch] +#define decode ENCODE_TO_NATIVE(ch) convert_a2e[(unsigned char)ch] +#else /* APR_CHARSET_EBCDIC */ +#define ENCODE_TO_ASCII(ch) (ch) +#define ENCODE_TO_NATIVE(ch) (ch) +#endif /* !APR_CHARSET_EBCDIC */ + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ENCODE_PRIVATE_H */ diff --git a/c/dependencies/windows/apr/x64/include/private/apu_config.h b/c/dependencies/windows/apr/x64/include/private/apu_config.h new file mode 100644 index 00000000..b0e20393 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/private/apu_config.h @@ -0,0 +1,52 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Note: This is a Windows specific version of apu_config.hw. It is copied + * as apu_config.h at the start of a Windows build. + */ + +#ifdef WIN32 + +#ifndef APU_CONFIG_H +#define APU_CONFIG_H + +/* Compile win32 with DSO support for .dll builds */ +#ifdef APU_DECLARE_STATIC +#define APU_DSO_BUILD 0 +#else +#define APU_DSO_BUILD 1 +#endif + +/* Presume a standard, modern (5.x) mysql sdk/ +#define HAVE_MY_GLOBAL_H 1 + +/* my_sys.h is broken on VC/Win32, and apparently not required */ +/* #undef HAVE_MY_SYS_H 0 */ + +/* + * Windows does not have GDBM, and we always use the bundled (new) Expat + */ + +/* Define if you have the gdbm library (-lgdbm). */ +/* #undef HAVE_LIBGDBM */ + +/* define if Expat 1.0 or 1.1 was found */ +/* #undef APR_HAVE_OLD_EXPAT */ + + +#endif /* APU_CONFIG_H */ +#endif /* WIN32 */ diff --git a/c/dependencies/windows/apr/x64/include/private/apu_config.hnw b/c/dependencies/windows/apr/x64/include/private/apu_config.hnw new file mode 100644 index 00000000..c7a6124b --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/private/apu_config.hnw @@ -0,0 +1,53 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Note: This is a NetWare specific version of apu_config.hnw. It is copied + * as apu_config.h at the start of a NetWare build. + */ + +#ifdef NETWARE + +#ifndef APU_CONFIG_H +#define APU_CONFIG_H + +/* Always compile Netware with DSO support for .nlm builds */ +#define APU_DSO_BUILD 0 + +/* + * NetWare does not have GDBM, and we always use the bundled (new) Expat + */ + +/* Define if you have the gdbm library (-lgdbm). */ +/* #undef HAVE_LIBGDBM */ + +/* define if Expat 1.0 or 1.1 was found */ +/* #undef APR_HAVE_OLD_EXPAT */ + +/* NetWare uses its own ICONV implementation. */ +#define HAVE_ICONV_H 1 + +/* + * check for newer NDKs which use now correctly 'const char*' with iconv. + */ +#include +#if (CURRENT_NDK_THRESHOLD >= 705110000) +#define APU_ICONV_INBUF_CONST +#endif + +#endif /* APU_CONFIG_H */ +#endif /* NETWARE */ + diff --git a/c/dependencies/windows/apr/x64/include/private/apu_config.hw b/c/dependencies/windows/apr/x64/include/private/apu_config.hw new file mode 100644 index 00000000..ac262fcb --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/private/apu_config.hw @@ -0,0 +1,52 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Note: This is a Windows specific version of apu_config.hw. It is copied + * as apu_config.h at the start of a Windows build. + */ + +#ifdef WIN32 + +#ifndef APU_CONFIG_H +#define APU_CONFIG_H + +/* Compile win32 with DSO support for .dll builds */ +#ifdef APU_DECLARE_STATIC +#define APU_DSO_BUILD 0 +#else +#define APU_DSO_BUILD 1 +#endif + +/* Presume a standard, modern (5.x) mysql sdk/ +#define HAVE_MY_GLOBAL_H 1 + +/* my_sys.h is broken on VC/Win32, and apparently not required */ +/* #undef HAVE_MY_SYS_H 0 */ + +/* + * Windows does not have GDBM, and we always use the bundled (new) Expat + */ + +/* Define if you have the gdbm library (-lgdbm). */ +/* #undef HAVE_LIBGDBM */ + +/* define if Expat 1.0 or 1.1 was found */ +/* #undef APR_HAVE_OLD_EXPAT */ + + +#endif /* APU_CONFIG_H */ +#endif /* WIN32 */ diff --git a/c/dependencies/windows/apr/x64/include/private/apu_internal.h b/c/dependencies/windows/apr/x64/include/private/apu_internal.h new file mode 100644 index 00000000..c95c9d50 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/private/apu_internal.h @@ -0,0 +1,73 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr.h" +#include "apr_dso.h" +#include "apu.h" + +#ifndef APU_INTERNAL_H +#define APU_INTERNAL_H + +#if APU_DSO_BUILD + +#ifdef __cplusplus +extern "C" { +#endif + +/* For modular dso loading, an internal interlock to allow us to + * continue to initialize modules by multiple threads, the caller + * of apu_dso_load must lock first, and not unlock until any init + * finalization is complete. + */ +apr_status_t apu_dso_init(apr_pool_t *pool); + +apr_status_t apu_dso_mutex_lock(void); +apr_status_t apu_dso_mutex_unlock(void); + +apr_status_t apu_dso_load(apr_dso_handle_t **dso, apr_dso_handle_sym_t *dsoptr, const char *module, + const char *modsym, apr_pool_t *pool); + +#if APR_HAS_LDAP + +/* For LDAP internal builds, wrap our LDAP namespace */ + +struct apr__ldap_dso_fntable { + int (*info)(apr_pool_t *pool, apr_ldap_err_t **result_err); + int (*init)(apr_pool_t *pool, LDAP **ldap, const char *hostname, + int portno, int secure, apr_ldap_err_t **result_err); + int (*ssl_init)(apr_pool_t *pool, const char *cert_auth_file, + int cert_file_type, apr_ldap_err_t **result_err); + int (*ssl_deinit)(void); + int (*get_option)(apr_pool_t *pool, LDAP *ldap, int option, + void *outvalue, apr_ldap_err_t **result_err); + int (*set_option)(apr_pool_t *pool, LDAP *ldap, int option, + const void *invalue, apr_ldap_err_t **result_err); + apr_status_t (*rebind_init)(apr_pool_t *pool); + apr_status_t (*rebind_add)(apr_pool_t *pool, LDAP *ld, + const char *bindDN, const char *bindPW); + apr_status_t (*rebind_remove)(LDAP *ld); +}; + +#endif /* APR_HAS_LDAP */ + +#ifdef __cplusplus +} +#endif + +#endif /* APU_DSO_BUILD */ + +#endif /* APU_INTERNAL_H */ + diff --git a/c/dependencies/windows/apr/x64/include/private/apu_select_dbm.h b/c/dependencies/windows/apr/x64/include/private/apu_select_dbm.h new file mode 100644 index 00000000..97c7b6c2 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/private/apu_select_dbm.h @@ -0,0 +1,28 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APU_SELECT_DBM_H +#define APU_SELECT_DBM_H + +/* +** The following macros control what features APRUTIL will use +*/ +#define APU_USE_SDBM 1 +#define APU_USE_GDBM 0 +#define APU_USE_NDBM 0 +#define APU_USE_DB 0 + +#endif /* !APU_SELECT_DBM_H */ diff --git a/c/dependencies/windows/apr/x64/include/private/apu_select_dbm.h.in b/c/dependencies/windows/apr/x64/include/private/apu_select_dbm.h.in new file mode 100644 index 00000000..d66be5fc --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/private/apu_select_dbm.h.in @@ -0,0 +1,28 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APU_SELECT_DBM_H +#define APU_SELECT_DBM_H + +/* +** The following macros control what features APRUTIL will use +*/ +#define APU_USE_SDBM @apu_use_sdbm@ +#define APU_USE_NDBM @apu_use_ndbm@ +#define APU_USE_GDBM @apu_use_gdbm@ +#define APU_USE_DB @apu_use_db@ + +#endif /* !APU_SELECT_DBM_H */ diff --git a/c/dependencies/windows/apr/x64/include/private/apu_select_dbm.hw b/c/dependencies/windows/apr/x64/include/private/apu_select_dbm.hw new file mode 100644 index 00000000..baa6c144 --- /dev/null +++ b/c/dependencies/windows/apr/x64/include/private/apu_select_dbm.hw @@ -0,0 +1,28 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APU_SELECT_DBM_H +#define APU_SELECT_DBM_H + +/* +** The following macros control what features APRUTIL will use +*/ +#define APU_USE_SDBM 1 +#define APU_USE_GDBM 0 +#define APU_USE_NDBM 0 +#define APU_USE_DB 0 + +#endif /* !APU_SELECT_DBM_H */ diff --git a/c/dependencies/windows/apr/x64/lib/apr.lib b/c/dependencies/windows/apr/x64/lib/apr.lib new file mode 100644 index 00000000..74d7278b Binary files /dev/null and b/c/dependencies/windows/apr/x64/lib/apr.lib differ diff --git a/c/dependencies/windows/apr/x64/lib/apr.pdb b/c/dependencies/windows/apr/x64/lib/apr.pdb new file mode 100644 index 00000000..918168b1 Binary files /dev/null and b/c/dependencies/windows/apr/x64/lib/apr.pdb differ diff --git a/c/dependencies/windows/apr/x64/lib/aprapp.lib b/c/dependencies/windows/apr/x64/lib/aprapp.lib new file mode 100644 index 00000000..f4acfa01 Binary files /dev/null and b/c/dependencies/windows/apr/x64/lib/aprapp.lib differ diff --git a/c/dependencies/windows/apr/x64/lib/aprapp.pdb b/c/dependencies/windows/apr/x64/lib/aprapp.pdb new file mode 100644 index 00000000..ae62f395 Binary files /dev/null and b/c/dependencies/windows/apr/x64/lib/aprapp.pdb differ diff --git a/c/dependencies/windows/apr/x64/lib/apriconv.lib b/c/dependencies/windows/apr/x64/lib/apriconv.lib new file mode 100644 index 00000000..81589787 Binary files /dev/null and b/c/dependencies/windows/apr/x64/lib/apriconv.lib differ diff --git a/c/dependencies/windows/apr/x64/lib/apriconv.pdb b/c/dependencies/windows/apr/x64/lib/apriconv.pdb new file mode 100644 index 00000000..cf3647d8 Binary files /dev/null and b/c/dependencies/windows/apr/x64/lib/apriconv.pdb differ diff --git a/c/dependencies/windows/apr/x64/lib/aprutil.lib b/c/dependencies/windows/apr/x64/lib/aprutil.lib new file mode 100644 index 00000000..ff60bd38 Binary files /dev/null and b/c/dependencies/windows/apr/x64/lib/aprutil.lib differ diff --git a/c/dependencies/windows/apr/x64/lib/aprutil.pdb b/c/dependencies/windows/apr/x64/lib/aprutil.pdb new file mode 100644 index 00000000..0288e2cf Binary files /dev/null and b/c/dependencies/windows/apr/x64/lib/aprutil.pdb differ diff --git a/c/dependencies/windows/apr/x64/lib/libapr.lib b/c/dependencies/windows/apr/x64/lib/libapr.lib new file mode 100644 index 00000000..61a8189d Binary files /dev/null and b/c/dependencies/windows/apr/x64/lib/libapr.lib differ diff --git a/c/dependencies/windows/apr/x64/lib/libapr.pdb b/c/dependencies/windows/apr/x64/lib/libapr.pdb new file mode 100644 index 00000000..f0086747 Binary files /dev/null and b/c/dependencies/windows/apr/x64/lib/libapr.pdb differ diff --git a/c/dependencies/windows/apr/x64/lib/libapr_src.pdb b/c/dependencies/windows/apr/x64/lib/libapr_src.pdb new file mode 100644 index 00000000..71b5b783 Binary files /dev/null and b/c/dependencies/windows/apr/x64/lib/libapr_src.pdb differ diff --git a/c/dependencies/windows/apr/x64/lib/libaprapp.lib b/c/dependencies/windows/apr/x64/lib/libaprapp.lib new file mode 100644 index 00000000..652060e5 Binary files /dev/null and b/c/dependencies/windows/apr/x64/lib/libaprapp.lib differ diff --git a/c/dependencies/windows/apr/x64/lib/libaprapp.pdb b/c/dependencies/windows/apr/x64/lib/libaprapp.pdb new file mode 100644 index 00000000..01d2d6a7 Binary files /dev/null and b/c/dependencies/windows/apr/x64/lib/libaprapp.pdb differ diff --git a/c/dependencies/windows/apr/x64/lib/libapriconv.lib b/c/dependencies/windows/apr/x64/lib/libapriconv.lib new file mode 100644 index 00000000..859b93a1 Binary files /dev/null and b/c/dependencies/windows/apr/x64/lib/libapriconv.lib differ diff --git a/c/dependencies/windows/apr/x64/lib/libapriconv.pdb b/c/dependencies/windows/apr/x64/lib/libapriconv.pdb new file mode 100644 index 00000000..c786c191 Binary files /dev/null and b/c/dependencies/windows/apr/x64/lib/libapriconv.pdb differ diff --git a/c/dependencies/windows/apr/x64/lib/libapriconv_src.pdb b/c/dependencies/windows/apr/x64/lib/libapriconv_src.pdb new file mode 100644 index 00000000..72af4c5a Binary files /dev/null and b/c/dependencies/windows/apr/x64/lib/libapriconv_src.pdb differ diff --git a/c/dependencies/windows/apr/x64/lib/libaprutil.lib b/c/dependencies/windows/apr/x64/lib/libaprutil.lib new file mode 100644 index 00000000..24b5669a Binary files /dev/null and b/c/dependencies/windows/apr/x64/lib/libaprutil.lib differ diff --git a/c/dependencies/windows/apr/x64/lib/libaprutil.pdb b/c/dependencies/windows/apr/x64/lib/libaprutil.pdb new file mode 100644 index 00000000..f0e07638 Binary files /dev/null and b/c/dependencies/windows/apr/x64/lib/libaprutil.pdb differ diff --git a/c/dependencies/windows/apr/x64/lib/libaprutil_src.pdb b/c/dependencies/windows/apr/x64/lib/libaprutil_src.pdb new file mode 100644 index 00000000..b3eacfe6 Binary files /dev/null and b/c/dependencies/windows/apr/x64/lib/libaprutil_src.pdb differ diff --git a/c/dependencies/windows/apr/x64_debug/include/api_version.h b/c/dependencies/windows/apr/x64_debug/include/api_version.h new file mode 100644 index 00000000..c2788959 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/api_version.h @@ -0,0 +1,132 @@ +/* Copyright 2000-2017 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef API_VERSION_H +#define API_VERSION_H + +/** + * @file api_version.h + * @brief APR-iconv Versioning Interface + * + * APR-iconv's Version + * + * There are several different mechanisms for accessing the version. There + * is a string form, and a set of numbers; in addition, there are constants + * which can be compiled into your application, and you can query the library + * being used for its actual version. + * + * Note that it is possible for an application to detect that it has been + * compiled against a different version of API by use of the compile-time + * constants and the use of the run-time query function. + * + * API version numbering follows the guidelines specified in: + * + * http://apr.apache.org/versioning.html + */ + + +/* The numeric compile-time version constants. These constants are the + * authoritative version numbers for API. + */ + +/** major version + * Major API changes that could cause compatibility problems for older + * programs such as structure size changes. No binary compatibility is + * possible across a change in the major version. + */ +#define API_MAJOR_VERSION 1 + +/** minor version + * Minor API changes that do not cause binary compatibility problems. + * Reset to 0 when upgrading API_MAJOR_VERSION + */ +#define API_MINOR_VERSION 2 + +/** patch level + * The Patch Level never includes API changes, simply bug fixes. + * Reset to 0 when upgrading API_MINOR_VERSION + */ +#define API_PATCH_VERSION 2 + +/** + * The symbol API_IS_DEV_VERSION is only defined for internal, + * "development" copies of API. It is undefined for released versions + * of API. + */ +/* #undef API_IS_DEV_VERSION */ + + +#if defined(API_IS_DEV_VERSION) || defined(DOXYGEN) +/** Internal: string form of the "is dev" flag */ +#define API_IS_DEV_STRING "-dev" +#else +#define API_IS_DEV_STRING "" +#endif + +#ifndef API_STRINGIFY +/** Properly quote a value as a string in the C preprocessor */ +#define API_STRINGIFY(n) API_STRINGIFY_HELPER(n) +/** Helper macro for API_STRINGIFY */ +#define API_STRINGIFY_HELPER(n) #n +#endif + +/** The formatted string of API's version */ +#define API_VERSION_STRING \ + API_STRINGIFY(API_MAJOR_VERSION) "." \ + API_STRINGIFY(API_MINOR_VERSION) "." \ + API_STRINGIFY(API_PATCH_VERSION) \ + API_IS_DEV_STRING + +/** An alternative formatted string of APR's version */ +/* macro for Win32 .rc files using numeric csv representation */ +#define API_VERSION_STRING_CSV API_MAJOR_VERSION ##, \ + ##API_MINOR_VERSION ##, \ + ##API_PATCH_VERSION + + +#ifndef API_VERSION_ONLY + +/* The C language API to access the version at run time, + * as opposed to compile time. API_VERSION_ONLY may be defined + * externally when preprocessing apr_version.h to obtain strictly + * the C Preprocessor macro declarations. + */ + +#include "apr_version.h" + +#include "apr_iconv.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Return APR-iconv's version information information in a numeric form. + * + * @param pvsn Pointer to a version structure for returning the version + * information. + */ +API_DECLARE(void) api_version(apr_version_t *pvsn); + +/** Return API's version information as a string. */ +API_DECLARE(const char *) api_version_string(void); + +#ifdef __cplusplus +} +#endif + +#endif /* ndef API_VERSION_ONLY */ + +#endif /* ndef API_VERSION_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr.h b/c/dependencies/windows/apr/x64_debug/include/apr.h new file mode 100644 index 00000000..3352fef3 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr.h @@ -0,0 +1,667 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef APR_H +#define APR_H + +/* GENERATED FILE WARNING! DO NOT EDIT apr.h + * + * You must modify apr.hw instead. + * + * And please, make an effort to stub apr.hnw and apr.h.in in the process. + * + * This is the Win32 specific version of apr.h. It is copied from + * apr.hw by the apr.dsp and libapr.dsp projects. + */ + +/** + * @file apr.h + * @brief APR Platform Definitions + * @remark This is a generated header generated from include/apr.h.in by + * ./configure, or copied from include/apr.hw or include/apr.hnw + * for Win32 or Netware by those build environments, respectively. + */ + +/* Make sure we have our platform identifier macro defined we ask for later. + */ +#if defined(_WIN32) && !defined(WIN32) +#define WIN32 1 +#endif + +#if defined(WIN32) || defined(DOXYGEN) + +/* Ignore most warnings (back down to /W3) for poorly constructed headers + */ +#if defined(_MSC_VER) && _MSC_VER >= 1200 +#pragma warning(push, 3) +#endif + +/* disable or reduce the frequency of... + * C4057: indirection to slightly different base types + * C4075: slight indirection changes (unsigned short* vs short[]) + * C4100: unreferenced formal parameter + * C4127: conditional expression is constant + * C4163: '_rotl64' : not available as an intrinsic function + * C4201: nonstandard extension nameless struct/unions + * C4244: int to char/short - precision loss + * C4514: unreferenced inline function removed + */ +#if defined(_MSC_VER) +#pragma warning(disable: 4100 4127 4163 4201 4514; once: 4057 4075 4244) +#endif + +/* Ignore Microsoft's interpretation of secure development + * and the POSIX string handling API + */ +#if defined(_MSC_VER) && _MSC_VER >= 1400 +#ifndef _CRT_SECURE_NO_DEPRECATE +#define _CRT_SECURE_NO_DEPRECATE +#endif +#pragma warning(disable: 4996) +#endif + +/* Has windows.h already been included? If so, our preferences don't matter, + * but we will still need the winsock things no matter what was included. + * If not, include a restricted set of windows headers to our tastes. + */ +#ifndef _WINDOWS_ +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef _WIN32_WINNT + +/* Restrict the server to a subset of Windows XP header files by default + */ +#define _WIN32_WINNT 0x0A00 +#endif +#ifndef NOUSER +#define NOUSER +#endif +#ifndef NOMCX +#define NOMCX +#endif +#ifndef NOIME +#define NOIME +#endif +#include +/* + * Add a _very_few_ declarations missing from the restricted set of headers + * (If this list becomes extensive, re-enable the required headers above!) + * winsock headers were excluded by WIN32_LEAN_AND_MEAN, so include them now + */ +#define SW_HIDE 0 +#ifndef _WIN32_WCE +#include +#include +#include +#else +#include +#endif +#endif /* !_WINDOWS_ */ + +/** + * @defgroup APR Apache Portability Runtime library + * @{ + */ +/** + * @defgroup apr_platform Platform Definitions + * @{ + * @warning + * The actual values of macros and typedefs on this page
+ * are platform specific and should NOT be relied upon!
+ */ + +#define APR_INLINE __inline +#define APR_HAS_INLINE 1 +#if !defined(__GNUC__) && !defined(__attribute__) +#define __attribute__(__x) +#endif + +#ifndef _WIN32_WCE +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_CONIO_H 1 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 1 +#define APR_HAVE_DIRENT_H 0 +#define APR_HAVE_ERRNO_H 1 +#define APR_HAVE_FCNTL_H 1 +#define APR_HAVE_IO_H 1 +#define APR_HAVE_LIMITS_H 1 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SEMAPHORE_H 0 +#define APR_HAVE_SIGNAL_H 1 +#define APR_HAVE_STDARG_H 1 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_SYS_IOCTL_H 0 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SIGNAL_H 0 +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#define APR_HAVE_SYS_TIME_H 0 +#define APR_HAVE_SYS_TYPES_H 1 +#define APR_HAVE_SYS_UIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#define APR_HAVE_SYS_WAIT_H 0 +#define APR_HAVE_TIME_H 1 +#define APR_HAVE_UNISTD_H 0 +#define APR_HAVE_STDDEF_H 1 +#define APR_HAVE_PROCESS_H 1 +#else +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_CONIO_H 0 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 0 +#define APR_HAVE_DIRENT_H 0 +#define APR_HAVE_ERRNO_H 0 +#define APR_HAVE_FCNTL_H 0 +#define APR_HAVE_IO_H 0 +#define APR_HAVE_LIMITS_H 0 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SEMAPHORE_H 0 +#define APR_HAVE_SIGNAL_H 0 +#define APR_HAVE_STDARG_H 0 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_SYS_IOCTL_H 0 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SIGNAL_H 0 +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#define APR_HAVE_SYS_TIME_H 0 +#define APR_HAVE_SYS_TYPES_H 0 +#define APR_HAVE_SYS_UIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#define APR_HAVE_SYS_WAIT_H 0 +#define APR_HAVE_TIME_H 0 +#define APR_HAVE_UNISTD_H 0 +#define APR_HAVE_STDDEF_H 0 +#define APR_HAVE_PROCESS_H 0 +#endif + +/** @} */ +/** @} */ + +/* We don't include our conditional headers within the doxyblocks + * or the extern "C" namespace + */ + +#if APR_HAVE_STDLIB_H +#include +#endif + +#if APR_HAVE_STDIO_H +#include +#endif + +#if APR_HAVE_SYS_TYPES_H +#include +#endif + +#if APR_HAVE_STDDEF_H +#include +#endif + +#if APR_HAVE_SYS_SOCKET_H +#include +#endif + +#if APR_HAVE_STDINT_H +#include +#endif + +#if APR_HAVE_SYS_WAIT_H +#include +#endif + +#if APR_HAVE_TIME_H +#include +#endif + +#if APR_HAVE_PROCESS_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @addtogroup apr_platform + * @ingroup APR + * @{ + */ + +#define APR_HAVE_SHMEM_MMAP_TMP 0 +#define APR_HAVE_SHMEM_MMAP_SHM 0 +#define APR_HAVE_SHMEM_MMAP_ZERO 0 +#define APR_HAVE_SHMEM_SHMGET_ANON 0 +#define APR_HAVE_SHMEM_SHMGET 0 +#define APR_HAVE_SHMEM_MMAP_ANON 0 +#define APR_HAVE_SHMEM_BEOS 0 + +#define APR_USE_SHMEM_MMAP_TMP 0 +#define APR_USE_SHMEM_MMAP_SHM 0 +#define APR_USE_SHMEM_MMAP_ZERO 0 +#define APR_USE_SHMEM_SHMGET_ANON 0 +#define APR_USE_SHMEM_SHMGET 0 +#define APR_USE_SHMEM_MMAP_ANON 0 +#define APR_USE_SHMEM_BEOS 0 + +#define APR_USE_FLOCK_SERIALIZE 0 +#define APR_USE_POSIXSEM_SERIALIZE 0 +#define APR_USE_SYSVSEM_SERIALIZE 0 +#define APR_USE_FCNTL_SERIALIZE 0 +#define APR_USE_PROC_PTHREAD_SERIALIZE 0 +#define APR_USE_PTHREAD_SERIALIZE 0 + +#define APR_HAS_FLOCK_SERIALIZE 0 +#define APR_HAS_SYSVSEM_SERIALIZE 0 +#define APR_HAS_POSIXSEM_SERIALIZE 0 +#define APR_HAS_FCNTL_SERIALIZE 0 +#define APR_HAS_PROC_PTHREAD_SERIALIZE 0 + +#define APR_PROCESS_LOCK_IS_GLOBAL 0 + +#define APR_HAVE_CORKABLE_TCP 0 +#define APR_HAVE_GETRLIMIT 0 +#define APR_HAVE_ICONV 0 +#define APR_HAVE_IN_ADDR 1 +#define APR_HAVE_INET_ADDR 1 +#define APR_HAVE_INET_NETWORK 0 +#define APR_HAVE_IPV6 1 +#define APR_HAVE_SOCKADDR_UN 0 +#define APR_HAVE_MEMMOVE 1 +#define APR_HAVE_SETRLIMIT 0 +#define APR_HAVE_SIGACTION 0 +#define APR_HAVE_SIGSUSPEND 0 +#define APR_HAVE_SIGWAIT 0 +#define APR_HAVE_SA_STORAGE 0 +#define APR_HAVE_STRCASECMP 0 +#define APR_HAVE_STRDUP 1 +#define APR_HAVE_STRNCASECMP 0 +#define APR_HAVE_STRSTR 1 +#define APR_HAVE_MEMCHR 1 +#define APR_HAVE_STRUCT_RLIMIT 0 +#define APR_HAVE_UNION_SEMUN 0 +#define APR_HAVE_SCTP 0 +#define APR_HAVE_IOVEC 0 + +#ifndef _WIN32_WCE +#define APR_HAVE_STRICMP 1 +#define APR_HAVE_STRNICMP 1 +#else +#define APR_HAVE_STRICMP 0 +#define APR_HAVE_STRNICMP 0 +#endif + +/* APR Feature Macros */ +#define APR_HAS_SHARED_MEMORY 1 +#define APR_HAS_THREADS 1 +#define APR_HAS_MMAP 1 +#define APR_HAS_FORK 0 +#define APR_HAS_RANDOM 1 +#define APR_HAS_OTHER_CHILD 1 +#define APR_HAS_DSO 1 +#define APR_HAS_SO_ACCEPTFILTER 0 +#define APR_HAS_UNICODE_FS 1 +#define APR_HAS_PROC_INVOKED 1 +#define APR_HAS_OS_UUID 1 +#define APR_HAS_TIMEDLOCKS 1 + +#ifndef _WIN32_WCE +#define APR_HAS_SENDFILE 1 +#define APR_HAS_USER 1 +#define APR_HAS_LARGE_FILES 1 +#define APR_HAS_XTHREAD_FILES 1 +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 1 +#else +#define APR_HAS_SENDFILE 0 +#define APR_HAS_USER 0 +#define APR_HAS_LARGE_FILES 0 +#define APR_HAS_XTHREAD_FILES 0 +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 0 +#endif + +/* APR sets APR_FILES_AS_SOCKETS to 1 on systems where it is possible + * to poll on files/pipes. + */ +#define APR_FILES_AS_SOCKETS 0 + +/* This macro indicates whether or not EBCDIC is the native character set. + */ +#define APR_CHARSET_EBCDIC 0 + +/* If we have a TCP implementation that can be "corked", what flag + * do we use? + */ +#define APR_TCP_NOPUSH_FLAG @apr_tcp_nopush_flag@ + +/* Is the TCP_NODELAY socket option inherited from listening sockets? + */ +#define APR_TCP_NODELAY_INHERITED 1 + +/* Is the O_NONBLOCK flag inherited from listening sockets? + */ +#define APR_O_NONBLOCK_INHERITED 1 + +/* Typedefs that APR needs. */ + +typedef unsigned char apr_byte_t; + +typedef short apr_int16_t; +typedef unsigned short apr_uint16_t; + +typedef int apr_int32_t; +typedef unsigned int apr_uint32_t; + +typedef __int64 apr_int64_t; +typedef unsigned __int64 apr_uint64_t; + +typedef size_t apr_size_t; +#if APR_HAVE_STDDEF_H +typedef ptrdiff_t apr_ssize_t; +#else +typedef int apr_ssize_t; +#endif +#if APR_HAS_LARGE_FILES +typedef __int64 apr_off_t; +#else +typedef int apr_off_t; +#endif +typedef int apr_socklen_t; +typedef apr_uint64_t apr_ino_t; + +#ifdef _WIN64 +#define APR_SIZEOF_VOIDP 8 +#else +#define APR_SIZEOF_VOIDP 4 +#endif + +#if APR_SIZEOF_VOIDP == 8 +typedef apr_uint64_t apr_uintptr_t; +#else +typedef apr_uint32_t apr_uintptr_t; +#endif + +/* Are we big endian? */ +/* XXX: Fatal assumption on Alpha platforms */ +#define APR_IS_BIGENDIAN 0 + +/* Mechanisms to properly type numeric literals */ + +#ifndef __GNUC__ +#define APR_INT64_C(val) (val##i64) +#define APR_UINT64_C(val) (val##Ui64) +#else +#define APR_INT64_C(val) (val##LL) +#define APR_UINT64_C(val) (val##ULL) +#endif + +#ifdef INT16_MIN +#define APR_INT16_MIN INT16_MIN +#else +#define APR_INT16_MIN (-0x7fff - 1) +#endif + +#ifdef INT16_MAX +#define APR_INT16_MAX INT16_MAX +#else +#define APR_INT16_MAX (0x7fff) +#endif + +#ifdef UINT16_MAX +#define APR_UINT16_MAX UINT16_MAX +#else +#define APR_UINT16_MAX (0xffff) +#endif + +#ifdef INT32_MIN +#define APR_INT32_MIN INT32_MIN +#else +#define APR_INT32_MIN (-0x7fffffff - 1) +#endif + +#ifdef INT32_MAX +#define APR_INT32_MAX INT32_MAX +#else +#define APR_INT32_MAX 0x7fffffff +#endif + +#ifdef UINT32_MAX +#define APR_UINT32_MAX UINT32_MAX +#else +#define APR_UINT32_MAX (0xffffffffU) +#endif + +#ifdef INT64_MIN +#define APR_INT64_MIN INT64_MIN +#else +#define APR_INT64_MIN (APR_INT64_C(-0x7fffffffffffffff) - 1) +#endif + +#ifdef INT64_MAX +#define APR_INT64_MAX INT64_MAX +#else +#define APR_INT64_MAX APR_INT64_C(0x7fffffffffffffff) +#endif + +#ifdef UINT64_MAX +#define APR_UINT64_MAX UINT64_MAX +#else +#define APR_UINT64_MAX APR_UINT64_C(0xffffffffffffffff) +#endif + +#define APR_SIZE_MAX (~((apr_size_t)0)) + +/* Definitions that APR programs need to work properly. */ + +/** + * APR public API wrap for C++ compilers. + */ +#ifdef __cplusplus +#define APR_BEGIN_DECLS extern "C" { +#define APR_END_DECLS } +#else +#define APR_BEGIN_DECLS +#define APR_END_DECLS +#endif + +/** + * Thread callbacks from APR functions must be declared with APR_THREAD_FUNC, + * so that they follow the platform's calling convention. + *
+ *
+ * void* APR_THREAD_FUNC my_thread_entry_fn(apr_thread_t *thd, void *data);
+ *
+ * 
+ */ +#define APR_THREAD_FUNC __stdcall + + +#if defined(DOXYGEN) || !defined(WIN32) + +/** + * The public APR functions are declared with APR_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APR_DECLARE_NONSTD(). + * + * @remark Both the declaration and implementations must use the same macro. + * + *
+ * APR_DECLARE(rettype) apr_func(args)
+ * 
+ * @see APR_DECLARE_NONSTD @see APR_DECLARE_DATA + * @remark Note that when APR compiles the library itself, it passes the + * symbol -DAPR_DECLARE_EXPORT to the compiler on some platforms (e.g. Win32) + * to export public symbols from the dynamic library build.\n + * The user must define the APR_DECLARE_STATIC when compiling to target + * the static APR library on some platforms (e.g. Win32.) The public symbols + * are neither exported nor imported when APR_DECLARE_STATIC is defined.\n + * By default, compiling an application and including the APR public + * headers, without defining APR_DECLARE_STATIC, will prepare the code to be + * linked to the dynamic library. + */ +#define APR_DECLARE(type) type + +/** + * The public APR functions using variable arguments are declared with + * APR_DECLARE_NONSTD(), as they must follow the C language calling convention. + * @see APR_DECLARE @see APR_DECLARE_DATA + * @remark Both the declaration and implementations must use the same macro. + *
+ *
+ * APR_DECLARE_NONSTD(rettype) apr_func(args, ...);
+ *
+ * 
+ */ +#define APR_DECLARE_NONSTD(type) type + +/** + * The public APR variables are declared with AP_MODULE_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * @see APR_DECLARE @see APR_DECLARE_NONSTD + * @remark Note that the declaration and implementations use different forms, + * but both must include the macro. + * + *
+ *
+ * extern APR_DECLARE_DATA type apr_variable;\n
+ * APR_DECLARE_DATA type apr_variable = value;
+ *
+ * 
+ */ +#define APR_DECLARE_DATA + +#elif defined(APR_DECLARE_STATIC) +#define APR_DECLARE(type) type __stdcall +#define APR_DECLARE_NONSTD(type) type __cdecl +#define APR_DECLARE_DATA +#elif defined(APR_DECLARE_EXPORT) +#define APR_DECLARE(type) __declspec(dllexport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllexport) +#else +#define APR_DECLARE(type) __declspec(dllimport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllimport) +#endif + +#ifdef _WIN64 +#define APR_SSIZE_T_FMT "I64d" +#define APR_SIZE_T_FMT "I64u" +#else +#define APR_SSIZE_T_FMT "d" +#define APR_SIZE_T_FMT "u" +#endif + +#if APR_HAS_LARGE_FILES +#define APR_OFF_T_FMT "I64d" +#else +#define APR_OFF_T_FMT "d" +#endif + +#define APR_PID_T_FMT "d" + +#define APR_INT64_T_FMT "I64d" +#define APR_UINT64_T_FMT "I64u" +#define APR_UINT64_T_HEX_FMT "I64x" + +/* No difference between PROC and GLOBAL mutex */ +#define APR_PROC_MUTEX_IS_GLOBAL 1 + +/* Local machine definition for console and log output. */ +#define APR_EOL_STR "\r\n" + +typedef int apr_wait_t; + +#if APR_HAS_UNICODE_FS +/* An arbitrary size that is digestable. True max is a bit less than 32000 */ +#define APR_PATH_MAX 8192 +#else /* !APR_HAS_UNICODE_FS */ +#define APR_PATH_MAX MAX_PATH +#endif + +#define APR_DSOPATH "PATH" + +/** @} */ + +/* Definitions that only Win32 programs need to compile properly. */ + +/* XXX These simply don't belong here, perhaps in apr_portable.h + * based on some APR_HAVE_PID/GID/UID? + */ +#ifndef __GNUC__ +typedef int pid_t; +#endif +typedef int uid_t; +typedef int gid_t; + +/* Win32 .h ommissions we really need */ +#define STDIN_FILENO 0 +#define STDOUT_FILENO 1 +#define STDERR_FILENO 2 + +#if APR_HAVE_IPV6 + +/* Appears in later flavors, not the originals. */ +#ifndef in_addr6 +#define in6_addr in_addr6 +#endif + +#ifndef WS2TCPIP_INLINE +#define IN6_IS_ADDR_V4MAPPED(a) \ + ( (*(const apr_uint64_t *)(const void *)(&(a)->s6_addr[0]) == 0) \ + && (*(const apr_uint32_t *)(const void *)(&(a)->s6_addr[8]) == ntohl(0x0000ffff))) +#endif + +#endif /* APR_HAVE_IPV6 */ + +#ifdef __cplusplus +} +#endif + +/* Done with badly written headers, leave 'deprecated CRT' undeprecated + */ +#if defined(_MSC_VER) && _MSC_VER >= 1200 +#pragma warning(pop) +#if _MSC_VER >= 1400 +#pragma warning(disable: 4996) +#endif +#endif + +#endif /* WIN32 */ + +#endif /* APR_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr.h.in b/c/dependencies/windows/apr/x64_debug/include/apr.h.in new file mode 100644 index 00000000..47d8b55a --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr.h.in @@ -0,0 +1,656 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef APR_H +#define APR_H + +/* GENERATED FILE WARNING! DO NOT EDIT apr.h + * + * You must modify apr.h.in instead. + * + * And please, make an effort to stub apr.hw and apr.hnw in the process. + */ + +/** + * @file apr.h + * @brief APR Platform Definitions + * @remark This is a generated header generated from include/apr.h.in by + * ./configure, or copied from include/apr.hw or include/apr.hnw + * for Win32 or Netware by those build environments, respectively. + */ + +/** + * @defgroup APR Apache Portability Runtime library + * @{ + */ +/** + * @defgroup apr_platform Platform Definitions + * @{ + * @warning + * The actual values of macros and typedefs on this page
+ * are platform specific and should NOT be relied upon!
+ */ + +/* So that we can use inline on some critical functions, and use + * GNUC attributes (such as to get -Wall warnings for printf-like + * functions). Only do this in gcc 2.7 or later ... it may work + * on earlier stuff, but why chance it. + * + * We've since discovered that the gcc shipped with NeXT systems + * as "cc" is completely broken. It claims to be __GNUC__ and so + * on, but it doesn't implement half of the things that __GNUC__ + * means. In particular it's missing inline and the __attribute__ + * stuff. So we hack around it. PR#1613. -djg + */ +#if !defined(__GNUC__) || __GNUC__ < 2 || \ + (__GNUC__ == 2 && __GNUC_MINOR__ < 7) ||\ + defined(NEXT) +#ifndef __attribute__ +#define __attribute__(__x) +#endif +#define APR_INLINE +#define APR_HAS_INLINE 0 +#else +#define APR_INLINE __inline__ +#define APR_HAS_INLINE 1 +#endif + +#define APR_HAVE_ARPA_INET_H @arpa_ineth@ +#define APR_HAVE_CONIO_H @conioh@ +#define APR_HAVE_CRYPT_H @crypth@ +#define APR_HAVE_CTYPE_H @ctypeh@ +#define APR_HAVE_DIRENT_H @direnth@ +#define APR_HAVE_ERRNO_H @errnoh@ +#define APR_HAVE_FCNTL_H @fcntlh@ +#define APR_HAVE_IO_H @ioh@ +#define APR_HAVE_LIMITS_H @limitsh@ +#define APR_HAVE_NETDB_H @netdbh@ +#define APR_HAVE_NETINET_IN_H @netinet_inh@ +#define APR_HAVE_NETINET_SCTP_H @netinet_sctph@ +#define APR_HAVE_NETINET_SCTP_UIO_H @netinet_sctp_uioh@ +#define APR_HAVE_NETINET_TCP_H @netinet_tcph@ +#define APR_HAVE_PROCESS_H @processh@ +#define APR_HAVE_PTHREAD_H @pthreadh@ +#define APR_HAVE_SEMAPHORE_H @semaphoreh@ +#define APR_HAVE_SIGNAL_H @signalh@ +#define APR_HAVE_STDARG_H @stdargh@ +#define APR_HAVE_STDINT_H @stdint@ +#define APR_HAVE_STDIO_H @stdioh@ +#define APR_HAVE_STDLIB_H @stdlibh@ +#define APR_HAVE_STRING_H @stringh@ +#define APR_HAVE_STRINGS_H @stringsh@ +#define APR_HAVE_INTTYPES_H @inttypesh@ +#define APR_HAVE_SYS_IOCTL_H @sys_ioctlh@ +#define APR_HAVE_SYS_SENDFILE_H @sys_sendfileh@ +#define APR_HAVE_SYS_SIGNAL_H @sys_signalh@ +#define APR_HAVE_SYS_SOCKET_H @sys_socketh@ +#define APR_HAVE_SYS_SOCKIO_H @sys_sockioh@ +#define APR_HAVE_SYS_SYSLIMITS_H @sys_syslimitsh@ +#define APR_HAVE_SYS_TIME_H @sys_timeh@ +#define APR_HAVE_SYS_TYPES_H @sys_typesh@ +#define APR_HAVE_SYS_UIO_H @sys_uioh@ +#define APR_HAVE_SYS_UN_H @sys_unh@ +#define APR_HAVE_SYS_WAIT_H @sys_waith@ +#define APR_HAVE_TIME_H @timeh@ +#define APR_HAVE_UNISTD_H @unistdh@ +#define APR_HAVE_WINDOWS_H @windowsh@ +#define APR_HAVE_WINSOCK2_H @winsock2h@ + +/** @} */ +/** @} */ + +/* We don't include our conditional headers within the doxyblocks + * or the extern "C" namespace + */ + +#if APR_HAVE_WINDOWS_H && defined(WIN32) +/* If windows.h was already included, our preferences don't matter. + * If not, include a restricted set of windows headers to our tastes. + */ +#ifndef _WINDOWS_ + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif + +#ifndef _WIN32_WINNT +/* Restrict the server to a subset of Windows XP header files by default + */ +#define _WIN32_WINNT 0x0501 +#endif + +#ifndef NOUSER +#define NOUSER +#endif +#ifndef NOMCX +#define NOMCX +#endif +#ifndef NOIME +#define NOIME +#endif + +#include +/* + * Add a _very_few_ declarations missing from the restricted set of headers + * (If this list becomes extensive, re-enable the required headers above!) + * winsock headers were excluded by WIN32_LEAN_AND_MEAN, so include them now + */ +#define SW_HIDE 0 +#ifndef _WIN32_WCE +#include +#include +#include +#else +#include +#endif + +#endif /* ndef _WINDOWS_ */ +#endif /* APR_HAVE_WINDOWS_H */ + +#if APR_HAVE_SYS_TYPES_H +#include +#endif + +#if APR_HAVE_SYS_SOCKET_H +#include +#endif + +#if APR_HAVE_STDINT_H +#ifdef __cplusplus +/* C99 7.18.4 requires that stdint.h only exposes INT64_C + * and UINT64_C for C++ implementations if this is defined: */ +#ifndef __STDC_CONSTANT_MACROS +#define __STDC_CONSTANT_MACROS +#endif +/* C++ needs this too for PRI*NN formats: */ +#ifndef __STDC_FORMAT_MACROS +#define __STDC_FORMAT_MACROS +#endif +#endif /* __cplusplus */ +#include +#endif + +#if APR_HAVE_INTTYPES_H +#include +#endif + +#if APR_HAVE_SYS_WAIT_H +#include +#endif + +#ifdef OS2 +#define INCL_DOS +#define INCL_DOSERRORS +#include +#endif + +/* header files for PATH_MAX, _POSIX_PATH_MAX */ +#if APR_HAVE_LIMITS_H +#include +#else +#if APR_HAVE_SYS_SYSLIMITS_H +#include +#endif +#endif + +/* __APPLE__ is now the official pre-defined macro for macOS */ +#ifdef __APPLE__ +#undef DARWIN +#undef DARWIN_10 +#define DARWIN +#define DARWIN_10 +#endif /* __APPLE__ */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @addtogroup apr_platform + * @ingroup APR + * @{ + */ + +#define APR_HAVE_SHMEM_MMAP_TMP @havemmaptmp@ +#define APR_HAVE_SHMEM_MMAP_SHM @havemmapshm@ +#define APR_HAVE_SHMEM_MMAP_ZERO @havemmapzero@ +#define APR_HAVE_SHMEM_SHMGET_ANON @haveshmgetanon@ +#define APR_HAVE_SHMEM_SHMGET @haveshmget@ +#define APR_HAVE_SHMEM_MMAP_ANON @havemmapanon@ +#define APR_HAVE_SHMEM_BEOS @havebeosarea@ + +#define APR_USE_SHMEM_MMAP_TMP @usemmaptmp@ +#define APR_USE_SHMEM_MMAP_SHM @usemmapshm@ +#define APR_USE_SHMEM_MMAP_ZERO @usemmapzero@ +#define APR_USE_SHMEM_SHMGET_ANON @useshmgetanon@ +#define APR_USE_SHMEM_SHMGET @useshmget@ +#define APR_USE_SHMEM_MMAP_ANON @usemmapanon@ +#define APR_USE_SHMEM_BEOS @usebeosarea@ + +#define APR_USE_FLOCK_SERIALIZE @flockser@ +#define APR_USE_SYSVSEM_SERIALIZE @sysvser@ +#define APR_USE_POSIXSEM_SERIALIZE @posixser@ +#define APR_USE_FCNTL_SERIALIZE @fcntlser@ +#define APR_USE_PROC_PTHREAD_SERIALIZE @procpthreadser@ +#define APR_USE_PTHREAD_SERIALIZE @pthreadser@ + +#define APR_HAS_FLOCK_SERIALIZE @hasflockser@ +#define APR_HAS_SYSVSEM_SERIALIZE @hassysvser@ +#define APR_HAS_POSIXSEM_SERIALIZE @hasposixser@ +#define APR_HAS_FCNTL_SERIALIZE @hasfcntlser@ +#define APR_HAS_PROC_PTHREAD_SERIALIZE @hasprocpthreadser@ + +#define APR_PROCESS_LOCK_IS_GLOBAL @proclockglobal@ + +#define APR_HAVE_CORKABLE_TCP @have_corkable_tcp@ +#define APR_HAVE_GETRLIMIT @have_getrlimit@ +#define APR_HAVE_IN_ADDR @have_in_addr@ +#define APR_HAVE_INET_ADDR @have_inet_addr@ +#define APR_HAVE_INET_NETWORK @have_inet_network@ +#define APR_HAVE_IPV6 @have_ipv6@ +#define APR_HAVE_SOCKADDR_UN @have_sockaddr_un@ +#define APR_HAVE_MEMMOVE @have_memmove@ +#define APR_HAVE_SETRLIMIT @have_setrlimit@ +#define APR_HAVE_SIGACTION @have_sigaction@ +#define APR_HAVE_SIGSUSPEND @have_sigsuspend@ +#define APR_HAVE_SIGWAIT @have_sigwait@ +#define APR_HAVE_SA_STORAGE @have_sa_storage@ +#define APR_HAVE_STRCASECMP @have_strcasecmp@ +#define APR_HAVE_STRDUP @have_strdup@ +#define APR_HAVE_STRICMP @have_stricmp@ +#define APR_HAVE_STRNCASECMP @have_strncasecmp@ +#define APR_HAVE_STRNICMP @have_strnicmp@ +#define APR_HAVE_STRSTR @have_strstr@ +#define APR_HAVE_MEMCHR @have_memchr@ +#define APR_HAVE_STRUCT_RLIMIT @struct_rlimit@ +#define APR_HAVE_UNION_SEMUN @have_union_semun@ +#define APR_HAVE_SCTP @have_sctp@ +#define APR_HAVE_IOVEC @have_iovec@ + +/* APR Feature Macros */ +#define APR_HAS_SHARED_MEMORY @sharedmem@ +#define APR_HAS_THREADS @threads@ +#define APR_HAS_SENDFILE @sendfile@ +#define APR_HAS_MMAP @mmap@ +#define APR_HAS_FORK @fork@ +#define APR_HAS_RANDOM @rand@ +#define APR_HAS_OTHER_CHILD @oc@ +#define APR_HAS_DSO @aprdso@ +#define APR_HAS_SO_ACCEPTFILTER @acceptfilter@ +#define APR_HAS_UNICODE_FS @have_unicode_fs@ +#define APR_HAS_PROC_INVOKED @have_proc_invoked@ +#define APR_HAS_USER @apr_has_user@ +#define APR_HAS_LARGE_FILES @aprlfs@ +#define APR_HAS_XTHREAD_FILES @apr_has_xthread_files@ +#define APR_HAS_OS_UUID @osuuid@ +#define APR_HAS_TIMEDLOCKS @apr_has_timedlocks@ + +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD @apr_procattr_user_set_requires_password@ + +/* APR sets APR_FILES_AS_SOCKETS to 1 on systems where it is possible + * to poll on files/pipes. + */ +#define APR_FILES_AS_SOCKETS @file_as_socket@ + +/* This macro indicates whether or not EBCDIC is the native character set. + */ +#define APR_CHARSET_EBCDIC @apr_charset_ebcdic@ + +/* If we have a TCP implementation that can be "corked", what flag + * do we use? + */ +#define APR_TCP_NOPUSH_FLAG @apr_tcp_nopush_flag@ + +/* Is the TCP_NODELAY socket option inherited from listening sockets? +*/ +#define APR_TCP_NODELAY_INHERITED @tcp_nodelay_inherited@ + +/* Is the O_NONBLOCK flag inherited from listening sockets? +*/ +#define APR_O_NONBLOCK_INHERITED @o_nonblock_inherited@ + +/* Typedefs that APR needs. */ + +typedef unsigned char apr_byte_t; + +typedef @short_value@ apr_int16_t; +typedef unsigned @short_value@ apr_uint16_t; + +typedef @int_value@ apr_int32_t; +typedef unsigned @int_value@ apr_uint32_t; + +#define APR_SIZEOF_VOIDP @voidp_size@ + +/* + * Darwin 10's default compiler (gcc42) builds for both 64 and + * 32 bit architectures unless specifically told not to. + * In those cases, we need to override types depending on how + * we're being built at compile time. + * NOTE: This is an ugly work-around for Darwin's + * concept of universal binaries, a single package + * (executable, lib, etc...) which contains both 32 + * and 64 bit versions. The issue is that if APR is + * built universally, if something else is compiled + * against it, some bit sizes will depend on whether + * it is 32 or 64 bit. This is determined by the __LP64__ + * flag. Since we need to support both, we have to + * handle OS X unqiuely. + */ +#ifdef DARWIN_10 +#undef APR_SIZEOF_VOIDP +#undef APR_INT64_C +#undef APR_UINT64_C +#ifdef __LP64__ + typedef long apr_int64_t; + typedef unsigned long apr_uint64_t; + #define APR_SIZEOF_VOIDP 8 + #define APR_INT64_C(v) (v ## L) + #define APR_UINT64_C(v) (v ## UL) +#else + typedef long long apr_int64_t; + typedef unsigned long long apr_uint64_t; + #define APR_SIZEOF_VOIDP 4 + #define APR_INT64_C(v) (v ## LL) + #define APR_UINT64_C(v) (v ## ULL) +#endif +#else + typedef @int64_value@ apr_int64_t; + typedef @uint64_value@ apr_uint64_t; + + /* Mechanisms to properly type numeric literals */ + @int64_literal@ + @uint64_literal@ +#endif + +typedef @size_t_value@ apr_size_t; +typedef @ssize_t_value@ apr_ssize_t; +typedef @off_t_value@ apr_off_t; +typedef @socklen_t_value@ apr_socklen_t; +typedef @ino_t_value@ apr_ino_t; + +#if APR_SIZEOF_VOIDP == 8 +typedef apr_uint64_t apr_uintptr_t; +#else +typedef apr_uint32_t apr_uintptr_t; +#endif + +/* Are we big endian? */ +#define APR_IS_BIGENDIAN @bigendian@ + +#ifdef INT16_MIN +#define APR_INT16_MIN INT16_MIN +#else +#define APR_INT16_MIN (-0x7fff - 1) +#endif + +#ifdef INT16_MAX +#define APR_INT16_MAX INT16_MAX +#else +#define APR_INT16_MAX (0x7fff) +#endif + +#ifdef UINT16_MAX +#define APR_UINT16_MAX UINT16_MAX +#else +#define APR_UINT16_MAX (0xffff) +#endif + +#ifdef INT32_MIN +#define APR_INT32_MIN INT32_MIN +#else +#define APR_INT32_MIN (-0x7fffffff - 1) +#endif + +#ifdef INT32_MAX +#define APR_INT32_MAX INT32_MAX +#else +#define APR_INT32_MAX 0x7fffffff +#endif + +#ifdef UINT32_MAX +#define APR_UINT32_MAX UINT32_MAX +#else +#define APR_UINT32_MAX (0xffffffffU) +#endif + +#ifdef INT64_MIN +#define APR_INT64_MIN INT64_MIN +#else +#define APR_INT64_MIN (APR_INT64_C(-0x7fffffffffffffff) - 1) +#endif + +#ifdef INT64_MAX +#define APR_INT64_MAX INT64_MAX +#else +#define APR_INT64_MAX APR_INT64_C(0x7fffffffffffffff) +#endif + +#ifdef UINT64_MAX +#define APR_UINT64_MAX UINT64_MAX +#else +#define APR_UINT64_MAX APR_UINT64_C(0xffffffffffffffff) +#endif + +#define APR_SIZE_MAX (~((apr_size_t)0)) + + +/* Definitions that APR programs need to work properly. */ + +/** + * APR public API wrap for C++ compilers. + */ +#ifdef __cplusplus +#define APR_BEGIN_DECLS extern "C" { +#define APR_END_DECLS } +#else +#define APR_BEGIN_DECLS +#define APR_END_DECLS +#endif + +/** + * Thread callbacks from APR functions must be declared with APR_THREAD_FUNC, + * so that they follow the platform's calling convention. + *
+ *
+ * void* APR_THREAD_FUNC my_thread_entry_fn(apr_thread_t *thd, void *data);
+ *
+ * 
+ */ +#define APR_THREAD_FUNC @apr_thread_func@ + +#if defined(DOXYGEN) || !defined(WIN32) + +/** + * The public APR functions are declared with APR_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APR_DECLARE_NONSTD(). + * + * @remark Both the declaration and implementations must use the same macro. + * + *
+ * APR_DECLARE(rettype) apr_func(args)
+ * 
+ * @see APR_DECLARE_NONSTD @see APR_DECLARE_DATA + * @remark Note that when APR compiles the library itself, it passes the + * symbol -DAPR_DECLARE_EXPORT to the compiler on some platforms (e.g. Win32) + * to export public symbols from the dynamic library build.\n + * The user must define the APR_DECLARE_STATIC when compiling to target + * the static APR library on some platforms (e.g. Win32.) The public symbols + * are neither exported nor imported when APR_DECLARE_STATIC is defined.\n + * By default, compiling an application and including the APR public + * headers, without defining APR_DECLARE_STATIC, will prepare the code to be + * linked to the dynamic library. + */ +#define APR_DECLARE(type) type + +/** + * The public APR functions using variable arguments are declared with + * APR_DECLARE_NONSTD(), as they must follow the C language calling convention. + * @see APR_DECLARE @see APR_DECLARE_DATA + * @remark Both the declaration and implementations must use the same macro. + *
+ *
+ * APR_DECLARE_NONSTD(rettype) apr_func(args, ...);
+ *
+ * 
+ */ +#define APR_DECLARE_NONSTD(type) type + +/** + * The public APR variables are declared with AP_MODULE_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * @see APR_DECLARE @see APR_DECLARE_NONSTD + * @remark Note that the declaration and implementations use different forms, + * but both must include the macro. + * + *
+ *
+ * extern APR_DECLARE_DATA type apr_variable;\n
+ * APR_DECLARE_DATA type apr_variable = value;
+ *
+ * 
+ */ +#define APR_DECLARE_DATA + +#elif defined(APR_DECLARE_STATIC) +#define APR_DECLARE(type) type __stdcall +#define APR_DECLARE_NONSTD(type) type __cdecl +#define APR_DECLARE_DATA +#elif defined(APR_DECLARE_EXPORT) +#define APR_DECLARE(type) __declspec(dllexport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllexport) +#else +#define APR_DECLARE(type) __declspec(dllimport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllimport) +#endif + +/* Define APR_SSIZE_T_FMT. + * If ssize_t is an integer we define it to be "d", + * if ssize_t is a long int we define it to be "ld", + * if ssize_t is neither we declare an error here. + * I looked for a better way to define this here, but couldn't find one, so + * to find the logic for this definition search for "ssize_t_fmt" in + * configure.in. + */ + +@ssize_t_fmt@ + +/* And APR_SIZE_T_FMT */ +@size_t_fmt@ + +/* And APR_OFF_T_FMT */ +@off_t_fmt@ + +/* And APR_PID_T_FMT */ +@pid_t_fmt@ + +/* And APR_INT64_T_FMT */ +@int64_t_fmt@ + +/* And APR_UINT64_T_FMT */ +@uint64_t_fmt@ + +/* And APR_UINT64_T_HEX_FMT */ +@uint64_t_hex_fmt@ + +/* + * Ensure we work with universal binaries on Darwin + */ +#ifdef DARWIN_10 + +#undef APR_HAS_LARGE_FILES +#undef APR_SIZEOF_VOIDP +#undef APR_INT64_T_FMT +#undef APR_UINT64_T_FMT +#undef APR_UINT64_T_HEX_FMT + +#ifdef __LP64__ + #define APR_HAS_LARGE_FILES 0 + #define APR_SIZEOF_VOIDP 8 + #define APR_INT64_T_FMT "ld" + #define APR_UINT64_T_FMT "lu" + #define APR_UINT64_T_HEX_FMT "lx" +#else + #define APR_HAS_LARGE_FILES 1 + #define APR_SIZEOF_VOIDP 4 + #define APR_INT64_T_FMT "lld" + #define APR_UINT64_T_FMT "llu" + #define APR_UINT64_T_HEX_FMT "llx" +#endif + +#undef APR_IS_BIGENDIAN +#ifdef __BIG_ENDIAN__ + #define APR_IS_BIGENDIAN 1 +#else + #define APR_IS_BIGENDIAN 0 +#endif + +#undef APR_OFF_T_FMT +#define APR_OFF_T_FMT "lld" + +#endif /* DARWIN_10 */ + +/* Does the proc mutex lock threads too */ +#define APR_PROC_MUTEX_IS_GLOBAL @proc_mutex_is_global@ + +/* Local machine definition for console and log output. */ +#define APR_EOL_STR "@eolstr@" + +#if APR_HAVE_SYS_WAIT_H +#ifdef WEXITSTATUS +#define apr_wait_t int +#else +#define apr_wait_t union wait +#define WEXITSTATUS(status) (int)((status).w_retcode) +#define WTERMSIG(status) (int)((status).w_termsig) +#endif /* !WEXITSTATUS */ +#elif defined(__MINGW32__) +typedef int apr_wait_t; +#endif /* HAVE_SYS_WAIT_H */ + +#if defined(PATH_MAX) +#define APR_PATH_MAX PATH_MAX +#elif defined(_POSIX_PATH_MAX) +#define APR_PATH_MAX _POSIX_PATH_MAX +#else +#error no decision has been made on APR_PATH_MAX for your platform +#endif + +#define APR_DSOPATH "@shlibpath_var@" + +/** @} */ + +/* Definitions that only Win32 programs need to compile properly. */ + +/* XXX These simply don't belong here, perhaps in apr_portable.h + * based on some APR_HAVE_PID/GID/UID? + */ +#ifdef __MINGW32__ +#ifndef __GNUC__ +typedef int pid_t; +#endif +typedef int uid_t; +typedef int gid_t; +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* APR_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr.hnw b/c/dependencies/windows/apr/x64_debug/include/apr.hnw new file mode 100644 index 00000000..21c8a98e --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr.hnw @@ -0,0 +1,445 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef APR_H +#define APR_H + +/* GENERATED FILE WARNING! DO NOT EDIT apr.h + * + * You must modify apr.hnw instead. + * + * And please, make an effort to stub apr.hw and apr.h.in in the process. + * + * This is the NetWare specific version of apr.h. It is copied from + * apr.hnw at the start of a NetWare build by the ./build/NWGNmakefile. + */ + +/** + * @file apr.h + * @brief APR Platform Definitions + * @remark This is a generated header generated from include/apr.h.in by + * ./configure, or copied from include/apr.hw or include/apr.hnw + * for Win32 or Netware by those build environments, respectively. + */ + +#if defined(NETWARE) || defined(DOXYGEN) + +#undef FD_SETSIZE +#define FD_SETSIZE 1024 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef USE_WINSOCK +#include +#ifdef NW_BUILD_IPV6 +#include +#endif +#else +#include +#include +#endif +#include + +#define _POSIX_THREAD_SAFE_FUNCTIONS 1 +#define READDIR_IS_THREAD_SAFE 1 + +/* Keep #include'd headers from within the __cplusplus or doxyblocks */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_platform Platform Definitions + * @ingroup APR + * @{ + */ + +#define APR_INLINE +#define APR_HAS_INLINE 0 +#ifndef __attribute__ +#define __attribute__(__x) +#endif +#define ENUM_BITFIELD(e,n,w) signed int n : w + +#define APR_HAVE_CONIO_H 0 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 1 +#define APR_HAVE_DIRENT_H 1 +#define APR_HAVE_ERRNO_H 1 +#define APR_HAVE_FCNTL_H 1 +#define APR_HAVE_IO_H 0 +#define APR_HAVE_LIMITS_H 1 +#ifdef USE_WINSOCK +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#else +#define APR_HAVE_ARPA_INET_H 1 +#define APR_HAVE_NETDB_H 1 +#define APR_HAVE_NETINET_IN_H 1 +#endif +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SIGNAL_H 1 +#define APR_HAVE_STDARG_H 1 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_STRTOLL 1 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#ifdef USE_WINSOCK +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#else +#define APR_HAVE_SYS_SOCKET_H 1 +#define APR_HAVE_SYS_SOCKIO_H 1 +#define APR_HAVE_SYS_UN_H 1 +#endif +#define APR_HAVE_SYS_SIGNAL_H 1 +#define APR_HAVE_SYS_TIME_H 1 +#define APR_HAVE_SYS_TYPES_H 1 +#define APR_HAVE_SYS_UIO_H 1 +#define APR_HAVE_SYS_WAIT_H 1 +#define APR_HAVE_TIME_H 1 +#define APR_HAVE_UNISTD_H 1 + +#define APR_HAVE_SHMEM_MMAP_TMP 0 +#define APR_HAVE_SHMEM_MMAP_SHM 0 +#define APR_HAVE_SHMEM_MMAP_ZERO 0 +#define APR_HAVE_SHMEM_SHMGET_ANON 0 +#define APR_HAVE_SHMEM_SHMGET 0 +#define APR_HAVE_SHMEM_MMAP_ANON 0 +#define APR_HAVE_SHMEM_BEOS 0 + +#define APR_USE_SHMEM_MMAP_TMP 0 +#define APR_USE_SHMEM_MMAP_SHM 0 +#define APR_USE_SHMEM_MMAP_ZERO 0 +#define APR_USE_SHMEM_SHMGET_ANON 0 +#define APR_USE_SHMEM_SHMGET 0 +#define APR_USE_SHMEM_MMAP_ANON 0 +#define APR_USE_SHMEM_BEOS 0 + +#define APR_USE_FLOCK_SERIALIZE 0 +#define APR_USE_SYSVSEM_SERIALIZE 0 +#define APR_USE_FCNTL_SERIALIZE 0 +#define APR_USE_PROC_PTHREAD_SERIALIZE 0 +#define APR_USE_PTHREAD_SERIALIZE 0 + +#define APR_HAS_FLOCK_SERIALIZE 0 +#define APR_HAS_SYSVSEM_SERIALIZE 0 +#define APR_HAS_FCNTL_SERIALIZE 0 +#define APR_HAS_PROC_PTHREAD_SERIALIZE 0 +#define APR_HAS_RWLOCK_SERIALIZE 0 + +#define APR_HAS_LOCK_CREATE_NP 0 + +#define APR_PROCESS_LOCK_IS_GLOBAL 1 + +#define APR_FILE_BASED_SHM 0 + +#define APR_HAVE_CORKABLE_TCP 0 +#define APR_HAVE_GETRLIMIT 0 +#define APR_HAVE_ICONV 0 +#define APR_HAVE_IN_ADDR 1 +#define APR_HAVE_INET_ADDR 1 +#define APR_HAVE_INET_NETWORK 0 +#ifdef NW_BUILD_IPV6 +#define APR_HAVE_IPV6 1 +#else +#define APR_HAVE_IPV6 0 +#endif +#define APR_HAVE_SOCKADDR_UN 0 +#define APR_HAVE_MEMCHR 1 +#define APR_HAVE_MEMMOVE 1 +#define APR_HAVE_SETRLIMIT 0 +#define APR_HAVE_SIGACTION 0 +#define APR_HAVE_SIGSUSPEND 0 +#define APR_HAVE_SIGWAIT 0 +#define APR_HAVE_STRCASECMP 1 +#define APR_HAVE_STRDUP 1 +#define APR_HAVE_STRICMP 1 +#define APR_HAVE_STRNCASECMP 1 +#define APR_HAVE_STRNICMP 1 +#define APR_HAVE_STRSTR 1 +#define APR_HAVE_STRUCT_RLIMIT 0 +#define APR_HAVE_UNION_SEMUN 0 +#define APR_HAVE_SCTP 0 +#define APR_HAVE_IOVEC 1 + +/* APR Feature Macros */ +#define APR_HAS_SHARED_MEMORY 0 +#define APR_HAS_THREADS 1 +#define APR_HAS_SENDFILE 0 +#define APR_HAS_MMAP 0 +#define APR_HAS_FORK 0 +#define APR_HAS_RANDOM 1 +#define APR_HAS_OTHER_CHILD 0 +#define APR_HAS_DSO 1 +#define APR_HAS_SO_ACCEPTFILTER 0 +#define APR_HAS_UNICODE_FS 0 +#define APR_HAS_PROC_INVOKED 0 +#define APR_HAS_USER 1 +#define APR_HAS_LARGE_FILES 1 +#define APR_HAS_XTHREAD_FILES 0 +#define APR_HAS_OS_UUID 0 +#define APR_HAS_TIMEDLOCKS 1 + +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 0 + +/* Netware can poll on files/pipes. + */ +#define APR_FILES_AS_SOCKETS 1 + +/* This macro indicates whether or not EBCDIC is the native character set. + */ +#define APR_CHARSET_EBCDIC 0 + +/* Is the TCP_NODELAY socket option inherited from listening sockets? +*/ +#define APR_TCP_NODELAY_INHERITED 1 + +/* Is the O_NONBLOCK flag inherited from listening sockets? +*/ +#define APR_O_NONBLOCK_INHERITED 1 + +/* Typedefs that APR needs. */ + +typedef unsigned char apr_byte_t; + +typedef short apr_int16_t; +typedef unsigned short apr_uint16_t; + +typedef int apr_int32_t; +typedef unsigned int apr_uint32_t; + +typedef long long apr_int64_t; +typedef unsigned long long apr_uint64_t; + +typedef size_t apr_size_t; +typedef ssize_t apr_ssize_t; +#if APR_HAS_LARGE_FILES +typedef off64_t apr_off_t; +#else +typedef off_t apr_off_t; +#endif +#ifdef USE_WINSOCK +typedef int apr_socklen_t; +#else +typedef size_t apr_socklen_t; +#endif +typedef apr_uint64_t apr_ino_t; + +/* Are we big endian? */ +/* XXX: Fatal assumption on Alpha platforms */ +#define APR_IS_BIGENDIAN 0 + +#ifdef UNKNOWN_NETWARE_64BIT_FLAG_NEEDED +#define APR_SIZEOF_VOIDP 8 +#else +#define APR_SIZEOF_VOIDP 4 +#endif + +#if APR_SIZEOF_VOIDP == 8 +typedef apr_uint64_t apr_uintptr_t; +#else +typedef apr_uint32_t apr_uintptr_t; +#endif + +/* Mechanisms to properly type numeric literals */ +#define APR_INT64_C(val) (val##LL) +#define APR_UINT64_C(val) (val##ULL) + +#ifdef INT16_MIN +#define APR_INT16_MIN INT16_MIN +#else +#define APR_INT16_MIN (-0x7fff - 1) +#endif + +#ifdef INT16_MAX +#define APR_INT16_MAX INT16_MAX +#else +#define APR_INT16_MAX (0x7fff) +#endif + +#ifdef UINT16_MAX +#define APR_UINT16_MAX UINT16_MAX +#else +#define APR_UINT16_MAX (0xffff) +#endif + +#ifdef INT32_MIN +#define APR_INT32_MIN INT32_MIN +#else +#define APR_INT32_MIN (-0x7fffffff - 1) +#endif + +#ifdef INT32_MAX +#define APR_INT32_MAX INT32_MAX +#else +#define APR_INT32_MAX 0x7fffffff +#endif + +#ifdef UINT32_MAX +#define APR_UINT32_MAX UINT32_MAX +#else +#define APR_UINT32_MAX (0xffffffffU) +#endif + +#ifdef INT64_MIN +#define APR_INT64_MIN INT64_MIN +#else +#define APR_INT64_MIN (APR_INT64_C(-0x7fffffffffffffff) - 1) +#endif + +#ifdef INT64_MAX +#define APR_INT64_MAX INT64_MAX +#else +#define APR_INT64_MAX APR_INT64_C(0x7fffffffffffffff) +#endif + +#ifdef UINT64_MAX +#define APR_UINT64_MAX UINT64_MAX +#else +#define APR_UINT64_MAX APR_UINT64_C(0xffffffffffffffff) +#endif + +#define APR_SIZE_MAX (~((apr_size_t)0)) + +/* PROC mutex is a GLOBAL mutex on Netware */ +#define APR_PROC_MUTEX_IS_GLOBAL 1 + +/* Definitions that APR programs need to work properly. */ + +/** + * APR public API wrap for C++ compilers. + */ +#ifdef __cplusplus +#define APR_BEGIN_DECLS extern "C" { +#define APR_END_DECLS } +#else +#define APR_BEGIN_DECLS +#define APR_END_DECLS +#endif + +/** + * Thread callbacks from APR functions must be declared with APR_THREAD_FUNC, + * so that they follow the platform's calling convention. + * @example + */ +/** void* APR_THREAD_FUNC my_thread_entry_fn(apr_thread_t *thd, void *data); + */ +#define APR_THREAD_FUNC + +/** + * The public APR functions are declared with APR_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APR_DECLARE_NONSTD(). + * + * @remark Both the declaration and implementations must use the same macro. + * @example + */ +/** APR_DECLARE(rettype) apr_func(args) + * @see APR_DECLARE_NONSTD @see APR_DECLARE_DATA + * @remark Note that when APR compiles the library itself, it passes the + * symbol -DAPR_DECLARE_EXPORT to the compiler on some platforms (e.g. Win32) + * to export public symbols from the dynamic library build.\n + * The user must define the APR_DECLARE_STATIC when compiling to target + * the static APR library on some platforms (e.g. Win32.) The public symbols + * are neither exported nor imported when APR_DECLARE_STATIC is defined.\n + * By default, compiling an application and including the APR public + * headers, without defining APR_DECLARE_STATIC, will prepare the code to be + * linked to the dynamic library. + */ +#define APR_DECLARE(type) type + +/** + * The public APR functions using variable arguments are declared with + * APR_DECLARE_NONSTD(), as they must follow the C language calling convention. + * @see APR_DECLARE @see APR_DECLARE_DATA + * @remark Both the declaration and implementations must use the same macro. + * @example + */ +/** APR_DECLARE_NONSTD(rettype) apr_func(args, ...); + */ +#define APR_DECLARE_NONSTD(type) type + +/** + * The public APR variables are declared with APR_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * @see APR_DECLARE @see APR_DECLARE_NONSTD + * @remark Note that the declaration and implementations use different forms, + * but both must include the macro. + * @example + */ +/** extern APR_DECLARE_DATA type apr_variable;\n + * APR_DECLARE_DATA type apr_variable = value; + */ +#define APR_DECLARE_DATA + +#define APR_SSIZE_T_FMT "d" + +#define APR_SIZE_T_FMT "d" + +#if APR_HAS_LARGE_FILES +#define APR_OFF_T_FMT "lld" +#else +#define APR_OFF_T_FMT "ld" +#endif + +#define APR_PID_T_FMT "d" + +/* Local machine definition for console and log output. */ +#define APR_EOL_STR "\r\n" + +typedef int apr_wait_t; + +#define APR_PATH_MAX PATH_MAX + +#define APR_DSOPATH "PATH" + +#define APR_INT64_T_FMT "lld" +#define APR_UINT64_T_FMT "llu" +#define APR_UINT64_T_HEX_FMT "llx" +#define APR_TIME_T_FMT APR_INT64_T_FMT + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* NETWARE */ + +#endif /* APR_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr.hw b/c/dependencies/windows/apr/x64_debug/include/apr.hw new file mode 100644 index 00000000..b8d97495 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr.hw @@ -0,0 +1,667 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef APR_H +#define APR_H + +/* GENERATED FILE WARNING! DO NOT EDIT apr.h + * + * You must modify apr.hw instead. + * + * And please, make an effort to stub apr.hnw and apr.h.in in the process. + * + * This is the Win32 specific version of apr.h. It is copied from + * apr.hw by the apr.dsp and libapr.dsp projects. + */ + +/** + * @file apr.h + * @brief APR Platform Definitions + * @remark This is a generated header generated from include/apr.h.in by + * ./configure, or copied from include/apr.hw or include/apr.hnw + * for Win32 or Netware by those build environments, respectively. + */ + +/* Make sure we have our platform identifier macro defined we ask for later. + */ +#if defined(_WIN32) && !defined(WIN32) +#define WIN32 1 +#endif + +#if defined(WIN32) || defined(DOXYGEN) + +/* Ignore most warnings (back down to /W3) for poorly constructed headers + */ +#if defined(_MSC_VER) && _MSC_VER >= 1200 +#pragma warning(push, 3) +#endif + +/* disable or reduce the frequency of... + * C4057: indirection to slightly different base types + * C4075: slight indirection changes (unsigned short* vs short[]) + * C4100: unreferenced formal parameter + * C4127: conditional expression is constant + * C4163: '_rotl64' : not available as an intrinsic function + * C4201: nonstandard extension nameless struct/unions + * C4244: int to char/short - precision loss + * C4514: unreferenced inline function removed + */ +#if defined(_MSC_VER) +#pragma warning(disable: 4100 4127 4163 4201 4514; once: 4057 4075 4244) +#endif + +/* Ignore Microsoft's interpretation of secure development + * and the POSIX string handling API + */ +#if defined(_MSC_VER) && _MSC_VER >= 1400 +#ifndef _CRT_SECURE_NO_DEPRECATE +#define _CRT_SECURE_NO_DEPRECATE +#endif +#pragma warning(disable: 4996) +#endif + +/* Has windows.h already been included? If so, our preferences don't matter, + * but we will still need the winsock things no matter what was included. + * If not, include a restricted set of windows headers to our tastes. + */ +#ifndef _WINDOWS_ +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef _WIN32_WINNT + +/* Restrict the server to a subset of Windows XP header files by default + */ +#define _WIN32_WINNT 0x0A00 +#endif +#ifndef NOUSER +#define NOUSER +#endif +#ifndef NOMCX +#define NOMCX +#endif +#ifndef NOIME +#define NOIME +#endif +#include +/* + * Add a _very_few_ declarations missing from the restricted set of headers + * (If this list becomes extensive, re-enable the required headers above!) + * winsock headers were excluded by WIN32_LEAN_AND_MEAN, so include them now + */ +#define SW_HIDE 0 +#ifndef _WIN32_WCE +#include +#include +#include +#else +#include +#endif +#endif /* !_WINDOWS_ */ + +/** + * @defgroup APR Apache Portability Runtime library + * @{ + */ +/** + * @defgroup apr_platform Platform Definitions + * @{ + * @warning + * The actual values of macros and typedefs on this page
+ * are platform specific and should NOT be relied upon!
+ */ + +#define APR_INLINE __inline +#define APR_HAS_INLINE 1 +#if !defined(__GNUC__) && !defined(__attribute__) +#define __attribute__(__x) +#endif + +#ifndef _WIN32_WCE +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_CONIO_H 1 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 1 +#define APR_HAVE_DIRENT_H 0 +#define APR_HAVE_ERRNO_H 1 +#define APR_HAVE_FCNTL_H 1 +#define APR_HAVE_IO_H 1 +#define APR_HAVE_LIMITS_H 1 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SEMAPHORE_H 0 +#define APR_HAVE_SIGNAL_H 1 +#define APR_HAVE_STDARG_H 1 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_SYS_IOCTL_H 0 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SIGNAL_H 0 +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#define APR_HAVE_SYS_TIME_H 0 +#define APR_HAVE_SYS_TYPES_H 1 +#define APR_HAVE_SYS_UIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#define APR_HAVE_SYS_WAIT_H 0 +#define APR_HAVE_TIME_H 1 +#define APR_HAVE_UNISTD_H 0 +#define APR_HAVE_STDDEF_H 1 +#define APR_HAVE_PROCESS_H 1 +#else +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_CONIO_H 0 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 0 +#define APR_HAVE_DIRENT_H 0 +#define APR_HAVE_ERRNO_H 0 +#define APR_HAVE_FCNTL_H 0 +#define APR_HAVE_IO_H 0 +#define APR_HAVE_LIMITS_H 0 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SEMAPHORE_H 0 +#define APR_HAVE_SIGNAL_H 0 +#define APR_HAVE_STDARG_H 0 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_SYS_IOCTL_H 0 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SIGNAL_H 0 +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#define APR_HAVE_SYS_TIME_H 0 +#define APR_HAVE_SYS_TYPES_H 0 +#define APR_HAVE_SYS_UIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#define APR_HAVE_SYS_WAIT_H 0 +#define APR_HAVE_TIME_H 0 +#define APR_HAVE_UNISTD_H 0 +#define APR_HAVE_STDDEF_H 0 +#define APR_HAVE_PROCESS_H 0 +#endif + +/** @} */ +/** @} */ + +/* We don't include our conditional headers within the doxyblocks + * or the extern "C" namespace + */ + +#if APR_HAVE_STDLIB_H +#include +#endif + +#if APR_HAVE_STDIO_H +#include +#endif + +#if APR_HAVE_SYS_TYPES_H +#include +#endif + +#if APR_HAVE_STDDEF_H +#include +#endif + +#if APR_HAVE_SYS_SOCKET_H +#include +#endif + +#if APR_HAVE_STDINT_H +#include +#endif + +#if APR_HAVE_SYS_WAIT_H +#include +#endif + +#if APR_HAVE_TIME_H +#include +#endif + +#if APR_HAVE_PROCESS_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @addtogroup apr_platform + * @ingroup APR + * @{ + */ + +#define APR_HAVE_SHMEM_MMAP_TMP 0 +#define APR_HAVE_SHMEM_MMAP_SHM 0 +#define APR_HAVE_SHMEM_MMAP_ZERO 0 +#define APR_HAVE_SHMEM_SHMGET_ANON 0 +#define APR_HAVE_SHMEM_SHMGET 0 +#define APR_HAVE_SHMEM_MMAP_ANON 0 +#define APR_HAVE_SHMEM_BEOS 0 + +#define APR_USE_SHMEM_MMAP_TMP 0 +#define APR_USE_SHMEM_MMAP_SHM 0 +#define APR_USE_SHMEM_MMAP_ZERO 0 +#define APR_USE_SHMEM_SHMGET_ANON 0 +#define APR_USE_SHMEM_SHMGET 0 +#define APR_USE_SHMEM_MMAP_ANON 0 +#define APR_USE_SHMEM_BEOS 0 + +#define APR_USE_FLOCK_SERIALIZE 0 +#define APR_USE_POSIXSEM_SERIALIZE 0 +#define APR_USE_SYSVSEM_SERIALIZE 0 +#define APR_USE_FCNTL_SERIALIZE 0 +#define APR_USE_PROC_PTHREAD_SERIALIZE 0 +#define APR_USE_PTHREAD_SERIALIZE 0 + +#define APR_HAS_FLOCK_SERIALIZE 0 +#define APR_HAS_SYSVSEM_SERIALIZE 0 +#define APR_HAS_POSIXSEM_SERIALIZE 0 +#define APR_HAS_FCNTL_SERIALIZE 0 +#define APR_HAS_PROC_PTHREAD_SERIALIZE 0 + +#define APR_PROCESS_LOCK_IS_GLOBAL 0 + +#define APR_HAVE_CORKABLE_TCP 0 +#define APR_HAVE_GETRLIMIT 0 +#define APR_HAVE_ICONV 0 +#define APR_HAVE_IN_ADDR 1 +#define APR_HAVE_INET_ADDR 1 +#define APR_HAVE_INET_NETWORK 0 +#define APR_HAVE_IPV6 1 +#define APR_HAVE_SOCKADDR_UN 0 +#define APR_HAVE_MEMMOVE 1 +#define APR_HAVE_SETRLIMIT 0 +#define APR_HAVE_SIGACTION 0 +#define APR_HAVE_SIGSUSPEND 0 +#define APR_HAVE_SIGWAIT 0 +#define APR_HAVE_SA_STORAGE 0 +#define APR_HAVE_STRCASECMP 0 +#define APR_HAVE_STRDUP 1 +#define APR_HAVE_STRNCASECMP 0 +#define APR_HAVE_STRSTR 1 +#define APR_HAVE_MEMCHR 1 +#define APR_HAVE_STRUCT_RLIMIT 0 +#define APR_HAVE_UNION_SEMUN 0 +#define APR_HAVE_SCTP 0 +#define APR_HAVE_IOVEC 0 + +#ifndef _WIN32_WCE +#define APR_HAVE_STRICMP 1 +#define APR_HAVE_STRNICMP 1 +#else +#define APR_HAVE_STRICMP 0 +#define APR_HAVE_STRNICMP 0 +#endif + +/* APR Feature Macros */ +#define APR_HAS_SHARED_MEMORY 1 +#define APR_HAS_THREADS 1 +#define APR_HAS_MMAP 1 +#define APR_HAS_FORK 0 +#define APR_HAS_RANDOM 1 +#define APR_HAS_OTHER_CHILD 1 +#define APR_HAS_DSO 1 +#define APR_HAS_SO_ACCEPTFILTER 0 +#define APR_HAS_UNICODE_FS 1 +#define APR_HAS_PROC_INVOKED 1 +#define APR_HAS_OS_UUID 1 +#define APR_HAS_TIMEDLOCKS 1 + +#ifndef _WIN32_WCE +#define APR_HAS_SENDFILE 1 +#define APR_HAS_USER 1 +#define APR_HAS_LARGE_FILES 1 +#define APR_HAS_XTHREAD_FILES 1 +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 1 +#else +#define APR_HAS_SENDFILE 0 +#define APR_HAS_USER 0 +#define APR_HAS_LARGE_FILES 0 +#define APR_HAS_XTHREAD_FILES 0 +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 0 +#endif + +/* APR sets APR_FILES_AS_SOCKETS to 1 on systems where it is possible + * to poll on files/pipes. + */ +#define APR_FILES_AS_SOCKETS 0 + +/* This macro indicates whether or not EBCDIC is the native character set. + */ +#define APR_CHARSET_EBCDIC 0 + +/* If we have a TCP implementation that can be "corked", what flag + * do we use? + */ +#define APR_TCP_NOPUSH_FLAG @apr_tcp_nopush_flag@ + +/* Is the TCP_NODELAY socket option inherited from listening sockets? + */ +#define APR_TCP_NODELAY_INHERITED 1 + +/* Is the O_NONBLOCK flag inherited from listening sockets? + */ +#define APR_O_NONBLOCK_INHERITED 1 + +/* Typedefs that APR needs. */ + +typedef unsigned char apr_byte_t; + +typedef short apr_int16_t; +typedef unsigned short apr_uint16_t; + +typedef int apr_int32_t; +typedef unsigned int apr_uint32_t; + +typedef __int64 apr_int64_t; +typedef unsigned __int64 apr_uint64_t; + +typedef size_t apr_size_t; +#if APR_HAVE_STDDEF_H +typedef ptrdiff_t apr_ssize_t; +#else +typedef int apr_ssize_t; +#endif +#if APR_HAS_LARGE_FILES +typedef __int64 apr_off_t; +#else +typedef int apr_off_t; +#endif +typedef int apr_socklen_t; +typedef apr_uint64_t apr_ino_t; + +#ifdef _WIN64 +#define APR_SIZEOF_VOIDP 8 +#else +#define APR_SIZEOF_VOIDP 4 +#endif + +#if APR_SIZEOF_VOIDP == 8 +typedef apr_uint64_t apr_uintptr_t; +#else +typedef apr_uint32_t apr_uintptr_t; +#endif + +/* Are we big endian? */ +/* XXX: Fatal assumption on Alpha platforms */ +#define APR_IS_BIGENDIAN 0 + +/* Mechanisms to properly type numeric literals */ + +#ifndef __GNUC__ +#define APR_INT64_C(val) (val##i64) +#define APR_UINT64_C(val) (val##Ui64) +#else +#define APR_INT64_C(val) (val##LL) +#define APR_UINT64_C(val) (val##ULL) +#endif + +#ifdef INT16_MIN +#define APR_INT16_MIN INT16_MIN +#else +#define APR_INT16_MIN (-0x7fff - 1) +#endif + +#ifdef INT16_MAX +#define APR_INT16_MAX INT16_MAX +#else +#define APR_INT16_MAX (0x7fff) +#endif + +#ifdef UINT16_MAX +#define APR_UINT16_MAX UINT16_MAX +#else +#define APR_UINT16_MAX (0xffff) +#endif + +#ifdef INT32_MIN +#define APR_INT32_MIN INT32_MIN +#else +#define APR_INT32_MIN (-0x7fffffff - 1) +#endif + +#ifdef INT32_MAX +#define APR_INT32_MAX INT32_MAX +#else +#define APR_INT32_MAX 0x7fffffff +#endif + +#ifdef UINT32_MAX +#define APR_UINT32_MAX UINT32_MAX +#else +#define APR_UINT32_MAX (0xffffffffU) +#endif + +#ifdef INT64_MIN +#define APR_INT64_MIN INT64_MIN +#else +#define APR_INT64_MIN (APR_INT64_C(-0x7fffffffffffffff) - 1) +#endif + +#ifdef INT64_MAX +#define APR_INT64_MAX INT64_MAX +#else +#define APR_INT64_MAX APR_INT64_C(0x7fffffffffffffff) +#endif + +#ifdef UINT64_MAX +#define APR_UINT64_MAX UINT64_MAX +#else +#define APR_UINT64_MAX APR_UINT64_C(0xffffffffffffffff) +#endif + +#define APR_SIZE_MAX (~((apr_size_t)0)) + +/* Definitions that APR programs need to work properly. */ + +/** + * APR public API wrap for C++ compilers. + */ +#ifdef __cplusplus +#define APR_BEGIN_DECLS extern "C" { +#define APR_END_DECLS } +#else +#define APR_BEGIN_DECLS +#define APR_END_DECLS +#endif + +/** + * Thread callbacks from APR functions must be declared with APR_THREAD_FUNC, + * so that they follow the platform's calling convention. + *
+ *
+ * void* APR_THREAD_FUNC my_thread_entry_fn(apr_thread_t *thd, void *data);
+ *
+ * 
+ */ +#define APR_THREAD_FUNC __stdcall + + +#if defined(DOXYGEN) || !defined(WIN32) + +/** + * The public APR functions are declared with APR_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APR_DECLARE_NONSTD(). + * + * @remark Both the declaration and implementations must use the same macro. + * + *
+ * APR_DECLARE(rettype) apr_func(args)
+ * 
+ * @see APR_DECLARE_NONSTD @see APR_DECLARE_DATA + * @remark Note that when APR compiles the library itself, it passes the + * symbol -DAPR_DECLARE_EXPORT to the compiler on some platforms (e.g. Win32) + * to export public symbols from the dynamic library build.\n + * The user must define the APR_DECLARE_STATIC when compiling to target + * the static APR library on some platforms (e.g. Win32.) The public symbols + * are neither exported nor imported when APR_DECLARE_STATIC is defined.\n + * By default, compiling an application and including the APR public + * headers, without defining APR_DECLARE_STATIC, will prepare the code to be + * linked to the dynamic library. + */ +#define APR_DECLARE(type) type + +/** + * The public APR functions using variable arguments are declared with + * APR_DECLARE_NONSTD(), as they must follow the C language calling convention. + * @see APR_DECLARE @see APR_DECLARE_DATA + * @remark Both the declaration and implementations must use the same macro. + *
+ *
+ * APR_DECLARE_NONSTD(rettype) apr_func(args, ...);
+ *
+ * 
+ */ +#define APR_DECLARE_NONSTD(type) type + +/** + * The public APR variables are declared with AP_MODULE_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * @see APR_DECLARE @see APR_DECLARE_NONSTD + * @remark Note that the declaration and implementations use different forms, + * but both must include the macro. + * + *
+ *
+ * extern APR_DECLARE_DATA type apr_variable;\n
+ * APR_DECLARE_DATA type apr_variable = value;
+ *
+ * 
+ */ +#define APR_DECLARE_DATA + +#elif defined(APR_DECLARE_STATIC) +#define APR_DECLARE(type) type __stdcall +#define APR_DECLARE_NONSTD(type) type __cdecl +#define APR_DECLARE_DATA +#elif defined(APR_DECLARE_EXPORT) +#define APR_DECLARE(type) __declspec(dllexport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllexport) +#else +#define APR_DECLARE(type) __declspec(dllimport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllimport) +#endif + +#ifdef _WIN64 +#define APR_SSIZE_T_FMT "I64d" +#define APR_SIZE_T_FMT "I64u" +#else +#define APR_SSIZE_T_FMT "d" +#define APR_SIZE_T_FMT "u" +#endif + +#if APR_HAS_LARGE_FILES +#define APR_OFF_T_FMT "I64d" +#else +#define APR_OFF_T_FMT "d" +#endif + +#define APR_PID_T_FMT "d" + +#define APR_INT64_T_FMT "I64d" +#define APR_UINT64_T_FMT "I64u" +#define APR_UINT64_T_HEX_FMT "I64x" + +/* No difference between PROC and GLOBAL mutex */ +#define APR_PROC_MUTEX_IS_GLOBAL 1 + +/* Local machine definition for console and log output. */ +#define APR_EOL_STR "\r\n" + +typedef int apr_wait_t; + +#if APR_HAS_UNICODE_FS +/* An arbitrary size that is digestable. True max is a bit less than 32000 */ +#define APR_PATH_MAX 8192 +#else /* !APR_HAS_UNICODE_FS */ +#define APR_PATH_MAX MAX_PATH +#endif + +#define APR_DSOPATH "PATH" + +/** @} */ + +/* Definitions that only Win32 programs need to compile properly. */ + +/* XXX These simply don't belong here, perhaps in apr_portable.h + * based on some APR_HAVE_PID/GID/UID? + */ +#ifndef __GNUC__ +typedef int pid_t; +#endif +typedef int uid_t; +typedef int gid_t; + +/* Win32 .h ommissions we really need */ +#define STDIN_FILENO 0 +#define STDOUT_FILENO 1 +#define STDERR_FILENO 2 + +#if APR_HAVE_IPV6 + +/* Appears in later flavors, not the originals. */ +#ifndef in_addr6 +#define in6_addr in_addr6 +#endif + +#ifndef WS2TCPIP_INLINE +#define IN6_IS_ADDR_V4MAPPED(a) \ + ( (*(const apr_uint64_t *)(const void *)(&(a)->s6_addr[0]) == 0) \ + && (*(const apr_uint32_t *)(const void *)(&(a)->s6_addr[8]) == ntohl(0x0000ffff))) +#endif + +#endif /* APR_HAVE_IPV6 */ + +#ifdef __cplusplus +} +#endif + +/* Done with badly written headers, leave 'deprecated CRT' undeprecated + */ +#if defined(_MSC_VER) && _MSC_VER >= 1200 +#pragma warning(pop) +#if _MSC_VER >= 1400 +#pragma warning(disable: 4996) +#endif +#endif + +#endif /* WIN32 */ + +#endif /* APR_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr.hwc b/c/dependencies/windows/apr/x64_debug/include/apr.hwc new file mode 100644 index 00000000..ffb8368b --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr.hwc @@ -0,0 +1,664 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef APR_H +#define APR_H + +/* GENERATED FILE WARNING! DO NOT EDIT apr.h + * + * You must modify apr.hwc instead. + * + * And please, make an effort to stub apr.hnw and apr.h.in in the process. + * + * This is the Win32 specific version of apr.h. It is copied from + * apr.hw by the apr.dsp and libapr.dsp projects. + */ + +/** + * @file apr.h + * @brief APR Platform Definitions + * @remark This is a generated header generated from include/apr.h.in by + * ./configure, or copied from include/apr.hw or include/apr.hnw + * for Win32 or Netware by those build environments, respectively. + */ + +/* Make sure we have our platform identifier macro defined we ask for later. + */ +#if defined(_WIN32) && !defined(WIN32) +#define WIN32 1 +#endif + +#if defined(WIN32) || defined(DOXYGEN) + +/* Ignore most warnings (back down to /W3) for poorly constructed headers + */ +#if defined(_MSC_VER) && _MSC_VER >= 1200 +#pragma warning(push, 3) +#endif + +/* disable or reduce the frequency of... + * C4057: indirection to slightly different base types + * C4075: slight indirection changes (unsigned short* vs short[]) + * C4100: unreferenced formal parameter + * C4127: conditional expression is constant + * C4163: '_rotl64' : not available as an intrinsic function + * C4201: nonstandard extension nameless struct/unions + * C4244: int to char/short - precision loss + * C4514: unreferenced inline function removed + */ +#if defined(_MSC_VER) +#pragma warning(disable: 4100 4127 4163 4201 4514; once: 4057 4075 4244) +#endif + +/* Ignore Microsoft's interpretation of secure development + * and the POSIX string handling API + */ +#if defined(_MSC_VER) && _MSC_VER >= 1400 +#ifndef _CRT_SECURE_NO_DEPRECATE +#define _CRT_SECURE_NO_DEPRECATE +#endif +#pragma warning(disable: 4996) +#endif + +/* Has windows.h already been included? If so, our preferences don't matter, + * but we will still need the winsock things no matter what was included. + * If not, include a restricted set of windows headers to our tastes. + */ +#ifndef _WINDOWS_ +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef _WIN32_WINNT +#define _WIN32_WINNT @win32_winnt_str@ +#endif +#ifndef NOUSER +#define NOUSER +#endif +#ifndef NOMCX +#define NOMCX +#endif +#ifndef NOIME +#define NOIME +#endif +#include +/* + * Add a _very_few_ declarations missing from the restricted set of headers + * (If this list becomes extensive, re-enable the required headers above!) + * winsock headers were excluded by WIN32_LEAN_AND_MEAN, so include them now + */ +#define SW_HIDE 0 +#ifndef _WIN32_WCE +#include +#include +#include +#else +#include +#endif +#endif /* !_WINDOWS_ */ + +/** + * @defgroup APR Apache Portability Runtime library + * @{ + */ +/** + * @defgroup apr_platform Platform Definitions + * @{ + * @warning + * The actual values of macros and typedefs on this page
+ * are platform specific and should NOT be relied upon!
+ */ + +#define APR_INLINE __inline +#define APR_HAS_INLINE 1 +#if !defined(__GNUC__) && !defined(__attribute__) +#define __attribute__(__x) +#endif + +#ifndef _WIN32_WCE +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_CONIO_H 1 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 1 +#define APR_HAVE_DIRENT_H 0 +#define APR_HAVE_ERRNO_H 1 +#define APR_HAVE_FCNTL_H 1 +#define APR_HAVE_IO_H 1 +#define APR_HAVE_LIMITS_H 1 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SEMAPHORE_H 0 +#define APR_HAVE_SIGNAL_H 1 +#define APR_HAVE_STDARG_H 1 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_SYS_IOCTL_H 0 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SIGNAL_H 0 +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#define APR_HAVE_SYS_TIME_H 0 +#define APR_HAVE_SYS_TYPES_H 1 +#define APR_HAVE_SYS_UIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#define APR_HAVE_SYS_WAIT_H 0 +#define APR_HAVE_TIME_H 1 +#define APR_HAVE_UNISTD_H 0 +#define APR_HAVE_STDDEF_H 1 +#define APR_HAVE_PROCESS_H 1 +#else +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_CONIO_H 0 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 0 +#define APR_HAVE_DIRENT_H 0 +#define APR_HAVE_ERRNO_H 0 +#define APR_HAVE_FCNTL_H 0 +#define APR_HAVE_IO_H 0 +#define APR_HAVE_LIMITS_H 0 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SEMAPHORE_H 0 +#define APR_HAVE_SIGNAL_H 0 +#define APR_HAVE_STDARG_H 0 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_SYS_IOCTL_H 0 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SIGNAL_H 0 +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#define APR_HAVE_SYS_TIME_H 0 +#define APR_HAVE_SYS_TYPES_H 0 +#define APR_HAVE_SYS_UIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#define APR_HAVE_SYS_WAIT_H 0 +#define APR_HAVE_TIME_H 0 +#define APR_HAVE_UNISTD_H 0 +#define APR_HAVE_STDDEF_H 0 +#define APR_HAVE_PROCESS_H 0 +#endif + +/** @} */ +/** @} */ + +/* We don't include our conditional headers within the doxyblocks + * or the extern "C" namespace + */ + +#if APR_HAVE_STDLIB_H +#include +#endif + +#if APR_HAVE_STDIO_H +#include +#endif + +#if APR_HAVE_SYS_TYPES_H +#include +#endif + +#if APR_HAVE_STDDEF_H +#include +#endif + +#if APR_HAVE_SYS_SOCKET_H +#include +#endif + +#if APR_HAVE_STDINT_H +#include +#endif + +#if APR_HAVE_SYS_WAIT_H +#include +#endif + +#if APR_HAVE_TIME_H +#include +#endif + +#if APR_HAVE_PROCESS_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @addtogroup apr_platform + * @ingroup APR + * @{ + */ + +#define APR_HAVE_SHMEM_MMAP_TMP 0 +#define APR_HAVE_SHMEM_MMAP_SHM 0 +#define APR_HAVE_SHMEM_MMAP_ZERO 0 +#define APR_HAVE_SHMEM_SHMGET_ANON 0 +#define APR_HAVE_SHMEM_SHMGET 0 +#define APR_HAVE_SHMEM_MMAP_ANON 0 +#define APR_HAVE_SHMEM_BEOS 0 + +#define APR_USE_SHMEM_MMAP_TMP 0 +#define APR_USE_SHMEM_MMAP_SHM 0 +#define APR_USE_SHMEM_MMAP_ZERO 0 +#define APR_USE_SHMEM_SHMGET_ANON 0 +#define APR_USE_SHMEM_SHMGET 0 +#define APR_USE_SHMEM_MMAP_ANON 0 +#define APR_USE_SHMEM_BEOS 0 + +#define APR_USE_FLOCK_SERIALIZE 0 +#define APR_USE_POSIXSEM_SERIALIZE 0 +#define APR_USE_SYSVSEM_SERIALIZE 0 +#define APR_USE_FCNTL_SERIALIZE 0 +#define APR_USE_PROC_PTHREAD_SERIALIZE 0 +#define APR_USE_PTHREAD_SERIALIZE 0 + +#define APR_HAS_FLOCK_SERIALIZE 0 +#define APR_HAS_SYSVSEM_SERIALIZE 0 +#define APR_HAS_POSIXSEM_SERIALIZE 0 +#define APR_HAS_FCNTL_SERIALIZE 0 +#define APR_HAS_PROC_PTHREAD_SERIALIZE 0 + +#define APR_PROCESS_LOCK_IS_GLOBAL 0 + +#define APR_HAVE_CORKABLE_TCP 0 +#define APR_HAVE_GETRLIMIT 0 +#define APR_HAVE_ICONV 0 +#define APR_HAVE_IN_ADDR 1 +#define APR_HAVE_INET_ADDR 1 +#define APR_HAVE_INET_NETWORK 0 +#define APR_HAVE_IPV6 @apr_have_ipv6_10@ +#define APR_HAVE_SOCKADDR_UN 0 +#define APR_HAVE_MEMMOVE 1 +#define APR_HAVE_SETRLIMIT 0 +#define APR_HAVE_SIGACTION 0 +#define APR_HAVE_SIGSUSPEND 0 +#define APR_HAVE_SIGWAIT 0 +#define APR_HAVE_SA_STORAGE 0 +#define APR_HAVE_STRCASECMP 0 +#define APR_HAVE_STRDUP 1 +#define APR_HAVE_STRNCASECMP 0 +#define APR_HAVE_STRSTR 1 +#define APR_HAVE_MEMCHR 1 +#define APR_HAVE_STRUCT_RLIMIT 0 +#define APR_HAVE_UNION_SEMUN 0 +#define APR_HAVE_SCTP 0 +#define APR_HAVE_IOVEC 0 + +#ifndef _WIN32_WCE +#define APR_HAVE_STRICMP 1 +#define APR_HAVE_STRNICMP 1 +#else +#define APR_HAVE_STRICMP 0 +#define APR_HAVE_STRNICMP 0 +#endif + +/* APR Feature Macros */ +#define APR_HAS_SHARED_MEMORY 1 +#define APR_HAS_THREADS 1 +#define APR_HAS_MMAP 1 +#define APR_HAS_FORK 0 +#define APR_HAS_RANDOM 1 +#define APR_HAS_OTHER_CHILD 1 +#define APR_HAS_DSO 1 +#define APR_HAS_SO_ACCEPTFILTER 0 +#define APR_HAS_UNICODE_FS 1 +#define APR_HAS_PROC_INVOKED 1 +#define APR_HAS_OS_UUID 1 +#define APR_HAS_TIMEDLOCKS 1 + +#ifndef _WIN32_WCE +#define APR_HAS_SENDFILE 1 +#define APR_HAS_USER 1 +#define APR_HAS_LARGE_FILES 1 +#define APR_HAS_XTHREAD_FILES 1 +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 1 +#else +#define APR_HAS_SENDFILE 0 +#define APR_HAS_USER 0 +#define APR_HAS_LARGE_FILES 0 +#define APR_HAS_XTHREAD_FILES 0 +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 0 +#endif + +/* APR sets APR_FILES_AS_SOCKETS to 1 on systems where it is possible + * to poll on files/pipes. + */ +#define APR_FILES_AS_SOCKETS 0 + +/* This macro indicates whether or not EBCDIC is the native character set. + */ +#define APR_CHARSET_EBCDIC 0 + +/* If we have a TCP implementation that can be "corked", what flag + * do we use? + */ +#define APR_TCP_NOPUSH_FLAG @apr_tcp_nopush_flag@ + +/* Is the TCP_NODELAY socket option inherited from listening sockets? + */ +#define APR_TCP_NODELAY_INHERITED 1 + +/* Is the O_NONBLOCK flag inherited from listening sockets? + */ +#define APR_O_NONBLOCK_INHERITED 1 + +/* Typedefs that APR needs. */ + +typedef unsigned char apr_byte_t; + +typedef short apr_int16_t; +typedef unsigned short apr_uint16_t; + +typedef int apr_int32_t; +typedef unsigned int apr_uint32_t; + +typedef __int64 apr_int64_t; +typedef unsigned __int64 apr_uint64_t; + +typedef size_t apr_size_t; +#if APR_HAVE_STDDEF_H +typedef ptrdiff_t apr_ssize_t; +#else +typedef int apr_ssize_t; +#endif +#if APR_HAS_LARGE_FILES +typedef __int64 apr_off_t; +#else +typedef int apr_off_t; +#endif +typedef int apr_socklen_t; +typedef apr_uint64_t apr_ino_t; + +#ifdef _WIN64 +#define APR_SIZEOF_VOIDP 8 +#else +#define APR_SIZEOF_VOIDP 4 +#endif + +#if APR_SIZEOF_VOIDP == 8 +typedef apr_uint64_t apr_uintptr_t; +#else +typedef apr_uint32_t apr_uintptr_t; +#endif + +/* Are we big endian? */ +/* XXX: Fatal assumption on Alpha platforms */ +#define APR_IS_BIGENDIAN 0 + +/* Mechanisms to properly type numeric literals */ + +#ifndef __GNUC__ +#define APR_INT64_C(val) (val##i64) +#define APR_UINT64_C(val) (val##Ui64) +#else +#define APR_INT64_C(val) (val##LL) +#define APR_UINT64_C(val) (val##ULL) +#endif + +#ifdef INT16_MIN +#define APR_INT16_MIN INT16_MIN +#else +#define APR_INT16_MIN (-0x7fff - 1) +#endif + +#ifdef INT16_MAX +#define APR_INT16_MAX INT16_MAX +#else +#define APR_INT16_MAX (0x7fff) +#endif + +#ifdef UINT16_MAX +#define APR_UINT16_MAX UINT16_MAX +#else +#define APR_UINT16_MAX (0xffff) +#endif + +#ifdef INT32_MIN +#define APR_INT32_MIN INT32_MIN +#else +#define APR_INT32_MIN (-0x7fffffff - 1) +#endif + +#ifdef INT32_MAX +#define APR_INT32_MAX INT32_MAX +#else +#define APR_INT32_MAX 0x7fffffff +#endif + +#ifdef UINT32_MAX +#define APR_UINT32_MAX UINT32_MAX +#else +#define APR_UINT32_MAX (0xffffffffU) +#endif + +#ifdef INT64_MIN +#define APR_INT64_MIN INT64_MIN +#else +#define APR_INT64_MIN (APR_INT64_C(-0x7fffffffffffffff) - 1) +#endif + +#ifdef INT64_MAX +#define APR_INT64_MAX INT64_MAX +#else +#define APR_INT64_MAX APR_INT64_C(0x7fffffffffffffff) +#endif + +#ifdef UINT64_MAX +#define APR_UINT64_MAX UINT64_MAX +#else +#define APR_UINT64_MAX APR_UINT64_C(0xffffffffffffffff) +#endif + +#define APR_SIZE_MAX (~((apr_size_t)0)) + +/* Definitions that APR programs need to work properly. */ + +/** + * APR public API wrap for C++ compilers. + */ +#ifdef __cplusplus +#define APR_BEGIN_DECLS extern "C" { +#define APR_END_DECLS } +#else +#define APR_BEGIN_DECLS +#define APR_END_DECLS +#endif + +/** + * Thread callbacks from APR functions must be declared with APR_THREAD_FUNC, + * so that they follow the platform's calling convention. + *
+ *
+ * void* APR_THREAD_FUNC my_thread_entry_fn(apr_thread_t *thd, void *data);
+ *
+ * 
+ */ +#define APR_THREAD_FUNC __stdcall + + +#if defined(DOXYGEN) || !defined(WIN32) + +/** + * The public APR functions are declared with APR_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APR_DECLARE_NONSTD(). + * + * @remark Both the declaration and implementations must use the same macro. + * + *
+ * APR_DECLARE(rettype) apr_func(args)
+ * 
+ * @see APR_DECLARE_NONSTD @see APR_DECLARE_DATA + * @remark Note that when APR compiles the library itself, it passes the + * symbol -DAPR_DECLARE_EXPORT to the compiler on some platforms (e.g. Win32) + * to export public symbols from the dynamic library build.\n + * The user must define the APR_DECLARE_STATIC when compiling to target + * the static APR library on some platforms (e.g. Win32.) The public symbols + * are neither exported nor imported when APR_DECLARE_STATIC is defined.\n + * By default, compiling an application and including the APR public + * headers, without defining APR_DECLARE_STATIC, will prepare the code to be + * linked to the dynamic library. + */ +#define APR_DECLARE(type) type + +/** + * The public APR functions using variable arguments are declared with + * APR_DECLARE_NONSTD(), as they must follow the C language calling convention. + * @see APR_DECLARE @see APR_DECLARE_DATA + * @remark Both the declaration and implementations must use the same macro. + *
+ *
+ * APR_DECLARE_NONSTD(rettype) apr_func(args, ...);
+ *
+ * 
+ */ +#define APR_DECLARE_NONSTD(type) type + +/** + * The public APR variables are declared with AP_MODULE_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * @see APR_DECLARE @see APR_DECLARE_NONSTD + * @remark Note that the declaration and implementations use different forms, + * but both must include the macro. + * + *
+ *
+ * extern APR_DECLARE_DATA type apr_variable;\n
+ * APR_DECLARE_DATA type apr_variable = value;
+ *
+ * 
+ */ +#define APR_DECLARE_DATA + +#elif defined(APR_DECLARE_STATIC) +#define APR_DECLARE(type) type __stdcall +#define APR_DECLARE_NONSTD(type) type __cdecl +#define APR_DECLARE_DATA +#elif defined(APR_DECLARE_EXPORT) +#define APR_DECLARE(type) __declspec(dllexport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllexport) +#else +#define APR_DECLARE(type) __declspec(dllimport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllimport) +#endif + +#ifdef _WIN64 +#define APR_SSIZE_T_FMT "I64d" +#define APR_SIZE_T_FMT "I64u" +#else +#define APR_SSIZE_T_FMT "d" +#define APR_SIZE_T_FMT "u" +#endif + +#if APR_HAS_LARGE_FILES +#define APR_OFF_T_FMT "I64d" +#else +#define APR_OFF_T_FMT "d" +#endif + +#define APR_PID_T_FMT "d" + +#define APR_INT64_T_FMT "I64d" +#define APR_UINT64_T_FMT "I64u" +#define APR_UINT64_T_HEX_FMT "I64x" + +/* No difference between PROC and GLOBAL mutex */ +#define APR_PROC_MUTEX_IS_GLOBAL 1 + +/* Local machine definition for console and log output. */ +#define APR_EOL_STR "\r\n" + +typedef int apr_wait_t; + +#if APR_HAS_UNICODE_FS +/* An arbitrary size that is digestable. True max is a bit less than 32000 */ +#define APR_PATH_MAX 8192 +#else /* !APR_HAS_UNICODE_FS */ +#define APR_PATH_MAX MAX_PATH +#endif + +#define APR_DSOPATH "PATH" + +/** @} */ + +/* Definitions that only Win32 programs need to compile properly. */ + +/* XXX These simply don't belong here, perhaps in apr_portable.h + * based on some APR_HAVE_PID/GID/UID? + */ +#ifndef __GNUC__ +typedef int pid_t; +#endif +typedef int uid_t; +typedef int gid_t; + +/* Win32 .h ommissions we really need */ +#define STDIN_FILENO 0 +#define STDOUT_FILENO 1 +#define STDERR_FILENO 2 + +#if APR_HAVE_IPV6 + +/* Appears in later flavors, not the originals. */ +#ifndef in_addr6 +#define in6_addr in_addr6 +#endif + +#ifndef WS2TCPIP_INLINE +#define IN6_IS_ADDR_V4MAPPED(a) \ + ( (*(const apr_uint64_t *)(const void *)(&(a)->s6_addr[0]) == 0) \ + && (*(const apr_uint32_t *)(const void *)(&(a)->s6_addr[8]) == ntohl(0x0000ffff))) +#endif + +#endif /* APR_HAVE_IPV6 */ + +#ifdef __cplusplus +} +#endif + +/* Done with badly written headers, leave 'deprecated CRT' undeprecated + */ +#if defined(_MSC_VER) && _MSC_VER >= 1200 +#pragma warning(pop) +#if _MSC_VER >= 1400 +#pragma warning(disable: 4996) +#endif +#endif + +#endif /* WIN32 */ + +#endif /* APR_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_allocator.h b/c/dependencies/windows/apr/x64_debug/include/apr_allocator.h new file mode 100644 index 00000000..be05d0e4 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_allocator.h @@ -0,0 +1,179 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ALLOCATOR_H +#define APR_ALLOCATOR_H + +/** + * @file apr_allocator.h + * @brief APR Internal Memory Allocation + */ + +#include "apr.h" +#include "apr_errno.h" +#define APR_WANT_MEMFUNC /**< For no good reason? */ +#include "apr_want.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_allocator Internal Memory Allocation + * @ingroup APR + * @{ + */ + +/** the allocator structure */ +typedef struct apr_allocator_t apr_allocator_t; +/** the structure which holds information about the allocation */ +typedef struct apr_memnode_t apr_memnode_t; + +/** basic memory node structure + * @note The next, ref and first_avail fields are available for use by the + * caller of apr_allocator_alloc(), the remaining fields are read-only. + * The next field has to be used with caution and sensibly set when the + * memnode is passed back to apr_allocator_free(). See apr_allocator_free() + * for details. + * The ref and first_avail fields will be properly restored by + * apr_allocator_free(). + */ +struct apr_memnode_t { + apr_memnode_t *next; /**< next memnode */ + apr_memnode_t **ref; /**< reference to self */ + apr_uint32_t index; /**< size */ + apr_uint32_t free_index; /**< how much free */ + char *first_avail; /**< pointer to first free memory */ + char *endp; /**< pointer to end of free memory */ +}; + +/** The base size of a memory node - aligned. */ +#define APR_MEMNODE_T_SIZE APR_ALIGN_DEFAULT(sizeof(apr_memnode_t)) + +/** Symbolic constants */ +#define APR_ALLOCATOR_MAX_FREE_UNLIMITED 0 + +/** + * Create a new allocator + * @param allocator The allocator we have just created. + * + */ +APR_DECLARE(apr_status_t) apr_allocator_create(apr_allocator_t **allocator) + __attribute__((nonnull(1))); + +/** + * Destroy an allocator + * @param allocator The allocator to be destroyed + * @remark Any memnodes not given back to the allocator prior to destroying + * will _not_ be free()d. + */ +APR_DECLARE(void) apr_allocator_destroy(apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +/** + * Allocate a block of mem from the allocator + * @param allocator The allocator to allocate from + * @param size The size of the mem to allocate (excluding the + * memnode structure) + */ +APR_DECLARE(apr_memnode_t *) apr_allocator_alloc(apr_allocator_t *allocator, + apr_size_t size) + __attribute__((nonnull(1))); + +/** + * Free a list of blocks of mem, giving them back to the allocator. + * The list is typically terminated by a memnode with its next field + * set to NULL. + * @param allocator The allocator to give the mem back to + * @param memnode The memory node to return + */ +APR_DECLARE(void) apr_allocator_free(apr_allocator_t *allocator, + apr_memnode_t *memnode) + __attribute__((nonnull(1,2))); + +/** + * Get the true size that would be allocated for the given size (including + * the header and alignment). + * @param allocator The allocator from which to the memory would be allocated + * @param size The size to align + * @return The aligned size (or zero on apr_size_t overflow) + */ +APR_DECLARE(apr_size_t) apr_allocator_align(apr_allocator_t *allocator, + apr_size_t size); + +#include "apr_pools.h" + +/** + * Set the owner of the allocator + * @param allocator The allocator to set the owner for + * @param pool The pool that is to own the allocator + * @remark Typically pool is the highest level pool using the allocator + */ +/* + * XXX: see if we can come up with something a bit better. Currently + * you can make a pool an owner, but if the pool doesn't use the allocator + * the allocator will never be destroyed. + */ +APR_DECLARE(void) apr_allocator_owner_set(apr_allocator_t *allocator, + apr_pool_t *pool) + __attribute__((nonnull(1))); + +/** + * Get the current owner of the allocator + * @param allocator The allocator to get the owner from + */ +APR_DECLARE(apr_pool_t *) apr_allocator_owner_get(apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +/** + * Set the current threshold at which the allocator should start + * giving blocks back to the system. + * @param allocator The allocator to set the threshold on + * @param size The threshold. 0 == unlimited. + */ +APR_DECLARE(void) apr_allocator_max_free_set(apr_allocator_t *allocator, + apr_size_t size) + __attribute__((nonnull(1))); + +#include "apr_thread_mutex.h" + +#if APR_HAS_THREADS +/** + * Set a mutex for the allocator to use + * @param allocator The allocator to set the mutex for + * @param mutex The mutex + */ +APR_DECLARE(void) apr_allocator_mutex_set(apr_allocator_t *allocator, + apr_thread_mutex_t *mutex) + __attribute__((nonnull(1))); + +/** + * Get the mutex currently set for the allocator + * @param allocator The allocator + */ +APR_DECLARE(apr_thread_mutex_t *) apr_allocator_mutex_get( + apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ALLOCATOR_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_anylock.h b/c/dependencies/windows/apr/x64_debug/include/apr_anylock.h new file mode 100644 index 00000000..51e97ff3 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_anylock.h @@ -0,0 +1,128 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_anylock.h + * @brief APR-Util transparent any lock flavor wrapper + */ +#ifndef APR_ANYLOCK_H +#define APR_ANYLOCK_H + +#include "apr_proc_mutex.h" +#include "apr_thread_mutex.h" +#include "apr_thread_rwlock.h" + +/** Structure that may contain any APR lock type */ +typedef struct apr_anylock_t { + /** Indicates what type of lock is in lock */ + enum tm_lock { + apr_anylock_none, /**< None */ + apr_anylock_procmutex, /**< Process-based */ + apr_anylock_threadmutex, /**< Thread-based */ + apr_anylock_readlock, /**< Read lock */ + apr_anylock_writelock /**< Write lock */ + } type; + /** Union of all possible APR locks */ + union apr_anylock_u_t { + apr_proc_mutex_t *pm; /**< Process mutex */ +#if APR_HAS_THREADS + apr_thread_mutex_t *tm; /**< Thread mutex */ + apr_thread_rwlock_t *rw; /**< Read-write lock */ +#endif + } lock; +} apr_anylock_t; + +#if APR_HAS_THREADS + +/** Lock an apr_anylock_t structure */ +#define APR_ANYLOCK_LOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_threadmutex) \ + ? apr_thread_mutex_lock((lck)->lock.tm) \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_lock((lck)->lock.pm) \ + : (((lck)->type == apr_anylock_readlock) \ + ? apr_thread_rwlock_rdlock((lck)->lock.rw) \ + : (((lck)->type == apr_anylock_writelock) \ + ? apr_thread_rwlock_wrlock((lck)->lock.rw) \ + : APR_EINVAL))))) + +#else /* APR_HAS_THREADS */ + +#define APR_ANYLOCK_LOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_lock((lck)->lock.pm) \ + : APR_EINVAL)) + +#endif /* APR_HAS_THREADS */ + +#if APR_HAS_THREADS + +/** Try to lock an apr_anylock_t structure */ +#define APR_ANYLOCK_TRYLOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_threadmutex) \ + ? apr_thread_mutex_trylock((lck)->lock.tm) \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_trylock((lck)->lock.pm) \ + : (((lck)->type == apr_anylock_readlock) \ + ? apr_thread_rwlock_tryrdlock((lck)->lock.rw) \ + : (((lck)->type == apr_anylock_writelock) \ + ? apr_thread_rwlock_trywrlock((lck)->lock.rw) \ + : APR_EINVAL))))) + +#else /* APR_HAS_THREADS */ + +#define APR_ANYLOCK_TRYLOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_trylock((lck)->lock.pm) \ + : APR_EINVAL)) + +#endif /* APR_HAS_THREADS */ + +#if APR_HAS_THREADS + +/** Unlock an apr_anylock_t structure */ +#define APR_ANYLOCK_UNLOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_threadmutex) \ + ? apr_thread_mutex_unlock((lck)->lock.tm) \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_unlock((lck)->lock.pm) \ + : ((((lck)->type == apr_anylock_readlock) || \ + ((lck)->type == apr_anylock_writelock)) \ + ? apr_thread_rwlock_unlock((lck)->lock.rw) \ + : APR_EINVAL)))) + +#else /* APR_HAS_THREADS */ + +#define APR_ANYLOCK_UNLOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_unlock((lck)->lock.pm) \ + : APR_EINVAL)) + +#endif /* APR_HAS_THREADS */ + +#endif /* !APR_ANYLOCK_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_atomic.h b/c/dependencies/windows/apr/x64_debug/include/apr_atomic.h new file mode 100644 index 00000000..3d203edc --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_atomic.h @@ -0,0 +1,207 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ATOMIC_H +#define APR_ATOMIC_H + +/** + * @file apr_atomic.h + * @brief APR Atomic Operations + */ + +#include "apr.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_atomic Atomic Operations + * @ingroup APR + * @{ + */ + +/** + * this function is required on some platforms to initialize the + * atomic operation's internal structures + * @param p pool + * @return APR_SUCCESS on successful completion + * @remark Programs do NOT need to call this directly. APR will call this + * automatically from apr_initialize(). + * @internal + */ +APR_DECLARE(apr_status_t) apr_atomic_init(apr_pool_t *p); + +/* + * Atomic operations on 32-bit values + * Note: Each of these functions internally implements a memory barrier + * on platforms that require it + */ + +/** + * atomically read an apr_uint32_t from memory + * @param mem the pointer + */ +APR_DECLARE(apr_uint32_t) apr_atomic_read32(volatile apr_uint32_t *mem); + +/** + * atomically set an apr_uint32_t in memory + * @param mem pointer to the object + * @param val value that the object will assume + */ +APR_DECLARE(void) apr_atomic_set32(volatile apr_uint32_t *mem, apr_uint32_t val); + +/** + * atomically add 'val' to an apr_uint32_t + * @param mem pointer to the object + * @param val amount to add + * @return old value pointed to by mem + */ +APR_DECLARE(apr_uint32_t) apr_atomic_add32(volatile apr_uint32_t *mem, apr_uint32_t val); + +/** + * atomically subtract 'val' from an apr_uint32_t + * @param mem pointer to the object + * @param val amount to subtract + */ +APR_DECLARE(void) apr_atomic_sub32(volatile apr_uint32_t *mem, apr_uint32_t val); + +/** + * atomically increment an apr_uint32_t by 1 + * @param mem pointer to the object + * @return old value pointed to by mem + */ +APR_DECLARE(apr_uint32_t) apr_atomic_inc32(volatile apr_uint32_t *mem); + +/** + * atomically decrement an apr_uint32_t by 1 + * @param mem pointer to the atomic value + * @return zero if the value becomes zero on decrement, otherwise non-zero + */ +APR_DECLARE(int) apr_atomic_dec32(volatile apr_uint32_t *mem); + +/** + * compare an apr_uint32_t's value with 'cmp'. + * If they are the same swap the value with 'with' + * @param mem pointer to the value + * @param with what to swap it with + * @param cmp the value to compare it to + * @return the old value of *mem + */ +APR_DECLARE(apr_uint32_t) apr_atomic_cas32(volatile apr_uint32_t *mem, apr_uint32_t with, + apr_uint32_t cmp); + +/** + * exchange an apr_uint32_t's value with 'val'. + * @param mem pointer to the value + * @param val what to swap it with + * @return the old value of *mem + */ +APR_DECLARE(apr_uint32_t) apr_atomic_xchg32(volatile apr_uint32_t *mem, apr_uint32_t val); + +/* + * Atomic operations on 64-bit values + * Note: Each of these functions internally implements a memory barrier + * on platforms that require it + */ + +/** + * atomically read an apr_uint64_t from memory + * @param mem the pointer + */ +APR_DECLARE(apr_uint64_t) apr_atomic_read64(volatile apr_uint64_t *mem); + +/** + * atomically set an apr_uint64_t in memory + * @param mem pointer to the object + * @param val value that the object will assume + */ +APR_DECLARE(void) apr_atomic_set64(volatile apr_uint64_t *mem, apr_uint64_t val); + +/** + * atomically add 'val' to an apr_uint64_t + * @param mem pointer to the object + * @param val amount to add + * @return old value pointed to by mem + */ +APR_DECLARE(apr_uint64_t) apr_atomic_add64(volatile apr_uint64_t *mem, apr_uint64_t val); + +/** + * atomically subtract 'val' from an apr_uint64_t + * @param mem pointer to the object + * @param val amount to subtract + */ +APR_DECLARE(void) apr_atomic_sub64(volatile apr_uint64_t *mem, apr_uint64_t val); + +/** + * atomically increment an apr_uint64_t by 1 + * @param mem pointer to the object + * @return old value pointed to by mem + */ +APR_DECLARE(apr_uint64_t) apr_atomic_inc64(volatile apr_uint64_t *mem); + +/** + * atomically decrement an apr_uint64_t by 1 + * @param mem pointer to the atomic value + * @return zero if the value becomes zero on decrement, otherwise non-zero + */ +APR_DECLARE(int) apr_atomic_dec64(volatile apr_uint64_t *mem); + +/** + * compare an apr_uint64_t's value with 'cmp'. + * If they are the same swap the value with 'with' + * @param mem pointer to the value + * @param with what to swap it with + * @param cmp the value to compare it to + * @return the old value of *mem + */ +APR_DECLARE(apr_uint64_t) apr_atomic_cas64(volatile apr_uint64_t *mem, apr_uint64_t with, + apr_uint64_t cmp); + +/** + * exchange an apr_uint64_t's value with 'val'. + * @param mem pointer to the value + * @param val what to swap it with + * @return the old value of *mem + */ +APR_DECLARE(apr_uint64_t) apr_atomic_xchg64(volatile apr_uint64_t *mem, apr_uint64_t val); + +/** + * compare the pointer's value with cmp. + * If they are the same swap the value with 'with' + * @param mem pointer to the pointer + * @param with what to swap it with + * @param cmp the value to compare it to + * @return the old value of the pointer + */ +APR_DECLARE(void*) apr_atomic_casptr(volatile void **mem, void *with, const void *cmp); + +/** + * exchange a pair of pointer values + * @param mem pointer to the pointer + * @param with what to swap it with + * @return the old value of the pointer + */ +APR_DECLARE(void*) apr_atomic_xchgptr(volatile void **mem, void *with); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ATOMIC_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_base64.h b/c/dependencies/windows/apr/x64_debug/include/apr_base64.h new file mode 100644 index 00000000..17de1c58 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_base64.h @@ -0,0 +1,113 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * The apr_vsnprintf/apr_snprintf functions are based on, and used with the + * permission of, the SIO stdio-replacement strx_* functions by Panos + * Tsirigotis for xinetd. + */ + +/** + * @file apr_base64.h + * @brief APR-UTIL Base64 Encoding + */ +#ifndef APR_BASE64_H +#define APR_BASE64_H + +#include "apu.h" +#include "apr_general.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Base64 Base64 Encoding + * @ingroup APR_Util + * @{ + */ + +/* Simple BASE64 encode/decode functions. + * + * As we might encode binary strings, hence we require the length of + * the incoming plain source. And return the length of what we decoded. + * + * The decoding function takes any non valid char (i.e. whitespace, \0 + * or anything non A-Z,0-9 etc as terminal. + * + * plain strings/binary sequences are not assumed '\0' terminated. Encoded + * strings are neither. But probably should. + * + */ + +/** + * Given the length of an un-encoded string, get the length of the + * encoded string. + * @param len the length of an unencoded string. + * @return the length of the string after it is encoded, including the + * trailing \0 + */ +APU_DECLARE(int) apr_base64_encode_len(int len); + +/** + * Encode a text string using base64encoding. + * @param coded_dst The destination string for the encoded string. + * @param plain_src The original string in plain text + * @param len_plain_src The length of the plain text string + * @return the length of the encoded string + */ +APU_DECLARE(int) apr_base64_encode(char * coded_dst, const char *plain_src, + int len_plain_src); + +/** + * Encode an EBCDIC string using base64encoding. + * @param coded_dst The destination string for the encoded string. + * @param plain_src The original string in plain text + * @param len_plain_src The length of the plain text string + * @return the length of the encoded string + */ +APU_DECLARE(int) apr_base64_encode_binary(char * coded_dst, + const unsigned char *plain_src, + int len_plain_src); + +/** + * Determine the maximum buffer length required to decode the plain text + * string given the encoded string. + * @param coded_src The encoded string + * @return the maximum required buffer length for the plain text string + */ +APU_DECLARE(int) apr_base64_decode_len(const char * coded_src); + +/** + * Decode a string to plain text + * @param plain_dst The destination string for the plain text + * @param coded_src The encoded string + * @return the length of the plain text string + */ +APU_DECLARE(int) apr_base64_decode(char * plain_dst, const char *coded_src); + +/** + * Decode an EBCDIC string to plain text + * @param plain_dst The destination string for the plain text + * @param coded_src The encoded string + * @return the length of the plain text string + */ +APU_DECLARE(int) apr_base64_decode_binary(unsigned char * plain_dst, + const char *coded_src); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_BASE64_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_buckets.h b/c/dependencies/windows/apr/x64_debug/include/apr_buckets.h new file mode 100644 index 00000000..ce64b78d --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_buckets.h @@ -0,0 +1,1598 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file apr_buckets.h + * @brief APR-UTIL Buckets/Bucket Brigades + */ + +#ifndef APR_BUCKETS_H +#define APR_BUCKETS_H + +#if defined(APR_BUCKET_DEBUG) && !defined(APR_RING_DEBUG) +#define APR_RING_DEBUG +#endif + +#include "apu.h" +#include "apr_network_io.h" +#include "apr_file_io.h" +#include "apr_general.h" +#include "apr_mmap.h" +#include "apr_errno.h" +#include "apr_ring.h" +#include "apr.h" +#if APR_HAVE_SYS_UIO_H +#include /* for struct iovec */ +#endif +#if APR_HAVE_STDARG_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Bucket_Brigades Bucket Brigades + * @ingroup APR_Util + * @{ + */ + +/** default bucket buffer size - 8KB minus room for memory allocator headers */ +#define APR_BUCKET_BUFF_SIZE 8000 + +/** Determines how a bucket or brigade should be read */ +typedef enum { + APR_BLOCK_READ, /**< block until data becomes available */ + APR_NONBLOCK_READ /**< return immediately if no data is available */ +} apr_read_type_e; + +/** + * The one-sentence buzzword-laden overview: Bucket brigades represent + * a complex data stream that can be passed through a layered IO + * system without unnecessary copying. A longer overview follows... + * + * A bucket brigade is a doubly linked list (ring) of buckets, so we + * aren't limited to inserting at the front and removing at the end. + * Buckets are only passed around as members of a brigade, although + * singleton buckets can occur for short periods of time. + * + * Buckets are data stores of various types. They can refer to data in + * memory, or part of a file or mmap area, or the output of a process, + * etc. Buckets also have some type-dependent accessor functions: + * read, split, copy, setaside, and destroy. + * + * read returns the address and size of the data in the bucket. If the + * data isn't in memory then it is read in and the bucket changes type + * so that it can refer to the new location of the data. If all the + * data doesn't fit in the bucket then a new bucket is inserted into + * the brigade to hold the rest of it. + * + * split divides the data in a bucket into two regions. After a split + * the original bucket refers to the first part of the data and a new + * bucket inserted into the brigade after the original bucket refers + * to the second part of the data. Reference counts are maintained as + * necessary. + * + * setaside ensures that the data in the bucket has a long enough + * lifetime. Sometimes it is convenient to create a bucket referring + * to data on the stack in the expectation that it will be consumed + * (output to the network) before the stack is unwound. If that + * expectation turns out not to be valid, the setaside function is + * called to move the data somewhere safer. + * + * copy makes a duplicate of the bucket structure as long as it's + * possible to have multiple references to a single copy of the + * data itself. Not all bucket types can be copied. + * + * destroy maintains the reference counts on the resources used by a + * bucket and frees them if necessary. + * + * Note: all of the above functions have wrapper macros (apr_bucket_read(), + * apr_bucket_destroy(), etc), and those macros should be used rather + * than using the function pointers directly. + * + * To write a bucket brigade, they are first made into an iovec, so that we + * don't write too little data at one time. Currently we ignore compacting the + * buckets into as few buckets as possible, but if we really want good + * performance, then we need to compact the buckets before we convert to an + * iovec, or possibly while we are converting to an iovec. + */ + +/* + * Forward declaration of the main types. + */ + +/** @see apr_bucket_brigade */ +typedef struct apr_bucket_brigade apr_bucket_brigade; +/** @see apr_bucket */ +typedef struct apr_bucket apr_bucket; +/** @see apr_bucket_alloc_t */ +typedef struct apr_bucket_alloc_t apr_bucket_alloc_t; + +/** @see apr_bucket_type_t */ +typedef struct apr_bucket_type_t apr_bucket_type_t; + +/** + * Basic bucket type + */ +struct apr_bucket_type_t { + /** + * The name of the bucket type + */ + const char *name; + /** + * The number of functions this bucket understands. Can not be less than + * five. + */ + int num_func; + /** + * Whether the bucket contains metadata (ie, information that + * describes the regular contents of the brigade). The metadata + * is not returned by apr_bucket_read() and is not indicated by + * the ->length of the apr_bucket itself. In other words, an + * empty bucket is safe to arbitrarily remove if and only if it + * contains no metadata. In this sense, "data" is just raw bytes + * that are the "content" of the brigade and "metadata" describes + * that data but is not a proper part of it. + */ + enum { + /** This bucket type represents actual data to send to the client. */ + APR_BUCKET_DATA = 0, + /** This bucket type represents metadata. */ + APR_BUCKET_METADATA = 1 + } is_metadata; + /** + * Free the private data and any resources used by the bucket (if they + * aren't shared with another bucket). This function is required to be + * implemented for all bucket types, though it might be a no-op on some + * of them (namely ones that never allocate any private data structures). + * @param data The private data pointer from the bucket to be destroyed + */ + void (*destroy)(void *data); + + /** + * Read the data from the bucket. This is required to be implemented + * for all bucket types. + * @param b The bucket to read from + * @param str A place to store the data read. Allocation should only be + * done if absolutely necessary. + * @param len The amount of data read. + * @param block Should this read function block if there is more data that + * cannot be read immediately. + */ + apr_status_t (*read)(apr_bucket *b, const char **str, apr_size_t *len, + apr_read_type_e block); + + /** + * Make it possible to set aside the data for at least as long as the + * given pool. Buckets containing data that could potentially die before + * this pool (e.g. the data resides on the stack, in a child pool of + * the given pool, or in a disjoint pool) must somehow copy, shift, or + * transform the data to have the proper lifetime. + * @param e The bucket to convert + * @remark Some bucket types contain data that will always outlive the + * bucket itself. For example no data (EOS and FLUSH), or the data + * resides in global, constant memory (IMMORTAL), or the data is on + * the heap (HEAP). For these buckets, apr_bucket_setaside_noop can + * be used. + */ + apr_status_t (*setaside)(apr_bucket *e, apr_pool_t *pool); + + /** + * Split one bucket in two at the specified position by duplicating + * the bucket structure (not the data) and modifying any necessary + * start/end/offset information. If it's not possible to do this + * for the bucket type (perhaps the length of the data is indeterminate, + * as with pipe and socket buckets), then APR_ENOTIMPL is returned. + * @param e The bucket to split + * @param point The offset of the first byte in the new bucket + */ + apr_status_t (*split)(apr_bucket *e, apr_size_t point); + + /** + * Copy the bucket structure (not the data), assuming that this is + * possible for the bucket type. If it's not, APR_ENOTIMPL is returned. + * @param e The bucket to copy + * @param c Returns a pointer to the new bucket + */ + apr_status_t (*copy)(apr_bucket *e, apr_bucket **c); + +}; + +/** + * apr_bucket structures are allocated on the malloc() heap and + * their lifetime is controlled by the parent apr_bucket_brigade + * structure. Buckets can move from one brigade to another e.g. by + * calling APR_BRIGADE_CONCAT(). In general the data in a bucket has + * the same lifetime as the bucket and is freed when the bucket is + * destroyed; if the data is shared by more than one bucket (e.g. + * after a split) the data is freed when the last bucket goes away. + */ +struct apr_bucket { + /** Links to the rest of the brigade */ + APR_RING_ENTRY(apr_bucket) link; + /** The type of bucket. */ + const apr_bucket_type_t *type; + /** The length of the data in the bucket. This could have been implemented + * with a function, but this is an optimization, because the most + * common thing to do will be to get the length. If the length is unknown, + * the value of this field will be (apr_size_t)(-1). + */ + apr_size_t length; + /** The start of the data in the bucket relative to the private base + * pointer. The vast majority of bucket types allow a fixed block of + * data to be referenced by multiple buckets, each bucket pointing to + * a different segment of the data. That segment starts at base+start + * and ends at base+start+length. + * If the length == (apr_size_t)(-1), then start == -1. + */ + apr_off_t start; + /** type-dependent data hangs off this pointer */ + void *data; + /** + * Pointer to function used to free the bucket. This function should + * always be defined and it should be consistent with the memory + * function used to allocate the bucket. For example, if malloc() is + * used to allocate the bucket, this pointer should point to free(). + * @param e Pointer to the bucket being freed + */ + void (*free)(void *e); + /** The freelist from which this bucket was allocated */ + apr_bucket_alloc_t *list; +}; + +/** A list of buckets */ +struct apr_bucket_brigade { + /** The pool to associate the brigade with. The data is not allocated out + * of the pool, but a cleanup is registered with this pool. If the + * brigade is destroyed by some mechanism other than pool destruction, + * the destroying function is responsible for killing the cleanup. + */ + apr_pool_t *p; + /** The buckets in the brigade are on this list. */ + /* + * The apr_bucket_list structure doesn't actually need a name tag + * because it has no existence independent of struct apr_bucket_brigade; + * the ring macros are designed so that you can leave the name tag + * argument empty in this situation but apparently the Windows compiler + * doesn't like that. + */ + APR_RING_HEAD(apr_bucket_list, apr_bucket) list; + /** The freelist from which this bucket was allocated */ + apr_bucket_alloc_t *bucket_alloc; +}; + + +/** + * Function called when a brigade should be flushed + */ +typedef apr_status_t (*apr_brigade_flush)(apr_bucket_brigade *bb, void *ctx); + +/* + * define APR_BUCKET_DEBUG if you want your brigades to be checked for + * validity at every possible instant. this will slow your code down + * substantially but is a very useful debugging tool. + */ +#ifdef APR_BUCKET_DEBUG + +#define APR_BRIGADE_CHECK_CONSISTENCY(b) \ + APR_RING_CHECK_CONSISTENCY(&(b)->list, apr_bucket, link) + +#define APR_BUCKET_CHECK_CONSISTENCY(e) \ + APR_RING_CHECK_ELEM_CONSISTENCY((e), apr_bucket, link) + +#else +/** + * checks the ring pointers in a bucket brigade for consistency. an + * abort() will be triggered if any inconsistencies are found. + * note: this is a no-op unless APR_BUCKET_DEBUG is defined. + * @param b The brigade + */ +#define APR_BRIGADE_CHECK_CONSISTENCY(b) +/** + * checks the brigade a bucket is in for ring consistency. an + * abort() will be triggered if any inconsistencies are found. + * note: this is a no-op unless APR_BUCKET_DEBUG is defined. + * @param e The bucket + */ +#define APR_BUCKET_CHECK_CONSISTENCY(e) +#endif + + +/** + * Wrappers around the RING macros to reduce the verbosity of the code + * that handles bucket brigades. + */ +/** + * The magic pointer value that indicates the head of the brigade + * @remark This is used to find the beginning and end of the brigade, eg: + *
+ *      while (e != APR_BRIGADE_SENTINEL(b)) {
+ *          ...
+ *          e = APR_BUCKET_NEXT(e);
+ *      }
+ * 
+ * @param b The brigade + * @return The magic pointer value + */ +#define APR_BRIGADE_SENTINEL(b) APR_RING_SENTINEL(&(b)->list, apr_bucket, link) + +/** + * Determine if the bucket brigade is empty + * @param b The brigade to check + * @return true or false + */ +#define APR_BRIGADE_EMPTY(b) APR_RING_EMPTY(&(b)->list, apr_bucket, link) + +/** + * Return the first bucket in a brigade + * @param b The brigade to query + * @return The first bucket in the brigade + */ +#define APR_BRIGADE_FIRST(b) APR_RING_FIRST(&(b)->list) +/** + * Return the last bucket in a brigade + * @param b The brigade to query + * @return The last bucket in the brigade + */ +#define APR_BRIGADE_LAST(b) APR_RING_LAST(&(b)->list) + +/** + * Insert a single bucket at the front of a brigade + * @param b The brigade to add to + * @param e The bucket to insert + */ +#define APR_BRIGADE_INSERT_HEAD(b, e) do { \ + apr_bucket *ap__b = (e); \ + APR_RING_INSERT_HEAD(&(b)->list, ap__b, apr_bucket, link); \ + APR_BRIGADE_CHECK_CONSISTENCY((b)); \ + } while (0) + +/** + * Insert a single bucket at the end of a brigade + * @param b The brigade to add to + * @param e The bucket to insert + */ +#define APR_BRIGADE_INSERT_TAIL(b, e) do { \ + apr_bucket *ap__b = (e); \ + APR_RING_INSERT_TAIL(&(b)->list, ap__b, apr_bucket, link); \ + APR_BRIGADE_CHECK_CONSISTENCY((b)); \ + } while (0) + +/** + * Concatenate brigade b onto the end of brigade a, leaving brigade b empty + * @param a The first brigade + * @param b The second brigade + */ +#define APR_BRIGADE_CONCAT(a, b) do { \ + APR_RING_CONCAT(&(a)->list, &(b)->list, apr_bucket, link); \ + APR_BRIGADE_CHECK_CONSISTENCY((a)); \ + } while (0) + +/** + * Prepend brigade b onto the beginning of brigade a, leaving brigade b empty + * @param a The first brigade + * @param b The second brigade + */ +#define APR_BRIGADE_PREPEND(a, b) do { \ + APR_RING_PREPEND(&(a)->list, &(b)->list, apr_bucket, link); \ + APR_BRIGADE_CHECK_CONSISTENCY((a)); \ + } while (0) + +/** + * Insert a single bucket before a specified bucket + * @param a The bucket to insert before + * @param b The bucket to insert + */ +#define APR_BUCKET_INSERT_BEFORE(a, b) do { \ + apr_bucket *ap__a = (a), *ap__b = (b); \ + APR_RING_INSERT_BEFORE(ap__a, ap__b, link); \ + APR_BUCKET_CHECK_CONSISTENCY(ap__a); \ + } while (0) + +/** + * Insert a single bucket after a specified bucket + * @param a The bucket to insert after + * @param b The bucket to insert + */ +#define APR_BUCKET_INSERT_AFTER(a, b) do { \ + apr_bucket *ap__a = (a), *ap__b = (b); \ + APR_RING_INSERT_AFTER(ap__a, ap__b, link); \ + APR_BUCKET_CHECK_CONSISTENCY(ap__a); \ + } while (0) + +/** + * Get the next bucket in the list + * @param e The current bucket + * @return The next bucket + */ +#define APR_BUCKET_NEXT(e) APR_RING_NEXT((e), link) +/** + * Get the previous bucket in the list + * @param e The current bucket + * @return The previous bucket + */ +#define APR_BUCKET_PREV(e) APR_RING_PREV((e), link) + +/** + * Remove a bucket from its bucket brigade + * @param e The bucket to remove + */ +#define APR_BUCKET_REMOVE(e) APR_RING_REMOVE((e), link) + +/** + * Initialize a new bucket's prev/next pointers + * @param e The bucket to initialize + */ +#define APR_BUCKET_INIT(e) APR_RING_ELEM_INIT((e), link) + +/** + * Determine if a bucket contains metadata. An empty bucket is + * safe to arbitrarily remove if and only if this is false. + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_METADATA(e) ((e)->type->is_metadata) + +/** + * Determine if a bucket is a FLUSH bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_FLUSH(e) ((e)->type == &apr_bucket_type_flush) +/** + * Determine if a bucket is an EOS bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_EOS(e) ((e)->type == &apr_bucket_type_eos) +/** + * Determine if a bucket is a FILE bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_FILE(e) ((e)->type == &apr_bucket_type_file) +/** + * Determine if a bucket is a PIPE bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_PIPE(e) ((e)->type == &apr_bucket_type_pipe) +/** + * Determine if a bucket is a SOCKET bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_SOCKET(e) ((e)->type == &apr_bucket_type_socket) +/** + * Determine if a bucket is a HEAP bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_HEAP(e) ((e)->type == &apr_bucket_type_heap) +/** + * Determine if a bucket is a TRANSIENT bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_TRANSIENT(e) ((e)->type == &apr_bucket_type_transient) +/** + * Determine if a bucket is a IMMORTAL bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_IMMORTAL(e) ((e)->type == &apr_bucket_type_immortal) +#if APR_HAS_MMAP +/** + * Determine if a bucket is a MMAP bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_MMAP(e) ((e)->type == &apr_bucket_type_mmap) +#endif +/** + * Determine if a bucket is a POOL bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_POOL(e) ((e)->type == &apr_bucket_type_pool) + +/* + * General-purpose reference counting for the various bucket types. + * + * Any bucket type that keeps track of the resources it uses (i.e. + * most of them except for IMMORTAL, TRANSIENT, and EOS) needs to + * attach a reference count to the resource so that it can be freed + * when the last bucket that uses it goes away. Resource-sharing may + * occur because of bucket splits or buckets that refer to globally + * cached data. */ + +/** @see apr_bucket_refcount */ +typedef struct apr_bucket_refcount apr_bucket_refcount; +/** + * The structure used to manage the shared resource must start with an + * apr_bucket_refcount which is updated by the general-purpose refcount + * code. A pointer to the bucket-type-dependent private data structure + * can be cast to a pointer to an apr_bucket_refcount and vice versa. + */ +struct apr_bucket_refcount { + /** The number of references to this bucket */ + int refcount; +}; + +/* ***** Reference-counted bucket types ***** */ + +/** @see apr_bucket_heap */ +typedef struct apr_bucket_heap apr_bucket_heap; +/** + * A bucket referring to data allocated off the heap. + */ +struct apr_bucket_heap { + /** Number of buckets using this memory */ + apr_bucket_refcount refcount; + /** The start of the data actually allocated. This should never be + * modified, it is only used to free the bucket. + */ + char *base; + /** how much memory was allocated */ + apr_size_t alloc_len; + /** function to use to delete the data */ + void (*free_func)(void *data); +}; + +/** @see apr_bucket_pool */ +typedef struct apr_bucket_pool apr_bucket_pool; +/** + * A bucket referring to data allocated from a pool + */ +struct apr_bucket_pool { + /** The pool bucket must be able to be easily morphed to a heap + * bucket if the pool gets cleaned up before all references are + * destroyed. This apr_bucket_heap structure is populated automatically + * when the pool gets cleaned up, and subsequent calls to pool_read() + * will result in the apr_bucket in question being morphed into a + * regular heap bucket. (To avoid having to do many extra refcount + * manipulations and b->data manipulations, the apr_bucket_pool + * struct actually *contains* the apr_bucket_heap struct that it + * will become as its first element; the two share their + * apr_bucket_refcount members.) + */ + apr_bucket_heap heap; + /** The block of data actually allocated from the pool. + * Segments of this block are referenced by adjusting + * the start and length of the apr_bucket accordingly. + * This will be NULL after the pool gets cleaned up. + */ + const char *base; + /** The pool the data was allocated from. When the pool + * is cleaned up, this gets set to NULL as an indicator + * to pool_read() that the data is now on the heap and + * so it should morph the bucket into a regular heap + * bucket before continuing. + */ + apr_pool_t *pool; + /** The freelist this structure was allocated from, which is + * needed in the cleanup phase in order to allocate space on the heap + */ + apr_bucket_alloc_t *list; +}; + +#if APR_HAS_MMAP +/** @see apr_bucket_mmap */ +typedef struct apr_bucket_mmap apr_bucket_mmap; +/** + * A bucket referring to an mmap()ed file + */ +struct apr_bucket_mmap { + /** Number of buckets using this memory */ + apr_bucket_refcount refcount; + /** The mmap this sub_bucket refers to */ + apr_mmap_t *mmap; +}; +#endif + +/** @see apr_bucket_file */ +typedef struct apr_bucket_file apr_bucket_file; +/** + * A bucket referring to an file + */ +struct apr_bucket_file { + /** Number of buckets using this memory */ + apr_bucket_refcount refcount; + /** The file this bucket refers to */ + apr_file_t *fd; + /** The pool into which any needed structures should + * be created while reading from this file bucket */ + apr_pool_t *readpool; +#if APR_HAS_MMAP + /** Whether this bucket should be memory-mapped if + * a caller tries to read from it */ + int can_mmap; +#endif /* APR_HAS_MMAP */ + /** File read block size */ + apr_size_t read_size; +}; + +/** @see apr_bucket_structs */ +typedef union apr_bucket_structs apr_bucket_structs; +/** + * A union of all bucket structures so we know what + * the max size is. + */ +union apr_bucket_structs { + apr_bucket b; /**< Bucket */ + apr_bucket_heap heap; /**< Heap */ + apr_bucket_pool pool; /**< Pool */ +#if APR_HAS_MMAP + apr_bucket_mmap mmap; /**< MMap */ +#endif + apr_bucket_file file; /**< File */ +}; + +/** + * The amount that apr_bucket_alloc() should allocate in the common case. + * Note: this is twice as big as apr_bucket_structs to allow breathing + * room for third-party bucket types. + */ +#define APR_BUCKET_ALLOC_SIZE APR_ALIGN_DEFAULT(2*sizeof(apr_bucket_structs)) + +/* ***** Bucket Brigade Functions ***** */ +/** + * Create a new bucket brigade. The bucket brigade is originally empty. + * @param p The pool to associate with the brigade. Data is not allocated out + * of the pool, but a cleanup is registered. + * @param list The bucket allocator to use + * @return The empty bucket brigade + */ +APU_DECLARE(apr_bucket_brigade *) apr_brigade_create(apr_pool_t *p, + apr_bucket_alloc_t *list); + +/** + * destroy an entire bucket brigade. This includes destroying all of the + * buckets within the bucket brigade's bucket list. + * @param b The bucket brigade to destroy + */ +APU_DECLARE(apr_status_t) apr_brigade_destroy(apr_bucket_brigade *b); + +/** + * empty out an entire bucket brigade. This includes destroying all of the + * buckets within the bucket brigade's bucket list. This is similar to + * apr_brigade_destroy(), except that it does not deregister the brigade's + * pool cleanup function. + * @param data The bucket brigade to clean up + * @remark Generally, you should use apr_brigade_destroy(). This function + * can be useful in situations where you have a single brigade that + * you wish to reuse many times by destroying all of the buckets in + * the brigade and putting new buckets into it later. + */ +APU_DECLARE(apr_status_t) apr_brigade_cleanup(void *data); + +/** + * Move the buckets from the tail end of the existing brigade @a b into + * the brigade @a a. If @a a is NULL a new brigade is created. Buckets + * from @a e to the last bucket (inclusively) of brigade @a b are moved + * from @a b to the returned brigade @a a. + * + * @param b The brigade to split + * @param e The first bucket to move + * @param a The brigade which should be used for the result or NULL if + * a new brigade should be created. The brigade @a a will be + * cleared if it is not empty. + * @return The brigade supplied in @a a or a new one if @a a was NULL. + * @warning Note that this function allocates a new brigade if @a a is + * NULL so memory consumption should be carefully considered. + */ +APU_DECLARE(apr_bucket_brigade *) apr_brigade_split_ex(apr_bucket_brigade *b, + apr_bucket *e, + apr_bucket_brigade *a); + +/** + * Create a new bucket brigade and move the buckets from the tail end + * of an existing brigade into the new brigade. Buckets from + * @a e to the last bucket (inclusively) of brigade @a b + * are moved from @a b to the returned brigade. + * @param b The brigade to split + * @param e The first bucket to move + * @return The new brigade + * @warning Note that this function always allocates a new brigade + * so memory consumption should be carefully considered. + */ +APU_DECLARE(apr_bucket_brigade *) apr_brigade_split(apr_bucket_brigade *b, + apr_bucket *e); + +/** + * Partition a bucket brigade at a given offset (in bytes from the start of + * the brigade). This is useful whenever a filter wants to use known ranges + * of bytes from the brigade; the ranges can even overlap. + * @param b The brigade to partition + * @param point The offset at which to partition the brigade + * @param after_point Returns a pointer to the first bucket after the partition + * @return APR_SUCCESS on success, APR_INCOMPLETE if the contents of the + * brigade were shorter than @a point, or an error code. + * @remark if APR_INCOMPLETE is returned, @a after_point will be set to + * the brigade sentinel. + */ +APU_DECLARE(apr_status_t) apr_brigade_partition(apr_bucket_brigade *b, + apr_off_t point, + apr_bucket **after_point); + +/** + * Return the total length of the brigade. + * @param bb The brigade to compute the length of + * @param read_all Read unknown-length buckets to force a size + * @param length Returns the length of the brigade (up to the end, or up + * to a bucket read error), or -1 if the brigade has buckets + * of indeterminate length and read_all is 0. + */ +APU_DECLARE(apr_status_t) apr_brigade_length(apr_bucket_brigade *bb, + int read_all, + apr_off_t *length); + +/** + * Take a bucket brigade and store the data in a flat char* + * @param bb The bucket brigade to create the char* from + * @param c The char* to write into + * @param len The maximum length of the char array. On return, it is the + * actual length of the char array. + */ +APU_DECLARE(apr_status_t) apr_brigade_flatten(apr_bucket_brigade *bb, + char *c, + apr_size_t *len); + +/** + * Creates a pool-allocated string representing a flat bucket brigade + * @param bb The bucket brigade to create the char array from + * @param c On return, the allocated char array + * @param len On return, the length of the char array. + * @param pool The pool to allocate the string from. + */ +APU_DECLARE(apr_status_t) apr_brigade_pflatten(apr_bucket_brigade *bb, + char **c, + apr_size_t *len, + apr_pool_t *pool); + +/** + * Split a brigade to represent one LF line. + * @param bbOut The bucket brigade that will have the LF line appended to. + * @param bbIn The input bucket brigade to search for a LF-line. + * @param block The blocking mode to be used to split the line. + * @param maxbytes The maximum bytes to read. If this many bytes are seen + * without a LF, the brigade will contain a partial line. + */ +APU_DECLARE(apr_status_t) apr_brigade_split_line(apr_bucket_brigade *bbOut, + apr_bucket_brigade *bbIn, + apr_read_type_e block, + apr_off_t maxbytes); + +/** + * Create an iovec of the elements in a bucket_brigade... return number + * of elements used. This is useful for writing to a file or to the + * network efficiently. + * @param b The bucket brigade to create the iovec from + * @param vec The iovec to create + * @param nvec The number of elements in the iovec. On return, it is the + * number of iovec elements actually filled out. + */ +APU_DECLARE(apr_status_t) apr_brigade_to_iovec(apr_bucket_brigade *b, + struct iovec *vec, int *nvec); + +/** + * This function writes a list of strings into a bucket brigade. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param va A list of strings to add + * @return APR_SUCCESS or error code. + */ +APU_DECLARE(apr_status_t) apr_brigade_vputstrs(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, + va_list va); + +/** + * This function writes a string into a bucket brigade. + * + * The apr_brigade_write function attempts to be efficient with the + * handling of heap buckets. Regardless of the amount of data stored + * inside a heap bucket, heap buckets are a fixed size to promote their + * reuse. + * + * If an attempt is made to write a string to a brigade that already + * ends with a heap bucket, this function will attempt to pack the + * string into the remaining space in the previous heap bucket, before + * allocating a new heap bucket. + * + * This function always returns APR_SUCCESS, unless a flush function is + * passed, in which case the return value of the flush function will be + * returned if used. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param str The string to add + * @param nbyte The number of bytes to write + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_write(apr_bucket_brigade *b, + apr_brigade_flush flush, void *ctx, + const char *str, apr_size_t nbyte); + +/** + * This function writes multiple strings into a bucket brigade. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param vec The strings to add (address plus length for each) + * @param nvec The number of entries in iovec + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_writev(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, + const struct iovec *vec, + apr_size_t nvec); + +/** + * This function writes a string into a bucket brigade. + * @param bb The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param str The string to add + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_puts(apr_bucket_brigade *bb, + apr_brigade_flush flush, void *ctx, + const char *str); + +/** + * This function writes a character into a bucket brigade. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param c The character to add + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_putc(apr_bucket_brigade *b, + apr_brigade_flush flush, void *ctx, + const char c); + +/** + * This function writes an unspecified number of strings into a bucket brigade. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param ... The strings to add + * @return APR_SUCCESS or error code + */ +APU_DECLARE_NONSTD(apr_status_t) apr_brigade_putstrs(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, ...); + +/** + * Evaluate a printf and put the resulting string at the end + * of the bucket brigade. + * @param b The brigade to write to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param fmt The format of the string to write + * @param ... The arguments to fill out the format + * @return APR_SUCCESS or error code + */ +APU_DECLARE_NONSTD(apr_status_t) apr_brigade_printf(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, + const char *fmt, ...) + __attribute__((format(printf,4,5))); + +/** + * Evaluate a printf and put the resulting string at the end + * of the bucket brigade. + * @param b The brigade to write to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param fmt The format of the string to write + * @param va The arguments to fill out the format + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_vprintf(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, + const char *fmt, va_list va); + +/** + * Utility function to insert a file (or a segment of a file) onto the + * end of the brigade. The file is split into multiple buckets if it + * is larger than the maximum size which can be represented by a + * single bucket. + * @param bb the brigade to insert into + * @param f the file to insert + * @param start the offset of the start of the segment + * @param len the length of the segment of the file to insert + * @param p pool from which file buckets are allocated + * @return the last bucket inserted + */ +APU_DECLARE(apr_bucket *) apr_brigade_insert_file(apr_bucket_brigade *bb, + apr_file_t *f, + apr_off_t start, + apr_off_t len, + apr_pool_t *p); + + + +/* ***** Bucket freelist functions ***** */ +/** + * Create a bucket allocator. + * @param p This pool's underlying apr_allocator_t is used to allocate memory + * for the bucket allocator. When the pool is destroyed, the bucket + * allocator's cleanup routine will free all memory that has been + * allocated from it. + * @remark The reason the allocator gets its memory from the pool's + * apr_allocator_t rather than from the pool itself is because + * the bucket allocator will free large memory blocks back to the + * allocator when it's done with them, thereby preventing memory + * footprint growth that would occur if we allocated from the pool. + * @warning The allocator must never be used by more than one thread at a time. + */ +APU_DECLARE_NONSTD(apr_bucket_alloc_t *) apr_bucket_alloc_create(apr_pool_t *p); + +/** + * Create a bucket allocator. + * @param allocator This apr_allocator_t is used to allocate both the bucket + * allocator and all memory handed out by the bucket allocator. The + * caller is responsible for destroying the bucket allocator and the + * apr_allocator_t -- no automatic cleanups will happen. + * @warning The allocator must never be used by more than one thread at a time. + */ +APU_DECLARE_NONSTD(apr_bucket_alloc_t *) apr_bucket_alloc_create_ex(apr_allocator_t *allocator); + +/** + * Destroy a bucket allocator. + * @param list The allocator to be destroyed + */ +APU_DECLARE_NONSTD(void) apr_bucket_alloc_destroy(apr_bucket_alloc_t *list); + +/** + * Get the aligned size corresponding to the requested size, but minus the + * allocator(s) overhead such that the allocation would remain in the + * same boundary. + * @param list The allocator from which to the memory would be allocated. + * @param size The requested size. + * @return The corresponding aligned/floored size. + */ +APU_DECLARE_NONSTD(apr_size_t) apr_bucket_alloc_aligned_floor(apr_bucket_alloc_t *list, + apr_size_t size) + __attribute__((nonnull(1))); + +/** + * Allocate memory for use by the buckets. + * @param size The amount to allocate. + * @param list The allocator from which to allocate the memory. + */ +APU_DECLARE_NONSTD(void *) apr_bucket_alloc(apr_size_t size, apr_bucket_alloc_t *list); + +/** + * Free memory previously allocated with apr_bucket_alloc(). + * @param block The block of memory to be freed. + */ +APU_DECLARE_NONSTD(void) apr_bucket_free(void *block); + + +/* ***** Bucket Functions ***** */ +/** + * Free the resources used by a bucket. If multiple buckets refer to + * the same resource it is freed when the last one goes away. + * @see apr_bucket_delete() + * @param e The bucket to destroy + */ +#define apr_bucket_destroy(e) do { \ + (e)->type->destroy((e)->data); \ + (e)->free(e); \ + } while (0) + +/** + * Delete a bucket by removing it from its brigade (if any) and then + * destroying it. + * @remark This mainly acts as an aid in avoiding code verbosity. It is + * the preferred exact equivalent to: + *
+ *      APR_BUCKET_REMOVE(e);
+ *      apr_bucket_destroy(e);
+ * 
+ * @param e The bucket to delete + */ +#define apr_bucket_delete(e) do { \ + APR_BUCKET_REMOVE(e); \ + apr_bucket_destroy(e); \ + } while (0) + +/** + * Read some data from the bucket. + * + * The apr_bucket_read function returns a convenient amount of data + * from the bucket provided, writing the address and length of the + * data to the pointers provided by the caller. The function tries + * as hard as possible to avoid a memory copy. + * + * Buckets are expected to be a member of a brigade at the time they + * are read. + * + * In typical application code, buckets are read in a loop, and after + * each bucket is read and processed, it is moved or deleted from the + * brigade and the next bucket read. + * + * The definition of "convenient" depends on the type of bucket that + * is being read, and is decided by APR. In the case of memory based + * buckets such as heap and immortal buckets, a pointer will be + * returned to the location of the buffer containing the complete + * contents of the bucket. + * + * Some buckets, such as the socket bucket, might have no concept + * of length. If an attempt is made to read such a bucket, the + * apr_bucket_read function will read a convenient amount of data + * from the socket. The socket bucket is magically morphed into a + * heap bucket containing the just-read data, and a new socket bucket + * is inserted just after this heap bucket. + * + * To understand why apr_bucket_read might do this, consider the loop + * described above to read and process buckets. The current bucket + * is magically morphed into a heap bucket and returned to the caller. + * The caller processes the data, and deletes the heap bucket, moving + * onto the next bucket, the new socket bucket. This process repeats, + * giving the illusion of a bucket brigade that contains potentially + * infinite amounts of data. It is up to the caller to decide at what + * point to stop reading buckets. + * + * Some buckets, such as the file bucket, might have a fixed size, + * but be significantly larger than is practical to store in RAM in + * one go. As with the socket bucket, if an attempt is made to read + * from a file bucket, the file bucket is magically morphed into a + * heap bucket containing a convenient amount of data read from the + * current offset in the file. During the read, the offset will be + * moved forward on the file, and a new file bucket will be inserted + * directly after the current bucket representing the remainder of the + * file. If the heap bucket was large enough to store the whole + * remainder of the file, no more file buckets are inserted, and the + * file bucket will disappear completely. + * + * The pattern for reading buckets described above does create the + * illusion that the code is willing to swallow buckets that might be + * too large for the system to handle in one go. This however is just + * an illusion: APR will always ensure that large (file) or infinite + * (socket) buckets are broken into convenient bite sized heap buckets + * before data is returned to the caller. + * + * There is a potential gotcha to watch for: if buckets are read in a + * loop, and aren't deleted after being processed, the potentially large + * bucket will slowly be converted into RAM resident heap buckets. If + * the file is larger than available RAM, an out of memory condition + * could be caused if the application is not careful to manage this. + * + * @param e The bucket to read from + * @param str The location to store a pointer to the data in + * @param len The location to store the amount of data read + * @param block Whether the read function blocks + */ +#define apr_bucket_read(e,str,len,block) (e)->type->read(e, str, len, block) + +/** + * Setaside data so that stack data is not destroyed on returning from + * the function + * @param e The bucket to setaside + * @param p The pool to setaside into + */ +#define apr_bucket_setaside(e,p) (e)->type->setaside(e,p) + +/** + * Split one bucket in two at the point provided. + * + * Once split, the original bucket becomes the first of the two new buckets. + * + * (It is assumed that the bucket is a member of a brigade when this + * function is called). + * @param e The bucket to split + * @param point The offset to split the bucket at + */ +#define apr_bucket_split(e,point) (e)->type->split(e, point) + +/** + * Copy a bucket. + * @param e The bucket to copy + * @param c Returns a pointer to the new bucket + */ +#define apr_bucket_copy(e,c) (e)->type->copy(e, c) + +/* Bucket type handling */ + +/** + * This function simply returns APR_SUCCESS to denote that the bucket does + * not require anything to happen for its setaside() function. This is + * appropriate for buckets that have "immortal" data -- the data will live + * at least as long as the bucket. + * @param data The bucket to setaside + * @param pool The pool defining the desired lifetime of the bucket data + * @return APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_setaside_noop(apr_bucket *data, + apr_pool_t *pool); + +/** + * A place holder function that signifies that the setaside function was not + * implemented for this bucket + * @param data The bucket to setaside + * @param pool The pool defining the desired lifetime of the bucket data + * @return APR_ENOTIMPL + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_setaside_notimpl(apr_bucket *data, + apr_pool_t *pool); + +/** + * A place holder function that signifies that the split function was not + * implemented for this bucket + * @param data The bucket to split + * @param point The location to split the bucket + * @return APR_ENOTIMPL + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_split_notimpl(apr_bucket *data, + apr_size_t point); + +/** + * A place holder function that signifies that the copy function was not + * implemented for this bucket + * @param e The bucket to copy + * @param c Returns a pointer to the new bucket + * @return APR_ENOTIMPL + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_copy_notimpl(apr_bucket *e, + apr_bucket **c); + +/** + * A place holder function that signifies that this bucket does not need + * to do anything special to be destroyed. That's only the case for buckets + * that either have no data (metadata buckets) or buckets whose data pointer + * points to something that's not a bucket-type-specific structure, as with + * simple buckets where data points to a string and pipe buckets where data + * points directly to the apr_file_t. + * @param data The bucket data to destroy + */ +APU_DECLARE_NONSTD(void) apr_bucket_destroy_noop(void *data); + +/** + * There is no apr_bucket_destroy_notimpl, because destruction is required + * to be implemented (it could be a noop, but only if that makes sense for + * the bucket type) + */ + +/* There is no apr_bucket_read_notimpl, because it is a required function + */ + + +/* All of the bucket types implemented by the core */ +/** + * The flush bucket type. This signifies that all data should be flushed to + * the next filter. The flush bucket should be sent with the other buckets. + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_flush; +/** + * The EOS bucket type. This signifies that there will be no more data, ever. + * All filters MUST send all data to the next filter when they receive a + * bucket of this type + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_eos; +/** + * The FILE bucket type. This bucket represents a file on disk + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_file; +/** + * The HEAP bucket type. This bucket represents a data allocated from the + * heap. + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_heap; +#if APR_HAS_MMAP +/** + * The MMAP bucket type. This bucket represents an MMAP'ed file + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_mmap; +#endif +/** + * The POOL bucket type. This bucket represents a data that was allocated + * from a pool. IF this bucket is still available when the pool is cleared, + * the data is copied on to the heap. + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_pool; +/** + * The PIPE bucket type. This bucket represents a pipe to another program. + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_pipe; +/** + * The IMMORTAL bucket type. This bucket represents a segment of data that + * the creator is willing to take responsibility for. The core will do + * nothing with the data in an immortal bucket + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_immortal; +/** + * The TRANSIENT bucket type. This bucket represents a data allocated off + * the stack. When the setaside function is called, this data is copied on + * to the heap + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_transient; +/** + * The SOCKET bucket type. This bucket represents a socket to another machine + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_socket; + + +/* ***** Simple buckets ***** */ + +/** + * Split a simple bucket into two at the given point. Most non-reference + * counting buckets that allow multiple references to the same block of + * data (eg transient and immortal) will use this as their split function + * without any additional type-specific handling. + * @param b The bucket to be split + * @param point The offset of the first byte in the new bucket + * @return APR_EINVAL if the point is not within the bucket; + * APR_ENOMEM if allocation failed; + * or APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_simple_split(apr_bucket *b, + apr_size_t point); + +/** + * Copy a simple bucket. Most non-reference-counting buckets that allow + * multiple references to the same block of data (eg transient and immortal) + * will use this as their copy function without any additional type-specific + * handling. + * @param a The bucket to copy + * @param b Returns a pointer to the new bucket + * @return APR_ENOMEM if allocation failed; + * or APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_simple_copy(apr_bucket *a, + apr_bucket **b); + + +/* ***** Shared, reference-counted buckets ***** */ + +/** + * Initialize a bucket containing reference-counted data that may be + * shared. The caller must allocate the bucket if necessary and + * initialize its type-dependent fields, and allocate and initialize + * its own private data structure. This function should only be called + * by type-specific bucket creation functions. + * @param b The bucket to initialize + * @param data A pointer to the private data structure + * with the reference count at the start + * @param start The start of the data in the bucket + * relative to the private base pointer + * @param length The length of the data in the bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_shared_make(apr_bucket *b, void *data, + apr_off_t start, + apr_size_t length); + +/** + * Decrement the refcount of the data in the bucket. This function + * should only be called by type-specific bucket destruction functions. + * @param data The private data pointer from the bucket to be destroyed + * @return TRUE or FALSE; TRUE if the reference count is now + * zero, indicating that the shared resource itself can + * be destroyed by the caller. + */ +APU_DECLARE(int) apr_bucket_shared_destroy(void *data); + +/** + * Split a bucket into two at the given point, and adjust the refcount + * to the underlying data. Most reference-counting bucket types will + * be able to use this function as their split function without any + * additional type-specific handling. + * @param b The bucket to be split + * @param point The offset of the first byte in the new bucket + * @return APR_EINVAL if the point is not within the bucket; + * APR_ENOMEM if allocation failed; + * or APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_shared_split(apr_bucket *b, + apr_size_t point); + +/** + * Copy a refcounted bucket, incrementing the reference count. Most + * reference-counting bucket types will be able to use this function + * as their copy function without any additional type-specific handling. + * @param a The bucket to copy + * @param b Returns a pointer to the new bucket + * @return APR_ENOMEM if allocation failed; + or APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_shared_copy(apr_bucket *a, + apr_bucket **b); + + +/* ***** Functions to Create Buckets of varying types ***** */ +/* + * Each bucket type foo has two initialization functions: + * apr_bucket_foo_make which sets up some already-allocated memory as a + * bucket of type foo; and apr_bucket_foo_create which allocates memory + * for the bucket, calls apr_bucket_make_foo, and initializes the + * bucket's list pointers. The apr_bucket_foo_make functions are used + * inside the bucket code to change the type of buckets in place; + * other code should call apr_bucket_foo_create. All the initialization + * functions change nothing if they fail. + */ + +/** + * Create an End of Stream bucket. This indicates that there is no more data + * coming from down the filter stack. All filters should flush at this point. + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_eos_create(apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in an EOS bucket. This indicates that there is no + * more data coming from down the filter stack. All filters should flush at + * this point. + * @param b The bucket to make into an EOS bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_eos_make(apr_bucket *b); + +/** + * Create a flush bucket. This indicates that filters should flush their + * data. There is no guarantee that they will flush it, but this is the + * best we can do. + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_flush_create(apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a FLUSH bucket. This indicates that filters + * should flush their data. There is no guarantee that they will flush it, + * but this is the best we can do. + * @param b The bucket to make into a FLUSH bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_flush_make(apr_bucket *b); + +/** + * Create a bucket referring to long-lived data. + * @param buf The data to insert into the bucket + * @param nbyte The size of the data to insert. + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_immortal_create(const char *buf, + apr_size_t nbyte, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to long-lived data + * @param b The bucket to make into a IMMORTAL bucket + * @param buf The data to insert into the bucket + * @param nbyte The size of the data to insert. + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_immortal_make(apr_bucket *b, + const char *buf, + apr_size_t nbyte); + +/** + * Create a bucket referring to data on the stack. + * @param buf The data to insert into the bucket + * @param nbyte The size of the data to insert. + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_transient_create(const char *buf, + apr_size_t nbyte, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to stack data + * @param b The bucket to make into a TRANSIENT bucket + * @param buf The data to insert into the bucket + * @param nbyte The size of the data to insert. + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_transient_make(apr_bucket *b, + const char *buf, + apr_size_t nbyte); + +/** + * Create a bucket referring to memory on the heap. If the caller asks + * for the data to be copied, this function always allocates 4K of + * memory so that more data can be added to the bucket without + * requiring another allocation. Therefore not all the data may be put + * into the bucket. If copying is not requested then the bucket takes + * over responsibility for free()ing the memory. + * @param buf The buffer to insert into the bucket + * @param nbyte The size of the buffer to insert. + * @param free_func Function to use to free the data; NULL indicates that the + * bucket should make a copy of the data + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_heap_create(const char *buf, + apr_size_t nbyte, + void (*free_func)(void *data), + apr_bucket_alloc_t *list); +/** + * Make the bucket passed in a bucket refer to heap data + * @param b The bucket to make into a HEAP bucket + * @param buf The buffer to insert into the bucket + * @param nbyte The size of the buffer to insert. + * @param free_func Function to use to free the data; NULL indicates that the + * bucket should make a copy of the data + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_heap_make(apr_bucket *b, const char *buf, + apr_size_t nbyte, + void (*free_func)(void *data)); + +/** + * Create a bucket referring to memory allocated from a pool. + * + * @param buf The buffer to insert into the bucket + * @param length The number of bytes referred to by this bucket + * @param pool The pool the memory was allocated from + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_pool_create(const char *buf, + apr_size_t length, + apr_pool_t *pool, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to pool data + * @param b The bucket to make into a pool bucket + * @param buf The buffer to insert into the bucket + * @param length The number of bytes referred to by this bucket + * @param pool The pool the memory was allocated from + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_pool_make(apr_bucket *b, const char *buf, + apr_size_t length, + apr_pool_t *pool); + +#if APR_HAS_MMAP +/** + * Create a bucket referring to mmap()ed memory. + * @param mm The mmap to insert into the bucket + * @param start The offset of the first byte in the mmap + * that this bucket refers to + * @param length The number of bytes referred to by this bucket + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_mmap_create(apr_mmap_t *mm, + apr_off_t start, + apr_size_t length, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to an MMAP'ed file + * @param b The bucket to make into a MMAP bucket + * @param mm The mmap to insert into the bucket + * @param start The offset of the first byte in the mmap + * that this bucket refers to + * @param length The number of bytes referred to by this bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_mmap_make(apr_bucket *b, apr_mmap_t *mm, + apr_off_t start, + apr_size_t length); +#endif + +/** + * Create a bucket referring to a socket. + * @param thissock The socket to put in the bucket + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_socket_create(apr_socket_t *thissock, + apr_bucket_alloc_t *list); +/** + * Make the bucket passed in a bucket refer to a socket + * @param b The bucket to make into a SOCKET bucket + * @param thissock The socket to put in the bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_socket_make(apr_bucket *b, + apr_socket_t *thissock); + +/** + * Create a bucket referring to a pipe. + * @param thispipe The pipe to put in the bucket + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_pipe_create(apr_file_t *thispipe, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to a pipe + * @param b The bucket to make into a PIPE bucket + * @param thispipe The pipe to put in the bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_pipe_make(apr_bucket *b, + apr_file_t *thispipe); + +/** + * Create a bucket referring to a file. + * @param fd The file to put in the bucket + * @param offset The offset where the data of interest begins in the file + * @param len The amount of data in the file we are interested in + * @param p The pool into which any needed structures should be created + * while reading from this file bucket + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + * @remark If the file is truncated such that the segment of the file + * referenced by the bucket no longer exists, an attempt to read + * from the bucket will fail with APR_EOF. + * @remark apr_brigade_insert_file() should generally be used to + * insert files into brigades, since that function can correctly + * handle large file issues. + */ +APU_DECLARE(apr_bucket *) apr_bucket_file_create(apr_file_t *fd, + apr_off_t offset, + apr_size_t len, + apr_pool_t *p, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to a file + * @param b The bucket to make into a FILE bucket + * @param fd The file to put in the bucket + * @param offset The offset where the data of interest begins in the file + * @param len The amount of data in the file we are interested in + * @param p The pool into which any needed structures should be created + * while reading from this file bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_file_make(apr_bucket *b, apr_file_t *fd, + apr_off_t offset, + apr_size_t len, apr_pool_t *p); + +/** + * Enable or disable memory-mapping for a FILE bucket (default is enabled) + * @param b The bucket + * @param enabled Whether memory-mapping should be enabled + * @return APR_SUCCESS normally, or an error code if the operation fails + */ +APU_DECLARE(apr_status_t) apr_bucket_file_enable_mmap(apr_bucket *b, + int enabled); + +/** + * Set the size of the read buffer allocated by a FILE bucket (default + * is @a APR_BUCKET_BUFF_SIZE) + * memory-mapping is disabled only) + * @param b The bucket + * @param size Size of the allocated buffers + * @return APR_SUCCESS normally, or an error code if the operation fails + * @remark Relevant/used only when memory-mapping is disabled (@see + * apr_bucket_file_enable_mmap) + */ +APU_DECLARE(apr_status_t) apr_bucket_file_set_buf_size(apr_bucket *e, + apr_size_t size); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_BUCKETS_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_crypto.h b/c/dependencies/windows/apr/x64_debug/include/apr_crypto.h new file mode 100644 index 00000000..b90f3fec --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_crypto.h @@ -0,0 +1,507 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_CRYPTO_H +#define APR_CRYPTO_H + +#include "apu.h" +#include "apr_pools.h" +#include "apr_tables.h" +#include "apr_hash.h" +#include "apu_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_crypto.h + * @brief APR-UTIL Crypto library + */ +/** + * @defgroup APR_Util_Crypto Crypto routines + * @ingroup APR_Util + * @{ + */ + +#if APU_HAVE_CRYPTO + +#ifndef APU_CRYPTO_RECOMMENDED_DRIVER +#if APU_HAVE_COMMONCRYPTO +#define APU_CRYPTO_RECOMMENDED_DRIVER "commoncrypto" +#else +#if APU_HAVE_OPENSSL +#define APU_CRYPTO_RECOMMENDED_DRIVER "openssl" +#else +#if APU_HAVE_NSS +#define APU_CRYPTO_RECOMMENDED_DRIVER "nss" +#else +#if APU_HAVE_MSCNG +#define APU_CRYPTO_RECOMMENDED_DRIVER "mscng" +#else +#if APU_HAVE_MSCAPI +#define APU_CRYPTO_RECOMMENDED_DRIVER "mscapi" +#else +#endif +#endif +#endif +#endif +#endif +#endif + +/** + * Symmetric Key types understood by the library. + * + * NOTE: It is expected that this list will grow over time. + * + * Interoperability Matrix: + * + * The matrix is based on the testcrypto.c unit test, which attempts to + * test whether a simple encrypt/decrypt will succeed, as well as testing + * whether an encrypted string by one library can be decrypted by the + * others. + * + * Some libraries will successfully encrypt and decrypt their own data, + * but won't decrypt data from another library. It is hoped that over + * time these anomalies will be found and fixed, but until then it is + * recommended that ciphers are chosen that interoperate across platform. + * + * An X below means the test passes, it does not necessarily mean that + * encryption performed is correct or secure. Applications should stick + * to ciphers that pass the interoperablity tests on the right hand side + * of the table. + * + * Aligned data is data whose length is a multiple of the block size for + * the chosen cipher. Padded data is data that is not aligned by block + * size and must be padded by the crypto library. + * + * OpenSSL CommonCrypto NSS Interop + * Align Pad Align Pad Align Pad Align Pad + * 3DES_192/CBC X X X X X X X X + * 3DES_192/ECB X X X X + * AES_256/CBC X X X X X X X X + * AES_256/ECB X X X X X X + * AES_192/CBC X X X X X X + * AES_192/ECB X X X X X + * AES_128/CBC X X X X X X + * AES_128/ECB X X X X X + * + * Conclusion: for padded data, use 3DES_192/CBC or AES_256/CBC. For + * aligned data, use 3DES_192/CBC, AES_256/CBC or AES_256/ECB. + */ + +typedef enum +{ + APR_KEY_NONE, APR_KEY_3DES_192, /** 192 bit (3-Key) 3DES */ + APR_KEY_AES_128, /** 128 bit AES */ + APR_KEY_AES_192, /** 192 bit AES */ + APR_KEY_AES_256 +/** 256 bit AES */ +} apr_crypto_block_key_type_e; + +typedef enum +{ + APR_MODE_NONE, /** An error condition */ + APR_MODE_ECB, /** Electronic Code Book */ + APR_MODE_CBC +/** Cipher Block Chaining */ +} apr_crypto_block_key_mode_e; + +/* These are opaque structs. Instantiation is up to each backend */ +typedef struct apr_crypto_driver_t apr_crypto_driver_t; +typedef struct apr_crypto_t apr_crypto_t; +typedef struct apr_crypto_config_t apr_crypto_config_t; +typedef struct apr_crypto_key_t apr_crypto_key_t; +typedef struct apr_crypto_block_t apr_crypto_block_t; + +typedef struct apr_crypto_block_key_type_t { + apr_crypto_block_key_type_e type; + int keysize; + int blocksize; + int ivsize; +} apr_crypto_block_key_type_t; + +typedef struct apr_crypto_block_key_mode_t { + apr_crypto_block_key_mode_e mode; +} apr_crypto_block_key_mode_t; + +typedef struct apr_crypto_passphrase_t { + const char *pass; + apr_size_t passLen; + const unsigned char * salt; + apr_size_t saltLen; + int iterations; +} apr_crypto_passphrase_t; + +typedef struct apr_crypto_secret_t { + const unsigned char *secret; + apr_size_t secretLen; +} apr_crypto_secret_t; + +typedef enum { + /** Key is derived from a passphrase */ + APR_CRYPTO_KTYPE_PASSPHRASE = 1, + /** Key is derived from a raw key */ + APR_CRYPTO_KTYPE_SECRET = 2, +} apr_crypto_key_type; + +typedef struct apr_crypto_key_rec_t { + apr_crypto_key_type ktype; + apr_crypto_block_key_type_e type; + apr_crypto_block_key_mode_e mode; + int pad; + union { + apr_crypto_passphrase_t passphrase; + apr_crypto_secret_t secret; + } k; +} apr_crypto_key_rec_t; + +/** + * @brief Perform once-only initialisation. Call once only. + * + * @param pool - pool to register any shutdown cleanups, etc + * @return APR_NOTIMPL in case of no crypto support. + */ +APU_DECLARE(apr_status_t) apr_crypto_init(apr_pool_t *pool); + +/** + * @brief Zero out the buffer provided when the pool is cleaned up. + * + * @param pool - pool to register the cleanup + * @param buffer - buffer to zero out + * @param size - size of the buffer to zero out + */ +APU_DECLARE(apr_status_t) apr_crypto_clear(apr_pool_t *pool, void *buffer, + apr_size_t size); + +/** + * @brief Always zero out the buffer provided, without being optimized out by + * the compiler. + * + * @param buffer - buffer to zero out + * @param size - size of the buffer to zero out + */ +APU_DECLARE(apr_status_t) apr_crypto_memzero(void *buffer, apr_size_t size); + +/** + * @brief Timing attacks safe buffers comparison, where the executing time does + * not depend on the bytes compared but solely on the number of bytes. + * + * @param buf1 - first buffer to compare + * @param buf2 - second buffer to compare + * @param size - size of the buffers to compare + * @return 1 if the buffers are equals, 0 otherwise. + */ +APU_DECLARE(int) apr_crypto_equals(const void *buf1, const void *buf2, + apr_size_t size); + +/** + * @brief Get the driver struct for a name + * + * @param driver - pointer to driver struct. + * @param name - driver name + * @param params - array of initialisation parameters + * @param result - result and error message on failure + * @param pool - (process) pool to register cleanup + * @return APR_SUCCESS for success + * @return APR_ENOTIMPL for no driver (when DSO not enabled) + * @return APR_EDSOOPEN if DSO driver file can't be opened + * @return APR_ESYMNOTFOUND if the driver file doesn't contain a driver + * @remarks NSS: the params can have "dir", "key3", "cert7" and "secmod" + * keys, each followed by an equal sign and a value. Such key/value pairs can + * be delimited by space or tab. If the value contains a space, surround the + * whole key value pair in quotes: "dir=My Directory". + * @remarks OpenSSL: currently no params are supported. + */ +APU_DECLARE(apr_status_t) apr_crypto_get_driver( + const apr_crypto_driver_t **driver, + const char *name, const char *params, const apu_err_t **result, + apr_pool_t *pool); + +/** + * @brief Return the name of the driver. + * + * @param driver - The driver in use. + * @return The name of the driver. + */ +APU_DECLARE(const char *) apr_crypto_driver_name( + const apr_crypto_driver_t *driver); + +/** + * @brief Get the result of the last operation on a context. If the result + * is NULL, the operation was successful. + * @param result - the result structure + * @param f - context pointer + * @return APR_SUCCESS for success + */ +APU_DECLARE(apr_status_t) apr_crypto_error(const apu_err_t **result, + const apr_crypto_t *f); + +/** + * @brief Create a context for supporting encryption. Keys, certificates, + * algorithms and other parameters will be set per context. More than + * one context can be created at one time. A cleanup will be automatically + * registered with the given pool to guarantee a graceful shutdown. + * @param f - context pointer will be written here + * @param driver - driver to use + * @param params - array of key parameters + * @param pool - process pool + * @return APR_ENOENGINE when the engine specified does not exist. APR_EINITENGINE + * if the engine cannot be initialised. + * @remarks NSS: currently no params are supported. + * @remarks OpenSSL: the params can have "engine" as a key, followed by an equal + * sign and a value. + */ +APU_DECLARE(apr_status_t) apr_crypto_make(apr_crypto_t **f, + const apr_crypto_driver_t *driver, const char *params, + apr_pool_t *pool); + +/** + * @brief Get a hash table of key types, keyed by the name of the type against + * a pointer to apr_crypto_block_key_type_t, which in turn begins with an + * integer. + * + * @param types - hashtable of key types keyed to constants. + * @param f - encryption context + * @return APR_SUCCESS for success + */ +APU_DECLARE(apr_status_t) apr_crypto_get_block_key_types(apr_hash_t **types, + const apr_crypto_t *f); + +/** + * @brief Get a hash table of key modes, keyed by the name of the mode against + * a pointer to apr_crypto_block_key_mode_t, which in turn begins with an + * integer. + * + * @param modes - hashtable of key modes keyed to constants. + * @param f - encryption context + * @return APR_SUCCESS for success + */ +APU_DECLARE(apr_status_t) apr_crypto_get_block_key_modes(apr_hash_t **modes, + const apr_crypto_t *f); + +/** + * @brief Create a key from the provided secret or passphrase. The key is cleaned + * up when the context is cleaned, and may be reused with multiple encryption + * or decryption operations. + * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If + * *key is not NULL, *key must point at a previously created structure. + * @param key The key returned, see note. + * @param rec The key record, from which the key will be derived. + * @param f The context to use. + * @param p The pool to use. + * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend + * error occurred while generating the key. APR_ENOCIPHER if the type or mode + * is not supported by the particular backend. APR_EKEYTYPE if the key type is + * not known. APR_EPADDING if padding was requested but is not supported. + * APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_key(apr_crypto_key_t **key, + const apr_crypto_key_rec_t *rec, const apr_crypto_t *f, apr_pool_t *p); + +/** + * @brief Create a key from the given passphrase. By default, the PBKDF2 + * algorithm is used to generate the key from the passphrase. It is expected + * that the same pass phrase will generate the same key, regardless of the + * backend crypto platform used. The key is cleaned up when the context + * is cleaned, and may be reused with multiple encryption or decryption + * operations. + * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If + * *key is not NULL, *key must point at a previously created structure. + * @param key The key returned, see note. + * @param ivSize The size of the initialisation vector will be returned, based + * on whether an IV is relevant for this type of crypto. + * @param pass The passphrase to use. + * @param passLen The passphrase length in bytes + * @param salt The salt to use. + * @param saltLen The salt length in bytes + * @param type 3DES_192, AES_128, AES_192, AES_256. + * @param mode Electronic Code Book / Cipher Block Chaining. + * @param doPad Pad if necessary. + * @param iterations Number of iterations to use in algorithm + * @param f The context to use. + * @param p The pool to use. + * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend + * error occurred while generating the key. APR_ENOCIPHER if the type or mode + * is not supported by the particular backend. APR_EKEYTYPE if the key type is + * not known. APR_EPADDING if padding was requested but is not supported. + * APR_ENOTIMPL if not implemented. + * @deprecated Replaced by apr_crypto_key(). + */ +APU_DECLARE(apr_status_t) apr_crypto_passphrase(apr_crypto_key_t **key, + apr_size_t *ivSize, const char *pass, apr_size_t passLen, + const unsigned char * salt, apr_size_t saltLen, + const apr_crypto_block_key_type_e type, + const apr_crypto_block_key_mode_e mode, const int doPad, + const int iterations, const apr_crypto_t *f, apr_pool_t *p); + +/** + * @brief Initialise a context for encrypting arbitrary data using the given key. + * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If + * *ctx is not NULL, *ctx must point at a previously created structure. + * @param ctx The block context returned, see note. + * @param iv Optional initialisation vector. If the buffer pointed to is NULL, + * an IV will be created at random, in space allocated from the pool. + * If the buffer pointed to is not NULL, the IV in the buffer will be + * used. + * @param key The key structure to use. + * @param blockSize The block size of the cipher. + * @param p The pool to use. + * @return Returns APR_ENOIV if an initialisation vector is required but not specified. + * Returns APR_EINIT if the backend failed to initialise the context. Returns + * APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_encrypt_init( + apr_crypto_block_t **ctx, const unsigned char **iv, + const apr_crypto_key_t *key, apr_size_t *blockSize, apr_pool_t *p); + +/** + * @brief Encrypt data provided by in, write it to out. + * @note The number of bytes written will be written to outlen. If + * out is NULL, outlen will contain the maximum size of the + * buffer needed to hold the data, including any data + * generated by apr_crypto_block_encrypt_finish below. If *out points + * to NULL, a buffer sufficiently large will be created from + * the pool provided. If *out points to a not-NULL value, this + * value will be used as a buffer instead. + * @param out Address of a buffer to which data will be written, + * see note. + * @param outlen Length of the output will be written here. + * @param in Address of the buffer to read. + * @param inlen Length of the buffer to read. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if + * not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_encrypt(unsigned char **out, + apr_size_t *outlen, const unsigned char *in, apr_size_t inlen, + apr_crypto_block_t *ctx); + +/** + * @brief Encrypt final data block, write it to out. + * @note If necessary the final block will be written out after being + * padded. Typically the final block will be written to the + * same buffer used by apr_crypto_block_encrypt, offset by the + * number of bytes returned as actually written by the + * apr_crypto_block_encrypt() call. After this call, the context + * is cleaned and can be reused by apr_crypto_block_encrypt_init(). + * @param out Address of a buffer to which data will be written. This + * buffer must already exist, and is usually the same + * buffer used by apr_evp_crypt(). See note. + * @param outlen Length of the output will be written here. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. + * @return APR_EPADDING if padding was enabled and the block was incorrectly + * formatted. + * @return APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_encrypt_finish(unsigned char *out, + apr_size_t *outlen, apr_crypto_block_t *ctx); + +/** + * @brief Initialise a context for decrypting arbitrary data using the given key. + * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If + * *ctx is not NULL, *ctx must point at a previously created structure. + * @param ctx The block context returned, see note. + * @param blockSize The block size of the cipher. + * @param iv Optional initialisation vector. + * @param key The key structure to use. + * @param p The pool to use. + * @return Returns APR_ENOIV if an initialisation vector is required but not specified. + * Returns APR_EINIT if the backend failed to initialise the context. Returns + * APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_decrypt_init( + apr_crypto_block_t **ctx, apr_size_t *blockSize, + const unsigned char *iv, const apr_crypto_key_t *key, apr_pool_t *p); + +/** + * @brief Decrypt data provided by in, write it to out. + * @note The number of bytes written will be written to outlen. If + * out is NULL, outlen will contain the maximum size of the + * buffer needed to hold the data, including any data + * generated by apr_crypto_block_decrypt_finish below. If *out points + * to NULL, a buffer sufficiently large will be created from + * the pool provided. If *out points to a not-NULL value, this + * value will be used as a buffer instead. + * @param out Address of a buffer to which data will be written, + * see note. + * @param outlen Length of the output will be written here. + * @param in Address of the buffer to read. + * @param inlen Length of the buffer to read. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if + * not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_decrypt(unsigned char **out, + apr_size_t *outlen, const unsigned char *in, apr_size_t inlen, + apr_crypto_block_t *ctx); + +/** + * @brief Decrypt final data block, write it to out. + * @note If necessary the final block will be written out after being + * padded. Typically the final block will be written to the + * same buffer used by apr_crypto_block_decrypt, offset by the + * number of bytes returned as actually written by the + * apr_crypto_block_decrypt() call. After this call, the context + * is cleaned and can be reused by apr_crypto_block_decrypt_init(). + * @param out Address of a buffer to which data will be written. This + * buffer must already exist, and is usually the same + * buffer used by apr_evp_crypt(). See note. + * @param outlen Length of the output will be written here. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. + * @return APR_EPADDING if padding was enabled and the block was incorrectly + * formatted. + * @return APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_decrypt_finish(unsigned char *out, + apr_size_t *outlen, apr_crypto_block_t *ctx); + +/** + * @brief Clean encryption / decryption context. + * @note After cleanup, a context is free to be reused if necessary. + * @param ctx The block context to use. + * @return Returns APR_ENOTIMPL if not supported. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_cleanup(apr_crypto_block_t *ctx); + +/** + * @brief Clean encryption / decryption context. + * @note After cleanup, a context is free to be reused if necessary. + * @param f The context to use. + * @return Returns APR_ENOTIMPL if not supported. + */ +APU_DECLARE(apr_status_t) apr_crypto_cleanup(apr_crypto_t *f); + +/** + * @brief Shutdown the crypto library. + * @note After shutdown, it is expected that the init function can be called again. + * @param driver - driver to use + * @return Returns APR_ENOTIMPL if not supported. + */ +APU_DECLARE(apr_status_t) apr_crypto_shutdown( + const apr_crypto_driver_t *driver); + +#endif /* APU_HAVE_CRYPTO */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_cstr.h b/c/dependencies/windows/apr/x64_debug/include/apr_cstr.h new file mode 100644 index 00000000..3f1b1a09 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_cstr.h @@ -0,0 +1,292 @@ +/* ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * ==================================================================== + */ + +/** + * @file apr_cstr.h + * @brief C string goodies. + */ + +#ifndef APR_CSTR_H +#define APR_CSTR_H + +#include /* for apr_size_t */ +#include /* for apr_pool_t */ +#include /* for apr_array_header_t */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_cstr C (POSIX) locale string functions + * @ingroup apr_strings + * + * The apr_cstr_* functions provide traditional C char * string text handling, + * and notabilty they treat all text in the C (a.k.a. POSIX) locale using the + * minimal POSIX character set, represented in either ASCII or a corresponding + * EBCDIC subset. + * + * Character values outside of that set are treated as opaque bytes, and all + * multi-byte character sequences are handled as individual distinct octets. + * + * Multi-byte characters sequences whose octets fall in the ASCII range cause + * unexpected results, such as in the ISO-2022-JP code page where ASCII octets + * occur within both shift-state and multibyte sequences. + * + * In the case of the UTF-8 encoding, all multibyte characters all fall outside + * of the C/POSIX range of characters, so these functions are generally safe + * to use on UTF-8 strings. The programmer must be aware that each octet may + * not represent a distinct printable character in such encodings. + * + * The standard C99/POSIX string functions, rather than apr_cstr, should be + * used in all cases where the current locale and encoding of the text is + * significant. + * @{ + */ + + +/** Divide @a input into substrings, interpreting any char from @a sep + * as a token separator. + * + * Return an array of copies of those substrings (plain const char*), + * allocating both the array and the copies in @a pool. + * + * None of the elements added to the array contain any of the + * characters in @a sep_chars, and none of the new elements are empty + * (thus, it is possible that the returned array will have length + * zero). + * + * If @a chop_whitespace is TRUE, then remove leading and trailing + * whitespace from the returned strings. + * + * @since New in 1.6 + */ +APR_DECLARE(apr_array_header_t *) apr_cstr_split(const char *input, + const char *sep_chars, + int chop_whitespace, + apr_pool_t *pool); + +/** Like apr_cstr_split(), but append to existing @a array instead of + * creating a new one. Allocate the copied substrings in @a pool + * (i.e., caller decides whether or not to pass @a array->pool as @a pool). + * + * @since New in 1.6 + */ +APR_DECLARE(void) apr_cstr_split_append(apr_array_header_t *array, + const char *input, + const char *sep_chars, + int chop_whitespace, + apr_pool_t *pool); + + +/** Return @c TRUE iff @a str matches any of the elements of @a list, a list + * of zero or more glob patterns. + * + * @since New in 1.6 + */ +APR_DECLARE(int) apr_cstr_match_glob_list(const char *str, + const apr_array_header_t *list); + +/** Return @c TRUE iff @a str exactly matches any of the elements of @a list. + * + * @since New in 1.6 + */ +APR_DECLARE(int) apr_cstr_match_list(const char *str, + const apr_array_header_t *list); + +/** + * Get the next token from @a *str interpreting any char from @a sep as a + * token separator. Separators at the beginning of @a str will be skipped. + * Returns a pointer to the beginning of the first token in @a *str or NULL + * if no token is left. Modifies @a str such that the next call will return + * the next token. + * + * @note The content of @a *str may be modified by this function. + * + * @since New in 1.6. + */ +APR_DECLARE(char *) apr_cstr_tokenize(const char *sep, char **str); + +/** + * Return the number of line breaks in @a msg, allowing any kind of newline + * termination (CR, LF, CRLF, or LFCR), even inconsistent. + * + * @since New in 1.6. + */ +APR_DECLARE(int) apr_cstr_count_newlines(const char *msg); + +#if 0 /* XXX: stringbuf logic is not present in APR */ +/** + * Return a cstring which is the concatenation of @a strings (an array + * of char *) each followed by @a separator (that is, @a separator + * will also end the resulting string). Allocate the result in @a pool. + * If @a strings is empty, then return the empty string. + * + * @since New in 1.6. + */ +APR_DECLARE(char *) apr_cstr_join(const apr_array_header_t *strings, + const char *separator, + apr_pool_t *pool); +#endif + +/** + * Perform a case-insensitive comparison of two strings @a atr1 and @a atr2, + * treating upper and lower case values of the 26 standard C/POSIX alphabetic + * characters as equivalent. Extended latin characters outside of this set + * are treated as unique octets, irrespective of the current locale. + * + * Returns in integer greater than, equal to, or less than 0, + * according to whether @a str1 is considered greater than, equal to, + * or less than @a str2. + * + * @since New in 1.6. + */ +APR_DECLARE(int) apr_cstr_casecmp(const char *str1, const char *str2); + +/** + * Perform a case-insensitive comparison of two strings @a atr1 and @a atr2, + * treating upper and lower case values of the 26 standard C/POSIX alphabetic + * characters as equivalent. Extended latin characters outside of this set + * are treated as unique octets, irrespective of the current locale. + * + * Returns in integer greater than, equal to, or less than 0, + * according to whether @a str1 is considered greater than, equal to, + * or less than @a str2. + * + * @since New in 1.6. + */ +APR_DECLARE(int) apr_cstr_casecmpn(const char *str1, + const char *str2, + apr_size_t n); + +/** + * Parse the C string @a str into a 64 bit number, and return it in @a *n. + * Assume that the number is represented in base @a base. + * Raise an error if conversion fails (e.g. due to overflow), or if the + * converted number is smaller than @a minval or larger than @a maxval. + * + * Leading whitespace in @a str is skipped in a locale-dependent way. + * After that, the string may contain an optional '+' (positive, default) + * or '-' (negative) character, followed by an optional '0x' prefix if + * @a base is 0 or 16, followed by numeric digits appropriate for the base. + * If there are any more characters after the numeric digits, an error is + * returned. + * + * If @a base is zero, then a leading '0x' or '0X' prefix means hexadecimal, + * else a leading '0' means octal (implemented, though not documented, in + * apr_strtoi64() in APR 0.9.0 through 1.5.0), else use base ten. + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_strtoi64(apr_int64_t *n, const char *str, + apr_int64_t minval, + apr_int64_t maxval, + int base); + +/** + * Parse the C string @a str into a 64 bit number, and return it in @a *n. + * Assume that the number is represented in base 10. + * Raise an error if conversion fails (e.g. due to overflow). + * + * The behaviour otherwise is as described for apr_cstr_strtoi64(). + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_atoi64(apr_int64_t *n, const char *str); + +/** + * Parse the C string @a str into a 32 bit number, and return it in @a *n. + * Assume that the number is represented in base 10. + * Raise an error if conversion fails (e.g. due to overflow). + * + * The behaviour otherwise is as described for apr_cstr_strtoi64(). + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_atoi(int *n, const char *str); + +/** + * Parse the C string @a str into an unsigned 64 bit number, and return + * it in @a *n. Assume that the number is represented in base @a base. + * Raise an error if conversion fails (e.g. due to overflow), or if the + * converted number is smaller than @a minval or larger than @a maxval. + * + * Leading whitespace in @a str is skipped in a locale-dependent way. + * After that, the string may contain an optional '+' (positive, default) + * or '-' (negative) character, followed by an optional '0x' prefix if + * @a base is 0 or 16, followed by numeric digits appropriate for the base. + * If there are any more characters after the numeric digits, an error is + * returned. + * + * If @a base is zero, then a leading '0x' or '0X' prefix means hexadecimal, + * else a leading '0' means octal (as implemented, though not documented, in + * apr_strtoi64(), else use base ten. + * + * @warning The implementation returns APR_ERANGE if the parsed number + * is greater than APR_INT64_MAX, even if it is not greater than @a maxval. + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_strtoui64(apr_uint64_t *n, const char *str, + apr_uint64_t minval, + apr_uint64_t maxval, + int base); + +/** + * Parse the C string @a str into an unsigned 64 bit number, and return + * it in @a *n. Assume that the number is represented in base 10. + * Raise an error if conversion fails (e.g. due to overflow). + * + * The behaviour otherwise is as described for apr_cstr_strtoui64(), + * including the upper limit of APR_INT64_MAX. + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_atoui64(apr_uint64_t *n, const char *str); + +/** + * Parse the C string @a str into an unsigned 32 bit number, and return + * it in @a *n. Assume that the number is represented in base 10. + * Raise an error if conversion fails (e.g. due to overflow). + * + * The behaviour otherwise is as described for apr_cstr_strtoui64(), + * including the upper limit of APR_INT64_MAX. + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_atoui(unsigned int *n, const char *str); + +/** + * Skip the common prefix @a prefix from the C string @a str, and return + * a pointer to the next character after the prefix. + * Return @c NULL if @a str does not start with @a prefix. + * + * @since New in 1.6. + */ +APR_DECLARE(const char *) apr_cstr_skip_prefix(const char *str, + const char *prefix); + +/** @} */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* SVN_STRING_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_date.h b/c/dependencies/windows/apr/x64_debug/include/apr_date.h new file mode 100644 index 00000000..b098b542 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_date.h @@ -0,0 +1,106 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_DATE_H +#define APR_DATE_H + +/** + * @file apr_date.h + * @brief APR-UTIL date routines + */ + +/** + * @defgroup APR_Util_Date Date routines + * @ingroup APR_Util + * @{ + */ + +/* + * apr_date.h: prototypes for date parsing utility routines + */ + +#include "apu.h" +#include "apr_time.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** A bad date. */ +#define APR_DATE_BAD ((apr_time_t)0) + +/** + * Compare a string to a mask + * @param data The string to compare + * @param mask Mask characters (arbitrary maximum is 256 characters): + *
+ *   '\@' - uppercase letter
+ *   '\$' - lowercase letter
+ *   '\&' - hex digit
+ *   '#' - digit
+ *   '~' - digit or space
+ *   '*' - swallow remaining characters
+ * 
+ * @remark The mask tests for an exact match for any other character + * @return 1 if the string matches, 0 otherwise + */ +APU_DECLARE(int) apr_date_checkmask(const char *data, const char *mask); + +/** + * Parses an HTTP date in one of three standard forms: + *
+ *     Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
+ *     Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
+ *     Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format
+ * 
+ * @param date The date in one of the three formats above + * @return the apr_time_t number of microseconds since 1 Jan 1970 GMT, or + * 0 if this would be out of range or if the date is invalid. + */ +APU_DECLARE(apr_time_t) apr_date_parse_http(const char *date); + +/** + * Parses a string resembling an RFC 822 date. This is meant to be + * leinent in its parsing of dates. Hence, this will parse a wider + * range of dates than apr_date_parse_http. + * + * The prominent mailer (or poster, if mailer is unknown) that has + * been seen in the wild is included for the unknown formats. + *
+ *     Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
+ *     Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
+ *     Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format
+ *     Sun, 6 Nov 1994 08:49:37 GMT   ; RFC 822, updated by RFC 1123
+ *     Sun, 06 Nov 94 08:49:37 GMT    ; RFC 822
+ *     Sun, 6 Nov 94 08:49:37 GMT     ; RFC 822
+ *     Sun, 06 Nov 94 08:49 GMT       ; Unknown [drtr\@ast.cam.ac.uk] 
+ *     Sun, 6 Nov 94 08:49 GMT        ; Unknown [drtr\@ast.cam.ac.uk]
+ *     Sun, 06 Nov 94 8:49:37 GMT     ; Unknown [Elm 70.85]
+ *     Sun, 6 Nov 94 8:49:37 GMT      ; Unknown [Elm 70.85] 
+ * 
+ * + * @param date The date in one of the formats above + * @return the apr_time_t number of microseconds since 1 Jan 1970 GMT, or + * 0 if this would be out of range or if the date is invalid. + */ +APU_DECLARE(apr_time_t) apr_date_parse_rfc(const char *date); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_DATE_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_dbd.h b/c/dependencies/windows/apr/x64_debug/include/apr_dbd.h new file mode 100644 index 00000000..9912612b --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_dbd.h @@ -0,0 +1,549 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* Overview of what this is and does: + * http://www.apache.org/~niq/dbd.html + */ + +#ifndef APR_DBD_H +#define APR_DBD_H + +#include "apu.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_dbd.h + * @brief APR-UTIL DBD library + */ +/** + * @defgroup APR_Util_DBD DBD routines + * @ingroup APR_Util + * @{ + */ + +/** + * Mapping of C to SQL types, used for prepared statements. + * @remarks + * For apr_dbd_p[v]query/select functions, in and out parameters are always + * const char * (i.e. regular nul terminated strings). LOB types are passed + * with four (4) arguments: payload, length, table and column, all as const + * char *, where table and column are reserved for future use by Oracle. + * @remarks + * For apr_dbd_p[v]bquery/select functions, in and out parameters are + * described next to each enumeration constant and are generally native binary + * types or some APR data type. LOB types are passed with four (4) arguments: + * payload (char*), length (apr_size_t*), table (char*) and column (char*). + * Table and column are reserved for future use by Oracle. + */ +typedef enum { + APR_DBD_TYPE_NONE, + APR_DBD_TYPE_TINY, /**< \%hhd : in, out: char* */ + APR_DBD_TYPE_UTINY, /**< \%hhu : in, out: unsigned char* */ + APR_DBD_TYPE_SHORT, /**< \%hd : in, out: short* */ + APR_DBD_TYPE_USHORT, /**< \%hu : in, out: unsigned short* */ + APR_DBD_TYPE_INT, /**< \%d : in, out: int* */ + APR_DBD_TYPE_UINT, /**< \%u : in, out: unsigned int* */ + APR_DBD_TYPE_LONG, /**< \%ld : in, out: long* */ + APR_DBD_TYPE_ULONG, /**< \%lu : in, out: unsigned long* */ + APR_DBD_TYPE_LONGLONG, /**< \%lld : in, out: apr_int64_t* */ + APR_DBD_TYPE_ULONGLONG, /**< \%llu : in, out: apr_uint64_t* */ + APR_DBD_TYPE_FLOAT, /**< \%f : in, out: float* */ + APR_DBD_TYPE_DOUBLE, /**< \%lf : in, out: double* */ + APR_DBD_TYPE_STRING, /**< \%s : in: char*, out: char** */ + APR_DBD_TYPE_TEXT, /**< \%pDt : in: char*, out: char** */ + APR_DBD_TYPE_TIME, /**< \%pDi : in: char*, out: char** */ + APR_DBD_TYPE_DATE, /**< \%pDd : in: char*, out: char** */ + APR_DBD_TYPE_DATETIME, /**< \%pDa : in: char*, out: char** */ + APR_DBD_TYPE_TIMESTAMP, /**< \%pDs : in: char*, out: char** */ + APR_DBD_TYPE_ZTIMESTAMP, /**< \%pDz : in: char*, out: char** */ + APR_DBD_TYPE_BLOB, /**< \%pDb : in: char* apr_size_t* char* char*, out: apr_bucket_brigade* */ + APR_DBD_TYPE_CLOB, /**< \%pDc : in: char* apr_size_t* char* char*, out: apr_bucket_brigade* */ + APR_DBD_TYPE_NULL /**< \%pDn : in: void*, out: void** */ +} apr_dbd_type_e; + +/* These are opaque structs. Instantiation is up to each backend */ +typedef struct apr_dbd_driver_t apr_dbd_driver_t; +typedef struct apr_dbd_t apr_dbd_t; +typedef struct apr_dbd_transaction_t apr_dbd_transaction_t; +typedef struct apr_dbd_results_t apr_dbd_results_t; +typedef struct apr_dbd_row_t apr_dbd_row_t; +typedef struct apr_dbd_prepared_t apr_dbd_prepared_t; + +/** apr_dbd_init: perform once-only initialisation. Call once only. + * + * @param pool - pool to register any shutdown cleanups, etc + */ +APU_DECLARE(apr_status_t) apr_dbd_init(apr_pool_t *pool); + +/** apr_dbd_get_driver: get the driver struct for a name + * + * @param pool - (process) pool to register cleanup + * @param name - driver name + * @param driver - pointer to driver struct. + * @return APR_SUCCESS for success + * @return APR_ENOTIMPL for no driver (when DSO not enabled) + * @return APR_EDSOOPEN if DSO driver file can't be opened + * @return APR_ESYMNOTFOUND if the driver file doesn't contain a driver + */ +APU_DECLARE(apr_status_t) apr_dbd_get_driver(apr_pool_t *pool, const char *name, + const apr_dbd_driver_t **driver); + +/** apr_dbd_open_ex: open a connection to a backend + * + * @param driver - driver struct. + * @param pool - working pool + * @param params - arguments to driver (implementation-dependent) + * @param handle - pointer to handle to return + * @param error - descriptive error. + * @return APR_SUCCESS for success + * @return APR_EGENERAL if driver exists but connection failed + * @remarks PostgreSQL: the params is passed directly to the PQconnectdb() + * function (check PostgreSQL documentation for more details on the syntax). + * @remarks SQLite2: the params is split on a colon, with the first part used + * as the filename and second part converted to an integer and used as file + * mode. + * @remarks SQLite3: the params is passed directly to the sqlite3_open() + * function as a filename to be opened (check SQLite3 documentation for more + * details). + * @remarks Oracle: the params can have "user", "pass", "dbname" and "server" + * keys, each followed by an equal sign and a value. Such key/value pairs can + * be delimited by space, CR, LF, tab, semicolon, vertical bar or comma. + * @remarks MySQL: the params can have "host", "port", "user", "pass", + * "dbname", "sock", "flags" "fldsz", "group" and "reconnect" keys, each + * followed by an equal sign and a value. Such key/value pairs can be + * delimited by space, CR, LF, tab, semicolon, vertical bar or comma. For + * now, "flags" can only recognise CLIENT_FOUND_ROWS (check MySQL manual for + * details). The value associated with "fldsz" determines maximum amount of + * memory (in bytes) for each of the fields in the result set of prepared + * statements. By default, this value is 1 MB. The value associated with + * "group" determines which group from configuration file to use (see + * MYSQL_READ_DEFAULT_GROUP option of mysql_options() in MySQL manual). + * Reconnect is set to 1 by default (i.e. true). + */ +APU_DECLARE(apr_status_t) apr_dbd_open_ex(const apr_dbd_driver_t *driver, + apr_pool_t *pool, const char *params, + apr_dbd_t **handle, + const char **error); + +/** apr_dbd_open: open a connection to a backend + * + * @param driver - driver struct. + * @param pool - working pool + * @param params - arguments to driver (implementation-dependent) + * @param handle - pointer to handle to return + * @return APR_SUCCESS for success + * @return APR_EGENERAL if driver exists but connection failed + * @see apr_dbd_open_ex + */ +APU_DECLARE(apr_status_t) apr_dbd_open(const apr_dbd_driver_t *driver, + apr_pool_t *pool, const char *params, + apr_dbd_t **handle); + +/** apr_dbd_close: close a connection to a backend + * + * @param driver - driver struct. + * @param handle - handle to close + * @return APR_SUCCESS for success or error status + */ +APU_DECLARE(apr_status_t) apr_dbd_close(const apr_dbd_driver_t *driver, + apr_dbd_t *handle); + +/* apr-function-shaped versions of things */ + +/** apr_dbd_name: get the name of the driver + * + * @param driver - the driver + * @return - name + */ +APU_DECLARE(const char*) apr_dbd_name(const apr_dbd_driver_t *driver); + +/** apr_dbd_native_handle: get native database handle of the underlying db + * + * @param driver - the driver + * @param handle - apr_dbd handle + * @return - native handle + */ +APU_DECLARE(void*) apr_dbd_native_handle(const apr_dbd_driver_t *driver, + apr_dbd_t *handle); + +/** check_conn: check status of a database connection + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection to check + * @return APR_SUCCESS or error + */ +APU_DECLARE(int) apr_dbd_check_conn(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle); + +/** apr_dbd_set_dbname: select database name. May be a no-op if not supported. + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param name - the database to select + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_set_dbname(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, const char *name); + +/** apr_dbd_transaction_start: start a transaction. May be a no-op. + * + * @param driver - the driver + * @param pool - a pool to use for error messages (if any). + * @param handle - the db connection + * @param trans - ptr to a transaction. May be null on entry + * @return 0 for success or error code + * @remarks Note that transaction modes, set by calling + * apr_dbd_transaction_mode_set(), will affect all query/select calls within + * a transaction. By default, any error in query/select during a transaction + * will cause the transaction to inherit the error code and any further + * query/select calls will fail immediately. Put transaction in "ignore + * errors" mode to avoid that. Use "rollback" mode to do explicit rollback. + */ +APU_DECLARE(int) apr_dbd_transaction_start(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_t *handle, + apr_dbd_transaction_t **trans); + +/** apr_dbd_transaction_end: end a transaction + * (commit on success, rollback on error). + * May be a no-op. + * + * @param driver - the driver + * @param handle - the db connection + * @param trans - the transaction. + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_transaction_end(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_transaction_t *trans); + +#define APR_DBD_TRANSACTION_COMMIT 0x00 /**< commit the transaction */ +#define APR_DBD_TRANSACTION_ROLLBACK 0x01 /**< rollback the transaction */ +#define APR_DBD_TRANSACTION_IGNORE_ERRORS 0x02 /**< ignore transaction errors */ + +/** apr_dbd_transaction_mode_get: get the mode of transaction + * + * @param driver - the driver + * @param trans - the transaction + * @return mode of transaction + */ +APU_DECLARE(int) apr_dbd_transaction_mode_get(const apr_dbd_driver_t *driver, + apr_dbd_transaction_t *trans); + +/** apr_dbd_transaction_mode_set: set the mode of transaction + * + * @param driver - the driver + * @param trans - the transaction + * @param mode - new mode of the transaction + * @return the mode of transaction in force after the call + */ +APU_DECLARE(int) apr_dbd_transaction_mode_set(const apr_dbd_driver_t *driver, + apr_dbd_transaction_t *trans, + int mode); + +/** apr_dbd_query: execute an SQL query that doesn't return a result set + * + * @param driver - the driver + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the SQL statement to execute + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_query(const apr_dbd_driver_t *driver, apr_dbd_t *handle, + int *nrows, const char *statement); + +/** apr_dbd_select: execute an SQL query that returns a result set + * + * @param driver - the driver + * @param pool - pool to allocate the result set + * @param handle - the connection + * @param res - pointer to result set pointer. May point to NULL on entry + * @param statement - the SQL statement to execute + * @param random - 1 to support random access to results (seek any row); + * 0 to support only looping through results in order + * (async access - faster) + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_select(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, apr_dbd_results_t **res, + const char *statement, int random); + +/** apr_dbd_num_cols: get the number of columns in a results set + * + * @param driver - the driver + * @param res - result set. + * @return number of columns + */ +APU_DECLARE(int) apr_dbd_num_cols(const apr_dbd_driver_t *driver, + apr_dbd_results_t *res); + +/** apr_dbd_num_tuples: get the number of rows in a results set + * of a synchronous select + * + * @param driver - the driver + * @param res - result set. + * @return number of rows, or -1 if the results are asynchronous + */ +APU_DECLARE(int) apr_dbd_num_tuples(const apr_dbd_driver_t *driver, + apr_dbd_results_t *res); + +/** apr_dbd_get_row: get a row from a result set + * + * @param driver - the driver + * @param pool - pool to allocate the row + * @param res - result set pointer + * @param row - pointer to row pointer. May point to NULL on entry + * @param rownum - row number (counting from 1), or -1 for "next row". + * Ignored if random access is not supported. + * @return 0 for success, -1 for rownum out of range or data finished + */ +APU_DECLARE(int) apr_dbd_get_row(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_results_t *res, apr_dbd_row_t **row, + int rownum); + +/** apr_dbd_get_entry: get an entry from a row + * + * @param driver - the driver + * @param row - row pointer + * @param col - entry number + * @return value from the row, or NULL if col is out of bounds. + */ +APU_DECLARE(const char*) apr_dbd_get_entry(const apr_dbd_driver_t *driver, + apr_dbd_row_t *row, int col); + +/** apr_dbd_get_name: get an entry name from a result set + * + * @param driver - the driver + * @param res - result set pointer + * @param col - entry number + * @return name of the entry, or NULL if col is out of bounds. + */ +APU_DECLARE(const char*) apr_dbd_get_name(const apr_dbd_driver_t *driver, + apr_dbd_results_t *res, int col); + + +/** apr_dbd_error: get current error message (if any) + * + * @param driver - the driver + * @param handle - the connection + * @param errnum - error code from operation that returned an error + * @return the database current error message, or message for errnum + * (implementation-dependent whether errnum is ignored) + */ +APU_DECLARE(const char*) apr_dbd_error(const apr_dbd_driver_t *driver, + apr_dbd_t *handle, int errnum); + +/** apr_dbd_escape: escape a string so it is safe for use in query/select + * + * @param driver - the driver + * @param pool - pool to alloc the result from + * @param string - the string to escape + * @param handle - the connection + * @return the escaped, safe string + */ +APU_DECLARE(const char*) apr_dbd_escape(const apr_dbd_driver_t *driver, + apr_pool_t *pool, const char *string, + apr_dbd_t *handle); + +/** apr_dbd_prepare: prepare a statement + * + * @param driver - the driver + * @param pool - pool to alloc the result from + * @param handle - the connection + * @param query - the SQL query + * @param label - A label for the prepared statement. + * use NULL for temporary prepared statements + * (eg within a Request in httpd) + * @param statement - statement to prepare. May point to null on entry. + * @return 0 for success or error code + * @remarks To specify parameters of the prepared query, use \%s, \%d etc. + * (see below for full list) in place of database specific parameter syntax + * (e.g. for PostgreSQL, this would be $1, $2, for SQLite3 this would be ? + * etc.). For instance: "SELECT name FROM customers WHERE name=%s" would be + * a query that this function understands. + * @remarks Here is the full list of format specifiers that this function + * understands and what they map to in SQL: \%hhd (TINY INT), \%hhu (UNSIGNED + * TINY INT), \%hd (SHORT), \%hu (UNSIGNED SHORT), \%d (INT), \%u (UNSIGNED + * INT), \%ld (LONG), \%lu (UNSIGNED LONG), \%lld (LONG LONG), \%llu + * (UNSIGNED LONG LONG), \%f (FLOAT, REAL), \%lf (DOUBLE PRECISION), \%s + * (VARCHAR), \%pDt (TEXT), \%pDi (TIME), \%pDd (DATE), \%pDa (DATETIME), + * \%pDs (TIMESTAMP), \%pDz (TIMESTAMP WITH TIME ZONE), \%pDb (BLOB), \%pDc + * (CLOB) and \%pDn (NULL). Not all databases have support for all these + * types, so the underlying driver will attempt the "best match" where + * possible. A \% followed by any letter not in the above list will be + * interpreted as VARCHAR (i.e. \%s). + */ +APU_DECLARE(int) apr_dbd_prepare(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, const char *query, + const char *label, + apr_dbd_prepared_t **statement); + + +/** apr_dbd_pquery: query using a prepared statement + args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param nargs - ignored (for backward compatibility only) + * @param args - args to prepared statement + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_pquery(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, int nargs, + const char **args); + +/** apr_dbd_pselect: select using a prepared statement + args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param nargs - ignored (for backward compatibility only) + * @param args - args to prepared statement + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_pselect(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, int random, + int nargs, const char **args); + +/** apr_dbd_pvquery: query using a prepared statement + args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param ... - varargs list + * @return 0 for success or error code + */ +APU_DECLARE_NONSTD(int) apr_dbd_pvquery(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, ...); + +/** apr_dbd_pvselect: select using a prepared statement + args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param ... - varargs list + * @return 0 for success or error code + */ +APU_DECLARE_NONSTD(int) apr_dbd_pvselect(const apr_dbd_driver_t *driver, + apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, + int random, ...); + +/** apr_dbd_pbquery: query using a prepared statement + binary args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_pbquery(const apr_dbd_driver_t *driver, + apr_pool_t *pool, apr_dbd_t *handle, + int *nrows, apr_dbd_prepared_t *statement, + const void **args); + +/** apr_dbd_pbselect: select using a prepared statement + binary args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_pbselect(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_t *handle, apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, int random, + const void **args); + +/** apr_dbd_pvbquery: query using a prepared statement + binary args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param ... - varargs list of binary args + * @return 0 for success or error code + */ +APU_DECLARE_NONSTD(int) apr_dbd_pvbquery(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, ...); + +/** apr_dbd_pvbselect: select using a prepared statement + binary args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param ... - varargs list of binary args + * @return 0 for success or error code + */ +APU_DECLARE_NONSTD(int) apr_dbd_pvbselect(const apr_dbd_driver_t *driver, + apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, + int random, ...); + +/** apr_dbd_datum_get: get a binary entry from a row + * + * @param driver - the driver + * @param row - row pointer + * @param col - entry number + * @param type - type of data to get + * @param data - pointer to data, allocated by the caller + * @return APR_SUCCESS on success, APR_ENOENT if data is NULL or APR_EGENERAL + */ +APU_DECLARE(apr_status_t) apr_dbd_datum_get(const apr_dbd_driver_t *driver, + apr_dbd_row_t *row, int col, + apr_dbd_type_e type, void *data); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_dbm.h b/c/dependencies/windows/apr/x64_debug/include/apr_dbm.h new file mode 100644 index 00000000..ad1b4f39 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_dbm.h @@ -0,0 +1,227 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_DBM_H +#define APR_DBM_H + +#include "apu.h" +#include "apr.h" +#include "apr_errno.h" +#include "apr_pools.h" +#include "apr_file_info.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_dbm.h + * @brief APR-UTIL DBM library + */ +/** + * @defgroup APR_Util_DBM DBM routines + * @ingroup APR_Util + * @{ + */ +/** + * Structure for referencing a dbm + */ +typedef struct apr_dbm_t apr_dbm_t; + +/** + * Structure for referencing the datum record within a dbm + */ +typedef struct +{ + /** pointer to the 'data' to retrieve/store in the DBM */ + char *dptr; + /** size of the 'data' to retrieve/store in the DBM */ + apr_size_t dsize; +} apr_datum_t; + +/* modes to open the DB */ +#define APR_DBM_READONLY 1 /**< open for read-only access */ +#define APR_DBM_READWRITE 2 /**< open for read-write access */ +#define APR_DBM_RWCREATE 3 /**< open for r/w, create if needed */ +#define APR_DBM_RWTRUNC 4 /**< open for r/w, truncating an existing + DB if present */ +/** + * Open a dbm file by file name and type of DBM + * @param dbm The newly opened database + * @param type The type of the DBM (not all may be available at run time) + *
+ *  db   for Berkeley DB files
+ *  gdbm for GDBM files
+ *  ndbm for NDBM files
+ *  sdbm for SDBM files (always available)
+ *  default for the default DBM type
+ *  
+ * @param name The dbm file name to open + * @param mode The flag value + *
+ *           APR_DBM_READONLY   open for read-only access
+ *           APR_DBM_READWRITE  open for read-write access
+ *           APR_DBM_RWCREATE   open for r/w, create if needed
+ *           APR_DBM_RWTRUNC    open for r/w, truncate if already there
+ * 
+ * @param perm Permissions to apply to if created + * @param cntxt The pool to use when creating the dbm + * @remark The dbm name may not be a true file name, as many dbm packages + * append suffixes for seperate data and index files. + * @bug In apr-util 0.9 and 1.x, the type arg was case insensitive. This + * was highly inefficient, and as of 2.x the dbm name must be provided in + * the correct case (lower case for all bundled providers) + */ + +APU_DECLARE(apr_status_t) apr_dbm_open_ex(apr_dbm_t **dbm, const char* type, + const char *name, + apr_int32_t mode, apr_fileperms_t perm, + apr_pool_t *cntxt); + + +/** + * Open a dbm file by file name + * @param dbm The newly opened database + * @param name The dbm file name to open + * @param mode The flag value + *
+ *           APR_DBM_READONLY   open for read-only access
+ *           APR_DBM_READWRITE  open for read-write access
+ *           APR_DBM_RWCREATE   open for r/w, create if needed
+ *           APR_DBM_RWTRUNC    open for r/w, truncate if already there
+ * 
+ * @param perm Permissions to apply to if created + * @param cntxt The pool to use when creating the dbm + * @remark The dbm name may not be a true file name, as many dbm packages + * append suffixes for seperate data and index files. + */ +APU_DECLARE(apr_status_t) apr_dbm_open(apr_dbm_t **dbm, const char *name, + apr_int32_t mode, apr_fileperms_t perm, + apr_pool_t *cntxt); + +/** + * Close a dbm file previously opened by apr_dbm_open + * @param dbm The database to close + */ +APU_DECLARE(void) apr_dbm_close(apr_dbm_t *dbm); + +/** + * Fetch a dbm record value by key + * @param dbm The database + * @param key The key datum to find this record + * @param pvalue The value datum retrieved for this record + */ +APU_DECLARE(apr_status_t) apr_dbm_fetch(apr_dbm_t *dbm, apr_datum_t key, + apr_datum_t *pvalue); +/** + * Store a dbm record value by key + * @param dbm The database + * @param key The key datum to store this record by + * @param value The value datum to store in this record + */ +APU_DECLARE(apr_status_t) apr_dbm_store(apr_dbm_t *dbm, apr_datum_t key, + apr_datum_t value); + +/** + * Delete a dbm record value by key + * @param dbm The database + * @param key The key datum of the record to delete + * @remark It is not an error to delete a non-existent record. + */ +APU_DECLARE(apr_status_t) apr_dbm_delete(apr_dbm_t *dbm, apr_datum_t key); + +/** + * Search for a key within the dbm + * @param dbm The database + * @param key The datum describing a key to test + */ +APU_DECLARE(int) apr_dbm_exists(apr_dbm_t *dbm, apr_datum_t key); + +/** + * Retrieve the first record key from a dbm + * @param dbm The database + * @param pkey The key datum of the first record + */ +APU_DECLARE(apr_status_t) apr_dbm_firstkey(apr_dbm_t *dbm, apr_datum_t *pkey); + +/** + * Retrieve the next record key from a dbm + * @param dbm The database + * @param pkey The key datum of the next record + */ +APU_DECLARE(apr_status_t) apr_dbm_nextkey(apr_dbm_t *dbm, apr_datum_t *pkey); + +/** + * Proactively toss any memory associated with the apr_datum_t. + * @param dbm The database + * @param data The datum to free. + */ +APU_DECLARE(void) apr_dbm_freedatum(apr_dbm_t *dbm, apr_datum_t data); + +/** + * Report more information when an apr_dbm function fails. + * @param dbm The database + * @param errcode A DBM-specific value for the error (for logging). If this + * isn't needed, it may be NULL. + * @param errbuf Location to store the error text + * @param errbufsize The size of the provided buffer + * @return The errbuf parameter, for convenience. + */ +APU_DECLARE(char *) apr_dbm_geterror(apr_dbm_t *dbm, int *errcode, + char *errbuf, apr_size_t errbufsize); +/** + * If the specified file/path were passed to apr_dbm_open(), return the + * actual file/path names which would be (created and) used. At most, two + * files may be used; used2 may be NULL if only one file is used. + * @param pool The pool for allocating used1 and used2. + * @param type The type of DBM you require info on @see apr_dbm_open_ex + * @param pathname The path name to generate used-names from. + * @param used1 The first pathname used by the apr_dbm implementation. + * @param used2 The second pathname used by apr_dbm. If only one file is + * used by the specific implementation, this will be set to NULL. + * @return An error if the specified type is invalid. + * @remark The dbm file(s) don't need to exist. This function only manipulates + * the pathnames. + */ +APU_DECLARE(apr_status_t) apr_dbm_get_usednames_ex(apr_pool_t *pool, + const char *type, + const char *pathname, + const char **used1, + const char **used2); + +/** + * If the specified file/path were passed to apr_dbm_open(), return the + * actual file/path names which would be (created and) used. At most, two + * files may be used; used2 may be NULL if only one file is used. + * @param pool The pool for allocating used1 and used2. + * @param pathname The path name to generate used-names from. + * @param used1 The first pathname used by the apr_dbm implementation. + * @param used2 The second pathname used by apr_dbm. If only one file is + * used by the specific implementation, this will be set to NULL. + * @remark The dbm file(s) don't need to exist. This function only manipulates + * the pathnames. + */ +APU_DECLARE(void) apr_dbm_get_usednames(apr_pool_t *pool, + const char *pathname, + const char **used1, + const char **used2); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_DBM_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_dso.h b/c/dependencies/windows/apr/x64_debug/include/apr_dso.h new file mode 100644 index 00000000..ac701cfd --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_dso.h @@ -0,0 +1,94 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_DSO_DOT_H +#define APR_DSO_DOT_H + +/** + * @file apr_dso.h + * @brief APR Dynamic Object Handling Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_dso Dynamic Object Handling + * @ingroup APR + * @{ + */ + +#if APR_HAS_DSO || defined(DOXYGEN) + +/** + * Structure for referencing dynamic objects + */ +typedef struct apr_dso_handle_t apr_dso_handle_t; + +/** + * Structure for referencing symbols from dynamic objects + */ +typedef void * apr_dso_handle_sym_t; + +/** + * Load a DSO library. + * @param res_handle Location to store new handle for the DSO. + * @param path Path to the DSO library + * @param ctx Pool to use. + * @bug We aught to provide an alternative to RTLD_GLOBAL, which + * is the only supported method of loading DSOs today. + */ +APR_DECLARE(apr_status_t) apr_dso_load(apr_dso_handle_t **res_handle, + const char *path, apr_pool_t *ctx); + +/** + * Close a DSO library. + * @param handle handle to close. + */ +APR_DECLARE(apr_status_t) apr_dso_unload(apr_dso_handle_t *handle); + +/** + * Load a symbol from a DSO handle. + * @param ressym Location to store the loaded symbol + * @param handle handle to load the symbol from. + * @param symname Name of the symbol to load. + */ +APR_DECLARE(apr_status_t) apr_dso_sym(apr_dso_handle_sym_t *ressym, + apr_dso_handle_t *handle, + const char *symname); + +/** + * Report more information when a DSO function fails. + * @param dso The dso handle that has been opened + * @param buf Location to store the dso error + * @param bufsize The size of the provided buffer + */ +APR_DECLARE(const char *) apr_dso_error(apr_dso_handle_t *dso, char *buf, apr_size_t bufsize); + +#endif /* APR_HAS_DSO */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_encode.h b/c/dependencies/windows/apr/x64_debug/include/apr_encode.h new file mode 100644 index 00000000..20fc932f --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_encode.h @@ -0,0 +1,569 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_encode.h + * @brief APR-UTIL Encoding + */ +#ifndef APR_ENCODE_H +#define APR_ENCODE_H + +#include "apr.h" +#include "apr_general.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Encode Base64/Base64Url/Base32/Base32Hex/Base16 Encoding + * @ingroup APR_Util + * @{ + */ + +/** + * RFC4648 and RFC7515 compliant BASE64, BASE64URL, BASE32, BASE32HEX + * and BASE16 encode/decode functions. + * + * The following encodings are supported: + * + * - Base 64 Encoding + * + * o Use flag APR_ENCODE_NONE + * o https://tools.ietf.org/html/rfc4648#section-4 + * + * - Base 64 Encoding with URL and Filename Safe Alphabet + * + * o Use flag APR_ENCODE_URL + * o https://tools.ietf.org/html/rfc4648#section-5 + * + * - Base 64 URL Encoding without Padding + * + * o Use flag APR_ENCODE_BASE64URL + * o https://tools.ietf.org/html/rfc7515#appendix-C + * + * - Base 32 Encoding + * + * o Use flag APR_ENCODE_NONE + * o https://tools.ietf.org/html/rfc4648#section-6 + * + * - Base 32 Encoding with Extended Hex Alphabet + * + * o Use flag APR_ENCODE_BASE32HEX + * o https://tools.ietf.org/html/rfc4648#section-7 + * + * - Base 16 Encoding + * + * o Use flags APR_ENCODE_NONE/APR_ENCODE_COLON + * o https://tools.ietf.org/html/rfc4648#section-8 + * + * If a non valid character of any kind including whitespace is passed to any + * of the decoder functions, APR_BADCH will be returned. In this case decoding + * will still take place, but the results can not be trusted. + * + * If APR_ENCODE_RELAXED is passed to the decoder functions, decoding will be + * attempted up until the first non valid character. If this results in an + * invalid state in the decoder, such as but not limited to an odd number of + * base16 characters, APR_BADCH will still be returned. + * + * If APR_ENCODE_RELAXED is not passed to a decoder function, the decoding will + * be done in constant time regardless of whether the result returns APR_SUCCESS + * or APR_BADCH. + * + * If the dest parameter is NULL, the maximum theoretical buffer size is + * returned in the len field, including space for a terminating zero character + * if the destination is a string. This value can be used to allocate buffers + * of a suitable safe size. + * + * If the dest parameter is provided, the encoding or decoding will take place, + * and the actual number of characters written is returned in the len field, + * ignoring any terminating zero. + * + * Plain strings are not assumed '\0' terminated unless APR_ENCODE_STRING is + * provided. + * + */ + +/** + * When passing a string to one of the encode functions, this value can be + * passed to indicate a string-valued key, and have the length computed + * automatically. + */ +#define APR_ENCODE_STRING (-1) + +/** + * Generate RFC4648 base16/base32/base64. + */ +#define APR_ENCODE_NONE 0 + +/** + * If relaxed, decode up until the first non base16/base32/base64 character. + */ +#define APR_ENCODE_RELAXED 1 + +/** + * Omit the padding character (=) while encoding. + */ +#define APR_ENCODE_NOPADDING 2 + +/** + * Generate RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet + */ +#define APR_ENCODE_URL 4 + +/** + * Generate RFC7515 BASE64URL + */ +#define APR_ENCODE_BASE64URL (APR_ENCODE_NOPADDING | APR_ENCODE_URL) + +/** + * Generate base32hex encoding instead of base32 encoding + */ +#define APR_ENCODE_BASE32HEX 8 + +/** + * Generate base16 with colons between each token. + */ +#define APR_ENCODE_COLON 16 + +/** + * Generate base16 with lower case characters. + */ +#define APR_ENCODE_LOWER 32 + +/** + * Convert text data to base64. + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 64 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_URL, + * use RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet. + * If APR_ENCODE_BASE64URL, use RFC7515 base64url Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination string, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base64(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert binary data to base64. + * @param dest The destination string, can be NULL. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 64 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_URL, + * use RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet. + * If APR_ENCODE_BASE64URL, use RFC7515 base64url Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination string, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base64_binary(char *dest, const unsigned char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert text data to base64, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 64 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_URL, + * use RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet. + * If APR_ENCODE_BASE64URL, use RFC7515 base64url Encoding. + * @param len If present, returns the number of characters written excluding + * the zero pad. + * @return A zero padded string allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *)apr_pencode_base64(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len)__attribute__((nonnull(1))); + +/** + * Convert binary data to base64, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 64 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_URL, + * use RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet. + * If APR_ENCODE_BASE64URL, use RFC7515 base64url Encoding. + * @param len If present, returns the number of characters written excluding + * the zero pad. + * @return A zero padded string allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *)apr_pencode_base64_binary(apr_pool_t * p, const unsigned char *src, + apr_ssize_t slen, int flags, apr_size_t * len)__attribute__((nonnull(1))); + +/** + * Convert base64 or base64url with or without padding to text data. + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, attempt to decode the full original buffer, + * and return NULL if any bad character is detected. If APR_ENCODE_RELAXED, + * decode until the first non base64/base64url character. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination string, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL, or APR_BADCH + * if a non hex character is present. + */ +APR_DECLARE(apr_status_t) apr_decode_base64(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base64 or base64url with or without padding to binary data. + * @param dest The destination buffer, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, attempt to decode the full original buffer, + * and return NULL if any bad character is detected. If APR_ENCODE_RELAXED, + * decode until the first non base64/base64url character. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the src was NULL, or APR_BADCH + * if a non base64 character is present. + */ +APR_DECLARE(apr_status_t) apr_decode_base64_binary(unsigned char *dest, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base64 or base64url with or without padding to text data, and + * return the results from a pool. + * @param p Pool to allocate from. + * @param src The base64 string to decode. + * @param slen The length of the base64 string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, attempt to decode the full original buffer, + * and return NULL if any bad character is detected. If APR_ENCODE_RELAXED, + * decode until the first non base64/base64url character. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A string allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const char *)apr_pdecode_base64(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert base64 or base64url with or without padding to binary data, and + * return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, attempt to decode the full original buffer, + * and return NULL if any bad character is detected. If APR_ENCODE_RELAXED, + * decode until the first non base64/base64url character. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A buffer allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const unsigned char *)apr_pdecode_base64_binary(apr_pool_t * p, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert text data to base32. + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 32 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_BASE32HEX, + * use RFC4648 base32hex Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination string, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base32(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert binary data to base32. + * @param dest The destination string, can be NULL. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 32 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_BASE32HEX, + * use RFC4648 base32hex Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination string, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base32_binary(char *dest, const unsigned char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert text data to base32, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 32 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_BASE32HEX, + * use RFC4648 base32hex Encoding. + * @param len If present, returns the number of characters written excluding + * the zero pad. + * @return A zero padded string allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *)apr_pencode_base32(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert binary data to base32, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 32 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_BASE32HEX, + * use RFC7515 base32hex Encoding. + * @param len If present, returns the number of characters written excluding + * the zero pad. + * @return A zero padded string allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *)apr_pencode_base32_binary(apr_pool_t * p, const unsigned char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert base32 or base32hex with or without padding to text data. + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 32 Encoding. If + * APR_ENCODE_BASE32HEX, use RFC4648 base32hex Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL, or APR_BADCH + * if a non base32 character is present. + */ +APR_DECLARE(apr_status_t) apr_decode_base32(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base32 or base32hex with or without padding to binary data. + * @param dest The destination buffer, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 32 Encoding. If + * APR_ENCODE_BASE32HEX, use RFC4648 base32hex Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the src was NULL, or APR_BADCH + * if a non base32 character is present. + */ +APR_DECLARE(apr_status_t) apr_decode_base32_binary(unsigned char *dest, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base32 or base32hex with or without padding to text data, and + * return the results from a pool. + * @param p Pool to allocate from. + * @param src The base32 string to decode. + * @param slen The length of the base32 string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 32 Encoding. If + * APR_ENCODE_BASE32HEX, use RFC4648 base32hex Encoding. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A string allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const char *)apr_pdecode_base32(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert base32 or base32hex with or without padding to binary data, and + * return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 32 Encoding. If + * APR_ENCODE_BASE32HEX, use RFC4648 base32hex Encoding. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A buffer allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const unsigned char *)apr_pdecode_base32_binary(apr_pool_t * p, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert text data to base16 (hex). + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, separate each token with a colon. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base16(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert binary data to base16 (hex). + * @param dest The destination string, can be NULL. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, separate each token with a colon. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base16_binary(char *dest, + const unsigned char *src, apr_ssize_t slen, int flags, + apr_size_t * len); + +/** + * Convert text data to base16 (hex), and return the results from a + * pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, separate each token with a colon. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A string allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const char *)apr_pencode_base16(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert binary data to base16 (hex), and return the results from a + * pool. + * @param p Pool to allocate from. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, separate each token with a colon. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A string allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const char *)apr_pencode_base16_binary(apr_pool_t * p, + const unsigned char *src, apr_ssize_t slen, + int flags, apr_size_t * len)__attribute__((nonnull(1))); + +/** + * Convert base16 (hex) to text data. + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, allow tokens to be separated with a colon. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL, or APR_BADCH + * if a non hex character is present. A zero pad is appended to the buffer. + */ +APR_DECLARE(apr_status_t) apr_decode_base16(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base16 (hex) to binary data. + * @param dest The destination buffer, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, allow tokens to be separated with a colon. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL, or APR_BADCH + * if a non hex character is present. No zero pad is written to the buffer. + */ +APR_DECLARE(apr_status_t) apr_decode_base16_binary(unsigned char *dest, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base16 (hex) and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, allow tokens to be separated with a colon. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A buffer allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const char *)apr_pdecode_base16(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert base16 (hex) to binary data, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, allow tokens to be separated with a colon. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A buffer allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const unsigned char *)apr_pdecode_base16_binary(apr_pool_t * p, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ENCODE_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_env.h b/c/dependencies/windows/apr/x64_debug/include/apr_env.h new file mode 100644 index 00000000..85ab6704 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_env.h @@ -0,0 +1,67 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ENV_H +#define APR_ENV_H +/** + * @file apr_env.h + * @brief APR Environment functions + */ +#include "apr_errno.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_env Functions for manipulating the environment + * @ingroup APR + * @{ + */ + +/** + * Get the value of an environment variable + * @param value the returned value, allocated from @a pool + * @param envvar the name of the environment variable + * @param pool where to allocate @a value and any temporary storage from + */ +APR_DECLARE(apr_status_t) apr_env_get(char **value, const char *envvar, + apr_pool_t *pool); + +/** + * Set the value of an environment variable + * @param envvar the name of the environment variable + * @param value the value to set + * @param pool where to allocate temporary storage from + */ +APR_DECLARE(apr_status_t) apr_env_set(const char *envvar, const char *value, + apr_pool_t *pool); + +/** + * Delete a variable from the environment + * @param envvar the name of the environment variable + * @param pool where to allocate temporary storage from + */ +APR_DECLARE(apr_status_t) apr_env_delete(const char *envvar, apr_pool_t *pool); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_ENV_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_errno.h b/c/dependencies/windows/apr/x64_debug/include/apr_errno.h new file mode 100644 index 00000000..8fa6628b --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_errno.h @@ -0,0 +1,1342 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ERRNO_H +#define APR_ERRNO_H + +/** + * @file apr_errno.h + * @brief APR Error Codes + */ + +#include "apr.h" + +#if APR_HAVE_ERRNO_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_errno Error Codes + * @ingroup APR + * @{ + */ + +/** + * Type for specifying an error or status code. + */ +typedef int apr_status_t; + +/** + * Return a human readable string describing the specified error. + * @param statcode The error code to get a string for. + * @param buf A buffer to hold the error string. + * @param bufsize Size of the buffer to hold the string. + */ +APR_DECLARE(char *) apr_strerror(apr_status_t statcode, char *buf, + apr_size_t bufsize); + +#if defined(DOXYGEN) +/** + * @def APR_FROM_OS_ERROR(os_err_type syserr) + * Fold a platform specific error into an apr_status_t code. + * @return apr_status_t + * @param e The platform os error code. + * @warning macro implementation; the syserr argument may be evaluated + * multiple times. + */ +#define APR_FROM_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e + APR_OS_START_SYSERR) + +/** + * @def APR_TO_OS_ERROR(apr_status_t statcode) + * @return os_err_type + * Fold an apr_status_t code back to the native platform defined error. + * @param e The apr_status_t folded platform os error code. + * @warning macro implementation; the statcode argument may be evaluated + * multiple times. If the statcode was not created by apr_get_os_error + * or APR_FROM_OS_ERROR, the results are undefined. + */ +#define APR_TO_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e - APR_OS_START_SYSERR) + +/** @def apr_get_os_error() + * @return apr_status_t the last platform error, folded into apr_status_t, on most platforms + * @remark This retrieves errno, or calls a GetLastError() style function, and + * folds it with APR_FROM_OS_ERROR. Some platforms (such as OS2) have no + * such mechanism, so this call may be unsupported. Do NOT use this + * call for socket errors from socket, send, recv etc! + */ + +/** @def apr_set_os_error(e) + * Reset the last platform error, unfolded from an apr_status_t, on some platforms + * @param e The OS error folded in a prior call to APR_FROM_OS_ERROR() + * @warning This is a macro implementation; the statcode argument may be evaluated + * multiple times. If the statcode was not created by apr_get_os_error + * or APR_FROM_OS_ERROR, the results are undefined. This macro sets + * errno, or calls a SetLastError() style function, unfolding statcode + * with APR_TO_OS_ERROR. Some platforms (such as OS2) have no such + * mechanism, so this call may be unsupported. + */ + +/** @def apr_get_netos_error() + * Return the last socket error, folded into apr_status_t, on all platforms + * @remark This retrieves errno or calls a GetLastSocketError() style function, + * and folds it with APR_FROM_OS_ERROR. + */ + +/** @def apr_set_netos_error(e) + * Reset the last socket error, unfolded from an apr_status_t + * @param e The socket error folded in a prior call to APR_FROM_OS_ERROR() + * @warning This is a macro implementation; the statcode argument may be evaluated + * multiple times. If the statcode was not created by apr_get_os_error + * or APR_FROM_OS_ERROR, the results are undefined. This macro sets + * errno, or calls a WSASetLastError() style function, unfolding + * socketcode with APR_TO_OS_ERROR. + */ + +#endif /* defined(DOXYGEN) */ + +/** + * APR_OS_START_ERROR is where the APR specific error values start. + */ +#define APR_OS_START_ERROR 20000 +/** + * APR_OS_ERRSPACE_SIZE is the maximum number of errors you can fit + * into one of the error/status ranges below -- except for + * APR_OS_START_USERERR, which see. + */ +#define APR_OS_ERRSPACE_SIZE 50000 +/** + * APR_UTIL_ERRSPACE_SIZE is the size of the space that is reserved for + * use within apr-util. This space is reserved above that used by APR + * internally. + * @note This number MUST be smaller than APR_OS_ERRSPACE_SIZE by a + * large enough amount that APR has sufficient room for its + * codes. + */ +#define APR_UTIL_ERRSPACE_SIZE 20000 +/** + * APR_OS_START_STATUS is where the APR specific status codes start. + */ +#define APR_OS_START_STATUS (APR_OS_START_ERROR + APR_OS_ERRSPACE_SIZE) +/** + * APR_UTIL_START_STATUS is where APR-Util starts defining its + * status codes. + */ +#define APR_UTIL_START_STATUS (APR_OS_START_STATUS + \ + (APR_OS_ERRSPACE_SIZE - APR_UTIL_ERRSPACE_SIZE)) +/** + * APR_OS_START_USERERR are reserved for applications that use APR that + * layer their own error codes along with APR's. Note that the + * error immediately following this one is set ten times farther + * away than usual, so that users of apr have a lot of room in + * which to declare custom error codes. + * + * In general applications should try and create unique error codes. To try + * and assist in finding suitable ranges of numbers to use, the following + * ranges are known to be used by the listed applications. If your + * application defines error codes please advise the range of numbers it + * uses to dev@apr.apache.org for inclusion in this list. + * + * Ranges shown are in relation to APR_OS_START_USERERR + * + * Subversion - Defined ranges, of less than 100, at intervals of 5000 + * starting at an offset of 5000, e.g. + * +5000 to 5100, +10000 to 10100 + * + * Apache HTTPD - +2000 to 2999 + */ +#define APR_OS_START_USERERR (APR_OS_START_STATUS + APR_OS_ERRSPACE_SIZE) +/** + * APR_OS_START_USEERR is obsolete, defined for compatibility only. + * Use APR_OS_START_USERERR instead. + */ +#define APR_OS_START_USEERR APR_OS_START_USERERR +/** + * APR_OS_START_CANONERR is where APR versions of errno values are defined + * on systems which don't have the corresponding errno. + */ +#define APR_OS_START_CANONERR (APR_OS_START_USERERR \ + + (APR_OS_ERRSPACE_SIZE * 10)) +/** + * APR_OS_START_EAIERR folds EAI_ error codes from getaddrinfo() into + * apr_status_t values. + */ +#define APR_OS_START_EAIERR (APR_OS_START_CANONERR + APR_OS_ERRSPACE_SIZE) +/** + * APR_OS_START_SYSERR folds platform-specific system error values into + * apr_status_t values. + */ +#define APR_OS_START_SYSERR (APR_OS_START_EAIERR + APR_OS_ERRSPACE_SIZE) + +/** + * @defgroup APR_ERROR_map APR Error Space + *
+ * The following attempts to show the relation of the various constants
+ * used for mapping APR Status codes.
+ *
+ *       0
+ *
+ *  20,000     APR_OS_START_ERROR
+ *
+ *         + APR_OS_ERRSPACE_SIZE (50,000)
+ *
+ *  70,000      APR_OS_START_STATUS
+ *
+ *         + APR_OS_ERRSPACE_SIZE - APR_UTIL_ERRSPACE_SIZE (30,000)
+ *
+ * 100,000      APR_UTIL_START_STATUS
+ *
+ *         + APR_UTIL_ERRSPACE_SIZE (20,000)
+ *
+ * 120,000      APR_OS_START_USERERR
+ *
+ *         + 10 x APR_OS_ERRSPACE_SIZE (50,000 * 10)
+ *
+ * 620,000      APR_OS_START_CANONERR
+ *
+ *         + APR_OS_ERRSPACE_SIZE (50,000)
+ *
+ * 670,000      APR_OS_START_EAIERR
+ *
+ *         + APR_OS_ERRSPACE_SIZE (50,000)
+ *
+ * 720,000      APR_OS_START_SYSERR
+ *
+ * 
+ */ + +/** no error. */ +#define APR_SUCCESS 0 + +/** + * @defgroup APR_Error APR Error Values + *
+ * APR ERROR VALUES
+ * APR_ENOSTAT      APR was unable to perform a stat on the file
+ * APR_ENOPOOL      APR was not provided a pool with which to allocate memory
+ * APR_EBADDATE     APR was given an invalid date
+ * APR_EINVALSOCK   APR was given an invalid socket
+ * APR_ENOPROC      APR was not given a process structure
+ * APR_ENOTIME      APR was not given a time structure
+ * APR_ENODIR       APR was not given a directory structure
+ * APR_ENOLOCK      APR was not given a lock structure
+ * APR_ENOPOLL      APR was not given a poll structure
+ * APR_ENOSOCKET    APR was not given a socket
+ * APR_ENOTHREAD    APR was not given a thread structure
+ * APR_ENOTHDKEY    APR was not given a thread key structure
+ * APR_ENOSHMAVAIL  There is no more shared memory available
+ * APR_EDSOOPEN     APR was unable to open the dso object.  For more
+ *                  information call apr_dso_error().
+ * APR_EGENERAL     General failure (specific information not available)
+ * APR_EBADIP       The specified IP address is invalid
+ * APR_EBADMASK     The specified netmask is invalid
+ * APR_ESYMNOTFOUND Could not find the requested symbol
+ * APR_ENOTENOUGHENTROPY Not enough entropy to continue
+ * 
+ * + *
+ * APR STATUS VALUES
+ * APR_INCHILD        Program is currently executing in the child
+ * APR_INPARENT       Program is currently executing in the parent
+ * APR_DETACH         The thread is detached
+ * APR_NOTDETACH      The thread is not detached
+ * APR_CHILD_DONE     The child has finished executing
+ * APR_CHILD_NOTDONE  The child has not finished executing
+ * APR_TIMEUP         The operation did not finish before the timeout
+ * APR_INCOMPLETE     The operation was incomplete although some processing
+ *                    was performed and the results are partially valid
+ * APR_BADCH          Getopt found an option not in the option string
+ * APR_BADARG         Getopt found an option that is missing an argument
+ *                    and an argument was specified in the option string
+ * APR_EOF            APR has encountered the end of the file
+ * APR_NOTFOUND       APR was unable to find the socket in the poll structure
+ * APR_ANONYMOUS      APR is using anonymous shared memory
+ * APR_FILEBASED      APR is using a file name as the key to the shared memory
+ * APR_KEYBASED       APR is using a shared key as the key to the shared memory
+ * APR_EINIT          Ininitalizer value.  If no option has been found, but
+ *                    the status variable requires a value, this should be used
+ * APR_ENOTIMPL       The APR function has not been implemented on this
+ *                    platform, either because nobody has gotten to it yet,
+ *                    or the function is impossible on this platform.
+ * APR_EMISMATCH      Two passwords do not match.
+ * APR_EABSOLUTE      The given path was absolute.
+ * APR_ERELATIVE      The given path was relative.
+ * APR_EINCOMPLETE    The given path was neither relative nor absolute.
+ * APR_EABOVEROOT     The given path was above the root path.
+ * APR_EBUSY          The given lock was busy.
+ * APR_EPROC_UNKNOWN  The given process wasn't recognized by APR
+ * 
+ * @{ + */ +/** @see APR_STATUS_IS_ENOSTAT */ +#define APR_ENOSTAT (APR_OS_START_ERROR + 1) +/** @see APR_STATUS_IS_ENOPOOL */ +#define APR_ENOPOOL (APR_OS_START_ERROR + 2) +/* empty slot: +3 */ +/** @see APR_STATUS_IS_EBADDATE */ +#define APR_EBADDATE (APR_OS_START_ERROR + 4) +/** @see APR_STATUS_IS_EINVALSOCK */ +#define APR_EINVALSOCK (APR_OS_START_ERROR + 5) +/** @see APR_STATUS_IS_ENOPROC */ +#define APR_ENOPROC (APR_OS_START_ERROR + 6) +/** @see APR_STATUS_IS_ENOTIME */ +#define APR_ENOTIME (APR_OS_START_ERROR + 7) +/** @see APR_STATUS_IS_ENODIR */ +#define APR_ENODIR (APR_OS_START_ERROR + 8) +/** @see APR_STATUS_IS_ENOLOCK */ +#define APR_ENOLOCK (APR_OS_START_ERROR + 9) +/** @see APR_STATUS_IS_ENOPOLL */ +#define APR_ENOPOLL (APR_OS_START_ERROR + 10) +/** @see APR_STATUS_IS_ENOSOCKET */ +#define APR_ENOSOCKET (APR_OS_START_ERROR + 11) +/** @see APR_STATUS_IS_ENOTHREAD */ +#define APR_ENOTHREAD (APR_OS_START_ERROR + 12) +/** @see APR_STATUS_IS_ENOTHDKEY */ +#define APR_ENOTHDKEY (APR_OS_START_ERROR + 13) +/** @see APR_STATUS_IS_EGENERAL */ +#define APR_EGENERAL (APR_OS_START_ERROR + 14) +/** @see APR_STATUS_IS_ENOSHMAVAIL */ +#define APR_ENOSHMAVAIL (APR_OS_START_ERROR + 15) +/** @see APR_STATUS_IS_EBADIP */ +#define APR_EBADIP (APR_OS_START_ERROR + 16) +/** @see APR_STATUS_IS_EBADMASK */ +#define APR_EBADMASK (APR_OS_START_ERROR + 17) +/* empty slot: +18 */ +/** @see APR_STATUS_IS_EDSOPEN */ +#define APR_EDSOOPEN (APR_OS_START_ERROR + 19) +/** @see APR_STATUS_IS_EABSOLUTE */ +#define APR_EABSOLUTE (APR_OS_START_ERROR + 20) +/** @see APR_STATUS_IS_ERELATIVE */ +#define APR_ERELATIVE (APR_OS_START_ERROR + 21) +/** @see APR_STATUS_IS_EINCOMPLETE */ +#define APR_EINCOMPLETE (APR_OS_START_ERROR + 22) +/** @see APR_STATUS_IS_EABOVEROOT */ +#define APR_EABOVEROOT (APR_OS_START_ERROR + 23) +/** @see APR_STATUS_IS_EBADPATH */ +#define APR_EBADPATH (APR_OS_START_ERROR + 24) +/** @see APR_STATUS_IS_EPATHWILD */ +#define APR_EPATHWILD (APR_OS_START_ERROR + 25) +/** @see APR_STATUS_IS_ESYMNOTFOUND */ +#define APR_ESYMNOTFOUND (APR_OS_START_ERROR + 26) +/** @see APR_STATUS_IS_EPROC_UNKNOWN */ +#define APR_EPROC_UNKNOWN (APR_OS_START_ERROR + 27) +/** @see APR_STATUS_IS_ENOTENOUGHENTROPY */ +#define APR_ENOTENOUGHENTROPY (APR_OS_START_ERROR + 28) +/** @} */ + +/** + * @defgroup APR_STATUS_IS Status Value Tests + * @warning For any particular error condition, more than one of these tests + * may match. This is because platform-specific error codes may not + * always match the semantics of the POSIX codes these tests (and the + * corresponding APR error codes) are named after. A notable example + * are the APR_STATUS_IS_ENOENT and APR_STATUS_IS_ENOTDIR tests on + * Win32 platforms. The programmer should always be aware of this and + * adjust the order of the tests accordingly. + * @{ + */ +/** + * APR was unable to perform a stat on the file + * @warning always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_ENOSTAT(s) ((s) == APR_ENOSTAT) +/** + * APR was not provided a pool with which to allocate memory + * @warning always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_ENOPOOL(s) ((s) == APR_ENOPOOL) +/** APR was given an invalid date */ +#define APR_STATUS_IS_EBADDATE(s) ((s) == APR_EBADDATE) +/** APR was given an invalid socket */ +#define APR_STATUS_IS_EINVALSOCK(s) ((s) == APR_EINVALSOCK) +/** APR was not given a process structure */ +#define APR_STATUS_IS_ENOPROC(s) ((s) == APR_ENOPROC) +/** APR was not given a time structure */ +#define APR_STATUS_IS_ENOTIME(s) ((s) == APR_ENOTIME) +/** APR was not given a directory structure */ +#define APR_STATUS_IS_ENODIR(s) ((s) == APR_ENODIR) +/** APR was not given a lock structure */ +#define APR_STATUS_IS_ENOLOCK(s) ((s) == APR_ENOLOCK) +/** APR was not given a poll structure */ +#define APR_STATUS_IS_ENOPOLL(s) ((s) == APR_ENOPOLL) +/** APR was not given a socket */ +#define APR_STATUS_IS_ENOSOCKET(s) ((s) == APR_ENOSOCKET) +/** APR was not given a thread structure */ +#define APR_STATUS_IS_ENOTHREAD(s) ((s) == APR_ENOTHREAD) +/** APR was not given a thread key structure */ +#define APR_STATUS_IS_ENOTHDKEY(s) ((s) == APR_ENOTHDKEY) +/** Generic Error which can not be put into another spot */ +#define APR_STATUS_IS_EGENERAL(s) ((s) == APR_EGENERAL) +/** There is no more shared memory available */ +#define APR_STATUS_IS_ENOSHMAVAIL(s) ((s) == APR_ENOSHMAVAIL) +/** The specified IP address is invalid */ +#define APR_STATUS_IS_EBADIP(s) ((s) == APR_EBADIP) +/** The specified netmask is invalid */ +#define APR_STATUS_IS_EBADMASK(s) ((s) == APR_EBADMASK) +/* empty slot: +18 */ +/** + * APR was unable to open the dso object. + * For more information call apr_dso_error(). + */ +#if defined(WIN32) +#define APR_STATUS_IS_EDSOOPEN(s) ((s) == APR_EDSOOPEN \ + || APR_TO_OS_ERROR(s) == ERROR_MOD_NOT_FOUND) +#else +#define APR_STATUS_IS_EDSOOPEN(s) ((s) == APR_EDSOOPEN) +#endif +/** The given path was absolute. */ +#define APR_STATUS_IS_EABSOLUTE(s) ((s) == APR_EABSOLUTE) +/** The given path was relative. */ +#define APR_STATUS_IS_ERELATIVE(s) ((s) == APR_ERELATIVE) +/** The given path was neither relative nor absolute. */ +#define APR_STATUS_IS_EINCOMPLETE(s) ((s) == APR_EINCOMPLETE) +/** The given path was above the root path. */ +#define APR_STATUS_IS_EABOVEROOT(s) ((s) == APR_EABOVEROOT) +/** The given path was bad. */ +#define APR_STATUS_IS_EBADPATH(s) ((s) == APR_EBADPATH) +/** The given path contained wildcards. */ +#define APR_STATUS_IS_EPATHWILD(s) ((s) == APR_EPATHWILD) +/** Could not find the requested symbol. + * For more information call apr_dso_error(). + */ +#if defined(WIN32) +#define APR_STATUS_IS_ESYMNOTFOUND(s) ((s) == APR_ESYMNOTFOUND \ + || APR_TO_OS_ERROR(s) == ERROR_PROC_NOT_FOUND) +#else +#define APR_STATUS_IS_ESYMNOTFOUND(s) ((s) == APR_ESYMNOTFOUND) +#endif +/** The given process was not recognized by APR. */ +#define APR_STATUS_IS_EPROC_UNKNOWN(s) ((s) == APR_EPROC_UNKNOWN) +/** APR could not gather enough entropy to continue. */ +#define APR_STATUS_IS_ENOTENOUGHENTROPY(s) ((s) == APR_ENOTENOUGHENTROPY) + +/** @} */ + +/** + * @addtogroup APR_Error + * @{ + */ +/** @see APR_STATUS_IS_INCHILD */ +#define APR_INCHILD (APR_OS_START_STATUS + 1) +/** @see APR_STATUS_IS_INPARENT */ +#define APR_INPARENT (APR_OS_START_STATUS + 2) +/** @see APR_STATUS_IS_DETACH */ +#define APR_DETACH (APR_OS_START_STATUS + 3) +/** @see APR_STATUS_IS_NOTDETACH */ +#define APR_NOTDETACH (APR_OS_START_STATUS + 4) +/** @see APR_STATUS_IS_CHILD_DONE */ +#define APR_CHILD_DONE (APR_OS_START_STATUS + 5) +/** @see APR_STATUS_IS_CHILD_NOTDONE */ +#define APR_CHILD_NOTDONE (APR_OS_START_STATUS + 6) +/** @see APR_STATUS_IS_TIMEUP */ +#define APR_TIMEUP (APR_OS_START_STATUS + 7) +/** @see APR_STATUS_IS_INCOMPLETE */ +#define APR_INCOMPLETE (APR_OS_START_STATUS + 8) +/* empty slot: +9 */ +/* empty slot: +10 */ +/* empty slot: +11 */ +/** @see APR_STATUS_IS_BADCH */ +#define APR_BADCH (APR_OS_START_STATUS + 12) +/** @see APR_STATUS_IS_BADARG */ +#define APR_BADARG (APR_OS_START_STATUS + 13) +/** @see APR_STATUS_IS_EOF */ +#define APR_EOF (APR_OS_START_STATUS + 14) +/** @see APR_STATUS_IS_NOTFOUND */ +#define APR_NOTFOUND (APR_OS_START_STATUS + 15) +/* empty slot: +16 */ +/* empty slot: +17 */ +/* empty slot: +18 */ +/** @see APR_STATUS_IS_ANONYMOUS */ +#define APR_ANONYMOUS (APR_OS_START_STATUS + 19) +/** @see APR_STATUS_IS_FILEBASED */ +#define APR_FILEBASED (APR_OS_START_STATUS + 20) +/** @see APR_STATUS_IS_KEYBASED */ +#define APR_KEYBASED (APR_OS_START_STATUS + 21) +/** @see APR_STATUS_IS_EINIT */ +#define APR_EINIT (APR_OS_START_STATUS + 22) +/** @see APR_STATUS_IS_ENOTIMPL */ +#define APR_ENOTIMPL (APR_OS_START_STATUS + 23) +/** @see APR_STATUS_IS_EMISMATCH */ +#define APR_EMISMATCH (APR_OS_START_STATUS + 24) +/** @see APR_STATUS_IS_EBUSY */ +#define APR_EBUSY (APR_OS_START_STATUS + 25) +/** @} */ + +/** + * @addtogroup APR_STATUS_IS + * @{ + */ +/** + * Program is currently executing in the child + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code */ +#define APR_STATUS_IS_INCHILD(s) ((s) == APR_INCHILD) +/** + * Program is currently executing in the parent + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_INPARENT(s) ((s) == APR_INPARENT) +/** + * The thread is detached + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_DETACH(s) ((s) == APR_DETACH) +/** + * The thread is not detached + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_NOTDETACH(s) ((s) == APR_NOTDETACH) +/** + * The child has finished executing + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_CHILD_DONE(s) ((s) == APR_CHILD_DONE) +/** + * The child has not finished executing + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_CHILD_NOTDONE(s) ((s) == APR_CHILD_NOTDONE) +/** + * The operation did not finish before the timeout + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_TIMEUP(s) ((s) == APR_TIMEUP) +/** + * The operation was incomplete although some processing was performed + * and the results are partially valid. + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_INCOMPLETE(s) ((s) == APR_INCOMPLETE) +/* empty slot: +9 */ +/* empty slot: +10 */ +/* empty slot: +11 */ +/** + * Getopt found an option not in the option string + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_BADCH(s) ((s) == APR_BADCH) +/** + * Getopt found an option not in the option string and an argument was + * specified in the option string + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_BADARG(s) ((s) == APR_BADARG) +/** + * APR has encountered the end of the file + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_EOF(s) ((s) == APR_EOF) +/** + * APR was unable to find the socket in the poll structure + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_NOTFOUND(s) ((s) == APR_NOTFOUND) +/* empty slot: +16 */ +/* empty slot: +17 */ +/* empty slot: +18 */ +/** + * APR is using anonymous shared memory + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_ANONYMOUS(s) ((s) == APR_ANONYMOUS) +/** + * APR is using a file name as the key to the shared memory + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_FILEBASED(s) ((s) == APR_FILEBASED) +/** + * APR is using a shared key as the key to the shared memory + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_KEYBASED(s) ((s) == APR_KEYBASED) +/** + * Ininitalizer value. If no option has been found, but + * the status variable requires a value, this should be used + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_EINIT(s) ((s) == APR_EINIT) +/** + * The APR function has not been implemented on this + * platform, either because nobody has gotten to it yet, + * or the function is impossible on this platform. + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_ENOTIMPL(s) ((s) == APR_ENOTIMPL) +/** + * Two passwords do not match. + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_EMISMATCH(s) ((s) == APR_EMISMATCH) +/** + * The given lock was busy + * @warning always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_EBUSY(s) ((s) == APR_EBUSY) + +/** @} */ + +/** + * @addtogroup APR_Error APR Error Values + * @{ + */ +/* APR CANONICAL ERROR VALUES */ +/** @see APR_STATUS_IS_EACCES */ +#ifdef EACCES +#define APR_EACCES EACCES +#else +#define APR_EACCES (APR_OS_START_CANONERR + 1) +#endif + +/** @see APR_STATUS_IS_EEXIST */ +#ifdef EEXIST +#define APR_EEXIST EEXIST +#else +#define APR_EEXIST (APR_OS_START_CANONERR + 2) +#endif + +/** @see APR_STATUS_IS_ENAMETOOLONG */ +#ifdef ENAMETOOLONG +#define APR_ENAMETOOLONG ENAMETOOLONG +#else +#define APR_ENAMETOOLONG (APR_OS_START_CANONERR + 3) +#endif + +/** @see APR_STATUS_IS_ENOENT */ +#ifdef ENOENT +#define APR_ENOENT ENOENT +#else +#define APR_ENOENT (APR_OS_START_CANONERR + 4) +#endif + +/** @see APR_STATUS_IS_ENOTDIR */ +#ifdef ENOTDIR +#define APR_ENOTDIR ENOTDIR +#else +#define APR_ENOTDIR (APR_OS_START_CANONERR + 5) +#endif + +/** @see APR_STATUS_IS_ENOSPC */ +#ifdef ENOSPC +#define APR_ENOSPC ENOSPC +#else +#define APR_ENOSPC (APR_OS_START_CANONERR + 6) +#endif + +/** @see APR_STATUS_IS_ENOMEM */ +#ifdef ENOMEM +#define APR_ENOMEM ENOMEM +#else +#define APR_ENOMEM (APR_OS_START_CANONERR + 7) +#endif + +/** @see APR_STATUS_IS_EMFILE */ +#ifdef EMFILE +#define APR_EMFILE EMFILE +#else +#define APR_EMFILE (APR_OS_START_CANONERR + 8) +#endif + +/** @see APR_STATUS_IS_ENFILE */ +#ifdef ENFILE +#define APR_ENFILE ENFILE +#else +#define APR_ENFILE (APR_OS_START_CANONERR + 9) +#endif + +/** @see APR_STATUS_IS_EBADF */ +#ifdef EBADF +#define APR_EBADF EBADF +#else +#define APR_EBADF (APR_OS_START_CANONERR + 10) +#endif + +/** @see APR_STATUS_IS_EINVAL */ +#ifdef EINVAL +#define APR_EINVAL EINVAL +#else +#define APR_EINVAL (APR_OS_START_CANONERR + 11) +#endif + +/** @see APR_STATUS_IS_ESPIPE */ +#ifdef ESPIPE +#define APR_ESPIPE ESPIPE +#else +#define APR_ESPIPE (APR_OS_START_CANONERR + 12) +#endif + +/** + * @see APR_STATUS_IS_EAGAIN + * @warning use APR_STATUS_IS_EAGAIN instead of just testing this value + */ +#ifdef EAGAIN +#define APR_EAGAIN EAGAIN +#elif defined(EWOULDBLOCK) +#define APR_EAGAIN EWOULDBLOCK +#else +#define APR_EAGAIN (APR_OS_START_CANONERR + 13) +#endif + +/** @see APR_STATUS_IS_EINTR */ +#ifdef EINTR +#define APR_EINTR EINTR +#else +#define APR_EINTR (APR_OS_START_CANONERR + 14) +#endif + +/** @see APR_STATUS_IS_ENOTSOCK */ +#ifdef ENOTSOCK +#define APR_ENOTSOCK ENOTSOCK +#else +#define APR_ENOTSOCK (APR_OS_START_CANONERR + 15) +#endif + +/** @see APR_STATUS_IS_ECONNREFUSED */ +#ifdef ECONNREFUSED +#define APR_ECONNREFUSED ECONNREFUSED +#else +#define APR_ECONNREFUSED (APR_OS_START_CANONERR + 16) +#endif + +/** @see APR_STATUS_IS_EINPROGRESS */ +#ifdef EINPROGRESS +#define APR_EINPROGRESS EINPROGRESS +#else +#define APR_EINPROGRESS (APR_OS_START_CANONERR + 17) +#endif + +/** + * @see APR_STATUS_IS_ECONNABORTED + * @warning use APR_STATUS_IS_ECONNABORTED instead of just testing this value + */ + +#ifdef ECONNABORTED +#define APR_ECONNABORTED ECONNABORTED +#else +#define APR_ECONNABORTED (APR_OS_START_CANONERR + 18) +#endif + +/** @see APR_STATUS_IS_ECONNRESET */ +#ifdef ECONNRESET +#define APR_ECONNRESET ECONNRESET +#else +#define APR_ECONNRESET (APR_OS_START_CANONERR + 19) +#endif + +/** @see APR_STATUS_IS_ETIMEDOUT + * @deprecated */ +#ifdef ETIMEDOUT +#define APR_ETIMEDOUT ETIMEDOUT +#else +#define APR_ETIMEDOUT (APR_OS_START_CANONERR + 20) +#endif + +/** @see APR_STATUS_IS_EHOSTUNREACH */ +#ifdef EHOSTUNREACH +#define APR_EHOSTUNREACH EHOSTUNREACH +#else +#define APR_EHOSTUNREACH (APR_OS_START_CANONERR + 21) +#endif + +/** @see APR_STATUS_IS_ENETUNREACH */ +#ifdef ENETUNREACH +#define APR_ENETUNREACH ENETUNREACH +#else +#define APR_ENETUNREACH (APR_OS_START_CANONERR + 22) +#endif + +/** @see APR_STATUS_IS_EFTYPE */ +#ifdef EFTYPE +#define APR_EFTYPE EFTYPE +#else +#define APR_EFTYPE (APR_OS_START_CANONERR + 23) +#endif + +/** @see APR_STATUS_IS_EPIPE */ +#ifdef EPIPE +#define APR_EPIPE EPIPE +#else +#define APR_EPIPE (APR_OS_START_CANONERR + 24) +#endif + +/** @see APR_STATUS_IS_EXDEV */ +#ifdef EXDEV +#define APR_EXDEV EXDEV +#else +#define APR_EXDEV (APR_OS_START_CANONERR + 25) +#endif + +/** @see APR_STATUS_IS_ENOTEMPTY */ +#ifdef ENOTEMPTY +#define APR_ENOTEMPTY ENOTEMPTY +#else +#define APR_ENOTEMPTY (APR_OS_START_CANONERR + 26) +#endif + +/** @see APR_STATUS_IS_EAFNOSUPPORT */ +#ifdef EAFNOSUPPORT +#define APR_EAFNOSUPPORT EAFNOSUPPORT +#else +#define APR_EAFNOSUPPORT (APR_OS_START_CANONERR + 27) +#endif + +/** @see APR_STATUS_IS_EOPNOTSUPP */ +#ifdef EOPNOTSUPP +#define APR_EOPNOTSUPP EOPNOTSUPP +#else +#define APR_EOPNOTSUPP (APR_OS_START_CANONERR + 28) +#endif + +/** @see APR_STATUS_IS_ERANGE */ +#ifdef ERANGE +#define APR_ERANGE ERANGE +#else +#define APR_ERANGE (APR_OS_START_CANONERR + 29) +#endif + +/** @} */ + +#if defined(OS2) && !defined(DOXYGEN) + +#define APR_FROM_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e + APR_OS_START_SYSERR) +#define APR_TO_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e - APR_OS_START_SYSERR) + +#define INCL_DOSERRORS +#define INCL_DOS + +/* Leave these undefined. + * OS2 doesn't rely on the errno concept. + * The API calls always return a result codes which + * should be filtered through APR_FROM_OS_ERROR(). + * + * #define apr_get_os_error() (APR_FROM_OS_ERROR(GetLastError())) + * #define apr_set_os_error(e) (SetLastError(APR_TO_OS_ERROR(e))) + */ + +/* A special case, only socket calls require this; + */ +#define apr_get_netos_error() (APR_FROM_OS_ERROR(errno)) +#define apr_set_netos_error(e) (errno = APR_TO_OS_ERROR(e)) + +/* And this needs to be greped away for good: + */ +#define APR_OS2_STATUS(e) (APR_FROM_OS_ERROR(e)) + +/* These can't sit in a private header, so in spite of the extra size, + * they need to be made available here. + */ +#define SOCBASEERR 10000 +#define SOCEPERM (SOCBASEERR+1) /* Not owner */ +#define SOCESRCH (SOCBASEERR+3) /* No such process */ +#define SOCEINTR (SOCBASEERR+4) /* Interrupted system call */ +#define SOCENXIO (SOCBASEERR+6) /* No such device or address */ +#define SOCEBADF (SOCBASEERR+9) /* Bad file number */ +#define SOCEACCES (SOCBASEERR+13) /* Permission denied */ +#define SOCEFAULT (SOCBASEERR+14) /* Bad address */ +#define SOCEINVAL (SOCBASEERR+22) /* Invalid argument */ +#define SOCEMFILE (SOCBASEERR+24) /* Too many open files */ +#define SOCEPIPE (SOCBASEERR+32) /* Broken pipe */ +#define SOCEOS2ERR (SOCBASEERR+100) /* OS/2 Error */ +#define SOCEWOULDBLOCK (SOCBASEERR+35) /* Operation would block */ +#define SOCEINPROGRESS (SOCBASEERR+36) /* Operation now in progress */ +#define SOCEALREADY (SOCBASEERR+37) /* Operation already in progress */ +#define SOCENOTSOCK (SOCBASEERR+38) /* Socket operation on non-socket */ +#define SOCEDESTADDRREQ (SOCBASEERR+39) /* Destination address required */ +#define SOCEMSGSIZE (SOCBASEERR+40) /* Message too long */ +#define SOCEPROTOTYPE (SOCBASEERR+41) /* Protocol wrong type for socket */ +#define SOCENOPROTOOPT (SOCBASEERR+42) /* Protocol not available */ +#define SOCEPROTONOSUPPORT (SOCBASEERR+43) /* Protocol not supported */ +#define SOCESOCKTNOSUPPORT (SOCBASEERR+44) /* Socket type not supported */ +#define SOCEOPNOTSUPP (SOCBASEERR+45) /* Operation not supported on socket */ +#define SOCEPFNOSUPPORT (SOCBASEERR+46) /* Protocol family not supported */ +#define SOCEAFNOSUPPORT (SOCBASEERR+47) /* Address family not supported by protocol family */ +#define SOCEADDRINUSE (SOCBASEERR+48) /* Address already in use */ +#define SOCEADDRNOTAVAIL (SOCBASEERR+49) /* Can't assign requested address */ +#define SOCENETDOWN (SOCBASEERR+50) /* Network is down */ +#define SOCENETUNREACH (SOCBASEERR+51) /* Network is unreachable */ +#define SOCENETRESET (SOCBASEERR+52) /* Network dropped connection on reset */ +#define SOCECONNABORTED (SOCBASEERR+53) /* Software caused connection abort */ +#define SOCECONNRESET (SOCBASEERR+54) /* Connection reset by peer */ +#define SOCENOBUFS (SOCBASEERR+55) /* No buffer space available */ +#define SOCEISCONN (SOCBASEERR+56) /* Socket is already connected */ +#define SOCENOTCONN (SOCBASEERR+57) /* Socket is not connected */ +#define SOCESHUTDOWN (SOCBASEERR+58) /* Can't send after socket shutdown */ +#define SOCETOOMANYREFS (SOCBASEERR+59) /* Too many references: can't splice */ +#define SOCETIMEDOUT (SOCBASEERR+60) /* Connection timed out */ +#define SOCECONNREFUSED (SOCBASEERR+61) /* Connection refused */ +#define SOCELOOP (SOCBASEERR+62) /* Too many levels of symbolic links */ +#define SOCENAMETOOLONG (SOCBASEERR+63) /* File name too long */ +#define SOCEHOSTDOWN (SOCBASEERR+64) /* Host is down */ +#define SOCEHOSTUNREACH (SOCBASEERR+65) /* No route to host */ +#define SOCENOTEMPTY (SOCBASEERR+66) /* Directory not empty */ + +/* APR CANONICAL ERROR TESTS */ +#define APR_STATUS_IS_EACCES(s) ((s) == APR_EACCES \ + || (s) == APR_OS_START_SYSERR + ERROR_ACCESS_DENIED \ + || (s) == APR_OS_START_SYSERR + ERROR_SHARING_VIOLATION) +#define APR_STATUS_IS_EEXIST(s) ((s) == APR_EEXIST \ + || (s) == APR_OS_START_SYSERR + ERROR_OPEN_FAILED \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_EXISTS \ + || (s) == APR_OS_START_SYSERR + ERROR_ALREADY_EXISTS \ + || (s) == APR_OS_START_SYSERR + ERROR_ACCESS_DENIED) +#define APR_STATUS_IS_ENAMETOOLONG(s) ((s) == APR_ENAMETOOLONG \ + || (s) == APR_OS_START_SYSERR + ERROR_FILENAME_EXCED_RANGE \ + || (s) == APR_OS_START_SYSERR + SOCENAMETOOLONG) +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_PATH_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_MORE_FILES \ + || (s) == APR_OS_START_SYSERR + ERROR_OPEN_FAILED) +#define APR_STATUS_IS_ENOTDIR(s) ((s) == APR_ENOTDIR) +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC \ + || (s) == APR_OS_START_SYSERR + ERROR_DISK_FULL) +#define APR_STATUS_IS_ENOMEM(s) ((s) == APR_ENOMEM) +#define APR_STATUS_IS_EMFILE(s) ((s) == APR_EMFILE \ + || (s) == APR_OS_START_SYSERR + ERROR_TOO_MANY_OPEN_FILES) +#define APR_STATUS_IS_ENFILE(s) ((s) == APR_ENFILE) +#define APR_STATUS_IS_EBADF(s) ((s) == APR_EBADF \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_HANDLE) +#define APR_STATUS_IS_EINVAL(s) ((s) == APR_EINVAL \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_PARAMETER \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_FUNCTION) +#define APR_STATUS_IS_ESPIPE(s) ((s) == APR_ESPIPE \ + || (s) == APR_OS_START_SYSERR + ERROR_NEGATIVE_SEEK) +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_DATA \ + || (s) == APR_OS_START_SYSERR + SOCEWOULDBLOCK \ + || (s) == APR_OS_START_SYSERR + ERROR_LOCK_VIOLATION) +#define APR_STATUS_IS_EINTR(s) ((s) == APR_EINTR \ + || (s) == APR_OS_START_SYSERR + SOCEINTR) +#define APR_STATUS_IS_ENOTSOCK(s) ((s) == APR_ENOTSOCK \ + || (s) == APR_OS_START_SYSERR + SOCENOTSOCK) +#define APR_STATUS_IS_ECONNREFUSED(s) ((s) == APR_ECONNREFUSED \ + || (s) == APR_OS_START_SYSERR + SOCECONNREFUSED) +#define APR_STATUS_IS_EINPROGRESS(s) ((s) == APR_EINPROGRESS \ + || (s) == APR_OS_START_SYSERR + SOCEINPROGRESS) +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED \ + || (s) == APR_OS_START_SYSERR + SOCECONNABORTED) +#define APR_STATUS_IS_ECONNRESET(s) ((s) == APR_ECONNRESET \ + || (s) == APR_OS_START_SYSERR + SOCECONNRESET) +/* XXX deprecated */ +#define APR_STATUS_IS_ETIMEDOUT(s) ((s) == APR_ETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + SOCETIMEDOUT) +#undef APR_STATUS_IS_TIMEUP +#define APR_STATUS_IS_TIMEUP(s) ((s) == APR_TIMEUP \ + || (s) == APR_OS_START_SYSERR + SOCETIMEDOUT) +#define APR_STATUS_IS_EHOSTUNREACH(s) ((s) == APR_EHOSTUNREACH \ + || (s) == APR_OS_START_SYSERR + SOCEHOSTUNREACH) +#define APR_STATUS_IS_ENETUNREACH(s) ((s) == APR_ENETUNREACH \ + || (s) == APR_OS_START_SYSERR + SOCENETUNREACH) +#define APR_STATUS_IS_EFTYPE(s) ((s) == APR_EFTYPE) +#define APR_STATUS_IS_EPIPE(s) ((s) == APR_EPIPE \ + || (s) == APR_OS_START_SYSERR + ERROR_BROKEN_PIPE \ + || (s) == APR_OS_START_SYSERR + SOCEPIPE) +#define APR_STATUS_IS_EXDEV(s) ((s) == APR_EXDEV \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_SAME_DEVICE) +#define APR_STATUS_IS_ENOTEMPTY(s) ((s) == APR_ENOTEMPTY \ + || (s) == APR_OS_START_SYSERR + ERROR_DIR_NOT_EMPTY \ + || (s) == APR_OS_START_SYSERR + ERROR_ACCESS_DENIED) +#define APR_STATUS_IS_EAFNOSUPPORT(s) ((s) == APR_AFNOSUPPORT \ + || (s) == APR_OS_START_SYSERR + SOCEAFNOSUPPORT) +#define APR_STATUS_IS_EOPNOTSUPP(s) ((s) == APR_EOPNOTSUPP \ + || (s) == APR_OS_START_SYSERR + SOCEOPNOTSUPP) +#define APR_STATUS_IS_ERANGE(s) ((s) == APR_ERANGE) + +/* + Sorry, too tired to wrap this up for OS2... feel free to + fit the following into their best matches. + + { ERROR_NO_SIGNAL_SENT, ESRCH }, + { SOCEALREADY, EALREADY }, + { SOCEDESTADDRREQ, EDESTADDRREQ }, + { SOCEMSGSIZE, EMSGSIZE }, + { SOCEPROTOTYPE, EPROTOTYPE }, + { SOCENOPROTOOPT, ENOPROTOOPT }, + { SOCEPROTONOSUPPORT, EPROTONOSUPPORT }, + { SOCESOCKTNOSUPPORT, ESOCKTNOSUPPORT }, + { SOCEPFNOSUPPORT, EPFNOSUPPORT }, + { SOCEADDRINUSE, EADDRINUSE }, + { SOCEADDRNOTAVAIL, EADDRNOTAVAIL }, + { SOCENETDOWN, ENETDOWN }, + { SOCENETRESET, ENETRESET }, + { SOCENOBUFS, ENOBUFS }, + { SOCEISCONN, EISCONN }, + { SOCENOTCONN, ENOTCONN }, + { SOCESHUTDOWN, ESHUTDOWN }, + { SOCETOOMANYREFS, ETOOMANYREFS }, + { SOCELOOP, ELOOP }, + { SOCEHOSTDOWN, EHOSTDOWN }, + { SOCENOTEMPTY, ENOTEMPTY }, + { SOCEPIPE, EPIPE } +*/ + +#elif defined(WIN32) && !defined(DOXYGEN) /* !defined(OS2) */ + +#define APR_FROM_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e + APR_OS_START_SYSERR) +#define APR_TO_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e - APR_OS_START_SYSERR) + +#define apr_get_os_error() (APR_FROM_OS_ERROR(GetLastError())) +#define apr_set_os_error(e) (SetLastError(APR_TO_OS_ERROR(e))) + +/* A special case, only socket calls require this: + */ +#define apr_get_netos_error() (APR_FROM_OS_ERROR(WSAGetLastError())) +#define apr_set_netos_error(e) (WSASetLastError(APR_TO_OS_ERROR(e))) + +/* APR CANONICAL ERROR TESTS */ +#define APR_STATUS_IS_EACCES(s) ((s) == APR_EACCES \ + || (s) == APR_OS_START_SYSERR + ERROR_ACCESS_DENIED \ + || (s) == APR_OS_START_SYSERR + ERROR_CANNOT_MAKE \ + || (s) == APR_OS_START_SYSERR + ERROR_CURRENT_DIRECTORY \ + || (s) == APR_OS_START_SYSERR + ERROR_DRIVE_LOCKED \ + || (s) == APR_OS_START_SYSERR + ERROR_FAIL_I24 \ + || (s) == APR_OS_START_SYSERR + ERROR_LOCK_VIOLATION \ + || (s) == APR_OS_START_SYSERR + ERROR_LOCK_FAILED \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_LOCKED \ + || (s) == APR_OS_START_SYSERR + ERROR_NETWORK_ACCESS_DENIED \ + || (s) == APR_OS_START_SYSERR + ERROR_SHARING_VIOLATION) +#define APR_STATUS_IS_EEXIST(s) ((s) == APR_EEXIST \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_EXISTS \ + || (s) == APR_OS_START_SYSERR + ERROR_ALREADY_EXISTS) +#define APR_STATUS_IS_ENAMETOOLONG(s) ((s) == APR_ENAMETOOLONG \ + || (s) == APR_OS_START_SYSERR + ERROR_FILENAME_EXCED_RANGE \ + || (s) == APR_OS_START_SYSERR + WSAENAMETOOLONG) +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_PATH_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_OPEN_FAILED \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_MORE_FILES) +#define APR_STATUS_IS_ENOTDIR(s) ((s) == APR_ENOTDIR \ + || (s) == APR_OS_START_SYSERR + ERROR_PATH_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_NETPATH \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_NET_NAME \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_PATHNAME \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_DRIVE \ + || (s) == APR_OS_START_SYSERR + ERROR_DIRECTORY) +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC \ + || (s) == APR_OS_START_SYSERR + ERROR_DISK_FULL) +#define APR_STATUS_IS_ENOMEM(s) ((s) == APR_ENOMEM \ + || (s) == APR_OS_START_SYSERR + ERROR_ARENA_TRASHED \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_ENOUGH_MEMORY \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_BLOCK \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_ENOUGH_QUOTA \ + || (s) == APR_OS_START_SYSERR + ERROR_OUTOFMEMORY) +#define APR_STATUS_IS_EMFILE(s) ((s) == APR_EMFILE \ + || (s) == APR_OS_START_SYSERR + ERROR_TOO_MANY_OPEN_FILES) +#define APR_STATUS_IS_ENFILE(s) ((s) == APR_ENFILE) +#define APR_STATUS_IS_EBADF(s) ((s) == APR_EBADF \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_HANDLE \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_TARGET_HANDLE) +#define APR_STATUS_IS_EINVAL(s) ((s) == APR_EINVAL \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_ACCESS \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_DATA \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_FUNCTION \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_HANDLE \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_PARAMETER \ + || (s) == APR_OS_START_SYSERR + ERROR_NEGATIVE_SEEK) +#define APR_STATUS_IS_ESPIPE(s) ((s) == APR_ESPIPE \ + || (s) == APR_OS_START_SYSERR + ERROR_SEEK_ON_DEVICE \ + || (s) == APR_OS_START_SYSERR + ERROR_NEGATIVE_SEEK) +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_DATA \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_PROC_SLOTS \ + || (s) == APR_OS_START_SYSERR + ERROR_NESTING_NOT_ALLOWED \ + || (s) == APR_OS_START_SYSERR + ERROR_MAX_THRDS_REACHED \ + || (s) == APR_OS_START_SYSERR + ERROR_LOCK_VIOLATION \ + || (s) == APR_OS_START_SYSERR + WSAEWOULDBLOCK) +#define APR_STATUS_IS_EINTR(s) ((s) == APR_EINTR \ + || (s) == APR_OS_START_SYSERR + WSAEINTR) +#define APR_STATUS_IS_ENOTSOCK(s) ((s) == APR_ENOTSOCK \ + || (s) == APR_OS_START_SYSERR + WSAENOTSOCK) +#define APR_STATUS_IS_ECONNREFUSED(s) ((s) == APR_ECONNREFUSED \ + || (s) == APR_OS_START_SYSERR + WSAECONNREFUSED) +#define APR_STATUS_IS_EINPROGRESS(s) ((s) == APR_EINPROGRESS \ + || (s) == APR_OS_START_SYSERR + WSAEINPROGRESS) +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED \ + || (s) == APR_OS_START_SYSERR + WSAECONNABORTED) +#define APR_STATUS_IS_ECONNRESET(s) ((s) == APR_ECONNRESET \ + || (s) == APR_OS_START_SYSERR + ERROR_NETNAME_DELETED \ + || (s) == APR_OS_START_SYSERR + WSAECONNRESET) +/* XXX deprecated */ +#define APR_STATUS_IS_ETIMEDOUT(s) ((s) == APR_ETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WSAETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WAIT_TIMEOUT) +#undef APR_STATUS_IS_TIMEUP +#define APR_STATUS_IS_TIMEUP(s) ((s) == APR_TIMEUP \ + || (s) == APR_OS_START_SYSERR + WSAETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WAIT_TIMEOUT) +#define APR_STATUS_IS_EHOSTUNREACH(s) ((s) == APR_EHOSTUNREACH \ + || (s) == APR_OS_START_SYSERR + WSAEHOSTUNREACH) +#define APR_STATUS_IS_ENETUNREACH(s) ((s) == APR_ENETUNREACH \ + || (s) == APR_OS_START_SYSERR + WSAENETUNREACH) +#define APR_STATUS_IS_EFTYPE(s) ((s) == APR_EFTYPE \ + || (s) == APR_OS_START_SYSERR + ERROR_EXE_MACHINE_TYPE_MISMATCH \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_DLL \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_MODULETYPE \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_EXE_FORMAT \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_EXE_SIGNATURE \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_CORRUPT \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_FORMAT) +#define APR_STATUS_IS_EPIPE(s) ((s) == APR_EPIPE \ + || (s) == APR_OS_START_SYSERR + ERROR_BROKEN_PIPE) +#define APR_STATUS_IS_EXDEV(s) ((s) == APR_EXDEV \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_SAME_DEVICE) +#define APR_STATUS_IS_ENOTEMPTY(s) ((s) == APR_ENOTEMPTY \ + || (s) == APR_OS_START_SYSERR + ERROR_DIR_NOT_EMPTY) +#define APR_STATUS_IS_EAFNOSUPPORT(s) ((s) == APR_EAFNOSUPPORT \ + || (s) == APR_OS_START_SYSERR + WSAEAFNOSUPPORT) +#define APR_STATUS_IS_EOPNOTSUPP(s) ((s) == APR_EOPNOTSUPP \ + || (s) == APR_OS_START_SYSERR + WSAEOPNOTSUPP) +#define APR_STATUS_IS_ERANGE(s) ((s) == APR_ERANGE) + +#elif defined(NETWARE) && defined(USE_WINSOCK) && !defined(DOXYGEN) /* !defined(OS2) && !defined(WIN32) */ + +#define APR_FROM_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e + APR_OS_START_SYSERR) +#define APR_TO_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e - APR_OS_START_SYSERR) + +#define apr_get_os_error() (errno) +#define apr_set_os_error(e) (errno = (e)) + +/* A special case, only socket calls require this: */ +#define apr_get_netos_error() (APR_FROM_OS_ERROR(WSAGetLastError())) +#define apr_set_netos_error(e) (WSASetLastError(APR_TO_OS_ERROR(e))) + +/* APR CANONICAL ERROR TESTS */ +#define APR_STATUS_IS_EACCES(s) ((s) == APR_EACCES) +#define APR_STATUS_IS_EEXIST(s) ((s) == APR_EEXIST) +#define APR_STATUS_IS_ENAMETOOLONG(s) ((s) == APR_ENAMETOOLONG) +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT) +#define APR_STATUS_IS_ENOTDIR(s) ((s) == APR_ENOTDIR) +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC) +#define APR_STATUS_IS_ENOMEM(s) ((s) == APR_ENOMEM) +#define APR_STATUS_IS_EMFILE(s) ((s) == APR_EMFILE) +#define APR_STATUS_IS_ENFILE(s) ((s) == APR_ENFILE) +#define APR_STATUS_IS_EBADF(s) ((s) == APR_EBADF) +#define APR_STATUS_IS_EINVAL(s) ((s) == APR_EINVAL) +#define APR_STATUS_IS_ESPIPE(s) ((s) == APR_ESPIPE) + +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN \ + || (s) == EWOULDBLOCK \ + || (s) == APR_OS_START_SYSERR + WSAEWOULDBLOCK) +#define APR_STATUS_IS_EINTR(s) ((s) == APR_EINTR \ + || (s) == APR_OS_START_SYSERR + WSAEINTR) +#define APR_STATUS_IS_ENOTSOCK(s) ((s) == APR_ENOTSOCK \ + || (s) == APR_OS_START_SYSERR + WSAENOTSOCK) +#define APR_STATUS_IS_ECONNREFUSED(s) ((s) == APR_ECONNREFUSED \ + || (s) == APR_OS_START_SYSERR + WSAECONNREFUSED) +#define APR_STATUS_IS_EINPROGRESS(s) ((s) == APR_EINPROGRESS \ + || (s) == APR_OS_START_SYSERR + WSAEINPROGRESS) +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED \ + || (s) == APR_OS_START_SYSERR + WSAECONNABORTED) +#define APR_STATUS_IS_ECONNRESET(s) ((s) == APR_ECONNRESET \ + || (s) == APR_OS_START_SYSERR + WSAECONNRESET) +/* XXX deprecated */ +#define APR_STATUS_IS_ETIMEDOUT(s) ((s) == APR_ETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WSAETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WAIT_TIMEOUT) +#undef APR_STATUS_IS_TIMEUP +#define APR_STATUS_IS_TIMEUP(s) ((s) == APR_TIMEUP \ + || (s) == APR_OS_START_SYSERR + WSAETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WAIT_TIMEOUT) +#define APR_STATUS_IS_EHOSTUNREACH(s) ((s) == APR_EHOSTUNREACH \ + || (s) == APR_OS_START_SYSERR + WSAEHOSTUNREACH) +#define APR_STATUS_IS_ENETUNREACH(s) ((s) == APR_ENETUNREACH \ + || (s) == APR_OS_START_SYSERR + WSAENETUNREACH) +#define APR_STATUS_IS_ENETDOWN(s) ((s) == APR_OS_START_SYSERR + WSAENETDOWN) +#define APR_STATUS_IS_EFTYPE(s) ((s) == APR_EFTYPE) +#define APR_STATUS_IS_EPIPE(s) ((s) == APR_EPIPE) +#define APR_STATUS_IS_EXDEV(s) ((s) == APR_EXDEV) +#define APR_STATUS_IS_ENOTEMPTY(s) ((s) == APR_ENOTEMPTY) +#define APR_STATUS_IS_EAFNOSUPPORT(s) ((s) == APR_EAFNOSUPPORT \ + || (s) == APR_OS_START_SYSERR + WSAEAFNOSUPPORT) +#define APR_STATUS_IS_EOPNOTSUPP(s) ((s) == APR_EOPNOTSUPP \ + || (s) == APR_OS_START_SYSERR + WSAEOPNOTSUPP) +#define APR_STATUS_IS_ERANGE(s) ((s) == APR_ERANGE) + +#else /* !defined(NETWARE) && !defined(OS2) && !defined(WIN32) */ + +/* + * os error codes are clib error codes + */ +#define APR_FROM_OS_ERROR(e) (e) +#define APR_TO_OS_ERROR(e) (e) + +#define apr_get_os_error() (errno) +#define apr_set_os_error(e) (errno = (e)) + +/* A special case, only socket calls require this: + */ +#define apr_get_netos_error() (errno) +#define apr_set_netos_error(e) (errno = (e)) + +/** + * @addtogroup APR_STATUS_IS + * @{ + */ + +/** permission denied */ +#define APR_STATUS_IS_EACCES(s) ((s) == APR_EACCES) +/** file exists */ +#define APR_STATUS_IS_EEXIST(s) ((s) == APR_EEXIST) +/** path name is too long */ +#define APR_STATUS_IS_ENAMETOOLONG(s) ((s) == APR_ENAMETOOLONG) +/** + * no such file or directory + * @remark + * EMVSCATLG can be returned by the automounter on z/OS for + * paths which do not exist. + */ +#ifdef EMVSCATLG +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT \ + || (s) == EMVSCATLG) +#else +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT) +#endif +/** not a directory */ +#define APR_STATUS_IS_ENOTDIR(s) ((s) == APR_ENOTDIR) +/** no space left on device */ +#ifdef EDQUOT +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC \ + || (s) == EDQUOT) +#else +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC) +#endif +/** not enough memory */ +#define APR_STATUS_IS_ENOMEM(s) ((s) == APR_ENOMEM) +/** too many open files */ +#define APR_STATUS_IS_EMFILE(s) ((s) == APR_EMFILE) +/** file table overflow */ +#define APR_STATUS_IS_ENFILE(s) ((s) == APR_ENFILE) +/** bad file # */ +#define APR_STATUS_IS_EBADF(s) ((s) == APR_EBADF) +/** invalid argument */ +#define APR_STATUS_IS_EINVAL(s) ((s) == APR_EINVAL) +/** illegal seek */ +#define APR_STATUS_IS_ESPIPE(s) ((s) == APR_ESPIPE) + +/** operation would block */ +#if !defined(EWOULDBLOCK) || !defined(EAGAIN) +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN) +#elif (EWOULDBLOCK == EAGAIN) +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN) +#else +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN \ + || (s) == EWOULDBLOCK) +#endif + +/** interrupted system call */ +#define APR_STATUS_IS_EINTR(s) ((s) == APR_EINTR) +/** socket operation on a non-socket */ +#define APR_STATUS_IS_ENOTSOCK(s) ((s) == APR_ENOTSOCK) +/** Connection Refused */ +#define APR_STATUS_IS_ECONNREFUSED(s) ((s) == APR_ECONNREFUSED) +/** operation now in progress */ +#define APR_STATUS_IS_EINPROGRESS(s) ((s) == APR_EINPROGRESS) + +/** + * Software caused connection abort + * @remark + * EPROTO on certain older kernels really means ECONNABORTED, so we need to + * ignore it for them. See discussion in new-httpd archives nh.9701 & nh.9603 + * + * There is potentially a bug in Solaris 2.x x<6, and other boxes that + * implement tcp sockets in userland (i.e. on top of STREAMS). On these + * systems, EPROTO can actually result in a fatal loop. See PR#981 for + * example. It's hard to handle both uses of EPROTO. + */ +#ifdef EPROTO +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED \ + || (s) == EPROTO) +#else +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED) +#endif + +/** Connection Reset by peer */ +#define APR_STATUS_IS_ECONNRESET(s) ((s) == APR_ECONNRESET) +/** Operation timed out + * @deprecated */ +#define APR_STATUS_IS_ETIMEDOUT(s) ((s) == APR_ETIMEDOUT) +/** no route to host */ +#define APR_STATUS_IS_EHOSTUNREACH(s) ((s) == APR_EHOSTUNREACH) +/** network is unreachable */ +#define APR_STATUS_IS_ENETUNREACH(s) ((s) == APR_ENETUNREACH) +/** inappropriate file type or format */ +#define APR_STATUS_IS_EFTYPE(s) ((s) == APR_EFTYPE) +/** broken pipe */ +#define APR_STATUS_IS_EPIPE(s) ((s) == APR_EPIPE) +/** cross device link */ +#define APR_STATUS_IS_EXDEV(s) ((s) == APR_EXDEV) +/** Directory Not Empty */ +#define APR_STATUS_IS_ENOTEMPTY(s) ((s) == APR_ENOTEMPTY || \ + (s) == APR_EEXIST) +/** Address Family not supported */ +#define APR_STATUS_IS_EAFNOSUPPORT(s) ((s) == APR_EAFNOSUPPORT) +/** Socket operation not supported */ +#define APR_STATUS_IS_EOPNOTSUPP(s) ((s) == APR_EOPNOTSUPP) + +/** Numeric value not representable */ +#define APR_STATUS_IS_ERANGE(s) ((s) == APR_ERANGE) +/** @} */ + +#endif /* !defined(NETWARE) && !defined(OS2) && !defined(WIN32) */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_ERRNO_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_escape.h b/c/dependencies/windows/apr/x64_debug/include/apr_escape.h new file mode 100644 index 00000000..ed048c95 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_escape.h @@ -0,0 +1,431 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file apr_escape.h + * @brief APR-UTIL Escaping + */ +#ifndef APR_ESCAPE_H +#define APR_ESCAPE_H +#include "apr.h" +#include "apr_general.h" +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Escaping Escape functions + * @ingroup APR + * @{ + */ + +/* Simple escape/unescape functions. + * + * The design goal of these functions are: + * + * - Avoid unnecessary work. + * + * In most cases the strings passed in do not need to be escaped at all. In + * these cases the original string will be returned. + * + * - Lowest possible memory footprint. + * + * The amount of memory allocated for a given encoding is calculated based + * on the exact amount of memory needed, and not the theoretical worst case + * scenario. + * + */ + +/** + * When passing a string to one of the escape functions, this value can be + * passed to indicate a string-valued key, and have the length computed + * automatically. + */ +#define APR_ESCAPE_STRING (-1) + +/** + * Apply LDAP distinguished name escaping as per RFC4514. + */ +#define APR_ESCAPE_LDAP_DN (0x01) + +/** + * Apply LDAP filter escaping as per RFC4515. + */ +#define APR_ESCAPE_LDAP_FILTER (0x02) + +/** + * Apply both RFC4514 and RFC4515 LDAP escaping. + */ +#define APR_ESCAPE_LDAP_ALL (0x03) + +/** + * Perform shell escaping on the provided string. + * + * Shell escaping causes characters to be prefixed with a '\' character. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_shell(char *escaped, const char *str, + apr_ssize_t slen, apr_size_t *len); + +/** + * Perform shell escaping on the provided string, returning the result + * from the pool. + * + * Shell escaping causes characters to be prefixed with a '\' character. + * + * If no characters were escaped, the original string is returned. + * @param p Pool to allocate from + * @param str The original string + * @return the encoded string, allocated from the pool, or the original + * string if no escaping took place or the string was NULL. + */ +APR_DECLARE(const char *) apr_pescape_shell(apr_pool_t *p, const char *str) + __attribute__((nonnull(1))); + +/** + * Unescapes a URL, leaving reserved characters intact. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param url String to be unescaped + * @param slen The length of the original url, or APR_ESCAPE_STRING + * @param forbid Optional list of forbidden characters, in addition to + * 0x00 + * @param reserved Optional list of reserved characters that will be + * left unescaped + * @param plus If non zero, '+' is converted to ' ' as per + * application/x-www-form-urlencoded encoding + * @param len If set, the length of the escaped string will be returned + * @return APR_SUCCESS on success, APR_NOTFOUND if no characters are + * decoded or the string is NULL, APR_EINVAL if a bad escape sequence is + * found, APR_BADCH if a character on the forbid list is found. + */ +APR_DECLARE(apr_status_t) apr_unescape_url(char *escaped, const char *url, + apr_ssize_t slen, const char *forbid, const char *reserved, int plus, + apr_size_t *len); + +/** + * Unescapes a URL, leaving reserved characters intact, returning the + * result from a pool. + * @param p Pool to allocate from + * @param url String to be unescaped in place + * @param forbid Optional list of forbidden characters, in addition to + * 0x00 + * @param reserved Optional list of reserved characters that will be + * left unescaped + * @param plus If non zero, '+' is converted to ' ' as per + * application/x-www-form-urlencoded encoding + * @return A string allocated from the pool on success, the original string + * if no characters are decoded, or NULL if a bad escape sequence is found + * or if a character on the forbid list is found, or if the original string + * was NULL. + */ +APR_DECLARE(const char *) apr_punescape_url(apr_pool_t *p, const char *url, + const char *forbid, const char *reserved, int plus) + __attribute__((nonnull(1))); + +/** + * Escape a path segment, as defined in RFC1808. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_path_segment(char *escaped, + const char *str, apr_ssize_t slen, apr_size_t *len); + +/** + * Escape a path segment, as defined in RFC1808, returning the result from a + * pool. + * @param p Pool to allocate from + * @param str String to be escaped + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or the string is NULL. + */ +APR_DECLARE(const char *) apr_pescape_path_segment(apr_pool_t *p, + const char *str) __attribute__((nonnull(1))); + +/** + * Converts an OS path to a URL, in an OS dependent way, as defined in RFC1808. + * In all cases if a ':' occurs before the first '/' in the URL, the URL should + * be prefixed with "./" (or the ':' escaped). In the case of Unix, this means + * leaving '/' alone, but otherwise doing what escape_path_segment() does. For + * efficiency reasons, we don't use escape_path_segment(), which is provided for + * reference. Again, RFC 1808 is where this stuff is defined. + * + * If partial is set, os_escape_path() assumes that the path will be appended to + * something with a '/' in it (and thus does not prefix "./"). + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param path The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param partial If non zero, suppresses the prepending of "./" + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or if the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_path(char *escaped, const char *path, + apr_ssize_t slen, int partial, apr_size_t *len); + +/** + * Converts an OS path to a URL, in an OS dependent way, as defined in RFC1808, + * returning the result from a pool. + * + * In all cases if a ':' occurs before the first '/' in the URL, the URL should + * be prefixed with "./" (or the ':' escaped). In the case of Unix, this means + * leaving '/' alone, but otherwise doing what escape_path_segment() does. For + * efficiency reasons, we don't use escape_path_segment(), which is provided for + * reference. Again, RFC 1808 is where this stuff is defined. + * + * If partial is set, os_escape_path() assumes that the path will be appended to + * something with a '/' in it (and thus does not prefix "./"). + * @param p Pool to allocate from + * @param str The original string + * @param partial If non zero, suppresses the prepending of "./" + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or if the string was NULL. + */ +APR_DECLARE(const char *) apr_pescape_path(apr_pool_t *p, const char *str, + int partial) __attribute__((nonnull(1))); + +/** + * Urlencode a string, as defined in + * http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or if the stirng was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_urlencoded(char *escaped, const char *str, + apr_ssize_t slen, apr_size_t *len); + +/** + * Urlencode a string, as defined in + * http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1, returning + * the result from a pool. + * @param p Pool to allocate from + * @param str String to be escaped + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or if the string was NULL. + */ +APR_DECLARE(const char *) apr_pescape_urlencoded(apr_pool_t *p, + const char *str) __attribute__((nonnull(1))); + +/** + * Apply entity encoding to a string. Characters are replaced as follows: + * '<' becomes '\<', '>' becomes '\>', '&' becomes '\&', the + * double quote becomes '\"" and the single quote becomes '\''. + * + * If toasc is not zero, any non ascii character will be encoded as + * '%\#ddd;', where ddd is the decimal code of the character. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param toasc If non zero, encode non ascii characters + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_entity(char *escaped, const char *str, + apr_ssize_t slen, int toasc, apr_size_t *len); + +/** + * Apply entity encoding to a string, returning the result from a pool. + * Characters are replaced as follows: '<' becomes '\<', '>' becomes + * '\>', '&' becomes '\&', the double quote becomes '\"" and the + * single quote becomes '\''. + * @param p Pool to allocate from + * @param str The original string + * @param toasc If non zero, encode non ascii characters + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or the string is NULL. + */ +APR_DECLARE(const char *) apr_pescape_entity(apr_pool_t *p, const char *str, + int toasc) __attribute__((nonnull(1))); + +/** + * Decodes html entities or numeric character references in a string. If + * the string to be unescaped is syntactically incorrect, then the + * following fixups will be made: + * unknown entities will be left undecoded; + * references to unused numeric characters will be deleted. + * In particular, � will not be decoded, but will be deleted. + * @param unescaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_unescape_entity(char *unescaped, const char *str, + apr_ssize_t slen, apr_size_t *len); + +/** + * Decodes html entities or numeric character references in a string. If + * the string to be unescaped is syntactically incorrect, then the + * following fixups will be made: + * unknown entities will be left undecoded; + * references to unused numeric characters will be deleted. + * In particular, � will not be decoded, but will be deleted. + * @param p Pool to allocate from + * @param str The original string + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or the string is NULL. + */ +APR_DECLARE(const char *) apr_punescape_entity(apr_pool_t *p, const char *str) + __attribute__((nonnull(1))); + +/** + * Escape control characters in a string, as performed by the shell's + * 'echo' command. Characters are replaced as follows: + * \\a alert (bell), \\b backspace, \\f form feed, \\n new line, \\r carriage + * return, \\t horizontal tab, \\v vertical tab, \\ backslash. + * + * Any non ascii character will be encoded as '\\xHH', where HH is the hex + * code of the character. + * + * If quote is not zero, the double quote character will also be escaped. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param quote If non zero, encode double quotes + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_echo(char *escaped, const char *str, + apr_ssize_t slen, int quote, apr_size_t *len); + +/** + * Escape control characters in a string, as performed by the shell's + * 'echo' command, and return the results from a pool. Characters are + * replaced as follows: \\a alert (bell), \\b backspace, \\f form feed, + * \\n new line, \\r carriage return, \\t horizontal tab, \\v vertical tab, + * \\ backslash. + * + * Any non ascii character will be encoded as '\\xHH', where HH is the hex + * code of the character. + * + * If quote is not zero, the double quote character will also be escaped. + * @param p Pool to allocate from + * @param str The original string + * @param quote If non zero, encode double quotes + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or the string is NULL. + */ +APR_DECLARE(const char *) apr_pescape_echo(apr_pool_t *p, const char *str, + int quote); + +/** + * Convert binary data to a hex encoding. + * @param dest The destination buffer, can be NULL + * @param src The original buffer + * @param srclen The length of the original buffer + * @param colon If not zero, insert colon characters between hex digits. + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_hex(char *dest, const void *src, + apr_size_t srclen, int colon, apr_size_t *len); + +/** + * Convert binary data to a hex encoding, and return the results from a + * pool. + * @param p Pool to allocate from + * @param src The original buffer + * @param slen The length of the original buffer + * @param colon If not zero, insert colon characters between hex digits. + * @return A zero padded buffer allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *) apr_pescape_hex(apr_pool_t *p, const void *src, + apr_size_t slen, int colon) __attribute__((nonnull(1))); + +/** + * Convert hex encoded string to binary data. + * @param dest The destination buffer, can be NULL + * @param str The original buffer + * @param slen The length of the original buffer + * @param colon If not zero, ignore colon characters between hex digits. + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL, or APR_BADCH + * if a non hex character is present. + */ +APR_DECLARE(apr_status_t) apr_unescape_hex(void *dest, const char *str, + apr_ssize_t slen, int colon, apr_size_t *len); + +/** + * Convert hex encoding to binary data, and return the results from a pool. + * If the colon character appears between pairs of hex digits, it will be + * ignored. + * @param p Pool to allocate from + * @param str The original string + * @param colon If not zero, ignore colon characters between hex digits. + * @param len If present, returns the length of the final buffer + * @return A buffer allocated from the pool on success, or NULL if src was + * NULL, or a bad character was present. + */ +APR_DECLARE(const void *) apr_punescape_hex(apr_pool_t *p, const char *str, + int colon, apr_size_t *len); + +/** + * Apply LDAP escaping to binary data. Characters from RFC4514 and RFC4515 + * are escaped with their hex equivalents. + * @param dest The destination buffer, can be NULL + * @param src The original buffer + * @param srclen The length of the original buffer + * @param flags APR_ESCAPE_LDAP_DN for RFC4514, APR_ESCAPE_LDAP_FILTER for + * RFC4515, APR_ESCAPE_LDAP_ALL for both + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_ldap(char *dest, const void *src, + apr_ssize_t srclen, int flags, apr_size_t *len); + +/** + * Apply LDAP escaping to binary data, and return the results from a + * pool. Characters from RFC4514 and RFC4515 are escaped with their hex + * equivalents. + * @param p Pool to allocate from + * @param src The original buffer + * @param slen The length of the original buffer + * @param flags APR_ESCAPE_LDAP_DN for RFC4514, APR_ESCAPE_LDAP_FILTER for + * RFC4515, APR_ESCAPE_LDAP_ALL for both + * @return A zero padded buffer allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *) apr_pescape_ldap(apr_pool_t *p, const void *src, + apr_ssize_t slen, int flags) __attribute__((nonnull(1))); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ESCAPE_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_escape_test_char.h b/c/dependencies/windows/apr/x64_debug/include/apr_escape_test_char.h new file mode 100644 index 00000000..ad36c615 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_escape_test_char.h @@ -0,0 +1,25 @@ +/* this file is automatically generated by gen_test_char, do not edit. "make include/private/apr_escape_test_char.h" to regenerate. */ +#define T_ESCAPE_SHELL_CMD (1) +#define T_ESCAPE_PATH_SEGMENT (2) +#define T_OS_ESCAPE_PATH (4) +#define T_ESCAPE_ECHO (8) +#define T_ESCAPE_URLENCODED (16) +#define T_ESCAPE_XML (32) +#define T_ESCAPE_LDAP_DN (64) +#define T_ESCAPE_LDAP_FILTER (128) + +static const unsigned char test_char_table[256] = { + 224,222,222,222,222,222,222,222,222,222,223,222,222,223,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,6,16,127,22,17,23,49,17, + 145,145,129,80,80,0,0,18,0,0,0,0,0,0,0,0,0,0,16,87, + 119,16,119,23,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,23,223,23,23,0,23,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,23,23,23,17,222,222,222,222,222,222,222,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222 +}; diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_file_info.h b/c/dependencies/windows/apr/x64_debug/include/apr_file_info.h new file mode 100644 index 00000000..cfddc68d --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_file_info.h @@ -0,0 +1,428 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_FILE_INFO_H +#define APR_FILE_INFO_H + +/** + * @file apr_file_info.h + * @brief APR File Information + */ + +#include "apr.h" +#include "apr_user.h" +#include "apr_pools.h" +#include "apr_tables.h" +#include "apr_time.h" +#include "apr_errno.h" + +#if APR_HAVE_SYS_UIO_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_file_info File Information + * @ingroup APR + * @{ + */ + +/* Many applications use the type member to determine the + * existance of a file or initialization of the file info, + * so the APR_NOFILE value must be distinct from APR_UNKFILE. + */ + +/** apr_filetype_e values for the filetype member of the + * apr_file_info_t structure + * @warning Not all of the filetypes below can be determined. + * For example, a given platform might not correctly report + * a socket descriptor as APR_SOCK if that type isn't + * well-identified on that platform. In such cases where + * a filetype exists but cannot be described by the recognized + * flags below, the filetype will be APR_UNKFILE. If the + * filetype member is not determined, the type will be APR_NOFILE. + */ + +typedef enum { + APR_NOFILE = 0, /**< no file type determined */ + APR_REG, /**< a regular file */ + APR_DIR, /**< a directory */ + APR_CHR, /**< a character device */ + APR_BLK, /**< a block device */ + APR_PIPE, /**< a FIFO / pipe */ + APR_LNK, /**< a symbolic link */ + APR_SOCK, /**< a [unix domain] socket */ + APR_UNKFILE = 127 /**< a file of some other unknown type */ +} apr_filetype_e; + +/** + * @defgroup apr_file_permissions File Permissions flags + * @{ + */ + +#define APR_FPROT_USETID 0x8000 /**< Set user id */ +#define APR_FPROT_UREAD 0x0400 /**< Read by user */ +#define APR_FPROT_UWRITE 0x0200 /**< Write by user */ +#define APR_FPROT_UEXECUTE 0x0100 /**< Execute by user */ + +#define APR_FPROT_GSETID 0x4000 /**< Set group id */ +#define APR_FPROT_GREAD 0x0040 /**< Read by group */ +#define APR_FPROT_GWRITE 0x0020 /**< Write by group */ +#define APR_FPROT_GEXECUTE 0x0010 /**< Execute by group */ + +#define APR_FPROT_WSTICKY 0x2000 /**< Sticky bit */ +#define APR_FPROT_WREAD 0x0004 /**< Read by others */ +#define APR_FPROT_WWRITE 0x0002 /**< Write by others */ +#define APR_FPROT_WEXECUTE 0x0001 /**< Execute by others */ + +#define APR_FPROT_OS_DEFAULT 0x0FFF /**< use OS's default permissions */ + +/* additional permission flags for apr_file_copy and apr_file_append */ +#define APR_FPROT_FILE_SOURCE_PERMS 0x1000 /**< Copy source file's permissions */ + +/* backcompat */ +#define APR_USETID APR_FPROT_USETID /**< @deprecated @see APR_FPROT_USETID */ +#define APR_UREAD APR_FPROT_UREAD /**< @deprecated @see APR_FPROT_UREAD */ +#define APR_UWRITE APR_FPROT_UWRITE /**< @deprecated @see APR_FPROT_UWRITE */ +#define APR_UEXECUTE APR_FPROT_UEXECUTE /**< @deprecated @see APR_FPROT_UEXECUTE */ +#define APR_GSETID APR_FPROT_GSETID /**< @deprecated @see APR_FPROT_GSETID */ +#define APR_GREAD APR_FPROT_GREAD /**< @deprecated @see APR_FPROT_GREAD */ +#define APR_GWRITE APR_FPROT_GWRITE /**< @deprecated @see APR_FPROT_GWRITE */ +#define APR_GEXECUTE APR_FPROT_GEXECUTE /**< @deprecated @see APR_FPROT_GEXECUTE */ +#define APR_WSTICKY APR_FPROT_WSTICKY /**< @deprecated @see APR_FPROT_WSTICKY */ +#define APR_WREAD APR_FPROT_WREAD /**< @deprecated @see APR_FPROT_WREAD */ +#define APR_WWRITE APR_FPROT_WWRITE /**< @deprecated @see APR_FPROT_WWRITE */ +#define APR_WEXECUTE APR_FPROT_WEXECUTE /**< @deprecated @see APR_FPROT_WEXECUTE */ +#define APR_OS_DEFAULT APR_FPROT_OS_DEFAULT /**< @deprecated @see APR_FPROT_OS_DEFAULT */ +#define APR_FILE_SOURCE_PERMS APR_FPROT_FILE_SOURCE_PERMS /**< @deprecated @see APR_FPROT_FILE_SOURCE_PERMS */ + +/** @} */ + + +/** + * Structure for referencing directories. + */ +typedef struct apr_dir_t apr_dir_t; +/** + * Structure for determining file permissions. + */ +typedef apr_int32_t apr_fileperms_t; +#if (defined WIN32) || (defined NETWARE) +/** + * Structure for determining the device the file is on. + */ +typedef apr_uint32_t apr_dev_t; +#else +/** + * Structure for determining the device the file is on. + */ +typedef dev_t apr_dev_t; +#endif + +/** + * @defgroup apr_file_stat Stat Functions + * @{ + */ +/** file info structure */ +typedef struct apr_finfo_t apr_finfo_t; + +#define APR_FINFO_LINK 0x00000001 /**< Stat the link not the file itself if it is a link */ +#define APR_FINFO_MTIME 0x00000010 /**< Modification Time */ +#define APR_FINFO_CTIME 0x00000020 /**< Creation or inode-changed time */ +#define APR_FINFO_ATIME 0x00000040 /**< Access Time */ +#define APR_FINFO_SIZE 0x00000100 /**< Size of the file */ +#define APR_FINFO_CSIZE 0x00000200 /**< Storage size consumed by the file */ +#define APR_FINFO_DEV 0x00001000 /**< Device */ +#define APR_FINFO_INODE 0x00002000 /**< Inode */ +#define APR_FINFO_NLINK 0x00004000 /**< Number of links */ +#define APR_FINFO_TYPE 0x00008000 /**< Type */ +#define APR_FINFO_USER 0x00010000 /**< User */ +#define APR_FINFO_GROUP 0x00020000 /**< Group */ +#define APR_FINFO_UPROT 0x00100000 /**< User protection bits */ +#define APR_FINFO_GPROT 0x00200000 /**< Group protection bits */ +#define APR_FINFO_WPROT 0x00400000 /**< World protection bits */ +#define APR_FINFO_ICASE 0x01000000 /**< if dev is case insensitive */ +#define APR_FINFO_NAME 0x02000000 /**< ->name in proper case */ + +#define APR_FINFO_MIN 0x00008170 /**< type, mtime, ctime, atime, size */ +#define APR_FINFO_IDENT 0x00003000 /**< dev and inode */ +#define APR_FINFO_OWNER 0x00030000 /**< user and group */ +#define APR_FINFO_PROT 0x00700000 /**< all protections */ +#define APR_FINFO_NORM 0x0073b170 /**< an atomic unix apr_stat() */ +#define APR_FINFO_DIRENT 0x02000000 /**< an atomic unix apr_dir_read() */ + +/** + * The file information structure. This is analogous to the POSIX + * stat structure. + */ +struct apr_finfo_t { + /** Allocates memory and closes lingering handles in the specified pool */ + apr_pool_t *pool; + /** The bitmask describing valid fields of this apr_finfo_t structure + * including all available 'wanted' fields and potentially more */ + apr_int32_t valid; + /** The access permissions of the file. Mimics Unix access rights. */ + apr_fileperms_t protection; + /** The type of file. One of APR_REG, APR_DIR, APR_CHR, APR_BLK, APR_PIPE, + * APR_LNK or APR_SOCK. If the type is undetermined, the value is APR_NOFILE. + * If the type cannot be determined, the value is APR_UNKFILE. + */ + apr_filetype_e filetype; + /** The user id that owns the file */ + apr_uid_t user; + /** The group id that owns the file */ + apr_gid_t group; + /** The inode of the file. */ + apr_ino_t inode; + /** The id of the device the file is on. */ + apr_dev_t device; + /** The number of hard links to the file. */ + apr_int32_t nlink; + /** The size of the file */ + apr_off_t size; + /** The storage size consumed by the file */ + apr_off_t csize; + /** The time the file was last accessed */ + apr_time_t atime; + /** The time the file was last modified */ + apr_time_t mtime; + /** The time the file was created, or the inode was last changed */ + apr_time_t ctime; + /** The pathname of the file (possibly unrooted) */ + const char *fname; + /** The file's name (no path) in filesystem case */ + const char *name; + /** Unused */ + struct apr_file_t *filehand; +}; + +/** + * get the specified file's stats. The file is specified by filename, + * instead of using a pre-opened file. + * @param finfo Where to store the information about the file, which is + * never touched if the call fails. + * @param fname The name of the file to stat. + * @param wanted The desired apr_finfo_t fields, as a bit flag of APR_FINFO_ + values + * @param pool the pool to use to allocate the new file. + * + * @note If @c APR_INCOMPLETE is returned all the fields in @a finfo may + * not be filled in, and you need to check the @c finfo->valid bitmask + * to verify that what you're looking for is there. + */ +APR_DECLARE(apr_status_t) apr_stat(apr_finfo_t *finfo, const char *fname, + apr_int32_t wanted, apr_pool_t *pool); + +/** @} */ +/** + * @defgroup apr_dir Directory Manipulation Functions + * @{ + */ + +/** + * Open the specified directory. + * @param new_dir The opened directory descriptor. + * @param dirname The full path to the directory (use / on all systems) + * @param pool The pool to use. + */ +APR_DECLARE(apr_status_t) apr_dir_open(apr_dir_t **new_dir, + const char *dirname, + apr_pool_t *pool); + +/** + * close the specified directory. + * @param thedir the directory descriptor to close. + */ +APR_DECLARE(apr_status_t) apr_dir_close(apr_dir_t *thedir); + +/** + * Read the next entry from the specified directory. + * @param finfo the file info structure and filled in by apr_dir_read + * @param wanted The desired apr_finfo_t fields, as a bit flag of APR_FINFO_ + values + * @param thedir the directory descriptor returned from apr_dir_open + * @remark No ordering is guaranteed for the entries read. + * + * @note If @c APR_INCOMPLETE is returned all the fields in @a finfo may + * not be filled in, and you need to check the @c finfo->valid bitmask + * to verify that what you're looking for is there. When no more + * entries are available, APR_ENOENT is returned. + */ +APR_DECLARE(apr_status_t) apr_dir_read(apr_finfo_t *finfo, apr_int32_t wanted, + apr_dir_t *thedir); + +/** + * Rewind the directory to the first entry. + * @param thedir the directory descriptor to rewind. + */ +APR_DECLARE(apr_status_t) apr_dir_rewind(apr_dir_t *thedir); +/** @} */ + +/** + * @defgroup apr_filepath Filepath Manipulation Functions + * @{ + */ + +/** Cause apr_filepath_merge to fail if addpath is above rootpath + * @bug in APR 0.9 and 1.x, this flag's behavior is undefined + * if the rootpath is NULL or empty. In APR 2.0 this should be + * changed to imply NOTABSOLUTE if the rootpath is NULL or empty. + */ +#define APR_FILEPATH_NOTABOVEROOT 0x01 + +/** internal: Only meaningful with APR_FILEPATH_NOTABOVEROOT */ +#define APR_FILEPATH_SECUREROOTTEST 0x02 + +/** Cause apr_filepath_merge to fail if addpath is above rootpath, + * even given a rootpath /foo/bar and an addpath ../bar/bash + */ +#define APR_FILEPATH_SECUREROOT 0x03 + +/** Fail apr_filepath_merge if the merged path is relative */ +#define APR_FILEPATH_NOTRELATIVE 0x04 + +/** Fail apr_filepath_merge if the merged path is absolute */ +#define APR_FILEPATH_NOTABSOLUTE 0x08 + +/** Return the file system's native path format (e.g. path delimiters + * of ':' on MacOS9, '\' on Win32, etc.) */ +#define APR_FILEPATH_NATIVE 0x10 + +/** Resolve the true case of existing directories and file elements + * of addpath, (resolving any aliases on Win32) and append a proper + * trailing slash if a directory + */ +#define APR_FILEPATH_TRUENAME 0x20 + +/** + * Extract the rootpath from the given filepath + * @param rootpath the root file path returned with APR_SUCCESS or APR_EINCOMPLETE + * @param filepath the pathname to parse for its root component + * @param flags the desired rules to apply, from + *
+ *      APR_FILEPATH_NATIVE    Use native path separators (e.g. '\' on Win32)
+ *      APR_FILEPATH_TRUENAME  Tests that the root exists, and makes it proper
+ * 
+ * @param p the pool to allocate the new path string from + * @remark on return, filepath points to the first non-root character in the + * given filepath. In the simplest example, given a filepath of "/foo", + * returns the rootpath of "/" and filepath points at "foo". This is far + * more complex on other platforms, which will canonicalize the root form + * to a consistant format, given the APR_FILEPATH_TRUENAME flag, and also + * test for the validity of that root (e.g., that a drive d:/ or network + * share //machine/foovol/). + * The function returns APR_ERELATIVE if filepath isn't rooted (an + * error), APR_EINCOMPLETE if the root path is ambiguous (but potentially + * legitimate, e.g. "/" on Windows is incomplete because it doesn't specify + * the drive letter), or APR_EBADPATH if the root is simply invalid. + * APR_SUCCESS is returned if filepath is an absolute path. + */ +APR_DECLARE(apr_status_t) apr_filepath_root(const char **rootpath, + const char **filepath, + apr_int32_t flags, + apr_pool_t *p); + +/** + * Merge additional file path onto the previously processed rootpath + * @param newpath the merged paths returned + * @param rootpath the root file path (NULL uses the current working path) + * @param addpath the path to add to the root path + * @param flags the desired APR_FILEPATH_ rules to apply when merging + * @param p the pool to allocate the new path string from + * @remark if the flag APR_FILEPATH_TRUENAME is given, and the addpath + * contains wildcard characters ('*', '?') on platforms that don't support + * such characters within filenames, the paths will be merged, but the + * result code will be APR_EPATHWILD, and all further segments will not + * reflect the true filenames including the wildcard and following segments. + */ +APR_DECLARE(apr_status_t) apr_filepath_merge(char **newpath, + const char *rootpath, + const char *addpath, + apr_int32_t flags, + apr_pool_t *p); + +/** + * Split a search path into separate components + * @param pathelts the returned components of the search path + * @param liststr the search path (e.g., getenv("PATH")) + * @param p the pool to allocate the array and path components from + * @remark empty path components do not become part of @a pathelts. + * @remark the path separator in @a liststr is system specific; + * e.g., ':' on Unix, ';' on Windows, etc. + */ +APR_DECLARE(apr_status_t) apr_filepath_list_split(apr_array_header_t **pathelts, + const char *liststr, + apr_pool_t *p); + +/** + * Merge a list of search path components into a single search path + * @param liststr the returned search path; may be NULL if @a pathelts is empty + * @param pathelts the components of the search path + * @param p the pool to allocate the search path from + * @remark emtpy strings in the source array are ignored. + * @remark the path separator in @a liststr is system specific; + * e.g., ':' on Unix, ';' on Windows, etc. + */ +APR_DECLARE(apr_status_t) apr_filepath_list_merge(char **liststr, + apr_array_header_t *pathelts, + apr_pool_t *p); + +/** + * Return the default file path (for relative file names) + * @param path the default path string returned + * @param flags optional flag APR_FILEPATH_NATIVE to retrieve the + * default file path in os-native format. + * @param p the pool to allocate the default path string from + */ +APR_DECLARE(apr_status_t) apr_filepath_get(char **path, apr_int32_t flags, + apr_pool_t *p); + +/** + * Set the default file path (for relative file names) + * @param path the default path returned + * @param p the pool to allocate any working storage + */ +APR_DECLARE(apr_status_t) apr_filepath_set(const char *path, apr_pool_t *p); + +/** The FilePath character encoding is unknown */ +#define APR_FILEPATH_ENCODING_UNKNOWN 0 + +/** The FilePath character encoding is locale-dependent */ +#define APR_FILEPATH_ENCODING_LOCALE 1 + +/** The FilePath character encoding is UTF-8 */ +#define APR_FILEPATH_ENCODING_UTF8 2 + +/** + * Determine the encoding used internally by the FilePath functions + * @param style points to a variable which receives the encoding style flag + * @param p the pool to allocate any working storage + * @remark Use apr_os_locale_encoding() and/or apr_os_default_encoding() + * to get the name of the path encoding if it's not UTF-8. + */ +APR_DECLARE(apr_status_t) apr_filepath_encoding(int *style, apr_pool_t *p); +/** @} */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_FILE_INFO_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_file_io.h b/c/dependencies/windows/apr/x64_debug/include/apr_file_io.h new file mode 100644 index 00000000..af931939 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_file_io.h @@ -0,0 +1,1005 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_FILE_IO_H +#define APR_FILE_IO_H + +/** + * @file apr_file_io.h + * @brief APR File I/O Handling + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_time.h" +#include "apr_errno.h" +#include "apr_file_info.h" +#include "apr_inherit.h" + +#define APR_WANT_STDIO /**< for SEEK_* */ +#define APR_WANT_IOVEC /**< for apr_file_writev */ +#include "apr_want.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_file_io File I/O Handling Functions + * @ingroup APR + * @{ + */ + +/** + * @defgroup apr_file_open_flags File Open Flags/Routines + * @{ + */ + +/* Note to implementors: Values in the range 0x00100000--0x80000000 + are reserved for platform-specific values. */ + +#define APR_FOPEN_READ 0x00001 /**< Open the file for reading */ +#define APR_FOPEN_WRITE 0x00002 /**< Open the file for writing */ +#define APR_FOPEN_CREATE 0x00004 /**< Create the file if not there */ +#define APR_FOPEN_APPEND 0x00008 /**< Append to the end of the file */ +#define APR_FOPEN_TRUNCATE 0x00010 /**< Open the file and truncate + to 0 length */ +#define APR_FOPEN_BINARY 0x00020 /**< Open the file in binary mode + (This flag is ignored on UNIX + because it has no meaning)*/ +#define APR_FOPEN_EXCL 0x00040 /**< Open should fail if #APR_FOPEN_CREATE + and file exists. */ +#define APR_FOPEN_BUFFERED 0x00080 /**< Open the file for buffered I/O */ +#define APR_FOPEN_DELONCLOSE 0x00100 /**< Delete the file after close */ +#define APR_FOPEN_XTHREAD 0x00200 /**< Platform dependent tag to open + the file for use across multiple + threads */ +#define APR_FOPEN_SHARELOCK 0x00400 /**< Platform dependent support for + higher level locked read/write + access to support writes across + process/machines */ +#define APR_FOPEN_NOCLEANUP 0x00800 /**< Do not register a cleanup + when the file is opened. The + apr_os_file_t handle in apr_file_t + will not be closed when the pool + is destroyed. */ +#define APR_FOPEN_SENDFILE_ENABLED 0x01000 /**< Advisory flag that this + file should support + apr_socket_sendfile operation */ +#define APR_FOPEN_LARGEFILE 0x04000 /**< Platform dependent flag to enable + * large file support, see WARNING below + */ +#define APR_FOPEN_SPARSE 0x08000 /**< Platform dependent flag to enable + * sparse file support, see WARNING below + */ +#define APR_FOPEN_NONBLOCK 0x40000 /**< Platform dependent flag to enable + * non blocking file io */ + + +/* backcompat */ +#define APR_READ APR_FOPEN_READ /**< @deprecated @see APR_FOPEN_READ */ +#define APR_WRITE APR_FOPEN_WRITE /**< @deprecated @see APR_FOPEN_WRITE */ +#define APR_CREATE APR_FOPEN_CREATE /**< @deprecated @see APR_FOPEN_CREATE */ +#define APR_APPEND APR_FOPEN_APPEND /**< @deprecated @see APR_FOPEN_APPEND */ +#define APR_TRUNCATE APR_FOPEN_TRUNCATE /**< @deprecated @see APR_FOPEN_TRUNCATE */ +#define APR_BINARY APR_FOPEN_BINARY /**< @deprecated @see APR_FOPEN_BINARY */ +#define APR_EXCL APR_FOPEN_EXCL /**< @deprecated @see APR_FOPEN_EXCL */ +#define APR_BUFFERED APR_FOPEN_BUFFERED /**< @deprecated @see APR_FOPEN_BUFFERED */ +#define APR_DELONCLOSE APR_FOPEN_DELONCLOSE /**< @deprecated @see APR_FOPEN_DELONCLOSE */ +#define APR_XTHREAD APR_FOPEN_XTHREAD /**< @deprecated @see APR_FOPEN_XTHREAD */ +#define APR_SHARELOCK APR_FOPEN_SHARELOCK /**< @deprecated @see APR_FOPEN_SHARELOCK */ +#define APR_FILE_NOCLEANUP APR_FOPEN_NOCLEANUP /**< @deprecated @see APR_FOPEN_NOCLEANUP */ +#define APR_SENDFILE_ENABLED APR_FOPEN_SENDFILE_ENABLED /**< @deprecated @see APR_FOPEN_SENDFILE_ENABLED */ +#define APR_LARGEFILE APR_FOPEN_LARGEFILE /**< @deprecated @see APR_FOPEN_LARGEFILE */ + +/** @def APR_FOPEN_LARGEFILE + * @warning APR_FOPEN_LARGEFILE flag only has effect on some + * platforms where sizeof(apr_off_t) == 4. Where implemented, it + * allows opening and writing to a file which exceeds the size which + * can be represented by apr_off_t (2 gigabytes). When a file's size + * does exceed 2Gb, apr_file_info_get() will fail with an error on the + * descriptor, likewise apr_stat()/apr_lstat() will fail on the + * filename. apr_dir_read() will fail with #APR_INCOMPLETE on a + * directory entry for a large file depending on the particular + * APR_FINFO_* flags. Generally, it is not recommended to use this + * flag. + * + * @def APR_FOPEN_SPARSE + * @warning APR_FOPEN_SPARSE may, depending on platform, convert a + * normal file to a sparse file. Some applications may be unable + * to decipher a sparse file, so it's critical that the sparse file + * flag should only be used for files accessed only by APR or other + * applications known to be able to decipher them. APR does not + * guarantee that it will compress the file into sparse segments + * if it was previously created and written without the sparse flag. + * On platforms which do not understand, or on file systems which + * cannot handle sparse files, the flag is ignored by apr_file_open(). + * + * @def APR_FOPEN_NONBLOCK + * @warning APR_FOPEN_NONBLOCK is not implemented on all platforms. + * Callers should be prepared for it to fail with #APR_ENOTIMPL. + */ + +/** @} */ + +/** + * @defgroup apr_file_seek_flags File Seek Flags + * @{ + */ + +/* flags for apr_file_seek */ +/** Set the file position */ +#define APR_SET SEEK_SET +/** Current */ +#define APR_CUR SEEK_CUR +/** Go to end of file */ +#define APR_END SEEK_END +/** @} */ + +/** + * @defgroup apr_file_attrs_set_flags File Attribute Flags + * @{ + */ + +/* flags for apr_file_attrs_set */ +#define APR_FILE_ATTR_READONLY 0x01 /**< File is read-only */ +#define APR_FILE_ATTR_EXECUTABLE 0x02 /**< File is executable */ +#define APR_FILE_ATTR_HIDDEN 0x04 /**< File is hidden */ +/** @} */ + +/** + * @defgroup apr_file_writev{_full} max iovec size + * @{ + */ +#if defined(DOXYGEN) +#define APR_MAX_IOVEC_SIZE 1024 /**< System dependent maximum + size of an iovec array */ +#elif defined(IOV_MAX) +#define APR_MAX_IOVEC_SIZE IOV_MAX +#elif defined(MAX_IOVEC) +#define APR_MAX_IOVEC_SIZE MAX_IOVEC +#else +#define APR_MAX_IOVEC_SIZE 1024 +#endif +/** @} */ + +/** File attributes */ +typedef apr_uint32_t apr_fileattrs_t; + +/** Type to pass as whence argument to apr_file_seek. */ +typedef int apr_seek_where_t; + +/** + * Structure for referencing files. + */ +typedef struct apr_file_t apr_file_t; + +/* File lock types/flags */ +/** + * @defgroup apr_file_lock_types File Lock Types + * @{ + */ + +#define APR_FLOCK_SHARED 1 /**< Shared lock. More than one process + or thread can hold a shared lock + at any given time. Essentially, + this is a "read lock", preventing + writers from establishing an + exclusive lock. */ +#define APR_FLOCK_EXCLUSIVE 2 /**< Exclusive lock. Only one process + may hold an exclusive lock at any + given time. This is analogous to + a "write lock". */ + +#define APR_FLOCK_TYPEMASK 0x000F /**< mask to extract lock type */ +#define APR_FLOCK_NONBLOCK 0x0010 /**< do not block while acquiring the + file lock */ +/** @} */ + +/** + * Open the specified file. + * @param newf The opened file descriptor. + * @param fname The full path to the file (using / on all systems) + * @param flag Or'ed value of: + * @li #APR_FOPEN_READ open for reading + * @li #APR_FOPEN_WRITE open for writing + * @li #APR_FOPEN_CREATE create the file if not there + * @li #APR_FOPEN_APPEND file ptr is set to end prior to all writes + * @li #APR_FOPEN_TRUNCATE set length to zero if file exists + * @li #APR_FOPEN_BINARY not a text file + * @li #APR_FOPEN_BUFFERED buffer the data. Default is non-buffered + * @li #APR_FOPEN_EXCL return error if #APR_FOPEN_CREATE and file exists + * @li #APR_FOPEN_DELONCLOSE delete the file after closing + * @li #APR_FOPEN_XTHREAD Platform dependent tag to open the file + * for use across multiple threads + * @li #APR_FOPEN_SHARELOCK Platform dependent support for higher + * level locked read/write access to support + * writes across process/machines + * @li #APR_FOPEN_NOCLEANUP Do not register a cleanup with the pool + * passed in on the @a pool argument (see below) + * @li #APR_FOPEN_SENDFILE_ENABLED Open with appropriate platform semantics + * for sendfile operations. Advisory only, + * apr_socket_sendfile does not check this flag + * @li #APR_FOPEN_LARGEFILE Platform dependent flag to enable large file + * support, see WARNING below + * @li #APR_FOPEN_SPARSE Platform dependent flag to enable sparse file + * support, see WARNING below + * @li #APR_FOPEN_NONBLOCK Platform dependent flag to enable + * non blocking file io + * @param perm Access permissions for file. + * @param pool The pool to use. + * @remark If perm is #APR_FPROT_OS_DEFAULT and the file is being created, + * appropriate default permissions will be used. + * @remark By default, the returned file descriptor will not be + * inherited by child processes created by apr_proc_create(). This + * can be changed using apr_file_inherit_set(). + */ +APR_DECLARE(apr_status_t) apr_file_open(apr_file_t **newf, const char *fname, + apr_int32_t flag, apr_fileperms_t perm, + apr_pool_t *pool); + +/** + * Close the specified file. + * @param file The file descriptor to close. + */ +APR_DECLARE(apr_status_t) apr_file_close(apr_file_t *file); + +/** + * Delete the specified file. + * @param path The full path to the file (using / on all systems) + * @param pool The pool to use. + * @remark If the file is open, it won't be removed until all + * instances are closed. + */ +APR_DECLARE(apr_status_t) apr_file_remove(const char *path, apr_pool_t *pool); + +/** + * Rename the specified file. + * @param from_path The full path to the original file (using / on all systems) + * @param to_path The full path to the new file (using / on all systems) + * @param pool The pool to use. + * @warning If a file exists at the new location, then it will be + * overwritten. Moving files or directories across devices may not be + * possible. + */ +APR_DECLARE(apr_status_t) apr_file_rename(const char *from_path, + const char *to_path, + apr_pool_t *pool); + +/** + * Create a hard link to the specified file. + * @param from_path The full path to the original file (using / on all systems) + * @param to_path The full path to the new file (using / on all systems) + * @remark Both files must reside on the same device. + */ +APR_DECLARE(apr_status_t) apr_file_link(const char *from_path, + const char *to_path); + +/** + * Copy the specified file to another file. + * @param from_path The full path to the original file (using / on all systems) + * @param to_path The full path to the new file (using / on all systems) + * @param perms Access permissions for the new file if it is created. + * In place of the usual or'd combination of file permissions, the + * value #APR_FPROT_FILE_SOURCE_PERMS may be given, in which case the source + * file's permissions are copied. + * @param pool The pool to use. + * @remark The new file does not need to exist, it will be created if required. + * @warning If the new file already exists, its contents will be overwritten. + */ +APR_DECLARE(apr_status_t) apr_file_copy(const char *from_path, + const char *to_path, + apr_fileperms_t perms, + apr_pool_t *pool); + +/** + * Append the specified file to another file. + * @param from_path The full path to the source file (use / on all systems) + * @param to_path The full path to the destination file (use / on all systems) + * @param perms Access permissions for the destination file if it is created. + * In place of the usual or'd combination of file permissions, the + * value #APR_FPROT_FILE_SOURCE_PERMS may be given, in which case the source + * file's permissions are copied. + * @param pool The pool to use. + * @remark The new file does not need to exist, it will be created if required. + * @remark Note that advanced filesystem permissions such as ACLs are not + * duplicated by this API. The target permissions (including duplicating the + * source file permissions) are assigned only when the target file does not yet + * exist. + */ +APR_DECLARE(apr_status_t) apr_file_append(const char *from_path, + const char *to_path, + apr_fileperms_t perms, + apr_pool_t *pool); + +/** + * Are we at the end of the file + * @param fptr The apr file we are testing. + * @remark Returns #APR_EOF if we are at the end of file, #APR_SUCCESS otherwise. + */ +APR_DECLARE(apr_status_t) apr_file_eof(apr_file_t *fptr); + +/** + * Open standard error as an apr file pointer. + * @param thefile The apr file to use as stderr. + * @param pool The pool to allocate the file out of. + * + * @remark The only reason that the apr_file_open_std* functions exist + * is that you may not always have a stderr/out/in on Windows. This + * is generally a problem with newer versions of Windows and services. + * + * @remark The other problem is that the C library functions generally work + * differently on Windows and Unix. So, by using apr_file_open_std* + * functions, you can get a handle to an APR struct that works with + * the APR functions which are supposed to work identically on all + * platforms. + */ +APR_DECLARE(apr_status_t) apr_file_open_stderr(apr_file_t **thefile, + apr_pool_t *pool); + +/** + * open standard output as an apr file pointer. + * @param thefile The apr file to use as stdout. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_stdout(apr_file_t **thefile, + apr_pool_t *pool); + +/** + * open standard input as an apr file pointer. + * @param thefile The apr file to use as stdin. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_stdin(apr_file_t **thefile, + apr_pool_t *pool); + +/** + * open standard error as an apr file pointer, with flags. + * @param thefile The apr file to use as stderr. + * @param flags The flags to open the file with. Only the + * @li #APR_FOPEN_EXCL + * @li #APR_FOPEN_BUFFERED + * @li #APR_FOPEN_XTHREAD + * @li #APR_FOPEN_SHARELOCK + * @li #APR_FOPEN_SENDFILE_ENABLED + * @li #APR_FOPEN_LARGEFILE + * + * flags should be used. The #APR_FOPEN_WRITE flag will + * be set unconditionally. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_flags_stderr(apr_file_t **thefile, + apr_int32_t flags, + apr_pool_t *pool); + +/** + * open standard output as an apr file pointer, with flags. + * @param thefile The apr file to use as stdout. + * @param flags The flags to open the file with. Only the + * @li #APR_FOPEN_EXCL + * @li #APR_FOPEN_BUFFERED + * @li #APR_FOPEN_XTHREAD + * @li #APR_FOPEN_SHARELOCK + * @li #APR_FOPEN_SENDFILE_ENABLED + * @li #APR_FOPEN_LARGEFILE + * + * flags should be used. The #APR_FOPEN_WRITE flag will + * be set unconditionally. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_flags_stdout(apr_file_t **thefile, + apr_int32_t flags, + apr_pool_t *pool); + +/** + * open standard input as an apr file pointer, with flags. + * @param thefile The apr file to use as stdin. + * @param flags The flags to open the file with. Only the + * @li #APR_FOPEN_EXCL + * @li #APR_FOPEN_BUFFERED + * @li #APR_FOPEN_XTHREAD + * @li #APR_FOPEN_SHARELOCK + * @li #APR_FOPEN_SENDFILE_ENABLED + * @li #APR_FOPEN_LARGEFILE + * + * flags should be used. The #APR_FOPEN_WRITE flag will + * be set unconditionally. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_flags_stdin(apr_file_t **thefile, + apr_int32_t flags, + apr_pool_t *pool); + +/** + * Read data from the specified file. + * @param thefile The file descriptor to read from. + * @param buf The buffer to store the data to. + * @param nbytes On entry, the number of bytes to read; on exit, the number + * of bytes read. + * + * @remark apr_file_read() will read up to the specified number of + * bytes, but never more. If there isn't enough data to fill that + * number of bytes, all of the available data is read. The third + * argument is modified to reflect the number of bytes read. If a + * char was put back into the stream via ungetc, it will be the first + * character returned. + * + * @remark It is not possible for both bytes to be read and an #APR_EOF + * or other error to be returned. #APR_EINTR is never returned. + */ +APR_DECLARE(apr_status_t) apr_file_read(apr_file_t *thefile, void *buf, + apr_size_t *nbytes); + +/** + * Write data to the specified file. + * @param thefile The file descriptor to write to. + * @param buf The buffer which contains the data. + * @param nbytes On entry, the number of bytes to write; on exit, the number + * of bytes written. + * + * @remark apr_file_write() will write up to the specified number of + * bytes, but never more. If the OS cannot write that many bytes, it + * will write as many as it can. The third argument is modified to + * reflect the * number of bytes written. + * + * @remark It is possible for both bytes to be written and an error to + * be returned. #APR_EINTR is never returned. + */ +APR_DECLARE(apr_status_t) apr_file_write(apr_file_t *thefile, const void *buf, + apr_size_t *nbytes); + +/** + * Write data from iovec array to the specified file. + * @param thefile The file descriptor to write to. + * @param vec The array from which to get the data to write to the file. + * @param nvec The number of elements in the struct iovec array. This must + * be smaller than #APR_MAX_IOVEC_SIZE. If it isn't, the function + * will fail with #APR_EINVAL. + * @param nbytes The number of bytes written. + * + * @remark It is possible for both bytes to be written and an error to + * be returned. #APR_EINTR is never returned. + * + * @remark apr_file_writev() is available even if the underlying + * operating system doesn't provide writev(). + */ +APR_DECLARE(apr_status_t) apr_file_writev(apr_file_t *thefile, + const struct iovec *vec, + apr_size_t nvec, apr_size_t *nbytes); + +/** + * Read data from the specified file, ensuring that the buffer is filled + * before returning. + * @param thefile The file descriptor to read from. + * @param buf The buffer to store the data to. + * @param nbytes The number of bytes to read. + * @param bytes_read If non-NULL, this will contain the number of bytes read. + * + * @remark apr_file_read_full() will read up to the specified number of + * bytes, but never more. If there isn't enough data to fill that + * number of bytes, then the process/thread will block until it is + * available or EOF is reached. If a char was put back into the + * stream via ungetc, it will be the first character returned. + * + * @remark It is possible for both bytes to be read and an error to be + * returned. And if *bytes_read is less than nbytes, an accompanying + * error is _always_ returned. + * + * @remark #APR_EINTR is never returned. + */ +APR_DECLARE(apr_status_t) apr_file_read_full(apr_file_t *thefile, void *buf, + apr_size_t nbytes, + apr_size_t *bytes_read); + +/** + * Write data to the specified file, ensuring that all of the data is + * written before returning. + * @param thefile The file descriptor to write to. + * @param buf The buffer which contains the data. + * @param nbytes The number of bytes to write. + * @param bytes_written If non-NULL, set to the number of bytes written. + * + * @remark apr_file_write_full() will write up to the specified number of + * bytes, but never more. If the OS cannot write that many bytes, the + * process/thread will block until they can be written. Exceptional + * error such as "out of space" or "pipe closed" will terminate with + * an error. + * + * @remark It is possible for both bytes to be written and an error to + * be returned. And if *bytes_written is less than nbytes, an + * accompanying error is _always_ returned. + * + * @remark #APR_EINTR is never returned. + */ +APR_DECLARE(apr_status_t) apr_file_write_full(apr_file_t *thefile, + const void *buf, + apr_size_t nbytes, + apr_size_t *bytes_written); + + +/** + * Write data from iovec array to the specified file, ensuring that all of the + * data is written before returning. + * @param thefile The file descriptor to write to. + * @param vec The array from which to get the data to write to the file. + * @param nvec The number of elements in the struct iovec array. This must + * be smaller than #APR_MAX_IOVEC_SIZE. If it isn't, the function + * will fail with #APR_EINVAL. + * @param nbytes The number of bytes written. + * + * @remark apr_file_writev_full() is available even if the underlying + * operating system doesn't provide writev(). + */ +APR_DECLARE(apr_status_t) apr_file_writev_full(apr_file_t *thefile, + const struct iovec *vec, + apr_size_t nvec, + apr_size_t *nbytes); +/** + * Write a character into the specified file. + * @param ch The character to write. + * @param thefile The file descriptor to write to + */ +APR_DECLARE(apr_status_t) apr_file_putc(char ch, apr_file_t *thefile); + +/** + * Read a character from the specified file. + * @param ch The character to read into + * @param thefile The file descriptor to read from + */ +APR_DECLARE(apr_status_t) apr_file_getc(char *ch, apr_file_t *thefile); + +/** + * Put a character back onto a specified stream. + * @param ch The character to write. + * @param thefile The file descriptor to write to + */ +APR_DECLARE(apr_status_t) apr_file_ungetc(char ch, apr_file_t *thefile); + +/** + * Read a line from the specified file + * @param str The buffer to store the string in. + * @param len The length of the string + * @param thefile The file descriptor to read from + * @remark The buffer will be NUL-terminated if any characters are stored. + * The newline at the end of the line will not be stripped. + */ +APR_DECLARE(apr_status_t) apr_file_gets(char *str, int len, + apr_file_t *thefile); + +/** + * Write the string into the specified file. + * @param str The string to write. + * @param thefile The file descriptor to write to + */ +APR_DECLARE(apr_status_t) apr_file_puts(const char *str, apr_file_t *thefile); + +/** + * Flush the file's buffer. + * @param thefile The file descriptor to flush + */ +APR_DECLARE(apr_status_t) apr_file_flush(apr_file_t *thefile); + +/** + * Transfer all file modified data and metadata to disk. + * @param thefile The file descriptor to sync + */ +APR_DECLARE(apr_status_t) apr_file_sync(apr_file_t *thefile); + +/** + * Transfer all file modified data to disk. + * @param thefile The file descriptor to sync + */ +APR_DECLARE(apr_status_t) apr_file_datasync(apr_file_t *thefile); + +/** + * Duplicate the specified file descriptor. + * @param new_file The structure to duplicate into. + * @param old_file The file to duplicate. + * @param p The pool to use for the new file. + * @remark *new_file must point to a valid apr_file_t, or point to NULL. + */ +APR_DECLARE(apr_status_t) apr_file_dup(apr_file_t **new_file, + apr_file_t *old_file, + apr_pool_t *p); + +/** + * Duplicate the specified file descriptor and close the original + * @param new_file The old file that is to be closed and reused + * @param old_file The file to duplicate + * @param p The pool to use for the new file + * + * @remark new_file MUST point at a valid apr_file_t. It cannot be NULL. + */ +APR_DECLARE(apr_status_t) apr_file_dup2(apr_file_t *new_file, + apr_file_t *old_file, + apr_pool_t *p); + +/** + * Move the specified file descriptor to a new pool + * @param new_file Pointer in which to return the new apr_file_t + * @param old_file The file to move + * @param p The pool to which the descriptor is to be moved + * @remark Unlike apr_file_dup2(), this function doesn't do an + * OS dup() operation on the underlying descriptor; it just + * moves the descriptor's apr_file_t wrapper to a new pool. + * @remark The new pool need not be an ancestor of old_file's pool. + * @remark After calling this function, old_file may not be used + */ +APR_DECLARE(apr_status_t) apr_file_setaside(apr_file_t **new_file, + apr_file_t *old_file, + apr_pool_t *p); + +/** + * Give the specified apr file handle a new buffer + * @param thefile The file handle that is to be modified + * @param buffer The buffer + * @param bufsize The size of the buffer + * @remark It is possible to add a buffer to previously unbuffered + * file handles, the #APR_FOPEN_BUFFERED flag will be added to + * the file handle's flags. Likewise, with buffer=NULL and + * bufsize=0 arguments it is possible to make a previously + * buffered file handle unbuffered. + */ +APR_DECLARE(apr_status_t) apr_file_buffer_set(apr_file_t *thefile, + char * buffer, + apr_size_t bufsize); + +/** + * Get the size of any buffer for the specified apr file handle + * @param thefile The file handle + */ +APR_DECLARE(apr_size_t) apr_file_buffer_size_get(apr_file_t *thefile); + +/** + * Move the read/write file offset to a specified byte within a file. + * @param thefile The file descriptor + * @param where How to move the pointer, one of: + * @li #APR_SET -- set the offset to offset + * @li #APR_CUR -- add the offset to the current position + * @li #APR_END -- add the offset to the current file size + * @param offset The offset to move the pointer to. + * @remark The third argument is modified to be the offset the pointer + was actually moved to. + */ +APR_DECLARE(apr_status_t) apr_file_seek(apr_file_t *thefile, + apr_seek_where_t where, + apr_off_t *offset); + +/** + * Create an anonymous pipe. + * @param in The newly created pipe's file for reading. + * @param out The newly created pipe's file for writing. + * @param pool The pool to operate on. + * @remark By default, the returned file descriptors will be inherited + * by child processes created using apr_proc_create(). This can be + * changed using apr_file_inherit_unset(). + * @bug Some platforms cannot toggle between blocking and nonblocking, + * and when passing a pipe as a standard handle to an application which + * does not expect it, a non-blocking stream will fluxor the client app. + * @deprecated @see apr_file_pipe_create_pools() + */ +APR_DECLARE(apr_status_t) apr_file_pipe_create(apr_file_t **in, + apr_file_t **out, + apr_pool_t *pool); + +/** + * Create an anonymous pipe which portably supports async timeout options. + * @param in The newly created pipe's file for reading. + * @param out The newly created pipe's file for writing. + * @param blocking one of these values defined in apr_thread_proc.h; + * @li #APR_FULL_BLOCK + * @li #APR_READ_BLOCK + * @li #APR_WRITE_BLOCK + * @li #APR_FULL_NONBLOCK + * @param pool The pool to operate on. + * @remark By default, the returned file descriptors will be inherited + * by child processes created using apr_proc_create(). This can be + * changed using apr_file_inherit_unset(). + * @remark Some platforms cannot toggle between blocking and nonblocking, + * and when passing a pipe as a standard handle to an application which + * does not expect it, a non-blocking stream will fluxor the client app. + * Use this function rather than apr_file_pipe_create() to create pipes + * where one or both ends require non-blocking semantics. + * @deprecated @see apr_file_pipe_create_pools() + */ +APR_DECLARE(apr_status_t) apr_file_pipe_create_ex(apr_file_t **in, + apr_file_t **out, + apr_int32_t blocking, + apr_pool_t *pool); + +/** + * Create an anonymous pipe which portably supports async timeout options, + * placing each side of the pipe in a different pool. + * @param in The newly created pipe's file for reading. + * @param out The newly created pipe's file for writing. + * @param blocking one of these values defined in apr_thread_proc.h; + * @li #APR_FULL_BLOCK + * @li #APR_READ_BLOCK + * @li #APR_WRITE_BLOCK + * @li #APR_FULL_NONBLOCK + * @param pool_in The pool for the reading pipe. + * @param pool_out The pool for the writing pipe. + * @remark By default, the returned file descriptors will be inherited + * by child processes created using apr_proc_create(). This can be + * changed using apr_file_inherit_unset(). + * @remark Some platforms cannot toggle between blocking and nonblocking, + * and when passing a pipe as a standard handle to an application which + * does not expect it, a non-blocking stream will fluxor the client app. + * Use this function rather than apr_file_pipe_create() to create pipes + * where one or both ends require non-blocking semantics. + */ +APR_DECLARE(apr_status_t) apr_file_pipe_create_pools(apr_file_t **in, + apr_file_t **out, + apr_int32_t blocking, + apr_pool_t *pool_in, + apr_pool_t *pool_out); + +/** + * Create a named pipe. + * @param filename The filename of the named pipe + * @param perm The permissions for the newly created pipe. + * @param pool The pool to operate on. + */ +APR_DECLARE(apr_status_t) apr_file_namedpipe_create(const char *filename, + apr_fileperms_t perm, + apr_pool_t *pool); + +/** + * Get the timeout value for a pipe or manipulate the blocking state. + * @param thepipe The pipe we are getting a timeout for. + * @param timeout The current timeout value in microseconds. + */ +APR_DECLARE(apr_status_t) apr_file_pipe_timeout_get(apr_file_t *thepipe, + apr_interval_time_t *timeout); + +/** + * Set the timeout value for a pipe or manipulate the blocking state. + * @param thepipe The pipe we are setting a timeout on. + * @param timeout The timeout value in microseconds. Values < 0 mean wait + * forever, 0 means do not wait at all. + */ +APR_DECLARE(apr_status_t) apr_file_pipe_timeout_set(apr_file_t *thepipe, + apr_interval_time_t timeout); + +/** file (un)locking functions. */ + +/** + * Establish a lock on the specified, open file. The lock may be advisory + * or mandatory, at the discretion of the platform. The lock applies to + * the file as a whole, rather than a specific range. Locks are established + * on a per-thread/process basis; a second lock by the same thread will not + * block. + * @param thefile The file to lock. + * @param type The type of lock to establish on the file. + */ +APR_DECLARE(apr_status_t) apr_file_lock(apr_file_t *thefile, int type); + +/** + * Remove any outstanding locks on the file. + * @param thefile The file to unlock. + */ +APR_DECLARE(apr_status_t) apr_file_unlock(apr_file_t *thefile); + +/**accessor and general file_io functions. */ + +/** + * return the file name of the current file. + * @param new_path The path of the file. + * @param thefile The currently open file. + */ +APR_DECLARE(apr_status_t) apr_file_name_get(const char **new_path, + apr_file_t *thefile); + +/** + * Return the data associated with the current file. + * @param data The user data associated with the file. + * @param key The key to use for retrieving data associated with this file. + * @param file The currently open file. + */ +APR_DECLARE(apr_status_t) apr_file_data_get(void **data, const char *key, + apr_file_t *file); + +/** + * Set the data associated with the current file. + * @param file The currently open file. + * @param data The user data to associate with the file. + * @param key The key to use for associating data with the file. + * @param cleanup The cleanup routine to use when the file is destroyed. + */ +APR_DECLARE(apr_status_t) apr_file_data_set(apr_file_t *file, void *data, + const char *key, + apr_status_t (*cleanup)(void *)); + +/** + * Write a string to a file using a printf format. + * @param fptr The file to write to. + * @param format The format string + * @param ... The values to substitute in the format string + * @return The number of bytes written + */ +APR_DECLARE_NONSTD(int) apr_file_printf(apr_file_t *fptr, + const char *format, ...) + __attribute__((format(printf,2,3))); + +/** + * set the specified file's permission bits. + * @param fname The file (name) to apply the permissions to. + * @param perms The permission bits to apply to the file. + * + * @warning Some platforms may not be able to apply all of the + * available permission bits; #APR_INCOMPLETE will be returned if some + * permissions are specified which could not be set. + * + * @warning Platforms which do not implement this feature will return + * #APR_ENOTIMPL. + */ +APR_DECLARE(apr_status_t) apr_file_perms_set(const char *fname, + apr_fileperms_t perms); + +/** + * Set attributes of the specified file. + * @param fname The full path to the file (using / on all systems) + * @param attributes Or'd combination of + * @li #APR_FILE_ATTR_READONLY - make the file readonly + * @li #APR_FILE_ATTR_EXECUTABLE - make the file executable + * @li #APR_FILE_ATTR_HIDDEN - make the file hidden + * @param attr_mask Mask of valid bits in attributes. + * @param pool the pool to use. + * @remark This function should be used in preference to explicit manipulation + * of the file permissions, because the operations to provide these + * attributes are platform specific and may involve more than simply + * setting permission bits. + * @warning Platforms which do not implement this feature will return + * #APR_ENOTIMPL. + */ +APR_DECLARE(apr_status_t) apr_file_attrs_set(const char *fname, + apr_fileattrs_t attributes, + apr_fileattrs_t attr_mask, + apr_pool_t *pool); + +/** + * Set the mtime of the specified file. + * @param fname The full path to the file (using / on all systems) + * @param mtime The mtime to apply to the file. + * @param pool The pool to use. + * @warning Platforms which do not implement this feature will return + * #APR_ENOTIMPL. + */ +APR_DECLARE(apr_status_t) apr_file_mtime_set(const char *fname, + apr_time_t mtime, + apr_pool_t *pool); + +/** + * Create a new directory on the file system. + * @param path the path for the directory to be created. (use / on all systems) + * @param perm Permissions for the new directory. + * @param pool the pool to use. + */ +APR_DECLARE(apr_status_t) apr_dir_make(const char *path, apr_fileperms_t perm, + apr_pool_t *pool); + +/** Creates a new directory on the file system, but behaves like + * 'mkdir -p'. Creates intermediate directories as required. No error + * will be reported if PATH already exists. + * @param path the path for the directory to be created. (use / on all systems) + * @param perm Permissions for the new directory. + * @param pool the pool to use. + */ +APR_DECLARE(apr_status_t) apr_dir_make_recursive(const char *path, + apr_fileperms_t perm, + apr_pool_t *pool); + +/** + * Remove directory from the file system. + * @param path the path for the directory to be removed. (use / on all systems) + * @param pool the pool to use. + * @remark Removing a directory which is in-use (e.g., the current working + * directory, or during apr_dir_read, or with an open file) is not portable. + */ +APR_DECLARE(apr_status_t) apr_dir_remove(const char *path, apr_pool_t *pool); + +/** + * get the specified file's stats. + * @param finfo Where to store the information about the file. + * @param wanted The desired apr_finfo_t fields, as a bit flag of APR_FINFO_* values + * @param thefile The file to get information about. + */ +APR_DECLARE(apr_status_t) apr_file_info_get(apr_finfo_t *finfo, + apr_int32_t wanted, + apr_file_t *thefile); + + +/** + * Truncate the file's length to the specified offset + * @param fp The file to truncate + * @param offset The offset to truncate to. + * @remark The read/write file offset is repositioned to offset. + */ +APR_DECLARE(apr_status_t) apr_file_trunc(apr_file_t *fp, apr_off_t offset); + +/** + * Retrieve the flags that were passed into apr_file_open() + * when the file was opened. + * @return apr_int32_t the flags + */ +APR_DECLARE(apr_int32_t) apr_file_flags_get(apr_file_t *f); + +/** + * Get the pool used by the file. + */ +APR_POOL_DECLARE_ACCESSOR(file); + +/** + * Set a file to be inherited by child processes. + * + */ +APR_DECLARE_INHERIT_SET(file); + +/** + * Unset a file from being inherited by child processes. + */ +APR_DECLARE_INHERIT_UNSET(file); + +/** + * Open a temporary file + * @param fp The apr file to use as a temporary file. + * @param templ The template to use when creating a temp file. + * @param flags The flags to open the file with. If this is zero, + * the file is opened with + * #APR_FOPEN_CREATE | #APR_FOPEN_READ | #APR_FOPEN_WRITE | + * #APR_FOPEN_EXCL | #APR_FOPEN_DELONCLOSE + * @param p The pool to allocate the file out of. + * @remark + * This function generates a unique temporary file name from template. + * The last six characters of template must be XXXXXX and these are replaced + * with a string that makes the filename unique. Since it will be modified, + * template must not be a string constant, but should be declared as a character + * array. + * + */ +APR_DECLARE(apr_status_t) apr_file_mktemp(apr_file_t **fp, char *templ, + apr_int32_t flags, apr_pool_t *p); + + +/** + * Find an existing directory suitable as a temporary storage location. + * @param temp_dir The temp directory. + * @param p The pool to use for any necessary allocations. + * @remark + * This function uses an algorithm to search for a directory that an + * an application can use for temporary storage. + * + */ +APR_DECLARE(apr_status_t) apr_temp_dir_get(const char **temp_dir, + apr_pool_t *p); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_FILE_IO_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_fnmatch.h b/c/dependencies/windows/apr/x64_debug/include/apr_fnmatch.h new file mode 100644 index 00000000..e8f6b03c --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_fnmatch.h @@ -0,0 +1,153 @@ +/* + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)fnmatch.h 8.1 (Berkeley) 6/2/93 + */ + +/* This file has been modified by the Apache Software Foundation. */ +#ifndef _APR_FNMATCH_H_ +#define _APR_FNMATCH_H_ + +/** + * @file apr_fnmatch.h + * @brief APR FNMatch Functions + */ + +#include "apr_errno.h" +#include "apr_tables.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_fnmatch Filename Matching Functions + * @ingroup APR + * @{ + */ + +#define APR_FNM_NOMATCH 1 /**< Match failed. */ + +#define APR_FNM_NOESCAPE 0x01 /**< Disable backslash escaping. */ +#define APR_FNM_PATHNAME 0x02 /**< Slash must be matched by slash. */ +#define APR_FNM_PERIOD 0x04 /**< Period must be matched by period. */ +#define APR_FNM_CASE_BLIND 0x08 /**< Compare characters case-insensitively. */ + +/** + * Try to match the string to the given pattern, return APR_SUCCESS if + * match, else return APR_FNM_NOMATCH. Note that there is no such thing as + * an illegal pattern. + * + * With all flags unset, a pattern is interpreted as such: + * + * PATTERN: Backslash followed by any character, including another + * backslash.
+ * MATCHES: That character exactly. + * + *

+ * PATTERN: ?
+ * MATCHES: Any single character. + *

+ * + *

+ * PATTERN: *
+ * MATCHES: Any sequence of zero or more characters. (Note that multiple + * *s in a row are equivalent to one.) + * + * PATTERN: Any character other than \?*[ or a \ at the end of the pattern
+ * MATCHES: That character exactly. (Case sensitive.) + * + * PATTERN: [ followed by a class description followed by ]
+ * MATCHES: A single character described by the class description. + * (Never matches, if the class description reaches until the + * end of the string without a ].) If the first character of + * the class description is ^ or !, the sense of the description + * is reversed. The rest of the class description is a list of + * single characters or pairs of characters separated by -. Any + * of those characters can have a backslash in front of them, + * which is ignored; this lets you use the characters ] and - + * in the character class, as well as ^ and ! at the + * beginning. The pattern matches a single character if it + * is one of the listed characters or falls into one of the + * listed ranges (inclusive, case sensitive). Ranges with + * the first character larger than the second are legal but + * never match. Edge cases: [] never matches, and [^] and [!] + * always match without consuming a character. + * + * Note that these patterns attempt to match the entire string, not + * just find a substring matching the pattern. + * + * @param pattern The pattern to match to + * @param strings The string we are trying to match + * @param flags flags to use in the match. Bitwise OR of: + *

+ *              APR_FNM_NOESCAPE       Disable backslash escaping
+ *              APR_FNM_PATHNAME       Slash must be matched by slash
+ *              APR_FNM_PERIOD         Period must be matched by period
+ *              APR_FNM_CASE_BLIND     Compare characters case-insensitively.
+ * 
+ */ + +APR_DECLARE(apr_status_t) apr_fnmatch(const char *pattern, + const char *strings, int flags); + +/** + * Determine if the given pattern is a regular expression. + * @param pattern The pattern to search for glob characters. + * @return non-zero if pattern has any glob characters in it + */ +APR_DECLARE(int) apr_fnmatch_test(const char *pattern); + +/** + * Find all files that match a specified pattern in a directory. + * @param dir_pattern The pattern to use for finding files, appended + * to the search directory. The pattern is anything following the + * final forward or backward slash in the parameter. If no slash + * is found, the current directory is searched. + * @param result Array to use when storing the results + * @param p The pool to use. + * @return APR_SUCCESS if no processing errors occurred, APR error + * code otherwise + * @remark The returned array may be empty even if APR_SUCCESS was + * returned. + */ +APR_DECLARE(apr_status_t) apr_match_glob(const char *dir_pattern, + apr_array_header_t **result, + apr_pool_t *p); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !_APR_FNMATCH_H_ */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_general.h b/c/dependencies/windows/apr/x64_debug/include/apr_general.h new file mode 100644 index 00000000..fa073c85 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_general.h @@ -0,0 +1,244 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_GENERAL_H +#define APR_GENERAL_H + +/** + * @file apr_general.h + * This is collection of oddballs that didn't fit anywhere else, + * and might move to more appropriate headers with the release + * of APR 1.0. + * @brief APR Miscellaneous library routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" + +#if APR_HAVE_SIGNAL_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_general Miscellaneous library routines + * @ingroup APR + * This is collection of oddballs that didn't fit anywhere else, + * and might move to more appropriate headers with the release + * of APR 1.0. + * @{ + */ + +/** FALSE */ +#ifndef FALSE +#define FALSE 0 +#endif +/** TRUE */ +#ifndef TRUE +#define TRUE (!FALSE) +#endif + +/** a space */ +#define APR_ASCII_BLANK '\040' +/** a carrige return */ +#define APR_ASCII_CR '\015' +/** a line feed */ +#define APR_ASCII_LF '\012' +/** a tab */ +#define APR_ASCII_TAB '\011' + +/** signal numbers typedef */ +typedef int apr_signum_t; + +/** + * Finding offsets of elements within structures. + * Taken from the X code... they've sweated portability of this stuff + * so we don't have to. Sigh... + * @param p_type pointer type name + * @param field data field within the structure pointed to + * @return offset + */ + +#if defined(CRAY) || (defined(__arm) && !(defined(LINUX) || defined(__FreeBSD__))) +#ifdef __STDC__ +#define APR_OFFSET(p_type,field) _Offsetof(p_type,field) +#else +#ifdef CRAY2 +#define APR_OFFSET(p_type,field) \ + (sizeof(int)*((unsigned int)&(((p_type)NULL)->field))) + +#else /* !CRAY2 */ + +#define APR_OFFSET(p_type,field) ((unsigned int)&(((p_type)NULL)->field)) + +#endif /* !CRAY2 */ +#endif /* __STDC__ */ +#else /* ! (CRAY || __arm) */ + +#define APR_OFFSET(p_type,field) \ + ((long) (((char *) (&(((p_type)NULL)->field))) - ((char *) NULL))) + +#endif /* !CRAY */ + +/** + * Finding offsets of elements within structures. + * @param s_type structure type name + * @param field data field within the structure + * @return offset + */ +#if defined(offsetof) && !defined(__cplusplus) +#define APR_OFFSETOF(s_type,field) offsetof(s_type,field) +#else +#define APR_OFFSETOF(s_type,field) APR_OFFSET(s_type*,field) +#endif + +#ifndef DOXYGEN + +/* A couple of prototypes for functions in case some platform doesn't + * have it + */ +#if (!APR_HAVE_STRCASECMP) && (APR_HAVE_STRICMP) +#define strcasecmp(s1, s2) stricmp(s1, s2) +#elif (!APR_HAVE_STRCASECMP) +int strcasecmp(const char *a, const char *b); +#endif + +#if (!APR_HAVE_STRNCASECMP) && (APR_HAVE_STRNICMP) +#define strncasecmp(s1, s2, n) strnicmp(s1, s2, n) +#elif (!APR_HAVE_STRNCASECMP) +int strncasecmp(const char *a, const char *b, size_t n); +#endif + +#endif + +/** + * Alignment macros + */ + +/* APR_ALIGN() is only to be used to align on a power of 2 boundary */ +#define APR_ALIGN(size, boundary) \ + (((size) + ((boundary) - 1)) & ~((boundary) - 1)) + +/** Default alignment */ +#define APR_ALIGN_DEFAULT(size) APR_ALIGN(size, 8) + + +/** + * String and memory functions + */ + +/* APR_STRINGIFY is defined here, and also in apr_release.h, so wrap it */ +#ifndef APR_STRINGIFY +/** Properly quote a value as a string in the C preprocessor */ +#define APR_STRINGIFY(n) APR_STRINGIFY_HELPER(n) +/** Helper macro for APR_STRINGIFY */ +#define APR_STRINGIFY_HELPER(n) #n +#endif + +#if (!APR_HAVE_MEMMOVE) +#define memmove(a,b,c) bcopy(b,a,c) +#endif + +#if (!APR_HAVE_MEMCHR) +void *memchr(const void *s, int c, size_t n); +#endif + +/** @} */ + +/** + * @defgroup apr_library Library initialization and termination + * @{ + */ + +/** + * Setup any APR internal data structures. This MUST be the first function + * called for any APR library. It is safe to call apr_initialize several + * times as long as apr_terminate() is called the same number of times. + * @remark See apr_app_initialize() if this is an application, rather than + * a library consumer of apr. + */ +APR_DECLARE(apr_status_t) apr_initialize(void); + +/** + * Set up an application with normalized argc, argv (and optionally env) in + * order to deal with platform-specific oddities, such as Win32 services, + * code pages and signals. This must be the first function called for any + * APR program. + * @param argc Pointer to the argc that may be corrected + * @param argv Pointer to the argv that may be corrected + * @param env Pointer to the env that may be corrected, may be NULL + * @remark See apr_initialize() if this is a library consumer of apr. + * Otherwise, this call is identical to apr_initialize(), and must be closed + * with a call to apr_terminate() at the end of program execution. + */ +APR_DECLARE(apr_status_t) apr_app_initialize(int *argc, + char const * const * *argv, + char const * const * *env); + +/** + * Tear down any APR internal data structures which aren't torn down + * automatically. apr_terminate must be called once for every call to + * apr_initialize() or apr_app_initialize(). + * @remark An APR program must call this function at termination once it + * has stopped using APR services. The APR developers suggest using + * @c atexit(apr_terminate) to ensure this is called. When using APR + * from a language other than C that has problems with the calling + * convention, use apr_terminate2() instead. + * @see apr_terminate2 + */ +APR_DECLARE_NONSTD(void) apr_terminate(void); + +/** + * Tear down any APR internal data structures which aren't torn down + * automatically, same as apr_terminate() + * @remark An APR program must call either the apr_terminate() or apr_terminate2 + * function once it it has finished using APR services. The APR + * developers suggest using @c atexit(apr_terminate) to ensure this is done. + * apr_terminate2 exists to allow non-c language apps to tear down apr, + * while apr_terminate() is recommended from c language applications. + */ +APR_DECLARE(void) apr_terminate2(void); + +/** @} */ + +/** + * @defgroup apr_random Random Functions + * @{ + */ + +#if APR_HAS_RANDOM || defined(DOXYGEN) + +/* TODO: I'm not sure this is the best place to put this prototype...*/ +/** + * Generate random bytes. + * @param buf Buffer to fill with random bytes + * @param length Length of buffer in bytes + */ +APR_DECLARE(apr_status_t) apr_generate_random_bytes(unsigned char * buf, + apr_size_t length); + +#endif +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_GENERAL_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_getopt.h b/c/dependencies/windows/apr/x64_debug/include/apr_getopt.h new file mode 100644 index 00000000..75ad5663 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_getopt.h @@ -0,0 +1,160 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_GETOPT_H +#define APR_GETOPT_H + +/** + * @file apr_getopt.h + * @brief APR Command Arguments (getopt) + */ + +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_getopt Command Argument Parsing + * @ingroup APR + * @{ + */ + +/** + * An @c apr_getopt_t error callback function. + * + * @a arg is this @c apr_getopt_t's @c errarg member. + */ +typedef void (apr_getopt_err_fn_t)(void *arg, const char *err, ...); + +/** @see apr_getopt_t */ +typedef struct apr_getopt_t apr_getopt_t; + +/** + * Structure to store command line argument information. + */ +struct apr_getopt_t { + /** context for processing */ + apr_pool_t *cont; + /** function to print error message (NULL == no messages) */ + apr_getopt_err_fn_t *errfn; + /** user defined first arg to pass to error message */ + void *errarg; + /** index into parent argv vector */ + int ind; + /** character checked for validity */ + int opt; + /** reset getopt */ + int reset; + /** count of arguments */ + int argc; + /** array of pointers to arguments */ + const char **argv; + /** argument associated with option */ + char const* place; + /** set to nonzero to support interleaving options with regular args */ + int interleave; + /** start of non-option arguments skipped for interleaving */ + int skip_start; + /** end of non-option arguments skipped for interleaving */ + int skip_end; +}; + +/** @see apr_getopt_option_t */ +typedef struct apr_getopt_option_t apr_getopt_option_t; + +/** + * Structure used to describe options that getopt should search for. + */ +struct apr_getopt_option_t { + /** long option name, or NULL if option has no long name */ + const char *name; + /** option letter, or a value greater than 255 if option has no letter */ + int optch; + /** nonzero if option takes an argument */ + int has_arg; + /** a description of the option */ + const char *description; +}; + +/** + * Initialize the arguments for parsing by apr_getopt(). + * @param os The options structure created for apr_getopt() + * @param cont The pool to operate on + * @param argc The number of arguments to parse + * @param argv The array of arguments to parse + * @remark Arguments 3 and 4 are most commonly argc and argv from main(argc, argv) + * The (*os)->errfn is initialized to fprintf(stderr... but may be overridden. + */ +APR_DECLARE(apr_status_t) apr_getopt_init(apr_getopt_t **os, apr_pool_t *cont, + int argc, const char * const *argv); + +/** + * Parse the options initialized by apr_getopt_init(). + * @param os The apr_opt_t structure returned by apr_getopt_init() + * @param opts A string of characters that are acceptable options to the + * program. Characters followed by ":" are required to have an + * option associated + * @param option_ch The next option character parsed + * @param option_arg The argument following the option character: + * @return There are four potential status values on exit. They are: + *
+ *             APR_EOF      --  No more options to parse
+ *             APR_BADCH    --  Found a bad option character
+ *             APR_BADARG   --  No argument followed the option flag
+ *             APR_SUCCESS  --  The next option was found.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_getopt(apr_getopt_t *os, const char *opts, + char *option_ch, const char **option_arg); + +/** + * Parse the options initialized by apr_getopt_init(), accepting long + * options beginning with "--" in addition to single-character + * options beginning with "-". + * @param os The apr_getopt_t structure created by apr_getopt_init() + * @param opts A pointer to a list of apr_getopt_option_t structures, which + * can be initialized with { "name", optch, has_args }. has_args + * is nonzero if the option requires an argument. A structure + * with an optch value of 0 terminates the list. + * @param option_ch Receives the value of "optch" from the apr_getopt_option_t + * structure corresponding to the next option matched. + * @param option_arg Receives the argument following the option, if any. + * @return There are four potential status values on exit. They are: + *
+ *             APR_EOF      --  No more options to parse
+ *             APR_BADCH    --  Found a bad option character
+ *             APR_BADARG   --  No argument followed the option flag
+ *             APR_SUCCESS  --  The next option was found.
+ * 
+ * When APR_SUCCESS is returned, os->ind gives the index of the first + * non-option argument. On error, a message will be printed to stdout unless + * os->err is set to 0. If os->interleave is set to nonzero, options can come + * after arguments, and os->argv will be permuted to leave non-option arguments + * at the end (the original argv is unaffected). + */ +APR_DECLARE(apr_status_t) apr_getopt_long(apr_getopt_t *os, + const apr_getopt_option_t *opts, + int *option_ch, + const char **option_arg); +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_GETOPT_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_global_mutex.h b/c/dependencies/windows/apr/x64_debug/include/apr_global_mutex.h new file mode 100644 index 00000000..e3cba23f --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_global_mutex.h @@ -0,0 +1,195 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_GLOBAL_MUTEX_H +#define APR_GLOBAL_MUTEX_H + +/** + * @file apr_global_mutex.h + * @brief APR Global Locking Routines + */ + +#include "apr.h" +#include "apr_proc_mutex.h" /* only for apr_lockmech_e */ +#include "apr_pools.h" +#include "apr_errno.h" +#if APR_PROC_MUTEX_IS_GLOBAL +#include "apr_proc_mutex.h" +#endif +#include "apr_time.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_GlobalMutex Global Locking Routines + * @ingroup APR + * @{ + */ + +#if !APR_PROC_MUTEX_IS_GLOBAL || defined(DOXYGEN) + +/** Opaque global mutex structure. */ +typedef struct apr_global_mutex_t apr_global_mutex_t; + +/* Function definitions */ + +/** + * Create and initialize a mutex that can be used to synchronize both + * processes and threads. Note: There is considerable overhead in using + * this API if only cross-process or cross-thread mutual exclusion is + * required. See apr_proc_mutex.h and apr_thread_mutex.h for more + * specialized lock routines. + * @param mutex the memory address where the newly created mutex will be + * stored. + * @param fname A file name to use if the lock mechanism requires one. This + * argument should always be provided. The lock code itself will + * determine if it should be used. + * @param mech The mechanism to use for the interprocess lock, if any; one of + *
+ *            APR_LOCK_FCNTL
+ *            APR_LOCK_FLOCK
+ *            APR_LOCK_SYSVSEM
+ *            APR_LOCK_POSIXSEM
+ *            APR_LOCK_PROC_PTHREAD
+ *            APR_LOCK_DEFAULT     pick the default mechanism for the platform
+ *            APR_LOCK_DEFAULT_TIMED pick the default timed mechanism
+ * 
+ * @param pool the pool from which to allocate the mutex. + * @warning Check APR_HAS_foo_SERIALIZE defines to see if the platform supports + * APR_LOCK_foo. Only APR_LOCK_DEFAULT is portable. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_create(apr_global_mutex_t **mutex, + const char *fname, + apr_lockmech_e mech, + apr_pool_t *pool); + +/** + * Re-open a mutex in a child process. + * @param mutex The newly re-opened mutex structure. + * @param fname A file name to use if the mutex mechanism requires one. This + * argument should always be provided. The mutex code itself will + * determine if it should be used. This filename should be the + * same one that was passed to apr_global_mutex_create(). + * @param pool The pool to operate on. + * @remark This function must be called to maintain portability, even + * if the underlying lock mechanism does not require it. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_child_init( + apr_global_mutex_t **mutex, + const char *fname, + apr_pool_t *pool); + +/** + * Acquire the lock for the given mutex. If the mutex is already locked, + * the current thread will be put to sleep until the lock becomes available. + * @param mutex the mutex on which to acquire the lock. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_lock(apr_global_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex. If the mutex has already + * been acquired, the call returns immediately with APR_EBUSY. Note: it + * is important that the APR_STATUS_IS_EBUSY(s) macro be used to determine + * if the return value was APR_EBUSY, for portability reasons. + * @param mutex the mutex on which to attempt the lock acquiring. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_trylock(apr_global_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex until timeout expires. + * If the acquisition time outs, the call returns with APR_TIMEUP. + * @param mutex the mutex on which to attempt the lock acquiring. + * @param timeout the relative timeout (microseconds). + * @note A negative or nul timeout means immediate attempt, returning + * APR_TIMEUP without blocking if it the lock is already acquired. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_timedlock(apr_global_mutex_t *mutex, + apr_interval_time_t timeout); + +/** + * Release the lock for the given mutex. + * @param mutex the mutex from which to release the lock. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_unlock(apr_global_mutex_t *mutex); + +/** + * Destroy the mutex and free the memory associated with the lock. + * @param mutex the mutex to destroy. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_destroy(apr_global_mutex_t *mutex); + +/** + * Return the name of the lockfile for the mutex, or NULL + * if the mutex doesn't use a lock file + */ +APR_DECLARE(const char *) apr_global_mutex_lockfile(apr_global_mutex_t *mutex); + +/** + * Get the mechanism of the mutex, as it relates to the actual method + * used for the underlying apr_proc_mutex_t. + * @param mutex the mutex to get the mechanism from. + */ +APR_DECLARE(apr_lockmech_e) apr_global_mutex_mech(apr_global_mutex_t *mutex); + +/** + * Get the mechanism's name of the mutex, as it relates to the actual method + * used for the underlying apr_proc_mutex_t. + * @param mutex the mutex to get the mechanism's name from. + */ +APR_DECLARE(const char *) apr_global_mutex_name(apr_global_mutex_t *mutex); + +/** + * Set mutex permissions. + */ +APR_PERMS_SET_IMPLEMENT(global_mutex); + +/** + * Get the pool used by this global_mutex. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(global_mutex); + +#else /* APR_PROC_MUTEX_IS_GLOBAL */ + +/* Some platforms [e.g. Win32] have cross process locks that are truly + * global locks, since there isn't the concept of cross-process locks. + * Define these platforms in terms of an apr_proc_mutex_t. + */ + +#define apr_global_mutex_t apr_proc_mutex_t +#define apr_global_mutex_create apr_proc_mutex_create +#define apr_global_mutex_child_init apr_proc_mutex_child_init +#define apr_global_mutex_lock apr_proc_mutex_lock +#define apr_global_mutex_trylock apr_proc_mutex_trylock +#define apr_global_mutex_unlock apr_proc_mutex_unlock +#define apr_global_mutex_destroy apr_proc_mutex_destroy +#define apr_global_mutex_lockfile apr_proc_mutex_lockfile +#define apr_global_mutex_mech apr_proc_mutex_mech +#define apr_global_mutex_name apr_proc_mutex_name +#define apr_global_mutex_perms_set apr_proc_mutex_perms_set +#define apr_global_mutex_pool_get apr_proc_mutex_pool_get + +#endif + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ndef APR_GLOBAL_MUTEX_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_hash.h b/c/dependencies/windows/apr/x64_debug/include/apr_hash.h new file mode 100644 index 00000000..2276f84c --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_hash.h @@ -0,0 +1,283 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_HASH_H +#define APR_HASH_H + +/** + * @file apr_hash.h + * @brief APR Hash Tables + */ + +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_hash Hash Tables + * @ingroup APR + * @{ + */ + +/** + * When passing a key to apr_hash_set or apr_hash_get, this value can be + * passed to indicate a string-valued key, and have apr_hash compute the + * length automatically. + * + * @remark apr_hash will use strlen(key) for the length. The NUL terminator + * is not included in the hash value (why throw a constant in?). + * Since the hash table merely references the provided key (rather + * than copying it), apr_hash_this() will return the NUL-term'd key. + */ +#define APR_HASH_KEY_STRING (-1) + +/** + * Abstract type for hash tables. + */ +typedef struct apr_hash_t apr_hash_t; + +/** + * Abstract type for scanning hash tables. + */ +typedef struct apr_hash_index_t apr_hash_index_t; + +/** + * Callback functions for calculating hash values. + * @param key The key. + * @param klen The length of the key, or APR_HASH_KEY_STRING to use the string + * length. If APR_HASH_KEY_STRING then returns the actual key length. + */ +typedef unsigned int (*apr_hashfunc_t)(const char *key, apr_ssize_t *klen); + +/** + * The default hash function. + */ +APR_DECLARE_NONSTD(unsigned int) apr_hashfunc_default(const char *key, + apr_ssize_t *klen); + +/** + * Create a hash table. + * @param pool The pool to allocate the hash table out of + * @return The hash table just created + */ +APR_DECLARE(apr_hash_t *) apr_hash_make(apr_pool_t *pool); + +/** + * Create a hash table with a custom hash function + * @param pool The pool to allocate the hash table out of + * @param hash_func A custom hash function. + * @return The hash table just created + */ +APR_DECLARE(apr_hash_t *) apr_hash_make_custom(apr_pool_t *pool, + apr_hashfunc_t hash_func); + +/** + * Make a copy of a hash table + * @param pool The pool from which to allocate the new hash table + * @param h The hash table to clone + * @return The hash table just created + * @remark Makes a shallow copy + */ +APR_DECLARE(apr_hash_t *) apr_hash_copy(apr_pool_t *pool, + const apr_hash_t *h); + +/** + * Associate a value with a key in a hash table. + * @param ht The hash table + * @param key Pointer to the key + * @param klen Length of the key. Can be APR_HASH_KEY_STRING to use the string length. + * @param val Value to associate with the key + * @remark If the value is NULL the hash entry is deleted. The key is stored as is, + * and so must have a lifetime at least as long as the hash table's pool. + */ +APR_DECLARE(void) apr_hash_set(apr_hash_t *ht, const void *key, + apr_ssize_t klen, const void *val); + +/** + * Look up the value associated with a key in a hash table. + * @param ht The hash table + * @param key Pointer to the key + * @param klen Length of the key. Can be APR_HASH_KEY_STRING to use the string length. + * @return Returns NULL if the key is not present. + */ +APR_DECLARE(void *) apr_hash_get(apr_hash_t *ht, const void *key, + apr_ssize_t klen); + +/** + * Start iterating over the entries in a hash table. + * @param p The pool to allocate the apr_hash_index_t iterator. If this + * pool is NULL, then an internal, non-thread-safe iterator is used. + * @param ht The hash table + * @return The iteration state + * @remark There is no restriction on adding or deleting hash entries during + * an iteration (although the results may be unpredictable unless all you do + * is delete the current entry) and multiple iterations can be in + * progress at the same time. + * + * @par Example: + * + * @code + * int sum_values(apr_pool_t *p, apr_hash_t *ht) + * { + * apr_hash_index_t *hi; + * void *val; + * int sum = 0; + * for (hi = apr_hash_first(p, ht); hi; hi = apr_hash_next(hi)) { + * apr_hash_this(hi, NULL, NULL, &val); + * sum += *(int *)val; + * } + * return sum; + * } + * @endcode + */ +APR_DECLARE(apr_hash_index_t *) apr_hash_first(apr_pool_t *p, apr_hash_t *ht); + +/** + * Continue iterating over the entries in a hash table. + * @param hi The iteration state + * @return a pointer to the updated iteration state. NULL if there are no more + * entries. + */ +APR_DECLARE(apr_hash_index_t *) apr_hash_next(apr_hash_index_t *hi); + +/** + * Get the current entry's details from the iteration state. + * @param hi The iteration state + * @param key Return pointer for the pointer to the key. + * @param klen Return pointer for the key length. + * @param val Return pointer for the associated value. + * @remark The return pointers should point to a variable that will be set to the + * corresponding data, or they may be NULL if the data isn't interesting. + */ +APR_DECLARE(void) apr_hash_this(apr_hash_index_t *hi, const void **key, + apr_ssize_t *klen, void **val); + +/** + * Get the current entry's key from the iteration state. + * @param hi The iteration state + * @return The pointer to the key + */ +APR_DECLARE(const void*) apr_hash_this_key(apr_hash_index_t *hi); + +/** + * Get the current entry's key length from the iteration state. + * @param hi The iteration state + * @return The key length + */ +APR_DECLARE(apr_ssize_t) apr_hash_this_key_len(apr_hash_index_t *hi); + +/** + * Get the current entry's value from the iteration state. + * @param hi The iteration state + * @return The pointer to the value + */ +APR_DECLARE(void*) apr_hash_this_val(apr_hash_index_t *hi); + +/** + * Get the number of key/value pairs in the hash table. + * @param ht The hash table + * @return The number of key/value pairs in the hash table. + */ +APR_DECLARE(unsigned int) apr_hash_count(apr_hash_t *ht); + +/** + * Clear any key/value pairs in the hash table. + * @param ht The hash table + */ +APR_DECLARE(void) apr_hash_clear(apr_hash_t *ht); + +/** + * Merge two hash tables into one new hash table. The values of the overlay + * hash override the values of the base if both have the same key. Both + * hash tables must use the same hash function. + * @param p The pool to use for the new hash table + * @param overlay The table to add to the initial table + * @param base The table that represents the initial values of the new table + * @return A new hash table containing all of the data from the two passed in + */ +APR_DECLARE(apr_hash_t *) apr_hash_overlay(apr_pool_t *p, + const apr_hash_t *overlay, + const apr_hash_t *base); + +/** + * Merge two hash tables into one new hash table. If the same key + * is present in both tables, call the supplied merge function to + * produce a merged value for the key in the new table. Both + * hash tables must use the same hash function. + * @param p The pool to use for the new hash table + * @param h1 The first of the tables to merge + * @param h2 The second of the tables to merge + * @param merger A callback function to merge values, or NULL to + * make values from h1 override values from h2 (same semantics as + * apr_hash_overlay()) + * @param data Client data to pass to the merger function + * @return A new hash table containing all of the data from the two passed in + */ +APR_DECLARE(apr_hash_t *) apr_hash_merge(apr_pool_t *p, + const apr_hash_t *h1, + const apr_hash_t *h2, + void * (*merger)(apr_pool_t *p, + const void *key, + apr_ssize_t klen, + const void *h1_val, + const void *h2_val, + const void *data), + const void *data); + +/** + * Declaration prototype for the iterator callback function of apr_hash_do(). + * + * @param rec The data passed as the first argument to apr_hash_[v]do() + * @param key The key from this iteration of the hash table + * @param klen The key length from this iteration of the hash table + * @param value The value from this iteration of the hash table + * @remark Iteration continues while this callback function returns non-zero. + * To export the callback function for apr_hash_do() it must be declared + * in the _NONSTD convention. + */ +typedef int (apr_hash_do_callback_fn_t)(void *rec, const void *key, + apr_ssize_t klen, + const void *value); + +/** + * Iterate over a hash table running the provided function once for every + * element in the hash table. The @param comp function will be invoked for + * every element in the hash table. + * + * @param comp The function to run + * @param rec The data to pass as the first argument to the function + * @param ht The hash table to iterate over + * @return FALSE if one of the comp() iterations returned zero; TRUE if all + * iterations returned non-zero + * @see apr_hash_do_callback_fn_t + */ +APR_DECLARE(int) apr_hash_do(apr_hash_do_callback_fn_t *comp, + void *rec, const apr_hash_t *ht); + +/** + * Get a pointer to the pool which the hash table was created in + */ +APR_POOL_DECLARE_ACCESSOR(hash); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_HASH_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_hooks.h b/c/dependencies/windows/apr/x64_debug/include/apr_hooks.h new file mode 100644 index 00000000..eee16e3c --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_hooks.h @@ -0,0 +1,358 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_HOOKS_H +#define APR_HOOKS_H + +#include "apu.h" +/* For apr_array_header_t */ +#include "apr_tables.h" + +/** + * @file apr_hooks.h + * @brief Apache hook functions + */ + +#ifdef __cplusplus +extern "C" { +#endif +/** + * @defgroup APR_Util_Hook Hook Functions + * @ingroup APR_Util + * @{ + */ + +/** + * @defgroup apr_hook_probes Hook probe capability + * APR hooks provide a trace probe capability for capturing + * the flow of control and return values with hooks. + * + * In order to use this facility, the application must define + * the symbol APR_HOOK_PROBES_ENABLED and the four APR_HOOK_PROBE_ + * macros described below before including apr_hooks.h in files + * that use the APR_IMPLEMENT_EXTERNAL_HOOK_* macros. + * + * This probe facility is not provided for APR optional hooks. + * @{ + */ + +#ifdef APR_HOOK_PROBES_ENABLED +#define APR_HOOK_INT_DCL_UD void *ud = NULL +#else +/** internal implementation detail to avoid the ud declaration when + * hook probes are not used + */ +#define APR_HOOK_INT_DCL_UD +/** + * User-defined hook probe macro that is invoked when the hook + * is run, before calling any hook functions. + * @param ud A void * user data field that should be filled in by + * this macro, and will be provided to the other hook probe macros. + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param args The argument list to the hook functions, with enclosing + * parens. + */ +#define APR_HOOK_PROBE_ENTRY(ud,ns,name,args) +/** + * User-defined hook probe macro that is invoked after the hook + * has run. + * @param ud A void * user data field that was filled in by the user- + * provided APR_HOOK_PROBE_ENTRY(). + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param rv The return value of the hook, or 0 if the hook is void. + * @param args The argument list to the hook functions, with enclosing + * parens. + */ +#define APR_HOOK_PROBE_RETURN(ud,ns,name,rv,args) +/** + * User-defined hook probe macro that is invoked before calling a + * hook function. + * @param ud A void * user data field that was filled in by the user- + * provided APR_HOOK_PROBE_ENTRY(). + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param src The value of apr_hook_debug_current at the time the function + * was hooked (usually the source file implementing the hook function). + * @param args The argument list to the hook functions, with enclosing + * parens. + */ +#define APR_HOOK_PROBE_INVOKE(ud,ns,name,src,args) +/** + * User-defined hook probe macro that is invoked after calling a + * hook function. + * @param ud A void * user data field that was filled in by the user- + * provided APR_HOOK_PROBE_ENTRY(). + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param src The value of apr_hook_debug_current at the time the function + * was hooked (usually the source file implementing the hook function). + * @param rv The return value of the hook function, or 0 if the hook is void. + * @param args The argument list to the hook functions, with enclosing + * parens. + */ +#define APR_HOOK_PROBE_COMPLETE(ud,ns,name,src,rv,args) +#endif + +/** @} */ + +/** macro to return the prototype of the hook function */ +#define APR_IMPLEMENT_HOOK_GET_PROTO(ns,link,name) \ +link##_DECLARE(apr_array_header_t *) ns##_hook_get_##name(void) + +/** macro to declare the hook correctly */ +#define APR_DECLARE_EXTERNAL_HOOK(ns,link,ret,name,args) \ +typedef ret ns##_HOOK_##name##_t args; \ +link##_DECLARE(void) ns##_hook_##name(ns##_HOOK_##name##_t *pf, \ + const char * const *aszPre, \ + const char * const *aszSucc, int nOrder); \ +link##_DECLARE(ret) ns##_run_##name args; \ +APR_IMPLEMENT_HOOK_GET_PROTO(ns,link,name); \ +typedef struct ns##_LINK_##name##_t \ + { \ + ns##_HOOK_##name##_t *pFunc; \ + const char *szName; \ + const char * const *aszPredecessors; \ + const char * const *aszSuccessors; \ + int nOrder; \ + } ns##_LINK_##name##_t; + +/** macro to declare the hook structure */ +#define APR_HOOK_STRUCT(members) \ +static struct { members } _hooks; + +/** macro to link the hook structure */ +#define APR_HOOK_LINK(name) \ + apr_array_header_t *link_##name; + +/** macro to implement the hook */ +#define APR_IMPLEMENT_EXTERNAL_HOOK_BASE(ns,link,name) \ +link##_DECLARE(void) ns##_hook_##name(ns##_HOOK_##name##_t *pf,const char * const *aszPre, \ + const char * const *aszSucc,int nOrder) \ + { \ + ns##_LINK_##name##_t *pHook; \ + if(!_hooks.link_##name) \ + { \ + _hooks.link_##name=apr_array_make(apr_hook_global_pool,1,sizeof(ns##_LINK_##name##_t)); \ + apr_hook_sort_register(#name,&_hooks.link_##name); \ + } \ + pHook=apr_array_push(_hooks.link_##name); \ + pHook->pFunc=pf; \ + pHook->aszPredecessors=aszPre; \ + pHook->aszSuccessors=aszSucc; \ + pHook->nOrder=nOrder; \ + pHook->szName=apr_hook_debug_current; \ + if(apr_hook_debug_enabled) \ + apr_hook_debug_show(#name,aszPre,aszSucc); \ + } \ + APR_IMPLEMENT_HOOK_GET_PROTO(ns,link,name) \ + { \ + return _hooks.link_##name; \ + } + +/** + * Implement a hook that has no return code, and therefore runs all of the + * registered functions + * @param ns The namespace prefix of the hook functions + * @param link The linkage declaration prefix of the hook + * @param name The name of the hook + * @param args_decl The declaration of the arguments for the hook + * @param args_use The names for the arguments for the hook + * @note The link prefix FOO corresponds to FOO_DECLARE() macros, which + * provide export linkage from the module that IMPLEMENTs the hook, and + * import linkage from external modules that link to the hook's module. + */ +#define APR_IMPLEMENT_EXTERNAL_HOOK_VOID(ns,link,name,args_decl,args_use) \ +APR_IMPLEMENT_EXTERNAL_HOOK_BASE(ns,link,name) \ +link##_DECLARE(void) ns##_run_##name args_decl \ + { \ + ns##_LINK_##name##_t *pHook; \ + int n; \ + APR_HOOK_INT_DCL_UD; \ +\ + APR_HOOK_PROBE_ENTRY(ud, ns, name, args_use); \ +\ + if(_hooks.link_##name) \ + { \ + pHook=(ns##_LINK_##name##_t *)_hooks.link_##name->elts; \ + for(n=0 ; n < _hooks.link_##name->nelts ; ++n) \ + { \ + APR_HOOK_PROBE_INVOKE(ud, ns, name, (char *)pHook[n].szName, args_use); \ + pHook[n].pFunc args_use; \ + APR_HOOK_PROBE_COMPLETE(ud, ns, name, (char *)pHook[n].szName, 0, args_use); \ + } \ + } \ +\ + APR_HOOK_PROBE_RETURN(ud, ns, name, 0, args_use); \ +\ + } + +/* FIXME: note that this returns ok when nothing is run. I suspect it should + really return decline, but that breaks Apache currently - Ben +*/ +/** + * Implement a hook that runs until one of the functions returns something + * other than OK or DECLINE + * @param ns The namespace prefix of the hook functions + * @param link The linkage declaration prefix of the hook + * @param ret Type to return + * @param name The name of the hook + * @param args_decl The declaration of the arguments for the hook + * @param args_use The names for the arguments for the hook + * @param ok Success value + * @param decline Decline value + * @note The link prefix FOO corresponds to FOO_DECLARE() macros, which + * provide export linkage from the module that IMPLEMENTs the hook, and + * import linkage from external modules that link to the hook's module. + */ +#define APR_IMPLEMENT_EXTERNAL_HOOK_RUN_ALL(ns,link,ret,name,args_decl,args_use,ok,decline) \ +APR_IMPLEMENT_EXTERNAL_HOOK_BASE(ns,link,name) \ +link##_DECLARE(ret) ns##_run_##name args_decl \ + { \ + ns##_LINK_##name##_t *pHook; \ + int n; \ + ret rv = ok; \ + APR_HOOK_INT_DCL_UD; \ +\ + APR_HOOK_PROBE_ENTRY(ud, ns, name, args_use); \ +\ + if(_hooks.link_##name) \ + { \ + pHook=(ns##_LINK_##name##_t *)_hooks.link_##name->elts; \ + for(n=0 ; n < _hooks.link_##name->nelts ; ++n) \ + { \ + APR_HOOK_PROBE_INVOKE(ud, ns, name, (char *)pHook[n].szName, args_use); \ + rv=pHook[n].pFunc args_use; \ + APR_HOOK_PROBE_COMPLETE(ud, ns, name, (char *)pHook[n].szName, rv, args_use); \ + if(rv != ok && rv != decline) \ + break; \ + rv = ok; \ + } \ + } \ +\ + APR_HOOK_PROBE_RETURN(ud, ns, name, rv, args_use); \ +\ + return rv; \ + } + + +/** + * Implement a hook that runs until the first function returns something + * other than the value of decline + * @param ns The namespace prefix of the hook functions + * @param link The linkage declaration prefix of the hook + * @param name The name of the hook + * @param ret Type to return + * @param args_decl The declaration of the arguments for the hook + * @param args_use The names for the arguments for the hook + * @param decline Decline value + * @note The link prefix FOO corresponds to FOO_DECLARE() macros, which + * provide export linkage from the module that IMPLEMENTs the hook, and + * import linkage from external modules that link to the hook's module. + */ +#define APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(ns,link,ret,name,args_decl,args_use,decline) \ +APR_IMPLEMENT_EXTERNAL_HOOK_BASE(ns,link,name) \ +link##_DECLARE(ret) ns##_run_##name args_decl \ + { \ + ns##_LINK_##name##_t *pHook; \ + int n; \ + ret rv = decline; \ + APR_HOOK_INT_DCL_UD; \ +\ + APR_HOOK_PROBE_ENTRY(ud, ns, name, args_use); \ +\ + if(_hooks.link_##name) \ + { \ + pHook=(ns##_LINK_##name##_t *)_hooks.link_##name->elts; \ + for(n=0 ; n < _hooks.link_##name->nelts ; ++n) \ + { \ + APR_HOOK_PROBE_INVOKE(ud, ns, name, (char *)pHook[n].szName, args_use); \ + rv=pHook[n].pFunc args_use; \ + APR_HOOK_PROBE_COMPLETE(ud, ns, name, (char *)pHook[n].szName, rv, args_use); \ +\ + if(rv != decline) \ + break; \ + } \ + } \ +\ + APR_HOOK_PROBE_RETURN(ud, ns, name, rv, args_use); \ +\ + return rv; \ + } + + /* Hook orderings */ +/** run this hook first, before ANYTHING */ +#define APR_HOOK_REALLY_FIRST (-10) +/** run this hook first */ +#define APR_HOOK_FIRST 0 +/** run this hook somewhere */ +#define APR_HOOK_MIDDLE 10 +/** run this hook after every other hook which is defined*/ +#define APR_HOOK_LAST 20 +/** run this hook last, after EVERYTHING */ +#define APR_HOOK_REALLY_LAST 30 + +/** + * The global pool used to allocate any memory needed by the hooks. + */ +APU_DECLARE_DATA extern apr_pool_t *apr_hook_global_pool; + +/** + * A global variable to determine if debugging information about the + * hooks functions should be printed. + */ +APU_DECLARE_DATA extern int apr_hook_debug_enabled; + +/** + * The name of the module that is currently registering a function. + */ +APU_DECLARE_DATA extern const char *apr_hook_debug_current; + +/** + * Register a hook function to be sorted. + * @param szHookName The name of the Hook the function is registered for + * @param aHooks The array which stores all of the functions for this hook + */ +APU_DECLARE(void) apr_hook_sort_register(const char *szHookName, + apr_array_header_t **aHooks); +/** + * Sort all of the registered functions for a given hook. + */ +APU_DECLARE(void) apr_hook_sort_all(void); + +/** + * Print all of the information about the current hook. This is used for + * debugging purposes. + * @param szName The name of the hook + * @param aszPre All of the functions in the predecessor array + * @param aszSucc All of the functions in the successor array + */ +APU_DECLARE(void) apr_hook_debug_show(const char *szName, + const char * const *aszPre, + const char * const *aszSucc); + +/** + * Remove all currently registered functions. + */ +APU_DECLARE(void) apr_hook_deregister_all(void); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_HOOKS_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_iconv.h b/c/dependencies/windows/apr/x64_debug/include/apr_iconv.h new file mode 100644 index 00000000..81a0d315 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_iconv.h @@ -0,0 +1,150 @@ +/*- + * Copyright (c) 1999,2000 + * Konstantin Chuguev. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Konstantin Chuguev + * and its contributors. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + */ + +#ifndef APR_ICONV_H +#define APR_ICONV_H + +/** + * @file apr_iconv.h + * @brief APR-iconv substitute iconv library implementation + */ + +#include "apr.h" +#include "apr_pools.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_iconv substitute iconv implementation + * @ingroup APR-iconv + * @{ + */ + +/** + * API_DECLARE_EXPORT is defined when building the libapriconv dynamic + * library, so that all public symbols are exported. + * + * API_DECLARE_STATIC is defined when including the apriconv public headers, + * to provide static linkage when the dynamic library may be unavailable. + * + * API_DECLARE_STATIC and API_DECLARE_EXPORT are left undefined when + * including the apr-iconv public headers, to import and link the symbols + * from the dynamic libapriconv library and assure appropriate indirection + * and calling conventions at compile time. + */ + +#if defined(DOXYGEN) || !defined(WIN32) +/** + * The public apr-iconv functions are declared with API_DECLARE(), so they + * use the most portable calling convention. Public apr-iconv functions + * with variable arguments must use API_DECLARE_NONSTD(). + * + * @deffunc API_DECLARE(rettype) apr_func(args); + */ +#define API_DECLARE(type) type +/** + * The private apr-iconv functions are declared with API_DECLARE_NONSTD(), + * so they use the most optimal C language calling conventions. + * + * @deffunc API_DECLARE(rettype) apr_func(args); + */ +#define API_DECLARE_NONSTD(type) type +/** + * All exported apr-iconv variables are declared with API_DECLARE_DATA + * This assures the appropriate indirection is invoked at compile time. + * + * @deffunc API_DECLARE_DATA type apr_variable; + * @tip extern API_DECLARE_DATA type apr_variable; syntax is required for + * declarations within headers to properly import the variable. + */ +#define API_DECLARE_DATA +#elif defined(API_DECLARE_STATIC) +#define API_DECLARE(type) type __stdcall +#define API_DECLARE_NONSTD(type) type __cdecl +#define API_DECLARE_DATA +#elif defined(API_DECLARE_EXPORT) +#define API_DECLARE(type) __declspec(dllexport) type __stdcall +#define API_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define API_DECLARE_DATA __declspec(dllexport) +#else +#define API_DECLARE(type) __declspec(dllimport) type __stdcall +#define API_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define API_DECLARE_DATA __declspec(dllimport) +#endif + +/* + * apr_iconv_t: charset conversion descriptor type + */ +typedef void *apr_iconv_t; + +/* __BEGIN_DECLS */ + +/** + * Create a conversion descriptor. + * @param to name of charset to convert to. + * @param from name of charset of the input bytes. + * @param pool pool to alloc memory. + * @param cd conversion descriptor created in pool. + */ +API_DECLARE(apr_status_t) apr_iconv_open(const char *to, const char *from, + apr_pool_t *pool, apr_iconv_t *cd); +/** + * Perform character set conversion. + * @param cd conversion descriptor created by apr_iconv_open(). + * @param inbuf input buffer. + * @param inbytesleft bytes to convert. + * @param outbuf output buffer. + * @param outbytesleft space (in bytes) available in outbuf. + * @param translated number of input bytes converted. + */ +API_DECLARE(apr_status_t) apr_iconv(apr_iconv_t cd, + const char **inbuf, apr_size_t *inbytesleft, + char **outbuf, apr_size_t *outbytesleft, + apr_size_t *translated); +/** + * Deallocate descriptor for character set conversion. + * @param cd conversion descriptor. + * @param pool pool used in the apr_iconv_open(). + */ +API_DECLARE(apr_status_t) apr_iconv_close(apr_iconv_t cd, apr_pool_t *pool); + +/* __END_DECLS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_ICONV_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_inherit.h b/c/dependencies/windows/apr/x64_debug/include/apr_inherit.h new file mode 100644 index 00000000..b9fe56fe --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_inherit.h @@ -0,0 +1,51 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_INHERIT_H +#define APR_INHERIT_H + +/** + * @file apr_inherit.h + * @brief APR File Handle Inheritance Helpers + * @remark This internal header includes internal declaration helpers + * for other headers to declare apr_foo_inherit_[un]set functions. + */ + +/** + * Prototype for type-specific declarations of apr_foo_inherit_set + * functions. + * @remark Doxygen unwraps this macro (via doxygen.conf) to provide + * actual help for each specific occurrence of apr_foo_inherit_set. + * @remark the linkage is specified for APR. It would be possible to expand + * the macros to support other linkages. + */ +#define APR_DECLARE_INHERIT_SET(type) \ + APR_DECLARE(apr_status_t) apr_##type##_inherit_set( \ + apr_##type##_t *the##type) + +/** + * Prototype for type-specific declarations of apr_foo_inherit_unset + * functions. + * @remark Doxygen unwraps this macro (via doxygen.conf) to provide + * actual help for each specific occurrence of apr_foo_inherit_unset. + * @remark the linkage is specified for APR. It would be possible to expand + * the macros to support other linkages. + */ +#define APR_DECLARE_INHERIT_UNSET(type) \ + APR_DECLARE(apr_status_t) apr_##type##_inherit_unset( \ + apr_##type##_t *the##type) + +#endif /* ! APR_INHERIT_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_ldap.h b/c/dependencies/windows/apr/x64_debug/include/apr_ldap.h new file mode 100644 index 00000000..c1bd0d4b --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_ldap.h @@ -0,0 +1,197 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_ldap.h is generated from apr_ldap.h.in by configure -- do not edit apr_ldap.h + */ +/** + * @file apr_ldap.h + * @brief APR-UTIL LDAP + */ +#ifndef APU_LDAP_H +#define APU_LDAP_H + +/** + * @defgroup APR_Util_LDAP LDAP + * @ingroup APR_Util + * @{ + */ + +/* this will be defined if LDAP support was compiled into apr-util */ +#define APR_HAS_LDAP 1 + +/* identify the LDAP toolkit used */ +#define APR_HAS_NETSCAPE_LDAPSDK 0 +#define APR_HAS_SOLARIS_LDAPSDK 0 +#define APR_HAS_NOVELL_LDAPSDK 0 +#define APR_HAS_MOZILLA_LDAPSDK 0 +#define APR_HAS_OPENLDAP_LDAPSDK 0 +#define APR_HAS_MICROSOFT_LDAPSDK 1 +#define APR_HAS_TIVOLI_LDAPSDK 0 +#define APR_HAS_ZOS_LDAPSDK 0 +#define APR_HAS_OTHER_LDAPSDK 0 + + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/* + * The following #defines are DEPRECATED and should not be used for + * anything. They remain to maintain binary compatibility. + * The original code defined the OPENLDAP SDK as present regardless + * of what really was there, which was way bogus. In addition, the + * apr_ldap_url_parse*() functions have been rewritten specifically for + * APR, so the APR_HAS_LDAP_URL_PARSE macro is forced to zero. + */ +#if APR_HAS_TIVOLI_LDAPSDK +#define APR_HAS_LDAP_SSL 0 +#else +#define APR_HAS_LDAP_SSL 1 +#endif +#define APR_HAS_LDAP_URL_PARSE 0 + +#if APR_HAS_OPENLDAP_LDAPSDK && !defined(LDAP_DEPRECATED) +/* Ensure that the "deprecated" interfaces are still exposed + * with OpenLDAP >= 2.3; these were exposed by default in earlier + * releases. */ +#define LDAP_DEPRECATED 1 +#endif + +/* + * Include the standard LDAP header files. + */ + +#include + + +/* + * Detected standard functions + */ +#define APR_HAS_LDAPSSL_CLIENT_INIT 0 +#define APR_HAS_LDAPSSL_CLIENT_DEINIT 0 +#define APR_HAS_LDAPSSL_ADD_TRUSTED_CERT 0 +#define APR_HAS_LDAP_START_TLS_S 0 +#define APR_HAS_LDAP_SSLINIT 1 +#define APR_HAS_LDAPSSL_INIT 0 +#define APR_HAS_LDAPSSL_INSTALL_ROUTINES 0 + + +/* + * Make sure the secure LDAP port is defined + */ +#ifndef LDAPS_PORT +#define LDAPS_PORT 636 /* ldaps:/// default LDAP over TLS port */ +#endif + + +/* + * For ldap function calls that input a size limit on the number of returned elements + * Some SDKs do not have the define for LDAP_DEFAULT_LIMIT (-1) or LDAP_NO_LIMIT (0) + * LDAP_DEFAULT_LIMIT is preferred as it allows inheritance from whatever the SDK + * or process is configured for. + */ +#ifdef LDAP_DEFAULT_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_DEFAULT_LIMIT +#else +#ifdef LDAP_NO_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_NO_LIMIT +#endif +#endif + +#ifndef APR_LDAP_SIZELIMIT +#define APR_LDAP_SIZELIMIT 0 /* equivalent to LDAP_NO_LIMIT, and what goes on the wire */ +#endif + +/* + * z/OS is missing some defines + */ +#ifndef LDAP_VERSION_MAX +#define LDAP_VERSION_MAX LDAP_VERSION +#endif +#if APR_HAS_ZOS_LDAPSDK +#define LDAP_VENDOR_NAME "IBM z/OS" +#endif + +/* Note: Macros defining const casting has been removed in APR v1.0, + * pending real support for LDAP v2.0 toolkits. + * + * In the mean time, please use an LDAP v3.0 toolkit. + */ +#if LDAP_VERSION_MAX <= 2 +#error Support for LDAP v2.0 toolkits has been removed from apr-util. Please use an LDAP v3.0 toolkit. +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * This structure allows the C LDAP API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apr_ldap_err_t { + const char *reason; + const char *msg; + int rc; +} apr_ldap_err_t; + +#ifdef __cplusplus +} +#endif + +/* The MS SDK returns LDAP_UNAVAILABLE when the backend has closed the connection + * between LDAP calls. Protect with APR_HAS_MICROSOFT_LDAPSDK in case someone + * manually chooses another SDK on Windows + */ +#if APR_HAS_MICROSOFT_LDAPSDK +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN \ + || (s) == LDAP_UNAVAILABLE) +#else +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN) +#endif + +/* These symbols are not actually exported in a DSO build, but mapped into + * a private exported function array for apr_ldap_stub to bind dynamically. + * Rename them appropriately to protect the global namespace. + */ +#ifdef APU_DSO_LDAP_BUILD + +#define apr_ldap_info apr__ldap_info +#define apr_ldap_init apr__ldap_init +#define apr_ldap_ssl_init apr__ldap_ssl_init +#define apr_ldap_ssl_deinit apr__ldap_ssl_deinit +#define apr_ldap_get_option apr__ldap_get_option +#define apr_ldap_set_option apr__ldap_set_option +#define apr_ldap_rebind_init apr__ldap_rebind_init +#define apr_ldap_rebind_add apr__ldap_rebind_add +#define apr_ldap_rebind_remove apr__ldap_rebind_remove + +#define APU_DECLARE_LDAP(type) type +#else +#define APU_DECLARE_LDAP(type) APU_DECLARE(type) +#endif + +#include "apr_ldap_url.h" +#include "apr_ldap_init.h" +#include "apr_ldap_option.h" +#include "apr_ldap_rebind.h" + +/** @} */ +#endif /* APR_HAS_LDAP */ +#endif /* APU_LDAP_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_ldap.h.in b/c/dependencies/windows/apr/x64_debug/include/apr_ldap.h.in new file mode 100644 index 00000000..6c62d601 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_ldap.h.in @@ -0,0 +1,197 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_ldap.h is generated from apr_ldap.h.in by configure -- do not edit apr_ldap.h + */ +/** + * @file apr_ldap.h + * @brief APR-UTIL LDAP + */ +#ifndef APU_LDAP_H +#define APU_LDAP_H + +/** + * @defgroup APR_Util_LDAP LDAP + * @ingroup APR_Util + * @{ + */ + +/* this will be defined if LDAP support was compiled into apr-util */ +#define APR_HAS_LDAP @apu_has_ldap@ + +/* identify the LDAP toolkit used */ +#define APR_HAS_NETSCAPE_LDAPSDK @apu_has_ldap_netscape@ +#define APR_HAS_SOLARIS_LDAPSDK @apu_has_ldap_solaris@ +#define APR_HAS_NOVELL_LDAPSDK @apu_has_ldap_novell@ +#define APR_HAS_MOZILLA_LDAPSDK @apu_has_ldap_mozilla@ +#define APR_HAS_OPENLDAP_LDAPSDK @apu_has_ldap_openldap@ +#define APR_HAS_MICROSOFT_LDAPSDK @apu_has_ldap_microsoft@ +#define APR_HAS_TIVOLI_LDAPSDK @apu_has_ldap_tivoli@ +#define APR_HAS_ZOS_LDAPSDK @apu_has_ldap_zos@ +#define APR_HAS_OTHER_LDAPSDK @apu_has_ldap_other@ + + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/* + * The following #defines are DEPRECATED and should not be used for + * anything. They remain to maintain binary compatibility. + * The original code defined the OPENLDAP SDK as present regardless + * of what really was there, which was way bogus. In addition, the + * apr_ldap_url_parse*() functions have been rewritten specifically for + * APR, so the APR_HAS_LDAP_URL_PARSE macro is forced to zero. + */ +#if APR_HAS_TIVOLI_LDAPSDK +#define APR_HAS_LDAP_SSL 0 +#else +#define APR_HAS_LDAP_SSL 1 +#endif +#define APR_HAS_LDAP_URL_PARSE 0 + +#if APR_HAS_OPENLDAP_LDAPSDK && !defined(LDAP_DEPRECATED) +/* Ensure that the "deprecated" interfaces are still exposed + * with OpenLDAP >= 2.3; these were exposed by default in earlier + * releases. */ +#define LDAP_DEPRECATED 1 +#endif + +/* + * Include the standard LDAP header files. + */ + +@lber_h@ +@ldap_h@ +@ldap_ssl_h@ + + +/* + * Detected standard functions + */ +#define APR_HAS_LDAPSSL_CLIENT_INIT @apu_has_ldapssl_client_init@ +#define APR_HAS_LDAPSSL_CLIENT_DEINIT @apu_has_ldapssl_client_deinit@ +#define APR_HAS_LDAPSSL_ADD_TRUSTED_CERT @apu_has_ldapssl_add_trusted_cert@ +#define APR_HAS_LDAP_START_TLS_S @apu_has_ldap_start_tls_s@ +#define APR_HAS_LDAP_SSLINIT @apu_has_ldap_sslinit@ +#define APR_HAS_LDAPSSL_INIT @apu_has_ldapssl_init@ +#define APR_HAS_LDAPSSL_INSTALL_ROUTINES @apu_has_ldapssl_install_routines@ + +/* + * Make sure the secure LDAP port is defined + */ +#ifndef LDAPS_PORT +#define LDAPS_PORT 636 /* ldaps:/// default LDAP over TLS port */ +#endif + +/* + * For ldap function calls that input a size limit on the number of returned elements + * Some SDKs do not have the define for LDAP_DEFAULT_LIMIT (-1) or LDAP_NO_LIMIT (0) + * LDAP_DEFAULT_LIMIT is preferred as it allows inheritance from whatever the SDK + * or process is configured for. + */ +#ifdef LDAP_DEFAULT_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_DEFAULT_LIMIT +#else +#ifdef LDAP_NO_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_NO_LIMIT +#endif +#endif + +#ifndef APR_LDAP_SIZELIMIT +#define APR_LDAP_SIZELIMIT 0 /* equivalent to LDAP_NO_LIMIT, and what goes on the wire */ +#endif + +/* + * z/OS is missing some defines + */ +#ifndef LDAP_VERSION_MAX +#define LDAP_VERSION_MAX LDAP_VERSION +#endif +#if APR_HAS_ZOS_LDAPSDK +#define LDAP_VENDOR_NAME "IBM z/OS" +#endif + +/* Note: Macros defining const casting has been removed in APR v1.0, + * pending real support for LDAP v2.0 toolkits. + * + * In the mean time, please use an LDAP v3.0 toolkit. + */ +#if LDAP_VERSION_MAX <= 2 +#error Support for LDAP v2.0 toolkits has been removed from apr-util. Please use an LDAP v3.0 toolkit. +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * This structure allows the C LDAP API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apr_ldap_err_t { + const char *reason; + const char *msg; + int rc; +} apr_ldap_err_t; + +#ifdef __cplusplus +} +#endif + +/* The MS SDK returns LDAP_UNAVAILABLE when the backend has closed the connection + * between LDAP calls. Protect with APR_HAS_MICROSOFT_LDAPSDK in case someone + * manually chooses another SDK on Windows + */ +#if APR_HAS_MICROSOFT_LDAPSDK +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN \ + || (s) == LDAP_UNAVAILABLE) +#else +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN) +#endif + +/* These symbols are not actually exported in a DSO build, but mapped into + * a private exported function array for apr_ldap_stub to bind dynamically. + * Rename them appropriately to protect the global namespace. + */ +#ifdef APU_DSO_LDAP_BUILD + +#define apr_ldap_info apr__ldap_info +#define apr_ldap_init apr__ldap_init +#define apr_ldap_ssl_init apr__ldap_ssl_init +#define apr_ldap_ssl_deinit apr__ldap_ssl_deinit +#define apr_ldap_get_option apr__ldap_get_option +#define apr_ldap_set_option apr__ldap_set_option +#define apr_ldap_rebind_init apr__ldap_rebind_init +#define apr_ldap_rebind_add apr__ldap_rebind_add +#define apr_ldap_rebind_remove apr__ldap_rebind_remove + +#define APU_DECLARE_LDAP(type) type +#else +#define APU_DECLARE_LDAP(type) APU_DECLARE(type) +#endif + +#include "apr_ldap_url.h" +#include "apr_ldap_init.h" +#include "apr_ldap_option.h" +#include "apr_ldap_rebind.h" + +#endif /* APR_HAS_LDAP */ +/** @} */ +#endif /* APU_LDAP_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_ldap.hnw b/c/dependencies/windows/apr/x64_debug/include/apr_ldap.hnw new file mode 100644 index 00000000..2148c90f --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_ldap.hnw @@ -0,0 +1,158 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_ldap.h is generated from apr_ldap.h.in by configure -- do not edit apr_ldap.h + */ +/** + * @file apr_ldap.h + * @brief APR-UTIL LDAP + */ +#ifndef APU_LDAP_H +#define APU_LDAP_H + +/** + * @defgroup APR_Util_LDAP LDAP + * @ingroup APR_Util + * @{ + */ + +/* this will be defined if LDAP support was compiled into apr-util */ +#define APR_HAS_LDAP 1 + +/* identify the LDAP toolkit used */ +#define APR_HAS_NETSCAPE_LDAPSDK 0 +#define APR_HAS_SOLARIS_LDAPSDK 0 +#define APR_HAS_NOVELL_LDAPSDK 1 +#define APR_HAS_MOZILLA_LDAPSDK 0 +#define APR_HAS_OPENLDAP_LDAPSDK 0 +#define APR_HAS_MICROSOFT_LDAPSDK 0 +#define APR_HAS_OTHER_LDAPSDK 0 + + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/* + * The following #defines are DEPRECATED and should not be used for + * anything. They remain to maintain binary compatibility. + * The original code defined the OPENLDAP SDK as present regardless + * of what really was there, which was way bogus. In addition, the + * apr_ldap_url_parse*() functions have been rewritten specifically for + * APR, so the APR_HAS_LDAP_URL_PARSE macro is forced to zero. + */ +#define APR_HAS_LDAP_SSL 1 +#define APR_HAS_LDAP_URL_PARSE 0 + + +/* + * Include the standard LDAP header files. + */ + +#ifdef GENEXPORTS +#define LDAP_VERSION_MAX 3 +#define LDAP_INSUFFICIENT_ACCESS +#else +#include +#include +#if APR_HAS_LDAP_SSL +#include +#endif +#endif + + +/* + * Detected standard functions + */ +#define APR_HAS_LDAPSSL_CLIENT_INIT 1 +#define APR_HAS_LDAPSSL_CLIENT_DEINIT 1 +#define APR_HAS_LDAPSSL_ADD_TRUSTED_CERT 1 +#define APR_HAS_LDAP_START_TLS_S 0 +#define APR_HAS_LDAP_SSLINIT 0 +#define APR_HAS_LDAPSSL_INIT 1 +#define APR_HAS_LDAPSSL_INSTALL_ROUTINES 0 + + +/* + * Make sure the secure LDAP port is defined + */ +#ifndef LDAPS_PORT +#define LDAPS_PORT 636 /* ldaps:/// default LDAP over TLS port */ +#endif + + +/* Note: Macros defining const casting has been removed in APR v1.0, + * pending real support for LDAP v2.0 toolkits. + * + * In the mean time, please use an LDAP v3.0 toolkit. + */ +#if LDAP_VERSION_MAX <= 2 +#error Support for LDAP v2.0 toolkits has been removed from apr-util. Please use an LDAP v3.0 toolkit. +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * This structure allows the C LDAP API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apr_ldap_err_t { + const char *reason; + const char *msg; + int rc; +} apr_ldap_err_t; + +#ifdef __cplusplus +} +#endif + +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN) + +/* These symbols are not actually exported in a DSO build, but mapped into + * a private exported function array for apr_ldap_stub to bind dynamically. + * Rename them appropriately to protect the global namespace. + */ +#ifdef APU_DSO_LDAP_BUILD + +#define apr_ldap_info apr__ldap_info +#define apr_ldap_init apr__ldap_init +#define apr_ldap_ssl_init apr__ldap_ssl_init +#define apr_ldap_ssl_deinit apr__ldap_ssl_deinit +#define apr_ldap_get_option apr__ldap_get_option +#define apr_ldap_set_option apr__ldap_set_option +#define apr_ldap_rebind_init apr__ldap_rebind_init +#define apr_ldap_rebind_add apr__ldap_rebind_add +#define apr_ldap_rebind_remove apr__ldap_rebind_remove + +#define APU_DECLARE_LDAP(type) type +#else +#define APU_DECLARE_LDAP(type) APU_DECLARE(type) +#endif + +#include "apr_ldap_url.h" +#include "apr_ldap_init.h" +#include "apr_ldap_option.h" +#include "apr_ldap_rebind.h" + +/** @} */ +#endif /* APR_HAS_LDAP */ +#endif /* APU_LDAP_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_ldap.hw b/c/dependencies/windows/apr/x64_debug/include/apr_ldap.hw new file mode 100644 index 00000000..fcef8b17 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_ldap.hw @@ -0,0 +1,197 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_ldap.h is generated from apr_ldap.h.in by configure -- do not edit apr_ldap.h + */ +/** + * @file apr_ldap.h + * @brief APR-UTIL LDAP + */ +#ifndef APU_LDAP_H +#define APU_LDAP_H + +/** + * @defgroup APR_Util_LDAP LDAP + * @ingroup APR_Util + * @{ + */ + +/* this will be defined if LDAP support was compiled into apr-util */ +#define APR_HAS_LDAP 1 + +/* identify the LDAP toolkit used */ +#define APR_HAS_NETSCAPE_LDAPSDK 0 +#define APR_HAS_SOLARIS_LDAPSDK 0 +#define APR_HAS_NOVELL_LDAPSDK 0 +#define APR_HAS_MOZILLA_LDAPSDK 0 +#define APR_HAS_OPENLDAP_LDAPSDK 0 +#define APR_HAS_MICROSOFT_LDAPSDK 1 +#define APR_HAS_TIVOLI_LDAPSDK 0 +#define APR_HAS_ZOS_LDAPSDK 0 +#define APR_HAS_OTHER_LDAPSDK 0 + + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/* + * The following #defines are DEPRECATED and should not be used for + * anything. They remain to maintain binary compatibility. + * The original code defined the OPENLDAP SDK as present regardless + * of what really was there, which was way bogus. In addition, the + * apr_ldap_url_parse*() functions have been rewritten specifically for + * APR, so the APR_HAS_LDAP_URL_PARSE macro is forced to zero. + */ +#if APR_HAS_TIVOLI_LDAPSDK +#define APR_HAS_LDAP_SSL 0 +#else +#define APR_HAS_LDAP_SSL 1 +#endif +#define APR_HAS_LDAP_URL_PARSE 0 + +#if APR_HAS_OPENLDAP_LDAPSDK && !defined(LDAP_DEPRECATED) +/* Ensure that the "deprecated" interfaces are still exposed + * with OpenLDAP >= 2.3; these were exposed by default in earlier + * releases. */ +#define LDAP_DEPRECATED 1 +#endif + +/* + * Include the standard LDAP header files. + */ + +#include + + +/* + * Detected standard functions + */ +#define APR_HAS_LDAPSSL_CLIENT_INIT 0 +#define APR_HAS_LDAPSSL_CLIENT_DEINIT 0 +#define APR_HAS_LDAPSSL_ADD_TRUSTED_CERT 0 +#define APR_HAS_LDAP_START_TLS_S 0 +#define APR_HAS_LDAP_SSLINIT 1 +#define APR_HAS_LDAPSSL_INIT 0 +#define APR_HAS_LDAPSSL_INSTALL_ROUTINES 0 + + +/* + * Make sure the secure LDAP port is defined + */ +#ifndef LDAPS_PORT +#define LDAPS_PORT 636 /* ldaps:/// default LDAP over TLS port */ +#endif + + +/* + * For ldap function calls that input a size limit on the number of returned elements + * Some SDKs do not have the define for LDAP_DEFAULT_LIMIT (-1) or LDAP_NO_LIMIT (0) + * LDAP_DEFAULT_LIMIT is preferred as it allows inheritance from whatever the SDK + * or process is configured for. + */ +#ifdef LDAP_DEFAULT_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_DEFAULT_LIMIT +#else +#ifdef LDAP_NO_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_NO_LIMIT +#endif +#endif + +#ifndef APR_LDAP_SIZELIMIT +#define APR_LDAP_SIZELIMIT 0 /* equivalent to LDAP_NO_LIMIT, and what goes on the wire */ +#endif + +/* + * z/OS is missing some defines + */ +#ifndef LDAP_VERSION_MAX +#define LDAP_VERSION_MAX LDAP_VERSION +#endif +#if APR_HAS_ZOS_LDAPSDK +#define LDAP_VENDOR_NAME "IBM z/OS" +#endif + +/* Note: Macros defining const casting has been removed in APR v1.0, + * pending real support for LDAP v2.0 toolkits. + * + * In the mean time, please use an LDAP v3.0 toolkit. + */ +#if LDAP_VERSION_MAX <= 2 +#error Support for LDAP v2.0 toolkits has been removed from apr-util. Please use an LDAP v3.0 toolkit. +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * This structure allows the C LDAP API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apr_ldap_err_t { + const char *reason; + const char *msg; + int rc; +} apr_ldap_err_t; + +#ifdef __cplusplus +} +#endif + +/* The MS SDK returns LDAP_UNAVAILABLE when the backend has closed the connection + * between LDAP calls. Protect with APR_HAS_MICROSOFT_LDAPSDK in case someone + * manually chooses another SDK on Windows + */ +#if APR_HAS_MICROSOFT_LDAPSDK +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN \ + || (s) == LDAP_UNAVAILABLE) +#else +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN) +#endif + +/* These symbols are not actually exported in a DSO build, but mapped into + * a private exported function array for apr_ldap_stub to bind dynamically. + * Rename them appropriately to protect the global namespace. + */ +#ifdef APU_DSO_LDAP_BUILD + +#define apr_ldap_info apr__ldap_info +#define apr_ldap_init apr__ldap_init +#define apr_ldap_ssl_init apr__ldap_ssl_init +#define apr_ldap_ssl_deinit apr__ldap_ssl_deinit +#define apr_ldap_get_option apr__ldap_get_option +#define apr_ldap_set_option apr__ldap_set_option +#define apr_ldap_rebind_init apr__ldap_rebind_init +#define apr_ldap_rebind_add apr__ldap_rebind_add +#define apr_ldap_rebind_remove apr__ldap_rebind_remove + +#define APU_DECLARE_LDAP(type) type +#else +#define APU_DECLARE_LDAP(type) APU_DECLARE(type) +#endif + +#include "apr_ldap_url.h" +#include "apr_ldap_init.h" +#include "apr_ldap_option.h" +#include "apr_ldap_rebind.h" + +/** @} */ +#endif /* APR_HAS_LDAP */ +#endif /* APU_LDAP_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_ldap.hwc b/c/dependencies/windows/apr/x64_debug/include/apr_ldap.hwc new file mode 100644 index 00000000..4d07b296 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_ldap.hwc @@ -0,0 +1,197 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_ldap.h is generated from apr_ldap.h.in by configure -- do not edit apr_ldap.h + */ +/** + * @file apr_ldap.h + * @brief APR-UTIL LDAP + */ +#ifndef APU_LDAP_H +#define APU_LDAP_H + +/** + * @defgroup APR_Util_LDAP LDAP + * @ingroup APR_Util + * @{ + */ + +/* this will be defined if LDAP support was compiled into apr-util */ +#define APR_HAS_LDAP @apr_has_ldap_10@ + +/* identify the LDAP toolkit used */ +#define APR_HAS_NETSCAPE_LDAPSDK 0 +#define APR_HAS_SOLARIS_LDAPSDK 0 +#define APR_HAS_NOVELL_LDAPSDK 0 +#define APR_HAS_MOZILLA_LDAPSDK 0 +#define APR_HAS_OPENLDAP_LDAPSDK 0 +#define APR_HAS_MICROSOFT_LDAPSDK 1 +#define APR_HAS_TIVOLI_LDAPSDK 0 +#define APR_HAS_ZOS_LDAPSDK 0 +#define APR_HAS_OTHER_LDAPSDK 0 + + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/* + * The following #defines are DEPRECATED and should not be used for + * anything. They remain to maintain binary compatibility. + * The original code defined the OPENLDAP SDK as present regardless + * of what really was there, which was way bogus. In addition, the + * apr_ldap_url_parse*() functions have been rewritten specifically for + * APR, so the APR_HAS_LDAP_URL_PARSE macro is forced to zero. + */ +#if APR_HAS_TIVOLI_LDAPSDK +#define APR_HAS_LDAP_SSL 0 +#else +#define APR_HAS_LDAP_SSL 1 +#endif +#define APR_HAS_LDAP_URL_PARSE 0 + +#if APR_HAS_OPENLDAP_LDAPSDK && !defined(LDAP_DEPRECATED) +/* Ensure that the "deprecated" interfaces are still exposed + * with OpenLDAP >= 2.3; these were exposed by default in earlier + * releases. */ +#define LDAP_DEPRECATED 1 +#endif + +/* + * Include the standard LDAP header files. + */ + +#include + + +/* + * Detected standard functions + */ +#define APR_HAS_LDAPSSL_CLIENT_INIT 0 +#define APR_HAS_LDAPSSL_CLIENT_DEINIT 0 +#define APR_HAS_LDAPSSL_ADD_TRUSTED_CERT 0 +#define APR_HAS_LDAP_START_TLS_S 0 +#define APR_HAS_LDAP_SSLINIT 1 +#define APR_HAS_LDAPSSL_INIT 0 +#define APR_HAS_LDAPSSL_INSTALL_ROUTINES 0 + + +/* + * Make sure the secure LDAP port is defined + */ +#ifndef LDAPS_PORT +#define LDAPS_PORT 636 /* ldaps:/// default LDAP over TLS port */ +#endif + + +/* + * For ldap function calls that input a size limit on the number of returned elements + * Some SDKs do not have the define for LDAP_DEFAULT_LIMIT (-1) or LDAP_NO_LIMIT (0) + * LDAP_DEFAULT_LIMIT is preferred as it allows inheritance from whatever the SDK + * or process is configured for. + */ +#ifdef LDAP_DEFAULT_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_DEFAULT_LIMIT +#else +#ifdef LDAP_NO_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_NO_LIMIT +#endif +#endif + +#ifndef APR_LDAP_SIZELIMIT +#define APR_LDAP_SIZELIMIT 0 /* equivalent to LDAP_NO_LIMIT, and what goes on the wire */ +#endif + +/* + * z/OS is missing some defines + */ +#ifndef LDAP_VERSION_MAX +#define LDAP_VERSION_MAX LDAP_VERSION +#endif +#if APR_HAS_ZOS_LDAPSDK +#define LDAP_VENDOR_NAME "IBM z/OS" +#endif + +/* Note: Macros defining const casting has been removed in APR v1.0, + * pending real support for LDAP v2.0 toolkits. + * + * In the mean time, please use an LDAP v3.0 toolkit. + */ +#if LDAP_VERSION_MAX <= 2 +#error Support for LDAP v2.0 toolkits has been removed from apr-util. Please use an LDAP v3.0 toolkit. +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * This structure allows the C LDAP API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apr_ldap_err_t { + const char *reason; + const char *msg; + int rc; +} apr_ldap_err_t; + +#ifdef __cplusplus +} +#endif + +/* The MS SDK returns LDAP_UNAVAILABLE when the backend has closed the connection + * between LDAP calls. Protect with APR_HAS_MICROSOFT_LDAPSDK in case someone + * manually chooses another SDK on Windows + */ +#if APR_HAS_MICROSOFT_LDAPSDK +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN \ + || (s) == LDAP_UNAVAILABLE) +#else +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN) +#endif + +/* These symbols are not actually exported in a DSO build, but mapped into + * a private exported function array for apr_ldap_stub to bind dynamically. + * Rename them appropriately to protect the global namespace. + */ +#ifdef APU_DSO_LDAP_BUILD + +#define apr_ldap_info apr__ldap_info +#define apr_ldap_init apr__ldap_init +#define apr_ldap_ssl_init apr__ldap_ssl_init +#define apr_ldap_ssl_deinit apr__ldap_ssl_deinit +#define apr_ldap_get_option apr__ldap_get_option +#define apr_ldap_set_option apr__ldap_set_option +#define apr_ldap_rebind_init apr__ldap_rebind_init +#define apr_ldap_rebind_add apr__ldap_rebind_add +#define apr_ldap_rebind_remove apr__ldap_rebind_remove + +#define APU_DECLARE_LDAP(type) type +#else +#define APU_DECLARE_LDAP(type) APU_DECLARE(type) +#endif + +#include "apr_ldap_url.h" +#include "apr_ldap_init.h" +#include "apr_ldap_option.h" +#include "apr_ldap_rebind.h" + +/** @} */ +#endif /* APR_HAS_LDAP */ +#endif /* APU_LDAP_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_ldap_init.h b/c/dependencies/windows/apr/x64_debug/include/apr_ldap_init.h new file mode 100644 index 00000000..aeb6d9bb --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_ldap_init.h @@ -0,0 +1,165 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_ldap_init.h + * @brief APR-UTIL LDAP ldap_init() functions + */ +#ifndef APR_LDAP_INIT_H +#define APR_LDAP_INIT_H + +/** + * @addtogroup APR_Util_LDAP + * @{ + */ + +#include "apr_ldap.h" + +#if APR_HAS_LDAP + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + + +/** + * Macro to detect security related return values. + */ +#if defined(LDAP_INSUFFICIENT_ACCESS) +#define APU_LDAP_INSUFFICIENT_ACCESS LDAP_INSUFFICIENT_ACCESS +#elif defined(LDAP_INSUFFICIENT_RIGHTS) +#define APU_LDAP_INSUFFICIENT_ACCESS LDAP_INSUFFICIENT_RIGHTS +#elif defined(APR_HAS_MICROSOFT_LDAPSDK) +/* The macros above fail to contemplate that LDAP_RETCODE values + * may be represented by an enum. autoconf tests would be much + * more robust. + */ +#define APU_LDAP_INSUFFICIENT_ACCESS LDAP_INSUFFICIENT_RIGHTS +#else +#error The security return codes must be added to support this LDAP toolkit. +#endif + +#if defined(LDAP_SECURITY_ERROR) +#define APU_LDAP_SECURITY_ERROR LDAP_SECURITY_ERROR +#else +#define APU_LDAP_SECURITY_ERROR(n) \ + (LDAP_INAPPROPRIATE_AUTH == n) ? 1 \ + : (LDAP_INVALID_CREDENTIALS == n) ? 1 \ + : (APU_LDAP_INSUFFICIENT_ACCESS == n) ? 1 \ + : 0 +#endif + + +/** + * APR LDAP SSL Initialise function + * + * This function initialises SSL on the underlying LDAP toolkit + * if this is necessary. + * + * If a CA certificate is provided, this is set, however the setting + * of certificates via this method has been deprecated and will be removed in + * APR v2.0. + * + * The apr_ldap_set_option() function with the APR_LDAP_OPT_TLS_CERT option + * should be used instead to set certificates. + * + * If SSL support is not available on this platform, or a problem + * was encountered while trying to set the certificate, the function + * will return APR_EGENERAL. Further LDAP specific error information + * can be found in result_err. + * @param pool The pool to use + * @param cert_auth_file The name of the certificate to use, can be NULL + * @param cert_file_type The type of certificate specified. See the + * apr_ldap_set_option() APR_LDAP_OPT_TLS_CERT option for details. + * @param result_err The returned result + */ +APU_DECLARE_LDAP(int) apr_ldap_ssl_init(apr_pool_t *pool, + const char *cert_auth_file, + int cert_file_type, + apr_ldap_err_t **result_err); + +/** + * APR LDAP SSL De-Initialise function + * + * This function tears down any SSL certificate setup previously + * set using apr_ldap_ssl_init(). It should be called to clean + * up if a graceful restart of a service is attempted. + * @todo currently we do not check whether apr_ldap_ssl_init() + * has been called first - we probably should. + */ +APU_DECLARE_LDAP(int) apr_ldap_ssl_deinit(void); + +/** + * APR LDAP initialise function + * + * This function is responsible for initialising an LDAP + * connection in a toolkit independant way. It does the + * job of ldap_init() from the C api. + * + * It handles both the SSL and non-SSL case, and attempts + * to hide the complexity setup from the user. This function + * assumes that any certificate setup necessary has already + * been done. + * + * If SSL or STARTTLS needs to be enabled, and the underlying + * toolkit supports it, the following values are accepted for + * secure: + * + * APR_LDAP_NONE: No encryption + * APR_LDAP_SSL: SSL encryption (ldaps://) + * APR_LDAP_STARTTLS: Force STARTTLS on ldap:// + * @remark The Novell toolkit is only able to set the SSL mode via this + * function. To work around this limitation, set the SSL mode here if no + * per connection client certificates are present, otherwise set secure + * APR_LDAP_NONE here, then set the per connection client certificates, + * followed by setting the SSL mode via apr_ldap_set_option(). As Novell + * does not support per connection client certificates, this problem is + * worked around while still being compatible with other LDAP toolkits. + * @param pool The pool to use + * @param ldap The LDAP handle + * @param hostname The name of the host to connect to. This can be either a + * DNS name, or an IP address. + * @param portno The port to connect to + * @param secure The security mode to set + * @param result_err The returned result + */ +APU_DECLARE_LDAP(int) apr_ldap_init(apr_pool_t *pool, + LDAP **ldap, + const char *hostname, + int portno, + int secure, + apr_ldap_err_t **result_err); + +/** + * APR LDAP info function + * + * This function returns a string describing the LDAP toolkit + * currently in use. The string is placed inside result_err->reason. + * @param pool The pool to use + * @param result_err The returned result + */ +APU_DECLARE_LDAP(int) apr_ldap_info(apr_pool_t *pool, + apr_ldap_err_t **result_err); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_HAS_LDAP */ + +/** @} */ + +#endif /* APR_LDAP_URL_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_ldap_option.h b/c/dependencies/windows/apr/x64_debug/include/apr_ldap_option.h new file mode 100644 index 00000000..0ff8a862 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_ldap_option.h @@ -0,0 +1,254 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_ldap_option.h + * @brief APR-UTIL LDAP ldap_*_option() functions + */ +#ifndef APR_LDAP_OPTION_H +#define APR_LDAP_OPTION_H + +/** + * @addtogroup APR_Util_LDAP + * @{ + */ + +#include "apr_ldap.h" + +#if APR_HAS_LDAP + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* + * The following defines handle the different TLS certificate + * options available. If these options are missing, APR will try and + * emulate support for this using the deprecated ldap_start_tls_s() + * function. + */ +/** + * Set SSL mode to one of APR_LDAP_NONE, APR_LDAP_SSL, APR_LDAP_STARTTLS + * or APR_LDAP_STOPTLS. + */ +#define APR_LDAP_OPT_TLS 0x6fff +/** + * Set zero or more CA certificates, client certificates or private + * keys globally, or per connection (where supported). + */ +#define APR_LDAP_OPT_TLS_CERT 0x6ffe +/** + * Set the LDAP library to no verify the server certificate. This means + * all servers are considered trusted. + */ +#define APR_LDAP_OPT_VERIFY_CERT 0x6ffd +/** + * Set the LDAP library to indicate if referrals should be chased during + * LDAP searches. + */ +#define APR_LDAP_OPT_REFERRALS 0x6ffc +/** + * Set the LDAP library to indicate a maximum number of referral hops to + * chase before giving up on the search. + */ +#define APR_LDAP_OPT_REFHOPLIMIT 0x6ffb + +/** + * Structures for the apr_set_option() cases + */ + +/** + * APR_LDAP_OPT_TLS_CERT + * + * This structure includes possible options to set certificates on + * system initialisation. Different SDKs have different certificate + * requirements, and to achieve this multiple certificates must be + * specified at once passed as an (apr_array_header_t *). + * + * Netscape: + * Needs the CA cert database (cert7.db), the client cert database (key3.db) + * and the security module file (secmod.db) set at the system initialisation + * time. Three types are supported: APR_LDAP_CERT7_DB, APR_LDAP_KEY3_DB and + * APR_LDAP_SECMOD. + * + * To specify a client cert connection, a certificate nickname needs to be + * provided with a type of APR_LDAP_CERT. + * int ldapssl_enable_clientauth( LDAP *ld, char *keynickname, + * char *keypasswd, char *certnickname ); + * keynickname is currently not used, and should be set to "" + * + * Novell: + * Needs CA certificates and client certificates set at system initialisation + * time. Three types are supported: APR_LDAP_CA*, APR_LDAP_CERT* and + * APR_LDAP_KEY*. + * + * Certificates cannot be specified per connection. + * + * The functions used are: + * ldapssl_add_trusted_cert(serverTrustedRoot, serverTrustedRootEncoding); + * Clients certs and keys are set at system initialisation time with + * int ldapssl_set_client_cert ( + * void *cert, + * int type + * void *password); + * type can be LDAPSSL_CERT_FILETYPE_B64 or LDAPSSL_CERT_FILETYPE_DER + * ldapssl_set_client_private_key(clientPrivateKey, + * clientPrivateKeyEncoding, + * clientPrivateKeyPassword); + * + * OpenSSL: + * Needs one or more CA certificates to be set at system initialisation time + * with a type of APR_LDAP_CA*. + * + * May have one or more client certificates set per connection with a type of + * APR_LDAP_CERT*, and keys with APR_LDAP_KEY*. + */ +/** CA certificate type unknown */ +#define APR_LDAP_CA_TYPE_UNKNOWN 0 +/** binary DER encoded CA certificate */ +#define APR_LDAP_CA_TYPE_DER 1 +/** PEM encoded CA certificate */ +#define APR_LDAP_CA_TYPE_BASE64 2 +/** Netscape/Mozilla cert7.db CA certificate database */ +#define APR_LDAP_CA_TYPE_CERT7_DB 3 +/** Netscape/Mozilla secmod file */ +#define APR_LDAP_CA_TYPE_SECMOD 4 +/** Client certificate type unknown */ +#define APR_LDAP_CERT_TYPE_UNKNOWN 5 +/** binary DER encoded client certificate */ +#define APR_LDAP_CERT_TYPE_DER 6 +/** PEM encoded client certificate */ +#define APR_LDAP_CERT_TYPE_BASE64 7 +/** Netscape/Mozilla key3.db client certificate database */ +#define APR_LDAP_CERT_TYPE_KEY3_DB 8 +/** Netscape/Mozilla client certificate nickname */ +#define APR_LDAP_CERT_TYPE_NICKNAME 9 +/** Private key type unknown */ +#define APR_LDAP_KEY_TYPE_UNKNOWN 10 +/** binary DER encoded private key */ +#define APR_LDAP_KEY_TYPE_DER 11 +/** PEM encoded private key */ +#define APR_LDAP_KEY_TYPE_BASE64 12 +/** PKCS#12 encoded client certificate */ +#define APR_LDAP_CERT_TYPE_PFX 13 +/** PKCS#12 encoded private key */ +#define APR_LDAP_KEY_TYPE_PFX 14 +/** Openldap directory full of base64-encoded cert + * authorities with hashes in corresponding .0 directory + */ +#define APR_LDAP_CA_TYPE_CACERTDIR_BASE64 15 + + +/** + * Certificate structure. + * + * This structure is used to store certificate details. An array of + * these structures is passed to apr_ldap_set_option() to set CA + * and client certificates. + * @param type Type of certificate APR_LDAP_*_TYPE_* + * @param path Path, file or nickname of the certificate + * @param password Optional password, can be NULL + */ +typedef struct apr_ldap_opt_tls_cert_t apr_ldap_opt_tls_cert_t; +struct apr_ldap_opt_tls_cert_t { + int type; + const char *path; + const char *password; +}; + +/** + * APR_LDAP_OPT_TLS + * + * This sets the SSL level on the LDAP handle. + * + * Netscape/Mozilla: + * Supports SSL, but not STARTTLS + * SSL is enabled by calling ldapssl_install_routines(). + * + * Novell: + * Supports SSL and STARTTLS. + * SSL is enabled by calling ldapssl_install_routines(). Note that calling + * other ldap functions before ldapssl_install_routines() may cause this + * function to fail. + * STARTTLS is enabled by calling ldapssl_start_tls_s() after calling + * ldapssl_install_routines() (check this). + * + * OpenLDAP: + * Supports SSL and supports STARTTLS, but none of this is documented: + * http://www.openldap.org/lists/openldap-software/200409/msg00618.html + * Documentation for both SSL support and STARTTLS has been deleted from + * the OpenLDAP documentation and website. + */ + +/** No encryption */ +#define APR_LDAP_NONE 0 +/** SSL encryption (ldaps://) */ +#define APR_LDAP_SSL 1 +/** TLS encryption (STARTTLS) */ +#define APR_LDAP_STARTTLS 2 +/** end TLS encryption (STOPTLS) */ +#define APR_LDAP_STOPTLS 3 + +/** + * APR LDAP get option function + * + * This function gets option values from a given LDAP session if + * one was specified. It maps to the native ldap_get_option() function. + * @param pool The pool to use + * @param ldap The LDAP handle + * @param option The LDAP_OPT_* option to return + * @param outvalue The value returned (if any) + * @param result_err The apr_ldap_err_t structure contained detailed results + * of the operation. + */ +APU_DECLARE_LDAP(int) apr_ldap_get_option(apr_pool_t *pool, + LDAP *ldap, + int option, + void *outvalue, + apr_ldap_err_t **result_err); + +/** + * APR LDAP set option function + * + * This function sets option values to a given LDAP session if + * one was specified. It maps to the native ldap_set_option() function. + * + * Where an option is not supported by an LDAP toolkit, this function + * will try and apply legacy functions to achieve the same effect, + * depending on the platform. + * @param pool The pool to use + * @param ldap The LDAP handle + * @param option The LDAP_OPT_* option to set + * @param invalue The value to set + * @param result_err The apr_ldap_err_t structure contained detailed results + * of the operation. + */ +APU_DECLARE_LDAP(int) apr_ldap_set_option(apr_pool_t *pool, + LDAP *ldap, + int option, + const void *invalue, + apr_ldap_err_t **result_err); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_HAS_LDAP */ + +/** @} */ + +#endif /* APR_LDAP_OPTION_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_ldap_rebind.h b/c/dependencies/windows/apr/x64_debug/include/apr_ldap_rebind.h new file mode 100644 index 00000000..342a17c3 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_ldap_rebind.h @@ -0,0 +1,98 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The APR LDAP rebind functions provide an implementation of + * a rebind procedure that can be used to allow clients to chase referrals, + * using the same credentials used to log in originally. + * + * Use of this implementation is optional. + * + * @file apr_ldap_rebind.h + * @brief Apache LDAP library + */ + +#ifndef APU_LDAP_REBIND_H +#define APU_LDAP_REBIND_H + +/** + * @addtogroup APR_Util_LDAP + * @{ + **/ + +#if defined(DOXYGEN) +#include "apr_ldap.h" +#endif + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/** + * APR LDAP initialize rebind lock + * + * This function creates the lock for controlling access to the xref list.. + * @param pool Pool to use when creating the xref_lock. + */ +APU_DECLARE_LDAP(apr_status_t) apr_ldap_rebind_init(apr_pool_t *pool); + + +/** + * APR LDAP rebind_add function + * + * This function creates a cross reference entry for the specified ldap + * connection. The rebind callback function will look up this ldap + * connection so it can retrieve the bindDN and bindPW for use in any + * binds while referrals are being chased. + * + * This function will add the callback to the LDAP handle passed in. + * + * A cleanup is registered within the pool provided to remove this + * entry when the pool is removed. Alternatively apr_ldap_rebind_remove() + * can be called to explicitly remove the entry at will. + * + * @param pool The pool to use + * @param ld The LDAP connectionhandle + * @param bindDN The bind DN to be used for any binds while chasing + * referrals on this ldap connection. + * @param bindPW The bind Password to be used for any binds while + * chasing referrals on this ldap connection. + */ +APU_DECLARE_LDAP(apr_status_t) apr_ldap_rebind_add(apr_pool_t *pool, + LDAP *ld, + const char *bindDN, + const char *bindPW); + +/** + * APR LDAP rebind_remove function + * + * This function removes the rebind cross reference entry for the + * specified ldap connection. + * + * If not explicitly removed, this function will be called automatically + * when the pool is cleaned up. + * + * @param ld The LDAP connectionhandle + */ +APU_DECLARE_LDAP(apr_status_t) apr_ldap_rebind_remove(LDAP *ld); + +#endif /* APR_HAS_LDAP */ + +/** @} */ + +#endif /* APU_LDAP_REBIND_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_ldap_url.h b/c/dependencies/windows/apr/x64_debug/include/apr_ldap_url.h new file mode 100644 index 00000000..a71f5b3c --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_ldap_url.h @@ -0,0 +1,120 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_ldap_url.h + * @brief APR-UTIL LDAP ldap_init() functions + */ +#ifndef APR_LDAP_URL_H +#define APR_LDAP_URL_H + +/** + * @addtogroup APR_Util_LDAP + * @{ + */ + +#if defined(DOXYGEN) +#include "apr_ldap.h" +#endif + +#if APR_HAS_LDAP + +#include "apu.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** Structure to access an exploded LDAP URL */ +typedef struct apr_ldap_url_desc_t { + struct apr_ldap_url_desc_t *lud_next; + char *lud_scheme; + char *lud_host; + int lud_port; + char *lud_dn; + char **lud_attrs; + int lud_scope; + char *lud_filter; + char **lud_exts; + int lud_crit_exts; +} apr_ldap_url_desc_t; + +#ifndef APR_LDAP_URL_SUCCESS +#define APR_LDAP_URL_SUCCESS 0x00 /* Success */ +#define APR_LDAP_URL_ERR_MEM 0x01 /* can't allocate memory space */ +#define APR_LDAP_URL_ERR_PARAM 0x02 /* parameter is bad */ +#define APR_LDAP_URL_ERR_BADSCHEME 0x03 /* URL doesn't begin with "ldap[si]://" */ +#define APR_LDAP_URL_ERR_BADENCLOSURE 0x04 /* URL is missing trailing ">" */ +#define APR_LDAP_URL_ERR_BADURL 0x05 /* URL is bad */ +#define APR_LDAP_URL_ERR_BADHOST 0x06 /* host port is bad */ +#define APR_LDAP_URL_ERR_BADATTRS 0x07 /* bad (or missing) attributes */ +#define APR_LDAP_URL_ERR_BADSCOPE 0x08 /* scope string is invalid (or missing) */ +#define APR_LDAP_URL_ERR_BADFILTER 0x09 /* bad or missing filter */ +#define APR_LDAP_URL_ERR_BADEXTS 0x0a /* bad or missing extensions */ +#endif + +/** + * Is this URL an ldap url? ldap:// + * @param url The url to test + */ +APU_DECLARE(int) apr_ldap_is_ldap_url(const char *url); + +/** + * Is this URL an SSL ldap url? ldaps:// + * @param url The url to test + */ +APU_DECLARE(int) apr_ldap_is_ldaps_url(const char *url); + +/** + * Is this URL an ldap socket url? ldapi:// + * @param url The url to test + */ +APU_DECLARE(int) apr_ldap_is_ldapi_url(const char *url); + +/** + * Parse an LDAP URL. + * @param pool The pool to use + * @param url_in The URL to parse + * @param ludpp The structure to return the exploded URL + * @param result_err The result structure of the operation + */ +APU_DECLARE(int) apr_ldap_url_parse_ext(apr_pool_t *pool, + const char *url_in, + apr_ldap_url_desc_t **ludpp, + apr_ldap_err_t **result_err); + +/** + * Parse an LDAP URL. + * @param pool The pool to use + * @param url_in The URL to parse + * @param ludpp The structure to return the exploded URL + * @param result_err The result structure of the operation + */ +APU_DECLARE(int) apr_ldap_url_parse(apr_pool_t *pool, + const char *url_in, + apr_ldap_url_desc_t **ludpp, + apr_ldap_err_t **result_err); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_HAS_LDAP */ + +/** @} */ + +#endif /* APR_LDAP_URL_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_lib.h b/c/dependencies/windows/apr/x64_debug/include/apr_lib.h new file mode 100644 index 00000000..466e8185 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_lib.h @@ -0,0 +1,241 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_LIB_H +#define APR_LIB_H + +/** + * @file apr_lib.h + * This is collection of oddballs that didn't fit anywhere else, + * and might move to more appropriate headers with the release + * of APR 1.0. + * @brief APR general purpose library routines + */ + +#include "apr.h" +#include "apr_errno.h" + +#if APR_HAVE_CTYPE_H +#include +#endif +#if APR_HAVE_STDARG_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_lib General Purpose Library Routines + * @ingroup APR + * This is collection of oddballs that didn't fit anywhere else, + * and might move to more appropriate headers with the release + * of APR 1.0. + * @{ + */ + +/** A constant representing a 'large' string. */ +#define HUGE_STRING_LEN 8192 + +/* + * Define the structures used by the APR general-purpose library. + */ + +/** @see apr_vformatter_buff_t */ +typedef struct apr_vformatter_buff_t apr_vformatter_buff_t; + +/** + * Structure used by the variable-formatter routines. + */ +struct apr_vformatter_buff_t { + /** The current position */ + char *curpos; + /** The end position of the format string */ + char *endpos; +}; + +/** + * return the final element of the pathname + * @param pathname The path to get the final element of + * @return the final element of the path + * @remark + *
+ * For example:
+ *                 "/foo/bar/gum"    -> "gum"
+ *                 "/foo/bar/gum/"   -> ""
+ *                 "gum"             -> "gum"
+ *                 "bs\\path\\stuff" -> "stuff"
+ * 
+ */ +APR_DECLARE(const char *) apr_filepath_name_get(const char *pathname); + +/** + * apr_killpg + * Small utility macros to make things easier to read. Not usually a + * goal, to be sure.. + */ + +#ifdef WIN32 +#define apr_killpg(x, y) +#else /* WIN32 */ +#ifdef NO_KILLPG +#define apr_killpg(x, y) (kill (-(x), (y))) +#else /* NO_KILLPG */ +#define apr_killpg(x, y) (killpg ((x), (y))) +#endif /* NO_KILLPG */ +#endif /* WIN32 */ + +/** + * apr_vformatter() is a generic printf-style formatting routine + * with some extensions. + * @param flush_func The function to call when the buffer is full + * @param c The buffer to write to + * @param fmt The format string + * @param ap The arguments to use to fill out the format string. + * + * @remark + *
+ * The extensions are:
+ *
+ * - %%pA takes a struct in_addr *, and prints it as a.b.c.d
+ * - %%pI takes an apr_sockaddr_t * and prints it as a.b.c.d:port or
+ * \[ipv6-address\]:port
+ * - %%pT takes an apr_os_thread_t * and prints it in decimal
+ * ('0' is printed if !APR_HAS_THREADS)
+ * - %%pt takes an apr_os_thread_t * and prints it in hexadecimal
+ * ('0' is printed if !APR_HAS_THREADS)
+ * - %%pm takes an apr_status_t * and prints the appropriate error
+ * string (from apr_strerror) corresponding to that error code.
+ * - %%pp takes a void * and outputs it in hex
+ * - %%pB takes a apr_uint32_t * as bytes and outputs it's apr_strfsize
+ * - %%pF same as above, but takes a apr_off_t *
+ * - %%pS same as above, but takes a apr_size_t *
+ *
+ * %%pA, %%pI, %%pT, %%pp are available from APR 1.0.0 onwards (and in 0.9.x).
+ * %%pt is only available from APR 1.2.0 onwards.
+ * %%pm, %%pB, %%pF and %%pS are only available from APR 1.3.0 onwards.
+ *
+ * The %%p hacks are to force gcc's printf warning code to skip
+ * over a pointer argument without complaining.  This does
+ * mean that the ANSI-style %%p (output a void * in hex format) won't
+ * work as expected at all, but that seems to be a fair trade-off
+ * for the increased robustness of having printf-warnings work.
+ *
+ * Additionally, apr_vformatter allows for arbitrary output methods
+ * using the apr_vformatter_buff and flush_func.
+ *
+ * The apr_vformatter_buff has two elements curpos and endpos.
+ * curpos is where apr_vformatter will write the next byte of output.
+ * It proceeds writing output to curpos, and updating curpos, until
+ * either the end of output is reached, or curpos == endpos (i.e. the
+ * buffer is full).
+ *
+ * If the end of output is reached, apr_vformatter returns the
+ * number of bytes written.
+ *
+ * When the buffer is full, the flush_func is called.  The flush_func
+ * can return -1 to indicate that no further output should be attempted,
+ * and apr_vformatter will return immediately with -1.  Otherwise
+ * the flush_func should flush the buffer in whatever manner is
+ * appropriate, re apr_pool_t nitialize curpos and endpos, and return 0.
+ *
+ * Note that flush_func is only invoked as a result of attempting to
+ * write another byte at curpos when curpos >= endpos.  So for
+ * example, it's possible when the output exactly matches the buffer
+ * space available that curpos == endpos will be true when
+ * apr_vformatter returns.
+ *
+ * apr_vformatter does not call out to any other code, it is entirely
+ * self-contained.  This allows the callers to do things which are
+ * otherwise "unsafe".  For example, apr_psprintf uses the "scratch"
+ * space at the unallocated end of a block, and doesn't actually
+ * complete the allocation until apr_vformatter returns.  apr_psprintf
+ * would be completely broken if apr_vformatter were to call anything
+ * that used this same pool.  Similarly http_bprintf() uses the "scratch"
+ * space at the end of its output buffer, and doesn't actually note
+ * that the space is in use until it either has to flush the buffer
+ * or until apr_vformatter returns.
+ * 
+ */ +APR_DECLARE(int) apr_vformatter(int (*flush_func)(apr_vformatter_buff_t *b), + apr_vformatter_buff_t *c, const char *fmt, + va_list ap); + +/** + * Display a prompt and read in the password from stdin. + * @param prompt The prompt to display + * @param pwbuf Buffer to store the password + * @param bufsize The length of the password buffer. + * @remark If the password entered must be truncated to fit in + * the provided buffer, APR_ENAMETOOLONG will be returned. + * Note that the bufsize paramater is passed by reference for no + * reason; its value will never be modified by the apr_password_get() + * function. + */ +APR_DECLARE(apr_status_t) apr_password_get(const char *prompt, char *pwbuf, + apr_size_t *bufsize); + +/** @} */ + +/** + * @defgroup apr_ctype ctype functions + * These macros allow correct support of 8-bit characters on systems which + * support 8-bit characters. Pretty dumb how the cast is required, but + * that's legacy libc for ya. These new macros do not support EOF like + * the standard macros do. Tough. + * @{ + */ +/** @see isalnum */ +#define apr_isalnum(c) (isalnum(((unsigned char)(c)))) +/** @see isalpha */ +#define apr_isalpha(c) (isalpha(((unsigned char)(c)))) +/** @see iscntrl */ +#define apr_iscntrl(c) (iscntrl(((unsigned char)(c)))) +/** @see isdigit */ +#define apr_isdigit(c) (isdigit(((unsigned char)(c)))) +/** @see isgraph */ +#define apr_isgraph(c) (isgraph(((unsigned char)(c)))) +/** @see islower*/ +#define apr_islower(c) (islower(((unsigned char)(c)))) +/** @see isascii */ +#ifdef isascii +#define apr_isascii(c) (isascii(((unsigned char)(c)))) +#else +#define apr_isascii(c) (((c) & ~0x7f)==0) +#endif +/** @see isprint */ +#define apr_isprint(c) (isprint(((unsigned char)(c)))) +/** @see ispunct */ +#define apr_ispunct(c) (ispunct(((unsigned char)(c)))) +/** @see isspace */ +#define apr_isspace(c) (isspace(((unsigned char)(c)))) +/** @see isupper */ +#define apr_isupper(c) (isupper(((unsigned char)(c)))) +/** @see isxdigit */ +#define apr_isxdigit(c) (isxdigit(((unsigned char)(c)))) +/** @see tolower */ +#define apr_tolower(c) (tolower(((unsigned char)(c)))) +/** @see toupper */ +#define apr_toupper(c) (toupper(((unsigned char)(c)))) + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_LIB_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_md4.h b/c/dependencies/windows/apr/x64_debug/include/apr_md4.h new file mode 100644 index 00000000..43fb33e3 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_md4.h @@ -0,0 +1,135 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* This is derived from material copyright RSA Data Security, Inc. + * Their notice is reproduced below in its entirety. + * + * Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All + * rights reserved. + * + * License to copy and use this software is granted provided that it + * is identified as the "RSA Data Security, Inc. MD4 Message-Digest + * Algorithm" in all material mentioning or referencing this software + * or this function. + * + * License is also granted to make and use derivative works provided + * that such works are identified as "derived from the RSA Data + * Security, Inc. MD4 Message-Digest Algorithm" in all material + * mentioning or referencing the derived work. + * + * RSA Data Security, Inc. makes no representations concerning either + * the merchantability of this software or the suitability of this + * software for any particular purpose. It is provided "as is" + * without express or implied warranty of any kind. + * + * These notices must be retained in any copies of any part of this + * documentation and/or software. + */ + +#ifndef APR_MD4_H +#define APR_MD4_H + +#include "apu.h" +#include "apr_xlate.h" +/** + * @file apr_md4.h + * @brief APR-UTIL MD4 Library + */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_MD4 MD4 Library + * @ingroup APR_Util + * @{ + */ + +/** The digestsize for MD4 */ +#define APR_MD4_DIGESTSIZE 16 + +/** @see apr_md4_ctx_t */ +typedef struct apr_md4_ctx_t apr_md4_ctx_t; + +/** MD4 context. */ +struct apr_md4_ctx_t { + /** state (ABCD) */ + apr_uint32_t state[4]; + /** number of bits, modulo 2^64 (lsb first) */ + apr_uint32_t count[2]; + /** input buffer */ + unsigned char buffer[64]; +#if APR_HAS_XLATE + /** translation handle */ + apr_xlate_t *xlate; +#endif +}; + +/** + * MD4 Initialize. Begins an MD4 operation, writing a new context. + * @param context The MD4 context to initialize. + */ +APU_DECLARE(apr_status_t) apr_md4_init(apr_md4_ctx_t *context); + +#if APR_HAS_XLATE +/** + * MDr4 translation setup. Provides the APR translation handle to be used + * for translating the content before calculating the digest. + * @param context The MD4 content to set the translation for. + * @param xlate The translation handle to use for this MD4 context + */ +APU_DECLARE(apr_status_t) apr_md4_set_xlate(apr_md4_ctx_t *context, + apr_xlate_t *xlate); +#else +#define apr_md4_set_xlate(context, xlate) APR_ENOTIMPL +#endif + +/** + * MD4 block update operation. Continue an MD4 message-digest operation, + * processing another message block, and updating the context. + * @param context The MD4 content to update. + * @param input next message block to update + * @param inputLen The length of the next message block + */ +APU_DECLARE(apr_status_t) apr_md4_update(apr_md4_ctx_t *context, + const unsigned char *input, + apr_size_t inputLen); + +/** + * MD4 finalization. Ends an MD4 message-digest operation, writing the + * message digest and zeroing the context + * @param digest The final MD4 digest + * @param context The MD4 content we are finalizing. + */ +APU_DECLARE(apr_status_t) apr_md4_final( + unsigned char digest[APR_MD4_DIGESTSIZE], + apr_md4_ctx_t *context); + +/** + * MD4 digest computation + * @param digest The MD4 digest + * @param input message block to use + * @param inputLen The length of the message block + */ +APU_DECLARE(apr_status_t) apr_md4(unsigned char digest[APR_MD4_DIGESTSIZE], + const unsigned char *input, + apr_size_t inputLen); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_MD4_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_md5.h b/c/dependencies/windows/apr/x64_debug/include/apr_md5.h new file mode 100644 index 00000000..e0202dfd --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_md5.h @@ -0,0 +1,176 @@ +/* + * This is work is derived from material Copyright RSA Data Security, Inc. + * + * The RSA copyright statement and Licence for that original material is + * included below. This is followed by the Apache copyright statement and + * licence for the modifications made to that material. + */ + +/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All + rights reserved. + + License to copy and use this software is granted provided that it + is identified as the "RSA Data Security, Inc. MD5 Message-Digest + Algorithm" in all material mentioning or referencing this software + or this function. + + License is also granted to make and use derivative works provided + that such works are identified as "derived from the RSA Data + Security, Inc. MD5 Message-Digest Algorithm" in all material + mentioning or referencing the derived work. + + RSA Data Security, Inc. makes no representations concerning either + the merchantability of this software or the suitability of this + software for any particular purpose. It is provided "as is" + without express or implied warranty of any kind. + + These notices must be retained in any copies of any part of this + documentation and/or software. + */ + +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_MD5_H +#define APR_MD5_H + +#include "apu.h" +#include "apr_xlate.h" + +#ifdef __cplusplus +extern "C" { +#endif +/** + * @file apr_md5.h + * @brief APR MD5 Routines + */ + +/** + * @defgroup APR_MD5 MD5 Routines + * @ingroup APR + * @{ + */ + +/** The MD5 digest size */ +#define APR_MD5_DIGESTSIZE 16 + +/** @see apr_md5_ctx_t */ +typedef struct apr_md5_ctx_t apr_md5_ctx_t; + +/** MD5 context. */ +struct apr_md5_ctx_t { + /** state (ABCD) */ + apr_uint32_t state[4]; + /** number of bits, modulo 2^64 (lsb first) */ + apr_uint32_t count[2]; + /** input buffer */ + unsigned char buffer[64]; + /** translation handle + * ignored if xlate is unsupported + */ + apr_xlate_t *xlate; +}; + +/** + * MD5 Initialize. Begins an MD5 operation, writing a new context. + * @param context The MD5 context to initialize. + */ +APU_DECLARE(apr_status_t) apr_md5_init(apr_md5_ctx_t *context); + +/** + * MD5 translation setup. Provides the APR translation handle to be used + * for translating the content before calculating the digest. + * @param context The MD5 content to set the translation for. + * @param xlate The translation handle to use for this MD5 context + */ +APU_DECLARE(apr_status_t) apr_md5_set_xlate(apr_md5_ctx_t *context, + apr_xlate_t *xlate); + +/** + * MD5 block update operation. Continue an MD5 message-digest operation, + * processing another message block, and updating the context. + * @param context The MD5 content to update. + * @param input next message block to update + * @param inputLen The length of the next message block + */ +APU_DECLARE(apr_status_t) apr_md5_update(apr_md5_ctx_t *context, + const void *input, + apr_size_t inputLen); + +/** + * MD5 finalization. Ends an MD5 message-digest operation, writing the + * message digest and zeroing the context + * @param digest The final MD5 digest + * @param context The MD5 content we are finalizing. + */ +APU_DECLARE(apr_status_t) apr_md5_final(unsigned char digest[APR_MD5_DIGESTSIZE], + apr_md5_ctx_t *context); + +/** + * MD5 in one step + * @param digest The final MD5 digest + * @param input The message block to use + * @param inputLen The length of the message block + */ +APU_DECLARE(apr_status_t) apr_md5(unsigned char digest[APR_MD5_DIGESTSIZE], + const void *input, + apr_size_t inputLen); + +/** + * Encode a password using an MD5 algorithm + * @param password The password to encode + * @param salt The salt string to use for the encoding + * @param result The string to store the encoded password in + * @param nbytes The size of the result buffer + */ +APU_DECLARE(apr_status_t) apr_md5_encode(const char *password, const char *salt, + char *result, apr_size_t nbytes); + +/** + * Encode a password using the bcrypt algorithm + * @param password The password to encode + * @param count The cost of the encoding, possible values are 4 to 31 + * @param salt Pointer to binary data to be used as salt for the encoding + * @param salt_len The size of the salt data (must be >= 16) + * @param out The string to store the encoded password in + * @param out_len The size of the result buffer (must be >= 61) + */ +APU_DECLARE(apr_status_t) apr_bcrypt_encode(const char *pw, + unsigned int count, + const unsigned char *salt, + apr_size_t salt_len, + char *out, apr_size_t out_len); + +/** + * Validate hashes created by APR-supported algorithms: md5, bcrypt, and sha1. + * hashes created by crypt are supported only on platforms that provide + * crypt(3), so don't rely on that function unless you know that your + * application will be run only on platforms that support it. On platforms + * that don't support crypt(3), this falls back to a clear text string + * comparison. + * @param passwd The password to validate + * @param hash The password to validate against + */ +APU_DECLARE(apr_status_t) apr_password_validate(const char *passwd, + const char *hash); + + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_MD5_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_memcache.h b/c/dependencies/windows/apr/x64_debug/include/apr_memcache.h new file mode 100644 index 00000000..82878825 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_memcache.h @@ -0,0 +1,444 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_MEMCACHE_H +#define APR_MEMCACHE_H + +/** + * @file apr_memcache.h + * @brief Client interface for memcached + * @remark To use this interface you must have a separate memcached + * server running. See the memcached website at http://www.danga.com/memcached/ + * for more information. + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_time.h" +#include "apr_strings.h" +#include "apr_network_io.h" +#include "apr_ring.h" +#include "apr_buckets.h" +#include "apr_reslist.h" +#include "apr_hash.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_Util_MC Memcached Client Routines + * @ingroup APR_Util + * @{ + */ + +/** Specifies the status of a memcached server */ +typedef enum +{ + APR_MC_SERVER_LIVE, /**< Server is alive and responding to requests */ + APR_MC_SERVER_DEAD /**< Server is not responding to requests */ +} apr_memcache_server_status_t; + +/** Opaque memcache client connection object */ +typedef struct apr_memcache_conn_t apr_memcache_conn_t; + +/** Memcache Server Info Object */ +typedef struct apr_memcache_server_t apr_memcache_server_t; +struct apr_memcache_server_t +{ + const char *host; /**< Hostname of this Server */ + apr_port_t port; /**< Port of this Server */ + apr_memcache_server_status_t status; /**< @see apr_memcache_server_status_t */ +#if APR_HAS_THREADS || defined(DOXYGEN) + apr_reslist_t *conns; /**< Resource list of actual client connections */ +#else + apr_memcache_conn_t *conn; +#endif + apr_pool_t *p; /** Pool to use for private allocations */ +#if APR_HAS_THREADS + apr_thread_mutex_t *lock; +#endif + apr_time_t btime; +}; + +/* Custom hash callback function prototype, user for server selection. +* @param baton user selected baton +* @param data data to hash +* @param data_len length of data +*/ +typedef apr_uint32_t (*apr_memcache_hash_func)(void *baton, + const char *data, + const apr_size_t data_len); + +typedef struct apr_memcache_t apr_memcache_t; + +/* Custom Server Select callback function prototype. +* @param baton user selected baton +* @param mc memcache instance, use mc->live_servers to select a node +* @param hash hash of the selected key. +*/ +typedef apr_memcache_server_t* (*apr_memcache_server_func)(void *baton, + apr_memcache_t *mc, + const apr_uint32_t hash); + +/** Container for a set of memcached servers */ +struct apr_memcache_t +{ + apr_uint32_t flags; /**< Flags, Not currently used */ + apr_uint16_t nalloc; /**< Number of Servers Allocated */ + apr_uint16_t ntotal; /**< Number of Servers Added */ + apr_memcache_server_t **live_servers; /**< Array of Servers */ + apr_pool_t *p; /** Pool to use for allocations */ + void *hash_baton; + apr_memcache_hash_func hash_func; + void *server_baton; + apr_memcache_server_func server_func; +}; + +/** Returned Data from a multiple get */ +typedef struct +{ + apr_status_t status; + const char* key; + apr_size_t len; + char *data; + apr_uint16_t flags; +} apr_memcache_value_t; + +/** + * Creates a crc32 hash used to split keys between servers + * @param mc The memcache client object to use + * @param data Data to be hashed + * @param data_len Length of the data to use + * @return crc32 hash of data + * @remark The crc32 hash is not compatible with old memcached clients. + */ +APU_DECLARE(apr_uint32_t) apr_memcache_hash(apr_memcache_t *mc, + const char *data, + const apr_size_t data_len); + +/** + * Pure CRC32 Hash. Used by some clients. + */ +APU_DECLARE(apr_uint32_t) apr_memcache_hash_crc32(void *baton, + const char *data, + const apr_size_t data_len); + +/** + * hash compatible with the standard Perl Client. + */ +APU_DECLARE(apr_uint32_t) apr_memcache_hash_default(void *baton, + const char *data, + const apr_size_t data_len); + +/** + * Picks a server based on a hash + * @param mc The memcache client object to use + * @param hash Hashed value of a Key + * @return server that controls specified hash + * @see apr_memcache_hash + */ +APU_DECLARE(apr_memcache_server_t *) apr_memcache_find_server_hash(apr_memcache_t *mc, + const apr_uint32_t hash); + +/** + * server selection compatible with the standard Perl Client. + */ +APU_DECLARE(apr_memcache_server_t *) apr_memcache_find_server_hash_default(void *baton, + apr_memcache_t *mc, + const apr_uint32_t hash); + +/** + * Adds a server to a client object + * @param mc The memcache client object to use + * @param server Server to add + * @remark Adding servers is not thread safe, and should be done once at startup. + * @warning Changing servers after startup may cause keys to go to + * different servers. + */ +APU_DECLARE(apr_status_t) apr_memcache_add_server(apr_memcache_t *mc, + apr_memcache_server_t *server); + + +/** + * Finds a Server object based on a hostname/port pair + * @param mc The memcache client object to use + * @param host Hostname of the server + * @param port Port of the server + * @return Server with matching Hostname and Port, or NULL if none was found. + */ +APU_DECLARE(apr_memcache_server_t *) apr_memcache_find_server(apr_memcache_t *mc, + const char *host, + apr_port_t port); + +/** + * Enables a Server for use again + * @param mc The memcache client object to use + * @param ms Server to Activate + */ +APU_DECLARE(apr_status_t) apr_memcache_enable_server(apr_memcache_t *mc, + apr_memcache_server_t *ms); + + +/** + * Disable a Server + * @param mc The memcache client object to use + * @param ms Server to Disable + */ +APU_DECLARE(apr_status_t) apr_memcache_disable_server(apr_memcache_t *mc, + apr_memcache_server_t *ms); + +/** + * Creates a new Server Object + * @param p Pool to use + * @param host hostname of the server + * @param port port of the server + * @param min minimum number of client sockets to open + * @param smax soft maximum number of client connections to open + * @param max hard maximum number of client connections + * @param ttl time to live in microseconds of a client connection + * @param ns location of the new server object + * @see apr_reslist_create + * @remark min, smax, and max are only used when APR_HAS_THREADS + */ +APU_DECLARE(apr_status_t) apr_memcache_server_create(apr_pool_t *p, + const char *host, + apr_port_t port, + apr_uint32_t min, + apr_uint32_t smax, + apr_uint32_t max, + apr_uint32_t ttl, + apr_memcache_server_t **ns); +/** + * Creates a new memcached client object + * @param p Pool to use + * @param max_servers maximum number of servers + * @param flags Not currently used + * @param mc location of the new memcache client object + */ +APU_DECLARE(apr_status_t) apr_memcache_create(apr_pool_t *p, + apr_uint16_t max_servers, + apr_uint32_t flags, + apr_memcache_t **mc); + +/** + * Gets a value from the server, allocating the value out of p + * @param mc client to use + * @param p Pool to use + * @param key null terminated string containing the key + * @param baton location of the allocated value + * @param len length of data at baton + * @param flags any flags set by the client for this key + * @return + */ +APU_DECLARE(apr_status_t) apr_memcache_getp(apr_memcache_t *mc, + apr_pool_t *p, + const char* key, + char **baton, + apr_size_t *len, + apr_uint16_t *flags); + + +/** + * Add a key to a hash for a multiget query + * if the hash (*value) is NULL it will be created + * @param data_pool pool from where the hash and their items are created from + * @param key null terminated string containing the key + * @param values hash of keys and values that this key will be added to + * @return + */ +APU_DECLARE(void) apr_memcache_add_multget_key(apr_pool_t *data_pool, + const char* key, + apr_hash_t **values); + +/** + * Gets multiple values from the server, allocating the values out of p + * @param mc client to use + * @param temp_pool Pool used for temporary allocations. May be cleared inside this + * call. + * @param data_pool Pool used to allocate data for the returned values. + * @param values hash of apr_memcache_value_t keyed by strings, contains the + * result of the multiget call. + * @return + */ +APU_DECLARE(apr_status_t) apr_memcache_multgetp(apr_memcache_t *mc, + apr_pool_t *temp_pool, + apr_pool_t *data_pool, + apr_hash_t *values); + +/** + * Sets a value by key on the server + * @param mc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param timeout time in seconds for the data to live on the server + * @param flags any flags set by the client for this key + */ +APU_DECLARE(apr_status_t) apr_memcache_set(apr_memcache_t *mc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint32_t timeout, + apr_uint16_t flags); + +/** + * Adds value by key on the server + * @param mc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param timeout time for the data to live on the server + * @param flags any flags set by the client for this key + * @return APR_SUCCESS if the key was added, APR_EEXIST if the key + * already exists on the server. + */ +APU_DECLARE(apr_status_t) apr_memcache_add(apr_memcache_t *mc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint32_t timeout, + apr_uint16_t flags); + +/** + * Replaces value by key on the server + * @param mc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param timeout time for the data to live on the server + * @param flags any flags set by the client for this key + * @return APR_SUCCESS if the key was added, APR_EEXIST if the key + * did not exist on the server. + */ +APU_DECLARE(apr_status_t) apr_memcache_replace(apr_memcache_t *mc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint32_t timeout, + apr_uint16_t flags); +/** + * Deletes a key from a server + * @param mc client to use + * @param key null terminated string containing the key + * @param timeout time for the delete to stop other clients from adding + */ +APU_DECLARE(apr_status_t) apr_memcache_delete(apr_memcache_t *mc, + const char *key, + apr_uint32_t timeout); + +/** + * Increments a value + * @param mc client to use + * @param key null terminated string containing the key + * @param n number to increment by + * @param nv new value after incrementing + */ +APU_DECLARE(apr_status_t) apr_memcache_incr(apr_memcache_t *mc, + const char *key, + apr_int32_t n, + apr_uint32_t *nv); + +/** + * Decrements a value + * @param mc client to use + * @param key null terminated string containing the key + * @param n number to decrement by + * @param new_value new value after decrementing + */ +APU_DECLARE(apr_status_t) apr_memcache_decr(apr_memcache_t *mc, + const char *key, + apr_int32_t n, + apr_uint32_t *new_value); + +/** + * Query a server's version + * @param ms server to query + * @param p Pool to allocate answer from + * @param baton location to store server version string + * @param len length of the server version string + */ +APU_DECLARE(apr_status_t) apr_memcache_version(apr_memcache_server_t *ms, + apr_pool_t *p, + char **baton); + +typedef struct +{ + /** Version string of this server */ + const char *version; + /** Process id of this server process */ + apr_uint32_t pid; + /** Number of seconds this server has been running */ + apr_uint32_t uptime; + /** current UNIX time according to the server */ + apr_time_t time; + /** The size of a pointer on the current machine */ + apr_uint32_t pointer_size; + /** Accumulated user time for this process */ + apr_time_t rusage_user; + /** Accumulated system time for this process */ + apr_time_t rusage_system; + /** Current number of items stored by the server */ + apr_uint32_t curr_items; + /** Total number of items stored by this server */ + apr_uint32_t total_items; + /** Current number of bytes used by this server to store items */ + apr_uint64_t bytes; + /** Number of open connections */ + apr_uint32_t curr_connections; + /** Total number of connections opened since the server started running */ + apr_uint32_t total_connections; + /** Number of connection structures allocated by the server */ + apr_uint32_t connection_structures; + /** Cumulative number of retrieval requests */ + apr_uint32_t cmd_get; + /** Cumulative number of storage requests */ + apr_uint32_t cmd_set; + /** Number of keys that have been requested and found present */ + apr_uint32_t get_hits; + /** Number of items that have been requested and not found */ + apr_uint32_t get_misses; + /** Number of items removed from cache because they passed their + expiration time */ + apr_uint64_t evictions; + /** Total number of bytes read by this server */ + apr_uint64_t bytes_read; + /** Total number of bytes sent by this server */ + apr_uint64_t bytes_written; + /** Number of bytes this server is allowed to use for storage. */ + apr_uint32_t limit_maxbytes; + /** Number of threads the server is running (if built with threading) */ + apr_uint32_t threads; +} apr_memcache_stats_t; + +/** + * Query a server for statistics + * @param ms server to query + * @param p Pool to allocate answer from + * @param stats location of the new statistics structure + */ +APU_DECLARE(apr_status_t) apr_memcache_stats(apr_memcache_server_t *ms, + apr_pool_t *p, + apr_memcache_stats_t **stats); + + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_MEMCACHE_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_mmap.h b/c/dependencies/windows/apr/x64_debug/include/apr_mmap.h new file mode 100644 index 00000000..c14de192 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_mmap.h @@ -0,0 +1,171 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_MMAP_H +#define APR_MMAP_H + +/** + * @file apr_mmap.h + * @brief APR MMAP routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_ring.h" +#include "apr_file_io.h" /* for apr_file_t */ + +#ifdef BEOS +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_mmap MMAP (Memory Map) Routines + * @ingroup APR + * @{ + */ + +/** MMap opened for reading */ +#define APR_MMAP_READ 1 +/** MMap opened for writing */ +#define APR_MMAP_WRITE 2 + +/** @see apr_mmap_t */ +typedef struct apr_mmap_t apr_mmap_t; + +/** + * @remark + * As far as I can tell the only really sane way to store an MMAP is as a + * void * and a length. BeOS requires this area_id, but that's just a little + * something extra. I am exposing this type, because it doesn't make much + * sense to keep it private, and opening it up makes some stuff easier in + * Apache. + */ +/** The MMAP structure */ +struct apr_mmap_t { + /** The pool the mmap structure was allocated out of. */ + apr_pool_t *cntxt; +#ifdef BEOS + /** An area ID. Only valid on BeOS */ + area_id area; +#endif +#ifdef WIN32 + /** The handle of the file mapping */ + HANDLE mhandle; + /** The start of the real memory page area (mapped view) */ + void *mv; + /** The physical start, size and offset */ + apr_off_t pstart; + apr_size_t psize; + apr_off_t poffset; +#endif + /** The start of the memory mapped area */ + void *mm; + /** The amount of data in the mmap */ + apr_size_t size; + /** ring of apr_mmap_t's that reference the same + * mmap'ed region; acts in place of a reference count */ + APR_RING_ENTRY(apr_mmap_t) link; +}; + +#if APR_HAS_MMAP || defined(DOXYGEN) + +/** @def APR_MMAP_THRESHOLD + * Files have to be at least this big before they're mmap()d. This is to deal + * with systems where the expense of doing an mmap() and an munmap() outweighs + * the benefit for small files. It shouldn't be set lower than 1. + */ +#ifdef MMAP_THRESHOLD +# define APR_MMAP_THRESHOLD MMAP_THRESHOLD +#else +# ifdef SUNOS4 +# define APR_MMAP_THRESHOLD (8*1024) +# else +# define APR_MMAP_THRESHOLD 1 +# endif /* SUNOS4 */ +#endif /* MMAP_THRESHOLD */ + +/** @def APR_MMAP_LIMIT + * Maximum size of MMap region + */ +#ifdef MMAP_LIMIT +# define APR_MMAP_LIMIT MMAP_LIMIT +#else +# define APR_MMAP_LIMIT (4*1024*1024) +#endif /* MMAP_LIMIT */ + +/** Can this file be MMaped */ +#define APR_MMAP_CANDIDATE(filelength) \ + ((filelength >= APR_MMAP_THRESHOLD) && (filelength < APR_MMAP_LIMIT)) + +/* Function definitions */ + +/** + * Create a new mmap'ed file out of an existing APR file. + * @param newmmap The newly created mmap'ed file. + * @param file The file to turn into an mmap. + * @param offset The offset into the file to start the data pointer at. + * @param size The size of the file + * @param flag bit-wise or of: + *
+ *          APR_MMAP_READ       MMap opened for reading
+ *          APR_MMAP_WRITE      MMap opened for writing
+ * 
+ * @param cntxt The pool to use when creating the mmap. + */ +APR_DECLARE(apr_status_t) apr_mmap_create(apr_mmap_t **newmmap, + apr_file_t *file, apr_off_t offset, + apr_size_t size, apr_int32_t flag, + apr_pool_t *cntxt); + +/** + * Duplicate the specified MMAP. + * @param new_mmap The structure to duplicate into. + * @param old_mmap The mmap to duplicate. + * @param p The pool to use for new_mmap. + */ +APR_DECLARE(apr_status_t) apr_mmap_dup(apr_mmap_t **new_mmap, + apr_mmap_t *old_mmap, + apr_pool_t *p); + +/** + * Remove a mmap'ed. + * @param mm The mmap'ed file. + */ +APR_DECLARE(apr_status_t) apr_mmap_delete(apr_mmap_t *mm); + +/** + * Move the pointer into the mmap'ed file to the specified offset. + * @param addr The pointer to the offset specified. + * @param mm The mmap'ed file. + * @param offset The offset to move to. + */ +APR_DECLARE(apr_status_t) apr_mmap_offset(void **addr, apr_mmap_t *mm, + apr_off_t offset); + +#endif /* APR_HAS_MMAP */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_MMAP_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_network_io.h b/c/dependencies/windows/apr/x64_debug/include/apr_network_io.h new file mode 100644 index 00000000..7d6957bc --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_network_io.h @@ -0,0 +1,951 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_NETWORK_IO_H +#define APR_NETWORK_IO_H +/** + * @file apr_network_io.h + * @brief APR Network library + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_file_io.h" +#include "apr_errno.h" +#include "apr_inherit.h" +#include "apr_perms_set.h" + +#if APR_HAVE_NETINET_IN_H +#include +#endif +#if APR_HAVE_SYS_UN_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_network_io Network Routines + * @ingroup APR + * @{ + */ + +#ifndef APR_MAX_SECS_TO_LINGER +/** Maximum seconds to linger */ +#define APR_MAX_SECS_TO_LINGER 30 +#endif + +#ifndef APRMAXHOSTLEN +/** Maximum hostname length */ +#define APRMAXHOSTLEN 256 +#endif + +#ifndef APR_ANYADDR +/** Default 'any' address */ +#define APR_ANYADDR "0.0.0.0" +#endif + +/** + * @defgroup apr_sockopt Socket option definitions + * @{ + */ +#define APR_SO_LINGER 1 /**< Linger */ +#define APR_SO_KEEPALIVE 2 /**< Keepalive */ +#define APR_SO_DEBUG 4 /**< Debug */ +#define APR_SO_NONBLOCK 8 /**< Non-blocking IO */ +#define APR_SO_REUSEADDR 16 /**< Reuse addresses */ +#define APR_SO_SNDBUF 64 /**< Send buffer */ +#define APR_SO_RCVBUF 128 /**< Receive buffer */ +#define APR_SO_DISCONNECTED 256 /**< Disconnected */ +#define APR_TCP_NODELAY 512 /**< For SCTP sockets, this is mapped + * to STCP_NODELAY internally. + */ +#define APR_TCP_NOPUSH 1024 /**< No push */ +#define APR_RESET_NODELAY 2048 /**< This flag is ONLY set internally + * when we set APR_TCP_NOPUSH with + * APR_TCP_NODELAY set to tell us that + * APR_TCP_NODELAY should be turned on + * again when NOPUSH is turned off + */ +#define APR_INCOMPLETE_READ 4096 /**< Set on non-blocking sockets + * (timeout != 0) on which the + * previous read() did not fill a buffer + * completely. the next apr_socket_recv() + * will first call select()/poll() rather than + * going straight into read(). (Can also + * be set by an application to force a + * select()/poll() call before the next + * read, in cases where the app expects + * that an immediate read would fail.) + */ +#define APR_INCOMPLETE_WRITE 8192 /**< like APR_INCOMPLETE_READ, but for write + * @see APR_INCOMPLETE_READ + */ +#define APR_IPV6_V6ONLY 16384 /**< Don't accept IPv4 connections on an + * IPv6 listening socket. + */ +#define APR_TCP_DEFER_ACCEPT 32768 /**< Delay accepting of new connections + * until data is available. + * @see apr_socket_accept_filter + */ +#define APR_SO_BROADCAST 65536 /**< Allow broadcast + */ +#define APR_SO_FREEBIND 131072 /**< Allow binding to addresses not owned + * by any interface + */ + +/** @} */ + +/** Define what type of socket shutdown should occur. */ +typedef enum { + APR_SHUTDOWN_READ, /**< no longer allow read request */ + APR_SHUTDOWN_WRITE, /**< no longer allow write requests */ + APR_SHUTDOWN_READWRITE /**< no longer allow read or write requests */ +} apr_shutdown_how_e; + +#define APR_IPV4_ADDR_OK 0x01 /**< @see apr_sockaddr_info_get() */ +#define APR_IPV6_ADDR_OK 0x02 /**< @see apr_sockaddr_info_get() */ + +#if (!APR_HAVE_IN_ADDR) +/** + * We need to make sure we always have an in_addr type, so APR will just + * define it ourselves, if the platform doesn't provide it. + */ +struct in_addr { + apr_uint32_t s_addr; /**< storage to hold the IP# */ +}; +#endif + +/** @def APR_INADDR_NONE + * Not all platforms have a real INADDR_NONE. This macro replaces + * INADDR_NONE on all platforms. + */ +#ifdef INADDR_NONE +#define APR_INADDR_NONE INADDR_NONE +#else +#define APR_INADDR_NONE ((unsigned int) 0xffffffff) +#endif + +/** + * @def APR_INET + * Not all platforms have these defined, so we'll define them here + * The default values come from FreeBSD 4.1.1 + */ +#define APR_INET AF_INET +/** @def APR_UNSPEC + * Let the system decide which address family to use + */ +#ifdef AF_UNSPEC +#define APR_UNSPEC AF_UNSPEC +#else +#define APR_UNSPEC 0 +#endif +#if APR_HAVE_IPV6 +/** @def APR_INET6 +* IPv6 Address Family. Not all platforms may have this defined. +*/ + +#define APR_INET6 AF_INET6 +#endif + +#if APR_HAVE_SOCKADDR_UN +#if defined (AF_UNIX) +#define APR_UNIX AF_UNIX +#elif defined(AF_LOCAL) +#define APR_UNIX AF_LOCAL +#else +#error "Neither AF_UNIX nor AF_LOCAL is defined" +#endif +#else /* !APR_HAVE_SOCKADDR_UN */ +#if defined (AF_UNIX) +#define APR_UNIX AF_UNIX +#elif defined(AF_LOCAL) +#define APR_UNIX AF_LOCAL +#else +/* TODO: Use a smarter way to detect unique APR_UNIX value */ +#define APR_UNIX 1234 +#endif +#endif + +/** + * @defgroup IP_Proto IP Protocol Definitions for use when creating sockets + * @{ + */ +#define APR_PROTO_TCP 6 /**< TCP */ +#define APR_PROTO_UDP 17 /**< UDP */ +#define APR_PROTO_SCTP 132 /**< SCTP */ +/** @} */ + +/** + * Enum used to denote either the local and remote endpoint of a + * connection. + */ +typedef enum { + APR_LOCAL, /**< Socket information for local end of connection */ + APR_REMOTE /**< Socket information for remote end of connection */ +} apr_interface_e; + +/** + * The specific declaration of inet_addr's ... some platforms fall back + * inet_network (this is not good, but necessary) + */ + +#if APR_HAVE_INET_ADDR +#define apr_inet_addr inet_addr +#elif APR_HAVE_INET_NETWORK /* only DGUX, as far as I know */ +/** + * @warning + * not generally safe... inet_network() and inet_addr() perform + * different functions */ +#define apr_inet_addr inet_network +#endif + +/** A structure to represent sockets */ +typedef struct apr_socket_t apr_socket_t; +/** + * A structure to encapsulate headers and trailers for apr_socket_sendfile + */ +typedef struct apr_hdtr_t apr_hdtr_t; +/** A structure to represent in_addr */ +typedef struct in_addr apr_in_addr_t; +/** A structure to represent an IP subnet */ +typedef struct apr_ipsubnet_t apr_ipsubnet_t; + +/** @remark use apr_uint16_t just in case some system has a short that isn't 16 bits... */ +typedef apr_uint16_t apr_port_t; + +/** @remark It's defined here as I think it should all be platform safe... + * @see apr_sockaddr_t + */ +typedef struct apr_sockaddr_t apr_sockaddr_t; +/** + * APRs socket address type, used to ensure protocol independence + */ +struct apr_sockaddr_t { + /** The pool to use... */ + apr_pool_t *pool; + /** The hostname */ + char *hostname; + /** Either a string of the port number or the service name for the port */ + char *servname; + /** The numeric port */ + apr_port_t port; + /** The family */ + apr_int32_t family; + /** How big is the sockaddr we're using? */ + apr_socklen_t salen; + /** How big is the ip address structure we're using? */ + int ipaddr_len; + /** How big should the address buffer be? 16 for v4 or 46 for v6 + * used in inet_ntop... */ + int addr_str_len; + /** This points to the IP address structure within the appropriate + * sockaddr structure. */ + void *ipaddr_ptr; + /** If multiple addresses were found by apr_sockaddr_info_get(), this + * points to a representation of the next address. */ + apr_sockaddr_t *next; + /** Union of either IPv4 or IPv6 sockaddr. */ + union { + /** IPv4 sockaddr structure */ + struct sockaddr_in sin; +#if APR_HAVE_IPV6 + /** IPv6 sockaddr structure */ + struct sockaddr_in6 sin6; +#endif +#if APR_HAVE_SA_STORAGE + /** Placeholder to ensure that the size of this union is not + * dependent on whether APR_HAVE_IPV6 is defined. */ + struct sockaddr_storage sas; +#endif +#if APR_HAVE_SOCKADDR_UN + /** Unix domain socket sockaddr structure */ + struct sockaddr_un unx; +#endif + } sa; +}; + +#if APR_HAS_SENDFILE +/** + * Support reusing the socket on platforms which support it (from disconnect, + * specifically Win32. + * @remark Optional flag passed into apr_socket_sendfile() + */ +#define APR_SENDFILE_DISCONNECT_SOCKET 1 +#endif + +/** A structure to encapsulate headers and trailers for apr_socket_sendfile */ +struct apr_hdtr_t { + /** An iovec to store the headers sent before the file. */ + struct iovec* headers; + /** number of headers in the iovec */ + int numheaders; + /** An iovec to store the trailers sent after the file. */ + struct iovec* trailers; + /** number of trailers in the iovec */ + int numtrailers; +}; + +/* function definitions */ + +/** + * Create a socket. + * @param new_sock The new socket that has been set up. + * @param family The address family of the socket (e.g., APR_INET). + * @param type The type of the socket (e.g., SOCK_STREAM). + * @param protocol The protocol of the socket (e.g., APR_PROTO_TCP). + * @param cont The pool for the apr_socket_t and associated storage. + * @note The pool will be used by various functions that operate on the + * socket. The caller must ensure that it is not used by other threads + * at the same time. + */ +APR_DECLARE(apr_status_t) apr_socket_create(apr_socket_t **new_sock, + int family, int type, + int protocol, + apr_pool_t *cont); + +/** + * Shutdown either reading, writing, or both sides of a socket. + * @param thesocket The socket to close + * @param how How to shutdown the socket. One of: + *
+ *            APR_SHUTDOWN_READ         no longer allow read requests
+ *            APR_SHUTDOWN_WRITE        no longer allow write requests
+ *            APR_SHUTDOWN_READWRITE    no longer allow read or write requests 
+ * 
+ * @see apr_shutdown_how_e + * @remark This does not actually close the socket descriptor, it just + * controls which calls are still valid on the socket. + */ +APR_DECLARE(apr_status_t) apr_socket_shutdown(apr_socket_t *thesocket, + apr_shutdown_how_e how); + +/** + * Close a socket. + * @param thesocket The socket to close + */ +APR_DECLARE(apr_status_t) apr_socket_close(apr_socket_t *thesocket); + +/** + * Bind the socket to its associated port + * @param sock The socket to bind + * @param sa The socket address to bind to + * @remark This may be where we will find out if there is any other process + * using the selected port. + */ +APR_DECLARE(apr_status_t) apr_socket_bind(apr_socket_t *sock, + apr_sockaddr_t *sa); + +/** + * Listen to a bound socket for connections. + * @param sock The socket to listen on + * @param backlog The number of outstanding connections allowed in the sockets + * listen queue. If this value is less than zero, the listen + * queue size is set to zero. + */ +APR_DECLARE(apr_status_t) apr_socket_listen(apr_socket_t *sock, + apr_int32_t backlog); + +/** + * Accept a new connection request + * @param new_sock A copy of the socket that is connected to the socket that + * made the connection request. This is the socket which should + * be used for all future communication. + * @param sock The socket we are listening on. + * @param connection_pool The pool for the new socket. + * @note The pool will be used by various functions that operate on the + * socket. The caller must ensure that it is not used by other threads + * at the same time. + */ +APR_DECLARE(apr_status_t) apr_socket_accept(apr_socket_t **new_sock, + apr_socket_t *sock, + apr_pool_t *connection_pool); + +/** + * Issue a connection request to a socket either on the same machine + * or a different one. + * @param sock The socket we wish to use for our side of the connection + * @param sa The address of the machine we wish to connect to. + */ +APR_DECLARE(apr_status_t) apr_socket_connect(apr_socket_t *sock, + apr_sockaddr_t *sa); + +/** + * Determine whether the receive part of the socket has been closed by + * the peer (such that a subsequent call to apr_socket_read would + * return APR_EOF), if the socket's receive buffer is empty. This + * function does not block waiting for I/O. + * + * @param sock The socket to check + * @param atreadeof If APR_SUCCESS is returned, *atreadeof is set to + * non-zero if a subsequent read would return APR_EOF + * @return an error is returned if it was not possible to determine the + * status, in which case *atreadeof is not changed. + */ +APR_DECLARE(apr_status_t) apr_socket_atreadeof(apr_socket_t *sock, + int *atreadeof); + +/** + * Create apr_sockaddr_t from hostname, address family, and port. + * @param sa The new apr_sockaddr_t. + * @param hostname The hostname or numeric address string to resolve/parse, or + * NULL to build an address that corresponds to 0.0.0.0 or :: + * or in case of APR_UNIX family it is absolute socket filename. + * @param family The address family to use, or APR_UNSPEC if the system should + * decide. + * @param port The port number. + * @param flags Special processing flags: + *
+ *       APR_IPV4_ADDR_OK          first query for IPv4 addresses; only look
+ *                                 for IPv6 addresses if the first query failed;
+ *                                 only valid if family is APR_UNSPEC and hostname
+ *                                 isn't NULL; mutually exclusive with
+ *                                 APR_IPV6_ADDR_OK
+ *       APR_IPV6_ADDR_OK          first query for IPv6 addresses; only look
+ *                                 for IPv4 addresses if the first query failed;
+ *                                 only valid if family is APR_UNSPEC and hostname
+ *                                 isn't NULL and APR_HAVE_IPV6; mutually exclusive
+ *                                 with APR_IPV4_ADDR_OK
+ * 
+ * @param p The pool for the apr_sockaddr_t and associated storage. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_info_get(apr_sockaddr_t **sa, + const char *hostname, + apr_int32_t family, + apr_port_t port, + apr_int32_t flags, + apr_pool_t *p); + +/** + * Copy apr_sockaddr_t src to dst on pool p. + * @param dst The destination apr_sockaddr_t. + * @param src The source apr_sockaddr_t. + * @param p The pool for the apr_sockaddr_t and associated storage. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_info_copy(apr_sockaddr_t **dst, + const apr_sockaddr_t *src, + apr_pool_t *p); + +/* Set the zone of an IPv6 link-local address object. + * @param sa Socket address object + * @param zone_id Zone ID (textual "eth0" or numeric "3"). + * @return Returns APR_EBADIP for non-IPv6 socket or an IPv6 address + * which isn't link-local. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_zone_set(apr_sockaddr_t *sa, + const char *zone_id); + + +/* Retrieve the zone of an IPv6 link-local address object. + * @param sa Socket address object + * @param name If non-NULL, set to the textual representation of the zone id + * @param id If non-NULL, set to the integer zone id + * @param p Pool from which *name is allocated if used. + * @return Returns APR_EBADIP for non-IPv6 socket or socket without any zone id + * set, or other error if the interface could not be mapped to a name. + * @remark Both name and id may be NULL, neither are modified if + * non-NULL in error cases. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_zone_get(const apr_sockaddr_t *sa, + const char **name, + apr_uint32_t *id, + apr_pool_t *p); + +/** + * Look up the host name from an apr_sockaddr_t. + * @param hostname The hostname. + * @param sa The apr_sockaddr_t. + * @param flags Special processing flags. + * @remark Results can vary significantly between platforms + * when processing wildcard socket addresses. + */ +APR_DECLARE(apr_status_t) apr_getnameinfo(char **hostname, + apr_sockaddr_t *sa, + apr_int32_t flags); + +/** + * Parse hostname/IP address with scope id and port. + * + * Any of the following strings are accepted: + * 8080 (just the port number) + * www.apache.org (just the hostname) + * www.apache.org:8080 (hostname and port number) + * [fe80::1]:80 (IPv6 numeric address string only) + * [fe80::1%eth0] (IPv6 numeric address string and scope id) + * + * Invalid strings: + * (empty string) + * [abc] (not valid IPv6 numeric address string) + * abc:65536 (invalid port number) + * + * @param addr The new buffer containing just the hostname. On output, *addr + * will be NULL if no hostname/IP address was specfied. + * @param scope_id The new buffer containing just the scope id. On output, + * *scope_id will be NULL if no scope id was specified. + * @param port The port number. On output, *port will be 0 if no port was + * specified. + * ### FIXME: 0 is a legal port (per RFC 1700). this should + * ### return something besides zero if the port is missing. + * @param str The input string to be parsed. + * @param p The pool from which *addr and *scope_id are allocated. + * @remark If scope id shouldn't be allowed, check for scope_id != NULL in + * addition to checking the return code. If addr/hostname should be + * required, check for addr == NULL in addition to checking the + * return code. + */ +APR_DECLARE(apr_status_t) apr_parse_addr_port(char **addr, + char **scope_id, + apr_port_t *port, + const char *str, + apr_pool_t *p); + +/** + * Get name of the current machine + * @param buf A buffer to store the hostname in. + * @param len The maximum length of the hostname that can be stored in the + * buffer provided. The suggested length is APRMAXHOSTLEN + 1. + * @param cont The pool to use. + * @remark If the buffer was not large enough, an error will be returned. + */ +APR_DECLARE(apr_status_t) apr_gethostname(char *buf, int len, apr_pool_t *cont); + +/** + * Return the data associated with the current socket + * @param data The user data associated with the socket. + * @param key The key to associate with the user data. + * @param sock The currently open socket. + */ +APR_DECLARE(apr_status_t) apr_socket_data_get(void **data, const char *key, + apr_socket_t *sock); + +/** + * Set the data associated with the current socket. + * @param sock The currently open socket. + * @param data The user data to associate with the socket. + * @param key The key to associate with the data. + * @param cleanup The cleanup to call when the socket is destroyed. + */ +APR_DECLARE(apr_status_t) apr_socket_data_set(apr_socket_t *sock, void *data, + const char *key, + apr_status_t (*cleanup)(void*)); + +/** + * Send data over a network. + * @param sock The socket to send the data over. + * @param buf The buffer which contains the data to be sent. + * @param len On entry, the number of bytes to send; on exit, the number + * of bytes sent. + * @remark + *
+ * This functions acts like a blocking write by default.  To change 
+ * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK
+ * socket option.
+ *
+ * It is possible for both bytes to be sent and an error to be returned.
+ *
+ * APR_EINTR is never returned.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_socket_send(apr_socket_t *sock, const char *buf, + apr_size_t *len); + +/** + * Send multiple buffers over a network. + * @param sock The socket to send the data over. + * @param vec The array of iovec structs containing the data to send + * @param nvec The number of iovec structs in the array + * @param len Receives the number of bytes actually written + * @remark + *
+ * This functions acts like a blocking write by default.  To change 
+ * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK
+ * socket option.
+ * The number of bytes actually sent is stored in argument 4.
+ *
+ * It is possible for both bytes to be sent and an error to be returned.
+ *
+ * APR_EINTR is never returned.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_socket_sendv(apr_socket_t *sock, + const struct iovec *vec, + apr_int32_t nvec, apr_size_t *len); + +/** + * @param sock The socket to send from + * @param where The apr_sockaddr_t describing where to send the data + * @param flags The flags to use + * @param buf The data to send + * @param len The length of the data to send + */ +APR_DECLARE(apr_status_t) apr_socket_sendto(apr_socket_t *sock, + apr_sockaddr_t *where, + apr_int32_t flags, const char *buf, + apr_size_t *len); + +/** + * Read data from a socket. On success, the address of the peer from + * which the data was sent is copied into the @a from parameter, and the + * @a len parameter is updated to give the number of bytes written to + * @a buf. + * + * @param from Updated with the address from which the data was received + * @param sock The socket to use + * @param flags The flags to use + * @param buf The buffer to use + * @param len The length of the available buffer + */ + +APR_DECLARE(apr_status_t) apr_socket_recvfrom(apr_sockaddr_t *from, + apr_socket_t *sock, + apr_int32_t flags, char *buf, + apr_size_t *len); + +#if APR_HAS_SENDFILE || defined(DOXYGEN) + +/** + * Send a file from an open file descriptor to a socket, along with + * optional headers and trailers + * @param sock The socket to which we're writing + * @param file The open file from which to read + * @param hdtr A structure containing the headers and trailers to send + * @param offset Offset into the file where we should begin writing + * @param len (input) - Number of bytes to send from the file + * (output) - Number of bytes actually sent, + * including headers, file, and trailers + * @param flags APR flags that are mapped to OS specific flags + * @remark This functions acts like a blocking write by default. To change + * this behavior, use apr_socket_timeout_set() or the + * APR_SO_NONBLOCK socket option. + * The number of bytes actually sent is stored in the len parameter. + * The offset parameter is passed by reference for no reason; its + * value will never be modified by the apr_socket_sendfile() function. + */ +APR_DECLARE(apr_status_t) apr_socket_sendfile(apr_socket_t *sock, + apr_file_t *file, + apr_hdtr_t *hdtr, + apr_off_t *offset, + apr_size_t *len, + apr_int32_t flags); + +#endif /* APR_HAS_SENDFILE */ + +/** + * Read data from a network. + * @param sock The socket to read the data from. + * @param buf The buffer to store the data in. + * @param len On entry, the number of bytes to receive; on exit, the number + * of bytes received. + * @remark + *
+ * This functions acts like a blocking read by default.  To change 
+ * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK
+ * socket option.
+ * The number of bytes actually received is stored in argument 3.
+ *
+ * It is possible for both bytes to be received and an APR_EOF or
+ * other error to be returned.
+ *
+ * APR_EINTR is never returned.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_socket_recv(apr_socket_t *sock, + char *buf, apr_size_t *len); + +/** + * Setup socket options for the specified socket + * @param sock The socket to set up. + * @param opt The option we would like to configure. One of: + *
+ *            APR_SO_DEBUG      --  turn on debugging information 
+ *            APR_SO_KEEPALIVE  --  keep connections active
+ *            APR_SO_LINGER     --  lingers on close if data is present
+ *            APR_SO_NONBLOCK   --  Turns blocking on/off for socket
+ *                                  When this option is enabled, use
+ *                                  the APR_STATUS_IS_EAGAIN() macro to
+ *                                  see if a send or receive function
+ *                                  could not transfer data without
+ *                                  blocking.
+ *            APR_SO_REUSEADDR  --  The rules used in validating addresses
+ *                                  supplied to bind should allow reuse
+ *                                  of local addresses.
+ *            APR_SO_SNDBUF     --  Set the SendBufferSize
+ *            APR_SO_RCVBUF     --  Set the ReceiveBufferSize
+ *            APR_SO_FREEBIND   --  Allow binding to non-local IP address.
+ * 
+ * @param on Value for the option. + */ +APR_DECLARE(apr_status_t) apr_socket_opt_set(apr_socket_t *sock, + apr_int32_t opt, apr_int32_t on); + +/** + * Setup socket timeout for the specified socket + * @param sock The socket to set up. + * @param t Value for the timeout. + *
+ *   t > 0  -- read and write calls return APR_TIMEUP if specified time
+ *             elapsess with no data read or written
+ *   t == 0 -- read and write calls never block
+ *   t < 0  -- read and write calls block
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_socket_timeout_set(apr_socket_t *sock, + apr_interval_time_t t); + +/** + * Query socket options for the specified socket + * @param sock The socket to query + * @param opt The option we would like to query. One of: + *
+ *            APR_SO_DEBUG      --  turn on debugging information 
+ *            APR_SO_KEEPALIVE  --  keep connections active
+ *            APR_SO_LINGER     --  lingers on close if data is present
+ *            APR_SO_NONBLOCK   --  Turns blocking on/off for socket
+ *            APR_SO_REUSEADDR  --  The rules used in validating addresses
+ *                                  supplied to bind should allow reuse
+ *                                  of local addresses.
+ *            APR_SO_SNDBUF     --  Set the SendBufferSize
+ *            APR_SO_RCVBUF     --  Set the ReceiveBufferSize
+ *            APR_SO_DISCONNECTED -- Query the disconnected state of the socket.
+ *                                  (Currently only used on Windows)
+ * 
+ * @param on Socket option returned on the call. + */ +APR_DECLARE(apr_status_t) apr_socket_opt_get(apr_socket_t *sock, + apr_int32_t opt, apr_int32_t *on); + +/** + * Query socket timeout for the specified socket + * @param sock The socket to query + * @param t Socket timeout returned from the query. + */ +APR_DECLARE(apr_status_t) apr_socket_timeout_get(apr_socket_t *sock, + apr_interval_time_t *t); + +/** + * Query the specified socket if at the OOB/Urgent data mark + * @param sock The socket to query + * @param atmark Is set to true if socket is at the OOB/urgent mark, + * otherwise is set to false. + */ +APR_DECLARE(apr_status_t) apr_socket_atmark(apr_socket_t *sock, + int *atmark); + +/** + * Return an address associated with a socket; either the address to + * which the socket is bound locally or the address of the peer + * to which the socket is connected. + * @param sa The returned apr_sockaddr_t. + * @param which Whether to retrieve the local or remote address + * @param sock The socket to use + */ +APR_DECLARE(apr_status_t) apr_socket_addr_get(apr_sockaddr_t **sa, + apr_interface_e which, + apr_socket_t *sock); + +/** + * Return the IP address (in numeric address string format) in + * an APR socket address. APR will allocate storage for the IP address + * string from the pool of the apr_sockaddr_t. + * @param addr The IP address. + * @param sockaddr The socket address to reference. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_ip_get(char **addr, + apr_sockaddr_t *sockaddr); + +/** + * Write the IP address (in numeric address string format) of the APR + * socket address @a sockaddr into the buffer @a buf (of size @a buflen). + * @param sockaddr The socket address to reference. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_ip_getbuf(char *buf, apr_size_t buflen, + apr_sockaddr_t *sockaddr); + +/** + * See if the IP addresses in two APR socket addresses are + * equivalent. Appropriate logic is present for comparing + * IPv4-mapped IPv6 addresses with IPv4 addresses. + * + * @param addr1 One of the APR socket addresses. + * @param addr2 The other APR socket address. + * @remark The return value will be non-zero if the addresses + * are equivalent. + */ +APR_DECLARE(int) apr_sockaddr_equal(const apr_sockaddr_t *addr1, + const apr_sockaddr_t *addr2); + +/** + * See if the IP address in an APR socket address refers to the wildcard + * address for the protocol family (e.g., INADDR_ANY for IPv4). + * + * @param addr The APR socket address to examine. + * @remark The return value will be non-zero if the address is + * initialized and is the wildcard address. + */ +APR_DECLARE(int) apr_sockaddr_is_wildcard(const apr_sockaddr_t *addr); + +/** +* Return the type of the socket. +* @param sock The socket to query. +* @param type The returned type (e.g., SOCK_STREAM). +*/ +APR_DECLARE(apr_status_t) apr_socket_type_get(apr_socket_t *sock, + int *type); + +/** + * Given an apr_sockaddr_t and a service name, set the port for the service + * @param sockaddr The apr_sockaddr_t that will have its port set + * @param servname The name of the service you wish to use + */ +APR_DECLARE(apr_status_t) apr_getservbyname(apr_sockaddr_t *sockaddr, + const char *servname); +/** + * Build an ip-subnet representation from an IP address and optional netmask or + * number-of-bits. + * @param ipsub The new ip-subnet representation + * @param ipstr The input IP address string + * @param mask_or_numbits The input netmask or number-of-bits string, or NULL + * @param p The pool to allocate from + */ +APR_DECLARE(apr_status_t) apr_ipsubnet_create(apr_ipsubnet_t **ipsub, + const char *ipstr, + const char *mask_or_numbits, + apr_pool_t *p); + +/** + * Test the IP address in an apr_sockaddr_t against a pre-built ip-subnet + * representation. + * @param ipsub The ip-subnet representation + * @param sa The socket address to test + * @return non-zero if the socket address is within the subnet, 0 otherwise + */ +APR_DECLARE(int) apr_ipsubnet_test(apr_ipsubnet_t *ipsub, apr_sockaddr_t *sa); + +#if APR_HAS_SO_ACCEPTFILTER || defined(DOXYGEN) +/** + * Set an OS level accept filter. + * @param sock The socket to put the accept filter on. + * @param name The accept filter + * @param args Any extra args to the accept filter. Passing NULL here removes + * the accept filter. + * @bug name and args should have been declared as const char *, as they are in + * APR 2.0 + */ +apr_status_t apr_socket_accept_filter(apr_socket_t *sock, char *name, + char *args); +#endif + +/** + * Return the protocol of the socket. + * @param sock The socket to query. + * @param protocol The returned protocol (e.g., APR_PROTO_TCP). + */ +APR_DECLARE(apr_status_t) apr_socket_protocol_get(apr_socket_t *sock, + int *protocol); + +/** + * Get the pool used by the socket. + */ +APR_POOL_DECLARE_ACCESSOR(socket); + +/** + * Set a socket to be inherited by child processes. + */ +APR_DECLARE_INHERIT_SET(socket); + +/** + * Unset a socket from being inherited by child processes. + */ +APR_DECLARE_INHERIT_UNSET(socket); + +/** + * Set socket permissions. + */ +APR_PERMS_SET_IMPLEMENT(socket); + +/** + * @defgroup apr_mcast IP Multicast + * @{ + */ + +/** + * Join a Multicast Group + * @param sock The socket to join a multicast group + * @param join The address of the multicast group to join + * @param iface Address of the interface to use. If NULL is passed, the + * default multicast interface will be used. (OS Dependent) + * @param source Source Address to accept transmissions from (non-NULL + * implies Source-Specific Multicast) + */ +APR_DECLARE(apr_status_t) apr_mcast_join(apr_socket_t *sock, + apr_sockaddr_t *join, + apr_sockaddr_t *iface, + apr_sockaddr_t *source); + +/** + * Leave a Multicast Group. All arguments must be the same as + * apr_mcast_join. + * @param sock The socket to leave a multicast group + * @param addr The address of the multicast group to leave + * @param iface Address of the interface to use. If NULL is passed, the + * default multicast interface will be used. (OS Dependent) + * @param source Source Address to accept transmissions from (non-NULL + * implies Source-Specific Multicast) + */ +APR_DECLARE(apr_status_t) apr_mcast_leave(apr_socket_t *sock, + apr_sockaddr_t *addr, + apr_sockaddr_t *iface, + apr_sockaddr_t *source); + +/** + * Set the Multicast Time to Live (ttl) for a multicast transmission. + * @param sock The socket to set the multicast ttl + * @param ttl Time to live to Assign. 0-255, default=1 + * @remark If the TTL is 0, packets will only be seen by sockets on + * the local machine, and only when multicast loopback is enabled. + */ +APR_DECLARE(apr_status_t) apr_mcast_hops(apr_socket_t *sock, + apr_byte_t ttl); + +/** + * Toggle IP Multicast Loopback + * @param sock The socket to set multicast loopback + * @param opt 0=disable, 1=enable + */ +APR_DECLARE(apr_status_t) apr_mcast_loopback(apr_socket_t *sock, + apr_byte_t opt); + + +/** + * Set the Interface to be used for outgoing Multicast Transmissions. + * @param sock The socket to set the multicast interface on + * @param iface Address of the interface to use for Multicast + */ +APR_DECLARE(apr_status_t) apr_mcast_interface(apr_socket_t *sock, + apr_sockaddr_t *iface); + +/** @} */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_NETWORK_IO_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_optional.h b/c/dependencies/windows/apr/x64_debug/include/apr_optional.h new file mode 100644 index 00000000..3301d66e --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_optional.h @@ -0,0 +1,92 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_OPTIONAL_H +#define APR_OPTIONAL_H + +#include "apu.h" +/** + * @file apr_optional.h + * @brief APR-UTIL registration of functions exported by modules + */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Opt Optional Functions + * @ingroup APR_Util + * + * Typesafe registration and retrieval of functions that may not be present + * (i.e. functions exported by optional modules) + * @{ + */ + +/** + * The type of an optional function. + * @param name The name of the function + */ +#define APR_OPTIONAL_FN_TYPE(name) apr_OFN_##name##_t + +/** + * Declare an optional function. + * @param ret The return type of the function + * @param name The name of the function + * @param args The function arguments (including brackets) + */ +#define APR_DECLARE_OPTIONAL_FN(ret,name,args) \ +typedef ret (APR_OPTIONAL_FN_TYPE(name)) args + +/** + * XXX: This doesn't belong here, then! + * Private function! DO NOT USE! + * @internal + */ + +typedef void (apr_opt_fn_t)(void); +/** @internal */ +APU_DECLARE_NONSTD(void) apr_dynamic_fn_register(const char *szName, + apr_opt_fn_t *pfn); + +/** + * Register an optional function. This can be later retrieved, type-safely, by + * name. Like all global functions, the name must be unique. Note that, + * confusingly but correctly, the function itself can be static! + * @param name The name of the function + */ +#define APR_REGISTER_OPTIONAL_FN(name) do { \ + APR_OPTIONAL_FN_TYPE(name) *apu__opt = name; \ + apr_dynamic_fn_register(#name,(apr_opt_fn_t *)apu__opt); \ +} while (0) + +/** @internal + * Private function! DO NOT USE! + */ +APU_DECLARE(apr_opt_fn_t *) apr_dynamic_fn_retrieve(const char *szName); + +/** + * Retrieve an optional function. Returns NULL if the function is not present. + * @param name The name of the function + */ +#define APR_RETRIEVE_OPTIONAL_FN(name) \ + (APR_OPTIONAL_FN_TYPE(name) *)apr_dynamic_fn_retrieve(#name) + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_OPTIONAL_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_optional_hooks.h b/c/dependencies/windows/apr/x64_debug/include/apr_optional_hooks.h new file mode 100644 index 00000000..8265f03f --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_optional_hooks.h @@ -0,0 +1,117 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file apr_optional_hooks.h + * @brief Apache optional hook functions + */ + + +#ifndef APR_OPTIONAL_HOOK_H +#define APR_OPTIONAL_HOOK_H + +#include "apr_tables.h" + +#ifdef __cplusplus +extern "C" { +#endif +/** + * @defgroup APR_Util_OPT_HOOK Optional Hook Functions + * @ingroup APR_Util_Hook + * @{ + */ +/** + * Function to implement the APR_OPTIONAL_HOOK Macro + * @internal + * @see APR_OPTIONAL_HOOK + * + * @param szName The name of the hook + * @param pfn A pointer to a function that will be called + * @param aszPre a NULL-terminated array of strings that name modules whose hooks should precede this one + * @param aszSucc a NULL-terminated array of strings that name modules whose hooks should succeed this one + * @param nOrder an integer determining order before honouring aszPre and aszSucc (for example HOOK_MIDDLE) + */ + + +APU_DECLARE(void) apr_optional_hook_add(const char *szName,void (*pfn)(void), + const char * const *aszPre, + const char * const *aszSucc, + int nOrder); + +/** + * Hook to an optional hook. + * + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param pfn A pointer to a function that will be called + * @param aszPre a NULL-terminated array of strings that name modules whose hooks should precede this one + * @param aszSucc a NULL-terminated array of strings that name modules whose hooks should succeed this one + * @param nOrder an integer determining order before honouring aszPre and aszSucc (for example HOOK_MIDDLE) + */ + +#define APR_OPTIONAL_HOOK(ns,name,pfn,aszPre,aszSucc,nOrder) do { \ + ns##_HOOK_##name##_t *apu__hook = pfn; \ + apr_optional_hook_add(#name,(void (*)(void))apu__hook,aszPre, aszSucc, nOrder); \ +} while (0) + +/** + * @internal + * @param szName - the name of the function + * @return the hook structure for a given hook + */ +APU_DECLARE(apr_array_header_t *) apr_optional_hook_get(const char *szName); + +/** + * Implement an optional hook that runs until one of the functions + * returns something other than OK or DECLINE. + * + * @param ns The namespace prefix of the hook functions + * @param link The linkage declaration prefix of the hook + * @param ret The type of the return value of the hook + * @param ret The type of the return value of the hook + * @param name The name of the hook + * @param args_decl The declaration of the arguments for the hook + * @param args_use The names for the arguments for the hook + * @param ok Success value + * @param decline Decline value + */ +#define APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(ns,link,ret,name,args_decl,args_use,ok,decline) \ +link##_DECLARE(ret) ns##_run_##name args_decl \ + { \ + ns##_LINK_##name##_t *pHook; \ + int n; \ + ret rv; \ + apr_array_header_t *pHookArray=apr_optional_hook_get(#name); \ +\ + if(!pHookArray) \ + return ok; \ +\ + pHook=(ns##_LINK_##name##_t *)pHookArray->elts; \ + for(n=0 ; n < pHookArray->nelts ; ++n) \ + { \ + rv=(pHook[n].pFunc)args_use; \ +\ + if(rv != ok && rv != decline) \ + return rv; \ + } \ + return ok; \ + } + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_OPTIONAL_HOOK_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_perms_set.h b/c/dependencies/windows/apr/x64_debug/include/apr_perms_set.h new file mode 100644 index 00000000..92a1362b --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_perms_set.h @@ -0,0 +1,65 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_PERMS_SET_H +#define APR_PERMS_SET_H + +/** + * @file apr_perms_set.h + * @brief APR Process Locking Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_user.h" +#include "apr_file_info.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_perms_set Object permission set functions + * @ingroup APR + * @{ + */ + +/** Permission set callback function. */ +typedef apr_status_t (apr_perms_setfn_t)(void *object, apr_fileperms_t perms, + apr_uid_t uid, apr_gid_t gid); + +#define APR_PERMS_SET_IMPLEMENT(type) \ + APR_DECLARE(apr_status_t) apr_##type##_perms_set \ + (void *the##type, apr_fileperms_t perms, \ + apr_uid_t uid, apr_gid_t gid) + +#define APR_PERMS_SET_ENOTIMPL(type) \ + APR_DECLARE(apr_status_t) apr_##type##_perms_set \ + (void *the##type, apr_fileperms_t perms, \ + apr_uid_t uid, apr_gid_t gid) \ + { return APR_ENOTIMPL ; } + +#define APR_PERMS_SET_FN(type) apr_##type##_perms_set + + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_PERMS_SET */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_poll.h b/c/dependencies/windows/apr/x64_debug/include/apr_poll.h new file mode 100644 index 00000000..482d6ee1 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_poll.h @@ -0,0 +1,446 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_POLL_H +#define APR_POLL_H +/** + * @file apr_poll.h + * @brief APR Poll interface + */ +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_inherit.h" +#include "apr_file_io.h" +#include "apr_network_io.h" + +#if APR_HAVE_NETINET_IN_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_poll Poll Routines + * @ingroup APR + * @{ + */ + +/** + * @defgroup pollopts Poll options + * @ingroup apr_poll + * @{ + */ +#define APR_POLLIN 0x001 /**< Can read without blocking */ +#define APR_POLLPRI 0x002 /**< Priority data available */ +#define APR_POLLOUT 0x004 /**< Can write without blocking */ +#define APR_POLLERR 0x010 /**< Pending error */ +#define APR_POLLHUP 0x020 /**< Hangup occurred */ +#define APR_POLLNVAL 0x040 /**< Descriptor invalid */ +/** @} */ + +/** + * @defgroup pollflags Pollset Flags + * @ingroup apr_poll + * @{ + */ +#define APR_POLLSET_THREADSAFE 0x001 /**< Adding or removing a descriptor is + * thread-safe + */ +#define APR_POLLSET_NOCOPY 0x002 /**< Descriptors passed to apr_pollset_add() + * are not copied + */ +#define APR_POLLSET_WAKEABLE 0x004 /**< Poll operations are interruptable by + * apr_pollset_wakeup() or apr_pollcb_wakeup() + */ +#define APR_POLLSET_NODEFAULT 0x010 /**< Do not try to use the default method if + * the specified non-default method cannot be + * used + */ +/** @} */ + +/** + * Pollset Methods + */ +typedef enum { + APR_POLLSET_DEFAULT, /**< Platform default poll method */ + APR_POLLSET_SELECT, /**< Poll uses select method */ + APR_POLLSET_KQUEUE, /**< Poll uses kqueue method */ + APR_POLLSET_PORT, /**< Poll uses Solaris event port method */ + APR_POLLSET_EPOLL, /**< Poll uses epoll method */ + APR_POLLSET_POLL, /**< Poll uses poll method */ + APR_POLLSET_AIO_MSGQ /**< Poll uses z/OS asio method */ +} apr_pollset_method_e; + +/** Used in apr_pollfd_t to determine what the apr_descriptor is */ +typedef enum { + APR_NO_DESC, /**< nothing here */ + APR_POLL_SOCKET, /**< descriptor refers to a socket */ + APR_POLL_FILE, /**< descriptor refers to a file */ + APR_POLL_LASTDESC /**< @deprecated descriptor is the last one in the list */ +} apr_datatype_e ; + +/** Union of either an APR file or socket. */ +typedef union { + apr_file_t *f; /**< file */ + apr_socket_t *s; /**< socket */ +} apr_descriptor; + +/** @see apr_pollfd_t */ +typedef struct apr_pollfd_t apr_pollfd_t; + +/** Poll descriptor set. */ +struct apr_pollfd_t { + apr_pool_t *p; /**< associated pool */ + apr_datatype_e desc_type; /**< descriptor type */ + apr_int16_t reqevents; /**< requested events */ + apr_int16_t rtnevents; /**< returned events */ + apr_descriptor desc; /**< @see apr_descriptor */ + void *client_data; /**< allows app to associate context */ +}; + + +/* General-purpose poll API for arbitrarily large numbers of + * file descriptors + */ + +/** Opaque structure used for pollset API */ +typedef struct apr_pollset_t apr_pollset_t; + +/** + * Set up a pollset object + * @param pollset The pointer in which to return the newly created object + * @param size The maximum number of descriptors that this pollset can hold + * @param p The pool from which to allocate the pollset + * @param flags Optional flags to modify the operation of the pollset. + * + * @remark If flags contains APR_POLLSET_THREADSAFE, then a pollset is + * created on which it is safe to make concurrent calls to + * apr_pollset_add(), apr_pollset_remove() and apr_pollset_poll() + * from separate threads. This feature is only supported on some + * platforms; the apr_pollset_create() call will fail with + * APR_ENOTIMPL on platforms where it is not supported. + * @remark If flags contains APR_POLLSET_WAKEABLE, then a pollset is + * created with an additional internal pipe object used for the + * apr_pollset_wakeup() call. The actual size of pollset is + * in that case @a size + 1. This feature is only supported on some + * platforms; the apr_pollset_create() call will fail with + * APR_ENOTIMPL on platforms where it is not supported. + * @remark If flags contains APR_POLLSET_NOCOPY, then the apr_pollfd_t + * structures passed to apr_pollset_add() are not copied and + * must have a lifetime at least as long as the pollset. + * @remark Some poll methods (including APR_POLLSET_KQUEUE, + * APR_POLLSET_PORT, and APR_POLLSET_EPOLL) do not have a + * fixed limit on the size of the pollset. For these methods, + * the size parameter controls the maximum number of + * descriptors that will be returned by a single call to + * apr_pollset_poll(). + */ +APR_DECLARE(apr_status_t) apr_pollset_create(apr_pollset_t **pollset, + apr_uint32_t size, + apr_pool_t *p, + apr_uint32_t flags); + +/** + * Set up a pollset object + * @param pollset The pointer in which to return the newly created object + * @param size The maximum number of descriptors that this pollset can hold + * @param p The pool from which to allocate the pollset + * @param flags Optional flags to modify the operation of the pollset. + * @param method Poll method to use. See #apr_pollset_method_e. If this + * method cannot be used, the default method will be used unless the + * APR_POLLSET_NODEFAULT flag has been specified. + * + * @remark If flags contains APR_POLLSET_THREADSAFE, then a pollset is + * created on which it is safe to make concurrent calls to + * apr_pollset_add(), apr_pollset_remove() and apr_pollset_poll() + * from separate threads. This feature is only supported on some + * platforms; the apr_pollset_create_ex() call will fail with + * APR_ENOTIMPL on platforms where it is not supported. + * @remark If flags contains APR_POLLSET_WAKEABLE, then a pollset is + * created with additional internal pipe object used for the + * apr_pollset_wakeup() call. The actual size of pollset is + * in that case size + 1. This feature is only supported on some + * platforms; the apr_pollset_create_ex() call will fail with + * APR_ENOTIMPL on platforms where it is not supported. + * @remark If flags contains APR_POLLSET_NOCOPY, then the apr_pollfd_t + * structures passed to apr_pollset_add() are not copied and + * must have a lifetime at least as long as the pollset. + * @remark Some poll methods (including APR_POLLSET_KQUEUE, + * APR_POLLSET_PORT, and APR_POLLSET_EPOLL) do not have a + * fixed limit on the size of the pollset. For these methods, + * the size parameter controls the maximum number of + * descriptors that will be returned by a single call to + * apr_pollset_poll(). + */ +APR_DECLARE(apr_status_t) apr_pollset_create_ex(apr_pollset_t **pollset, + apr_uint32_t size, + apr_pool_t *p, + apr_uint32_t flags, + apr_pollset_method_e method); + +/** + * Destroy a pollset object + * @param pollset The pollset to destroy + */ +APR_DECLARE(apr_status_t) apr_pollset_destroy(apr_pollset_t *pollset); + +/** + * Add a socket or file descriptor to a pollset + * @param pollset The pollset to which to add the descriptor + * @param descriptor The descriptor to add + * @remark If you set client_data in the descriptor, that value + * will be returned in the client_data field whenever this + * descriptor is signalled in apr_pollset_poll(). + * @remark If the pollset has been created with APR_POLLSET_THREADSAFE + * and thread T1 is blocked in a call to apr_pollset_poll() for + * this same pollset that is being modified via apr_pollset_add() + * in thread T2, the currently executing apr_pollset_poll() call in + * T1 will either: (1) automatically include the newly added descriptor + * in the set of descriptors it is watching or (2) return immediately + * with APR_EINTR. Option (1) is recommended, but option (2) is + * allowed for implementations where option (1) is impossible + * or impractical. + * @remark If the pollset has been created with APR_POLLSET_NOCOPY, the + * apr_pollfd_t structure referenced by descriptor will not be copied + * and must have a lifetime at least as long as the pollset. + * @remark Do not add the same socket or file descriptor to the same pollset + * multiple times, even if the requested events differ for the + * different calls to apr_pollset_add(). If the events of interest + * for a descriptor change, you must first remove the descriptor + * from the pollset with apr_pollset_remove(), then add it again + * specifying all requested events. + */ +APR_DECLARE(apr_status_t) apr_pollset_add(apr_pollset_t *pollset, + const apr_pollfd_t *descriptor); + +/** + * Remove a descriptor from a pollset + * @param pollset The pollset from which to remove the descriptor + * @param descriptor The descriptor to remove + * @remark If the descriptor is not found, APR_NOTFOUND is returned. + * @remark If the pollset has been created with APR_POLLSET_THREADSAFE + * and thread T1 is blocked in a call to apr_pollset_poll() for + * this same pollset that is being modified via apr_pollset_remove() + * in thread T2, the currently executing apr_pollset_poll() call in + * T1 will either: (1) automatically exclude the newly added descriptor + * in the set of descriptors it is watching or (2) return immediately + * with APR_EINTR. Option (1) is recommended, but option (2) is + * allowed for implementations where option (1) is impossible + * or impractical. + * @remark apr_pollset_remove() cannot be used to remove a subset of requested + * events for a descriptor. The reqevents field in the apr_pollfd_t + * parameter must contain the same value when removing as when adding. + */ +APR_DECLARE(apr_status_t) apr_pollset_remove(apr_pollset_t *pollset, + const apr_pollfd_t *descriptor); + +/** + * Block for activity on the descriptor(s) in a pollset + * @param pollset The pollset to use + * @param timeout The amount of time in microseconds to wait. This is a + * maximum, not a minimum. If a descriptor is signalled, the + * function will return before this time. If timeout is + * negative, the function will block until a descriptor is + * signalled or until apr_pollset_wakeup() has been called. + * @param num Number of signalled descriptors (output parameter) + * @param descriptors Array of signalled descriptors (output parameter) + * @remark APR_EINTR will be returned if the pollset has been created with + * APR_POLLSET_WAKEABLE, apr_pollset_wakeup() has been called while + * waiting for activity, and there were no signalled descriptors at the + * time of the wakeup call. + * @remark Multiple signalled conditions for the same descriptor may be reported + * in one or more returned apr_pollfd_t structures, depending on the + * implementation. + */ +APR_DECLARE(apr_status_t) apr_pollset_poll(apr_pollset_t *pollset, + apr_interval_time_t timeout, + apr_int32_t *num, + const apr_pollfd_t **descriptors); + +/** + * Interrupt the blocked apr_pollset_poll() call. + * @param pollset The pollset to use + * @remark If the pollset was not created with APR_POLLSET_WAKEABLE the + * return value is APR_EINIT. + */ +APR_DECLARE(apr_status_t) apr_pollset_wakeup(apr_pollset_t *pollset); + +/** + * Poll the descriptors in the poll structure + * @param aprset The poll structure we will be using. + * @param numsock The number of descriptors we are polling + * @param nsds The number of descriptors signalled (output parameter) + * @param timeout The amount of time in microseconds to wait. This is a + * maximum, not a minimum. If a descriptor is signalled, the + * function will return before this time. If timeout is + * negative, the function will block until a descriptor is + * signalled or until apr_pollset_wakeup() has been called. + * @remark The number of descriptors signalled is returned in the third argument. + * This is a blocking call, and it will not return until either a + * descriptor has been signalled or the timeout has expired. + * @remark The rtnevents field in the apr_pollfd_t array will only be filled- + * in if the return value is APR_SUCCESS. + */ +APR_DECLARE(apr_status_t) apr_poll(apr_pollfd_t *aprset, apr_int32_t numsock, + apr_int32_t *nsds, + apr_interval_time_t timeout); + +/** + * Return a printable representation of the pollset method. + * @param pollset The pollset to use + */ +APR_DECLARE(const char *) apr_pollset_method_name(apr_pollset_t *pollset); + +/** + * Return a printable representation of the default pollset method + * (APR_POLLSET_DEFAULT). + */ +APR_DECLARE(const char *) apr_poll_method_defname(void); + +/** Opaque structure used for pollcb API */ +typedef struct apr_pollcb_t apr_pollcb_t; + +/** + * Set up a pollcb object + * @param pollcb The pointer in which to return the newly created object + * @param size The maximum number of descriptors that a single _poll can return. + * @param p The pool from which to allocate the pollcb + * @param flags Optional flags to modify the operation of the pollcb. + * + * @remark If flags contains APR_POLLSET_WAKEABLE, then a pollcb is + * created with an additional internal pipe object used for the + * apr_pollcb_wakeup() call. The actual size of pollcb is + * in that case @a size + 1. + * @remark Pollcb is only supported on some platforms; the apr_pollcb_create() + * call will fail with APR_ENOTIMPL on platforms where it is not supported. + */ +APR_DECLARE(apr_status_t) apr_pollcb_create(apr_pollcb_t **pollcb, + apr_uint32_t size, + apr_pool_t *p, + apr_uint32_t flags); + +/** + * Set up a pollcb object + * @param pollcb The pointer in which to return the newly created object + * @param size The maximum number of descriptors that a single _poll can return. + * @param p The pool from which to allocate the pollcb + * @param flags Optional flags to modify the operation of the pollcb. + * @param method Poll method to use. See #apr_pollset_method_e. If this + * method cannot be used, the default method will be used unless the + * APR_POLLSET_NODEFAULT flag has been specified. + * + * @remark If flags contains APR_POLLSET_WAKEABLE, then a pollcb is + * created with an additional internal pipe object used for the + * apr_pollcb_wakeup() call. The actual size of pollcb is + * in that case @a size + 1. + * @remark Pollcb is only supported on some platforms; the apr_pollcb_create_ex() + * call will fail with APR_ENOTIMPL on platforms where it is not supported. + */ +APR_DECLARE(apr_status_t) apr_pollcb_create_ex(apr_pollcb_t **pollcb, + apr_uint32_t size, + apr_pool_t *p, + apr_uint32_t flags, + apr_pollset_method_e method); + +/** + * Add a socket or file descriptor to a pollcb + * @param pollcb The pollcb to which to add the descriptor + * @param descriptor The descriptor to add + * @remark If you set client_data in the descriptor, that value will be + * returned in the client_data field whenever this descriptor is + * signalled in apr_pollcb_poll(). + * @remark Unlike the apr_pollset API, the descriptor is not copied, and users + * must retain the memory used by descriptor, as the same pointer will + * be returned to them from apr_pollcb_poll. + * @remark Do not add the same socket or file descriptor to the same pollcb + * multiple times, even if the requested events differ for the + * different calls to apr_pollcb_add(). If the events of interest + * for a descriptor change, you must first remove the descriptor + * from the pollcb with apr_pollcb_remove(), then add it again + * specifying all requested events. + */ +APR_DECLARE(apr_status_t) apr_pollcb_add(apr_pollcb_t *pollcb, + apr_pollfd_t *descriptor); +/** + * Remove a descriptor from a pollcb + * @param pollcb The pollcb from which to remove the descriptor + * @param descriptor The descriptor to remove + * @remark If the descriptor is not found, APR_NOTFOUND is returned. + * @remark apr_pollcb_remove() cannot be used to remove a subset of requested + * events for a descriptor. The reqevents field in the apr_pollfd_t + * parameter must contain the same value when removing as when adding. + */ +APR_DECLARE(apr_status_t) apr_pollcb_remove(apr_pollcb_t *pollcb, + apr_pollfd_t *descriptor); + +/** + * Function prototype for pollcb handlers + * @param baton Opaque baton passed into apr_pollcb_poll() + * @param descriptor Contains the notification for an active descriptor. + * The @a rtnevents member describes which events were triggered + * for this descriptor. + * @remark If the pollcb handler does not return APR_SUCCESS, the apr_pollcb_poll() + * call returns with the handler's return value. + */ +typedef apr_status_t (*apr_pollcb_cb_t)(void *baton, apr_pollfd_t *descriptor); + +/** + * Block for activity on the descriptor(s) in a pollcb + * @param pollcb The pollcb to use + * @param timeout The amount of time in microseconds to wait. This is a + * maximum, not a minimum. If a descriptor is signalled, the + * function will return before this time. If timeout is + * negative, the function will block until a descriptor is + * signalled or until apr_pollcb_wakeup() has been called. + * @param func Callback function to call for each active descriptor. + * @param baton Opaque baton passed to the callback function. + * @remark Multiple signalled conditions for the same descriptor may be reported + * in one or more calls to the callback function, depending on the + * implementation. + * @remark APR_EINTR will be returned if the pollset has been created with + * APR_POLLSET_WAKEABLE and apr_pollcb_wakeup() has been called while + * waiting for activity. + */ +APR_DECLARE(apr_status_t) apr_pollcb_poll(apr_pollcb_t *pollcb, + apr_interval_time_t timeout, + apr_pollcb_cb_t func, + void *baton); + +/** + * Interrupt the blocked apr_pollcb_poll() call. + * @param pollcb The pollcb to use + * @remark If the pollcb was not created with APR_POLLSET_WAKEABLE the + * return value is APR_EINIT. + */ +APR_DECLARE(apr_status_t) apr_pollcb_wakeup(apr_pollcb_t *pollcb); + +/** + * Return a printable representation of the pollcb method. + * @param pollcb The pollcb to use + */ +APR_DECLARE(const char *) apr_pollcb_method_name(apr_pollcb_t *pollcb); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_POLL_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_pools.h b/c/dependencies/windows/apr/x64_debug/include/apr_pools.h new file mode 100644 index 00000000..783c9c42 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_pools.h @@ -0,0 +1,815 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_POOLS_H +#define APR_POOLS_H + +/** + * @file apr_pools.h + * @brief APR memory allocation + * + * Resource allocation routines... + * + * designed so that we don't have to keep track of EVERYTHING so that + * it can be explicitly freed later (a fundamentally unsound strategy --- + * particularly in the presence of die()). + * + * Instead, we maintain pools, and allocate items (both memory and I/O + * handlers) from the pools --- currently there are two, one for + * per-transaction info, and one for config info. When a transaction is + * over, we can delete everything in the per-transaction apr_pool_t without + * fear, and without thinking too hard about it either. + * + * Note that most operations on pools are not thread-safe: a single pool + * should only be accessed by a single thread at any given time. The one + * exception to this rule is creating a subpool of a given pool: one or more + * threads can safely create subpools at the same time that another thread + * accesses the parent pool. + */ + +#include "apr.h" +#include "apr_errno.h" +#include "apr_general.h" /* for APR_STRINGIFY */ +#define APR_WANT_MEMFUNC /**< for no good reason? */ +#include "apr_want.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_pools Memory Pool Functions + * @ingroup APR + * @{ + */ + +/** The fundamental pool type */ +typedef struct apr_pool_t apr_pool_t; + + +/** + * Declaration helper macro to construct apr_foo_pool_get()s. + * + * This standardized macro is used by opaque (APR) data types to return + * the apr_pool_t that is associated with the data type. + * + * APR_POOL_DECLARE_ACCESSOR() is used in a header file to declare the + * accessor function. A typical usage and result would be: + *
+ *    APR_POOL_DECLARE_ACCESSOR(file);
+ * becomes:
+ *    APR_DECLARE(apr_pool_t *) apr_file_pool_get(const apr_file_t *thefile);
+ * 
+ * @remark Doxygen unwraps this macro (via doxygen.conf) to provide + * actual help for each specific occurrence of apr_foo_pool_get. + * @remark the linkage is specified for APR. It would be possible to expand + * the macros to support other linkages. + */ +#define APR_POOL_DECLARE_ACCESSOR(type) \ + APR_DECLARE(apr_pool_t *) apr_##type##_pool_get \ + (const apr_##type##_t *the##type) + +/** + * Implementation helper macro to provide apr_foo_pool_get()s. + * + * In the implementation, the APR_POOL_IMPLEMENT_ACCESSOR() is used to + * actually define the function. It assumes the field is named "pool". + */ +#define APR_POOL_IMPLEMENT_ACCESSOR(type) \ + APR_DECLARE(apr_pool_t *) apr_##type##_pool_get \ + (const apr_##type##_t *the##type) \ + { return the##type->pool; } + + +/** + * Pool debug levels + * + *
+ * | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
+ * ---------------------------------
+ * |   |   |   |   |   |   |   | x |  General debug code enabled (useful in
+ *                                    combination with --with-efence).
+ *
+ * |   |   |   |   |   |   | x |   |  Verbose output on stderr (report
+ *                                    CREATE, CLEAR, DESTROY).
+ *
+ * |   |   |   | x |   |   |   |   |  Verbose output on stderr (report
+ *                                    PALLOC, PCALLOC).
+ *
+ * |   |   |   |   |   | x |   |   |  Lifetime checking. On each use of a
+ *                                    pool, check its lifetime.  If the pool
+ *                                    is out of scope, abort().
+ *                                    In combination with the verbose flag
+ *                                    above, it will output LIFE in such an
+ *                                    event prior to aborting.
+ *
+ * |   |   |   |   | x |   |   |   |  Pool owner checking.  On each use of a
+ *                                    pool, check if the current thread is the
+ *                                    pool's owner.  If not, abort().  In
+ *                                    combination with the verbose flag above,
+ *                                    it will output OWNER in such an event
+ *                                    prior to aborting.  Use the debug
+ *                                    function apr_pool_owner_set() to switch
+ *                                    a pool's ownership.
+ *
+ * When no debug level was specified, assume general debug mode.
+ * If level 0 was specified, debugging is switched off.
+ * 
+ */ +#if defined(APR_POOL_DEBUG) +/* If APR_POOL_DEBUG is blank, we get 1; if it is a number, we get -1. */ +#if (APR_POOL_DEBUG - APR_POOL_DEBUG -1 == 1) +#undef APR_POOL_DEBUG +#define APR_POOL_DEBUG 1 +#endif +#else +#define APR_POOL_DEBUG 0 +#endif + +/** the place in the code where the particular function was called */ +#define APR_POOL__FILE_LINE__ __FILE__ ":" APR_STRINGIFY(__LINE__) + + + +/** A function that is called when allocation fails. */ +typedef int (*apr_abortfunc_t)(int retcode); + +/* + * APR memory structure manipulators (pools, tables, and arrays). + */ + +/* + * Initialization + */ + +/** + * Setup all of the internal structures required to use pools + * @remark Programs do NOT need to call this directly. APR will call this + * automatically from apr_initialize. + * @internal + */ +APR_DECLARE(apr_status_t) apr_pool_initialize(void); + +/** + * Tear down all of the internal structures required to use pools + * @remark Programs do NOT need to call this directly. APR will call this + * automatically from apr_terminate. + * @internal + */ +APR_DECLARE(void) apr_pool_terminate(void); + + +/* + * Pool creation/destruction + */ + +#include "apr_allocator.h" + +/** + * Create a new pool. + * @param newpool The pool we have just created. + * @param parent The parent pool. If this is NULL, the new pool is a root + * pool. If it is non-NULL, the new pool will inherit all + * of its parent pool's attributes, except the apr_pool_t will + * be a sub-pool. + * @param abort_fn A function to use if the pool cannot allocate more memory. + * @param allocator The allocator to use with the new pool. If NULL the + * allocator of the parent pool will be used. + * @remark This function is thread-safe, in the sense that multiple threads + * can safely create subpools of the same parent pool concurrently. + * Similarly, a subpool can be created by one thread at the same + * time that another thread accesses the parent pool. + */ +APR_DECLARE(apr_status_t) apr_pool_create_ex(apr_pool_t **newpool, + apr_pool_t *parent, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +/** + * Create a new pool. + * @deprecated @see apr_pool_create_unmanaged_ex. + */ +APR_DECLARE(apr_status_t) apr_pool_create_core_ex(apr_pool_t **newpool, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator); + +/** + * Create a new unmanaged pool. + * @param newpool The pool we have just created. + * @param abort_fn A function to use if the pool cannot allocate more memory. + * @param allocator The allocator to use with the new pool. If NULL a + * new allocator will be created with the new pool as owner. + * @remark An unmanaged pool is a special pool without a parent; it will + * NOT be destroyed upon apr_terminate. It must be explicitly + * destroyed by calling apr_pool_destroy, to prevent memory leaks. + * Use of this function is discouraged, think twice about whether + * you really really need it. + * @warning Any child cleanups registered against the new pool, or + * against sub-pools thereof, will not be executed during an + * invocation of apr_proc_create(), so resources created in an + * "unmanaged" pool hierarchy will leak to child processes. + */ +APR_DECLARE(apr_status_t) apr_pool_create_unmanaged_ex(apr_pool_t **newpool, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +/** + * Debug version of apr_pool_create_ex. + * @param newpool @see apr_pool_create. + * @param parent @see apr_pool_create. + * @param abort_fn @see apr_pool_create. + * @param allocator @see apr_pool_create. + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @remark Only available when APR_POOL_DEBUG is defined. + * Call this directly if you have your apr_pool_create_ex + * calls in a wrapper function and wish to override + * the file_line argument to reflect the caller of + * your wrapper function. If you do not have + * apr_pool_create_ex in a wrapper, trust the macro + * and don't call apr_pool_create_ex_debug directly. + */ +APR_DECLARE(apr_status_t) apr_pool_create_ex_debug(apr_pool_t **newpool, + apr_pool_t *parent, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pool_create_ex(newpool, parent, abort_fn, allocator) \ + apr_pool_create_ex_debug(newpool, parent, abort_fn, allocator, \ + APR_POOL__FILE_LINE__) +#endif + +/** + * Debug version of apr_pool_create_core_ex. + * @deprecated @see apr_pool_create_unmanaged_ex_debug. + */ +APR_DECLARE(apr_status_t) apr_pool_create_core_ex_debug(apr_pool_t **newpool, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator, + const char *file_line); + +/** + * Debug version of apr_pool_create_unmanaged_ex. + * @param newpool @see apr_pool_create_unmanaged. + * @param abort_fn @see apr_pool_create_unmanaged. + * @param allocator @see apr_pool_create_unmanaged. + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @remark Only available when APR_POOL_DEBUG is defined. + * Call this directly if you have your apr_pool_create_unmanaged_ex + * calls in a wrapper function and wish to override + * the file_line argument to reflect the caller of + * your wrapper function. If you do not have + * apr_pool_create_core_ex in a wrapper, trust the macro + * and don't call apr_pool_create_core_ex_debug directly. + */ +APR_DECLARE(apr_status_t) apr_pool_create_unmanaged_ex_debug(apr_pool_t **newpool, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pool_create_core_ex(newpool, abort_fn, allocator) \ + apr_pool_create_unmanaged_ex_debug(newpool, abort_fn, allocator, \ + APR_POOL__FILE_LINE__) + +#define apr_pool_create_unmanaged_ex(newpool, abort_fn, allocator) \ + apr_pool_create_unmanaged_ex_debug(newpool, abort_fn, allocator, \ + APR_POOL__FILE_LINE__) + +#endif + +/** + * Create a new pool. + * @param newpool The pool we have just created. + * @param parent The parent pool. If this is NULL, the new pool is a root + * pool. If it is non-NULL, the new pool will inherit all + * of its parent pool's attributes, except the apr_pool_t will + * be a sub-pool. + * @remark This function is thread-safe, in the sense that multiple threads + * can safely create subpools of the same parent pool concurrently. + * Similarly, a subpool can be created by one thread at the same + * time that another thread accesses the parent pool. + */ +#if defined(DOXYGEN) +APR_DECLARE(apr_status_t) apr_pool_create(apr_pool_t **newpool, + apr_pool_t *parent); +#else +#if APR_POOL_DEBUG +#define apr_pool_create(newpool, parent) \ + apr_pool_create_ex_debug(newpool, parent, NULL, NULL, \ + APR_POOL__FILE_LINE__) +#else +#define apr_pool_create(newpool, parent) \ + apr_pool_create_ex(newpool, parent, NULL, NULL) +#endif +#endif + +/** + * Create a new unmanaged pool. + * @param newpool The pool we have just created. + */ +#if defined(DOXYGEN) +APR_DECLARE(apr_status_t) apr_pool_create_core(apr_pool_t **newpool); +APR_DECLARE(apr_status_t) apr_pool_create_unmanaged(apr_pool_t **newpool); +#else +#if APR_POOL_DEBUG +#define apr_pool_create_core(newpool) \ + apr_pool_create_unmanaged_ex_debug(newpool, NULL, NULL, \ + APR_POOL__FILE_LINE__) +#define apr_pool_create_unmanaged(newpool) \ + apr_pool_create_unmanaged_ex_debug(newpool, NULL, NULL, \ + APR_POOL__FILE_LINE__) +#else +#define apr_pool_create_core(newpool) \ + apr_pool_create_unmanaged_ex(newpool, NULL, NULL) +#define apr_pool_create_unmanaged(newpool) \ + apr_pool_create_unmanaged_ex(newpool, NULL, NULL) +#endif +#endif + +/** + * Find the pool's allocator + * @param pool The pool to get the allocator from. + */ +APR_DECLARE(apr_allocator_t *) apr_pool_allocator_get(apr_pool_t *pool) + __attribute__((nonnull(1))); + +/** + * Clear all memory in the pool and run all the cleanups. This also destroys all + * subpools. + * @param p The pool to clear + * @remark This does not actually free the memory, it just allows the pool + * to re-use this memory for the next allocation. + * @see apr_pool_destroy() + */ +APR_DECLARE(void) apr_pool_clear(apr_pool_t *p) __attribute__((nonnull(1))); + +/** + * Debug version of apr_pool_clear. + * @param p See: apr_pool_clear. + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @remark Only available when APR_POOL_DEBUG is defined. + * Call this directly if you have your apr_pool_clear + * calls in a wrapper function and wish to override + * the file_line argument to reflect the caller of + * your wrapper function. If you do not have + * apr_pool_clear in a wrapper, trust the macro + * and don't call apr_pool_destroy_clear directly. + */ +APR_DECLARE(void) apr_pool_clear_debug(apr_pool_t *p, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pool_clear(p) \ + apr_pool_clear_debug(p, APR_POOL__FILE_LINE__) +#endif + +/** + * Destroy the pool. This takes similar action as apr_pool_clear() and then + * frees all the memory. + * @param p The pool to destroy + * @remark This will actually free the memory + */ +APR_DECLARE(void) apr_pool_destroy(apr_pool_t *p) __attribute__((nonnull(1))); + +/** + * Debug version of apr_pool_destroy. + * @param p See: apr_pool_destroy. + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @remark Only available when APR_POOL_DEBUG is defined. + * Call this directly if you have your apr_pool_destroy + * calls in a wrapper function and wish to override + * the file_line argument to reflect the caller of + * your wrapper function. If you do not have + * apr_pool_destroy in a wrapper, trust the macro + * and don't call apr_pool_destroy_debug directly. + */ +APR_DECLARE(void) apr_pool_destroy_debug(apr_pool_t *p, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pool_destroy(p) \ + apr_pool_destroy_debug(p, APR_POOL__FILE_LINE__) +#endif + + +/* + * Memory allocation + */ + +/** + * Allocate a block of memory from a pool + * @param p The pool to allocate from + * @param size The amount of memory to allocate + * @return The allocated memory + */ +APR_DECLARE(void *) apr_palloc(apr_pool_t *p, apr_size_t size) +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) + __attribute__((alloc_size(2))) +#endif + __attribute__((nonnull(1))); + +/** + * Debug version of apr_palloc + * @param p See: apr_palloc + * @param size See: apr_palloc + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @return See: apr_palloc + */ +APR_DECLARE(void *) apr_palloc_debug(apr_pool_t *p, apr_size_t size, + const char *file_line) +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) + __attribute__((alloc_size(2))) +#endif + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_palloc(p, size) \ + apr_palloc_debug(p, size, APR_POOL__FILE_LINE__) +#endif + +/** + * Allocate a block of memory from a pool and set all of the memory to 0 + * @param p The pool to allocate from + * @param size The amount of memory to allocate + * @return The allocated memory + */ +#if defined(DOXYGEN) +APR_DECLARE(void *) apr_pcalloc(apr_pool_t *p, apr_size_t size); +#elif !APR_POOL_DEBUG +#define apr_pcalloc(p, size) memset(apr_palloc(p, size), 0, size) +#endif + +/** + * Debug version of apr_pcalloc + * @param p See: apr_pcalloc + * @param size See: apr_pcalloc + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @return See: apr_pcalloc + */ +APR_DECLARE(void *) apr_pcalloc_debug(apr_pool_t *p, apr_size_t size, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pcalloc(p, size) \ + apr_pcalloc_debug(p, size, APR_POOL__FILE_LINE__) +#endif + + +/* + * Pool Properties + */ + +/** + * Set the function to be called when an allocation failure occurs. + * @remark If the program wants APR to exit on a memory allocation error, + * then this function can be called to set the callback to use (for + * performing cleanup and then exiting). If this function is not called, + * then APR will return an error and expect the calling program to + * deal with the error accordingly. + */ +APR_DECLARE(void) apr_pool_abort_set(apr_abortfunc_t abortfunc, + apr_pool_t *pool) + __attribute__((nonnull(2))); + +/** + * Get the abort function associated with the specified pool. + * @param pool The pool for retrieving the abort function. + * @return The abort function for the given pool. + */ +APR_DECLARE(apr_abortfunc_t) apr_pool_abort_get(apr_pool_t *pool) + __attribute__((nonnull(1))); + +/** + * Get the parent pool of the specified pool. + * @param pool The pool for retrieving the parent pool. + * @return The parent of the given pool. + */ +APR_DECLARE(apr_pool_t *) apr_pool_parent_get(apr_pool_t *pool) + __attribute__((nonnull(1))); + +/** + * Determine if pool a is an ancestor of pool b. + * @param a The pool to search + * @param b The pool to search for + * @return True if a is an ancestor of b, NULL is considered an ancestor + * of all pools. + * @remark if compiled with APR_POOL_DEBUG, this function will also + * return true if A is a pool which has been guaranteed by the caller + * (using apr_pool_join) to have a lifetime at least as long as some + * ancestor of pool B. + */ +APR_DECLARE(int) apr_pool_is_ancestor(apr_pool_t *a, apr_pool_t *b); + +/** + * Tag a pool (give it a name) + * @param pool The pool to tag + * @param tag The tag + */ +APR_DECLARE(void) apr_pool_tag(apr_pool_t *pool, const char *tag) + __attribute__((nonnull(1))); + + +/* + * User data management + */ + +/** + * Set the data associated with the current pool + * @param data The user data associated with the pool. + * @param key The key to use for association + * @param cleanup The cleanup program to use to cleanup the data (NULL if none) + * @param pool The current pool + * @warning The data to be attached to the pool should have a life span + * at least as long as the pool it is being attached to. + * + * Users of APR must take EXTREME care when choosing a key to + * use for their data. It is possible to accidentally overwrite + * data by choosing a key that another part of the program is using. + * Therefore it is advised that steps are taken to ensure that unique + * keys are used for all of the userdata objects in a particular pool + * (the same key in two different pools or a pool and one of its + * subpools is okay) at all times. Careful namespace prefixing of + * key names is a typical way to help ensure this uniqueness. + * + */ +APR_DECLARE(apr_status_t) apr_pool_userdata_set(const void *data, + const char *key, + apr_status_t (*cleanup)(void *), + apr_pool_t *pool) + __attribute__((nonnull(2,4))); + +/** + * Set the data associated with the current pool + * @param data The user data associated with the pool. + * @param key The key to use for association + * @param cleanup The cleanup program to use to cleanup the data (NULL if none) + * @param pool The current pool + * @note same as apr_pool_userdata_set(), except that this version doesn't + * make a copy of the key (this function is useful, for example, when + * the key is a string literal) + * @warning This should NOT be used if the key could change addresses by + * any means between the apr_pool_userdata_setn() call and a + * subsequent apr_pool_userdata_get() on that key, such as if a + * static string is used as a userdata key in a DSO and the DSO could + * be unloaded and reloaded between the _setn() and the _get(). You + * MUST use apr_pool_userdata_set() in such cases. + * @warning More generally, the key and the data to be attached to the + * pool should have a life span at least as long as the pool itself. + * + */ +APR_DECLARE(apr_status_t) apr_pool_userdata_setn( + const void *data, const char *key, + apr_status_t (*cleanup)(void *), + apr_pool_t *pool) + __attribute__((nonnull(2,4))); + +/** + * Return the data associated with the current pool. + * @param data The user data associated with the pool. + * @param key The key for the data to retrieve + * @param pool The current pool. + */ +APR_DECLARE(apr_status_t) apr_pool_userdata_get(void **data, const char *key, + apr_pool_t *pool) + __attribute__((nonnull(1,2,3))); + + +/** + * @defgroup PoolCleanup Pool Cleanup Functions + * + * Cleanups are performed in the reverse order they were registered. That is: + * Last In, First Out. A cleanup function can safely allocate memory from + * the pool that is being cleaned up. It can also safely register additional + * cleanups which will be run LIFO, directly after the current cleanup + * terminates. Cleanups have to take caution in calling functions that + * create subpools. Subpools, created during cleanup will NOT automatically + * be cleaned up. In other words, cleanups are to clean up after themselves. + * + * @{ + */ + +/** + * Register a function to be called when a pool is cleared or destroyed + * @param p The pool to register the cleanup with + * @param data The data to pass to the cleanup function. + * @param plain_cleanup The function to call when the pool is cleared + * or destroyed + * @param child_cleanup The function to call when a child process is about + * to exec - this function is called in the child, obviously! + */ +APR_DECLARE(void) apr_pool_cleanup_register( + apr_pool_t *p, const void *data, + apr_status_t (*plain_cleanup)(void *), + apr_status_t (*child_cleanup)(void *)) + __attribute__((nonnull(3,4))); + +/** + * Register a function to be called when a pool is cleared or destroyed. + * + * Unlike apr_pool_cleanup_register which registers a cleanup + * that is called AFTER all subpools are destroyed, this function registers + * a function that will be called before any of the subpools are destroyed. + * + * @param p The pool to register the cleanup with + * @param data The data to pass to the cleanup function. + * @param plain_cleanup The function to call when the pool is cleared + * or destroyed + */ +APR_DECLARE(void) apr_pool_pre_cleanup_register( + apr_pool_t *p, const void *data, + apr_status_t (*plain_cleanup)(void *)) + __attribute__((nonnull(3))); + +/** + * Remove a previously registered cleanup function. + * + * The cleanup most recently registered with @a p having the same values of + * @a data and @a cleanup will be removed. + * + * @param p The pool to remove the cleanup from + * @param data The data of the registered cleanup + * @param cleanup The function to remove from cleanup + * @remarks For some strange reason only the plain_cleanup is handled by this + * function + */ +APR_DECLARE(void) apr_pool_cleanup_kill(apr_pool_t *p, const void *data, + apr_status_t (*cleanup)(void *)) + __attribute__((nonnull(3))); + +/** + * Replace the child cleanup function of a previously registered cleanup. + * + * The cleanup most recently registered with @a p having the same values of + * @a data and @a plain_cleanup will have the registered child cleanup + * function replaced with @a child_cleanup. + * + * @param p The pool of the registered cleanup + * @param data The data of the registered cleanup + * @param plain_cleanup The plain cleanup function of the registered cleanup + * @param child_cleanup The function to register as the child cleanup + */ +APR_DECLARE(void) apr_pool_child_cleanup_set( + apr_pool_t *p, const void *data, + apr_status_t (*plain_cleanup)(void *), + apr_status_t (*child_cleanup)(void *)) + __attribute__((nonnull(3,4))); + +/** + * Run the specified cleanup function immediately and unregister it. + * + * The cleanup most recently registered with @a p having the same values of + * @a data and @a cleanup will be removed and @a cleanup will be called + * with @a data as the argument. + * + * @param p The pool to remove the cleanup from + * @param data The data to remove from cleanup + * @param cleanup The function to remove from cleanup + */ +APR_DECLARE(apr_status_t) apr_pool_cleanup_run(apr_pool_t *p, void *data, + apr_status_t (*cleanup)(void *)) + __attribute__((nonnull(3))); + +/** + * An empty cleanup function. + * + * Passed to apr_pool_cleanup_register() when no cleanup is required. + * + * @param data The data to cleanup, will not be used by this function. + */ +APR_DECLARE_NONSTD(apr_status_t) apr_pool_cleanup_null(void *data); + +/** + * Run all registered child cleanups, in preparation for an exec() + * call in a forked child -- close files, etc., but *don't* flush I/O + * buffers, *don't* wait for subprocesses, and *don't* free any + * memory. + */ +APR_DECLARE(void) apr_pool_cleanup_for_exec(void); + +/** @} */ + +/** + * @defgroup PoolDebug Pool Debugging functions. + * + * pools have nested lifetimes -- sub_pools are destroyed when the + * parent pool is cleared. We allow certain liberties with operations + * on things such as tables (and on other structures in a more general + * sense) where we allow the caller to insert values into a table which + * were not allocated from the table's pool. The table's data will + * remain valid as long as all the pools from which its values are + * allocated remain valid. + * + * For example, if B is a sub pool of A, and you build a table T in + * pool B, then it's safe to insert data allocated in A or B into T + * (because B lives at most as long as A does, and T is destroyed when + * B is cleared/destroyed). On the other hand, if S is a table in + * pool A, it is safe to insert data allocated in A into S, but it + * is *not safe* to insert data allocated from B into S... because + * B can be cleared/destroyed before A is (which would leave dangling + * pointers in T's data structures). + * + * In general we say that it is safe to insert data into a table T + * if the data is allocated in any ancestor of T's pool. This is the + * basis on which the APR_POOL_DEBUG code works -- it tests these ancestor + * relationships for all data inserted into tables. APR_POOL_DEBUG also + * provides tools (apr_pool_find, and apr_pool_is_ancestor) for other + * folks to implement similar restrictions for their own data + * structures. + * + * However, sometimes this ancestor requirement is inconvenient -- + * sometimes it's necessary to create a sub pool where the sub pool is + * guaranteed to have the same lifetime as the parent pool. This is a + * guarantee implemented by the *caller*, not by the pool code. That + * is, the caller guarantees they won't destroy the sub pool + * individually prior to destroying the parent pool. + * + * In this case the caller must call apr_pool_join() to indicate this + * guarantee to the APR_POOL_DEBUG code. + * + * These functions are only implemented when #APR_POOL_DEBUG is set. + * + * @{ + */ +#if APR_POOL_DEBUG || defined(DOXYGEN) +/** + * Guarantee that a subpool has the same lifetime as the parent. + * @param p The parent pool + * @param sub The subpool + */ +APR_DECLARE(void) apr_pool_join(apr_pool_t *p, apr_pool_t *sub) + __attribute__((nonnull(2))); + +/** + * Find a pool from something allocated in it. + * @param mem The thing allocated in the pool + * @return The pool it is allocated in + */ +APR_DECLARE(apr_pool_t *) apr_pool_find(const void *mem); + +/** + * Report the number of bytes currently in the pool + * @param p The pool to inspect + * @param recurse Recurse/include the subpools' sizes + * @return The number of bytes + */ +APR_DECLARE(apr_size_t) apr_pool_num_bytes(apr_pool_t *p, int recurse) + __attribute__((nonnull(1))); + +/** + * Lock a pool + * @param pool The pool to lock + * @param flag The flag + */ +APR_DECLARE(void) apr_pool_lock(apr_pool_t *pool, int flag); + +/* @} */ + +#else /* APR_POOL_DEBUG or DOXYGEN */ + +#ifdef apr_pool_join +#undef apr_pool_join +#endif +#define apr_pool_join(a,b) + +#ifdef apr_pool_lock +#undef apr_pool_lock +#endif +#define apr_pool_lock(pool, lock) + +#endif /* APR_POOL_DEBUG or DOXYGEN */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_POOLS_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_portable.h b/c/dependencies/windows/apr/x64_debug/include/apr_portable.h new file mode 100644 index 00000000..f56997e4 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_portable.h @@ -0,0 +1,549 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* This header file is where you should put ANY platform specific information. + * This should be the only header file that programs need to include that + * actually has platform dependent code which refers to the . + */ +#ifndef APR_PORTABLE_H +#define APR_PORTABLE_H +/** + * @file apr_portable.h + * @brief APR Portability Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" +#include "apr_network_io.h" +#include "apr_errno.h" +#include "apr_global_mutex.h" +#include "apr_proc_mutex.h" +#include "apr_time.h" +#include "apr_dso.h" +#include "apr_shm.h" + +#if APR_HAVE_DIRENT_H +#include +#endif +#if APR_HAVE_FCNTL_H +#include +#endif +#if APR_HAVE_PTHREAD_H +#include +#endif +#if APR_HAVE_SEMAPHORE_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_portabile Portability Routines + * @ingroup APR + * @{ + */ + +#ifdef WIN32 +/* The primitives for Windows types */ +typedef HANDLE apr_os_file_t; +typedef HANDLE apr_os_dir_t; +typedef SOCKET apr_os_sock_t; +typedef HANDLE apr_os_proc_mutex_t; +typedef HANDLE apr_os_thread_t; +typedef HANDLE apr_os_proc_t; +typedef DWORD apr_os_threadkey_t; +typedef FILETIME apr_os_imp_time_t; +typedef SYSTEMTIME apr_os_exp_time_t; +typedef HANDLE apr_os_dso_handle_t; +typedef HANDLE apr_os_shm_t; + +#elif defined(OS2) +typedef HFILE apr_os_file_t; +typedef HDIR apr_os_dir_t; +typedef int apr_os_sock_t; +typedef HMTX apr_os_proc_mutex_t; +typedef TID apr_os_thread_t; +typedef PID apr_os_proc_t; +typedef PULONG apr_os_threadkey_t; +typedef struct timeval apr_os_imp_time_t; +typedef struct tm apr_os_exp_time_t; +typedef HMODULE apr_os_dso_handle_t; +typedef void* apr_os_shm_t; + +#elif defined(__BEOS__) +#include +#include + +struct apr_os_proc_mutex_t { + sem_id sem; + int32 ben; +}; + +typedef int apr_os_file_t; +typedef DIR apr_os_dir_t; +typedef int apr_os_sock_t; +typedef struct apr_os_proc_mutex_t apr_os_proc_mutex_t; +typedef thread_id apr_os_thread_t; +typedef thread_id apr_os_proc_t; +typedef int apr_os_threadkey_t; +typedef struct timeval apr_os_imp_time_t; +typedef struct tm apr_os_exp_time_t; +typedef image_id apr_os_dso_handle_t; +typedef void* apr_os_shm_t; + +#elif defined(NETWARE) +typedef int apr_os_file_t; +typedef DIR apr_os_dir_t; +typedef int apr_os_sock_t; +typedef NXMutex_t apr_os_proc_mutex_t; +typedef NXThreadId_t apr_os_thread_t; +typedef long apr_os_proc_t; +typedef NXKey_t apr_os_threadkey_t; +typedef struct timeval apr_os_imp_time_t; +typedef struct tm apr_os_exp_time_t; +typedef void * apr_os_dso_handle_t; +typedef void* apr_os_shm_t; + +#else +/* Any other OS should go above this one. This is the lowest common + * denominator typedefs for all UNIX-like systems. :) + */ + +/** Basic OS process mutex structure. */ +struct apr_os_proc_mutex_t { +#if APR_HAS_SYSVSEM_SERIALIZE || APR_HAS_FCNTL_SERIALIZE || APR_HAS_FLOCK_SERIALIZE + /** Value used for SYS V Semaphore, FCNTL and FLOCK serialization */ + int crossproc; +#endif +#if APR_HAS_PROC_PTHREAD_SERIALIZE + /** Value used for PTHREAD serialization */ + pthread_mutex_t *pthread_interproc; +#endif +#if APR_HAS_THREADS + /* If no threads, no need for thread locks */ +#if APR_USE_PTHREAD_SERIALIZE + /** This value is currently unused within APR and Apache */ + pthread_mutex_t *intraproc; +#endif +#endif +#if APR_HAS_POSIXSEM_SERIALIZE + /** Value used for POSIX semaphores serialization */ + sem_t *psem_interproc; +#endif +}; + +typedef int apr_os_file_t; /**< native file */ +typedef DIR apr_os_dir_t; /**< native dir */ +typedef int apr_os_sock_t; /**< native dir */ +typedef struct apr_os_proc_mutex_t apr_os_proc_mutex_t; /**< native process + * mutex + */ +#if APR_HAS_THREADS && APR_HAVE_PTHREAD_H +typedef pthread_t apr_os_thread_t; /**< native thread */ +typedef pthread_key_t apr_os_threadkey_t; /**< native thread address + * space */ +#endif +typedef pid_t apr_os_proc_t; /**< native pid */ +typedef struct timeval apr_os_imp_time_t; /**< native timeval */ +typedef struct tm apr_os_exp_time_t; /**< native tm */ +/** @var apr_os_dso_handle_t + * native dso types + */ +#if defined(HPUX) || defined(HPUX10) || defined(HPUX11) +#include +typedef shl_t apr_os_dso_handle_t; +#elif defined(DARWIN) +#include +typedef NSModule apr_os_dso_handle_t; +#else +typedef void * apr_os_dso_handle_t; +#endif +typedef void* apr_os_shm_t; /**< native SHM */ + +#endif + +/** + * @typedef apr_os_sock_info_t + * @brief alias for local OS socket + */ +/** + * everything APR needs to know about an active socket to construct + * an APR socket from it; currently, this is platform-independent + */ +struct apr_os_sock_info_t { + apr_os_sock_t *os_sock; /**< always required */ + struct sockaddr *local; /**< NULL if not yet bound */ + struct sockaddr *remote; /**< NULL if not connected */ + int family; /**< always required (APR_INET, APR_INET6, etc.) */ + int type; /**< always required (SOCK_STREAM, SOCK_DGRAM, etc.) */ + int protocol; /**< 0 or actual protocol (APR_PROTO_SCTP, APR_PROTO_TCP, etc.) */ +}; + +typedef struct apr_os_sock_info_t apr_os_sock_info_t; + +#if APR_PROC_MUTEX_IS_GLOBAL || defined(DOXYGEN) +/** Opaque global mutex type */ +#define apr_os_global_mutex_t apr_os_proc_mutex_t +/** @return apr_os_global_mutex */ +#define apr_os_global_mutex_get apr_os_proc_mutex_get +#else + /** Thread and process mutex for those platforms where process mutexes + * are not held in threads. + */ + struct apr_os_global_mutex_t { + apr_pool_t *pool; + apr_proc_mutex_t *proc_mutex; +#if APR_HAS_THREADS + apr_thread_mutex_t *thread_mutex; +#endif /* APR_HAS_THREADS */ + }; + typedef struct apr_os_global_mutex_t apr_os_global_mutex_t; + +APR_DECLARE(apr_status_t) apr_os_global_mutex_get(apr_os_global_mutex_t *ospmutex, + apr_global_mutex_t *pmutex); +#endif + + +/** + * convert the file from apr type to os specific type. + * @param thefile The os specific file we are converting to + * @param file The apr file to convert. + * @remark On Unix, it is only possible to get a file descriptor from + * an apr file type. + */ +APR_DECLARE(apr_status_t) apr_os_file_get(apr_os_file_t *thefile, + apr_file_t *file); + +/** + * convert the dir from apr type to os specific type. + * @param thedir The os specific dir we are converting to + * @param dir The apr dir to convert. + */ +APR_DECLARE(apr_status_t) apr_os_dir_get(apr_os_dir_t **thedir, + apr_dir_t *dir); + +/** + * Convert the socket from an apr type to an OS specific socket + * @param thesock The socket to convert. + * @param sock The os specific equivalent of the apr socket.. + */ +APR_DECLARE(apr_status_t) apr_os_sock_get(apr_os_sock_t *thesock, + apr_socket_t *sock); + +/** + * Convert the proc mutex from apr type to os specific type + * @param ospmutex The os specific proc mutex we are converting to. + * @param pmutex The apr proc mutex to convert. + */ +APR_DECLARE(apr_status_t) apr_os_proc_mutex_get(apr_os_proc_mutex_t *ospmutex, + apr_proc_mutex_t *pmutex); + +/** + * Convert the proc mutex from apr type to os specific type, also + * providing the mechanism used by the apr mutex. + * @param ospmutex The os specific proc mutex we are converting to. + * @param pmutex The apr proc mutex to convert. + * @param mech The mechanism used by the apr proc mutex (if not NULL). + * @remark Allows for disambiguation for platforms with multiple mechanisms + * available. + */ +APR_DECLARE(apr_status_t) apr_os_proc_mutex_get_ex(apr_os_proc_mutex_t *ospmutex, + apr_proc_mutex_t *pmutex, + apr_lockmech_e *mech); + +/** + * Get the exploded time in the platforms native format. + * @param ostime the native time format + * @param aprtime the time to convert + */ +APR_DECLARE(apr_status_t) apr_os_exp_time_get(apr_os_exp_time_t **ostime, + apr_time_exp_t *aprtime); + +/** + * Get the imploded time in the platforms native format. + * @param ostime the native time format + * @param aprtime the time to convert + */ +APR_DECLARE(apr_status_t) apr_os_imp_time_get(apr_os_imp_time_t **ostime, + apr_time_t *aprtime); + +/** + * convert the shm from apr type to os specific type. + * @param osshm The os specific shm representation + * @param shm The apr shm to convert. + */ +APR_DECLARE(apr_status_t) apr_os_shm_get(apr_os_shm_t *osshm, + apr_shm_t *shm); + +#if APR_HAS_THREADS || defined(DOXYGEN) +/** + * @defgroup apr_os_thread Thread portability Routines + * @{ + */ +/** + * convert the thread to os specific type from apr type. + * @param thethd The apr thread to convert + * @param thd The os specific thread we are converting to + */ +APR_DECLARE(apr_status_t) apr_os_thread_get(apr_os_thread_t **thethd, + apr_thread_t *thd); + +/** + * convert the thread private memory key to os specific type from an apr type. + * @param thekey The apr handle we are converting from. + * @param key The os specific handle we are converting to. + */ +APR_DECLARE(apr_status_t) apr_os_threadkey_get(apr_os_threadkey_t *thekey, + apr_threadkey_t *key); + +/** + * convert the thread from os specific type to apr type. + * @param thd The apr thread we are converting to. + * @param thethd The os specific thread to convert + * @param cont The pool to use if it is needed. + */ +APR_DECLARE(apr_status_t) apr_os_thread_put(apr_thread_t **thd, + apr_os_thread_t *thethd, + apr_pool_t *cont); + +/** + * convert the thread private memory key from os specific type to apr type. + * @param key The apr handle we are converting to. + * @param thekey The os specific handle to convert + * @param cont The pool to use if it is needed. + */ +APR_DECLARE(apr_status_t) apr_os_threadkey_put(apr_threadkey_t **key, + apr_os_threadkey_t *thekey, + apr_pool_t *cont); +/** + * Get the thread ID + */ +APR_DECLARE(apr_os_thread_t) apr_os_thread_current(void); + +/** + * Compare two thread id's + * @param tid1 1st Thread ID to compare + * @param tid2 2nd Thread ID to compare + * @return non-zero if the two threads are equal, zero otherwise + */ +APR_DECLARE(int) apr_os_thread_equal(apr_os_thread_t tid1, + apr_os_thread_t tid2); + +/** @} */ +#endif /* APR_HAS_THREADS */ + +/** + * convert the file from os specific type to apr type. + * @param file The apr file we are converting to. + * @param thefile The os specific file to convert + * @param flags The flags that were used to open this file. + * @param cont The pool to use if it is needed. + * @remark On Unix, it is only possible to put a file descriptor into + * an apr file type. + */ +APR_DECLARE(apr_status_t) apr_os_file_put(apr_file_t **file, + apr_os_file_t *thefile, + apr_int32_t flags, apr_pool_t *cont); + +/** + * convert the file from os specific type to apr type. + * @param file The apr file we are converting to. + * @param thefile The os specific pipe to convert + * @param cont The pool to use if it is needed. + * @remark On Unix, it is only possible to put a file descriptor into + * an apr file type. + */ +APR_DECLARE(apr_status_t) apr_os_pipe_put(apr_file_t **file, + apr_os_file_t *thefile, + apr_pool_t *cont); + +/** + * convert the file from os specific type to apr type. + * @param file The apr file we are converting to. + * @param thefile The os specific pipe to convert + * @param register_cleanup A cleanup will be registered on the apr_file_t + * to issue apr_file_close(). + * @param cont The pool to use if it is needed. + * @remark On Unix, it is only possible to put a file descriptor into + * an apr file type. + */ +APR_DECLARE(apr_status_t) apr_os_pipe_put_ex(apr_file_t **file, + apr_os_file_t *thefile, + int register_cleanup, + apr_pool_t *cont); + +/** + * convert the dir from os specific type to apr type. + * @param dir The apr dir we are converting to. + * @param thedir The os specific dir to convert + * @param cont The pool to use when creating to apr directory. + */ +APR_DECLARE(apr_status_t) apr_os_dir_put(apr_dir_t **dir, + apr_os_dir_t *thedir, + apr_pool_t *cont); + +/** + * Convert a socket from the os specific type to the APR type. If + * sock points to NULL, a socket will be created from the pool + * provided. If **sock does not point to NULL, the structure pointed + * to by sock will be reused and updated with the given socket. + * @param sock The pool to use. + * @param thesock The socket to convert to. + * @param cont The socket we are converting to an apr type. + * @remark If it is a true socket, it is best to call apr_os_sock_make() + * and provide APR with more information about the socket. + */ +APR_DECLARE(apr_status_t) apr_os_sock_put(apr_socket_t **sock, + apr_os_sock_t *thesock, + apr_pool_t *cont); + +/** + * Create a socket from an existing descriptor and local and remote + * socket addresses. + * @param apr_sock The new socket that has been set up + * @param os_sock_info The os representation of the socket handle and + * other characteristics of the socket + * @param cont The pool to use + * @remark If you only know the descriptor/handle or if it isn't really + * a true socket, use apr_os_sock_put() instead. + */ +APR_DECLARE(apr_status_t) apr_os_sock_make(apr_socket_t **apr_sock, + apr_os_sock_info_t *os_sock_info, + apr_pool_t *cont); + +/** + * Convert the proc mutex from os specific type to apr type + * @param pmutex The apr proc mutex we are converting to. + * @param ospmutex The os specific proc mutex to convert. + * @param cont The pool to use if it is needed. + */ +APR_DECLARE(apr_status_t) apr_os_proc_mutex_put(apr_proc_mutex_t **pmutex, + apr_os_proc_mutex_t *ospmutex, + apr_pool_t *cont); + +/** + * Convert the proc mutex from os specific type to apr type, using the + * specified mechanism. + * @param pmutex The apr proc mutex we are converting to. + * @param ospmutex The os specific proc mutex to convert. + * @param mech The apr mutex locking mechanism + * @param register_cleanup Whether to destroy the os mutex with the apr + * one (either on explicit destroy or pool cleanup). + * @param cont The pool to use if it is needed. + * @remark Allows for disambiguation for platforms with multiple mechanisms + * available. + */ +APR_DECLARE(apr_status_t) apr_os_proc_mutex_put_ex(apr_proc_mutex_t **pmutex, + apr_os_proc_mutex_t *ospmutex, + apr_lockmech_e mech, + int register_cleanup, + apr_pool_t *cont); + +/** + * Put the imploded time in the APR format. + * @param aprtime the APR time format + * @param ostime the time to convert + * @param cont the pool to use if necessary + */ +APR_DECLARE(apr_status_t) apr_os_imp_time_put(apr_time_t *aprtime, + apr_os_imp_time_t **ostime, + apr_pool_t *cont); + +/** + * Put the exploded time in the APR format. + * @param aprtime the APR time format + * @param ostime the time to convert + * @param cont the pool to use if necessary + */ +APR_DECLARE(apr_status_t) apr_os_exp_time_put(apr_time_exp_t *aprtime, + apr_os_exp_time_t **ostime, + apr_pool_t *cont); + +/** + * convert the shared memory from os specific type to apr type. + * @param shm The apr shm representation of osshm + * @param osshm The os specific shm identity + * @param cont The pool to use if it is needed. + * @remark On fork()ed architectures, this is typically nothing more than + * the memory block mapped. On non-fork architectures, this is typically + * some internal handle to pass the mapping from process to process. + */ +APR_DECLARE(apr_status_t) apr_os_shm_put(apr_shm_t **shm, + apr_os_shm_t *osshm, + apr_pool_t *cont); + + +#if APR_HAS_DSO || defined(DOXYGEN) +/** + * @defgroup apr_os_dso DSO (Dynamic Loading) Portability Routines + * @{ + */ +/** + * convert the dso handle from os specific to apr + * @param dso The apr handle we are converting to + * @param thedso the os specific handle to convert + * @param pool the pool to use if it is needed + */ +APR_DECLARE(apr_status_t) apr_os_dso_handle_put(apr_dso_handle_t **dso, + apr_os_dso_handle_t thedso, + apr_pool_t *pool); + +/** + * convert the apr dso handle into an os specific one + * @param aprdso The apr dso handle to convert + * @param dso The os specific dso to return + */ +APR_DECLARE(apr_status_t) apr_os_dso_handle_get(apr_os_dso_handle_t *dso, + apr_dso_handle_t *aprdso); + +/** @} */ +#endif /* APR_HAS_DSO */ + + +#if APR_HAS_OS_UUID +/** + * Private: apr-util's apr_uuid module when supported by the platform + */ +APR_DECLARE(apr_status_t) apr_os_uuid_get(unsigned char *uuid_data); +#endif + + +/** + * Get the name of the system default character set. + * @param pool the pool to allocate the name from, if needed + */ +APR_DECLARE(const char*) apr_os_default_encoding(apr_pool_t *pool); + + +/** + * Get the name of the current locale character set. + * @param pool the pool to allocate the name from, if needed + * @remark Defers to apr_os_default_encoding() if the current locale's + * data can't be retrieved on this system. + */ +APR_DECLARE(const char*) apr_os_locale_encoding(apr_pool_t *pool); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_PORTABLE_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_proc_mutex.h b/c/dependencies/windows/apr/x64_debug/include/apr_proc_mutex.h new file mode 100644 index 00000000..418c9504 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_proc_mutex.h @@ -0,0 +1,192 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_PROC_MUTEX_H +#define APR_PROC_MUTEX_H + +/** + * @file apr_proc_mutex.h + * @brief APR Process Locking Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_perms_set.h" +#include "apr_time.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_proc_mutex Process Locking Routines + * @ingroup APR + * @{ + */ + +/** + * Enumerated potential types for APR process locking methods + * @warning Check APR_HAS_foo_SERIALIZE defines to see if the platform supports + * APR_LOCK_foo. Only APR_LOCK_DEFAULT is portable. + */ +typedef enum { + APR_LOCK_FCNTL, /**< fcntl() */ + APR_LOCK_FLOCK, /**< flock() */ + APR_LOCK_SYSVSEM, /**< System V Semaphores */ + APR_LOCK_PROC_PTHREAD, /**< POSIX pthread process-based locking */ + APR_LOCK_POSIXSEM, /**< POSIX semaphore process-based locking */ + APR_LOCK_DEFAULT, /**< Use the default process lock */ + APR_LOCK_DEFAULT_TIMED /**< Use the default process timed lock */ +} apr_lockmech_e; + +/** Opaque structure representing a process mutex. */ +typedef struct apr_proc_mutex_t apr_proc_mutex_t; + +/* Function definitions */ + +/** + * Create and initialize a mutex that can be used to synchronize processes. + * @param mutex the memory address where the newly created mutex will be + * stored. + * @param fname A file name to use if the lock mechanism requires one. This + * argument should always be provided. The lock code itself will + * determine if it should be used. + * @param mech The mechanism to use for the interprocess lock, if any; one of + *
+ *            APR_LOCK_FCNTL
+ *            APR_LOCK_FLOCK
+ *            APR_LOCK_SYSVSEM
+ *            APR_LOCK_POSIXSEM
+ *            APR_LOCK_PROC_PTHREAD
+ *            APR_LOCK_DEFAULT     pick the default mechanism for the platform
+ * 
+ * @param pool the pool from which to allocate the mutex. + * @see apr_lockmech_e + * @warning Check APR_HAS_foo_SERIALIZE defines to see if the platform supports + * APR_LOCK_foo. Only APR_LOCK_DEFAULT is portable. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_create(apr_proc_mutex_t **mutex, + const char *fname, + apr_lockmech_e mech, + apr_pool_t *pool); + +/** + * Re-open a mutex in a child process. + * @param mutex The newly re-opened mutex structure. + * @param fname A file name to use if the mutex mechanism requires one. This + * argument should always be provided. The mutex code itself will + * determine if it should be used. This filename should be the + * same one that was passed to apr_proc_mutex_create(). + * @param pool The pool to operate on. + * @remark This function must be called to maintain portability, even + * if the underlying lock mechanism does not require it. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_child_init(apr_proc_mutex_t **mutex, + const char *fname, + apr_pool_t *pool); + +/** + * Acquire the lock for the given mutex. If the mutex is already locked, + * the current thread will be put to sleep until the lock becomes available. + * @param mutex the mutex on which to acquire the lock. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_lock(apr_proc_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex. If the mutex has already + * been acquired, the call returns immediately with APR_EBUSY. Note: it + * is important that the APR_STATUS_IS_EBUSY(s) macro be used to determine + * if the return value was APR_EBUSY, for portability reasons. + * @param mutex the mutex on which to attempt the lock acquiring. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_trylock(apr_proc_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex until timeout expires. + * If the acquisition time outs, the call returns with APR_TIMEUP. + * @param mutex the mutex on which to attempt the lock acquiring. + * @param timeout the relative timeout (microseconds). + * @note A negative or nul timeout means immediate attempt, returning + * APR_TIMEUP without blocking if it the lock is already acquired. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_timedlock(apr_proc_mutex_t *mutex, + apr_interval_time_t timeout); + +/** + * Release the lock for the given mutex. + * @param mutex the mutex from which to release the lock. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_unlock(apr_proc_mutex_t *mutex); + +/** + * Destroy the mutex and free the memory associated with the lock. + * @param mutex the mutex to destroy. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_destroy(apr_proc_mutex_t *mutex); + +/** + * Destroy the mutex and free the memory associated with the lock. + * @param mutex the mutex to destroy. + * @note This function is generally used to kill a cleanup on an already + * created mutex + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_cleanup(void *mutex); + +/** + * Return the name of the lockfile for the mutex, or NULL + * if the mutex doesn't use a lock file + */ + +APR_DECLARE(const char *) apr_proc_mutex_lockfile(apr_proc_mutex_t *mutex); + +/** + * Get the mechanism of the mutex, as it relates to the actual method + * used for the underlying apr_proc_mutex_t. + * @param mutex the mutex to get the mechanism from. + */ +APR_DECLARE(apr_lockmech_e) apr_proc_mutex_mech(apr_proc_mutex_t *mutex); + +/** + * Get the mechanism's name of the mutex, as it relates to the actual method + * used for the underlying apr_proc_mutex_t. + * @param mutex the mutex to get the mechanism's name from. + */ +APR_DECLARE(const char *) apr_proc_mutex_name(apr_proc_mutex_t *mutex); + +/** + * Display the name of the default mutex: APR_LOCK_DEFAULT + */ +APR_DECLARE(const char *) apr_proc_mutex_defname(void); + +/** + * Set mutex permissions. + */ +APR_PERMS_SET_IMPLEMENT(proc_mutex); + +/** + * Get the pool used by this proc_mutex. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(proc_mutex); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_PROC_MUTEX_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_queue.h b/c/dependencies/windows/apr/x64_debug/include/apr_queue.h new file mode 100644 index 00000000..a3a41704 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_queue.h @@ -0,0 +1,138 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_QUEUE_H +#define APR_QUEUE_H + +/** + * @file apr_queue.h + * @brief Thread Safe FIFO bounded queue + * @note Since most implementations of the queue are backed by a condition + * variable implementation, it isn't available on systems without threads. + * Although condition variables are sometimes available without threads. + */ + +#include "apu.h" +#include "apr_errno.h" +#include "apr_pools.h" + +#if APR_HAS_THREADS + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_Util_FIFO Thread Safe FIFO bounded queue + * @ingroup APR_Util + * @{ + */ + +/** + * opaque structure + */ +typedef struct apr_queue_t apr_queue_t; + +/** + * create a FIFO queue + * @param queue The new queue + * @param queue_capacity maximum size of the queue + * @param a pool to allocate queue from + */ +APU_DECLARE(apr_status_t) apr_queue_create(apr_queue_t **queue, + unsigned int queue_capacity, + apr_pool_t *a); + +/** + * push/add an object to the queue, blocking if the queue is already full + * + * @param queue the queue + * @param data the data + * @returns APR_EINTR the blocking was interrupted (try again) + * @returns APR_EOF the queue has been terminated + * @returns APR_SUCCESS on a successful push + */ +APU_DECLARE(apr_status_t) apr_queue_push(apr_queue_t *queue, void *data); + +/** + * pop/get an object from the queue, blocking if the queue is already empty + * + * @param queue the queue + * @param data the data + * @returns APR_EINTR the blocking was interrupted (try again) + * @returns APR_EOF if the queue has been terminated + * @returns APR_SUCCESS on a successful pop + */ +APU_DECLARE(apr_status_t) apr_queue_pop(apr_queue_t *queue, void **data); + +/** + * push/add an object to the queue, returning immediately if the queue is full + * + * @param queue the queue + * @param data the data + * @returns APR_EINTR the blocking operation was interrupted (try again) + * @returns APR_EAGAIN the queue is full + * @returns APR_EOF the queue has been terminated + * @returns APR_SUCCESS on a successful push + */ +APU_DECLARE(apr_status_t) apr_queue_trypush(apr_queue_t *queue, void *data); + +/** + * pop/get an object to the queue, returning immediately if the queue is empty + * + * @param queue the queue + * @param data the data + * @returns APR_EINTR the blocking operation was interrupted (try again) + * @returns APR_EAGAIN the queue is empty + * @returns APR_EOF the queue has been terminated + * @returns APR_SUCCESS on a successful pop + */ +APU_DECLARE(apr_status_t) apr_queue_trypop(apr_queue_t *queue, void **data); + +/** + * returns the size of the queue. + * + * @warning this is not threadsafe, and is intended for reporting/monitoring + * of the queue. + * @param queue the queue + * @returns the size of the queue + */ +APU_DECLARE(unsigned int) apr_queue_size(apr_queue_t *queue); + +/** + * interrupt all the threads blocking on this queue. + * + * @param queue the queue + */ +APU_DECLARE(apr_status_t) apr_queue_interrupt_all(apr_queue_t *queue); + +/** + * terminate the queue, sending an interrupt to all the + * blocking threads + * + * @param queue the queue + */ +APU_DECLARE(apr_status_t) apr_queue_term(apr_queue_t *queue); + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif /* APR_HAS_THREADS */ + +#endif /* APRQUEUE_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_random.h b/c/dependencies/windows/apr/x64_debug/include/apr_random.h new file mode 100644 index 00000000..29154358 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_random.h @@ -0,0 +1,153 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_RANDOM_H +#define APR_RANDOM_H + +/** + * @file apr_random.h + * @brief APR PRNG routines + */ + +#include "apr_pools.h" +#include "apr_thread_proc.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_random PRNG Routines + * @ingroup APR + * @{ + */ + +typedef struct apr_crypto_hash_t apr_crypto_hash_t; + +typedef void apr_crypto_hash_init_t(apr_crypto_hash_t *hash); +typedef void apr_crypto_hash_add_t(apr_crypto_hash_t *hash, const void *data, + apr_size_t bytes); +typedef void apr_crypto_hash_finish_t(apr_crypto_hash_t *hash, + unsigned char *result); + + +/* FIXME: make this opaque */ +struct apr_crypto_hash_t { + apr_crypto_hash_init_t *init; + apr_crypto_hash_add_t *add; + apr_crypto_hash_finish_t *finish; + apr_size_t size; + void *data; +}; + +/** + * Allocate and initialize the SHA-256 context + * @param p The pool to allocate from + */ +APR_DECLARE(apr_crypto_hash_t *) apr_crypto_sha256_new(apr_pool_t *p); + +/** Opaque PRNG structure. */ +typedef struct apr_random_t apr_random_t; + +/** + * Initialize a PRNG state + * @param g The PRNG state + * @param p The pool to allocate from + * @param pool_hash Pool hash functions + * @param key_hash Key hash functions + * @param prng_hash PRNG hash functions + */ +APR_DECLARE(void) apr_random_init(apr_random_t *g, apr_pool_t *p, + apr_crypto_hash_t *pool_hash, + apr_crypto_hash_t *key_hash, + apr_crypto_hash_t *prng_hash); +/** + * Allocate and initialize (apr_crypto_sha256_new) a new PRNG state. + * @param p The pool to allocate from + */ +APR_DECLARE(apr_random_t *) apr_random_standard_new(apr_pool_t *p); + +/** + * Mix the randomness pools. + * @param g The PRNG state + * @param entropy_ Entropy buffer + * @param bytes Length of entropy_ in bytes + */ +APR_DECLARE(void) apr_random_add_entropy(apr_random_t *g, + const void *entropy_, + apr_size_t bytes); +/** + * Generate cryptographically insecure random bytes. + * @param g The RNG state + * @param random Buffer to fill with random bytes + * @param bytes Length of buffer in bytes + */ +APR_DECLARE(apr_status_t) apr_random_insecure_bytes(apr_random_t *g, + void *random, + apr_size_t bytes); + +/** + * Generate cryptographically secure random bytes. + * @param g The RNG state + * @param random Buffer to fill with random bytes + * @param bytes Length of buffer in bytes + */ +APR_DECLARE(apr_status_t) apr_random_secure_bytes(apr_random_t *g, + void *random, + apr_size_t bytes); +/** + * Ensures that E bits of conditional entropy are mixed into the PRNG + * before any further randomness is extracted. + * @param g The RNG state + */ +APR_DECLARE(void) apr_random_barrier(apr_random_t *g); + +/** + * Return APR_SUCCESS if the cryptographic PRNG has been seeded with + * enough data, APR_ENOTENOUGHENTROPY otherwise. + * @param r The RNG state + */ +APR_DECLARE(apr_status_t) apr_random_secure_ready(apr_random_t *r); + +/** + * Return APR_SUCCESS if the PRNG has been seeded with enough data, + * APR_ENOTENOUGHENTROPY otherwise. + * @param r The PRNG state + */ +APR_DECLARE(apr_status_t) apr_random_insecure_ready(apr_random_t *r); + +/** + * Mix the randomness pools after forking. + * @param proc The resulting process handle from apr_proc_fork() + * @remark Call this in the child after forking to mix the randomness + * pools. Note that its generally a bad idea to fork a process with a + * real PRNG in it - better to have the PRNG externally and get the + * randomness from there. However, if you really must do it, then you + * should supply all your entropy to all the PRNGs - don't worry, they + * won't produce the same output. + * @remark Note that apr_proc_fork() calls this for you, so only weird + * applications need ever call it themselves. + * @internal + */ +APR_DECLARE(void) apr_random_after_fork(apr_proc_t *proc); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_RANDOM_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_redis.h b/c/dependencies/windows/apr/x64_debug/include/apr_redis.h new file mode 100644 index 00000000..66a828b0 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_redis.h @@ -0,0 +1,459 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_redis.h + * @brief Client interface for redis + * @remark To use this interface you must have a separate redis + * for more information. + */ + +#ifndef APR_REDIS_H +#define APR_REDIS_H + +#include "apr.h" +#include "apr_pools.h" +#include "apr_time.h" +#include "apr_strings.h" +#include "apr_network_io.h" +#include "apr_ring.h" +#include "apr_buckets.h" +#include "apr_reslist.h" +#include "apr_hash.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#ifndef RC_DEFAULT_SERVER_PORT +#define RC_DEFAULT_SERVER_PORT 6379 +#endif + +#ifndef RC_DEFAULT_SERVER_MIN +#define RC_DEFAULT_SERVER_MIN 0 +#endif + +#ifndef RC_DEFAULT_SERVER_SMAX +#define RC_DEFAULT_SERVER_SMAX 1 +#endif + +#ifndef RC_DEFAULT_SERVER_TTL +#define RC_DEFAULT_SERVER_TTL 600 +#endif + +/** + * @defgroup APR_Util_RC Redis Client Routines + * @ingroup APR_Util + * @{ + */ + +/** Specifies the status of a redis server */ +typedef enum +{ + APR_RC_SERVER_LIVE, /**< Server is alive and responding to requests */ + APR_RC_SERVER_DEAD /**< Server is not responding to requests */ +} apr_redis_server_status_t; + +/** Opaque redis client connection object */ +typedef struct apr_redis_conn_t apr_redis_conn_t; + +/** Redis Server Info Object */ +typedef struct apr_redis_server_t apr_redis_server_t; +struct apr_redis_server_t +{ + const char *host; /**< Hostname of this Server */ + apr_port_t port; /**< Port of this Server */ + apr_redis_server_status_t status; /**< @see apr_redis_server_status_t */ +#if APR_HAS_THREADS || defined(DOXYGEN) + apr_reslist_t *conns; /**< Resource list of actual client connections */ +#else + apr_redis_conn_t *conn; +#endif + apr_pool_t *p; /** Pool to use for private allocations */ +#if APR_HAS_THREADS + apr_thread_mutex_t *lock; +#endif + apr_time_t btime; + apr_uint32_t rwto; + struct + { + int major; + int minor; + int patch; + char *number; + } version; +}; + +typedef struct apr_redis_t apr_redis_t; + +/* Custom hash callback function prototype, user for server selection. +* @param baton user selected baton +* @param data data to hash +* @param data_len length of data +*/ +typedef apr_uint32_t (*apr_redis_hash_func)(void *baton, + const char *data, + const apr_size_t data_len); +/* Custom Server Select callback function prototype. +* @param baton user selected baton +* @param rc redis instance, use rc->live_servers to select a node +* @param hash hash of the selected key. +*/ +typedef apr_redis_server_t* (*apr_redis_server_func)(void *baton, + apr_redis_t *rc, + const apr_uint32_t hash); + +/** Container for a set of redis servers */ +struct apr_redis_t +{ + apr_uint32_t flags; /**< Flags, Not currently used */ + apr_uint16_t nalloc; /**< Number of Servers Allocated */ + apr_uint16_t ntotal; /**< Number of Servers Added */ + apr_redis_server_t **live_servers; /**< Array of Servers */ + apr_pool_t *p; /** Pool to use for allocations */ + void *hash_baton; + apr_redis_hash_func hash_func; + void *server_baton; + apr_redis_server_func server_func; +}; + +/** + * Creates a crc32 hash used to split keys between servers + * @param rc The redis client object to use + * @param data Data to be hashed + * @param data_len Length of the data to use + * @return crc32 hash of data + * @remark The crc32 hash is not compatible with old redisd clients. + */ +APU_DECLARE(apr_uint32_t) apr_redis_hash(apr_redis_t *rc, + const char *data, + const apr_size_t data_len); + +/** + * Pure CRC32 Hash. Used by some clients. + */ +APU_DECLARE(apr_uint32_t) apr_redis_hash_crc32(void *baton, + const char *data, + const apr_size_t data_len); + +/** + * hash compatible with the standard Perl Client. + */ +APU_DECLARE(apr_uint32_t) apr_redis_hash_default(void *baton, + const char *data, + const apr_size_t data_len); + +/** + * Picks a server based on a hash + * @param rc The redis client object to use + * @param hash Hashed value of a Key + * @return server that controls specified hash + * @see apr_redis_hash + */ +APU_DECLARE(apr_redis_server_t *) apr_redis_find_server_hash(apr_redis_t *rc, + const apr_uint32_t hash); + +/** + * server selection compatible with the standard Perl Client. + */ +APU_DECLARE(apr_redis_server_t *) apr_redis_find_server_hash_default(void *baton, + apr_redis_t *rc, + const apr_uint32_t hash); + +/** + * Adds a server to a client object + * @param rc The redis client object to use + * @param server Server to add + * @remark Adding servers is not thread safe, and should be done once at startup. + * @warning Changing servers after startup may cause keys to go to + * different servers. + */ +APU_DECLARE(apr_status_t) apr_redis_add_server(apr_redis_t *rc, + apr_redis_server_t *server); + + +/** + * Finds a Server object based on a hostname/port pair + * @param rc The redis client object to use + * @param host Hostname of the server + * @param port Port of the server + * @return Server with matching Hostname and Port, or NULL if none was found. + */ +APU_DECLARE(apr_redis_server_t *) apr_redis_find_server(apr_redis_t *rc, + const char *host, + apr_port_t port); + +/** + * Enables a Server for use again + * @param rc The redis client object to use + * @param rs Server to Activate + */ +APU_DECLARE(apr_status_t) apr_redis_enable_server(apr_redis_t *rc, + apr_redis_server_t *rs); + + +/** + * Disable a Server + * @param rc The redis client object to use + * @param rs Server to Disable + */ +APU_DECLARE(apr_status_t) apr_redis_disable_server(apr_redis_t *rc, + apr_redis_server_t *rs); + +/** + * Creates a new Server Object + * @param p Pool to use + * @param host hostname of the server + * @param port port of the server + * @param min minimum number of client sockets to open + * @param smax soft maximum number of client connections to open + * @param max hard maximum number of client connections + * @param ttl time to live in microseconds of a client connection + * @param rwto r/w timeout value in seconds of a client connection + * @param ns location of the new server object + * @see apr_reslist_create + * @remark min, smax, and max are only used when APR_HAS_THREADS + */ +APU_DECLARE(apr_status_t) apr_redis_server_create(apr_pool_t *p, + const char *host, + apr_port_t port, + apr_uint32_t min, + apr_uint32_t smax, + apr_uint32_t max, + apr_uint32_t ttl, + apr_uint32_t rwto, + apr_redis_server_t **ns); +/** + * Creates a new redisd client object + * @param p Pool to use + * @param max_servers maximum number of servers + * @param flags Not currently used + * @param rc location of the new redis client object + */ +APU_DECLARE(apr_status_t) apr_redis_create(apr_pool_t *p, + apr_uint16_t max_servers, + apr_uint32_t flags, + apr_redis_t **rc); + +/** + * Gets a value from the server, allocating the value out of p + * @param rc client to use + * @param p Pool to use + * @param key null terminated string containing the key + * @param baton location of the allocated value + * @param len length of data at baton + * @param flags any flags set by the client for this key + * @return + */ +APU_DECLARE(apr_status_t) apr_redis_getp(apr_redis_t *rc, + apr_pool_t *p, + const char* key, + char **baton, + apr_size_t *len, + apr_uint16_t *flags); + +/** + * Sets a value by key on the server + * @param rc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param flags any flags set by the client for this key + */ +APU_DECLARE(apr_status_t) apr_redis_set(apr_redis_t *rc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint16_t flags); + +/** + * Sets a value by key on the server + * @param rc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param timeout time in seconds for the data to live on the server + * @param flags any flags set by the client for this key + */ +APU_DECLARE(apr_status_t) apr_redis_setex(apr_redis_t *rc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint32_t timeout, + apr_uint16_t flags); + +/** + * Deletes a key from a server + * @param rc client to use + * @param key null terminated string containing the key + * @param timeout time for the delete to stop other clients from adding + */ +APU_DECLARE(apr_status_t) apr_redis_delete(apr_redis_t *rc, + const char *key, + apr_uint32_t timeout); + +/** + * Query a server's version + * @param rs server to query + * @param p Pool to allocate answer from + * @param baton location to store server version string + */ +APU_DECLARE(apr_status_t) apr_redis_version(apr_redis_server_t *rs, + apr_pool_t *p, + char **baton); + +/** + * Query a server's INFO + * @param rs server to query + * @param p Pool to allocate answer from + * @param baton location to store server INFO response string + */ +APU_DECLARE(apr_status_t) apr_redis_info(apr_redis_server_t *rs, + apr_pool_t *p, + char **baton); + +/** + * Increments a value + * @param rc client to use + * @param key null terminated string containing the key + * @param inc number to increment by + * @param new_value new value after incrementing + */ +APU_DECLARE(apr_status_t) apr_redis_incr(apr_redis_t *rc, + const char *key, + apr_int32_t inc, + apr_uint32_t *new_value); +/** + * Decrements a value + * @param rc client to use + * @param key null terminated string containing the key + * @param inc number to decrement by + * @param new_value new value after decrementing + */ +APU_DECLARE(apr_status_t) apr_redis_decr(apr_redis_t *rc, + const char *key, + apr_int32_t inc, + apr_uint32_t *new_value); + + +/** + * Pings the server + * @param rs Server to ping + */ +APU_DECLARE(apr_status_t) apr_redis_ping(apr_redis_server_t *rs); + +/** + * Gets multiple values from the server, allocating the values out of p + * @param rc client to use + * @param temp_pool Pool used for temporary allocations. May be cleared inside this + * call. + * @param data_pool Pool used to allocate data for the returned values. + * @param values hash of apr_redis_value_t keyed by strings, contains the + * result of the multiget call. + * @return + */ +APU_DECLARE(apr_status_t) apr_redis_multgetp(apr_redis_t *rc, + apr_pool_t *temp_pool, + apr_pool_t *data_pool, + apr_hash_t *values); + +typedef enum +{ + APR_RS_SERVER_MASTER, /**< Server is a master */ + APR_RS_SERVER_SLAVE, /**< Server is a slave */ + APR_RS_SERVER_UNKNOWN /**< Server role is unknown */ +} apr_redis_server_role_t; + +typedef struct +{ +/* # Server */ + /** Major version number of this server */ + apr_uint32_t major; + /** Minor version number of this server */ + apr_uint32_t minor; + /** Patch version number of this server */ + apr_uint32_t patch; + /** Process id of this server process */ + apr_uint32_t process_id; + /** Number of seconds this server has been running */ + apr_uint32_t uptime_in_seconds; + /** Bitsize of the arch on the current machine */ + apr_uint32_t arch_bits; + +/* # Clients */ + /** Number of connected clients */ + apr_uint32_t connected_clients; + /** Number of blocked clients */ + apr_uint32_t blocked_clients; + +/* # Memory */ + /** Max memory of this server */ + apr_uint64_t maxmemory; + /** Amount of used memory */ + apr_uint64_t used_memory; + /** Total memory available on this server */ + apr_uint64_t total_system_memory; + +/* # Stats */ + /** Total connections received */ + apr_uint64_t total_connections_received; + /** Total commands processed */ + apr_uint64_t total_commands_processed; + /** Total commands rejected */ + apr_uint64_t rejected_connections; + /** Total net input bytes */ + apr_uint64_t total_net_input_bytes; + /** Total net output bytes */ + apr_uint64_t total_net_output_bytes; + /** Keyspace hits */ + apr_uint64_t keyspace_hits; + /** Keyspace misses */ + apr_uint64_t keyspace_misses; + +/* # Replication */ + /** Role */ + apr_redis_server_role_t role; + /** Number of connected slave */ + apr_uint32_t connected_slaves; + +/* # CPU */ + /** Accumulated CPU user time for this process */ + apr_uint32_t used_cpu_sys; + /** Accumulated CPU system time for this process */ + apr_uint32_t used_cpu_user; + +/* # Cluster */ + /** Is cluster enabled */ + apr_uint32_t cluster_enabled; +} apr_redis_stats_t; + +/** + * Query a server for statistics + * @param rs server to query + * @param p Pool to allocate answer from + * @param stats location of the new statistics structure + */ +APU_DECLARE(apr_status_t) apr_redis_stats(apr_redis_server_t *rs, + apr_pool_t *p, + apr_redis_stats_t **stats); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_REDIS_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_reslist.h b/c/dependencies/windows/apr/x64_debug/include/apr_reslist.h new file mode 100644 index 00000000..02a8192b --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_reslist.h @@ -0,0 +1,183 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_RESLIST_H +#define APR_RESLIST_H + +/** + * @file apr_reslist.h + * @brief APR-UTIL Resource List Routines + */ + +#include "apr.h" +#include "apu.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_time.h" + +/** + * @defgroup APR_Util_RL Resource List Routines + * @ingroup APR_Util + * @{ + */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** Opaque resource list object */ +typedef struct apr_reslist_t apr_reslist_t; + +/* Generic constructor called by resource list when it needs to create a + * resource. + * @param resource opaque resource + * @param params flags + * @param pool Pool + */ +typedef apr_status_t (*apr_reslist_constructor)(void **resource, void *params, + apr_pool_t *pool); + +/* Generic destructor called by resource list when it needs to destroy a + * resource. + * @param resource opaque resource + * @param params flags + * @param pool Pool + */ +typedef apr_status_t (*apr_reslist_destructor)(void *resource, void *params, + apr_pool_t *pool); + +/* Cleanup order modes */ +#define APR_RESLIST_CLEANUP_DEFAULT 0 /**< default pool cleanup */ +#define APR_RESLIST_CLEANUP_FIRST 1 /**< use pool pre cleanup */ + +/** + * Create a new resource list with the following parameters: + * @param reslist An address where the pointer to the new resource + * list will be stored. + * @param min Allowed minimum number of available resources. Zero + * creates new resources only when needed. + * @param smax Resources will be destroyed during reslist maintenance to + * meet this maximum restriction as they expire (reach their ttl). + * @param hmax Absolute maximum limit on the number of total resources. + * @param ttl If non-zero, sets the maximum amount of time in microseconds an + * unused resource is valid. Any resource which has exceeded this + * time will be destroyed, either when encountered by + * apr_reslist_acquire() or during reslist maintenance. + * @param con Constructor routine that is called to create a new resource. + * @param de Destructor routine that is called to destroy an expired resource. + * @param params Passed to constructor and deconstructor + * @param pool The pool from which to create this resource list. Also the + * same pool that is passed to the constructor and destructor + * routines. + * @remark If APR has been compiled without thread support, hmax will be + * automatically set to 1 and values of min and smax will be forced to + * 1 for any non-zero value. + */ +APU_DECLARE(apr_status_t) apr_reslist_create(apr_reslist_t **reslist, + int min, int smax, int hmax, + apr_interval_time_t ttl, + apr_reslist_constructor con, + apr_reslist_destructor de, + void *params, + apr_pool_t *pool); + +/** + * Destroy the given resource list and all resources controlled by + * this list. + * FIXME: Should this block until all resources become available, + * or maybe just destroy all the free ones, or maybe destroy + * them even though they might be in use by something else? + * Currently it will abort if there are resources that haven't + * been released, so there is an assumption that all resources + * have been released to the list before calling this function. + * @param reslist The reslist to destroy + */ +APU_DECLARE(apr_status_t) apr_reslist_destroy(apr_reslist_t *reslist); + +/** + * Retrieve a resource from the list, creating a new one if necessary. + * If we have met our maximum number of resources, we will block + * until one becomes available. + * @param reslist The resource list. + * @param resource An address where the pointer to the resource + * will be stored. + */ +APU_DECLARE(apr_status_t) apr_reslist_acquire(apr_reslist_t *reslist, + void **resource); + +/** + * Return a resource back to the list of available resources. + * @param reslist The resource list. + * @param resource The resource to return to the list. + */ +APU_DECLARE(apr_status_t) apr_reslist_release(apr_reslist_t *reslist, + void *resource); + +/** + * Set the timeout the acquire will wait for a free resource + * when the maximum number of resources is exceeded. + * @param reslist The resource list. + * @param timeout Timeout to wait. The zero waits forever. + */ +APU_DECLARE(void) apr_reslist_timeout_set(apr_reslist_t *reslist, + apr_interval_time_t timeout); + +/** + * Return the number of outstanding resources. + * @param reslist The resource list. + */ +APU_DECLARE(apr_uint32_t) apr_reslist_acquired_count(apr_reslist_t *reslist); + +/** + * Invalidate a resource in the pool - e.g. a database connection + * that returns a "lost connection" error and can't be restored. + * Use this instead of apr_reslist_release if the resource is bad. + * @param reslist The resource list. + * @param resource The resource to invalidate. + */ +APU_DECLARE(apr_status_t) apr_reslist_invalidate(apr_reslist_t *reslist, + void *resource); + +/** + * Perform routine maintenance on the resource list. This call + * may instantiate new resources or expire old resources. + * @param reslist The resource list. + */ +APU_DECLARE(apr_status_t) apr_reslist_maintain(apr_reslist_t *reslist); + +/** + * Set reslist cleanup order. + * @param reslist The resource list. + * @param mode Cleanup order mode + *
+ *           APR_RESLIST_CLEANUP_DEFAULT  default pool cleanup order
+ *           APR_RESLIST_CLEANUP_FIRST    use pool pre cleanup
+ * 
+ * @remark If APR_RESLIST_CLEANUP_FIRST is used the destructors will + * be called before child pools of the pool used to create the reslist + * are destroyed. This allows to explicitly destroy the child pools + * inside reslist destructors. + */ +APU_DECLARE(void) apr_reslist_cleanup_order_set(apr_reslist_t *reslist, + apr_uint32_t mode); + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif /* ! APR_RESLIST_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_ring.h b/c/dependencies/windows/apr/x64_debug/include/apr_ring.h new file mode 100644 index 00000000..eec735fc --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_ring.h @@ -0,0 +1,513 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * This code draws heavily from the 4.4BSD macros + * and Dean Gaudet's "splim/ring.h". + * + * + * + * We'd use Dean's code directly if we could guarantee the + * availability of inline functions. + */ + +#ifndef APR_RING_H +#define APR_RING_H + +/** + * @file apr_ring.h + * @brief APR Rings + */ + +/* + * for offsetof() + */ +#include "apr_general.h" + +/** + * @defgroup apr_ring Ring Macro Implementations + * @ingroup APR + * A ring is a kind of doubly-linked list that can be manipulated + * without knowing where its head is. + * @{ + */ + +/** + * The Ring Element + * + * A ring element struct is linked to the other elements in the ring + * through its ring entry field, e.g. + *
+ *      struct my_element_t {
+ *          APR_RING_ENTRY(my_element_t) link;
+ *          int foo;
+ *          char *bar;
+ *      };
+ * 
+ * + * An element struct may be put on more than one ring if it has more + * than one APR_RING_ENTRY field. Each APR_RING_ENTRY has a corresponding + * APR_RING_HEAD declaration. + * + * @warning For strict C standards compliance you should put the APR_RING_ENTRY + * first in the element struct unless the head is always part of a larger + * object with enough earlier fields to accommodate the offsetof() used + * to compute the ring sentinel below. You can usually ignore this caveat. + */ +#define APR_RING_ENTRY(elem) \ + struct { \ + struct elem * volatile next; \ + struct elem * volatile prev; \ + } + +/** + * The Ring Head + * + * Each ring is managed via its head, which is a struct declared like this: + *
+ *      APR_RING_HEAD(my_ring_t, my_element_t);
+ *      struct my_ring_t ring, *ringp;
+ * 
+ * + * This struct looks just like the element link struct so that we can + * be sure that the typecasting games will work as expected. + * + * The first element in the ring is next after the head, and the last + * element is just before the head. + */ +#define APR_RING_HEAD(head, elem) \ + struct head { \ + struct elem * volatile next; \ + struct elem * volatile prev; \ + } + +/** + * The Ring Sentinel + * + * This is the magic pointer value that occurs before the first and + * after the last elements in the ring, computed from the address of + * the ring's head. The head itself isn't an element, but in order to + * get rid of all the special cases when dealing with the ends of the + * ring, we play typecasting games to make it look like one. + * + * Here is a diagram to illustrate the arrangements of the next and + * prev pointers of each element in a single ring. Note that they point + * to the start of each element, not to the APR_RING_ENTRY structure. + * + *
+ *     +->+------+<-+  +->+------+<-+  +->+------+<-+
+ *     |  |struct|  |  |  |struct|  |  |  |struct|  |
+ *    /   | elem |   \/   | elem |   \/   | elem |  \
+ * ...    |      |   /\   |      |   /\   |      |   ...
+ *        +------+  |  |  +------+  |  |  +------+
+ *   ...--|prev  |  |  +--|ring  |  |  +--|prev  |
+ *        |  next|--+     | entry|--+     |  next|--...
+ *        +------+        +------+        +------+
+ *        | etc. |        | etc. |        | etc. |
+ *        :      :        :      :        :      :
+ * 
+ * + * The APR_RING_HEAD is nothing but a bare APR_RING_ENTRY. The prev + * and next pointers in the first and last elements don't actually + * point to the head, they point to a phantom place called the + * sentinel. Its value is such that last->next->next == first because + * the offset from the sentinel to the head's next pointer is the same + * as the offset from the start of an element to its next pointer. + * This also works in the opposite direction. + * + *
+ *        last                            first
+ *     +->+------+<-+  +->sentinel<-+  +->+------+<-+
+ *     |  |struct|  |  |            |  |  |struct|  |
+ *    /   | elem |   \/              \/   | elem |  \
+ * ...    |      |   /\              /\   |      |   ...
+ *        +------+  |  |  +------+  |  |  +------+
+ *   ...--|prev  |  |  +--|ring  |  |  +--|prev  |
+ *        |  next|--+     |  head|--+     |  next|--...
+ *        +------+        +------+        +------+
+ *        | etc. |                        | etc. |
+ *        :      :                        :      :
+ * 
+ * + * Note that the offset mentioned above is different for each kind of + * ring that the element may be on, and each kind of ring has a unique + * name for its APR_RING_ENTRY in each element, and has its own type + * for its APR_RING_HEAD. + * + * Note also that if the offset is non-zero (which is required if an + * element has more than one APR_RING_ENTRY), the unreality of the + * sentinel may have bad implications on very perverse implementations + * of C -- see the warning in APR_RING_ENTRY. + * + * @param hp The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SENTINEL(hp, elem, link) \ + (struct elem *)((char *)(&(hp)->next) - APR_OFFSETOF(struct elem, link)) + +/** + * The first element of the ring + * @param hp The head of the ring + */ +#define APR_RING_FIRST(hp) (hp)->next +/** + * The last element of the ring + * @param hp The head of the ring + */ +#define APR_RING_LAST(hp) (hp)->prev +/** + * The next element in the ring + * @param ep The current element + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_NEXT(ep, link) (ep)->link.next +/** + * The previous element in the ring + * @param ep The current element + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_PREV(ep, link) (ep)->link.prev + + +/** + * Initialize a ring + * @param hp The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INIT(hp, elem, link) do { \ + APR_RING_FIRST((hp)) = APR_RING_SENTINEL((hp), elem, link); \ + APR_RING_LAST((hp)) = APR_RING_SENTINEL((hp), elem, link); \ + } while (0) + +/** + * Determine if a ring is empty + * @param hp The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + * @return true or false + */ +#define APR_RING_EMPTY(hp, elem, link) \ + (APR_RING_FIRST((hp)) == APR_RING_SENTINEL((hp), elem, link)) + +/** + * Initialize a singleton element + * @param ep The element + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_ELEM_INIT(ep, link) do { \ + APR_RING_NEXT((ep), link) = (ep); \ + APR_RING_PREV((ep), link) = (ep); \ + } while (0) + + +/** + * Splice the sequence ep1..epN into the ring before element lep + * (..lep.. becomes ..ep1..epN..lep..) + * @warning This doesn't work for splicing before the first element or on + * empty rings... see APR_RING_SPLICE_HEAD for one that does + * @param lep Element in the ring to splice before + * @param ep1 First element in the sequence to splice in + * @param epN Last element in the sequence to splice in + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SPLICE_BEFORE(lep, ep1, epN, link) do { \ + APR_RING_NEXT((epN), link) = (lep); \ + APR_RING_PREV((ep1), link) = APR_RING_PREV((lep), link); \ + APR_RING_NEXT(APR_RING_PREV((lep), link), link) = (ep1); \ + APR_RING_PREV((lep), link) = (epN); \ + } while (0) + +/** + * Splice the sequence ep1..epN into the ring after element lep + * (..lep.. becomes ..lep..ep1..epN..) + * @warning This doesn't work for splicing after the last element or on + * empty rings... see APR_RING_SPLICE_TAIL for one that does + * @param lep Element in the ring to splice after + * @param ep1 First element in the sequence to splice in + * @param epN Last element in the sequence to splice in + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SPLICE_AFTER(lep, ep1, epN, link) do { \ + APR_RING_PREV((ep1), link) = (lep); \ + APR_RING_NEXT((epN), link) = APR_RING_NEXT((lep), link); \ + APR_RING_PREV(APR_RING_NEXT((lep), link), link) = (epN); \ + APR_RING_NEXT((lep), link) = (ep1); \ + } while (0) + +/** + * Insert the element nep into the ring before element lep + * (..lep.. becomes ..nep..lep..) + * @warning This doesn't work for inserting before the first element or on + * empty rings... see APR_RING_INSERT_HEAD for one that does + * @param lep Element in the ring to insert before + * @param nep Element to insert + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INSERT_BEFORE(lep, nep, link) \ + APR_RING_SPLICE_BEFORE((lep), (nep), (nep), link) + +/** + * Insert the element nep into the ring after element lep + * (..lep.. becomes ..lep..nep..) + * @warning This doesn't work for inserting after the last element or on + * empty rings... see APR_RING_INSERT_TAIL for one that does + * @param lep Element in the ring to insert after + * @param nep Element to insert + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INSERT_AFTER(lep, nep, link) \ + APR_RING_SPLICE_AFTER((lep), (nep), (nep), link) + + +/** + * Splice the sequence ep1..epN into the ring before the first element + * (..hp.. becomes ..hp..ep1..epN..) + * @param hp Head of the ring + * @param ep1 First element in the sequence to splice in + * @param epN Last element in the sequence to splice in + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SPLICE_HEAD(hp, ep1, epN, elem, link) \ + APR_RING_SPLICE_AFTER(APR_RING_SENTINEL((hp), elem, link), \ + (ep1), (epN), link) + +/** + * Splice the sequence ep1..epN into the ring after the last element + * (..hp.. becomes ..ep1..epN..hp..) + * @param hp Head of the ring + * @param ep1 First element in the sequence to splice in + * @param epN Last element in the sequence to splice in + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SPLICE_TAIL(hp, ep1, epN, elem, link) \ + APR_RING_SPLICE_BEFORE(APR_RING_SENTINEL((hp), elem, link), \ + (ep1), (epN), link) + +/** + * Insert the element nep into the ring before the first element + * (..hp.. becomes ..hp..nep..) + * @param hp Head of the ring + * @param nep Element to insert + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INSERT_HEAD(hp, nep, elem, link) \ + APR_RING_SPLICE_HEAD((hp), (nep), (nep), elem, link) + +/** + * Insert the element nep into the ring after the last element + * (..hp.. becomes ..nep..hp..) + * @param hp Head of the ring + * @param nep Element to insert + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INSERT_TAIL(hp, nep, elem, link) \ + APR_RING_SPLICE_TAIL((hp), (nep), (nep), elem, link) + +/** + * Concatenate ring h2 onto the end of ring h1, leaving h2 empty. + * @param h1 Head of the ring to concatenate onto + * @param h2 Head of the ring to concatenate + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_CONCAT(h1, h2, elem, link) do { \ + if (!APR_RING_EMPTY((h2), elem, link)) { \ + APR_RING_SPLICE_BEFORE(APR_RING_SENTINEL((h1), elem, link), \ + APR_RING_FIRST((h2)), \ + APR_RING_LAST((h2)), link); \ + APR_RING_INIT((h2), elem, link); \ + } \ + } while (0) + +/** + * Prepend ring h2 onto the beginning of ring h1, leaving h2 empty. + * @param h1 Head of the ring to prepend onto + * @param h2 Head of the ring to prepend + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_PREPEND(h1, h2, elem, link) do { \ + if (!APR_RING_EMPTY((h2), elem, link)) { \ + APR_RING_SPLICE_AFTER(APR_RING_SENTINEL((h1), elem, link), \ + APR_RING_FIRST((h2)), \ + APR_RING_LAST((h2)), link); \ + APR_RING_INIT((h2), elem, link); \ + } \ + } while (0) + +/** + * Unsplice a sequence of elements from a ring + * @warning The unspliced sequence is left with dangling pointers at either end + * @param ep1 First element in the sequence to unsplice + * @param epN Last element in the sequence to unsplice + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_UNSPLICE(ep1, epN, link) do { \ + APR_RING_NEXT(APR_RING_PREV((ep1), link), link) = \ + APR_RING_NEXT((epN), link); \ + APR_RING_PREV(APR_RING_NEXT((epN), link), link) = \ + APR_RING_PREV((ep1), link); \ + } while (0) + +/** + * Remove a single element from a ring + * @warning The unspliced element is left with dangling pointers at either end + * @param ep Element to remove + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_REMOVE(ep, link) \ + APR_RING_UNSPLICE((ep), (ep), link) + +/** + * Iterate over a ring + * @param ep The current element + * @param head The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_FOREACH(ep, head, elem, link) \ + for (ep = APR_RING_FIRST(head); \ + ep != APR_RING_SENTINEL(head, elem, link); \ + ep = APR_RING_NEXT(ep, link)) + +/** + * Iterate over a ring safe against removal of the current element + * @param ep1 The current element + * @param ep2 Iteration cursor + * @param head The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_FOREACH_SAFE(ep1, ep2, head, elem, link) \ + for (ep1 = APR_RING_FIRST(head), ep2 = APR_RING_NEXT(ep1, link); \ + ep1 != APR_RING_SENTINEL(head, elem, link); \ + ep1 = ep2, ep2 = APR_RING_NEXT(ep1, link)) + +/* Debugging tools: */ + +#ifdef APR_RING_DEBUG +#include +#include + +#define APR_RING_CHECK_ONE(msg, ptr) \ + fprintf(stderr, "*** %s %p\n", msg, ptr) + +#define APR_RING_CHECK(hp, elem, link, msg) \ + APR_RING_CHECK_ELEM(APR_RING_SENTINEL(hp, elem, link), elem, link, msg) + +#define APR_RING_CHECK_ELEM(ep, elem, link, msg) do { \ + struct elem *start = (ep); \ + struct elem *here = start; \ + fprintf(stderr, "*** ring check start -- %s\n", msg); \ + do { \ + fprintf(stderr, "\telem %p\n", here); \ + fprintf(stderr, "\telem->next %p\n", \ + APR_RING_NEXT(here, link)); \ + fprintf(stderr, "\telem->prev %p\n", \ + APR_RING_PREV(here, link)); \ + fprintf(stderr, "\telem->next->prev %p\n", \ + APR_RING_PREV(APR_RING_NEXT(here, link), link)); \ + fprintf(stderr, "\telem->prev->next %p\n", \ + APR_RING_NEXT(APR_RING_PREV(here, link), link)); \ + if (APR_RING_PREV(APR_RING_NEXT(here, link), link) != here) { \ + fprintf(stderr, "\t*** elem->next->prev != elem\n"); \ + break; \ + } \ + if (APR_RING_NEXT(APR_RING_PREV(here, link), link) != here) { \ + fprintf(stderr, "\t*** elem->prev->next != elem\n"); \ + break; \ + } \ + here = APR_RING_NEXT(here, link); \ + } while (here != start); \ + fprintf(stderr, "*** ring check end\n"); \ + } while (0) + +#define APR_RING_CHECK_CONSISTENCY(hp, elem, link) \ + APR_RING_CHECK_ELEM_CONSISTENCY(APR_RING_SENTINEL(hp, elem, link),\ + elem, link) + +#define APR_RING_CHECK_ELEM_CONSISTENCY(ep, elem, link) do { \ + struct elem *start = (ep); \ + struct elem *here = start; \ + do { \ + assert(APR_RING_PREV(APR_RING_NEXT(here, link), link) == here); \ + assert(APR_RING_NEXT(APR_RING_PREV(here, link), link) == here); \ + here = APR_RING_NEXT(here, link); \ + } while (here != start); \ + } while (0) + +#else +/** + * Print a single pointer value to STDERR + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param msg Descriptive message + * @param ptr Pointer value to print + */ +#define APR_RING_CHECK_ONE(msg, ptr) +/** + * Dump all ring pointers to STDERR, starting with the head and looping all + * the way around the ring back to the head. Aborts if an inconsistency + * is found. + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param hp Head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + * @param msg Descriptive message + */ +#define APR_RING_CHECK(hp, elem, link, msg) +/** + * Loops around a ring and checks all the pointers for consistency. Pops + * an assertion if any inconsistency is found. Same idea as APR_RING_CHECK() + * except that it's silent if all is well. + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param hp Head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_CHECK_CONSISTENCY(hp, elem, link) +/** + * Dump all ring pointers to STDERR, starting with the given element and + * looping all the way around the ring back to that element. Aborts if + * an inconsistency is found. + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param ep The element + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + * @param msg Descriptive message + */ +#define APR_RING_CHECK_ELEM(ep, elem, link, msg) +/** + * Loops around a ring, starting with the given element, and checks all + * the pointers for consistency. Pops an assertion if any inconsistency + * is found. Same idea as APR_RING_CHECK_ELEM() except that it's silent + * if all is well. + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param ep The element + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_CHECK_ELEM_CONSISTENCY(ep, elem, link) +#endif + +/** @} */ + +#endif /* !APR_RING_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_rmm.h b/c/dependencies/windows/apr/x64_debug/include/apr_rmm.h new file mode 100644 index 00000000..976fe9c5 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_rmm.h @@ -0,0 +1,137 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_RMM_H +#define APR_RMM_H +/** + * @file apr_rmm.h + * @brief APR-UTIL Relocatable Memory Management Routines + */ +/** + * @defgroup APR_Util_RMM Relocatable Memory Management Routines + * @ingroup APR_Util + * @{ + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apu.h" +#include "apr_anylock.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** Structure to access Relocatable, Managed Memory */ +typedef struct apr_rmm_t apr_rmm_t; + +/** Fundamental allocation unit, within a specific apr_rmm_t */ +typedef apr_size_t apr_rmm_off_t; + +/** + * Initialize a relocatable memory block to be managed by the apr_rmm API. + * @param rmm The relocatable memory block + * @param lock An apr_anylock_t of the appropriate type of lock, or NULL + * if no locking is required. + * @param membuf The block of relocatable memory to be managed + * @param memsize The size of relocatable memory block to be managed + * @param cont The pool to use for local storage and management + * @remark Both @param membuf and @param memsize must be aligned + * (for instance using APR_ALIGN_DEFAULT). + */ +APU_DECLARE(apr_status_t) apr_rmm_init(apr_rmm_t **rmm, apr_anylock_t *lock, + void *membuf, apr_size_t memsize, + apr_pool_t *cont); + +/** + * Destroy a managed memory block. + * @param rmm The relocatable memory block to destroy + */ +APU_DECLARE(apr_status_t) apr_rmm_destroy(apr_rmm_t *rmm); + +/** + * Attach to a relocatable memory block already managed by the apr_rmm API. + * @param rmm The relocatable memory block + * @param lock An apr_anylock_t of the appropriate type of lock + * @param membuf The block of relocatable memory already under management + * @param cont The pool to use for local storage and management + */ +APU_DECLARE(apr_status_t) apr_rmm_attach(apr_rmm_t **rmm, apr_anylock_t *lock, + void *membuf, apr_pool_t *cont); + +/** + * Detach from the managed block of memory. + * @param rmm The relocatable memory block to detach from + */ +APU_DECLARE(apr_status_t) apr_rmm_detach(apr_rmm_t *rmm); + +/** + * Allocate memory from the block of relocatable memory. + * @param rmm The relocatable memory block + * @param reqsize How much memory to allocate + */ +APU_DECLARE(apr_rmm_off_t) apr_rmm_malloc(apr_rmm_t *rmm, apr_size_t reqsize); + +/** + * Realloc memory from the block of relocatable memory. + * @param rmm The relocatable memory block + * @param entity The memory allocation to realloc + * @param reqsize The new size + */ +APU_DECLARE(apr_rmm_off_t) apr_rmm_realloc(apr_rmm_t *rmm, void *entity, apr_size_t reqsize); + +/** + * Allocate memory from the block of relocatable memory and initialize it to zero. + * @param rmm The relocatable memory block + * @param reqsize How much memory to allocate + */ +APU_DECLARE(apr_rmm_off_t) apr_rmm_calloc(apr_rmm_t *rmm, apr_size_t reqsize); + +/** + * Free allocation returned by apr_rmm_malloc or apr_rmm_calloc. + * @param rmm The relocatable memory block + * @param entity The memory allocation to free + */ +APU_DECLARE(apr_status_t) apr_rmm_free(apr_rmm_t *rmm, apr_rmm_off_t entity); + +/** + * Retrieve the physical address of a relocatable allocation of memory + * @param rmm The relocatable memory block + * @param entity The memory allocation to free + * @return address The address, aligned with APR_ALIGN_DEFAULT. + */ +APU_DECLARE(void *) apr_rmm_addr_get(apr_rmm_t *rmm, apr_rmm_off_t entity); + +/** + * Compute the offset of a relocatable allocation of memory + * @param rmm The relocatable memory block + * @param entity The physical address to convert to an offset + */ +APU_DECLARE(apr_rmm_off_t) apr_rmm_offset_get(apr_rmm_t *rmm, void *entity); + +/** + * Compute the required overallocation of memory needed to fit n allocs + * @param n The number of alloc/calloc regions desired + */ +APU_DECLARE(apr_size_t) apr_rmm_overhead_get(int n); + +#ifdef __cplusplus +} +#endif +/** @} */ +#endif /* ! APR_RMM_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_sdbm.h b/c/dependencies/windows/apr/x64_debug/include/apr_sdbm.h new file mode 100644 index 00000000..5759508b --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_sdbm.h @@ -0,0 +1,176 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * sdbm - ndbm work-alike hashed database library + * based on Per-Ake Larson's Dynamic Hashing algorithms. BIT 18 (1978). + * author: oz@nexus.yorku.ca + * status: ex-public domain + */ + +#ifndef APR_SDBM_H +#define APR_SDBM_H + +#include "apu.h" +#include "apr_errno.h" +#include "apr_file_io.h" /* for apr_fileperms_t */ + +/** + * @file apr_sdbm.h + * @brief apr-util SDBM library + */ +/** + * @defgroup APR_Util_DBM_SDBM SDBM library + * @ingroup APR_Util_DBM + * @{ + */ + +/** + * Structure for referencing an sdbm + */ +typedef struct apr_sdbm_t apr_sdbm_t; + +/** + * Structure for referencing the datum record within an sdbm + */ +typedef struct { + /** pointer to the data stored/retrieved */ + char *dptr; + /** size of data */ + /* apr_ssize_t for release 2.0??? */ + int dsize; +} apr_sdbm_datum_t; + +/* The extensions used for the database files */ +/** SDBM Directory file extension */ +#define APR_SDBM_DIRFEXT ".dir" +/** SDBM page file extension */ +#define APR_SDBM_PAGFEXT ".pag" + +/* flags to sdbm_store */ +#define APR_SDBM_INSERT 0 /**< Insert */ +#define APR_SDBM_REPLACE 1 /**< Replace */ +#define APR_SDBM_INSERTDUP 2 /**< Insert with duplicates */ + +/** + * Open an sdbm database by file name + * @param db The newly opened database + * @param name The sdbm file to open + * @param mode The flag values (APR_READ and APR_BINARY flags are implicit) + *
+ *           APR_WRITE          open for read-write access
+ *           APR_CREATE         create the sdbm if it does not exist
+ *           APR_TRUNCATE       empty the contents of the sdbm
+ *           APR_EXCL           fail for APR_CREATE if the file exists
+ *           APR_DELONCLOSE     delete the sdbm when closed
+ *           APR_SHARELOCK      support locking across process/machines
+ * 
+ * @param perms Permissions to apply to if created + * @param p The pool to use when creating the sdbm + * @remark The sdbm name is not a true file name, as sdbm appends suffixes + * for seperate data and index files. + */ +APU_DECLARE(apr_status_t) apr_sdbm_open(apr_sdbm_t **db, const char *name, + apr_int32_t mode, + apr_fileperms_t perms, apr_pool_t *p); + +/** + * Close an sdbm file previously opened by apr_sdbm_open + * @param db The database to close + */ +APU_DECLARE(apr_status_t) apr_sdbm_close(apr_sdbm_t *db); + +/** + * Lock an sdbm database for concurency of multiple operations + * @param db The database to lock + * @param type The lock type + *
+ *           APR_FLOCK_SHARED
+ *           APR_FLOCK_EXCLUSIVE
+ * 
+ * @remark Calls to apr_sdbm_lock may be nested. All apr_sdbm functions + * perform implicit locking. Since an APR_FLOCK_SHARED lock cannot be + * portably promoted to an APR_FLOCK_EXCLUSIVE lock, apr_sdbm_store and + * apr_sdbm_delete calls will fail if an APR_FLOCK_SHARED lock is held. + * The apr_sdbm_lock call requires the database to be opened with the + * APR_SHARELOCK mode value. + */ +APU_DECLARE(apr_status_t) apr_sdbm_lock(apr_sdbm_t *db, int type); + +/** + * Release an sdbm lock previously aquired by apr_sdbm_lock + * @param db The database to unlock + */ +APU_DECLARE(apr_status_t) apr_sdbm_unlock(apr_sdbm_t *db); + +/** + * Fetch an sdbm record value by key + * @param db The database + * @param value The value datum retrieved for this record + * @param key The key datum to find this record + */ +APU_DECLARE(apr_status_t) apr_sdbm_fetch(apr_sdbm_t *db, + apr_sdbm_datum_t *value, + apr_sdbm_datum_t key); + +/** + * Store an sdbm record value by key + * @param db The database + * @param key The key datum to store this record by + * @param value The value datum to store in this record + * @param opt The method used to store the record + *
+ *           APR_SDBM_INSERT     return an error if the record exists
+ *           APR_SDBM_REPLACE    overwrite any existing record for key
+ * 
+ */ +APU_DECLARE(apr_status_t) apr_sdbm_store(apr_sdbm_t *db, apr_sdbm_datum_t key, + apr_sdbm_datum_t value, int opt); + +/** + * Delete an sdbm record value by key + * @param db The database + * @param key The key datum of the record to delete + * @remark It is not an error to delete a non-existent record. + */ +APU_DECLARE(apr_status_t) apr_sdbm_delete(apr_sdbm_t *db, + const apr_sdbm_datum_t key); + +/** + * Retrieve the first record key from a dbm + * @param db The database + * @param key The key datum of the first record + * @remark The keys returned are not ordered. To traverse the list of keys + * for an sdbm opened with APR_SHARELOCK, the caller must use apr_sdbm_lock + * prior to retrieving the first record, and hold the lock until after the + * last call to apr_sdbm_nextkey. + */ +APU_DECLARE(apr_status_t) apr_sdbm_firstkey(apr_sdbm_t *db, apr_sdbm_datum_t *key); + +/** + * Retrieve the next record key from an sdbm + * @param db The database + * @param key The key datum of the next record + */ +APU_DECLARE(apr_status_t) apr_sdbm_nextkey(apr_sdbm_t *db, apr_sdbm_datum_t *key); + +/** + * Returns true if the sdbm database opened for read-only access + * @param db The database to test + */ +APU_DECLARE(int) apr_sdbm_rdonly(apr_sdbm_t *db); +/** @} */ +#endif /* APR_SDBM_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_sha1.h b/c/dependencies/windows/apr/x64_debug/include/apr_sha1.h new file mode 100644 index 00000000..2a4edf36 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_sha1.h @@ -0,0 +1,121 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* NIST Secure Hash Algorithm + * heavily modified by Uwe Hollerbach uh@alumni.caltech edu + * from Peter C. Gutmann's implementation as found in + * Applied Cryptography by Bruce Schneier + * This code is hereby placed in the public domain + */ + +#ifndef APR_SHA1_H +#define APR_SHA1_H + +#include "apu.h" +#include "apr_general.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_sha1.h + * @brief APR-UTIL SHA1 library + */ + +/** size of the SHA1 DIGEST */ +#define APR_SHA1_DIGESTSIZE 20 + +/** + * Define the Magic String prefix that identifies a password as being + * hashed using our algorithm. + */ +#define APR_SHA1PW_ID "{SHA}" + +/** length of the SHA Password */ +#define APR_SHA1PW_IDLEN 5 + +/** @see apr_sha1_ctx_t */ +typedef struct apr_sha1_ctx_t apr_sha1_ctx_t; + +/** + * SHA1 context structure + */ +struct apr_sha1_ctx_t { + /** message digest */ + apr_uint32_t digest[5]; + /** 64-bit bit counts */ + apr_uint32_t count_lo, count_hi; + /** SHA data buffer */ + apr_uint32_t data[16]; + /** unprocessed amount in data */ + int local; +}; + +/** + * Provide a means to SHA1 crypt/encode a plaintext password in a way which + * makes password file compatible with those commonly use in netscape web + * and ldap installations. + * @param clear The plaintext password + * @param len The length of the plaintext password + * @param out The encrypted/encoded password + * @note SHA1 support is useful for migration purposes, but is less + * secure than Apache's password format, since Apache's (MD5) + * password format uses a random eight character salt to generate + * one of many possible hashes for the same password. Netscape + * uses plain SHA1 without a salt, so the same password + * will always generate the same hash, making it easier + * to break since the search space is smaller. + */ +APU_DECLARE(void) apr_sha1_base64(const char *clear, int len, char *out); + +/** + * Initialize the SHA digest + * @param context The SHA context to initialize + */ +APU_DECLARE(void) apr_sha1_init(apr_sha1_ctx_t *context); + +/** + * Update the SHA digest + * @param context The SHA1 context to update + * @param input The buffer to add to the SHA digest + * @param inputLen The length of the input buffer + */ +APU_DECLARE(void) apr_sha1_update(apr_sha1_ctx_t *context, const char *input, + unsigned int inputLen); + +/** + * Update the SHA digest with binary data + * @param context The SHA1 context to update + * @param input The buffer to add to the SHA digest + * @param inputLen The length of the input buffer + */ +APU_DECLARE(void) apr_sha1_update_binary(apr_sha1_ctx_t *context, + const unsigned char *input, + unsigned int inputLen); + +/** + * Finish computing the SHA digest + * @param digest the output buffer in which to store the digest + * @param context The context to finalize + */ +APU_DECLARE(void) apr_sha1_final(unsigned char digest[APR_SHA1_DIGESTSIZE], + apr_sha1_ctx_t *context); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_SHA1_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_shm.h b/c/dependencies/windows/apr/x64_debug/include/apr_shm.h new file mode 100644 index 00000000..635c654b --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_shm.h @@ -0,0 +1,229 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_SHM_H +#define APR_SHM_H + +/** + * @file apr_shm.h + * @brief APR Shared Memory Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_perms_set.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_shm Shared Memory Routines + * @ingroup APR + * @{ + */ + +/** + * Private, platform-specific data struture representing a shared memory + * segment. + */ +typedef struct apr_shm_t apr_shm_t; + +/** + * Create and make accessible a shared memory segment with default + * properties. + * @param m The shared memory structure to create. + * @param reqsize The desired size of the segment. + * @param filename The file to use for shared memory on platforms that + * require it. + * @param pool the pool from which to allocate the shared memory + * structure. + * @remark A note about Anonymous vs. Named shared memory segments: + * Not all plaforms support anonymous shared memory segments, but in + * some cases it is prefered over other types of shared memory + * implementations. Passing a NULL 'file' parameter to this function + * will cause the subsystem to use anonymous shared memory segments. + * If such a system is not available, APR_ENOTIMPL is returned. + * @remark A note about allocation sizes: + * On some platforms it is necessary to store some metainformation + * about the segment within the actual segment. In order to supply + * the caller with the requested size it may be necessary for the + * implementation to request a slightly greater segment length + * from the subsystem. In all cases, the apr_shm_baseaddr_get() + * function will return the first usable byte of memory. + * + */ +APR_DECLARE(apr_status_t) apr_shm_create(apr_shm_t **m, + apr_size_t reqsize, + const char *filename, + apr_pool_t *pool); + +/** + * Special processing flags for apr_shm_create_ex() and apr_shm_attach_ex(). + */ +#define APR_SHM_NS_LOCAL 1 /* Create or attach to named shared memory + * segment in the "Local" namespace on + * Windows. (Ignored on other platforms.) + * By default, the "Global" namespace is + * used for privileged processes and the + * "Local" namespace is used otherwise. + */ +#define APR_SHM_NS_GLOBAL 2 /* Create or attach to named shared memory + * segment in the "Global" namespace on + * Windows. (Ignored on other platforms.) + */ + +/** + * Create and make accessible a shared memory segment with platform- + * specific processing. + * @param m The shared memory structure to create. + * @param reqsize The desired size of the segment. + * @param filename The file to use for shared memory on platforms that + * require it. + * @param pool the pool from which to allocate the shared memory + * structure. + * @param flags mask of APR_SHM_* (defined above) + * @remark A note about Anonymous vs. Named shared memory segments: + * Not all plaforms support anonymous shared memory segments, but in + * some cases it is prefered over other types of shared memory + * implementations. Passing a NULL 'file' parameter to this function + * will cause the subsystem to use anonymous shared memory segments. + * If such a system is not available, APR_ENOTIMPL is returned. + * @remark A note about allocation sizes: + * On some platforms it is necessary to store some metainformation + * about the segment within the actual segment. In order to supply + * the caller with the requested size it may be necessary for the + * implementation to request a slightly greater segment length + * from the subsystem. In all cases, the apr_shm_baseaddr_get() + * function will return the first usable byte of memory. + * + */ +APR_DECLARE(apr_status_t) apr_shm_create_ex(apr_shm_t **m, + apr_size_t reqsize, + const char *filename, + apr_pool_t *pool, + apr_int32_t flags); + +/** + * Remove named resource associated with a shared memory segment, + * preventing attachments to the resource, but not destroying it. + * @param filename The filename associated with shared-memory segment which + * needs to be removed + * @param pool The pool used for file operations + * @remark This function is only supported on platforms which support + * name-based shared memory segments, and will return APR_ENOTIMPL on + * platforms without such support. Removing the file while the shm + * is in use is not entirely portable, caller may use this to enhance + * obscurity of the resource, but be prepared for the call to fail, + * and for concurrent attempts to create a resource of the same name + * to also fail. The pool cleanup of apr_shm_create (apr_shm_destroy) + * also removes the named resource. + */ +APR_DECLARE(apr_status_t) apr_shm_remove(const char *filename, + apr_pool_t *pool); + +/** + * Delete named resource associated with a shared memory segment, + * preventing attachments to the resource. + * @param m The shared memory segment structure to delete. + * @remark This function is only supported on platforms which support + * name-based shared memory segments, and will return APR_ENOTIMPL on + * platforms without such support. Removing the file while the shm + * is in use is not entirely portable, caller may use this to enhance + * obscurity of the resource, but be prepared for the call to fail, + * and for concurrent attempts to create a resource of the same name + * to also fail. The pool cleanup of apr_shm_create (apr_shm_destroy) + * also removes the named resource. + */ +APR_DECLARE(apr_status_t) apr_shm_delete(apr_shm_t *m); + +/** + * Destroy a shared memory segment and associated memory. + * @param m The shared memory segment structure to destroy. + */ +APR_DECLARE(apr_status_t) apr_shm_destroy(apr_shm_t *m); + +/** + * Attach to a shared memory segment that was created + * by another process. + * @param m The shared memory structure to create. + * @param filename The file used to create the original segment. + * (This MUST match the original filename.) + * @param pool the pool from which to allocate the shared memory + * structure for this process. + */ +APR_DECLARE(apr_status_t) apr_shm_attach(apr_shm_t **m, + const char *filename, + apr_pool_t *pool); + +/** + * Attach to a shared memory segment that was created + * by another process, with platform-specific processing. + * @param m The shared memory structure to create. + * @param filename The file used to create the original segment. + * (This MUST match the original filename.) + * @param pool the pool from which to allocate the shared memory + * structure for this process. + * @param flags mask of APR_SHM_* (defined above) + */ +APR_DECLARE(apr_status_t) apr_shm_attach_ex(apr_shm_t **m, + const char *filename, + apr_pool_t *pool, + apr_int32_t flags); + +/** + * Detach from a shared memory segment without destroying it. + * @param m The shared memory structure representing the segment + * to detach from. + */ +APR_DECLARE(apr_status_t) apr_shm_detach(apr_shm_t *m); + +/** + * Retrieve the base address of the shared memory segment. + * NOTE: This address is only usable within the callers address + * space, since this API does not guarantee that other attaching + * processes will maintain the same address mapping. + * @param m The shared memory segment from which to retrieve + * the base address. + * @return address, aligned by APR_ALIGN_DEFAULT. + */ +APR_DECLARE(void *) apr_shm_baseaddr_get(const apr_shm_t *m); + +/** + * Retrieve the length of a shared memory segment in bytes. + * @param m The shared memory segment from which to retrieve + * the segment length. + */ +APR_DECLARE(apr_size_t) apr_shm_size_get(const apr_shm_t *m); + +/** + * Set shared memory permissions. + */ +APR_PERMS_SET_IMPLEMENT(shm); + +/** + * Get the pool used by this shared memory segment. + */ +APR_POOL_DECLARE_ACCESSOR(shm); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_SHM_T */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_signal.h b/c/dependencies/windows/apr/x64_debug/include/apr_signal.h new file mode 100644 index 00000000..20631333 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_signal.h @@ -0,0 +1,109 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_SIGNAL_H +#define APR_SIGNAL_H + +/** + * @file apr_signal.h + * @brief APR Signal Handling + */ + +#include "apr.h" +#include "apr_pools.h" + +#if APR_HAVE_SIGNAL_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_signal Signal Handling + * @ingroup APR + * @{ + */ + +#if APR_HAVE_SIGACTION || defined(DOXYGEN) + +#if defined(DARWIN) && !defined(__cplusplus) && !defined(_ANSI_SOURCE) +/* work around Darwin header file bugs + * http://www.opensource.apple.com/bugs/X/BSD%20Kernel/2657228.html + */ +#undef SIG_DFL +#undef SIG_IGN +#undef SIG_ERR +#define SIG_DFL (void (*)(int))0 +#define SIG_IGN (void (*)(int))1 +#define SIG_ERR (void (*)(int))-1 +#endif + +/** Function prototype for signal handlers */ +typedef void apr_sigfunc_t(int); + +/** + * Set the signal handler function for a given signal + * @param signo The signal (eg... SIGWINCH) + * @param func the function to get called + */ +APR_DECLARE(apr_sigfunc_t *) apr_signal(int signo, apr_sigfunc_t * func); + +#if defined(SIG_IGN) && !defined(SIG_ERR) +#define SIG_ERR ((apr_sigfunc_t *) -1) +#endif + +#else /* !APR_HAVE_SIGACTION */ +#define apr_signal(a, b) signal(a, b) +#endif + + +/** + * Get the description for a specific signal number + * @param signum The signal number + * @return The description of the signal + */ +APR_DECLARE(const char *) apr_signal_description_get(int signum); + +/** + * APR-private function for initializing the signal package + * @internal + * @param pglobal The internal, global pool + */ +void apr_signal_init(apr_pool_t *pglobal); + +/** + * Block the delivery of a particular signal + * @param signum The signal number + * @return status + */ +APR_DECLARE(apr_status_t) apr_signal_block(int signum); + +/** + * Enable the delivery of a particular signal + * @param signum The signal number + * @return status + */ +APR_DECLARE(apr_status_t) apr_signal_unblock(int signum); + +/** @} */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* APR_SIGNAL_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_siphash.h b/c/dependencies/windows/apr/x64_debug/include/apr_siphash.h new file mode 100644 index 00000000..42aa8874 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_siphash.h @@ -0,0 +1,148 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + SipHash reference C implementation + Copyright (c) 2012-2014 Jean-Philippe Aumasson + + Copyright (c) 2012-2014 Daniel J. Bernstein + To the extent possible under law, the author(s) have dedicated all copyright + and related and neighboring rights to this software to the public domain + worldwide. This software is distributed without any warranty. + You should have received a copy of the CC0 Public Domain Dedication along + with this software. If not, see + . + */ + +#ifndef APR_SIPHASH_H +#define APR_SIPHASH_H + +#include "apr.h" +#include "apu.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_siphash.h + * @brief APR-UTIL siphash library + * "SipHash-c-d is a family of pseudorandom functions (a.k.a. keyed + * hash functions) optimized for speed on short messages", designed by + * Jean-Philippe Aumasson and Daniel J. Bernstein. It generates a 64bit + * hash (or MAC) from the message and a 128bit key. + * See http://cr.yp.to/siphash/siphash-20120620.pdf for the details, + * c is the number of compression rounds, d the number of finalization + * rounds; we also define fast implementations for c = 2 with d = 4 (aka + * siphash-2-4), and c = 4 with d = 8 (aka siphash-4-8), as recommended + * parameters per the authors. + */ + +/** size of the siphash digest */ +#define APR_SIPHASH_DSIZE 8 + +/** size of the siphash key */ +#define APR_SIPHASH_KSIZE 16 + + +/** + * @brief Computes SipHash-c-d, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key. + * @param src The message + * @param len The length of the message + * @param key The secret key + * @param c The number of compression rounds + * @param d The number of finalization rounds + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(apr_uint64_t) apr_siphash(const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE], + unsigned int c, unsigned int d); + +/** + * @brief Computes SipHash-c-d, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key, into a possibly + * unaligned buffer (using the little endian representation as defined by the + * authors for interoperabilty) usable as a MAC. + * @param out The output buffer (or MAC) + * @param src The message + * @param len The length of the message + * @param key The secret key + * @param c The number of compression rounds + * @param d The number of finalization rounds + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(void) apr_siphash_auth(unsigned char out[APR_SIPHASH_DSIZE], + const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE], + unsigned int c, unsigned int d); + +/** + * @brief Computes SipHash-2-4, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key. + * @param src The message to hash + * @param len The length of the message + * @param key The secret key + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(apr_uint64_t) apr_siphash24(const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE]); + +/** + * @brief Computes SipHash-2-4, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key, into a possibly + * unaligned buffer (using the little endian representation as defined by the + * authors for interoperabilty) usable as a MAC. + * @param out The output buffer (or MAC) + * @param src The message + * @param len The length of the message + * @param key The secret key + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(void) apr_siphash24_auth(unsigned char out[APR_SIPHASH_DSIZE], + const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE]); + +/** + * @brief Computes SipHash-4-8, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key. + * @param src The message + * @param len The length of the message + * @param key The secret key + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(apr_uint64_t) apr_siphash48(const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE]); + +/** + * @brief Computes SipHash-4-8, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key, into a possibly + * unaligned buffer (using the little endian representation as defined by the + * authors for interoperabilty) usable as a MAC. + * @param out The output buffer (or MAC) + * @param src The message + * @param len The length of the message + * @param key The secret key + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(void) apr_siphash48_auth(unsigned char out[APR_SIPHASH_DSIZE], + const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE]); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_SIPHASH_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_skiplist.h b/c/dependencies/windows/apr/x64_debug/include/apr_skiplist.h new file mode 100644 index 00000000..eeab10bf --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_skiplist.h @@ -0,0 +1,381 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_SKIPLIST_H +#define APR_SKIPLIST_H +/** + * @file apr_skiplist.h + * @brief APR skip list implementation + */ + +#include "apr.h" +#include "apr_portable.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_skiplist Skip list implementation + * Refer to http://en.wikipedia.org/wiki/Skip_list for information + * about the purpose of and ideas behind skip lists. + * @ingroup APR + * @{ + */ + +/** + * apr_skiplist_compare is the function type that must be implemented + * per object type that is used in a skip list for comparisons to maintain + * order + * */ +typedef int (*apr_skiplist_compare) (void *, void *); + +/** + * apr_skiplist_freefunc is the function type that must be implemented + * to handle elements as they are removed from a skip list. + */ +typedef void (*apr_skiplist_freefunc) (void *); + +/** Opaque structure used to represent the skip list */ +struct apr_skiplist; +/** Opaque structure used to represent the skip list */ +typedef struct apr_skiplist apr_skiplist; + +/** + * Opaque structure used to represent abstract nodes in the skip list + * (an abstraction above the raw elements which are collected in the + * skip list). + */ +struct apr_skiplistnode; +/** Opaque structure */ +typedef struct apr_skiplistnode apr_skiplistnode; + +/** + * Allocate memory using the same mechanism as the skip list. + * @param sl The skip list + * @param size The amount to allocate + * @remark If a pool was provided to apr_skiplist_init(), memory will + * be allocated from the pool or from a free list maintained with + * the skip list. Otherwise, memory will be allocated using the + * C standard library heap functions. + */ +APR_DECLARE(void *) apr_skiplist_alloc(apr_skiplist *sl, size_t size); + +/** + * Free memory using the same mechanism as the skip list. + * @param sl The skip list + * @param mem The object to free + * @remark If a pool was provided to apr_skiplist_init(), memory will + * be added to a free list maintained with the skip list and be available + * to operations on the skip list or to other calls to apr_skiplist_alloc(). + * Otherwise, memory will be freed using the C standard library heap + * functions. + */ +APR_DECLARE(void) apr_skiplist_free(apr_skiplist *sl, void *mem); + +/** + * Allocate a new skip list + * @param sl The pointer in which to return the newly created skip list + * @param p The pool from which to allocate the skip list (optional). + * @remark Unlike most APR functions, a pool is optional. If no pool + * is provided, the C standard library heap functions will be used instead. + */ +APR_DECLARE(apr_status_t) apr_skiplist_init(apr_skiplist **sl, apr_pool_t *p); + +/** + * Set the comparison functions to be used for searching the skip list. + * @param sl The skip list + * @param XXX1 FIXME + * @param XXX2 FIXME + * + * @remark If existing comparison functions are being replaced, the index + * will be replaced during this call. That is a potentially expensive + * operation. + */ +APR_DECLARE(void) apr_skiplist_set_compare(apr_skiplist *sl, apr_skiplist_compare XXX1, + apr_skiplist_compare XXX2); + +/** + * Set the indexing functions to the specified comparison functions and + * rebuild the index. + * @param sl The skip list + * @param XXX1 FIXME + * @param XXX2 FIXME + * + * @remark If an index already exists, it will not be replaced and the + * comparison functions will not be changed. + */ +APR_DECLARE(void) apr_skiplist_add_index(apr_skiplist *sl, apr_skiplist_compare XXX1, + apr_skiplist_compare XXX2); + +/** + * Return the list maintained by the skip list abstraction. + * @param sl The skip list + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_getlist(apr_skiplist *sl); + +/** + * Return the next matching element in the skip list using the specified + * comparison function. + * @param sl The skip list + * @param data The value to search for + * @param iter A pointer to the returned skip list node representing the element + * found + * @param func The comparison function to use + */ +APR_DECLARE(void *) apr_skiplist_find_compare(apr_skiplist *sl, + void *data, + apr_skiplistnode **iter, + apr_skiplist_compare func); + +/** + * Return the next matching element in the skip list using the current comparison + * function. + * @param sl The skip list + * @param data The value to search for + * @param iter A pointer to the returned skip list node representing the element + * found + */ +APR_DECLARE(void *) apr_skiplist_find(apr_skiplist *sl, void *data, apr_skiplistnode **iter); + +/** + * Return the last matching element in the skip list using the specified + * comparison function. + * @param sl The skip list + * @param data The value to search for + * @param iter A pointer to the returned skip list node representing the element + * found + * @param comp The comparison function to use + */ +APR_DECLARE(void *) apr_skiplist_last_compare(apr_skiplist *sl, void *data, + apr_skiplistnode **iter, + apr_skiplist_compare comp); + +/** + * Return the last matching element in the skip list using the current comparison + * function. + * @param sl The skip list + * @param data The value to search for + * @param iter A pointer to the returned skip list node representing the element + * found + */ +APR_DECLARE(void *) apr_skiplist_last(apr_skiplist *sl, void *data, + apr_skiplistnode **iter); + +/** + * Return the next element in the skip list. + * @param sl The skip list + * @param iter On entry, a pointer to the skip list node to start with; on return, + * a pointer to the skip list node representing the element returned + * @remark If iter points to a NULL value on entry, NULL will be returned. + */ +APR_DECLARE(void *) apr_skiplist_next(apr_skiplist *sl, apr_skiplistnode **iter); + +/** + * Return the previous element in the skip list. + * @param sl The skip list + * @param iter On entry, a pointer to the skip list node to start with; on return, + * a pointer to the skip list node representing the element returned + * @remark If iter points to a NULL value on entry, NULL will be returned. + */ +APR_DECLARE(void *) apr_skiplist_previous(apr_skiplist *sl, apr_skiplistnode **iter); + +/** + * Return the element of the skip list node + * @param iter The skip list node + */ +APR_DECLARE(void *) apr_skiplist_element(apr_skiplistnode *iter); + +/** + * Insert an element into the skip list using the specified comparison function + * if it does not already exist. + * @param sl The skip list + * @param data The element to insert + * @param comp The comparison function to use for placement into the skip list + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_insert_compare(apr_skiplist *sl, + void *data, apr_skiplist_compare comp); + +/** + * Insert an element into the skip list using the existing comparison function + * if it does not already exist. + * @param sl The skip list + * @param data The element to insert + * @remark If no comparison function has been set for the skip list, the element + * will not be inserted and NULL will be returned. + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_insert(apr_skiplist* sl, void *data); + +/** + * Add an element into the skip list using the specified comparison function + * allowing for duplicates. + * @param sl The skip list + * @param data The element to add + * @param comp The comparison function to use for placement into the skip list + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_add_compare(apr_skiplist *sl, + void *data, apr_skiplist_compare comp); + +/** + * Add an element into the skip list using the existing comparison function + * allowing for duplicates. + * @param sl The skip list + * @param data The element to insert + * @remark If no comparison function has been set for the skip list, the element + * will not be inserted and NULL will be returned. + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_add(apr_skiplist* sl, void *data); + +/** + * Add an element into the skip list using the specified comparison function + * removing the existing duplicates. + * @param sl The skip list + * @param data The element to insert + * @param comp The comparison function to use for placement into the skip list + * @param myfree A function to be called for each removed duplicate + * @remark If no comparison function has been set for the skip list, the element + * will not be inserted, none will be replaced, and NULL will be returned. + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_replace_compare(apr_skiplist *sl, + void *data, apr_skiplist_freefunc myfree, + apr_skiplist_compare comp); + +/** + * Add an element into the skip list using the existing comparison function + * removing the existing duplicates. + * @param sl The skip list + * @param data The element to insert + * @param myfree A function to be called for each removed duplicate + * @remark If no comparison function has been set for the skip list, the element + * will not be inserted, none will be replaced, and NULL will be returned. + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_replace(apr_skiplist *sl, + void *data, apr_skiplist_freefunc myfree); + +/** + * Remove a node from the skip list. + * @param sl The skip list + * @param iter The skip list node to remove + * @param myfree A function to be called for the removed element + */ +APR_DECLARE(int) apr_skiplist_remove_node(apr_skiplist *sl, + apr_skiplistnode *iter, + apr_skiplist_freefunc myfree); + +/** + * Remove an element from the skip list using the specified comparison function for + * locating the element. In the case of duplicates, the 1st entry will be removed. + * @param sl The skip list + * @param data The element to remove + * @param myfree A function to be called for each removed element + * @param comp The comparison function to use for placement into the skip list + * @remark If the element is not found, 0 will be returned. Otherwise, the heightXXX + * will be returned. + */ +APR_DECLARE(int) apr_skiplist_remove_compare(apr_skiplist *sl, void *data, + apr_skiplist_freefunc myfree, apr_skiplist_compare comp); + +/** + * Remove an element from the skip list using the existing comparison function for + * locating the element. In the case of duplicates, the 1st entry will be removed. + * @param sl The skip list + * @param data The element to remove + * @param myfree A function to be called for each removed element + * @remark If the element is not found, 0 will be returned. Otherwise, the heightXXX + * will be returned. + * @remark If no comparison function has been set for the skip list, the element + * will not be removed and 0 will be returned. + */ +APR_DECLARE(int) apr_skiplist_remove(apr_skiplist *sl, void *data, apr_skiplist_freefunc myfree); + +/** + * Remove all elements from the skip list. + * @param sl The skip list + * @param myfree A function to be called for each removed element + */ +APR_DECLARE(void) apr_skiplist_remove_all(apr_skiplist *sl, apr_skiplist_freefunc myfree); + +/** + * Remove each element from the skip list. + * @param sl The skip list + * @param myfree A function to be called for each removed element + */ +APR_DECLARE(void) apr_skiplist_destroy(apr_skiplist *sl, apr_skiplist_freefunc myfree); + +/** + * Return the first element in the skip list, removing the element from the skip list. + * @param sl The skip list + * @param myfree A function to be called for the removed element + * @remark NULL will be returned if there are no elements + */ +APR_DECLARE(void *) apr_skiplist_pop(apr_skiplist *sl, apr_skiplist_freefunc myfree); + +/** + * Return the first element in the skip list, leaving the element in the skip list. + * @param sl The skip list + * @remark NULL will be returned if there are no elements + */ +APR_DECLARE(void *) apr_skiplist_peek(apr_skiplist *sl); + +/** + * Return the size of the list (number of elements), in O(1). + * @param sl The skip list + */ +APR_DECLARE(size_t) apr_skiplist_size(const apr_skiplist *sl); + +/** + * Return the height of the list (number of skip paths), in O(1). + * @param sl The skip list + */ +APR_DECLARE(int) apr_skiplist_height(const apr_skiplist *sl); + +/** + * Return the predefined maximum height of the skip list. + * @param sl The skip list + */ +APR_DECLARE(int) apr_skiplist_preheight(const apr_skiplist *sl); + +/** + * Set a predefined maximum height for the skip list. + * @param sl The skip list + * @param to The preheight to set, or a nul/negative value to disable. + * @remark When a preheight is used, the height of each inserted element is + * computed randomly up to this preheight instead of the current skip list's + * height plus one used by the default implementation. Using a preheight can + * probably ensure more fairness with long living elements (since with an + * adaptative height, former elements may have been created with a low height, + * hence a longest path to reach them while the skip list grows). On the other + * hand, the default behaviour (preheight <= 0) with a growing and decreasing + * maximum height is more adaptative/suitable for short living values. + * @note Should be called before any insertion/add. + */ +APR_DECLARE(void) apr_skiplist_set_preheight(apr_skiplist *sl, int to); + +/** + * Merge two skip lists. XXX SEMANTICS + * @param sl1 One of two skip lists to be merged + * @param sl2 The other of two skip lists to be merged + */ +APR_DECLARE(apr_skiplist *) apr_skiplist_merge(apr_skiplist *sl1, apr_skiplist *sl2); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_SKIPLIST_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_strings.h b/c/dependencies/windows/apr/x64_debug/include/apr_strings.h new file mode 100644 index 00000000..d5f8719d --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_strings.h @@ -0,0 +1,380 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* Portions of this file are covered by */ +/* -*- mode: c; c-file-style: "k&r" -*- + + strnatcmp.c -- Perform 'natural order' comparisons of strings in C. + Copyright (C) 2000 by Martin Pool + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef APR_STRINGS_H +#define APR_STRINGS_H + +/** + * @file apr_strings.h + * @brief APR Strings library + */ + +#include "apr.h" +#include "apr_errno.h" +#include "apr_pools.h" +#define APR_WANT_IOVEC +#include "apr_want.h" + +#if APR_HAVE_STDARG_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_strings String routines + * @ingroup APR + * @{ + */ + +/** + * Do a natural order comparison of two strings. + * @param a The first string to compare + * @param b The second string to compare + * @return Either <0, 0, or >0. If the first string is less than the second + * this returns <0, if they are equivalent it returns 0, and if the + * first string is greater than second string it retuns >0. + */ +APR_DECLARE(int) apr_strnatcmp(char const *a, char const *b); + +/** + * Do a natural order comparison of two strings ignoring the case of the + * strings. + * @param a The first string to compare + * @param b The second string to compare + * @return Either <0, 0, or >0. If the first string is less than the second + * this returns <0, if they are equivalent it returns 0, and if the + * first string is greater than second string it retuns >0. + */ +APR_DECLARE(int) apr_strnatcasecmp(char const *a, char const *b); + +/** + * duplicate a string into memory allocated out of a pool + * @param p The pool to allocate out of + * @param s The string to duplicate + * @return The new string or NULL if s == NULL + */ +APR_DECLARE(char *) apr_pstrdup(apr_pool_t *p, const char *s); + +/** + * Create a null-terminated string by making a copy of a sequence + * of characters and appending a null byte + * @param p The pool to allocate out of + * @param s The block of characters to duplicate + * @param n The number of characters to duplicate + * @return The new string or NULL if s == NULL + * @remark This is a faster alternative to apr_pstrndup(), for use + * when you know that the string being duplicated really + * has 'n' or more characters. If the string might contain + * fewer characters, use apr_pstrndup(). + */ +APR_DECLARE(char *) apr_pstrmemdup(apr_pool_t *p, const char *s, apr_size_t n) +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) + __attribute__((alloc_size(3))) +#endif + ; + +/** + * Duplicate at most n characters of a string into memory allocated + * out of a pool; the new string will be NUL-terminated + * @param p The pool to allocate out of + * @param s The string to duplicate + * @param n The maximum number of characters to duplicate + * @return The new string or NULL if s == NULL + * @remark The amount of memory allocated from the pool is the length + * of the returned string including the NUL terminator + */ +APR_DECLARE(char *) apr_pstrndup(apr_pool_t *p, const char *s, apr_size_t n); + +/** + * Duplicate a block of memory. + * + * @param p The pool to allocate from + * @param m The memory to duplicate + * @param n The number of bytes to duplicate + * @return The new block of memory or NULL if m == NULL + */ +APR_DECLARE(void *) apr_pmemdup(apr_pool_t *p, const void *m, apr_size_t n) +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) + __attribute__((alloc_size(3))) +#endif + ; + +/** + * Concatenate multiple strings, allocating memory out a pool + * @param p The pool to allocate out of + * @param ... The strings to concatenate. The final string must be NULL + * @return The new string + */ +APR_DECLARE_NONSTD(char *) apr_pstrcat(apr_pool_t *p, ...) +#if defined(__GNUC__) && __GNUC__ >= 4 + __attribute__((sentinel)) +#endif + ; + +/** + * Concatenate multiple strings specified in a writev-style vector + * @param p The pool from which to allocate + * @param vec The strings to concatenate + * @param nvec The number of strings to concatenate + * @param nbytes (output) strlen of new string (pass in NULL to omit) + * @return The new string + */ +APR_DECLARE(char *) apr_pstrcatv(apr_pool_t *p, const struct iovec *vec, + apr_size_t nvec, apr_size_t *nbytes); + +/** + * printf-style style printing routine. The data is output to a string + * allocated from a pool + * @param p The pool to allocate out of + * @param fmt The format of the string + * @param ap The arguments to use while printing the data + * @return The new string + */ +APR_DECLARE(char *) apr_pvsprintf(apr_pool_t *p, const char *fmt, va_list ap); + +/** + * printf-style style printing routine. The data is output to a string + * allocated from a pool + * @param p The pool to allocate out of + * @param fmt The format of the string + * @param ... The arguments to use while printing the data + * @return The new string + */ +APR_DECLARE_NONSTD(char *) apr_psprintf(apr_pool_t *p, const char *fmt, ...) + __attribute__((format(printf,2,3))); + +/** + * Copy up to dst_size characters from src to dst; does not copy + * past a NUL terminator in src, but always terminates dst with a NUL + * regardless. + * @param dst The destination string + * @param src The source string + * @param dst_size The space available in dst; dst always receives + * NUL termination, so if src is longer than + * dst_size, the actual number of characters copied is + * dst_size - 1. + * @return Pointer to the NUL terminator of the destination string, dst + * @remark + *
+ * Note the differences between this function and strncpy():
+ *  1) strncpy() doesn't always NUL terminate; apr_cpystrn() does.
+ *  2) strncpy() pads the destination string with NULs, which is often 
+ *     unnecessary; apr_cpystrn() does not.
+ *  3) strncpy() returns a pointer to the beginning of the dst string;
+ *     apr_cpystrn() returns a pointer to the NUL terminator of dst, 
+ *     to allow a check for truncation.
+ * 
+ */ +APR_DECLARE(char *) apr_cpystrn(char *dst, const char *src, + apr_size_t dst_size); + +/** + * Remove all whitespace from a string + * @param dest The destination string. It is okay to modify the string + * in place. Namely dest == src + * @param src The string to rid the spaces from. + * @return A pointer to the destination string's null terminator. + */ +APR_DECLARE(char *) apr_collapse_spaces(char *dest, const char *src); + +/** + * Convert the arguments to a program from one string to an array of + * strings terminated by a NULL pointer + * @param arg_str The arguments to convert + * @param argv_out Output location. This is a pointer to an array of strings. + * @param token_context Pool to use. + */ +APR_DECLARE(apr_status_t) apr_tokenize_to_argv(const char *arg_str, + char ***argv_out, + apr_pool_t *token_context); + +/** + * Split a string into separate null-terminated tokens. The tokens are + * delimited in the string by one or more characters from the sep + * argument. + * @param str The string to separate; this should be specified on the + * first call to apr_strtok() for a given string, and NULL + * on subsequent calls. + * @param sep The set of delimiters + * @param last State saved by apr_strtok() between calls. + * @return The next token from the string + * @note the 'last' state points to the trailing NUL char of the final + * token, otherwise it points to the character following the current + * token (all successive or empty occurances of sep are skiped on the + * subsequent call to apr_strtok). Therefore it is possible to avoid + * a strlen() determination, with the following logic; + * toklen = last - retval; if (*last) --toklen; + */ +APR_DECLARE(char *) apr_strtok(char *str, const char *sep, char **last); + +/** + * @defgroup APR_Strings_Snprintf snprintf implementations + * @warning + * These are snprintf implementations based on apr_vformatter(). + * + * Note that various standards and implementations disagree on the return + * value of snprintf, and side-effects due to %n in the formatting string. + * apr_snprintf (and apr_vsnprintf) behaves as follows: + * + * Process the format string until the entire string is exhausted, or + * the buffer fills. If the buffer fills then stop processing immediately + * (so no further %n arguments are processed), and return the buffer + * length. In all cases the buffer is NUL terminated. It will return the + * number of characters inserted into the buffer, not including the + * terminating NUL. As a special case, if len is 0, apr_snprintf will + * return the number of characters that would have been inserted if + * the buffer had been infinite (in this case, *buffer can be NULL) + * + * In no event does apr_snprintf return a negative number. + * @{ + */ + +/** + * snprintf routine based on apr_vformatter. This means it understands the + * same extensions. + * @param buf The buffer to write to + * @param len The size of the buffer + * @param format The format string + * @param ... The arguments to use to fill out the format string. + */ +APR_DECLARE_NONSTD(int) apr_snprintf(char *buf, apr_size_t len, + const char *format, ...) + __attribute__((format(printf,3,4))); + +/** + * vsnprintf routine based on apr_vformatter. This means it understands the + * same extensions. + * @param buf The buffer to write to + * @param len The size of the buffer + * @param format The format string + * @param ap The arguments to use to fill out the format string. + */ +APR_DECLARE(int) apr_vsnprintf(char *buf, apr_size_t len, const char *format, + va_list ap); +/** @} */ + +/** + * create a string representation of an int, allocated from a pool + * @param p The pool from which to allocate + * @param n The number to format + * @return The string representation of the number + */ +APR_DECLARE(char *) apr_itoa(apr_pool_t *p, int n); + +/** + * create a string representation of a long, allocated from a pool + * @param p The pool from which to allocate + * @param n The number to format + * @return The string representation of the number + */ +APR_DECLARE(char *) apr_ltoa(apr_pool_t *p, long n); + +/** + * create a string representation of an apr_off_t, allocated from a pool + * @param p The pool from which to allocate + * @param n The number to format + * @return The string representation of the number + */ +APR_DECLARE(char *) apr_off_t_toa(apr_pool_t *p, apr_off_t n); + +/** + * Convert a numeric string into an apr_off_t numeric value. + * @param offset The value of the parsed string. + * @param buf The string to parse. It may contain optional whitespace, + * followed by an optional '+' (positive, default) or '-' (negative) + * character, followed by an optional '0x' prefix if base is 0 or 16, + * followed by numeric digits appropriate for base. + * @param end A pointer to the end of the valid character in buf. If + * not NULL, it is set to the first invalid character in buf. + * @param base A numeric base in the range between 2 and 36 inclusive, + * or 0. If base is zero, buf will be treated as base ten unless its + * digits are prefixed with '0x', in which case it will be treated as + * base 16. + * @bug *end breaks type safety; where *buf is const, *end needs to be + * declared as const in APR 2.0 + */ +APR_DECLARE(apr_status_t) apr_strtoff(apr_off_t *offset, const char *buf, + char **end, int base); + +/** + * parse a numeric string into a 64-bit numeric value + * @param buf The string to parse. It may contain optional whitespace, + * followed by an optional '+' (positive, default) or '-' (negative) + * character, followed by an optional '0x' prefix if base is 0 or 16, + * followed by numeric digits appropriate for base. + * @param end A pointer to the end of the valid character in buf. If + * not NULL, it is set to the first invalid character in buf. + * @param base A numeric base in the range between 2 and 36 inclusive, + * or 0. If base is zero, buf will be treated as base ten unless its + * digits are prefixed with '0x', in which case it will be treated as + * base 16. + * @return The numeric value of the string. On overflow, errno is set + * to ERANGE. On success, errno is set to 0. + */ +APR_DECLARE(apr_int64_t) apr_strtoi64(const char *buf, char **end, int base); + +/** + * parse a base-10 numeric string into a 64-bit numeric value. + * Equivalent to apr_strtoi64(buf, (char**)NULL, 10). + * @param buf The string to parse + * @return The numeric value of the string. On overflow, errno is set + * to ERANGE. On success, errno is set to 0. + */ +APR_DECLARE(apr_int64_t) apr_atoi64(const char *buf); + +/** + * Format a binary size (magnitiudes are 2^10 rather than 10^3) from an apr_off_t, + * as bytes, K, M, T, etc, to a four character compacted human readable string. + * @param size The size to format + * @param buf The 5 byte text buffer (counting the trailing null) + * @return The buf passed to apr_strfsize() + * @remark All negative sizes report ' - ', apr_strfsize only formats positive values. + */ +APR_DECLARE(char *) apr_strfsize(apr_off_t size, char *buf); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_STRINGS_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_strmatch.h b/c/dependencies/windows/apr/x64_debug/include/apr_strmatch.h new file mode 100644 index 00000000..53fadad5 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_strmatch.h @@ -0,0 +1,81 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_STRMATCH_H +#define APR_STRMATCH_H +/** + * @file apr_strmatch.h + * @brief APR-UTIL string matching routines + */ + +#include "apu.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_StrMatch String matching routines + * @ingroup APR_Util + * @{ + */ + +/** @see apr_strmatch_pattern */ +typedef struct apr_strmatch_pattern apr_strmatch_pattern; + +/** + * Precompiled search pattern + */ +struct apr_strmatch_pattern { + /** Function called to compare */ + const char *(*compare)(const apr_strmatch_pattern *this_pattern, + const char *s, apr_size_t slen); + const char *pattern; /**< Current pattern */ + apr_size_t length; /**< Current length */ + void *context; /**< hook to add precomputed metadata */ +}; + +#if defined(DOXYGEN) +/** + * Search for a precompiled pattern within a string + * @param pattern The pattern + * @param s The string in which to search for the pattern + * @param slen The length of s (excluding null terminator) + * @return A pointer to the first instance of the pattern in s, or + * NULL if not found + */ +APU_DECLARE(const char *) apr_strmatch(const apr_strmatch_pattern *pattern, + const char *s, apr_size_t slen); +#else +#define apr_strmatch(pattern, s, slen) (*((pattern)->compare))((pattern), (s), (slen)) +#endif + +/** + * Precompile a pattern for matching using the Boyer-Moore-Horspool algorithm + * @param p The pool from which to allocate the pattern + * @param s The pattern string + * @param case_sensitive Whether the matching should be case-sensitive + * @return a pointer to the compiled pattern, or NULL if compilation fails + */ +APU_DECLARE(const apr_strmatch_pattern *) apr_strmatch_precompile(apr_pool_t *p, const char *s, int case_sensitive); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_STRMATCH_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_support.h b/c/dependencies/windows/apr/x64_debug/include/apr_support.h new file mode 100644 index 00000000..79c8cb47 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_support.h @@ -0,0 +1,57 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_SUPPORT_H +#define APR_SUPPORT_H + +/** + * @file apr_support.h + * @brief APR Support functions + */ + +#include "apr.h" +#include "apr_network_io.h" +#include "apr_file_io.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_support Internal APR support functions + * @ingroup APR + * @{ + */ + +/** + * Wait for IO to occur or timeout. + * + * @param f The file to wait on. + * @param s The socket to wait on if @a f is @c NULL. + * @param for_read If non-zero wait for data to be available to read, + * otherwise wait for data to be able to be written. + * @return APR_TIMEUP if we run out of time. + */ +apr_status_t apr_wait_for_io_or_timeout(apr_file_t *f, apr_socket_t *s, + int for_read); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_SUPPORT_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_tables.h b/c/dependencies/windows/apr/x64_debug/include/apr_tables.h new file mode 100644 index 00000000..27974c0e --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_tables.h @@ -0,0 +1,507 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_TABLES_H +#define APR_TABLES_H + +/** + * @file apr_tables.h + * @brief APR Table library + */ + +#include "apr.h" +#include "apr_pools.h" + +#if APR_HAVE_STDARG_H +#include /* for va_list */ +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_tables Table and Array Functions + * @ingroup APR + * Arrays are used to store data which is referenced sequentially or + * as a stack. Functions are provided to push and pop individual + * elements as well as to operate on the entire array. + * + * Tables are used to store data which can be referenced by key. + * Limited capabilities are provided for tables with multiple elements + * which share a key; while key lookup will return only a single + * element, iteration is available. Additionally, a table can be + * compressed to resolve duplicates. + * + * Both arrays and tables may store string or binary data; some features, + * such as concatenation or merging of elements, work only for string + * data. + * @{ + */ + +/** the table abstract data type */ +typedef struct apr_table_t apr_table_t; + +/** @see apr_array_header_t */ +typedef struct apr_array_header_t apr_array_header_t; + +/** An opaque array type */ +struct apr_array_header_t { + /** The pool the array is allocated out of */ + apr_pool_t *pool; + /** The amount of memory allocated for each element of the array */ + int elt_size; + /** The number of active elements in the array */ + int nelts; + /** The number of elements allocated in the array */ + int nalloc; + /** The elements in the array */ + char *elts; +}; + +/** + * The (opaque) structure for string-content tables. + */ +typedef struct apr_table_entry_t apr_table_entry_t; + +/** The type for each entry in a string-content table */ +struct apr_table_entry_t { + /** The key for the current table entry */ + char *key; /* maybe NULL in future; + * check when iterating thru table_elts + */ + /** The value for the current table entry */ + char *val; + + /** A checksum for the key, for use by the apr_table internals */ + apr_uint32_t key_checksum; +}; + +/** + * Get the elements from a table. + * @param t The table + * @return An array containing the contents of the table + */ +APR_DECLARE(const apr_array_header_t *) apr_table_elts(const apr_table_t *t); + +/** + * Determine if the table is empty (either NULL or having no elements). + * @param t The table to check + * @return True if empty, False otherwise + */ +APR_DECLARE(int) apr_is_empty_table(const apr_table_t *t); + +/** + * Determine if the array is empty (either NULL or having no elements). + * @param a The array to check + * @return True if empty, False otherwise + */ +APR_DECLARE(int) apr_is_empty_array(const apr_array_header_t *a); + +/** + * Create an array. + * @param p The pool to allocate the memory out of + * @param nelts the number of elements in the initial array + * @param elt_size The size of each element in the array. + * @return The new array + */ +APR_DECLARE(apr_array_header_t *) apr_array_make(apr_pool_t *p, + int nelts, int elt_size); + +/** + * Add a new element to an array (as a first-in, last-out stack). + * @param arr The array to add an element to. + * @return Location for the new element in the array. + * @remark If there are no free spots in the array, then this function will + * allocate new space for the new element. + */ +APR_DECLARE(void *) apr_array_push(apr_array_header_t *arr); + +/** A helper macro for accessing a member of an APR array. + * + * @param ary the array + * @param i the index into the array to return + * @param type the type of the objects stored in the array + * + * @return the item at index i + */ +#define APR_ARRAY_IDX(ary,i,type) (((type *)(ary)->elts)[i]) + +/** A helper macro for pushing elements into an APR array. + * + * @param ary the array + * @param type the type of the objects stored in the array + * + * @return the location where the new object should be placed + */ +#define APR_ARRAY_PUSH(ary,type) (*((type *)apr_array_push(ary))) + +/** + * Remove an element from an array (as a first-in, last-out stack). + * @param arr The array to remove an element from. + * @return Location of the element in the array. + * @remark If there are no elements in the array, NULL is returned. + */ +APR_DECLARE(void *) apr_array_pop(apr_array_header_t *arr); + +/** + * Remove all elements from an array. + * @param arr The array to remove all elements from. + * @remark As the underlying storage is allocated from a pool, no + * memory is freed by this operation, but is available for reuse. + */ +APR_DECLARE(void) apr_array_clear(apr_array_header_t *arr); + +/** + * Concatenate two arrays together. + * @param dst The destination array, and the one to go first in the combined + * array + * @param src The source array to add to the destination array + */ +APR_DECLARE(void) apr_array_cat(apr_array_header_t *dst, + const apr_array_header_t *src); + +/** + * Copy the entire array. + * @param p The pool to allocate the copy of the array out of + * @param arr The array to copy + * @return An exact copy of the array passed in + * @remark The alternate apr_array_copy_hdr() copies only the header, and arranges + * for the elements to be copied if (and only if) the code subsequently + * does a push or arraycat. + */ +APR_DECLARE(apr_array_header_t *) apr_array_copy(apr_pool_t *p, + const apr_array_header_t *arr); +/** + * Copy the headers of the array, and arrange for the elements to be copied if + * and only if the code subsequently does a push or arraycat. + * @param p The pool to allocate the copy of the array out of + * @param arr The array to copy + * @return An exact copy of the array passed in + * @remark The alternate apr_array_copy() copies the *entire* array. + */ +APR_DECLARE(apr_array_header_t *) apr_array_copy_hdr(apr_pool_t *p, + const apr_array_header_t *arr); + +/** + * Append one array to the end of another, creating a new array in the process. + * @param p The pool to allocate the new array out of + * @param first The array to put first in the new array. + * @param second The array to put second in the new array. + * @return A new array containing the data from the two arrays passed in. +*/ +APR_DECLARE(apr_array_header_t *) apr_array_append(apr_pool_t *p, + const apr_array_header_t *first, + const apr_array_header_t *second); + +/** + * Generate a new string from the apr_pool_t containing the concatenated + * sequence of substrings referenced as elements within the array. The string + * will be empty if all substrings are empty or null, or if there are no + * elements in the array. If sep is non-NUL, it will be inserted between + * elements as a separator. + * @param p The pool to allocate the string out of + * @param arr The array to generate the string from + * @param sep The separator to use + * @return A string containing all of the data in the array. + */ +APR_DECLARE(char *) apr_array_pstrcat(apr_pool_t *p, + const apr_array_header_t *arr, + const char sep); + +/** + * Make a new table. + * @param p The pool to allocate the pool out of + * @param nelts The number of elements in the initial table. + * @return The new table. + * @warning This table can only store text data + */ +APR_DECLARE(apr_table_t *) apr_table_make(apr_pool_t *p, int nelts); + +/** + * Create a new table and copy another table into it. + * @param p The pool to allocate the new table out of + * @param t The table to copy + * @return A copy of the table passed in + * @warning The table keys and respective values are not copied + */ +APR_DECLARE(apr_table_t *) apr_table_copy(apr_pool_t *p, + const apr_table_t *t); + +/** + * Create a new table whose contents are deep copied from the given + * table. A deep copy operation copies all fields, and makes copies + * of dynamically allocated memory pointed to by the fields. + * @param p The pool to allocate the new table out of + * @param t The table to clone + * @return A deep copy of the table passed in + */ +APR_DECLARE(apr_table_t *) apr_table_clone(apr_pool_t *p, + const apr_table_t *t); + +/** + * Delete all of the elements from a table. + * @param t The table to clear + */ +APR_DECLARE(void) apr_table_clear(apr_table_t *t); + +/** + * Get the value associated with a given key from the table. After this call, + * the data is still in the table. + * @param t The table to search for the key + * @param key The key to search for (case does not matter) + * @return The value associated with the key, or NULL if the key does not exist. + */ +APR_DECLARE(const char *) apr_table_get(const apr_table_t *t, const char *key); + +/** + * Get values associated with a given key from the table. If more than one + * value exists, return a comma separated list of values. After this call, the + * data is still in the table. + * @param p The pool to allocate the combined value from, if necessary + * @param t The table to search for the key + * @param key The key to search for (case does not matter) + * @return The value associated with the key, or NULL if the key does not exist. + */ +APR_DECLARE(const char *) apr_table_getm(apr_pool_t *p, const apr_table_t *t, + const char *key); + +/** + * Add a key/value pair to a table. If another element already exists with the + * same key, this will overwrite the old data. + * @param t The table to add the data to. + * @param key The key to use (case does not matter) + * @param val The value to add + * @remark When adding data, this function makes a copy of both the key and the + * value. + */ +APR_DECLARE(void) apr_table_set(apr_table_t *t, const char *key, + const char *val); + +/** + * Add a key/value pair to a table. If another element already exists with the + * same key, this will overwrite the old data. + * @param t The table to add the data to. + * @param key The key to use (case does not matter) + * @param val The value to add + * @warning When adding data, this function does not make a copy of the key or + * the value, so care should be taken to ensure that the values will + * not change after they have been added.. + */ +APR_DECLARE(void) apr_table_setn(apr_table_t *t, const char *key, + const char *val); + +/** + * Remove data from the table. + * @param t The table to remove data from + * @param key The key of the data being removed (case does not matter) + */ +APR_DECLARE(void) apr_table_unset(apr_table_t *t, const char *key); + +/** + * Add data to a table by merging the value with data that has already been + * stored. The merging is done by concatenating the two values, separated + * by the string ", ". + * @param t The table to search for the data + * @param key The key to merge data for (case does not matter) + * @param val The data to add + * @remark If the key is not found, then this function acts like apr_table_add() + */ +APR_DECLARE(void) apr_table_merge(apr_table_t *t, const char *key, + const char *val); + +/** + * Add data to a table by merging the value with data that has already been + * stored. The merging is done by concatenating the two values, separated + * by the string ", ". + * @param t The table to search for the data + * @param key The key to merge data for (case does not matter) + * @param val The data to add + * @remark If the key is not found, then this function acts like apr_table_addn() + */ +APR_DECLARE(void) apr_table_mergen(apr_table_t *t, const char *key, + const char *val); + +/** + * Add data to a table, regardless of whether there is another element with the + * same key. + * @param t The table to add to + * @param key The key to use + * @param val The value to add. + * @remark When adding data, this function makes a copy of both the key and the + * value. + */ +APR_DECLARE(void) apr_table_add(apr_table_t *t, const char *key, + const char *val); + +/** + * Add data to a table, regardless of whether there is another element with the + * same key. + * @param t The table to add to + * @param key The key to use + * @param val The value to add. + * @remark When adding data, this function does not make a copy of the key or the + * value, so care should be taken to ensure that the values will not + * change after they have been added. + */ +APR_DECLARE(void) apr_table_addn(apr_table_t *t, const char *key, + const char *val); + +/** + * Merge two tables into one new table. + * @param p The pool to use for the new table + * @param overlay The first table to put in the new table + * @param base The table to add at the end of the new table + * @return A new table containing all of the data from the two passed in + */ +APR_DECLARE(apr_table_t *) apr_table_overlay(apr_pool_t *p, + const apr_table_t *overlay, + const apr_table_t *base); + +/** + * Declaration prototype for the iterator callback function of apr_table_do() + * and apr_table_vdo(). + * @param rec The data passed as the first argument to apr_table_[v]do() + * @param key The key from this iteration of the table + * @param value The value from this iteration of the table + * @remark Iteration continues while this callback function returns non-zero. + * To export the callback function for apr_table_[v]do() it must be declared + * in the _NONSTD convention. + * @see apr_table_do @see apr_table_vdo + */ +typedef int (apr_table_do_callback_fn_t)(void *rec, const char *key, + const char *value); + +/** + * Iterate over a table running the provided function once for every + * element in the table. The varargs array must be a list of zero or + * more (char *) keys followed by a NULL pointer. If zero keys are + * given, the @param comp function will be invoked for every element + * in the table. Otherwise, the function is invoked only for those + * elements matching the keys specified. + * + * If an invocation of the comp function returns zero, + * iteration will continue using the next specified key, if any. + * + * @param comp The function to run + * @param rec The data to pass as the first argument to the function + * @param t The table to iterate over + * @param ... A varargs array of zero or more (char *) keys followed by NULL + * @return FALSE if one of the comp() iterations returned zero; TRUE if all + * iterations returned non-zero + * @see apr_table_do_callback_fn_t @see apr_table_vdo + */ +APR_DECLARE_NONSTD(int) apr_table_do(apr_table_do_callback_fn_t *comp, + void *rec, const apr_table_t *t, ...) +#if defined(__GNUC__) && __GNUC__ >= 4 + __attribute__((sentinel)) +#endif + ; + +/** + * Iterate over a table running the provided function once for every + * element in the table. The vp varargs parameter must be a + * list of zero or more (char *) keys followed by a NULL pointer. If + * zero keys are given, the @param comp function will be invoked for + * every element in the table. Otherwise, the function is invoked + * only for those elements matching the keys specified. + * + * If an invocation of the comp function returns zero, + * iteration will continue using the next specified key, if any. + * + * @param comp The function to run + * @param rec The data to pass as the first argument to the function + * @param t The table to iterate over + * @param vp List of zero or more (char *) keys followed by NULL + * @return FALSE if one of the comp() iterations returned zero; TRUE if all + * iterations returned non-zero + * @see apr_table_do_callback_fn_t @see apr_table_do + */ +APR_DECLARE(int) apr_table_vdo(apr_table_do_callback_fn_t *comp, + void *rec, const apr_table_t *t, va_list vp); + +/** flag for overlap to use apr_table_setn */ +#define APR_OVERLAP_TABLES_SET (0) +/** flag for overlap to use apr_table_mergen */ +#define APR_OVERLAP_TABLES_MERGE (1) +/** flag for overlap to use apr_table_addn */ +#define APR_OVERLAP_TABLES_ADD (2) +/** + * For each element in table b, either use setn or mergen to add the data + * to table a. Which method is used is determined by the flags passed in. + * @param a The table to add the data to. + * @param b The table to iterate over, adding its data to table a + * @param flags How to add the table to table a. One of: + * APR_OVERLAP_TABLES_SET Use apr_table_setn + * APR_OVERLAP_TABLES_MERGE Use apr_table_mergen + * APR_OVERLAP_TABLES_ADD Use apr_table_addn + * @remark When merging duplicates, the two values are concatenated, + * separated by the string ", ". + * @remark This function is highly optimized, and uses less memory and CPU cycles + * than a function that just loops through table b calling other functions. + */ +/** + * Conceptually, apr_table_overlap does this: + * + *
+ *  apr_array_header_t *barr = apr_table_elts(b);
+ *  apr_table_entry_t *belt = (apr_table_entry_t *)barr->elts;
+ *  int i;
+ *
+ *  for (i = 0; i < barr->nelts; ++i) {
+ *      if (flags & APR_OVERLAP_TABLES_MERGE) {
+ *          apr_table_mergen(a, belt[i].key, belt[i].val);
+ *      }
+ *      else if (flags & APR_OVERLAP_TABLES_ADD) {
+ *          apr_table_addn(a, belt[i].key, belt[i].val);
+ *      }
+ *      else {
+ *          apr_table_setn(a, belt[i].key, belt[i].val);
+ *      }
+ *  }
+ * 
+ * + * Except that it is more efficient (less space and cpu-time) especially + * when b has many elements. + * + * Notice the assumptions on the keys and values in b -- they must be + * in an ancestor of a's pool. In practice b and a are usually from + * the same pool. + */ + +APR_DECLARE(void) apr_table_overlap(apr_table_t *a, const apr_table_t *b, + unsigned flags); + +/** + * Eliminate redundant entries in a table by either overwriting + * or merging duplicates. + * + * @param t Table. + * @param flags APR_OVERLAP_TABLES_MERGE to merge, or + * APR_OVERLAP_TABLES_SET to overwrite, or + * APR_OVERLAP_TABLES_ADD to add + * @remark When merging duplicates, the two values are concatenated, + * separated by the string ", ". + */ +APR_DECLARE(void) apr_table_compress(apr_table_t *t, unsigned flags); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_TABLES_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_thread_cond.h b/c/dependencies/windows/apr/x64_debug/include/apr_thread_cond.h new file mode 100644 index 00000000..199f1ded --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_thread_cond.h @@ -0,0 +1,139 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_THREAD_COND_H +#define APR_THREAD_COND_H + +/** + * @file apr_thread_cond.h + * @brief APR Condition Variable Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_time.h" +#include "apr_thread_mutex.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#if APR_HAS_THREADS || defined(DOXYGEN) + +/** + * @defgroup apr_thread_cond Condition Variable Routines + * @ingroup APR + * @{ + */ + +/** Opaque structure for thread condition variables */ +typedef struct apr_thread_cond_t apr_thread_cond_t; + +/** + * Note: destroying a condition variable (or likewise, destroying or + * clearing the pool from which a condition variable was allocated) if + * any threads are blocked waiting on it gives undefined results. + */ + +/** + * Create and initialize a condition variable that can be used to signal + * and schedule threads in a single process. + * @param cond the memory address where the newly created condition variable + * will be stored. + * @param pool the pool from which to allocate the condition. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_create(apr_thread_cond_t **cond, + apr_pool_t *pool); + +/** + * Put the active calling thread to sleep until signaled to wake up. Each + * condition variable must be associated with a mutex, and that mutex must + * be locked before calling this function, or the behavior will be + * undefined. As the calling thread is put to sleep, the given mutex + * will be simultaneously released; and as this thread wakes up the lock + * is again simultaneously acquired. + * @param cond the condition variable on which to block. + * @param mutex the mutex that must be locked upon entering this function, + * is released while the thread is asleep, and is again acquired before + * returning from this function. + * @remark Spurious wakeups may occur. Before and after every call to wait on + * a condition variable, the caller should test whether the condition is already + * met. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_wait(apr_thread_cond_t *cond, + apr_thread_mutex_t *mutex); + +/** + * Put the active calling thread to sleep until signaled to wake up or + * the timeout is reached. Each condition variable must be associated + * with a mutex, and that mutex must be locked before calling this + * function, or the behavior will be undefined. As the calling thread + * is put to sleep, the given mutex will be simultaneously released; + * and as this thread wakes up the lock is again simultaneously acquired. + * @param cond the condition variable on which to block. + * @param mutex the mutex that must be locked upon entering this function, + * is released while the thread is asleep, and is again acquired before + * returning from this function. + * @param timeout The amount of time in microseconds to wait. This is + * a maximum, not a minimum. If the condition is signaled, we + * will wake up before this time, otherwise the error APR_TIMEUP + * is returned. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_timedwait(apr_thread_cond_t *cond, + apr_thread_mutex_t *mutex, + apr_interval_time_t timeout); + +/** + * Signals a single thread, if one exists, that is blocking on the given + * condition variable. That thread is then scheduled to wake up and acquire + * the associated mutex. Although it is not required, if predictable scheduling + * is desired, that mutex must be locked while calling this function. + * @param cond the condition variable on which to produce the signal. + * @remark If no threads are waiting on the condition variable, nothing happens. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_signal(apr_thread_cond_t *cond); + +/** + * Signals all threads blocking on the given condition variable. + * Each thread that was signaled is then scheduled to wake up and acquire + * the associated mutex. This will happen in a serialized manner. + * @param cond the condition variable on which to produce the broadcast. + * @remark If no threads are waiting on the condition variable, nothing happens. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_broadcast(apr_thread_cond_t *cond); + +/** + * Destroy the condition variable and free the associated memory. + * @param cond the condition variable to destroy. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_destroy(apr_thread_cond_t *cond); + +/** + * Get the pool used by this thread_cond. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(thread_cond); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_THREAD_COND_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_thread_mutex.h b/c/dependencies/windows/apr/x64_debug/include/apr_thread_mutex.h new file mode 100644 index 00000000..8eb61729 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_thread_mutex.h @@ -0,0 +1,123 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_THREAD_MUTEX_H +#define APR_THREAD_MUTEX_H + +/** + * @file apr_thread_mutex.h + * @brief APR Thread Mutex Routines + */ + +#include "apr.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#if APR_HAS_THREADS || defined(DOXYGEN) + +/** + * @defgroup apr_thread_mutex Thread Mutex Routines + * @ingroup APR + * @{ + */ + +/** Opaque thread-local mutex structure */ +typedef struct apr_thread_mutex_t apr_thread_mutex_t; + +#define APR_THREAD_MUTEX_DEFAULT 0x0 /**< platform-optimal lock behavior */ +#define APR_THREAD_MUTEX_NESTED 0x1 /**< enable nested (recursive) locks */ +#define APR_THREAD_MUTEX_UNNESTED 0x2 /**< disable nested locks */ +#define APR_THREAD_MUTEX_TIMED 0x4 /**< enable timed locks */ + +/* Delayed the include to avoid a circular reference */ +#include "apr_pools.h" +#include "apr_time.h" + +/** + * Create and initialize a mutex that can be used to synchronize threads. + * @param mutex the memory address where the newly created mutex will be + * stored. + * @param flags Or'ed value of: + *
+ *           APR_THREAD_MUTEX_DEFAULT   platform-optimal lock behavior.
+ *           APR_THREAD_MUTEX_NESTED    enable nested (recursive) locks.
+ *           APR_THREAD_MUTEX_UNNESTED  disable nested locks (non-recursive).
+ * 
+ * @param pool the pool from which to allocate the mutex. + * @warning Be cautious in using APR_THREAD_MUTEX_DEFAULT. While this is the + * most optimal mutex based on a given platform's performance characteristics, + * it will behave as either a nested or an unnested lock. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_create(apr_thread_mutex_t **mutex, + unsigned int flags, + apr_pool_t *pool); +/** + * Acquire the lock for the given mutex. If the mutex is already locked, + * the current thread will be put to sleep until the lock becomes available. + * @param mutex the mutex on which to acquire the lock. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_lock(apr_thread_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex. If the mutex has already + * been acquired, the call returns immediately with APR_EBUSY. Note: it + * is important that the APR_STATUS_IS_EBUSY(s) macro be used to determine + * if the return value was APR_EBUSY, for portability reasons. + * @param mutex the mutex on which to attempt the lock acquiring. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_trylock(apr_thread_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex until timeout expires. + * If the acquisition time outs, the call returns with APR_TIMEUP. + * @param mutex the mutex on which to attempt the lock acquiring. + * @param timeout the relative timeout (microseconds). + * @note A timeout negative or nul means immediate attempt, returning + * APR_TIMEUP without blocking if it the lock is already acquired. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_timedlock(apr_thread_mutex_t *mutex, + apr_interval_time_t timeout); + +/** + * Release the lock for the given mutex. + * @param mutex the mutex from which to release the lock. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_unlock(apr_thread_mutex_t *mutex); + +/** + * Destroy the mutex and free the memory associated with the lock. + * @param mutex the mutex to destroy. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_destroy(apr_thread_mutex_t *mutex); + +/** + * Get the pool used by this thread_mutex. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(thread_mutex); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_THREAD_MUTEX_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_thread_pool.h b/c/dependencies/windows/apr/x64_debug/include/apr_thread_pool.h new file mode 100644 index 00000000..cbf382b3 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_thread_pool.h @@ -0,0 +1,299 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +#ifndef APU_THREAD_POOL_H +#define APU_THREAD_POOL_H + +#include "apu.h" +#include "apr_thread_proc.h" + +/** + * @file apr_thread_pool.h + * @brief APR Thread Pool Library + + * @remarks This library implements a thread pool using apr_thread_t. A thread + * pool is a set of threads that can be created in advance or on demand until a + * maximum number. When a task is scheduled, the thread pool will find an idle + * thread to handle the task. In case all existing threads are busy and the + * number of tasks in the queue is higher than the adjustable threshold, the + * pool will try to create a new thread to serve the task if the maximum number + * has not been reached. Otherwise, the task will be put into a queue based on + * priority, which can be valued from 0 to 255, with higher values being served + * first. If there are tasks with the same priority, the new task might be put at + * the top or at the bottom - it depends on which function is used to put the task. + * + * @remarks There may be the case where the thread pool can use up to the maximum + * number of threads at peak load, but having those threads idle afterwards. A + * maximum number of idle threads can be set so that the extra idling threads will + * be terminated to save system resources. + */ +#if APR_HAS_THREADS + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_Util_TP Thread Pool routines + * @ingroup APR_Util + * @{ + */ + +/** Opaque Thread Pool structure. */ +typedef struct apr_thread_pool apr_thread_pool_t; + +#define APR_THREAD_TASK_PRIORITY_LOWEST 0 +#define APR_THREAD_TASK_PRIORITY_LOW 63 +#define APR_THREAD_TASK_PRIORITY_NORMAL 127 +#define APR_THREAD_TASK_PRIORITY_HIGH 191 +#define APR_THREAD_TASK_PRIORITY_HIGHEST 255 + +/** + * Create a thread pool + * @param me The pointer in which to return the newly created apr_thread_pool + * object, or NULL if thread pool creation fails. + * @param init_threads The number of threads to be created initially, this number + * will also be used as the initial value for the maximum number of idle threads. + * @param max_threads The maximum number of threads that can be created + * @param pool The pool to use + * @return APR_SUCCESS if the thread pool was created successfully. Otherwise, + * the error code. + */ +APU_DECLARE(apr_status_t) apr_thread_pool_create(apr_thread_pool_t **me, + apr_size_t init_threads, + apr_size_t max_threads, + apr_pool_t *pool); + +/** + * Destroy the thread pool and stop all the threads + * @return APR_SUCCESS if all threads are stopped. + */ +APU_DECLARE(apr_status_t) apr_thread_pool_destroy(apr_thread_pool_t *me); + +/** + * Schedule a task to the bottom of the tasks of same priority. + * @param me The thread pool + * @param func The task function + * @param param The parameter for the task function + * @param priority The priority of the task. + * @param owner Owner of this task. + * @return APR_SUCCESS if the task had been scheduled successfully + */ +APU_DECLARE(apr_status_t) apr_thread_pool_push(apr_thread_pool_t *me, + apr_thread_start_t func, + void *param, + apr_byte_t priority, + void *owner); +/** + * Schedule a task to be run after a delay + * @param me The thread pool + * @param func The task function + * @param param The parameter for the task function + * @param time Time in microseconds + * @param owner Owner of this task. + * @return APR_SUCCESS if the task had been scheduled successfully + */ +APU_DECLARE(apr_status_t) apr_thread_pool_schedule(apr_thread_pool_t *me, + apr_thread_start_t func, + void *param, + apr_interval_time_t time, + void *owner); + +/** + * Schedule a task to the top of the tasks of same priority. + * @param me The thread pool + * @param func The task function + * @param param The parameter for the task function + * @param priority The priority of the task. + * @param owner Owner of this task. + * @return APR_SUCCESS if the task had been scheduled successfully + */ +APU_DECLARE(apr_status_t) apr_thread_pool_top(apr_thread_pool_t *me, + apr_thread_start_t func, + void *param, + apr_byte_t priority, + void *owner); + +/** + * Cancel tasks submitted by the owner. If there is any task from the owner that + * is currently running, the function will spin until the task finished. + * @param me The thread pool + * @param owner Owner of the task + * @return APR_SUCCESS if the task has been cancelled successfully + * @note The task function should not be calling cancel, otherwise the function + * may get stuck forever. The function assert if it detect such a case. + */ +APU_DECLARE(apr_status_t) apr_thread_pool_tasks_cancel(apr_thread_pool_t *me, + void *owner); + +/** + * Get the current number of tasks waiting in the queue + * @param me The thread pool + * @return Number of tasks in the queue + */ +APU_DECLARE(apr_size_t) apr_thread_pool_tasks_count(apr_thread_pool_t *me); + +/** + * Get the current number of scheduled tasks waiting in the queue + * @param me The thread pool + * @return Number of scheduled tasks in the queue + */ +APU_DECLARE(apr_size_t) apr_thread_pool_scheduled_tasks_count(apr_thread_pool_t *me); + +/** + * Get the current number of threads + * @param me The thread pool + * @return Total number of threads + */ +APU_DECLARE(apr_size_t) apr_thread_pool_threads_count(apr_thread_pool_t *me); + +/** + * Get the current number of busy threads + * @param me The thread pool + * @return Number of busy threads + */ +APU_DECLARE(apr_size_t) apr_thread_pool_busy_count(apr_thread_pool_t *me); + +/** + * Get the current number of idle threads + * @param me The thread pool + * @return Number of idle threads + */ +APU_DECLARE(apr_size_t) apr_thread_pool_idle_count(apr_thread_pool_t *me); + +/** + * Access function for the maximum number of idle threads. Number of current + * idle threads will be reduced to the new limit. + * @param me The thread pool + * @param cnt The number + * @return The number of threads that were stopped. + */ +APU_DECLARE(apr_size_t) apr_thread_pool_idle_max_set(apr_thread_pool_t *me, + apr_size_t cnt); + +/** + * Get number of tasks that have run + * @param me The thread pool + * @return Number of tasks that have run + */ +APU_DECLARE(apr_size_t) + apr_thread_pool_tasks_run_count(apr_thread_pool_t * me); + +/** + * Get high water mark of the number of tasks waiting to run + * @param me The thread pool + * @return High water mark of tasks waiting to run + */ +APU_DECLARE(apr_size_t) + apr_thread_pool_tasks_high_count(apr_thread_pool_t * me); + +/** + * Get high water mark of the number of threads + * @param me The thread pool + * @return High water mark of threads in thread pool + */ +APU_DECLARE(apr_size_t) + apr_thread_pool_threads_high_count(apr_thread_pool_t * me); + +/** + * Get the number of idle threads that were destroyed after timing out + * @param me The thread pool + * @return Number of idle threads that timed out + */ +APU_DECLARE(apr_size_t) + apr_thread_pool_threads_idle_timeout_count(apr_thread_pool_t * me); + +/** + * Access function for the maximum number of idle threads + * @param me The thread pool + * @return The current maximum number + */ +APU_DECLARE(apr_size_t) apr_thread_pool_idle_max_get(apr_thread_pool_t *me); + +/** + * Access function for the maximum number of threads. + * @param me The thread pool + * @param cnt Number of threads + * @return The original maximum number of threads + */ +APU_DECLARE(apr_size_t) apr_thread_pool_thread_max_set(apr_thread_pool_t *me, + apr_size_t cnt); + +/** + * Access function for the maximum wait time (in microseconds) of an + * idling thread that exceeds the maximum number of idling threads. + * A non-zero value allows for the reaping of idling threads to shrink + * over time. Which helps reduce thrashing. + * @param me The thread pool + * @param timeout The number of microseconds an idle thread should wait + * till it reaps itself + * @return The original maximum wait time + */ +APU_DECLARE(apr_interval_time_t) + apr_thread_pool_idle_wait_set(apr_thread_pool_t * me, + apr_interval_time_t timeout); + +/** + * Access function for the maximum wait time (in microseconds) of an + * idling thread that exceeds the maximum number of idling threads + * @param me The thread pool + * @return The current maximum wait time + */ +APU_DECLARE(apr_interval_time_t) + apr_thread_pool_idle_wait_get(apr_thread_pool_t * me); + +/** + * Access function for the maximum number of threads + * @param me The thread pool + * @return The current maximum number + */ +APU_DECLARE(apr_size_t) apr_thread_pool_thread_max_get(apr_thread_pool_t *me); + +/** + * Access function for the threshold of tasks in queue to trigger a new thread. + * @param me The thread pool + * @param cnt The new threshold + * @return The original threshold + */ +APU_DECLARE(apr_size_t) apr_thread_pool_threshold_set(apr_thread_pool_t *me, + apr_size_t val); + +/** + * Access function for the threshold of tasks in queue to trigger a new thread. + * @param me The thread pool + * @return The current threshold + */ +APU_DECLARE(apr_size_t) apr_thread_pool_threshold_get(apr_thread_pool_t * me); + +/** + * Get owner of the task currently been executed by the thread. + * @param thd The thread is executing a task + * @param owner Pointer to receive owner of the task. + * @return APR_SUCCESS if the owner is retrieved successfully + */ +APU_DECLARE(apr_status_t) apr_thread_pool_task_owner_get(apr_thread_t *thd, + void **owner); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_HAS_THREADS */ +#endif /* !APR_THREAD_POOL_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_thread_proc.h b/c/dependencies/windows/apr/x64_debug/include/apr_thread_proc.h new file mode 100644 index 00000000..ea3c43f9 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_thread_proc.h @@ -0,0 +1,846 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_THREAD_PROC_H +#define APR_THREAD_PROC_H + +/** + * @file apr_thread_proc.h + * @brief APR Thread and Process Library + */ + +#include "apr.h" +#include "apr_file_io.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_perms_set.h" + +#if APR_HAVE_STRUCT_RLIMIT +#include +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_thread_proc Threads and Process Functions + * @ingroup APR + * @{ + */ + +typedef enum { + APR_SHELLCMD, /**< use the shell to invoke the program */ + APR_PROGRAM, /**< invoke the program directly, no copied env */ + APR_PROGRAM_ENV, /**< invoke the program, replicating our environment */ + APR_PROGRAM_PATH, /**< find program on PATH, use our environment */ + APR_SHELLCMD_ENV /**< use the shell to invoke the program, + * replicating our environment + */ +} apr_cmdtype_e; + +typedef enum { + APR_WAIT, /**< wait for the specified process to finish */ + APR_NOWAIT /**< do not wait -- just see if it has finished */ +} apr_wait_how_e; + +/* I am specifically calling out the values so that the macros below make + * more sense. Yes, I know I don't need to, but I am hoping this makes what + * I am doing more clear. If you want to add more reasons to exit, continue + * to use bitmasks. + */ +typedef enum { + APR_PROC_EXIT = 1, /**< process exited normally */ + APR_PROC_SIGNAL = 2, /**< process exited due to a signal */ + APR_PROC_SIGNAL_CORE = 4 /**< process exited and dumped a core file */ +} apr_exit_why_e; + +/** did we exit the process */ +#define APR_PROC_CHECK_EXIT(x) (x & APR_PROC_EXIT) +/** did we get a signal */ +#define APR_PROC_CHECK_SIGNALED(x) (x & APR_PROC_SIGNAL) +/** did we get core */ +#define APR_PROC_CHECK_CORE_DUMP(x) (x & APR_PROC_SIGNAL_CORE) + +/** @see apr_procattr_io_set */ +#define APR_NO_PIPE 0 +/** @see apr_procattr_io_set and apr_file_pipe_create_ex */ +#define APR_FULL_BLOCK 1 +/** @see apr_procattr_io_set and apr_file_pipe_create_ex */ +#define APR_FULL_NONBLOCK 2 +/** @see apr_procattr_io_set */ +#define APR_PARENT_BLOCK 3 +/** @see apr_procattr_io_set */ +#define APR_CHILD_BLOCK 4 +/** @see apr_procattr_io_set */ +#define APR_NO_FILE 8 + +/** @see apr_file_pipe_create_ex */ +#define APR_READ_BLOCK 3 +/** @see apr_file_pipe_create_ex */ +#define APR_WRITE_BLOCK 4 + +/** @see apr_procattr_io_set + * @note Win32 only effective with version 1.2.12, portably introduced in 1.3.0 + */ +#define APR_NO_FILE 8 + +/** @see apr_procattr_limit_set */ +#define APR_LIMIT_CPU 0 +/** @see apr_procattr_limit_set */ +#define APR_LIMIT_MEM 1 +/** @see apr_procattr_limit_set */ +#define APR_LIMIT_NPROC 2 +/** @see apr_procattr_limit_set */ +#define APR_LIMIT_NOFILE 3 + +/** + * @defgroup APR_OC Other Child Flags + * @{ + */ +#define APR_OC_REASON_DEATH 0 /**< child has died, caller must call + * unregister still */ +#define APR_OC_REASON_UNWRITABLE 1 /**< write_fd is unwritable */ +#define APR_OC_REASON_RESTART 2 /**< a restart is occurring, perform + * any necessary cleanup (including + * sending a special signal to child) + */ +#define APR_OC_REASON_UNREGISTER 3 /**< unregister has been called, do + * whatever is necessary (including + * kill the child) */ +#define APR_OC_REASON_LOST 4 /**< somehow the child exited without + * us knowing ... buggy os? */ +#define APR_OC_REASON_RUNNING 5 /**< a health check is occurring, + * for most maintainence functions + * this is a no-op. + */ +/** @} */ + +/** The APR process type */ +typedef struct apr_proc_t { + /** The process ID */ + pid_t pid; + /** Parent's side of pipe to child's stdin */ + apr_file_t *in; + /** Parent's side of pipe to child's stdout */ + apr_file_t *out; + /** Parent's side of pipe to child's stdouterr */ + apr_file_t *err; +#if APR_HAS_PROC_INVOKED || defined(DOXYGEN) + /** Diagnositics/debugging string of the command invoked for + * this process [only present if APR_HAS_PROC_INVOKED is true] + * @remark Only enabled on Win32 by default. + * @bug This should either always or never be present in release + * builds - since it breaks binary compatibility. We may enable + * it always in APR 1.0 yet leave it undefined in most cases. + */ + char *invoked; +#endif +#if defined(WIN32) || defined(DOXYGEN) + /** (Win32 only) Creator's handle granting access to the process + * @remark This handle is closed and reset to NULL in every case + * corresponding to a waitpid() on Unix which returns the exit status. + * Therefore Win32 correspond's to Unix's zombie reaping characteristics + * and avoids potential handle leaks. + */ + HANDLE hproc; +#endif +} apr_proc_t; + +/** + * The prototype for APR child errfn functions. (See the description + * of apr_procattr_child_errfn_set() for more information.) + * It is passed the following parameters: + * @param pool Pool associated with the apr_proc_t. If your child + * error function needs user data, associate it with this + * pool. + * @param err APR error code describing the error + * @param description Text description of type of processing which failed + */ +typedef void (apr_child_errfn_t)(apr_pool_t *proc, apr_status_t err, + const char *description); + +/** Opaque Thread structure. */ +typedef struct apr_thread_t apr_thread_t; + +/** Opaque Thread attributes structure. */ +typedef struct apr_threadattr_t apr_threadattr_t; + +/** Opaque Process attributes structure. */ +typedef struct apr_procattr_t apr_procattr_t; + +/** Opaque control variable for one-time atomic variables. */ +typedef struct apr_thread_once_t apr_thread_once_t; + +/** Opaque thread private address space. */ +typedef struct apr_threadkey_t apr_threadkey_t; + +/** Opaque record of child process. */ +typedef struct apr_other_child_rec_t apr_other_child_rec_t; + +/** + * The prototype for any APR thread worker functions. + */ +typedef void *(APR_THREAD_FUNC *apr_thread_start_t)(apr_thread_t*, void*); + +typedef enum { + APR_KILL_NEVER, /**< process is never killed (i.e., never sent + * any signals), but it will be reaped if it exits + * before the pool is cleaned up */ + APR_KILL_ALWAYS, /**< process is sent SIGKILL on apr_pool_t cleanup */ + APR_KILL_AFTER_TIMEOUT, /**< SIGTERM, wait 3 seconds, SIGKILL */ + APR_JUST_WAIT, /**< wait forever for the process to complete */ + APR_KILL_ONLY_ONCE /**< send SIGTERM and then wait */ +} apr_kill_conditions_e; + +/* Thread Function definitions */ + +#if APR_HAS_THREADS + +/** + * Create and initialize a new threadattr variable + * @param new_attr The newly created threadattr. + * @param cont The pool to use + */ +APR_DECLARE(apr_status_t) apr_threadattr_create(apr_threadattr_t **new_attr, + apr_pool_t *cont); + +/** + * Set if newly created threads should be created in detached state. + * @param attr The threadattr to affect + * @param on Non-zero if detached threads should be created. + */ +APR_DECLARE(apr_status_t) apr_threadattr_detach_set(apr_threadattr_t *attr, + apr_int32_t on); + +/** + * Get the detach state for this threadattr. + * @param attr The threadattr to reference + * @return APR_DETACH if threads are to be detached, or APR_NOTDETACH + * if threads are to be joinable. + */ +APR_DECLARE(apr_status_t) apr_threadattr_detach_get(apr_threadattr_t *attr); + +/** + * Set the stack size of newly created threads. + * @param attr The threadattr to affect + * @param stacksize The stack size in bytes + */ +APR_DECLARE(apr_status_t) apr_threadattr_stacksize_set(apr_threadattr_t *attr, + apr_size_t stacksize); + +/** + * Set the stack guard area size of newly created threads. + * @param attr The threadattr to affect + * @param guardsize The stack guard area size in bytes + * @note Thread library implementations commonly use a "guard area" + * after each thread's stack which is not readable or writable such that + * stack overflows cause a segfault; this consumes e.g. 4K of memory + * and increases memory management overhead. Setting the guard area + * size to zero hence trades off reliable behaviour on stack overflow + * for performance. */ +APR_DECLARE(apr_status_t) apr_threadattr_guardsize_set(apr_threadattr_t *attr, + apr_size_t guardsize); + +/** + * Create a new thread of execution + * @param new_thread The newly created thread handle. + * @param attr The threadattr to use to determine how to create the thread + * @param func The function to start the new thread in + * @param data Any data to be passed to the starting function + * @param cont The pool to use + */ +APR_DECLARE(apr_status_t) apr_thread_create(apr_thread_t **new_thread, + apr_threadattr_t *attr, + apr_thread_start_t func, + void *data, apr_pool_t *cont); + +/** + * stop the current thread + * @param thd The thread to stop + * @param retval The return value to pass back to any thread that cares + */ +APR_DECLARE(apr_status_t) apr_thread_exit(apr_thread_t *thd, + apr_status_t retval); + +/** + * block until the desired thread stops executing. + * @param retval The return value from the dead thread. + * @param thd The thread to join + */ +APR_DECLARE(apr_status_t) apr_thread_join(apr_status_t *retval, + apr_thread_t *thd); + +/** + * force the current thread to yield the processor + */ +APR_DECLARE(void) apr_thread_yield(void); + +/** + * Initialize the control variable for apr_thread_once. If this isn't + * called, apr_initialize won't work. + * @param control The control variable to initialize + * @param p The pool to allocate data from. + */ +APR_DECLARE(apr_status_t) apr_thread_once_init(apr_thread_once_t **control, + apr_pool_t *p); + +/** + * Run the specified function one time, regardless of how many threads + * call it. + * @param control The control variable. The same variable should + * be passed in each time the function is tried to be + * called. This is how the underlying functions determine + * if the function has ever been called before. + * @param func The function to call. + */ +APR_DECLARE(apr_status_t) apr_thread_once(apr_thread_once_t *control, + void (*func)(void)); + +/** + * detach a thread + * @param thd The thread to detach + */ +APR_DECLARE(apr_status_t) apr_thread_detach(apr_thread_t *thd); + +/** + * Return user data associated with the current thread. + * @param data The user data associated with the thread. + * @param key The key to associate with the data + * @param thread The currently open thread. + */ +APR_DECLARE(apr_status_t) apr_thread_data_get(void **data, const char *key, + apr_thread_t *thread); + +/** + * Set user data associated with the current thread. + * @param data The user data to associate with the thread. + * @param key The key to use for associating the data with the thread + * @param cleanup The cleanup routine to use when the thread is destroyed. + * @param thread The currently open thread. + */ +APR_DECLARE(apr_status_t) apr_thread_data_set(void *data, const char *key, + apr_status_t (*cleanup) (void *), + apr_thread_t *thread); + +/** + * Create and initialize a new thread private address space + * @param key The thread private handle. + * @param dest The destructor to use when freeing the private memory. + * @param cont The pool to use + */ +APR_DECLARE(apr_status_t) apr_threadkey_private_create(apr_threadkey_t **key, + void (*dest)(void *), + apr_pool_t *cont); + +/** + * Get a pointer to the thread private memory + * @param new_mem The data stored in private memory + * @param key The handle for the desired thread private memory + */ +APR_DECLARE(apr_status_t) apr_threadkey_private_get(void **new_mem, + apr_threadkey_t *key); + +/** + * Set the data to be stored in thread private memory + * @param priv The data to be stored in private memory + * @param key The handle for the desired thread private memory + */ +APR_DECLARE(apr_status_t) apr_threadkey_private_set(void *priv, + apr_threadkey_t *key); + +/** + * Free the thread private memory + * @param key The handle for the desired thread private memory + */ +APR_DECLARE(apr_status_t) apr_threadkey_private_delete(apr_threadkey_t *key); + +/** + * Return the pool associated with the current threadkey. + * @param data The user data associated with the threadkey. + * @param key The key associated with the data + * @param threadkey The currently open threadkey. + */ +APR_DECLARE(apr_status_t) apr_threadkey_data_get(void **data, const char *key, + apr_threadkey_t *threadkey); + +/** + * Return the pool associated with the current threadkey. + * @param data The data to set. + * @param key The key to associate with the data. + * @param cleanup The cleanup routine to use when the file is destroyed. + * @param threadkey The currently open threadkey. + */ +APR_DECLARE(apr_status_t) apr_threadkey_data_set(void *data, const char *key, + apr_status_t (*cleanup) (void *), + apr_threadkey_t *threadkey); + +#endif + +/** + * Create and initialize a new procattr variable + * @param new_attr The newly created procattr. + * @param cont The pool to use + */ +APR_DECLARE(apr_status_t) apr_procattr_create(apr_procattr_t **new_attr, + apr_pool_t *cont); + +/** + * Determine if any of stdin, stdout, or stderr should be linked to pipes + * when starting a child process. + * @param attr The procattr we care about. + * @param in Should stdin be a pipe back to the parent? + * @param out Should stdout be a pipe back to the parent? + * @param err Should stderr be a pipe back to the parent? + * @note If APR_NO_PIPE, there will be no special channel, the child + * inherits the parent's corresponding stdio stream. If APR_NO_FILE is + * specified, that corresponding stream is closed in the child (and will + * be INVALID_HANDLE_VALUE when inspected on Win32). This can have ugly + * side effects, as the next file opened in the child on Unix will fall + * into the stdio stream fd slot! + */ +APR_DECLARE(apr_status_t) apr_procattr_io_set(apr_procattr_t *attr, + apr_int32_t in, apr_int32_t out, + apr_int32_t err); + +/** + * Set the child_in and/or parent_in values to existing apr_file_t values. + * @param attr The procattr we care about. + * @param child_in apr_file_t value to use as child_in. Must be a valid file. + * @param parent_in apr_file_t value to use as parent_in. Must be a valid file. + * @remark This is NOT a required initializer function. This is + * useful if you have already opened a pipe (or multiple files) + * that you wish to use, perhaps persistently across multiple + * process invocations - such as a log file. You can save some + * extra function calls by not creating your own pipe since this + * creates one in the process space for you. + * @bug Note that calling this function with two NULL files on some platforms + * creates an APR_FULL_BLOCK pipe, but this behavior is neither portable nor + * is it supported. @see apr_procattr_io_set instead for simple pipes. + */ +APR_DECLARE(apr_status_t) apr_procattr_child_in_set(struct apr_procattr_t *attr, + apr_file_t *child_in, + apr_file_t *parent_in); + +/** + * Set the child_out and parent_out values to existing apr_file_t values. + * @param attr The procattr we care about. + * @param child_out apr_file_t value to use as child_out. Must be a valid file. + * @param parent_out apr_file_t value to use as parent_out. Must be a valid file. + * @remark This is NOT a required initializer function. This is + * useful if you have already opened a pipe (or multiple files) + * that you wish to use, perhaps persistently across multiple + * process invocations - such as a log file. + * @bug Note that calling this function with two NULL files on some platforms + * creates an APR_FULL_BLOCK pipe, but this behavior is neither portable nor + * is it supported. @see apr_procattr_io_set instead for simple pipes. + */ +APR_DECLARE(apr_status_t) apr_procattr_child_out_set(struct apr_procattr_t *attr, + apr_file_t *child_out, + apr_file_t *parent_out); + +/** + * Set the child_err and parent_err values to existing apr_file_t values. + * @param attr The procattr we care about. + * @param child_err apr_file_t value to use as child_err. Must be a valid file. + * @param parent_err apr_file_t value to use as parent_err. Must be a valid file. + * @remark This is NOT a required initializer function. This is + * useful if you have already opened a pipe (or multiple files) + * that you wish to use, perhaps persistently across multiple + * process invocations - such as a log file. + * @bug Note that calling this function with two NULL files on some platforms + * creates an APR_FULL_BLOCK pipe, but this behavior is neither portable nor + * is it supported. @see apr_procattr_io_set instead for simple pipes. + */ +APR_DECLARE(apr_status_t) apr_procattr_child_err_set(struct apr_procattr_t *attr, + apr_file_t *child_err, + apr_file_t *parent_err); + +/** + * Set which directory the child process should start executing in. + * @param attr The procattr we care about. + * @param dir Which dir to start in. By default, this is the same dir as + * the parent currently resides in, when the createprocess call + * is made. + */ +APR_DECLARE(apr_status_t) apr_procattr_dir_set(apr_procattr_t *attr, + const char *dir); + +/** + * Set what type of command the child process will call. + * @param attr The procattr we care about. + * @param cmd The type of command. One of: + *
+ *            APR_SHELLCMD     --  Anything that the shell can handle
+ *            APR_PROGRAM      --  Executable program   (default) 
+ *            APR_PROGRAM_ENV  --  Executable program, copy environment
+ *            APR_PROGRAM_PATH --  Executable program on PATH, copy env
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_procattr_cmdtype_set(apr_procattr_t *attr, + apr_cmdtype_e cmd); + +/** + * Determine if the child should start in detached state. + * @param attr The procattr we care about. + * @param detach Should the child start in detached state? Default is no. + */ +APR_DECLARE(apr_status_t) apr_procattr_detach_set(apr_procattr_t *attr, + apr_int32_t detach); + +#if APR_HAVE_STRUCT_RLIMIT +/** + * Set the Resource Utilization limits when starting a new process. + * @param attr The procattr we care about. + * @param what Which limit to set, one of: + *
+ *                 APR_LIMIT_CPU
+ *                 APR_LIMIT_MEM
+ *                 APR_LIMIT_NPROC
+ *                 APR_LIMIT_NOFILE
+ * 
+ * @param limit Value to set the limit to. + */ +APR_DECLARE(apr_status_t) apr_procattr_limit_set(apr_procattr_t *attr, + apr_int32_t what, + struct rlimit *limit); +#endif + +/** + * Specify an error function to be called in the child process if APR + * encounters an error in the child prior to running the specified program. + * @param attr The procattr describing the child process to be created. + * @param errfn The function to call in the child process. + * @remark At the present time, it will only be called from apr_proc_create() + * on platforms where fork() is used. It will never be called on other + * platforms, on those platforms apr_proc_create() will return the error + * in the parent process rather than invoke the callback in the now-forked + * child process. + */ +APR_DECLARE(apr_status_t) apr_procattr_child_errfn_set(apr_procattr_t *attr, + apr_child_errfn_t *errfn); + +/** + * Specify that apr_proc_create() should do whatever it can to report + * failures to the caller of apr_proc_create(), rather than find out in + * the child. + * @param attr The procattr describing the child process to be created. + * @param chk Flag to indicate whether or not extra work should be done + * to try to report failures to the caller. + * @remark This flag only affects apr_proc_create() on platforms where + * fork() is used. This leads to extra overhead in the calling + * process, but that may help the application handle such + * errors more gracefully. + */ +APR_DECLARE(apr_status_t) apr_procattr_error_check_set(apr_procattr_t *attr, + apr_int32_t chk); + +/** + * Determine if the child should start in its own address space or using the + * current one from its parent + * @param attr The procattr we care about. + * @param addrspace Should the child start in its own address space? Default + * is no on NetWare and yes on other platforms. + */ +APR_DECLARE(apr_status_t) apr_procattr_addrspace_set(apr_procattr_t *attr, + apr_int32_t addrspace); + +/** + * Set the username used for running process + * @param attr The procattr we care about. + * @param username The username used + * @param password User password if needed. Password is needed on WIN32 + * or any other platform having + * APR_PROCATTR_USER_SET_REQUIRES_PASSWORD set. + */ +APR_DECLARE(apr_status_t) apr_procattr_user_set(apr_procattr_t *attr, + const char *username, + const char *password); + +/** + * Set the group used for running process + * @param attr The procattr we care about. + * @param groupname The group name used + */ +APR_DECLARE(apr_status_t) apr_procattr_group_set(apr_procattr_t *attr, + const char *groupname); + + +/** + * Register permission set function + * @param attr The procattr we care about. + * @param perms_set_fn Permission set callback + * @param data Data to pass to permission callback function + * @param perms Permissions to set + */ +APR_DECLARE(apr_status_t) apr_procattr_perms_set_register(apr_procattr_t *attr, + apr_perms_setfn_t *perms_set_fn, + void *data, + apr_fileperms_t perms); + +#if APR_HAS_FORK +/** + * This is currently the only non-portable call in APR. This executes + * a standard unix fork. + * @param proc The resulting process handle. + * @param cont The pool to use. + * @remark returns APR_INCHILD for the child, and APR_INPARENT for the parent + * or an error. + */ +APR_DECLARE(apr_status_t) apr_proc_fork(apr_proc_t *proc, apr_pool_t *cont); +#endif + +/** + * Create a new process and execute a new program within that process. + * @param new_proc The resulting process handle. + * @param progname The program to run + * @param args the arguments to pass to the new program. The first + * one should be the program name. + * @param env The new environment table for the new process. This + * should be a list of NULL-terminated strings. This argument + * is ignored for APR_PROGRAM_ENV, APR_PROGRAM_PATH, and + * APR_SHELLCMD_ENV types of commands. + * @param attr the procattr we should use to determine how to create the new + * process + * @param pool The pool to use. + * @note This function returns without waiting for the new process to terminate; + * use apr_proc_wait for that. + */ +APR_DECLARE(apr_status_t) apr_proc_create(apr_proc_t *new_proc, + const char *progname, + const char * const *args, + const char * const *env, + apr_procattr_t *attr, + apr_pool_t *pool); + +/** + * Wait for a child process to die + * @param proc The process handle that corresponds to the desired child process + * @param exitcode The returned exit status of the child, if a child process + * dies, or the signal that caused the child to die. + * On platforms that don't support obtaining this information, + * the status parameter will be returned as APR_ENOTIMPL. + * @param exitwhy Why the child died, the bitwise or of: + *
+ *            APR_PROC_EXIT         -- process terminated normally
+ *            APR_PROC_SIGNAL       -- process was killed by a signal
+ *            APR_PROC_SIGNAL_CORE  -- process was killed by a signal, and
+ *                                     generated a core dump.
+ * 
+ * @param waithow How should we wait. One of: + *
+ *            APR_WAIT   -- block until the child process dies.
+ *            APR_NOWAIT -- return immediately regardless of if the 
+ *                          child is dead or not.
+ * 
+ * @remark The child's status is in the return code to this process. It is one of: + *
+ *            APR_CHILD_DONE     -- child is no longer running.
+ *            APR_CHILD_NOTDONE  -- child is still running.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_proc_wait(apr_proc_t *proc, + int *exitcode, apr_exit_why_e *exitwhy, + apr_wait_how_e waithow); + +/** + * Wait for any current child process to die and return information + * about that child. + * @param proc Pointer to NULL on entry, will be filled out with child's + * information + * @param exitcode The returned exit status of the child, if a child process + * dies, or the signal that caused the child to die. + * On platforms that don't support obtaining this information, + * the status parameter will be returned as APR_ENOTIMPL. + * @param exitwhy Why the child died, the bitwise or of: + *
+ *            APR_PROC_EXIT         -- process terminated normally
+ *            APR_PROC_SIGNAL       -- process was killed by a signal
+ *            APR_PROC_SIGNAL_CORE  -- process was killed by a signal, and
+ *                                     generated a core dump.
+ * 
+ * @param waithow How should we wait. One of: + *
+ *            APR_WAIT   -- block until the child process dies.
+ *            APR_NOWAIT -- return immediately regardless of if the 
+ *                          child is dead or not.
+ * 
+ * @param p Pool to allocate child information out of. + * @bug Passing proc as a *proc rather than **proc was an odd choice + * for some platforms... this should be revisited in 1.0 + */ +APR_DECLARE(apr_status_t) apr_proc_wait_all_procs(apr_proc_t *proc, + int *exitcode, + apr_exit_why_e *exitwhy, + apr_wait_how_e waithow, + apr_pool_t *p); + +#define APR_PROC_DETACH_FOREGROUND 0 /**< Do not detach */ +#define APR_PROC_DETACH_DAEMONIZE 1 /**< Detach */ + +/** + * Detach the process from the controlling terminal. + * @param daemonize set to non-zero if the process should daemonize + * and become a background process, else it will + * stay in the foreground. + */ +APR_DECLARE(apr_status_t) apr_proc_detach(int daemonize); + +/** + * Register an other_child -- a child associated to its registered + * maintence callback. This callback is invoked when the process + * dies, is disconnected or disappears. + * @param proc The child process to register. + * @param maintenance maintenance is a function that is invoked with a + * reason and the data pointer passed here. + * @param data Opaque context data passed to the maintenance function. + * @param write_fd An fd that is probed for writing. If it is ever unwritable + * then the maintenance is invoked with reason + * OC_REASON_UNWRITABLE. + * @param p The pool to use for allocating memory. + * @bug write_fd duplicates the proc->out stream, it's really redundant + * and should be replaced in the APR 1.0 API with a bitflag of which + * proc->in/out/err handles should be health checked. + * @bug no platform currently tests the pipes health. + */ +APR_DECLARE(void) apr_proc_other_child_register(apr_proc_t *proc, + void (*maintenance) (int reason, + void *, + int status), + void *data, apr_file_t *write_fd, + apr_pool_t *p); + +/** + * Stop watching the specified other child. + * @param data The data to pass to the maintenance function. This is + * used to find the process to unregister. + * @warning Since this can be called by a maintenance function while we're + * scanning the other_children list, all scanners should protect + * themself by loading ocr->next before calling any maintenance + * function. + */ +APR_DECLARE(void) apr_proc_other_child_unregister(void *data); + +/** + * Notify the maintenance callback of a registered other child process + * that application has detected an event, such as death. + * @param proc The process to check + * @param reason The reason code to pass to the maintenance function + * @param status The status to pass to the maintenance function + * @remark An example of code using this behavior; + *
+ * rv = apr_proc_wait_all_procs(&proc, &exitcode, &status, APR_WAIT, p);
+ * if (APR_STATUS_IS_CHILD_DONE(rv)) {
+ * \#if APR_HAS_OTHER_CHILD
+ *     if (apr_proc_other_child_alert(&proc, APR_OC_REASON_DEATH, status)
+ *             == APR_SUCCESS) {
+ *         ;  (already handled)
+ *     }
+ *     else
+ * \#endif
+ *         [... handling non-otherchild processes death ...]
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_proc_other_child_alert(apr_proc_t *proc, + int reason, + int status); + +/** + * Test one specific other child processes and invoke the maintenance callback + * with the appropriate reason code, if still running, or the appropriate reason + * code if the process is no longer healthy. + * @param ocr The registered other child + * @param reason The reason code (e.g. APR_OC_REASON_RESTART) if still running + */ +APR_DECLARE(void) apr_proc_other_child_refresh(apr_other_child_rec_t *ocr, + int reason); + +/** + * Test all registered other child processes and invoke the maintenance callback + * with the appropriate reason code, if still running, or the appropriate reason + * code if the process is no longer healthy. + * @param reason The reason code (e.g. APR_OC_REASON_RESTART) to running processes + */ +APR_DECLARE(void) apr_proc_other_child_refresh_all(int reason); + +/** + * Terminate a process. + * @param proc The process to terminate. + * @param sig How to kill the process. + */ +APR_DECLARE(apr_status_t) apr_proc_kill(apr_proc_t *proc, int sig); + +/** + * Register a process to be killed when a pool dies. + * @param a The pool to use to define the processes lifetime + * @param proc The process to register + * @param how How to kill the process, one of: + *
+ *         APR_KILL_NEVER         -- process is never sent any signals
+ *         APR_KILL_ALWAYS        -- process is sent SIGKILL on apr_pool_t cleanup
+ *         APR_KILL_AFTER_TIMEOUT -- SIGTERM, wait 3 seconds, SIGKILL
+ *         APR_JUST_WAIT          -- wait forever for the process to complete
+ *         APR_KILL_ONLY_ONCE     -- send SIGTERM and then wait
+ * 
+ */ +APR_DECLARE(void) apr_pool_note_subprocess(apr_pool_t *a, apr_proc_t *proc, + apr_kill_conditions_e how); + +#if APR_HAS_THREADS + +#if (APR_HAVE_SIGWAIT || APR_HAVE_SIGSUSPEND) && !defined(OS2) + +/** + * Setup the process for a single thread to be used for all signal handling. + * @warning This must be called before any threads are created + */ +APR_DECLARE(apr_status_t) apr_setup_signal_thread(void); + +/** + * Make the current thread listen for signals. This thread will loop + * forever, calling a provided function whenever it receives a signal. That + * functions should return 1 if the signal has been handled, 0 otherwise. + * @param signal_handler The function to call when a signal is received + * apr_status_t apr_signal_thread((int)(*signal_handler)(int signum)) + * @note Synchronous signals like SIGABRT/SIGSEGV/SIGBUS/... are ignored by + * apr_signal_thread() and thus can't be waited by this function (they remain + * handled by the operating system or its native signals interface). + * @remark In APR version 1.6 and ealier, SIGUSR2 was part of these ignored + * signals and thus was never passed in to the signal_handler. From APR 1.7 + * this is no more the case so SIGUSR2 can be handled in signal_handler and + * acted upon like the other asynchronous signals. + */ +APR_DECLARE(apr_status_t) apr_signal_thread(int(*signal_handler)(int signum)); + +#endif /* (APR_HAVE_SIGWAIT || APR_HAVE_SIGSUSPEND) && !defined(OS2) */ + +/** + * Get the child-pool used by the thread from the thread info. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(thread); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_THREAD_PROC_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_thread_rwlock.h b/c/dependencies/windows/apr/x64_debug/include/apr_thread_rwlock.h new file mode 100644 index 00000000..0bd958fb --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_thread_rwlock.h @@ -0,0 +1,129 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_THREAD_RWLOCK_H +#define APR_THREAD_RWLOCK_H + +/** + * @file apr_thread_rwlock.h + * @brief APR Reader/Writer Lock Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#if APR_HAS_THREADS + +/** + * @defgroup apr_thread_rwlock Reader/Writer Lock Routines + * @ingroup APR + * @{ + */ + +/** Opaque read-write thread-safe lock. */ +typedef struct apr_thread_rwlock_t apr_thread_rwlock_t; + +/** + * Note: The following operations have undefined results: unlocking a + * read-write lock which is not locked in the calling thread; write + * locking a read-write lock which is already locked by the calling + * thread; destroying a read-write lock more than once; clearing or + * destroying the pool from which a locked read-write lock is + * allocated. + */ + +/** + * Create and initialize a read-write lock that can be used to synchronize + * threads. + * @param rwlock the memory address where the newly created readwrite lock + * will be stored. + * @param pool the pool from which to allocate the mutex. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_create(apr_thread_rwlock_t **rwlock, + apr_pool_t *pool); +/** + * Acquire a shared-read lock on the given read-write lock. This will allow + * multiple threads to enter the same critical section while they have acquired + * the read lock. + * @param rwlock the read-write lock on which to acquire the shared read. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_rdlock(apr_thread_rwlock_t *rwlock); + +/** + * Attempt to acquire the shared-read lock on the given read-write lock. This + * is the same as apr_thread_rwlock_rdlock(), only that the function fails + * if there is another thread holding the write lock, or if there are any + * write threads blocking on the lock. If the function fails for this case, + * APR_EBUSY will be returned. Note: it is important that the + * APR_STATUS_IS_EBUSY(s) macro be used to determine if the return value was + * APR_EBUSY, for portability reasons. + * @param rwlock the rwlock on which to attempt the shared read. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_tryrdlock(apr_thread_rwlock_t *rwlock); + +/** + * Acquire an exclusive-write lock on the given read-write lock. This will + * allow only one single thread to enter the critical sections. If there + * are any threads currently holding the read-lock, this thread is put to + * sleep until it can have exclusive access to the lock. + * @param rwlock the read-write lock on which to acquire the exclusive write. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_wrlock(apr_thread_rwlock_t *rwlock); + +/** + * Attempt to acquire the exclusive-write lock on the given read-write lock. + * This is the same as apr_thread_rwlock_wrlock(), only that the function fails + * if there is any other thread holding the lock (for reading or writing), + * in which case the function will return APR_EBUSY. Note: it is important + * that the APR_STATUS_IS_EBUSY(s) macro be used to determine if the return + * value was APR_EBUSY, for portability reasons. + * @param rwlock the rwlock on which to attempt the exclusive write. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_trywrlock(apr_thread_rwlock_t *rwlock); + +/** + * Release either the read or write lock currently held by the calling thread + * associated with the given read-write lock. + * @param rwlock the read-write lock to be released (unlocked). + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_unlock(apr_thread_rwlock_t *rwlock); + +/** + * Destroy the read-write lock and free the associated memory. + * @param rwlock the rwlock to destroy. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_destroy(apr_thread_rwlock_t *rwlock); + +/** + * Get the pool used by this thread_rwlock. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(thread_rwlock); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_THREAD_RWLOCK_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_time.h b/c/dependencies/windows/apr/x64_debug/include/apr_time.h new file mode 100644 index 00000000..b0efd791 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_time.h @@ -0,0 +1,237 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_TIME_H +#define APR_TIME_H + +/** + * @file apr_time.h + * @brief APR Time Library + */ + +#include "apr.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_time Time Routines + * @ingroup APR + * @{ + */ + +/** month names */ +APR_DECLARE_DATA extern const char apr_month_snames[12][4]; +/** day names */ +APR_DECLARE_DATA extern const char apr_day_snames[7][4]; + + +/** number of microseconds since 00:00:00 January 1, 1970 UTC */ +typedef apr_int64_t apr_time_t; + + +/** mechanism to properly type apr_time_t literals */ +#define APR_TIME_C(val) APR_INT64_C(val) + +/** mechanism to properly print apr_time_t values */ +#define APR_TIME_T_FMT APR_INT64_T_FMT + +/** intervals for I/O timeouts, in microseconds */ +typedef apr_int64_t apr_interval_time_t; +/** short interval for I/O timeouts, in microseconds */ +typedef apr_int32_t apr_short_interval_time_t; + +/** number of microseconds per second */ +#define APR_USEC_PER_SEC APR_TIME_C(1000000) + +/** @return apr_time_t as a second */ +#define apr_time_sec(time) ((time) / APR_USEC_PER_SEC) + +/** @return apr_time_t as a usec */ +#define apr_time_usec(time) ((time) % APR_USEC_PER_SEC) + +/** @return apr_time_t as a msec */ +#define apr_time_msec(time) (((time) / 1000) % 1000) + +/** @return apr_time_t as a msec */ +#define apr_time_as_msec(time) ((time) / 1000) + +/** @return milliseconds as an apr_time_t */ +#define apr_time_from_msec(msec) ((apr_time_t)(msec) * 1000) + +/** @return seconds as an apr_time_t */ +#define apr_time_from_sec(sec) ((apr_time_t)(sec) * APR_USEC_PER_SEC) + +/** @return a second and usec combination as an apr_time_t */ +#define apr_time_make(sec, usec) ((apr_time_t)(sec) * APR_USEC_PER_SEC \ + + (apr_time_t)(usec)) + +/** + * @return the current time + */ +APR_DECLARE(apr_time_t) apr_time_now(void); + +/** @see apr_time_exp_t */ +typedef struct apr_time_exp_t apr_time_exp_t; + +/** + * a structure similar to ANSI struct tm with the following differences: + * - tm_usec isn't an ANSI field + * - tm_gmtoff isn't an ANSI field (it's a BSDism) + */ +struct apr_time_exp_t { + /** microseconds past tm_sec */ + apr_int32_t tm_usec; + /** (0-61) seconds past tm_min */ + apr_int32_t tm_sec; + /** (0-59) minutes past tm_hour */ + apr_int32_t tm_min; + /** (0-23) hours past midnight */ + apr_int32_t tm_hour; + /** (1-31) day of the month */ + apr_int32_t tm_mday; + /** (0-11) month of the year */ + apr_int32_t tm_mon; + /** year since 1900 */ + apr_int32_t tm_year; + /** (0-6) days since Sunday */ + apr_int32_t tm_wday; + /** (0-365) days since January 1 */ + apr_int32_t tm_yday; + /** daylight saving time */ + apr_int32_t tm_isdst; + /** seconds east of UTC */ + apr_int32_t tm_gmtoff; +}; + +/* Delayed the include to avoid a circular reference */ +#include "apr_pools.h" + +/** + * Convert an ansi time_t to an apr_time_t + * @param result the resulting apr_time_t + * @param input the time_t to convert + */ +APR_DECLARE(apr_status_t) apr_time_ansi_put(apr_time_t *result, + time_t input); + +/** + * Convert a time to its human readable components using an offset + * from GMT. + * @param result the exploded time + * @param input the time to explode + * @param offs the number of seconds offset to apply + */ +APR_DECLARE(apr_status_t) apr_time_exp_tz(apr_time_exp_t *result, + apr_time_t input, + apr_int32_t offs); + +/** + * Convert a time to its human readable components (GMT). + * @param result the exploded time + * @param input the time to explode + */ +APR_DECLARE(apr_status_t) apr_time_exp_gmt(apr_time_exp_t *result, + apr_time_t input); + +/** + * Convert a time to its human readable components in the local timezone. + * @param result the exploded time + * @param input the time to explode + */ +APR_DECLARE(apr_status_t) apr_time_exp_lt(apr_time_exp_t *result, + apr_time_t input); + +/** + * Convert time value from human readable format to a numeric apr_time_t + * (elapsed microseconds since the epoch). + * @param result the resulting imploded time + * @param input the input exploded time + */ +APR_DECLARE(apr_status_t) apr_time_exp_get(apr_time_t *result, + apr_time_exp_t *input); + +/** + * Convert time value from human readable format to a numeric apr_time_t that + * always represents GMT. + * @param result the resulting imploded time + * @param input the input exploded time + */ +APR_DECLARE(apr_status_t) apr_time_exp_gmt_get(apr_time_t *result, + apr_time_exp_t *input); + +/** + * Sleep for the specified number of micro-seconds. + * @param t desired amount of time to sleep. + * @warning May sleep for longer than the specified time. + */ +APR_DECLARE(void) apr_sleep(apr_interval_time_t t); + +/** length of a RFC822 Date */ +#define APR_RFC822_DATE_LEN (30) +/** + * apr_rfc822_date formats dates in the RFC822 + * format in an efficient manner. It is a fixed length + * format which requires APR_RFC822_DATA_LEN bytes of storage, + * including the trailing NUL terminator. + * @param date_str String to write to. + * @param t the time to convert + */ +APR_DECLARE(apr_status_t) apr_rfc822_date(char *date_str, apr_time_t t); + +/** length of a CTIME date */ +#define APR_CTIME_LEN (25) +/** + * apr_ctime formats dates in the ctime() format + * in an efficient manner. It is a fixed length format + * and requires APR_CTIME_LEN bytes of storage including + * the trailing NUL terminator. + * Unlike ANSI/ISO C ctime(), apr_ctime() does not include + * a \\n at the end of the string. + * @param date_str String to write to. + * @param t the time to convert + */ +APR_DECLARE(apr_status_t) apr_ctime(char *date_str, apr_time_t t); + +/** + * Formats the exploded time according to the format specified + * @param s string to write to + * @param retsize The length of the returned string + * @param max The maximum length of the string + * @param format The format for the time string + * @param tm The time to convert + */ +APR_DECLARE(apr_status_t) apr_strftime(char *s, apr_size_t *retsize, + apr_size_t max, const char *format, + apr_time_exp_t *tm); + +/** + * Improve the clock resolution for the lifetime of the given pool. + * Generally this is only desirable on benchmarking and other very + * time-sensitive applications, and has no impact on most platforms. + * @param p The pool to associate the finer clock resolution + */ +APR_DECLARE(void) apr_time_clock_hires(apr_pool_t *p); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_TIME_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_uri.h b/c/dependencies/windows/apr/x64_debug/include/apr_uri.h new file mode 100644 index 00000000..02908a9d --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_uri.h @@ -0,0 +1,178 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_uri.h: External Interface of apr_uri.c + */ + +/** + * @file apr_uri.h + * @brief APR-UTIL URI Routines + */ + +#ifndef APR_URI_H +#define APR_URI_H + +#include "apu.h" + +#include "apr_network_io.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_URI URI + * @ingroup APR_Util + * @{ + */ + +#define APR_URI_FTP_DEFAULT_PORT 21 /**< default FTP port */ +#define APR_URI_SSH_DEFAULT_PORT 22 /**< default SSH port */ +#define APR_URI_TELNET_DEFAULT_PORT 23 /**< default telnet port */ +#define APR_URI_GOPHER_DEFAULT_PORT 70 /**< default Gopher port */ +#define APR_URI_HTTP_DEFAULT_PORT 80 /**< default HTTP port */ +#define APR_URI_POP_DEFAULT_PORT 110 /**< default POP port */ +#define APR_URI_NNTP_DEFAULT_PORT 119 /**< default NNTP port */ +#define APR_URI_IMAP_DEFAULT_PORT 143 /**< default IMAP port */ +#define APR_URI_PROSPERO_DEFAULT_PORT 191 /**< default Prospero port */ +#define APR_URI_WAIS_DEFAULT_PORT 210 /**< default WAIS port */ +#define APR_URI_LDAP_DEFAULT_PORT 389 /**< default LDAP port */ +#define APR_URI_HTTPS_DEFAULT_PORT 443 /**< default HTTPS port */ +#define APR_URI_RTSP_DEFAULT_PORT 554 /**< default RTSP port */ +#define APR_URI_SNEWS_DEFAULT_PORT 563 /**< default SNEWS port */ +#define APR_URI_ACAP_DEFAULT_PORT 674 /**< default ACAP port */ +#define APR_URI_NFS_DEFAULT_PORT 2049 /**< default NFS port */ +#define APR_URI_TIP_DEFAULT_PORT 3372 /**< default TIP port */ +#define APR_URI_SIP_DEFAULT_PORT 5060 /**< default SIP port */ + +/** Flags passed to unparse_uri_components(): */ +/** suppress "scheme://user\@site:port" */ +#define APR_URI_UNP_OMITSITEPART (1U<<0) +/** Just omit user */ +#define APR_URI_UNP_OMITUSER (1U<<1) +/** Just omit password */ +#define APR_URI_UNP_OMITPASSWORD (1U<<2) +/** omit "user:password\@" part */ +#define APR_URI_UNP_OMITUSERINFO (APR_URI_UNP_OMITUSER | \ + APR_URI_UNP_OMITPASSWORD) +/** Show plain text password (default: show XXXXXXXX) */ +#define APR_URI_UNP_REVEALPASSWORD (1U<<3) +/** Show "scheme://user\@site:port" only */ +#define APR_URI_UNP_OMITPATHINFO (1U<<4) +/** Omit the "?queryarg" from the path */ +#define APR_URI_UNP_OMITQUERY (1U<<5) + +/** @see apr_uri_t */ +typedef struct apr_uri_t apr_uri_t; + +/** + * A structure to encompass all of the fields in a uri + */ +struct apr_uri_t { + /** scheme ("http"/"ftp"/...) */ + char *scheme; + /** combined [user[:password]\@]host[:port] */ + char *hostinfo; + /** user name, as in http://user:passwd\@host:port/ */ + char *user; + /** password, as in http://user:passwd\@host:port/ */ + char *password; + /** hostname from URI (or from Host: header) */ + char *hostname; + /** port string (integer representation is in "port") */ + char *port_str; + /** the request path (or NULL if only scheme://host was given) */ + char *path; + /** Everything after a '?' in the path, if present */ + char *query; + /** Trailing "#fragment" string, if present */ + char *fragment; + + /** structure returned from gethostbyname() */ + struct hostent *hostent; + + /** The port number, numeric, valid only if port_str != NULL */ + apr_port_t port; + + /** has the structure been initialized */ + unsigned is_initialized:1; + + /** has the DNS been looked up yet */ + unsigned dns_looked_up:1; + /** has the dns been resolved yet */ + unsigned dns_resolved:1; +}; + +/* apr_uri.c */ +/** + * Return the default port for a given scheme. The schemes recognized are + * http, ftp, https, gopher, wais, nntp, snews, and prospero + * @param scheme_str The string that contains the current scheme + * @return The default port for this scheme + */ +APU_DECLARE(apr_port_t) apr_uri_port_of_scheme(const char *scheme_str); + +/** + * Unparse a apr_uri_t structure to an URI string. Optionally + * suppress the password for security reasons. + * @param p The pool to allocate out of + * @param uptr All of the parts of the uri + * @param flags How to unparse the uri. One of: + *
+ *    APR_URI_UNP_OMITSITEPART        Suppress "scheme://user\@site:port" 
+ *    APR_URI_UNP_OMITUSER            Just omit user 
+ *    APR_URI_UNP_OMITPASSWORD        Just omit password 
+ *    APR_URI_UNP_OMITUSERINFO        Omit "user:password\@" part
+ *    APR_URI_UNP_REVEALPASSWORD      Show plain text password (default: show XXXXXXXX)
+ *    APR_URI_UNP_OMITPATHINFO        Show "scheme://user\@site:port" only 
+ *    APR_URI_UNP_OMITQUERY           Omit "?queryarg" or "#fragment" 
+ * 
+ * @return The uri as a string + */ +APU_DECLARE(char *) apr_uri_unparse(apr_pool_t *p, + const apr_uri_t *uptr, + unsigned flags); + +/** + * Parse a given URI, fill in all supplied fields of a apr_uri_t + * structure. This eliminates the necessity of extracting host, port, + * path, query info repeatedly in the modules. + * @param p The pool to allocate out of + * @param uri The uri to parse + * @param uptr The apr_uri_t to fill out + * @return APR_SUCCESS for success or error code + */ +APU_DECLARE(apr_status_t) apr_uri_parse(apr_pool_t *p, const char *uri, + apr_uri_t *uptr); + +/** + * Special case for CONNECT parsing: it comes with the hostinfo part only + * @param p The pool to allocate out of + * @param hostinfo The hostinfo string to parse + * @param uptr The apr_uri_t to fill out + * @return APR_SUCCESS for success or error code + */ +APU_DECLARE(apr_status_t) apr_uri_parse_hostinfo(apr_pool_t *p, + const char *hostinfo, + apr_uri_t *uptr); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_URI_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_user.h b/c/dependencies/windows/apr/x64_debug/include/apr_user.h new file mode 100644 index 00000000..0e0a3ac5 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_user.h @@ -0,0 +1,158 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_USER_H +#define APR_USER_H + +/** + * @file apr_user.h + * @brief APR User ID Services + */ + +#include "apr.h" +#include "apr_errno.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_user User and Group ID Services + * @ingroup APR + * @{ + */ + +/** + * Structure for determining user ownership. + */ +#ifdef WIN32 +typedef PSID apr_uid_t; +#else +typedef uid_t apr_uid_t; +#endif + +/** + * Structure for determining group ownership. + */ +#ifdef WIN32 +typedef PSID apr_gid_t; +#else +typedef gid_t apr_gid_t; +#endif + +#if APR_HAS_USER + +/** + * Get the userid (and groupid) of the calling process + * @param userid Returns the user id + * @param groupid Returns the user's group id + * @param p The pool from which to allocate working space + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_uid_current(apr_uid_t *userid, + apr_gid_t *groupid, + apr_pool_t *p); + +/** + * Get the user name for a specified userid + * @param username Pointer to new string containing user name (on output) + * @param userid The userid + * @param p The pool from which to allocate the string + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_uid_name_get(char **username, apr_uid_t userid, + apr_pool_t *p); + +/** + * Get the userid (and groupid) for the specified username + * @param userid Returns the user id + * @param groupid Returns the user's group id + * @param username The username to look up + * @param p The pool from which to allocate working space + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_uid_get(apr_uid_t *userid, apr_gid_t *groupid, + const char *username, apr_pool_t *p); + +/** + * Get the home directory for the named user + * @param dirname Pointer to new string containing directory name (on output) + * @param username The named user + * @param p The pool from which to allocate the string + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_uid_homepath_get(char **dirname, + const char *username, + apr_pool_t *p); + +/** + * Compare two user identifiers for equality. + * @param left One uid to test + * @param right Another uid to test + * @return APR_SUCCESS if the apr_uid_t structures identify the same user, + * APR_EMISMATCH if not, APR_BADARG if an apr_uid_t is invalid. + * @remark This function is available only if APR_HAS_USER is defined. + */ +#if defined(WIN32) +APR_DECLARE(apr_status_t) apr_uid_compare(apr_uid_t left, apr_uid_t right); +#else +#define apr_uid_compare(left,right) (((left) == (right)) ? APR_SUCCESS : APR_EMISMATCH) +#endif + +/** + * Get the group name for a specified groupid + * @param groupname Pointer to new string containing group name (on output) + * @param groupid The groupid + * @param p The pool from which to allocate the string + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_gid_name_get(char **groupname, + apr_gid_t groupid, apr_pool_t *p); + +/** + * Get the groupid for a specified group name + * @param groupid Pointer to the group id (on output) + * @param groupname The group name to look up + * @param p The pool from which to allocate the string + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_gid_get(apr_gid_t *groupid, + const char *groupname, apr_pool_t *p); + +/** + * Compare two group identifiers for equality. + * @param left One gid to test + * @param right Another gid to test + * @return APR_SUCCESS if the apr_gid_t structures identify the same group, + * APR_EMISMATCH if not, APR_BADARG if an apr_gid_t is invalid. + * @remark This function is available only if APR_HAS_USER is defined. + */ +#if defined(WIN32) +APR_DECLARE(apr_status_t) apr_gid_compare(apr_gid_t left, apr_gid_t right); +#else +#define apr_gid_compare(left,right) (((left) == (right)) ? APR_SUCCESS : APR_EMISMATCH) +#endif + +#endif /* ! APR_HAS_USER */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_USER_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_uuid.h b/c/dependencies/windows/apr/x64_debug/include/apr_uuid.h new file mode 100644 index 00000000..5312a9f6 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_uuid.h @@ -0,0 +1,76 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_uuid.h + * @brief APR UUID library + */ +#ifndef APR_UUID_H +#define APR_UUID_H + +#include "apu.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_UUID UUID Handling + * @ingroup APR + * @{ + */ + +/** + * we represent a UUID as a block of 16 bytes. + */ + +typedef struct { + unsigned char data[16]; /**< the actual UUID */ +} apr_uuid_t; + +/** UUIDs are formatted as: 00112233-4455-6677-8899-AABBCCDDEEFF */ +#define APR_UUID_FORMATTED_LENGTH 36 + + +/** + * Generate and return a (new) UUID + * @param uuid The resulting UUID + */ +APU_DECLARE(void) apr_uuid_get(apr_uuid_t *uuid); + +/** + * Format a UUID into a string, following the standard format + * @param buffer The buffer to place the formatted UUID string into. It must + * be at least APR_UUID_FORMATTED_LENGTH + 1 bytes long to hold + * the formatted UUID and a null terminator + * @param uuid The UUID to format + */ +APU_DECLARE(void) apr_uuid_format(char *buffer, const apr_uuid_t *uuid); + +/** + * Parse a standard-format string into a UUID + * @param uuid The resulting UUID + * @param uuid_str The formatted UUID + */ +APU_DECLARE(apr_status_t) apr_uuid_parse(apr_uuid_t *uuid, const char *uuid_str); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_UUID_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_version.h b/c/dependencies/windows/apr/x64_debug/include/apr_version.h new file mode 100644 index 00000000..e96de383 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_version.h @@ -0,0 +1,164 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_VERSION_H +#define APR_VERSION_H + +/** + * @file apr_version.h + * @brief APR Versioning Interface + * + * APR's Version + * + * There are several different mechanisms for accessing the version. There + * is a string form, and a set of numbers; in addition, there are constants + * which can be compiled into your application, and you can query the library + * being used for its actual version. + * + * Note that it is possible for an application to detect that it has been + * compiled against a different version of APR by use of the compile-time + * constants and the use of the run-time query function. + * + * APR version numbering follows the guidelines specified in: + * + * http://apr.apache.org/versioning.html + */ + + +#define APR_COPYRIGHT "Copyright (c) 2000-2019 The Apache Software " \ + "Foundation or its licensors, as applicable." + +/* The numeric compile-time version constants. These constants are the + * authoritative version numbers for APR. + */ + +/** major version + * Major API changes that could cause compatibility problems for older + * programs such as structure size changes. No binary compatibility is + * possible across a change in the major version. + */ +#define APR_MAJOR_VERSION 1 + +/** minor version + * Minor API changes that do not cause binary compatibility problems. + * Reset to 0 when upgrading APR_MAJOR_VERSION + */ +#define APR_MINOR_VERSION 7 + +/** patch level + * The Patch Level never includes API changes, simply bug fixes. + * Reset to 0 when upgrading APR_MINOR_VERSION + */ +#define APR_PATCH_VERSION 0 + +/** + * The symbol APR_IS_DEV_VERSION is only defined for internal, + * "development" copies of APR. It is undefined for released versions + * of APR. + */ +/* #undef APR_IS_DEV_VERSION */ + +/** + * Check at compile time if the APR version is at least a certain + * level. + * @param major The major version component of the version checked + * for (e.g., the "1" of "1.3.0"). + * @param minor The minor version component of the version checked + * for (e.g., the "3" of "1.3.0"). + * @param patch The patch level component of the version checked + * for (e.g., the "0" of "1.3.0"). + * @remark This macro is available with APR versions starting with + * 1.3.0. + */ +#define APR_VERSION_AT_LEAST(major,minor,patch) \ +(((major) < APR_MAJOR_VERSION) \ + || ((major) == APR_MAJOR_VERSION && (minor) < APR_MINOR_VERSION) \ + || ((major) == APR_MAJOR_VERSION && (minor) == APR_MINOR_VERSION && (patch) <= APR_PATCH_VERSION)) + +#if defined(APR_IS_DEV_VERSION) || defined(DOXYGEN) +/** Internal: string form of the "is dev" flag */ +#ifndef APR_IS_DEV_STRING +#define APR_IS_DEV_STRING "-dev" +#endif +#else +#define APR_IS_DEV_STRING "" +#endif + +/* APR_STRINGIFY is defined here, and also in apr_general.h, so wrap it */ +#ifndef APR_STRINGIFY +/** Properly quote a value as a string in the C preprocessor */ +#define APR_STRINGIFY(n) APR_STRINGIFY_HELPER(n) +/** Helper macro for APR_STRINGIFY */ +#define APR_STRINGIFY_HELPER(n) #n +#endif + +/** The formatted string of APR's version */ +#define APR_VERSION_STRING \ + APR_STRINGIFY(APR_MAJOR_VERSION) "." \ + APR_STRINGIFY(APR_MINOR_VERSION) "." \ + APR_STRINGIFY(APR_PATCH_VERSION) \ + APR_IS_DEV_STRING + +/** An alternative formatted string of APR's version */ +/* macro for Win32 .rc files using numeric csv representation */ +#define APR_VERSION_STRING_CSV APR_MAJOR_VERSION ##, \ + ##APR_MINOR_VERSION ##, \ + ##APR_PATCH_VERSION + + +#ifndef APR_VERSION_ONLY + +/* The C language API to access the version at run time, + * as opposed to compile time. APR_VERSION_ONLY may be defined + * externally when preprocessing apr_version.h to obtain strictly + * the C Preprocessor macro declarations. + */ + +#include "apr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The numeric version information is broken out into fields within this + * structure. + */ +typedef struct { + int major; /**< major number */ + int minor; /**< minor number */ + int patch; /**< patch number */ + int is_dev; /**< is development (1 or 0) */ +} apr_version_t; + +/** + * Return APR's version information information in a numeric form. + * + * @param pvsn Pointer to a version structure for returning the version + * information. + */ +APR_DECLARE(void) apr_version(apr_version_t *pvsn); + +/** Return APR's version information as a string. */ +APR_DECLARE(const char *) apr_version_string(void); + +#ifdef __cplusplus +} +#endif + +#endif /* ndef APR_VERSION_ONLY */ + +#endif /* ndef APR_VERSION_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_want.h b/c/dependencies/windows/apr/x64_debug/include/apr_want.h new file mode 100644 index 00000000..2863b001 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_want.h @@ -0,0 +1,124 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr.h" /* configuration data */ +/** + * @file apr_want.h + * @brief APR Standard Headers Support + * + *
+ * Features:
+ *
+ *   APR_WANT_STRFUNC:  strcmp, strcat, strcpy, etc
+ *   APR_WANT_MEMFUNC:  memcmp, memcpy, etc
+ *   APR_WANT_STDIO:     and related bits
+ *   APR_WANT_IOVEC:    struct iovec
+ *   APR_WANT_BYTEFUNC: htons, htonl, ntohl, ntohs
+ *
+ * Typical usage:
+ *
+ *   \#define APR_WANT_STRFUNC
+ *   \#define APR_WANT_MEMFUNC
+ *   \#include "apr_want.h"
+ *
+ * The appropriate headers will be included.
+ *
+ * Note: it is safe to use this in a header (it won't interfere with other
+ *       headers' or source files' use of apr_want.h)
+ * 
+ */ + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_STRFUNC + +#if APR_HAVE_STRING_H +#include +#endif +#if APR_HAVE_STRINGS_H +#include +#endif + +#undef APR_WANT_STRFUNC +#endif + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_MEMFUNC + +#if APR_HAVE_STRING_H +#include +#endif + +#undef APR_WANT_MEMFUNC +#endif + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_STDIO + +#if APR_HAVE_STDIO_H +#include +#endif + +#undef APR_WANT_STDIO +#endif + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_IOVEC + +#if APR_HAVE_IOVEC + +#if APR_HAVE_SYS_UIO_H +#include +#endif + +#else + +#ifndef APR_IOVEC_DEFINED +#define APR_IOVEC_DEFINED +struct iovec +{ + void *iov_base; + size_t iov_len; +}; +#endif /* !APR_IOVEC_DEFINED */ + +#endif /* APR_HAVE_IOVEC */ + +#undef APR_WANT_IOVEC +#endif + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_BYTEFUNC + +/* Single Unix says they are in arpa/inet.h. Linux has them in + * netinet/in.h. FreeBSD has them in arpa/inet.h but requires that + * netinet/in.h be included first. + */ +#if APR_HAVE_NETINET_IN_H +#include +#endif +#if APR_HAVE_ARPA_INET_H +#include +#endif + +#undef APR_WANT_BYTEFUNC +#endif + +/* --------------------------------------------------------------------- */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_xlate.h b/c/dependencies/windows/apr/x64_debug/include/apr_xlate.h new file mode 100644 index 00000000..32636685 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_xlate.h @@ -0,0 +1,163 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_XLATE_H +#define APR_XLATE_H + +#include "apu.h" +#include "apr_pools.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @file apr_xlate.h + * @brief APR I18N translation library + */ + +/** + * @defgroup APR_XLATE I18N translation library + * @ingroup APR + * @{ + */ +/** Opaque translation buffer */ +typedef struct apr_xlate_t apr_xlate_t; + +/** + * Set up for converting text from one charset to another. + * @param convset The handle to be filled in by this function + * @param topage The name of the target charset + * @param frompage The name of the source charset + * @param pool The pool to use + * @remark + * Specify APR_DEFAULT_CHARSET for one of the charset + * names to indicate the charset of the source code at + * compile time. This is useful if there are literal + * strings in the source code which must be translated + * according to the charset of the source code. + * APR_DEFAULT_CHARSET is not useful if the source code + * of the caller was not encoded in the same charset as + * APR at compile time. + * + * @remark + * Specify APR_LOCALE_CHARSET for one of the charset + * names to indicate the charset of the current locale. + * + * @remark + * Return APR_EINVAL if unable to procure a convset, or APR_ENOTIMPL + * if charset transcoding is not available in this instance of + * apr-util at all (i.e., APR_HAS_XLATE is undefined). + */ +APU_DECLARE(apr_status_t) apr_xlate_open(apr_xlate_t **convset, + const char *topage, + const char *frompage, + apr_pool_t *pool); + +/** + * This is to indicate the charset of the sourcecode at compile time + * names to indicate the charset of the source code at + * compile time. This is useful if there are literal + * strings in the source code which must be translated + * according to the charset of the source code. + */ +#define APR_DEFAULT_CHARSET (const char *)0 +/** + * To indicate charset names of the current locale + */ +#define APR_LOCALE_CHARSET (const char *)1 + +/** + * Find out whether or not the specified conversion is single-byte-only. + * @param convset The handle allocated by apr_xlate_open, specifying the + * parameters of conversion + * @param onoff Output: whether or not the conversion is single-byte-only + * @remark + * Return APR_ENOTIMPL if charset transcoding is not available + * in this instance of apr-util (i.e., APR_HAS_XLATE is undefined). + */ +APU_DECLARE(apr_status_t) apr_xlate_sb_get(apr_xlate_t *convset, int *onoff); + +/** + * Convert a buffer of text from one codepage to another. + * @param convset The handle allocated by apr_xlate_open, specifying + * the parameters of conversion + * @param inbuf The address of the source buffer + * @param inbytes_left Input: the amount of input data to be translated + * Output: the amount of input data not yet translated + * @param outbuf The address of the destination buffer + * @param outbytes_left Input: the size of the output buffer + * Output: the amount of the output buffer not yet used + * @remark + * Returns APR_ENOTIMPL if charset transcoding is not available + * in this instance of apr-util (i.e., APR_HAS_XLATE is undefined). + * Returns APR_INCOMPLETE if the input buffer ends in an incomplete + * multi-byte character. + * + * To correctly terminate the output buffer for some multi-byte + * character set encodings, a final call must be made to this function + * after the complete input string has been converted, passing + * the inbuf and inbytes_left parameters as NULL. (Note that this + * mode only works from version 1.1.0 onwards) + */ +APU_DECLARE(apr_status_t) apr_xlate_conv_buffer(apr_xlate_t *convset, + const char *inbuf, + apr_size_t *inbytes_left, + char *outbuf, + apr_size_t *outbytes_left); + +/* @see apr_file_io.h the comment in apr_file_io.h about this hack */ +#ifdef APR_NOT_DONE_YET +/** + * The purpose of apr_xlate_conv_char is to translate one character + * at a time. This needs to be written carefully so that it works + * with double-byte character sets. + * @param convset The handle allocated by apr_xlate_open, specifying the + * parameters of conversion + * @param inchar The character to convert + * @param outchar The converted character + */ +APU_DECLARE(apr_status_t) apr_xlate_conv_char(apr_xlate_t *convset, + char inchar, char outchar); +#endif + +/** + * Convert a single-byte character from one charset to another. + * @param convset The handle allocated by apr_xlate_open, specifying the + * parameters of conversion + * @param inchar The single-byte character to convert. + * @warning This only works when converting between single-byte character sets. + * -1 will be returned if the conversion can't be performed. + */ +APU_DECLARE(apr_int32_t) apr_xlate_conv_byte(apr_xlate_t *convset, + unsigned char inchar); + +/** + * Close a codepage translation handle. + * @param convset The codepage translation handle to close + * @remark + * Return APR_ENOTIMPL if charset transcoding is not available + * in this instance of apr-util (i.e., APR_HAS_XLATE is undefined). + */ +APU_DECLARE(apr_status_t) apr_xlate_close(apr_xlate_t *convset); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_XLATE_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apr_xml.h b/c/dependencies/windows/apr/x64_debug/include/apr_xml.h new file mode 100644 index 00000000..87a696cc --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apr_xml.h @@ -0,0 +1,358 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file apr_xml.h + * @brief APR-UTIL XML Library + */ +#ifndef APR_XML_H +#define APR_XML_H + +/** + * @defgroup APR_Util_XML XML + * @ingroup APR_Util + * @{ + */ +#include "apr_pools.h" +#include "apr_tables.h" +#include "apr_file_io.h" + +#include "apu.h" +#if APR_CHARSET_EBCDIC +#include "apr_xlate.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @package Apache XML library + */ + +/* -------------------------------------------------------------------- */ + +/* ### these will need to move at some point to a more logical spot */ + +/** @see apr_text */ +typedef struct apr_text apr_text; + +/** Structure to keep a linked list of pieces of text */ +struct apr_text { + /** The current piece of text */ + const char *text; + /** a pointer to the next piece of text */ + struct apr_text *next; +}; + +/** @see apr_text_header */ +typedef struct apr_text_header apr_text_header; + +/** A list of pieces of text */ +struct apr_text_header { + /** The first piece of text in the list */ + apr_text *first; + /** The last piece of text in the list */ + apr_text *last; +}; + +/** + * Append a piece of text to the end of a list + * @param p The pool to allocate out of + * @param hdr The text header to append to + * @param text The new text to append + */ +APU_DECLARE(void) apr_text_append(apr_pool_t *p, apr_text_header *hdr, + const char *text); + + +/* -------------------------------------------------------------------- +** +** XML PARSING +*/ + +/* +** Qualified namespace values +** +** APR_XML_NS_DAV_ID +** We always insert the "DAV:" namespace URI at the head of the +** namespace array. This means that it will always be at ID==0, +** making it much easier to test for. +** +** APR_XML_NS_NONE +** This special ID is used for two situations: +** +** 1) The namespace prefix begins with "xml" (and we do not know +** what it means). Namespace prefixes with "xml" (any case) as +** their first three characters are reserved by the XML Namespaces +** specification for future use. mod_dav will pass these through +** unchanged. When this identifier is used, the prefix is LEFT in +** the element/attribute name. Downstream processing should not +** prepend another prefix. +** +** 2) The element/attribute does not have a namespace. +** +** a) No prefix was used, and a default namespace has not been +** defined. +** b) No prefix was used, and the default namespace was specified +** to mean "no namespace". This is done with a namespace +** declaration of: xmlns="" +** (this declaration is typically used to override a previous +** specification for the default namespace) +** +** In these cases, we need to record that the elem/attr has no +** namespace so that we will not attempt to prepend a prefix. +** All namespaces that are used will have a prefix assigned to +** them -- mod_dav will never set or use the default namespace +** when generating XML. This means that "no prefix" will always +** mean "no namespace". +** +** In both cases, the XML generation will avoid prepending a prefix. +** For the first case, this means the original prefix/name will be +** inserted into the output stream. For the latter case, it means +** the name will have no prefix, and since we never define a default +** namespace, this means it will have no namespace. +** +** Note: currently, mod_dav understands the "xmlns" prefix and the +** "xml:lang" attribute. These are handled specially (they aren't +** left within the XML tree), so the APR_XML_NS_NONE value won't ever +** really apply to these values. +*/ +#define APR_XML_NS_DAV_ID 0 /**< namespace ID for "DAV:" */ +#define APR_XML_NS_NONE -10 /**< no namespace for this elem/attr */ + +#define APR_XML_NS_ERROR_BASE -100 /**< used only during processing */ +/** Is this namespace an error? */ +#define APR_XML_NS_IS_ERROR(e) ((e) <= APR_XML_NS_ERROR_BASE) + +/** @see apr_xml_attr */ +typedef struct apr_xml_attr apr_xml_attr; +/** @see apr_xml_elem */ +typedef struct apr_xml_elem apr_xml_elem; +/** @see apr_xml_doc */ +typedef struct apr_xml_doc apr_xml_doc; + +/** apr_xml_attr: holds a parsed XML attribute */ +struct apr_xml_attr { + /** attribute name */ + const char *name; + /** index into namespace array */ + int ns; + + /** attribute value */ + const char *value; + + /** next attribute */ + struct apr_xml_attr *next; +}; + +/** apr_xml_elem: holds a parsed XML element */ +struct apr_xml_elem { + /** element name */ + const char *name; + /** index into namespace array */ + int ns; + /** xml:lang for attrs/contents */ + const char *lang; + + /** cdata right after start tag */ + apr_text_header first_cdata; + /** cdata after MY end tag */ + apr_text_header following_cdata; + + /** parent element */ + struct apr_xml_elem *parent; + /** next (sibling) element */ + struct apr_xml_elem *next; + /** first child element */ + struct apr_xml_elem *first_child; + /** first attribute */ + struct apr_xml_attr *attr; + + /* used only during parsing */ + /** last child element */ + struct apr_xml_elem *last_child; + /** namespaces scoped by this elem */ + struct apr_xml_ns_scope *ns_scope; + + /* used by modules during request processing */ + /** Place for modules to store private data */ + void *priv; +}; + +/** Is this XML element empty? */ +#define APR_XML_ELEM_IS_EMPTY(e) ((e)->first_child == NULL && \ + (e)->first_cdata.first == NULL) + +/** apr_xml_doc: holds a parsed XML document */ +struct apr_xml_doc { + /** root element */ + apr_xml_elem *root; + /** array of namespaces used */ + apr_array_header_t *namespaces; +}; + +/** Opaque XML parser structure */ +typedef struct apr_xml_parser apr_xml_parser; + +/** + * Create an XML parser + * @param pool The pool for allocating the parser and the parse results. + * @return The new parser. + */ +APU_DECLARE(apr_xml_parser *) apr_xml_parser_create(apr_pool_t *pool); + +/** + * Parse a File, producing a xml_doc + * @param p The pool for allocating the parse results. + * @param parser A pointer to *parser (needed so calling function can get + * errors), will be set to NULL on successful completion. + * @param ppdoc A pointer to *apr_xml_doc (which has the parsed results in it) + * @param xmlfd A file to read from. + * @param buffer_length Buffer length which would be suitable + * @return Any errors found during parsing. + */ +APU_DECLARE(apr_status_t) apr_xml_parse_file(apr_pool_t *p, + apr_xml_parser **parser, + apr_xml_doc **ppdoc, + apr_file_t *xmlfd, + apr_size_t buffer_length); + + +/** + * Feed input into the parser + * @param parser The XML parser for parsing this data. + * @param data The data to parse. + * @param len The length of the data. + * @return Any errors found during parsing. + * @remark Use apr_xml_parser_geterror() to get more error information. + */ +APU_DECLARE(apr_status_t) apr_xml_parser_feed(apr_xml_parser *parser, + const char *data, + apr_size_t len); + +/** + * Terminate the parsing and return the result + * @param parser The XML parser for parsing this data. + * @param pdoc The resulting parse information. May be NULL to simply + * terminate the parsing without fetching the info. + * @return Any errors found during the final stage of parsing. + * @remark Use apr_xml_parser_geterror() to get more error information. + */ +APU_DECLARE(apr_status_t) apr_xml_parser_done(apr_xml_parser *parser, + apr_xml_doc **pdoc); + +/** + * Fetch additional error information from the parser. + * @param parser The XML parser to query for errors. + * @param errbuf A buffer for storing error text. + * @param errbufsize The length of the error text buffer. + * @return The error buffer + */ +APU_DECLARE(char *) apr_xml_parser_geterror(apr_xml_parser *parser, + char *errbuf, + apr_size_t errbufsize); + + +/** + * Converts an XML element tree to flat text + * @param p The pool to allocate out of + * @param elem The XML element to convert + * @param style How to covert the XML. One of: + *
+ *     APR_XML_X2T_FULL                start tag, contents, end tag 
+ *     APR_XML_X2T_INNER               contents only 
+ *     APR_XML_X2T_LANG_INNER          xml:lang + inner contents 
+ *     APR_XML_X2T_FULL_NS_LANG        FULL + ns defns + xml:lang 
+ *     APR_XML_X2T_PARSED              original prefixes
+ * 
+ * @param namespaces The namespace of the current XML element + * @param ns_map Namespace mapping + * @param pbuf Buffer to put the converted text into + * @param psize Size of the converted text + */ +APU_DECLARE(void) apr_xml_to_text(apr_pool_t *p, const apr_xml_elem *elem, + int style, apr_array_header_t *namespaces, + int *ns_map, const char **pbuf, + apr_size_t *psize); + +/* style argument values: */ +#define APR_XML_X2T_FULL 0 /**< start tag, contents, end tag */ +#define APR_XML_X2T_INNER 1 /**< contents only */ +#define APR_XML_X2T_LANG_INNER 2 /**< xml:lang + inner contents */ +#define APR_XML_X2T_FULL_NS_LANG 3 /**< FULL + ns defns + xml:lang */ +#define APR_XML_X2T_PARSED 4 /**< original prefixes */ + +/** + * empty XML element + * @param p The pool to allocate out of + * @param elem The XML element to empty + * @return the string that was stored in the XML element + */ +APU_DECLARE(const char *) apr_xml_empty_elem(apr_pool_t *p, + const apr_xml_elem *elem); + +/** + * quote an XML string + * Replace '\<', '\>', and '\&' with '\<', '\>', and '\&'. + * @param p The pool to allocate out of + * @param s The string to quote + * @param quotes If quotes is true, then replace '"' with '\"'. + * @return The quoted string + * @note If the string does not contain special characters, it is not + * duplicated into the pool and the original string is returned. + */ +APU_DECLARE(const char *) apr_xml_quote_string(apr_pool_t *p, const char *s, + int quotes); + +/** + * Quote an XML element + * @param p The pool to allocate out of + * @param elem The element to quote + */ +APU_DECLARE(void) apr_xml_quote_elem(apr_pool_t *p, apr_xml_elem *elem); + +/* manage an array of unique URIs: apr_xml_insert_uri() and APR_XML_URI_ITEM() */ + +/** + * return the URI's (existing) index, or insert it and return a new index + * @param uri_array array to insert into + * @param uri The uri to insert + * @return int The uri's index + */ +APU_DECLARE(int) apr_xml_insert_uri(apr_array_header_t *uri_array, + const char *uri); + +/** Get the URI item for this XML element */ +#define APR_XML_GET_URI_ITEM(ary, i) (((const char * const *)(ary)->elts)[i]) + +#if APR_CHARSET_EBCDIC +/** + * Convert parsed tree in EBCDIC + * @param p The pool to allocate out of + * @param pdoc The apr_xml_doc to convert. + * @param xlate The translation handle to use. + * @return Any errors found during conversion. + */ +APU_DECLARE(apr_status_t) apr_xml_parser_convert_doc(apr_pool_t *p, + apr_xml_doc *pdoc, + apr_xlate_t *convset); +#endif + +#ifdef __cplusplus +} +#endif +/** @} */ +#endif /* APR_XML_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apu.h b/c/dependencies/windows/apr/x64_debug/include/apu.h new file mode 100644 index 00000000..21fbedff --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apu.h @@ -0,0 +1,146 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apu.h is duplicated from apu.hw at build time -- do not edit apu.h + */ +/* @file apu.h + * @brief APR-Utility main file + */ +/** + * @defgroup APR_Util APR Utility Functions + * @{ + */ + + +#ifndef APU_H +#define APU_H + +/** + * APU_DECLARE_EXPORT is defined when building the APR-UTIL dynamic library, + * so that all public symbols are exported. + * + * APU_DECLARE_STATIC is defined when including the APR-UTIL public headers, + * to provide static linkage when the dynamic library may be unavailable. + * + * APU_DECLARE_STATIC and APU_DECLARE_EXPORT are left undefined when + * including the APR-UTIL public headers, to import and link the symbols from + * the dynamic APR-UTIL library and assure appropriate indirection and calling + * conventions at compile time. + */ + +/* Make sure we have our platform identifier macro defined we ask for later. + */ +#if defined(_WIN32) && !defined(WIN32) +#define WIN32 1 +#endif + +#if defined(DOXYGEN) || !defined(WIN32) +/** + * The public APR-UTIL functions are declared with APU_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APU_DECLARE_NONSTD(). + * + * @fn APU_DECLARE(rettype) apr_func(args); + */ +#define APU_DECLARE(type) type +/** + * The public APR-UTIL functions using variable arguments are declared with + * APU_DECLARE_NONSTD(), as they must use the C language calling convention. + * + * @fn APU_DECLARE_NONSTD(rettype) apr_func(args, ...); + */ +#define APU_DECLARE_NONSTD(type) type +/** + * The public APR-UTIL variables are declared with APU_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * + * @fn APU_DECLARE_DATA type apr_variable; + * @note extern APU_DECLARE_DATA type apr_variable; syntax is required for + * declarations within headers to properly import the variable. + */ +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_STATIC) +#define APU_DECLARE(type) type __stdcall +#define APU_DECLARE_NONSTD(type) type __cdecl +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_EXPORT) +#define APU_DECLARE(type) __declspec(dllexport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllexport) +#else +#define APU_DECLARE(type) __declspec(dllimport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllimport) +#endif + +#if !defined(WIN32) || defined(APU_MODULE_DECLARE_STATIC) +/** + * Declare a dso module's exported module structure as APU_MODULE_DECLARE_DATA. + * + * Unless APU_MODULE_DECLARE_STATIC is defined at compile time, symbols + * declared with APU_MODULE_DECLARE_DATA are always exported. + * @code + * module APU_MODULE_DECLARE_DATA mod_tag + * @endcode + */ +#define APU_MODULE_DECLARE_DATA +#else +#define APU_MODULE_DECLARE_DATA __declspec(dllexport) +#endif + +/* + * we always have SDBM (it's in our codebase) + */ +#define APU_HAVE_SDBM 1 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_GDBM 0 +#define APU_HAVE_NDBM 0 +#define APU_HAVE_DB 0 + +#if APU_HAVE_DB +#define APU_HAVE_DB_VERSION 0 +#endif +#endif + +/* + * we always enable dynamic driver loads within apr_dbd + * Win32 always has odbc (it's always installed) + */ +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_PGSQL 0 +#define APU_HAVE_MYSQL 0 +#define APU_HAVE_SQLITE3 0 +#define APU_HAVE_SQLITE2 0 +#define APU_HAVE_ORACLE 0 +#define APU_HAVE_ODBC 1 +#endif + +#define APU_HAVE_CRYPTO 0 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_OPENSSL 0 +#define APU_HAVE_NSS 0 +#define APU_HAVE_COMMONCRYPTO 0 +#endif + +#define APU_HAVE_APR_ICONV 1 +#define APU_HAVE_ICONV 0 +#define APR_HAS_XLATE (APU_HAVE_APR_ICONV || APU_HAVE_ICONV) + +#endif /* APU_H */ +/** @} */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apu.h.in b/c/dependencies/windows/apr/x64_debug/include/apu.h.in new file mode 100644 index 00000000..0781a6a0 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apu.h.in @@ -0,0 +1,128 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apu.h is generated from apu.h.in by configure -- do not edit apu.h + */ +/* @file apu.h + * @brief APR-Utility main file + */ +/** + * @defgroup APR_Util APR Utility Functions + * @{ + */ + + +#ifndef APU_H +#define APU_H + +/** + * APU_DECLARE_EXPORT is defined when building the APR-UTIL dynamic library, + * so that all public symbols are exported. + * + * APU_DECLARE_STATIC is defined when including the APR-UTIL public headers, + * to provide static linkage when the dynamic library may be unavailable. + * + * APU_DECLARE_STATIC and APU_DECLARE_EXPORT are left undefined when + * including the APR-UTIL public headers, to import and link the symbols from + * the dynamic APR-UTIL library and assure appropriate indirection and calling + * conventions at compile time. + */ + +#if defined(DOXYGEN) || !defined(WIN32) +/** + * The public APR-UTIL functions are declared with APU_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APU_DECLARE_NONSTD(). + * + * @fn APU_DECLARE(rettype) apr_func(args); + */ +#define APU_DECLARE(type) type +/** + * The public APR-UTIL functions using variable arguments are declared with + * APU_DECLARE_NONSTD(), as they must use the C language calling convention. + * + * @fn APU_DECLARE_NONSTD(rettype) apr_func(args, ...); + */ +#define APU_DECLARE_NONSTD(type) type +/** + * The public APR-UTIL variables are declared with APU_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * + * @fn APU_DECLARE_DATA type apr_variable; + * @note APU_DECLARE_DATA extern type apr_variable; syntax is required for + * declarations within headers to properly import the variable. + */ +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_STATIC) +#define APU_DECLARE(type) type __stdcall +#define APU_DECLARE_NONSTD(type) type __cdecl +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_EXPORT) +#define APU_DECLARE(type) __declspec(dllexport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllexport) +#else +#define APU_DECLARE(type) __declspec(dllimport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllimport) +#endif + +#if !defined(WIN32) || defined(APU_MODULE_DECLARE_STATIC) +/** + * Declare a dso module's exported module structure as APU_MODULE_DECLARE_DATA. + * + * Unless APU_MODULE_DECLARE_STATIC is defined at compile time, symbols + * declared with APU_MODULE_DECLARE_DATA are always exported. + * @code + * module APU_MODULE_DECLARE_DATA mod_tag + * @endcode + */ +#define APU_MODULE_DECLARE_DATA +#else +#define APU_MODULE_DECLARE_DATA __declspec(dllexport) +#endif + +/* + * we always have SDBM (it's in our codebase) + */ +#define APU_HAVE_SDBM @apu_have_sdbm@ +#define APU_HAVE_GDBM @apu_have_gdbm@ +#define APU_HAVE_NDBM @apu_have_ndbm@ +#define APU_HAVE_DB @apu_have_db@ + +#if APU_HAVE_DB +#define APU_HAVE_DB_VERSION @apu_db_version@ +#endif + +#define APU_HAVE_PGSQL @apu_have_pgsql@ +#define APU_HAVE_MYSQL @apu_have_mysql@ +#define APU_HAVE_SQLITE3 @apu_have_sqlite3@ +#define APU_HAVE_SQLITE2 @apu_have_sqlite2@ +#define APU_HAVE_ORACLE @apu_have_oracle@ +#define APU_HAVE_ODBC @apu_have_odbc@ + +#define APU_HAVE_CRYPTO @apu_have_crypto@ +#define APU_HAVE_OPENSSL @apu_have_openssl@ +#define APU_HAVE_NSS @apu_have_nss@ +#define APU_HAVE_COMMONCRYPTO @apu_have_commoncrypto@ + +#define APU_HAVE_APR_ICONV @have_apr_iconv@ +#define APU_HAVE_ICONV @have_iconv@ +#define APR_HAS_XLATE (APU_HAVE_APR_ICONV || APU_HAVE_ICONV) + +#endif /* APU_H */ +/** @} */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apu.hnw b/c/dependencies/windows/apr/x64_debug/include/apu.hnw new file mode 100644 index 00000000..12e73818 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apu.hnw @@ -0,0 +1,124 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Note: This is a NetWare specific version of apu.h. It is renamed to + * apu.h at the start of a NetWare build. + */ +/* @file apu.h + * @brief APR-Utility main file + */ + +#ifdef NETWARE +#ifndef APU_H +#define APU_H +/** + * @defgroup APR_Util APR Utility Functions + * @{ + */ + + +/** + * APU_DECLARE_EXPORT is defined when building the APR-UTIL dynamic library, + * so that all public symbols are exported. + * + * APU_DECLARE_STATIC is defined when including the APR-UTIL public headers, + * to provide static linkage when the dynamic library may be unavailable. + * + * APU_DECLARE_STATIC and APU_DECLARE_EXPORT are left undefined when + * including the APR-UTIL public headers, to import and link the symbols from + * the dynamic APR-UTIL library and assure appropriate indirection and calling + * conventions at compile time. + */ + +/** + * The public APR-UTIL functions are declared with APU_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APU_DECLARE_NONSTD(). + * + * @fn APU_DECLARE(rettype) apr_func(args); + */ +#define APU_DECLARE(type) type +/** + * The public APR-UTIL functions using variable arguments are declared with + * APU_DECLARE_NONSTD(), as they must use the C language calling convention. + * + * @fn APU_DECLARE_NONSTD(rettype) apr_func(args, ...); + */ +#define APU_DECLARE_NONSTD(type) type +/** + * The public APR-UTIL variables are declared with APU_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * + * @fn APU_DECLARE_DATA type apr_variable; + * @note APU_DECLARE_DATA extern type apr_variable; syntax is required for + * declarations within headers to properly import the variable. + */ +#define APU_DECLARE_DATA + +/** + * Declare a dso module's exported module structure as APU_MODULE_DECLARE_DATA. + * + * Unless APU_MODULE_DECLARE_STATIC is defined at compile time, symbols + * declared with APU_MODULE_DECLARE_DATA are always exported. + * @code + * module APU_MODULE_DECLARE_DATA mod_tag + * @endcode + */ +#define APU_MODULE_DECLARE_DATA + +/* + * we always have SDBM (it's in our codebase) + */ +#define APU_HAVE_SDBM 1 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_GDBM 0 +#define APU_HAVE_NDBM 0 +#define APU_HAVE_DB 0 + +#if APU_HAVE_DB +#define APU_HAVE_DB_VERSION 0 +#endif +#endif + +/* + * we always enable dynamic driver loads within apr_dbd + */ +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_PGSQL 0 +#define APU_HAVE_MYSQL 0 +#define APU_HAVE_SQLITE3 0 +#define APU_HAVE_SQLITE2 0 +#define APU_HAVE_ORACLE 0 +#define APU_HAVE_ODBC 0 +#endif + +#define APU_HAVE_CRYPTO 0 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_OPENSSL 0 +#define APU_HAVE_NSS 0 +#define APU_HAVE_COMMONCRYPTO 0 +#endif + +#define APU_HAVE_APR_ICONV 0 +#define APU_HAVE_ICONV 1 +#define APR_HAS_XLATE (APU_HAVE_APR_ICONV || APU_HAVE_ICONV) + +#endif /* APU_H */ +#endif /* NETWARE */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/apu.hw b/c/dependencies/windows/apr/x64_debug/include/apu.hw new file mode 100644 index 00000000..a501d5d7 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apu.hw @@ -0,0 +1,146 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apu.h is duplicated from apu.hw at build time -- do not edit apu.h + */ +/* @file apu.h + * @brief APR-Utility main file + */ +/** + * @defgroup APR_Util APR Utility Functions + * @{ + */ + + +#ifndef APU_H +#define APU_H + +/** + * APU_DECLARE_EXPORT is defined when building the APR-UTIL dynamic library, + * so that all public symbols are exported. + * + * APU_DECLARE_STATIC is defined when including the APR-UTIL public headers, + * to provide static linkage when the dynamic library may be unavailable. + * + * APU_DECLARE_STATIC and APU_DECLARE_EXPORT are left undefined when + * including the APR-UTIL public headers, to import and link the symbols from + * the dynamic APR-UTIL library and assure appropriate indirection and calling + * conventions at compile time. + */ + +/* Make sure we have our platform identifier macro defined we ask for later. + */ +#if defined(_WIN32) && !defined(WIN32) +#define WIN32 1 +#endif + +#if defined(DOXYGEN) || !defined(WIN32) +/** + * The public APR-UTIL functions are declared with APU_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APU_DECLARE_NONSTD(). + * + * @fn APU_DECLARE(rettype) apr_func(args); + */ +#define APU_DECLARE(type) type +/** + * The public APR-UTIL functions using variable arguments are declared with + * APU_DECLARE_NONSTD(), as they must use the C language calling convention. + * + * @fn APU_DECLARE_NONSTD(rettype) apr_func(args, ...); + */ +#define APU_DECLARE_NONSTD(type) type +/** + * The public APR-UTIL variables are declared with APU_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * + * @fn APU_DECLARE_DATA type apr_variable; + * @note extern APU_DECLARE_DATA type apr_variable; syntax is required for + * declarations within headers to properly import the variable. + */ +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_STATIC) +#define APU_DECLARE(type) type __stdcall +#define APU_DECLARE_NONSTD(type) type __cdecl +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_EXPORT) +#define APU_DECLARE(type) __declspec(dllexport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllexport) +#else +#define APU_DECLARE(type) __declspec(dllimport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllimport) +#endif + +#if !defined(WIN32) || defined(APU_MODULE_DECLARE_STATIC) +/** + * Declare a dso module's exported module structure as APU_MODULE_DECLARE_DATA. + * + * Unless APU_MODULE_DECLARE_STATIC is defined at compile time, symbols + * declared with APU_MODULE_DECLARE_DATA are always exported. + * @code + * module APU_MODULE_DECLARE_DATA mod_tag + * @endcode + */ +#define APU_MODULE_DECLARE_DATA +#else +#define APU_MODULE_DECLARE_DATA __declspec(dllexport) +#endif + +/* + * we always have SDBM (it's in our codebase) + */ +#define APU_HAVE_SDBM 1 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_GDBM 0 +#define APU_HAVE_NDBM 0 +#define APU_HAVE_DB 0 + +#if APU_HAVE_DB +#define APU_HAVE_DB_VERSION 0 +#endif +#endif + +/* + * we always enable dynamic driver loads within apr_dbd + * Win32 always has odbc (it's always installed) + */ +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_PGSQL 0 +#define APU_HAVE_MYSQL 0 +#define APU_HAVE_SQLITE3 0 +#define APU_HAVE_SQLITE2 0 +#define APU_HAVE_ORACLE 0 +#define APU_HAVE_ODBC 1 +#endif + +#define APU_HAVE_CRYPTO 0 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_OPENSSL 0 +#define APU_HAVE_NSS 0 +#define APU_HAVE_COMMONCRYPTO 0 +#endif + +#define APU_HAVE_APR_ICONV 1 +#define APU_HAVE_ICONV 0 +#define APR_HAS_XLATE (APU_HAVE_APR_ICONV || APU_HAVE_ICONV) + +#endif /* APU_H */ +/** @} */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apu.hwc b/c/dependencies/windows/apr/x64_debug/include/apu.hwc new file mode 100644 index 00000000..a663ec3e --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apu.hwc @@ -0,0 +1,145 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apu.h is duplicated from apu.hwc at build time -- do not edit apu.h + */ +/* @file apu.h + * @brief APR-Utility main file + */ +/** + * @defgroup APR_Util APR Utility Functions + * @{ + */ + + +#ifndef APU_H +#define APU_H + +/** + * APU_DECLARE_EXPORT is defined when building the APR-UTIL dynamic library, + * so that all public symbols are exported. + * + * APU_DECLARE_STATIC is defined when including the APR-UTIL public headers, + * to provide static linkage when the dynamic library may be unavailable. + * + * APU_DECLARE_STATIC and APU_DECLARE_EXPORT are left undefined when + * including the APR-UTIL public headers, to import and link the symbols from + * the dynamic APR-UTIL library and assure appropriate indirection and calling + * conventions at compile time. + */ + +/* Make sure we have our platform identifier macro defined we ask for later. + */ +#if defined(_WIN32) && !defined(WIN32) +#define WIN32 1 +#endif + +#if defined(DOXYGEN) || !defined(WIN32) +/** + * The public APR-UTIL functions are declared with APU_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APU_DECLARE_NONSTD(). + * + * @fn APU_DECLARE(rettype) apr_func(args); + */ +#define APU_DECLARE(type) type +/** + * The public APR-UTIL functions using variable arguments are declared with + * APU_DECLARE_NONSTD(), as they must use the C language calling convention. + * + * @fn APU_DECLARE_NONSTD(rettype) apr_func(args, ...); + */ +#define APU_DECLARE_NONSTD(type) type +/** + * The public APR-UTIL variables are declared with APU_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * + * @fn APU_DECLARE_DATA type apr_variable; + * @note extern APU_DECLARE_DATA type apr_variable; syntax is required for + * declarations within headers to properly import the variable. + */ +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_STATIC) +#define APU_DECLARE(type) type __stdcall +#define APU_DECLARE_NONSTD(type) type __cdecl +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_EXPORT) +#define APU_DECLARE(type) __declspec(dllexport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllexport) +#else +#define APU_DECLARE(type) __declspec(dllimport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllimport) +#endif + +#if !defined(WIN32) || defined(APU_MODULE_DECLARE_STATIC) +/** + * Declare a dso module's exported module structure as APU_MODULE_DECLARE_DATA. + * + * Unless APU_MODULE_DECLARE_STATIC is defined at compile time, symbols + * declared with APU_MODULE_DECLARE_DATA are always exported. + * @code + * module APU_MODULE_DECLARE_DATA mod_tag + * @endcode + */ +#define APU_MODULE_DECLARE_DATA +#else +#define APU_MODULE_DECLARE_DATA __declspec(dllexport) +#endif + +/* + * we always have SDBM (it's in our codebase) + */ +#define APU_HAVE_SDBM 1 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_GDBM 0 +#define APU_HAVE_NDBM 0 +#define APU_HAVE_DB 0 + +#if APU_HAVE_DB +#define APU_HAVE_DB_VERSION 0 +#endif +#endif + +/* + * we always enable dynamic driver loads within apr_dbd + * Win32 always has odbc (it's always installed) + */ +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_PGSQL 0 +#define APU_HAVE_MYSQL 0 +#define APU_HAVE_SQLITE3 0 +#define APU_HAVE_SQLITE2 0 +#define APU_HAVE_ORACLE 0 +#define APU_HAVE_ODBC 1 +#endif + +#define APU_HAVE_CRYPTO @apu_have_crypto_10@ + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_OPENSSL 0 +#define APU_HAVE_NSS 0 +#endif + +#define APU_HAVE_APR_ICONV @apu_have_apr_iconv_10@ +#define APU_HAVE_ICONV 0 +#define APR_HAS_XLATE (APU_HAVE_APR_ICONV || APU_HAVE_ICONV) + +#endif /* APU_H */ +/** @} */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apu_errno.h b/c/dependencies/windows/apr/x64_debug/include/apu_errno.h new file mode 100644 index 00000000..c0a8ec7d --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apu_errno.h @@ -0,0 +1,173 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APU_ERRNO_H +#define APU_ERRNO_H + +/** + * @file apu_errno.h + * @brief APR-Util Error Codes + */ + +#include "apr.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apu_errno Error Codes + * @ingroup APR_Util + * @{ + */ + +/** + * @defgroup APR_Util_Error APR_Util Error Values + *
+ * APU ERROR VALUES
+ * APR_ENOKEY         The key provided was empty or NULL
+ * APR_ENOIV          The initialisation vector provided was NULL
+ * APR_EKEYTYPE       The key type was not recognised
+ * APR_ENOSPACE       The buffer supplied was not big enough
+ * APR_ECRYPT         An error occurred while encrypting or decrypting
+ * APR_EPADDING       Padding was not supported
+ * APR_EKEYLENGTH     The key length was incorrect
+ * APR_ENOCIPHER      The cipher provided was not recognised
+ * APR_ENODIGEST      The digest provided was not recognised
+ * APR_ENOENGINE      The engine provided was not recognised
+ * APR_EINITENGINE    The engine could not be initialised
+ * APR_EREINIT        Underlying crypto has already been initialised
+ * 
+ * + *
+ * APR STATUS VALUES
+ * APR_INCHILD        Program is currently executing in the child
+ * 
+ * @{ + */ +/** @see APR_STATUS_IS_ENOKEY */ +#define APR_ENOKEY (APR_UTIL_START_STATUS + 1) +/** @see APR_STATUS_IS_ENOIV */ +#define APR_ENOIV (APR_UTIL_START_STATUS + 2) +/** @see APR_STATUS_IS_EKEYTYPE */ +#define APR_EKEYTYPE (APR_UTIL_START_STATUS + 3) +/** @see APR_STATUS_IS_ENOSPACE */ +#define APR_ENOSPACE (APR_UTIL_START_STATUS + 4) +/** @see APR_STATUS_IS_ECRYPT */ +#define APR_ECRYPT (APR_UTIL_START_STATUS + 5) +/** @see APR_STATUS_IS_EPADDING */ +#define APR_EPADDING (APR_UTIL_START_STATUS + 6) +/** @see APR_STATUS_IS_EKEYLENGTH */ +#define APR_EKEYLENGTH (APR_UTIL_START_STATUS + 7) +/** @see APR_STATUS_IS_ENOCIPHER */ +#define APR_ENOCIPHER (APR_UTIL_START_STATUS + 8) +/** @see APR_STATUS_IS_ENODIGEST */ +#define APR_ENODIGEST (APR_UTIL_START_STATUS + 9) +/** @see APR_STATUS_IS_ENOENGINE */ +#define APR_ENOENGINE (APR_UTIL_START_STATUS + 10) +/** @see APR_STATUS_IS_EINITENGINE */ +#define APR_EINITENGINE (APR_UTIL_START_STATUS + 11) +/** @see APR_STATUS_IS_EREINIT */ +#define APR_EREINIT (APR_UTIL_START_STATUS + 12) +/** @} */ + +/** + * @defgroup APU_STATUS_IS Status Value Tests + * @warning For any particular error condition, more than one of these tests + * may match. This is because platform-specific error codes may not + * always match the semantics of the POSIX codes these tests (and the + * corresponding APR error codes) are named after. A notable example + * are the APR_STATUS_IS_ENOENT and APR_STATUS_IS_ENOTDIR tests on + * Win32 platforms. The programmer should always be aware of this and + * adjust the order of the tests accordingly. + * @{ + */ + +/** @} */ + +/** + * @addtogroup APR_Util_Error + * @{ + */ +/** + * The key was empty or not provided + */ +#define APR_STATUS_IS_ENOKEY(s) ((s) == APR_ENOKEY) +/** + * The initialisation vector was not provided + */ +#define APR_STATUS_IS_ENOIV(s) ((s) == APR_ENOIV) +/** + * The key type was not recognised + */ +#define APR_STATUS_IS_EKEYTYPE(s) ((s) == APR_EKEYTYPE) +/** + * The buffer provided was not big enough + */ +#define APR_STATUS_IS_ENOSPACE(s) ((s) == APR_ENOSPACE) +/** + * An error occurred while encrypting or decrypting + */ +#define APR_STATUS_IS_ECRYPT(s) ((s) == APR_ECRYPT) +/** + * An error occurred while padding + */ +#define APR_STATUS_IS_EPADDING(s) ((s) == APR_EPADDING) +/** + * An error occurred with the key length + */ +#define APR_STATUS_IS_EKEYLENGTH(s) ((s) == APR_EKEYLENGTH) +/** + * The cipher provided was not recognised + */ +#define APR_STATUS_IS_ENOCIPHER(s) ((s) == APR_ENOCIPHER) +/** + * The digest provided was not recognised + */ +#define APR_STATUS_IS_ENODIGEST(s) ((s) == APR_ENODIGEST) +/** + * The engine provided was not recognised + */ +#define APR_STATUS_IS_ENOENGINE(s) ((s) == APR_ENOENGINE) +/** + * The engine could not be initialised + */ +#define APR_STATUS_IS_EINITENGINE(s) ((s) == APR_EINITENGINE) +/** + * Crypto has already been initialised + */ +#define APR_STATUS_IS_EREINIT(s) ((s) == APR_EREINIT) +/** @} */ + +/** + * This structure allows the underlying API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apu_err_t { + const char *reason; + const char *msg; + int rc; +} apu_err_t; + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APU_ERRNO_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apu_version.h b/c/dependencies/windows/apr/x64_debug/include/apu_version.h new file mode 100644 index 00000000..e4fb2e64 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apu_version.h @@ -0,0 +1,139 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APU_VERSION_H +#define APU_VERSION_H + +/** + * @file apu_version.h + * @brief APR-util Versioning Interface + * + * APR-util's Version + * + * There are several different mechanisms for accessing the version. There + * is a string form, and a set of numbers; in addition, there are constants + * which can be compiled into your application, and you can query the library + * being used for its actual version. + * + * Note that it is possible for an application to detect that it has been + * compiled against a different version of APU by use of the compile-time + * constants and the use of the run-time query function. + * + * APU version numbering follows the guidelines specified in: + * + * http://apr.apache.org/versioning.html + */ + + +#define APU_COPYRIGHT "Copyright (c) 2000-2016 The Apache Software " \ + "Foundation or its licensors, as applicable." + +/* The numeric compile-time version constants. These constants are the + * authoritative version numbers for APU. + */ + +/** major version + * Major API changes that could cause compatibility problems for older + * programs such as structure size changes. No binary compatibility is + * possible across a change in the major version. + */ +#define APU_MAJOR_VERSION 1 + +/** minor version + * Minor API changes that do not cause binary compatibility problems. + * Reset to 0 when upgrading APU_MAJOR_VERSION + */ +#define APU_MINOR_VERSION 6 + +/** patch level + * The Patch Level never includes API changes, simply bug fixes. + * Reset to 0 when upgrading APR_MINOR_VERSION + */ +#define APU_PATCH_VERSION 1 + +/** + * The symbol APU_IS_DEV_VERSION is only defined for internal, + * "development" copies of APU. It is undefined for released versions + * of APU. + */ +/* #undef APU_IS_DEV_VERSION */ + + +#if defined(APU_IS_DEV_VERSION) || defined(DOXYGEN) +/** Internal: string form of the "is dev" flag */ +#ifndef APU_IS_DEV_STRING +#define APU_IS_DEV_STRING "-dev" +#endif +#else +#define APU_IS_DEV_STRING "" +#endif + + +#ifndef APU_STRINGIFY +/** Properly quote a value as a string in the C preprocessor */ +#define APU_STRINGIFY(n) APU_STRINGIFY_HELPER(n) +/** Helper macro for APU_STRINGIFY */ +#define APU_STRINGIFY_HELPER(n) #n +#endif + +/** The formatted string of APU's version */ +#define APU_VERSION_STRING \ + APU_STRINGIFY(APU_MAJOR_VERSION) "." \ + APU_STRINGIFY(APU_MINOR_VERSION) "." \ + APU_STRINGIFY(APU_PATCH_VERSION) \ + APU_IS_DEV_STRING + +/** An alternative formatted string of APR's version */ +/* macro for Win32 .rc files using numeric csv representation */ +#define APU_VERSION_STRING_CSV APU_MAJOR_VERSION ##, \ + ##APU_MINOR_VERSION ##, \ + ##APU_PATCH_VERSION + + +#ifndef APU_VERSION_ONLY + +/* The C language API to access the version at run time, + * as opposed to compile time. APU_VERSION_ONLY may be defined + * externally when preprocessing apr_version.h to obtain strictly + * the C Preprocessor macro declarations. + */ + +#include "apr_version.h" + +#include "apu.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Return APR-util's version information information in a numeric form. + * + * @param pvsn Pointer to a version structure for returning the version + * information. + */ +APU_DECLARE(void) apu_version(apr_version_t *pvsn); + +/** Return APU's version information as a string. */ +APU_DECLARE(const char *) apu_version_string(void); + +#ifdef __cplusplus +} +#endif + +#endif /* ndef APU_VERSION_ONLY */ + +#endif /* ndef APU_VERSION_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apu_want.h b/c/dependencies/windows/apr/x64_debug/include/apu_want.h new file mode 100644 index 00000000..8bb56ce7 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apu_want.h @@ -0,0 +1,52 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apu.h" /* configuration data */ + +/** + * @file apu_want.h + * @brief APR Standard Headers Support + * + *
+ * Features:
+ *
+ *   APU_WANT_DB:       
+ *
+ * Typical usage:
+ *
+ *   #define APU_WANT_DB
+ *   #include "apu_want.h"
+ *
+ * The appropriate headers will be included.
+ *
+ * Note: it is safe to use this in a header (it won't interfere with other
+ *       headers' or source files' use of apu_want.h)
+ * 
+ */ + +/* --------------------------------------------------------------------- */ + +#ifdef APU_WANT_DB + +#if APU_HAVE_DB +/* win32 note.. you will need to change this for db1 */ +#include +#endif + +#undef APU_WANT_DB +#endif + +/* --------------------------------------------------------------------- */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apu_want.h.in b/c/dependencies/windows/apr/x64_debug/include/apu_want.h.in new file mode 100644 index 00000000..81297a75 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apu_want.h.in @@ -0,0 +1,51 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apu.h" /* configuration data */ + +/** + * @file apu_want.h + * @brief APR Standard Headers Support + * + *
+ * Features:
+ *
+ *   APU_WANT_DB:       <@apu_db_header@>
+ *
+ * Typical usage:
+ *
+ *   #define APU_WANT_DB
+ *   #include "apu_want.h"
+ *
+ * The appropriate headers will be included.
+ *
+ * Note: it is safe to use this in a header (it won't interfere with other
+ *       headers' or source files' use of apu_want.h)
+ * 
+ */ + +/* --------------------------------------------------------------------- */ + +#ifdef APU_WANT_DB + +#if APU_HAVE_DB +#include <@apu_db_header@> +#endif + +#undef APU_WANT_DB +#endif + +/* --------------------------------------------------------------------- */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apu_want.hnw b/c/dependencies/windows/apr/x64_debug/include/apu_want.hnw new file mode 100644 index 00000000..5d6edd3c --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apu_want.hnw @@ -0,0 +1,52 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apu.h" /* configuration data */ + +/** + * @file apu_want.h + * @brief APR Standard Headers Support + * + *
+ * Features:
+ *
+ *   APU_WANT_DB:       <@apu_db_header>
+ *
+ * Typical usage:
+ *
+ *   #define APU_WANT_DB
+ *   #include "apu_want.h"
+ *
+ * The appropriate headers will be included.
+ *
+ * Note: it is safe to use this in a header (it won't interfere with other
+ *       headers' or source files' use of apu_want.h)
+ * 
+ */ + +/* --------------------------------------------------------------------- */ + +#ifdef APU_WANT_DB + +#if APU_HAVE_DB +/* win32 note.. you will need to change this for db1 */ +#include +#endif + +#undef APU_WANT_DB +#endif + +/* --------------------------------------------------------------------- */ diff --git a/c/dependencies/windows/apr/x64_debug/include/apu_want.hw b/c/dependencies/windows/apr/x64_debug/include/apu_want.hw new file mode 100644 index 00000000..03b6ea98 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/apu_want.hw @@ -0,0 +1,52 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apu.h" /* configuration data */ + +/** + * @file apu_want.h + * @brief APR Standard Headers Support + * + *
+ * Features:
+ *
+ *   APU_WANT_DB:       
+ *
+ * Typical usage:
+ *
+ *   #define APU_WANT_DB
+ *   #include "apu_want.h"
+ *
+ * The appropriate headers will be included.
+ *
+ * Note: it is safe to use this in a header (it won't interfere with other
+ *       headers' or source files' use of apu_want.h)
+ * 
+ */ + +/* --------------------------------------------------------------------- */ + +#ifdef APU_WANT_DB + +#if APU_HAVE_DB +/* win32 note.. you will need to change this for db1 */ +#include +#endif + +#undef APU_WANT_DB +#endif + +/* --------------------------------------------------------------------- */ diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/aix/apr_arch_dso.h b/c/dependencies/windows/apr/x64_debug/include/arch/aix/apr_arch_dso.h new file mode 100644 index 00000000..d1cac684 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/aix/apr_arch_dso.h @@ -0,0 +1,41 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_dso.h" +#include "apr.h" + +#if APR_HAS_DSO + +void *dlopen(const char *path, int mode); +void *dlsym(void *handle, const char *symbol); +const char *dlerror(void); +int dlclose(void *handle); + +struct apr_dso_handle_t { + apr_pool_t *pool; + void *handle; + const char *errormsg; +}; + +#endif + +#endif diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/apr_private_common.h b/c/dependencies/windows/apr/x64_debug/include/arch/apr_private_common.h new file mode 100644 index 00000000..ec850c65 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/apr_private_common.h @@ -0,0 +1,41 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * This file contains private declarations common to all architectures. + */ + +#ifndef APR_PRIVATE_COMMON_H +#define APR_PRIVATE_COMMON_H + +#include "apr_pools.h" +#include "apr_tables.h" + +apr_status_t apr_filepath_list_split_impl(apr_array_header_t **pathelts, + const char *liststr, + char separator, + apr_pool_t *p); + +apr_status_t apr_filepath_list_merge_impl(char **liststr, + apr_array_header_t *pathelts, + char separator, + apr_pool_t *p); + +/* temporary defines to handle 64bit compile mismatches */ +#define APR_INT_TRUNC_CAST int +#define APR_UINT32_TRUNC_CAST apr_uint32_t + +#endif /*APR_PRIVATE_COMMON_H*/ diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/beos/apr_arch_dso.h b/c/dependencies/windows/apr/x64_debug/include/arch/beos/apr_arch_dso.h new file mode 100644 index 00000000..fbc5c2ff --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/beos/apr_arch_dso.h @@ -0,0 +1,41 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_dso.h" +#include "apr.h" +#include +#include + +#if APR_HAS_DSO + +struct apr_dso_handle_t { + image_id handle; /* Handle to the DSO loaded */ + apr_pool_t *pool; + const char *errormsg; /* if the load fails, we have an error + * message here :) + */ +}; + +#endif + +#endif diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/beos/apr_arch_proc_mutex.h b/c/dependencies/windows/apr/x64_debug/include/arch/beos/apr_arch_proc_mutex.h new file mode 100644 index 00000000..c60d8c62 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/beos/apr_arch_proc_mutex.h @@ -0,0 +1,36 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PROC_MUTEX_H +#define PROC_MUTEX_H + +#include "apr_pools.h" +#include "apr_proc_mutex.h" +#include "apr_file_io.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_portable.h" + +struct apr_proc_mutex_t { + apr_pool_t *pool; + + /* Our lock :) */ + sem_id Lock; + int32 LockCount; +}; + +#endif /* PROC_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/beos/apr_arch_thread_cond.h b/c/dependencies/windows/apr/x64_debug/include/arch/beos/apr_arch_thread_cond.h new file mode 100644 index 00000000..c9420b53 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/beos/apr_arch_thread_cond.h @@ -0,0 +1,46 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_COND_H +#define THREAD_COND_H + +#include +#include "apr_pools.h" +#include "apr_thread_cond.h" +#include "apr_file_io.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_portable.h" +#include "apr_ring.h" + +struct waiter_t { + APR_RING_ENTRY(waiter_t) link; + sem_id sem; +}; + +struct apr_thread_cond_t { + apr_pool_t *pool; + sem_id lock; + apr_thread_mutex_t *condlock; + thread_id owner; + /* active list */ + APR_RING_HEAD(active_list, waiter_t) alist; + /* free list */ + APR_RING_HEAD(free_list, waiter_t) flist; +}; + +#endif /* THREAD_COND_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/beos/apr_arch_thread_mutex.h b/c/dependencies/windows/apr/x64_debug/include/arch/beos/apr_arch_thread_mutex.h new file mode 100644 index 00000000..bb7d4ae8 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/beos/apr_arch_thread_mutex.h @@ -0,0 +1,42 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_MUTEX_H +#define THREAD_MUTEX_H + +#include +#include "apr_pools.h" +#include "apr_thread_mutex.h" +#include "apr_file_io.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_portable.h" + +struct apr_thread_mutex_t { + apr_pool_t *pool; + + /* Our lock :) */ + sem_id Lock; + int32 LockCount; + + /* If we nest locks we need these... */ + int nested; + apr_os_thread_t owner; + int owner_ref; +}; + +#endif /* THREAD_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/beos/apr_arch_thread_rwlock.h b/c/dependencies/windows/apr/x64_debug/include/arch/beos/apr_arch_thread_rwlock.h new file mode 100644 index 00000000..694b0d50 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/beos/apr_arch_thread_rwlock.h @@ -0,0 +1,45 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_RWLOCK_H +#define THREAD_RWLOCK_H + +#include +#include "apr_pools.h" +#include "apr_thread_rwlock.h" +#include "apr_file_io.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_portable.h" + +struct apr_thread_rwlock_t { + apr_pool_t *pool; + + /* Our lock :) */ + sem_id Lock; + int32 LockCount; + /* Read/Write lock stuff */ + sem_id Read; + int32 ReadCount; + sem_id Write; + int32 WriteCount; + int32 Nested; + + thread_id writer; +}; + +#endif /* THREAD_RWLOCK_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/beos/apr_arch_threadproc.h b/c/dependencies/windows/apr/x64_debug/include/arch/beos/apr_arch_threadproc.h new file mode 100644 index 00000000..13de0536 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/beos/apr_arch_threadproc.h @@ -0,0 +1,95 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr_thread_proc.h" +#include "apr_arch_file_io.h" +#include "apr_file_io.h" +#include "apr_thread_proc.h" +#include "apr_general.h" +#include "apr_portable.h" +#include +#include +#include +#include +#include + +#ifndef THREAD_PROC_H +#define THREAD_PROC_H + +#define SHELL_PATH "/bin/sh" + +#define PTHREAD_CANCEL_AYNCHRONOUS CANCEL_ASYNCH; +#define PTHREAD_CANCEL_DEFERRED CANCEL_DEFER; + +#define PTHREAD_CANCEL_ENABLE CANCEL_ENABLE; +#define PTHREAD_CANCEL_DISABLE CANCEL_DISABLE; + +#define BEOS_MAX_DATAKEYS 128 + +struct apr_thread_t { + apr_pool_t *pool; + thread_id td; + void *data; + apr_thread_start_t func; + apr_status_t exitval; +}; + +struct apr_threadattr_t { + apr_pool_t *pool; + int32 attr; + int detached; + int joinable; +}; + +struct apr_threadkey_t { + apr_pool_t *pool; + int32 key; +}; + +struct beos_private_data { + const void ** data; + int count; + volatile thread_id td; +}; + +struct beos_key { + int assigned; + int count; + sem_id lock; + int32 ben_lock; + void (* destructor) (void *); +}; + +struct apr_procattr_t { + apr_pool_t *pool; + apr_file_t *parent_in; + apr_file_t *child_in; + apr_file_t *parent_out; + apr_file_t *child_out; + apr_file_t *parent_err; + apr_file_t *child_err; + char *currdir; + apr_int32_t cmdtype; + apr_int32_t detached; +}; + +struct apr_thread_once_t { + sem_id sem; + int hit; +}; + +#endif /* ! THREAD_PROC_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_dso.h b/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_dso.h new file mode 100644 index 00000000..ea0fe8c2 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_dso.h @@ -0,0 +1,43 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_dso.h" +#include "apr.h" + +#include + +typedef struct sym_list sym_list; + +struct sym_list { + sym_list *next; + char *symbol; +}; + +struct apr_dso_handle_t { + apr_pool_t *pool; + void *handle; + const char *errormsg; + sym_list *symbols; + char *path; +}; + +#endif diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_file_io.h b/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_file_io.h new file mode 100644 index 00000000..8bd2a72c --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_file_io.h @@ -0,0 +1,176 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FILE_IO_H +#define FILE_IO_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_tables.h" +#include "apr_file_io.h" +#include "apr_file_info.h" +#include "apr_errno.h" +#include "apr_lib.h" +#include "apr_poll.h" + +/* System headers the file I/O library needs */ +#if APR_HAVE_FCNTL_H +#include +#endif +#if APR_HAVE_SYS_TYPES_H +#include +#endif +#if APR_HAVE_ERRNO_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#if APR_HAVE_STRINGS_H +#include +#endif +#if APR_HAVE_DIRENT_H +#include +#endif +#ifdef HAVE_SYS_STAT_H +#include +#endif +#if APR_HAVE_UNISTD_H +#include +#endif +#if APR_HAVE_STDIO_H +#include +#endif +#if APR_HAVE_STDLIB_H +#include +#endif +#if APR_HAVE_SYS_UIO_H +#include +#endif +#if APR_HAVE_SYS_TIME_H +#include +#endif + +#include + +/* End System headers */ + +#define APR_FILE_DEFAULT_BUFSIZE 4096 +/* For backwards compat */ +#define APR_FILE_BUFSIZE APR_FILE_DEFAULT_BUFSIZE + +#if APR_HAS_THREADS +#define file_lock(f) do { \ + if ((f)->thlock) \ + apr_thread_mutex_lock((f)->thlock); \ + } while (0) +#define file_unlock(f) do { \ + if ((f)->thlock) \ + apr_thread_mutex_unlock((f)->thlock); \ + } while (0) +#else +#define file_lock(f) do {} while (0) +#define file_unlock(f) do {} while (0) +#endif + +#if APR_HAS_LARGE_FILES +#define lseek(f,o,w) lseek64(f,o,w) +#define ftruncate(f,l) ftruncate64(f,l) +#endif + +typedef struct stat struct_stat; + +struct apr_file_t { + apr_pool_t *pool; + int filedes; + char *fname; + apr_int32_t flags; + int eof_hit; + int is_pipe; + apr_interval_time_t timeout; + int buffered; + enum {BLK_UNKNOWN, BLK_OFF, BLK_ON } blocking; + int ungetchar; /* Last char provided by an unget op. (-1 = no char)*/ + + /* if there is a timeout set, then this pollset is used */ + apr_pollset_t *pollset; + + /* Stuff for buffered mode */ + char *buffer; + apr_size_t bufpos; /* Read/Write position in buffer */ + apr_size_t bufsize; /* The buffer size */ + apr_off_t dataRead; /* amount of valid data read into buffer */ + int direction; /* buffer being used for 0 = read, 1 = write */ + apr_off_t filePtr; /* position in file of handle */ +#if APR_HAS_THREADS + struct apr_thread_mutex_t *thlock; +#endif +}; + +struct apr_dir_t { + apr_pool_t *pool; + char *dirname; + DIR *dirstruct; + struct dirent *entry; +}; + +typedef struct apr_stat_entry_t apr_stat_entry_t; + +struct apr_stat_entry_t { + struct stat info; + char *casedName; + apr_time_t expire; + NXPathCtx_t pathCtx; +}; + +#define MAX_SERVER_NAME 64 +#define MAX_VOLUME_NAME 64 +#define MAX_PATH_NAME 256 +#define MAX_FILE_NAME 256 + +#define DRIVE_ONLY 1 + +/* If the user passes d: vs. D: (or //mach/share vs. //MACH/SHARE), + * we need to fold the case to canonical form. This function is + * supposed to do so. + */ +apr_status_t filepath_root_case(char **rootpath, char *root, apr_pool_t *p); + +/* This function check to see of the given path includes a drive/volume + * specifier. If the _only_ parameter is set to DRIVE_ONLY then it + * check to see of the path only contains a drive/volume specifier and + * nothing else. + */ +apr_status_t filepath_has_drive(const char *rootpath, int only, apr_pool_t *p); + +/* This function compares the drive/volume specifiers for each given path. + * It returns zero if they match or non-zero if not. + */ +apr_status_t filepath_compare_drive(const char *path1, const char *path2, apr_pool_t *p); + +apr_status_t apr_unix_file_cleanup(void *); +apr_status_t apr_unix_child_file_cleanup(void *); + +mode_t apr_unix_perms2mode(apr_fileperms_t perms); +apr_fileperms_t apr_unix_mode2perms(mode_t mode); + +apr_status_t apr_file_flush_locked(apr_file_t *thefile); +apr_status_t apr_file_info_get_locked(apr_finfo_t *finfo, apr_int32_t wanted, + apr_file_t *thefile); + +#endif /* ! FILE_IO_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_global_mutex.h b/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_global_mutex.h new file mode 100644 index 00000000..4167d378 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_global_mutex.h @@ -0,0 +1,29 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GLOBAL_MUTEX_H +#define GLOBAL_MUTEX_H + +#include "apr_global_mutex.h" +#include "apr_thread_mutex.h" + +struct apr_global_mutex_t { + apr_pool_t *pool; + apr_thread_mutex_t *mutex; +}; + +#endif /* GLOBAL_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_internal_time.h b/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_internal_time.h new file mode 100644 index 00000000..59f10672 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_internal_time.h @@ -0,0 +1,26 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIME_INTERNAL_H +#define TIME_INTERNAL_H + +#include "apr.h" + +#define TZONE (*___timezone()) + +void apr_netware_setup_time(void); + +#endif /* TIME_INTERNAL_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_networkio.h b/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_networkio.h new file mode 100644 index 00000000..63f17abe --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_networkio.h @@ -0,0 +1,31 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETWORK_IO_H + +#ifdef USE_WINSOCK +/* Making sure that we include the correct networkio.h since the + the project file is configured to first look for headers in + arch/netware and then arch/unix. But in this specific case we + want arch/win32. +*/ +#include <../win32/apr_arch_networkio.h> +#else +#include <../unix/apr_arch_networkio.h> +#endif + +#endif /* ! NETWORK_IO_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_pre_nw.h b/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_pre_nw.h new file mode 100644 index 00000000..7380e118 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_pre_nw.h @@ -0,0 +1,57 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef __pre_nw__ +#define __pre_nw__ + +#include + +#ifndef __GNUC__ +#pragma precompile_target "precomp.mch" +#endif + +#define NETWARE + +#define N_PLAT_NLM + +#define FAR +#define far + +/* no-op for Codewarrior C compiler; a functions are cdecl + by default */ +#define cdecl + +/* if we have wchar_t enabled in C++, predefine this type to avoid + a conflict in Novell's header files */ +#ifndef __GNUC__ +#ifndef DOXYGEN +#if (__option(cplusplus) && __option(wchar_type)) +#define _WCHAR_T +#endif +#endif +#endif + +/* C9X defintion used by MSL C++ library */ +#define DECIMAL_DIG 17 + +/* some code may want to use the MS convention for long long */ +#ifndef __int64 +#define __int64 long long +#endif + +#endif + + + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_proc_mutex.h b/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_proc_mutex.h new file mode 100644 index 00000000..7a634c2e --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_proc_mutex.h @@ -0,0 +1,29 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PROC_MUTEX_H +#define PROC_MUTEX_H + +#include "apr_proc_mutex.h" +#include "apr_thread_mutex.h" + +struct apr_proc_mutex_t { + apr_pool_t *pool; + apr_thread_mutex_t *mutex; +}; + +#endif /* PROC_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_thread_cond.h b/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_thread_cond.h new file mode 100644 index 00000000..b11a5f86 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_thread_cond.h @@ -0,0 +1,29 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_COND_H +#define THREAD_COND_H + +#include "apr_thread_cond.h" +#include + +struct apr_thread_cond_t { + apr_pool_t *pool; + NXCond_t *cond; +}; + +#endif /* THREAD_COND_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_thread_mutex.h b/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_thread_mutex.h new file mode 100644 index 00000000..18702fc7 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_thread_mutex.h @@ -0,0 +1,32 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_MUTEX_H +#define THREAD_MUTEX_H + +#include "apr_thread_mutex.h" +#include "apr_thread_cond.h" +#include + +struct apr_thread_mutex_t { + apr_pool_t *pool; + NXMutex_t *mutex; + apr_thread_cond_t *cond; + int locked, num_waiters; +}; + +#endif /* THREAD_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_thread_rwlock.h b/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_thread_rwlock.h new file mode 100644 index 00000000..d2dbd42f --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_thread_rwlock.h @@ -0,0 +1,29 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_RWLOCK_H +#define THREAD_RWLOCK_H + +#include "apr_thread_rwlock.h" +#include + +struct apr_thread_rwlock_t { + apr_pool_t *pool; + NXRwLock_t *rwlock; +}; + +#endif /* THREAD_RWLOCK_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_threadproc.h b/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_threadproc.h new file mode 100644 index 00000000..2fee2c00 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_arch_threadproc.h @@ -0,0 +1,80 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" + +#include + +#ifndef THREAD_PROC_H +#define THREAD_PROC_H + +#define SHELL_PATH "" +#define APR_DEFAULT_STACK_SIZE 65536 + +struct apr_thread_t { + apr_pool_t *pool; + NXContext_t ctx; + NXThreadId_t td; + char *thread_name; + apr_int32_t cancel; + apr_int32_t cancel_how; + void *data; + apr_thread_start_t func; + apr_status_t exitval; +}; + +struct apr_threadattr_t { + apr_pool_t *pool; + apr_size_t stack_size; + apr_int32_t detach; + char *thread_name; +}; + +struct apr_threadkey_t { + apr_pool_t *pool; + NXKey_t key; +}; + +struct apr_procattr_t { + apr_pool_t *pool; + apr_file_t *parent_in; + apr_file_t *child_in; + apr_file_t *parent_out; + apr_file_t *child_out; + apr_file_t *parent_err; + apr_file_t *child_err; + char *currdir; + apr_int32_t cmdtype; + apr_int32_t detached; + apr_int32_t addrspace; +}; + +struct apr_thread_once_t { + unsigned long value; +}; + +/* +struct apr_proc_t { + apr_pool_t *pool; + pid_t pid; + apr_procattr_t *attr; +}; +*/ + +#endif /* ! THREAD_PROC_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_private.h b/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_private.h new file mode 100644 index 00000000..04f336de --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/netware/apr_private.h @@ -0,0 +1,205 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Note: + * This is the netware-specific autoconf-like config file + * which unix creates at ./configure time. + */ + +#ifdef NETWARE + +#ifndef APR_PRIVATE_H +#define APR_PRIVATE_H + +/* Pick up publicly advertised headers and symbols before the + * APR internal private headers and symbols + */ +#include + +/* Pick up privately consumed headers */ +#include + +/* Include alloca.h to get compiler-dependent defines */ +#include + +#include +#include +#include +#include +#include +#include +#include + +/* Use this section to define all of the HAVE_FOO_H + * that are required to build properly. + */ +#define HAVE_DLFCN_H 1 +#define HAVE_LIMITS_H 1 +#define HAVE_SIGNAL_H 1 +#define HAVE_STDDEF_H 1 +#define HAVE_STDLIB_H 1 +#ifndef USE_WINSOCK +#define HAVE_SYS_SELECT_H 1 +#define HAVE_WRITEV 1 +#endif +#define HAVE_SYS_STAT_H 1 +#define HAVE_SYS_MMAN_H 1 +#define HAVE_FCNTL_H 1 +#define HAVE_ICONV_H 1 +#define HAVE_UTIME_H 1 + +#define HAVE_STRICMP 1 +#define HAVE_STRNICMP 1 +#define HAVE_STRDUP 1 +#define HAVE_STRSTR 1 +#define HAVE_MEMCHR 1 +#define HAVE_CALLOC 1 +#define HAVE_UTIME 1 + +#define HAVE_GETENV 1 +#define HAVE_SETENV 1 +#define HAVE_UNSETENV 1 + +#define HAVE_WRITEV 1 + +#define HAVE_GETPASS_R 1 +/* + * Hack around older NDKs which have only the getpassword() function, + * a threadsafe, API-equivalent of getpass_r(). + */ +#if (CURRENT_NDK_THRESHOLD < 709060000) +#define getpass_r getpassword +#endif + +/*#define DSO_USE_DLFCN */ + +#ifdef NW_BUILD_IPV6 +#define HAVE_GETADDRINFO 1 +#define HAVE_GETNAMEINFO 1 +#endif + +/* 1 is used for SIGABRT on netware */ +/* 2 is used for SIGFPE on netware */ +/* 3 is used for SIGILL on netware */ +/* 4 is used for SIGINT on netware */ +/* 5 is used for SIGSEGV on netware */ +/* 6 is used for SIGTERM on netware */ +/* 7 is used for SIGPOLL on netware */ + +#if (CURRENT_NDK_THRESHOLD < 306030000) +#define SIGKILL 11 +#define SIGALRM 13 +#define SIGCHLD 14 +#define SIGCONT 15 +#define SIGHUP 16 +#define SIGPIPE 17 +#define SIGQUIT 18 +#define SIGSTOP 19 +#define SIGTSTP 20 +#define SIGTTIN 21 +#define SIGTTOU 22 +#define SIGUSR1 23 +#define SIGUSR2 24 +#endif + +#define SIGTRAP 25 +#define SIGIOT 26 +#define SIGSTKFLT 28 +#define SIGURG 29 +#define SIGXCPU 30 +#define SIGXFSZ 31 +#define SIGVTALRM 32 +#define SIGPROF 33 +#define SIGWINCH 34 +#define SIGIO 35 + +#if (CURRENT_NDK_THRESHOLD < 406230000) +#undef SA_NOCLDSTOP +#define SA_NOCLDSTOP 0x00000001 +#endif +#ifndef SIGBUS +#define SIGBUS SIGSEGV +#endif + +#define _getch getcharacter + +#define SIZEOF_SHORT 2 +#define SIZEOF_INT 4 +#define SIZEOF_LONGLONG 8 +#define SIZEOF_CHAR 1 +#define SIZEOF_SSIZE_T SIZEOF_INT + +void netware_pool_proc_cleanup(); + +/* NLM registration routines for managing which NLMs + are using the library. */ +int register_NLM(void *NLMHandle); +int unregister_NLM(void *NLMHandle); + +/* Application global data management */ +extern int gLibId; +extern void *gLibHandle; + +typedef struct app_data { + int initialized; + void* gPool; + void* gs_aHooksToSort; + void* gs_phOptionalHooks; + void* gs_phOptionalFunctions; + void* gs_nlmhandle; + rtag_t gs_startup_rtag; + rtag_t gs_socket_rtag; + rtag_t gs_lookup_rtag; + rtag_t gs_event_rtag; + rtag_t gs_pcp_rtag; + void* gs_ldap_xref_lock; + void* gs_xref_head; +} APP_DATA; + +int setGlobalPool(void *data); +void* getGlobalPool(); +int setStatCache(void *data); +void* getStatCache(); + +/* Redefine malloc to use the library malloc call so + that all of the memory resources will be owned + and can be shared by the library. */ +#undef malloc +#define malloc(x) library_malloc(gLibHandle,x) +#ifndef __MWERKS__ +#define _alloca alloca +#endif + +/* 64-bit integer conversion function */ +#define APR_INT64_STRFN strtoll + +#if APR_HAS_LARGE_FILES +#define APR_OFF_T_STRFN strtoll +#else +#define APR_OFF_T_STRFN strtol +#endif + +/* used to check DWORD overflow for 64bit compiles */ +#define APR_DWORD_MAX 0xFFFFFFFFUL + +/* + * Include common private declarations. + */ +#include "../apr_private_common.h" + +#endif /*APR_PRIVATE_H*/ +#endif /*NETWARE*/ diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_dso.h b/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_dso.h new file mode 100644 index 00000000..2bda6b7c --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_dso.h @@ -0,0 +1,37 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_dso.h" +#include "apr.h" + +#if APR_HAS_DSO + +struct apr_dso_handle_t { + apr_pool_t *cont; /* Context for returning error strings */ + HMODULE handle; /* Handle to the DSO loaded */ + apr_status_t load_error; + char *failed_module; +}; + +#endif + +#endif diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_file_io.h b/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_file_io.h new file mode 100644 index 00000000..79a57964 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_file_io.h @@ -0,0 +1,86 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FILE_IO_H +#define FILE_IO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_thread_mutex.h" +#include "apr_file_io.h" +#include "apr_file_info.h" +#include "apr_errno.h" +#include "apr_poll.h" + +/* We have an implementation of mkstemp but it's not very multi-threading + * friendly & is part of the POSIX emulation rather than native so don't + * use it. + */ +#undef HAVE_MKSTEMP + +#define APR_FILE_DEFAULT_BUFSIZE 4096 +#define APR_FILE_BUFSIZE APR_FILE_DEFAULT_BUFSIZE + +struct apr_file_t { + apr_pool_t *pool; + HFILE filedes; + char * fname; + int isopen; + int buffered; + int eof_hit; + apr_int32_t flags; + int timeout; + int pipe; + HEV pipeSem; + enum { BLK_UNKNOWN, BLK_OFF, BLK_ON } blocking; + + /* Stuff for buffered mode */ + char *buffer; + apr_size_t bufsize; /* Read/Write position in buffer */ + apr_size_t bufpos; /* Read/Write position in buffer */ + unsigned long dataRead; /* amount of valid data read into buffer */ + int direction; /* buffer being used for 0 = read, 1 = write */ + unsigned long filePtr; /* position in file of handle */ + apr_thread_mutex_t *mutex; /* mutex semaphore, must be owned to access + the above fields */ +}; + +struct apr_dir_t { + apr_pool_t *pool; + char *dirname; + ULONG handle; + FILEFINDBUF3 entry; + int validentry; +}; + +apr_status_t apr_file_cleanup(void *); +apr_status_t apr_os2_time_to_apr_time(apr_time_t *result, FDATE os2date, + FTIME os2time); +apr_status_t apr_apr_time_to_os2_time(FDATE *os2date, FTIME *os2time, + apr_time_t aprtime); + +/* see win32/fileio.h for description of these */ +extern const char c_is_fnchar[256]; + +#define IS_FNCHAR(c) c_is_fnchar[(unsigned char)c] + +apr_status_t filepath_root_test(char *path, apr_pool_t *p); +apr_status_t filepath_drive_get(char **rootpath, char drive, + apr_int32_t flags, apr_pool_t *p); +apr_status_t filepath_root_case(char **rootpath, char *root, apr_pool_t *p); + +#endif /* ! FILE_IO_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_inherit.h b/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_inherit.h new file mode 100644 index 00000000..494772ac --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_inherit.h @@ -0,0 +1,50 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INHERIT_H +#define INHERIT_H + +#include "apr_inherit.h" + +#define APR_INHERIT (1 << 24) /* Must not conflict with other bits */ + +#define APR_IMPLEMENT_INHERIT_SET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_set(apr_##name##_t *the##name) \ +{ \ + int rv; \ + ULONG state; \ + if (((rv = DosQueryFHState(attr->parent_err->filedes, &state)) \ + != 0) || \ + ((rv = DosSetFHState(attr->parent_err->filedes, \ + state & ~OPEN_FLAGS_NOINHERIT)) != 0)) \ + return APR_FROM_OS_ERROR(rv); \ + return APR_SUCCESS; \ +} + +#define APR_IMPLEMENT_INHERIT_UNSET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_unset(apr_##name##_t *the##name)\ +{ \ + int rv; \ + ULONG state; \ + if (((rv = DosQueryFHState(attr->parent_err->filedes, &state)) \ + != 0) || \ + ((rv = DosSetFHState(attr->parent_err->filedes, \ + state | OPEN_FLAGS_NOINHERIT)) != 0)) \ + return APR_FROM_OS_ERROR(rv); \ + return APR_SUCCESS; \ +} + +#endif /* ! INHERIT_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_networkio.h b/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_networkio.h new file mode 100644 index 00000000..10c6de81 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_networkio.h @@ -0,0 +1,76 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETWORK_IO_H +#define NETWORK_IO_H + +#include "apr_private.h" +#include "apr_network_io.h" +#include "apr_general.h" +#include "apr_arch_os2calls.h" +#include "apr_poll.h" + +#if APR_HAVE_NETDB_H +#include +#endif + +typedef struct sock_userdata_t sock_userdata_t; +struct sock_userdata_t { + sock_userdata_t *next; + const char *key; + void *data; +}; + +struct apr_socket_t { + apr_pool_t *pool; + int socketdes; + int type; + int protocol; + apr_sockaddr_t *local_addr; + apr_sockaddr_t *remote_addr; + apr_interval_time_t timeout; + int nonblock; + int local_port_unknown; + int local_interface_unknown; + int remote_addr_unknown; + apr_int32_t options; + apr_int32_t inherit; + sock_userdata_t *userdata; + + /* if there is a timeout set, then this pollset is used */ + apr_pollset_t *pollset; +}; + +/* Error codes returned from sock_errno() */ +#define SOCBASEERR 10000 +#define SOCEPERM (SOCBASEERR+1) /* Not owner */ +#define SOCESRCH (SOCBASEERR+3) /* No such process */ +#define SOCEINTR (SOCBASEERR+4) /* Interrupted system call */ +#define SOCENXIO (SOCBASEERR+6) /* No such device or address */ +#define SOCEBADF (SOCBASEERR+9) /* Bad file number */ +#define SOCEACCES (SOCBASEERR+13) /* Permission denied */ +#define SOCEFAULT (SOCBASEERR+14) /* Bad address */ +#define SOCEINVAL (SOCBASEERR+22) /* Invalid argument */ +#define SOCEMFILE (SOCBASEERR+24) /* Too many open files */ +#define SOCEPIPE (SOCBASEERR+32) /* Broken pipe */ +#define SOCEOS2ERR (SOCBASEERR+100) /* OS/2 Error */ + +const char *apr_inet_ntop(int af, const void *src, char *dst, apr_size_t size); +int apr_inet_pton(int af, const char *src, void *dst); +void apr_sockaddr_vars_set(apr_sockaddr_t *, int, apr_port_t); + +#endif /* ! NETWORK_IO_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_os2calls.h b/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_os2calls.h new file mode 100644 index 00000000..3c739bfd --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_os2calls.h @@ -0,0 +1,59 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr_errno.h" +#include +#include + +extern int (*apr_os2_socket)(int, int, int); +extern int (*apr_os2_select)(int *, int, int, int, long); +extern int (*apr_os2_sock_errno)(); +extern int (*apr_os2_accept)(int, struct sockaddr *, int *); +extern int (*apr_os2_bind)(int, struct sockaddr *, int); +extern int (*apr_os2_connect)(int, struct sockaddr *, int); +extern int (*apr_os2_getpeername)(int, struct sockaddr *, int *); +extern int (*apr_os2_getsockname)(int, struct sockaddr *, int *); +extern int (*apr_os2_getsockopt)(int, int, int, char *, int *); +extern int (*apr_os2_ioctl)(int, int, caddr_t, int); +extern int (*apr_os2_listen)(int, int); +extern int (*apr_os2_recv)(int, char *, int, int); +extern int (*apr_os2_send)(int, const char *, int, int); +extern int (*apr_os2_setsockopt)(int, int, int, char *, int); +extern int (*apr_os2_shutdown)(int, int); +extern int (*apr_os2_soclose)(int); +extern int (*apr_os2_writev)(int, struct iovec *, int); +extern int (*apr_os2_sendto)(int, const char *, int, int, const struct sockaddr *, int); +extern int (*apr_os2_recvfrom)(int, char *, int, int, struct sockaddr *, int *); + +#define socket apr_os2_socket +#define select apr_os2_select +#define sock_errno apr_os2_sock_errno +#define accept apr_os2_accept +#define bind apr_os2_bind +#define connect apr_os2_connect +#define getpeername apr_os2_getpeername +#define getsockname apr_os2_getsockname +#define getsockopt apr_os2_getsockopt +#define ioctl apr_os2_ioctl +#define listen apr_os2_listen +#define recv apr_os2_recv +#define send apr_os2_send +#define setsockopt apr_os2_setsockopt +#define shutdown apr_os2_shutdown +#define soclose apr_os2_soclose +#define writev apr_os2_writev +#define sendto apr_os2_sendto +#define recvfrom apr_os2_recvfrom diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_proc_mutex.h b/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_proc_mutex.h new file mode 100644 index 00000000..8caf3369 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_proc_mutex.h @@ -0,0 +1,31 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PROC_MUTEX_H +#define PROC_MUTEX_H + +#include "apr_proc_mutex.h" +#include "apr_file_io.h" + +struct apr_proc_mutex_t { + apr_pool_t *pool; + HMTX hMutex; + TID owner; + int lock_count; +}; + +#endif /* PROC_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_thread_cond.h b/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_thread_cond.h new file mode 100644 index 00000000..aa0a7ca6 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_thread_cond.h @@ -0,0 +1,33 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_COND_H +#define THREAD_COND_H + +#include "apr_thread_cond.h" +#include "apr_file_io.h" + +struct apr_thread_cond_t { + apr_pool_t *pool; + HEV semaphore; + HMTX mutex; + unsigned long num_waiting; + unsigned long num_wake; + unsigned long generation; +}; + +#endif /* THREAD_COND_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_thread_mutex.h b/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_thread_mutex.h new file mode 100644 index 00000000..3ae2a41d --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_thread_mutex.h @@ -0,0 +1,29 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_MUTEX_H +#define THREAD_MUTEX_H + +#include "apr_thread_mutex.h" +#include "apr_file_io.h" + +struct apr_thread_mutex_t { + apr_pool_t *pool; + HMTX hMutex; +}; + +#endif /* THREAD_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_thread_rwlock.h b/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_thread_rwlock.h new file mode 100644 index 00000000..7187d5cb --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_thread_rwlock.h @@ -0,0 +1,31 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_RWLOCK_H +#define THREAD_RWLOCK_H + +#include "apr_thread_rwlock.h" +#include "apr_file_io.h" + +struct apr_thread_rwlock_t { + apr_pool_t *pool; + int readers; + HMTX write_lock; + HEV read_done; +}; + +#endif /* THREAD_RWLOCK_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_threadproc.h b/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_threadproc.h new file mode 100644 index 00000000..c8017adb --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/os2/apr_arch_threadproc.h @@ -0,0 +1,67 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr_thread_proc.h" +#include "apr_file_io.h" + +#ifndef THREAD_PROC_H +#define THREAD_PROC_H + +#define APR_THREADATTR_DETACHED 1 + +#define SHELL_PATH "cmd.exe" +#define APR_THREAD_STACKSIZE 65536 + +struct apr_threadattr_t { + apr_pool_t *pool; + unsigned long attr; + apr_size_t stacksize; +}; + +struct apr_thread_t { + apr_pool_t *pool; + struct apr_threadattr_t *attr; + unsigned long tid; + apr_thread_start_t func; + void *data; + apr_status_t exitval; +}; + +struct apr_threadkey_t { + apr_pool_t *pool; + unsigned long *key; +}; + +struct apr_procattr_t { + apr_pool_t *pool; + apr_file_t *parent_in; + apr_file_t *child_in; + apr_file_t *parent_out; + apr_file_t *child_out; + apr_file_t *parent_err; + apr_file_t *child_err; + char *currdir; + apr_int32_t cmdtype; + apr_int32_t detached; +}; + +struct apr_thread_once_t { + unsigned long sem; + char hit; +}; + +#endif /* ! THREAD_PROC_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/os390/apr_arch_dso.h b/c/dependencies/windows/apr/x64_debug/include/arch/os390/apr_arch_dso.h new file mode 100644 index 00000000..4263297b --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/os390/apr_arch_dso.h @@ -0,0 +1,39 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_dso.h" +#include "apr.h" + +#if APR_HAS_DSO + +#include + +struct apr_dso_handle_t { + dllhandle *handle; /* Handle to the DSO loaded */ + int failing_errno; /* Don't save the buffer returned by + strerror(); it gets reused */ + apr_pool_t *pool; +}; + +#endif + +#endif diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_atomic.h b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_atomic.h new file mode 100644 index 00000000..559257de --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_atomic.h @@ -0,0 +1,53 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ATOMIC_H +#define ATOMIC_H + +#include "apr.h" +#include "apr_pools.h" +#include "apr_private.h" +#include "apr_atomic.h" + +#if defined(USE_ATOMICS_GENERIC) +/* noop */ +#elif HAVE_ATOMIC_BUILTINS +# define USE_ATOMICS_BUILTINS +#elif defined(SOLARIS2) && SOLARIS2 >= 10 +# define USE_ATOMICS_SOLARIS +# define NEED_ATOMICS_GENERIC64 +#elif defined(__GNUC__) && defined(__STRICT_ANSI__) +/* force use of generic atomics if building e.g. with -std=c89, which + * doesn't allow inline asm */ +# define USE_ATOMICS_GENERIC +#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) +# define USE_ATOMICS_IA32 +# define NEED_ATOMICS_GENERIC64 +#elif defined(__GNUC__) && (defined(__PPC__) || defined(__ppc__)) +# define USE_ATOMICS_PPC +# define NEED_ATOMICS_GENERIC64 +#elif defined(__GNUC__) && (defined(__s390__) || defined(__s390x__)) +# define USE_ATOMICS_S390 +# define NEED_ATOMICS_GENERIC64 +#else +# define USE_ATOMICS_GENERIC +#endif + +#if defined(USE_ATOMICS_GENERIC) || defined (NEED_ATOMICS_GENERIC64) +apr_status_t apr__atomic_generic64_init(apr_pool_t *p); +#endif + +#endif /* ATOMIC_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_dso.h b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_dso.h new file mode 100644 index 00000000..d82182d4 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_dso.h @@ -0,0 +1,63 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_dso.h" +#include "apr.h" + +#if APR_HAS_DSO + +#ifdef HAVE_MACH_O_DYLD_H +#include +#endif + +#ifdef HAVE_DLFCN_H +#include +#endif + +#ifdef HAVE_DL_H +#include +#endif + +#ifndef RTLD_NOW +#define RTLD_NOW 1 +#endif + +#ifndef RTLD_GLOBAL +#define RTLD_GLOBAL 0 +#endif + +#if (defined(__DragonFly__) ||\ + defined(__FreeBSD__) ||\ + defined(__OpenBSD__) ||\ + defined(__NetBSD__) ) && !defined(__ELF__) +#define DLSYM_NEEDS_UNDERSCORE +#endif + +struct apr_dso_handle_t { + apr_pool_t *pool; + void *handle; + const char *errormsg; +}; + +#endif + +#endif diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_file_io.h b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_file_io.h new file mode 100644 index 00000000..77a90917 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_file_io.h @@ -0,0 +1,174 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FILE_IO_H +#define FILE_IO_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_tables.h" +#include "apr_file_io.h" +#include "apr_file_info.h" +#include "apr_errno.h" +#include "apr_lib.h" +#include "apr_thread_mutex.h" +#ifndef WAITIO_USES_POLL +#include "apr_poll.h" +#endif + +/* System headers the file I/O library needs */ +#if APR_HAVE_FCNTL_H +#include +#endif +#if APR_HAVE_SYS_TYPES_H +#include +#endif +#if APR_HAVE_ERRNO_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#if APR_HAVE_STRINGS_H +#include +#endif +#if APR_HAVE_DIRENT_H +#include +#endif +#ifdef HAVE_SYS_STAT_H +#include +#endif +#if APR_HAVE_UNISTD_H +#include +#endif +#if APR_HAVE_STDIO_H +#include +#endif +#if APR_HAVE_STDLIB_H +#include +#endif +#if APR_HAVE_SYS_UIO_H +#include +#endif +#if APR_HAVE_SYS_TIME_H +#include +#endif +#ifdef BEOS +#include +#endif +/* Hunting down DEV_BSIZE if not from dirent.h, sys/stat.h etc */ +#ifdef HAVE_SYS_PARAM_H +#include +#endif + +#if BEOS_BONE +# ifndef BONE7 + /* prior to BONE/7 fd_set & select were defined in sys/socket.h */ +# include +# else + /* Be moved the fd_set stuff and also the FIONBIO definition... */ +# include +# endif +#endif +/* End System headers */ + +#define APR_FILE_DEFAULT_BUFSIZE 4096 +/* For backwards-compat */ +#define APR_FILE_BUFSIZE APR_FILE_DEFAULT_BUFSIZE + +struct apr_file_t { + apr_pool_t *pool; + int filedes; + char *fname; + apr_int32_t flags; + int eof_hit; + int is_pipe; + apr_interval_time_t timeout; + int buffered; + enum {BLK_UNKNOWN, BLK_OFF, BLK_ON } blocking; + int ungetchar; /* Last char provided by an unget op. (-1 = no char)*/ +#ifndef WAITIO_USES_POLL + /* if there is a timeout set, then this pollset is used */ + apr_pollset_t *pollset; +#endif + /* Stuff for buffered mode */ + char *buffer; + apr_size_t bufpos; /* Read/Write position in buffer */ + apr_size_t bufsize; /* The size of the buffer */ + unsigned long dataRead; /* amount of valid data read into buffer */ + int direction; /* buffer being used for 0 = read, 1 = write */ + apr_off_t filePtr; /* position in file of handle */ +#if APR_HAS_THREADS + struct apr_thread_mutex_t *thlock; +#endif +}; + +#if APR_HAS_THREADS +#define file_lock(f) do { \ + if ((f)->thlock) \ + apr_thread_mutex_lock((f)->thlock); \ + } while (0) +#define file_unlock(f) do { \ + if ((f)->thlock) \ + apr_thread_mutex_unlock((f)->thlock); \ + } while (0) +#else +#define file_lock(f) do {} while (0) +#define file_unlock(f) do {} while (0) +#endif + +#if APR_HAS_LARGE_FILES && defined(_LARGEFILE64_SOURCE) +#define stat(f,b) stat64(f,b) +#define lstat(f,b) lstat64(f,b) +#define fstat(f,b) fstat64(f,b) +#define lseek(f,o,w) lseek64(f,o,w) +#define ftruncate(f,l) ftruncate64(f,l) +typedef struct stat64 struct_stat; +#else +typedef struct stat struct_stat; +#endif + +/* readdir64_r is only used in specific cases: */ +#if APR_HAS_THREADS && defined(_POSIX_THREAD_SAFE_FUNCTIONS) \ + && !defined(READDIR_IS_THREAD_SAFE) && defined(HAVE_READDIR64_R) +#define APR_USE_READDIR64_R +#endif + +struct apr_dir_t { + apr_pool_t *pool; + char *dirname; + DIR *dirstruct; +#ifdef APR_USE_READDIR64_R + struct dirent64 *entry; +#else + struct dirent *entry; +#endif +}; + +apr_status_t apr_unix_file_cleanup(void *); +apr_status_t apr_unix_child_file_cleanup(void *); + +mode_t apr_unix_perms2mode(apr_fileperms_t perms); +apr_fileperms_t apr_unix_mode2perms(mode_t mode); + +apr_status_t apr_file_flush_locked(apr_file_t *thefile); +apr_status_t apr_file_info_get_locked(apr_finfo_t *finfo, apr_int32_t wanted, + apr_file_t *thefile); + + +#endif /* ! FILE_IO_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_global_mutex.h b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_global_mutex.h new file mode 100644 index 00000000..3add9ecf --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_global_mutex.h @@ -0,0 +1,37 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GLOBAL_MUTEX_H +#define GLOBAL_MUTEX_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_global_mutex.h" +#include "apr_arch_proc_mutex.h" +#include "apr_arch_thread_mutex.h" + +struct apr_global_mutex_t { + apr_pool_t *pool; + apr_proc_mutex_t *proc_mutex; +#if APR_HAS_THREADS + apr_thread_mutex_t *thread_mutex; +#endif /* APR_HAS_THREADS */ +}; + +#endif /* GLOBAL_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_inherit.h b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_inherit.h new file mode 100644 index 00000000..21543c1e --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_inherit.h @@ -0,0 +1,64 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INHERIT_H +#define INHERIT_H + +#include "apr_inherit.h" + +#define APR_INHERIT (1 << 24) /* Must not conflict with other bits */ + +#define APR_IMPLEMENT_INHERIT_SET(name, flag, pool, cleanup) \ +apr_status_t apr_##name##_inherit_set(apr_##name##_t *the##name) \ +{ \ + if (the##name->flag & APR_FOPEN_NOCLEANUP) \ + return APR_EINVAL; \ + if (!(the##name->flag & APR_INHERIT)) { \ + int flags = fcntl(the##name->name##des, F_GETFD); \ + if (flags == -1) \ + return errno; \ + flags &= ~(FD_CLOEXEC); \ + if (fcntl(the##name->name##des, F_SETFD, flags) == -1) \ + return errno; \ + the##name->flag |= APR_INHERIT; \ + apr_pool_child_cleanup_set(the##name->pool, \ + (void *)the##name, \ + cleanup, apr_pool_cleanup_null); \ + } \ + return APR_SUCCESS; \ +} + +#define APR_IMPLEMENT_INHERIT_UNSET(name, flag, pool, cleanup) \ +apr_status_t apr_##name##_inherit_unset(apr_##name##_t *the##name) \ +{ \ + if (the##name->flag & APR_FOPEN_NOCLEANUP) \ + return APR_EINVAL; \ + if (the##name->flag & APR_INHERIT) { \ + int flags; \ + if ((flags = fcntl(the##name->name##des, F_GETFD)) == -1) \ + return errno; \ + flags |= FD_CLOEXEC; \ + if (fcntl(the##name->name##des, F_SETFD, flags) == -1) \ + return errno; \ + the##name->flag &= ~APR_INHERIT; \ + apr_pool_child_cleanup_set(the##name->pool, \ + (void *)the##name, \ + cleanup, cleanup); \ + } \ + return APR_SUCCESS; \ +} + +#endif /* ! INHERIT_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_internal_time.h b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_internal_time.h new file mode 100644 index 00000000..6e12c674 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_internal_time.h @@ -0,0 +1,24 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIME_INTERNAL_H +#define TIME_INTERNAL_H + +#include "apr.h" + +void apr_unix_setup_time(void); + +#endif /* TIME_INTERNAL_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_misc.h b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_misc.h new file mode 100644 index 00000000..82351250 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_misc.h @@ -0,0 +1,67 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MISC_H +#define MISC_H + +#include "apr.h" +#include "apr_portable.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_getopt.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" +#include "apr_errno.h" +#include "apr_getopt.h" + +#if APR_HAVE_STDIO_H +#include +#endif +#if APR_HAVE_SIGNAL_H +#include +#endif +#if APR_HAVE_PTHREAD_H +#include +#endif + +#if APR_HAVE_STDLIB_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif + +#ifdef BEOS +#include +#endif + +struct apr_other_child_rec_t { + apr_pool_t *p; + struct apr_other_child_rec_t *next; + apr_proc_t *proc; + void (*maintenance) (int, void *, int); + void *data; + apr_os_file_t write_fd; +}; + +#if defined(WIN32) || defined(NETWARE) +#define WSAHighByte 2 +#define WSALowByte 0 +#endif + +#endif /* ! MISC_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_networkio.h b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_networkio.h new file mode 100644 index 00000000..5f3189d9 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_networkio.h @@ -0,0 +1,145 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETWORK_IO_H +#define NETWORK_IO_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_network_io.h" +#include "apr_errno.h" +#include "apr_general.h" +#include "apr_lib.h" +#ifndef WAITIO_USES_POLL +#include "apr_poll.h" +#endif + +/* System headers the network I/O library needs */ +#if APR_HAVE_SYS_TYPES_H +#include +#endif +#if APR_HAVE_SYS_UIO_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#endif +#if APR_HAVE_ERRNO_H +#include +#endif +#if APR_HAVE_SYS_TIME_H +#include +#endif +#if APR_HAVE_UNISTD_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#if APR_HAVE_NETINET_TCP_H +#include +#endif +#if APR_HAVE_NETINET_SCTP_UIO_H +#include +#endif +#if APR_HAVE_NETINET_SCTP_H +#include +#endif +#if APR_HAVE_NETINET_IN_H +#include +#endif +#if APR_HAVE_ARPA_INET_H +#include +#endif +#if APR_HAVE_SYS_SOCKET_H +#include +#endif +#if APR_HAVE_SYS_SOCKIO_H +#include +#endif +#if APR_HAVE_NETDB_H +#include +#endif +#if APR_HAVE_FCNTL_H +#include +#endif +#if APR_HAVE_SYS_SENDFILE_H +#include +#endif +#if APR_HAVE_SYS_IOCTL_H +#include +#endif +/* End System Headers */ + +#ifndef HAVE_POLLIN +#define POLLIN 1 +#define POLLPRI 2 +#define POLLOUT 4 +#define POLLERR 8 +#define POLLHUP 16 +#define POLLNVAL 32 +#endif + +typedef struct sock_userdata_t sock_userdata_t; +struct sock_userdata_t { + sock_userdata_t *next; + const char *key; + void *data; +}; + +struct apr_socket_t { + apr_pool_t *pool; + int socketdes; + int type; + int protocol; + apr_sockaddr_t *local_addr; + apr_sockaddr_t *remote_addr; + apr_interval_time_t timeout; +#ifndef HAVE_POLL + int connected; +#endif +#if APR_HAVE_SOCKADDR_UN + int bound; +#endif + int local_port_unknown; + int local_interface_unknown; + int remote_addr_unknown; + apr_int32_t options; + apr_int32_t inherit; + sock_userdata_t *userdata; +#ifndef WAITIO_USES_POLL + /* if there is a timeout set, then this pollset is used */ + apr_pollset_t *pollset; +#endif +}; + +const char *apr_inet_ntop(int af, const void *src, char *dst, apr_size_t size); +int apr_inet_pton(int af, const char *src, void *dst); +void apr_sockaddr_vars_set(apr_sockaddr_t *, int, apr_port_t); + +#define apr_is_option_set(skt, option) \ + (((skt)->options & (option)) == (option)) + +#define apr_set_option(skt, option, on) \ + do { \ + if (on) \ + (skt)->options |= (option); \ + else \ + (skt)->options &= ~(option); \ + } while (0) + +#endif /* ! NETWORK_IO_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_poll_private.h b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_poll_private.h new file mode 100644 index 00000000..ff813123 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_poll_private.h @@ -0,0 +1,189 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ARCH_POLL_PRIVATE_H +#define APR_ARCH_POLL_PRIVATE_H + +#if HAVE_POLL_H +#include +#endif + +#if HAVE_SYS_POLL_H +#include +#endif + +#ifdef HAVE_PORT_CREATE +#include +#include +#endif + +#ifdef HAVE_KQUEUE +#include +#include +#include +#endif + +#ifdef HAVE_EPOLL +#include +#endif + +#ifdef NETWARE +#define HAS_SOCKETS(dt) (dt == APR_POLL_SOCKET) ? 1 : 0 +#define HAS_PIPES(dt) (dt == APR_POLL_FILE) ? 1 : 0 +#endif + +#if defined(HAVE_AIO_H) && defined(HAVE_AIO_MSGQ) +#define _AIO_OS390 /* enable a bunch of z/OS aio.h definitions */ +#include /* aiocb */ +#endif + +/* Choose the best method platform specific to use in apr_pollset */ +#ifdef HAVE_KQUEUE +#define POLLSET_USES_KQUEUE +#define POLLSET_DEFAULT_METHOD APR_POLLSET_KQUEUE +#elif defined(HAVE_PORT_CREATE) +#define POLLSET_USES_PORT +#define POLLSET_DEFAULT_METHOD APR_POLLSET_PORT +#elif defined(HAVE_EPOLL) +#define POLLSET_USES_EPOLL +#define POLLSET_DEFAULT_METHOD APR_POLLSET_EPOLL +#elif defined(HAVE_AIO_MSGQ) +#define POLLSET_USES_AIO_MSGQ +#define POLLSET_DEFAULT_METHOD APR_POLLSET_AIO_MSGQ +#elif defined(HAVE_POLL) +#define POLLSET_USES_POLL +#define POLLSET_DEFAULT_METHOD APR_POLLSET_POLL +#else +#define POLLSET_USES_SELECT +#define POLLSET_DEFAULT_METHOD APR_POLLSET_SELECT +#endif + +#ifdef WIN32 +#define POLL_USES_SELECT +#undef POLLSET_DEFAULT_METHOD +#define POLLSET_DEFAULT_METHOD APR_POLLSET_SELECT +#else +#ifdef HAVE_POLL +#define POLL_USES_POLL +#else +#define POLL_USES_SELECT +#endif +#endif + +#if defined(POLLSET_USES_KQUEUE) || defined(POLLSET_USES_EPOLL) || defined(POLLSET_USES_PORT) || defined(POLLSET_USES_AIO_MSGQ) + +#include "apr_ring.h" + +#if APR_HAS_THREADS +#include "apr_thread_mutex.h" +#define pollset_lock_rings() \ + if (pollset->flags & APR_POLLSET_THREADSAFE) \ + apr_thread_mutex_lock(pollset->p->ring_lock); +#define pollset_unlock_rings() \ + if (pollset->flags & APR_POLLSET_THREADSAFE) \ + apr_thread_mutex_unlock(pollset->p->ring_lock); +#else +#define pollset_lock_rings() +#define pollset_unlock_rings() +#endif + +typedef struct pfd_elem_t pfd_elem_t; + +struct pfd_elem_t { + APR_RING_ENTRY(pfd_elem_t) link; + apr_pollfd_t pfd; +#ifdef HAVE_PORT_CREATE + int on_query_ring; +#endif +}; + +#endif + +typedef struct apr_pollset_private_t apr_pollset_private_t; +typedef struct apr_pollset_provider_t apr_pollset_provider_t; +typedef struct apr_pollcb_provider_t apr_pollcb_provider_t; + +struct apr_pollset_t +{ + apr_pool_t *pool; + apr_uint32_t nelts; + apr_uint32_t nalloc; + apr_uint32_t flags; + /* Pipe descriptors used for wakeup */ + apr_file_t *wakeup_pipe[2]; + apr_pollfd_t wakeup_pfd; + apr_pollset_private_t *p; + const apr_pollset_provider_t *provider; +}; + +typedef union { +#if defined(HAVE_EPOLL) + struct epoll_event *epoll; +#endif +#if defined(HAVE_PORT_CREATE) + port_event_t *port; +#endif +#if defined(HAVE_KQUEUE) + struct kevent *ke; +#endif +#if defined(HAVE_POLL) + struct pollfd *ps; +#endif + void *undef; +} apr_pollcb_pset; + +struct apr_pollcb_t { + apr_pool_t *pool; + apr_uint32_t nelts; + apr_uint32_t nalloc; + apr_uint32_t flags; + /* Pipe descriptors used for wakeup */ + apr_file_t *wakeup_pipe[2]; + apr_pollfd_t wakeup_pfd; + int fd; + apr_pollcb_pset pollset; + apr_pollfd_t **copyset; + const apr_pollcb_provider_t *provider; +}; + +struct apr_pollset_provider_t { + apr_status_t (*create)(apr_pollset_t *, apr_uint32_t, apr_pool_t *, apr_uint32_t); + apr_status_t (*add)(apr_pollset_t *, const apr_pollfd_t *); + apr_status_t (*remove)(apr_pollset_t *, const apr_pollfd_t *); + apr_status_t (*poll)(apr_pollset_t *, apr_interval_time_t, apr_int32_t *, const apr_pollfd_t **); + apr_status_t (*cleanup)(apr_pollset_t *); + const char *name; +}; + +struct apr_pollcb_provider_t { + apr_status_t (*create)(apr_pollcb_t *, apr_uint32_t, apr_pool_t *, apr_uint32_t); + apr_status_t (*add)(apr_pollcb_t *, apr_pollfd_t *); + apr_status_t (*remove)(apr_pollcb_t *, apr_pollfd_t *); + apr_status_t (*poll)(apr_pollcb_t *, apr_interval_time_t, apr_pollcb_cb_t, void *); + apr_status_t (*cleanup)(apr_pollcb_t *); + const char *name; +}; + +/* + * Private functions used for the implementation of both apr_pollcb_* and + * apr_pollset_* + */ +apr_status_t apr_poll_create_wakeup_pipe(apr_pool_t *pool, apr_pollfd_t *pfd, + apr_file_t **wakeup_pipe); +apr_status_t apr_poll_close_wakeup_pipe(apr_file_t **wakeup_pipe); +void apr_poll_drain_wakeup_pipe(apr_file_t **wakeup_pipe); + +#endif /* APR_ARCH_POLL_PRIVATE_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_proc_mutex.h b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_proc_mutex.h new file mode 100644 index 00000000..cfa0049f --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_proc_mutex.h @@ -0,0 +1,121 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PROC_MUTEX_H +#define PROC_MUTEX_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_proc_mutex.h" +#include "apr_pools.h" +#include "apr_portable.h" +#include "apr_file_io.h" +#include "apr_arch_file_io.h" +#include "apr_time.h" + +/* System headers required by Locks library */ +#if APR_HAVE_SYS_TYPES_H +#include +#endif +#if APR_HAVE_STDIO_H +#include +#endif +#if APR_HAVE_FCNTL_H +#include +#endif + +#ifdef HAVE_SYS_IPC_H +#include +#endif +#ifdef HAVE_SYS_SEM_H +#include +#endif +#ifdef HAVE_SYS_FILE_H +#include +#endif +#if APR_HAVE_STDLIB_H +#include +#endif +#if APR_HAVE_UNISTD_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#ifdef HAVE_SYS_MMAN_H +#include +#endif +#if APR_HAVE_PTHREAD_H +#include +#endif +/* End System Headers */ + +struct apr_proc_mutex_unix_lock_methods_t { + unsigned int flags; + apr_status_t (*create)(apr_proc_mutex_t *, const char *); + apr_status_t (*acquire)(apr_proc_mutex_t *); + apr_status_t (*tryacquire)(apr_proc_mutex_t *); + apr_status_t (*timedacquire)(apr_proc_mutex_t *, apr_interval_time_t); + apr_status_t (*release)(apr_proc_mutex_t *); + apr_status_t (*cleanup)(void *); + apr_status_t (*child_init)(apr_proc_mutex_t **, apr_pool_t *, const char *); + apr_status_t (*perms_set)(apr_proc_mutex_t *, apr_fileperms_t, apr_uid_t, apr_gid_t); + apr_lockmech_e mech; + const char *name; +}; +typedef struct apr_proc_mutex_unix_lock_methods_t apr_proc_mutex_unix_lock_methods_t; + +/* bit values for flags field in apr_unix_lock_methods_t */ +#define APR_PROCESS_LOCK_MECH_IS_GLOBAL 1 + +#if !APR_HAVE_UNION_SEMUN && defined(APR_HAS_SYSVSEM_SERIALIZE) +union semun { + int val; + struct semid_ds *buf; + unsigned short *array; +}; +#endif + +struct apr_proc_mutex_t { + apr_pool_t *pool; + const apr_proc_mutex_unix_lock_methods_t *meth; + int curr_locked; + char *fname; + + apr_os_proc_mutex_t os; /* Native mutex holder. */ + +#if APR_HAS_FCNTL_SERIALIZE || APR_HAS_FLOCK_SERIALIZE + apr_file_t *interproc; /* For apr_file_ calls on native fd. */ + int interproc_closing; /* whether the native fd is opened/closed with + * 'interproc' or apr_os_file_put()ed (hence + * needing an an explicit close for consistency + * with other methods). + */ +#endif +#if APR_HAS_PROC_PTHREAD_SERIALIZE + int pthread_refcounting; /* Whether the native mutex is refcounted or + * apr_os_proc_mutex_put()ed, which makes + * refcounting impossible/undesirable. + */ +#endif +}; + +void apr_proc_mutex_unix_setup_lock(void); + +#endif /* PROC_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_shm.h b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_shm.h new file mode 100644 index 00000000..e9d25cad --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_shm.h @@ -0,0 +1,74 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SHM_H +#define SHM_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_shm.h" +#include "apr_pools.h" +#include "apr_file_io.h" +#include "apr_network_io.h" +#include "apr_portable.h" + +#if APR_HAVE_UNISTD_H +#include +#endif +#ifdef HAVE_SYS_MMAN_H +#include +#endif +#ifdef HAVE_SYS_IPC_H +#include +#endif +#ifdef HAVE_SYS_MUTEX_H +#include +#endif +#ifdef HAVE_SYS_SHM_H +#include +#endif +#if !defined(SHM_R) +#define SHM_R 0400 +#endif +#if !defined(SHM_W) +#define SHM_W 0200 +#endif +#ifdef HAVE_SYS_FILE_H +#include +#endif + +/* Not all systems seem to have MAP_FAILED defined, but it should always + * just be (void *)-1. */ +#ifndef MAP_FAILED +#define MAP_FAILED ((void *)-1) +#endif + +struct apr_shm_t { + apr_pool_t *pool; + void *base; /* base real address */ + void *usable; /* base usable address */ + apr_size_t reqsize; /* requested segment size */ + apr_size_t realsize; /* actual segment size */ + const char *filename; /* NULL if anonymous */ +#if APR_USE_SHMEM_SHMGET || APR_USE_SHMEM_SHMGET_ANON + int shmid; /* shmem ID returned from shmget() */ + key_t shmkey; /* shmem key IPC_ANON or returned from ftok() */ +#endif +}; + +#endif /* SHM_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_thread_cond.h b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_thread_cond.h new file mode 100644 index 00000000..5c2b51d1 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_thread_cond.h @@ -0,0 +1,42 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_COND_H +#define THREAD_COND_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_thread_mutex.h" +#include "apr_thread_cond.h" +#include "apr_pools.h" + +#if APR_HAVE_PTHREAD_H +#include +#endif + +/* XXX: Should we have a better autoconf search, something like + * APR_HAS_PTHREAD_COND? -aaron */ +#if APR_HAS_THREADS +struct apr_thread_cond_t { + apr_pool_t *pool; + pthread_cond_t cond; +}; +#endif + +#endif /* THREAD_COND_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_thread_mutex.h b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_thread_mutex.h new file mode 100644 index 00000000..4fe46c3b --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_thread_mutex.h @@ -0,0 +1,42 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_MUTEX_H +#define THREAD_MUTEX_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_thread_mutex.h" +#include "apr_thread_cond.h" +#include "apr_portable.h" +#include "apr_atomic.h" + +#if APR_HAVE_PTHREAD_H +#include +#endif + +#if APR_HAS_THREADS +struct apr_thread_mutex_t { + apr_pool_t *pool; + pthread_mutex_t mutex; + apr_thread_cond_t *cond; + int locked, num_waiters; +}; +#endif + +#endif /* THREAD_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_thread_rwlock.h b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_thread_rwlock.h new file mode 100644 index 00000000..2cb43af6 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_thread_rwlock.h @@ -0,0 +1,49 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_RWLOCK_H +#define THREAD_RWLOCK_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_thread_rwlock.h" +#include "apr_pools.h" + +#if APR_HAVE_PTHREAD_H +/* this gives us pthread_rwlock_t */ +#include +#endif + +#if APR_HAS_THREADS +#ifdef HAVE_PTHREAD_RWLOCKS + +struct apr_thread_rwlock_t { + apr_pool_t *pool; + pthread_rwlock_t rwlock; +}; + +#else + +struct apr_thread_rwlock_t { + apr_pool_t *pool; +}; +#endif + +#endif + +#endif /* THREAD_RWLOCK_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_threadproc.h b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_threadproc.h new file mode 100644 index 00000000..7a3b3c09 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/unix/apr_arch_threadproc.h @@ -0,0 +1,119 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr.h" +#include "apr_private.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" +#include "apr_arch_file_io.h" +#include "apr_perms_set.h" + +/* System headers required for thread/process library */ +#if APR_HAVE_PTHREAD_H +#include +#endif +#ifdef HAVE_SYS_RESOURCE_H +#include +#endif +#if APR_HAVE_SIGNAL_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#if APR_HAVE_SYS_WAIT_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#ifdef HAVE_SCHED_H +#include +#endif +/* End System Headers */ + + +#ifndef THREAD_PROC_H +#define THREAD_PROC_H + +#define SHELL_PATH "/bin/sh" + +#if APR_HAS_THREADS + +struct apr_thread_t { + apr_pool_t *pool; + pthread_t *td; + void *data; + apr_thread_start_t func; + apr_status_t exitval; +}; + +struct apr_threadattr_t { + apr_pool_t *pool; + pthread_attr_t attr; +}; + +struct apr_threadkey_t { + apr_pool_t *pool; + pthread_key_t key; +}; + +struct apr_thread_once_t { + pthread_once_t once; +}; + +#endif + +typedef struct apr_procattr_pscb_t apr_procattr_pscb_t; +struct apr_procattr_pscb_t { + struct apr_procattr_pscb_t *next; + apr_perms_setfn_t *perms_set_fn; + apr_fileperms_t perms; + const void *data; +}; + +struct apr_procattr_t { + apr_pool_t *pool; + apr_file_t *parent_in; + apr_file_t *child_in; + apr_file_t *parent_out; + apr_file_t *child_out; + apr_file_t *parent_err; + apr_file_t *child_err; + char *currdir; + apr_int32_t cmdtype; + apr_int32_t detached; +#ifdef RLIMIT_CPU + struct rlimit *limit_cpu; +#endif +#if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS) + struct rlimit *limit_mem; +#endif +#ifdef RLIMIT_NPROC + struct rlimit *limit_nproc; +#endif +#ifdef RLIMIT_NOFILE + struct rlimit *limit_nofile; +#endif + apr_child_errfn_t *errfn; + apr_int32_t errchk; + apr_uid_t uid; + apr_gid_t gid; + apr_procattr_pscb_t *perms_set_callbacks; +}; + +#endif /* ! THREAD_PROC_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_atime.h b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_atime.h new file mode 100644 index 00000000..35f2041a --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_atime.h @@ -0,0 +1,63 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ATIME_H +#define ATIME_H + +#include "apr_private.h" +#include "apr_time.h" +#if APR_HAVE_TIME_H +#include +#endif + +struct atime_t { + apr_pool_t *cntxt; + apr_time_t currtime; + SYSTEMTIME *explodedtime; +}; + + +/* Number of micro-seconds between the beginning of the Windows epoch + * (Jan. 1, 1601) and the Unix epoch (Jan. 1, 1970) + */ +#define APR_DELTA_EPOCH_IN_USEC APR_TIME_C(11644473600000000); + + +static APR_INLINE void FileTimeToAprTime(apr_time_t *result, FILETIME *input) +{ + /* Convert FILETIME one 64 bit number so we can work with it. */ + *result = input->dwHighDateTime; + *result = (*result) << 32; + *result |= input->dwLowDateTime; + *result /= 10; /* Convert from 100 nano-sec periods to micro-seconds. */ + *result -= APR_DELTA_EPOCH_IN_USEC; /* Convert from Windows epoch to Unix epoch */ + return; +} + + +static APR_INLINE void AprTimeToFileTime(LPFILETIME pft, apr_time_t t) +{ + LONGLONG ll; + t += APR_DELTA_EPOCH_IN_USEC; + ll = t * 10; + pft->dwLowDateTime = (DWORD)ll; + pft->dwHighDateTime = (DWORD) (ll >> 32); + return; +} + + +#endif /* ! ATIME_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_dso.h b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_dso.h new file mode 100644 index 00000000..e2e4e40f --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_dso.h @@ -0,0 +1,36 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_dso.h" +#include "apr.h" + +#if APR_HAS_DSO + +struct apr_dso_handle_t { + apr_pool_t *cont; + void *handle; + apr_status_t load_error; +}; + +#endif + +#endif diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_file_io.h b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_file_io.h new file mode 100644 index 00000000..9fb8df19 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_file_io.h @@ -0,0 +1,266 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FILE_IO_H +#define FILE_IO_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_pools.h" +#include "apr_general.h" +#include "apr_tables.h" +#include "apr_thread_mutex.h" +#include "apr_file_io.h" +#include "apr_file_info.h" +#include "apr_errno.h" +#include "apr_arch_misc.h" +#include "apr_poll.h" + +#ifdef HAVE_SYS_STAT_H +#include +#endif +#if APR_HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_FCNTL_H +#include +#endif +#ifdef HAVE_TIME_H +#include +#endif +#if APR_HAVE_DIRENT_H +#include +#endif +#ifdef HAVE_MALLOC_H +#include +#endif + +#if APR_HAS_UNICODE_FS +#include "arch/win32/apr_arch_utf8.h" +#include + +/* Helper functions for the WinNT ApiW() functions. APR treats all + * resource identifiers (files, etc) by their UTF-8 name, to provide + * access to all named identifiers. [UTF-8 completely maps Unicode + * into char type strings.] + * + * The _path flavors below provide us fast mappings of the + * Unicode filename //?/D:/path and //?/UNC/mach/share/path mappings, + * which allow unlimited (well, 32000 wide character) length names. + * These prefixes may appear in Unicode, but must not appear in the + * Ascii API calls. So we tack them on in utf8_to_unicode_path, and + * strip them right back off in unicode_to_utf8_path. + */ +apr_status_t utf8_to_unicode_path(apr_wchar_t* dststr, apr_size_t dstchars, + const char* srcstr); +apr_status_t unicode_to_utf8_path(char* dststr, apr_size_t dstchars, + const apr_wchar_t* srcstr); + +#endif /* APR_HAS_UNICODE_FS */ + +/* Another Helper functions for the WinNT ApiW() functions. We need to + * derive some 'resource' names (max length 255 characters, prefixed with + * Global/ or Local/ on WinNT) from something that looks like a filename. + * Since 'resource' names never contain slashes, convert these to '_'s + * and return the appropriate char* or wchar* for ApiA or ApiW calls. + */ + +void *res_name_from_filename(const char *file, int global, apr_pool_t *pool); + +#define APR_FILE_MAX MAX_PATH + +#define APR_FILE_DEFAULT_BUFSIZE 4096 +/* For backwards-compat */ +#define APR_FILE_BUFSIZE APR_FILE_DEFAULT_BUFSIZE + +/* obscure ommissions from msvc's sys/stat.h */ +#ifdef _MSC_VER +#define S_IFIFO _S_IFIFO /* pipe */ +#define S_IFBLK 0060000 /* Block Special */ +#define S_IFLNK 0120000 /* Symbolic Link */ +#define S_IFSOCK 0140000 /* Socket */ +#define S_IFWHT 0160000 /* Whiteout */ +#endif + +/* Internal Flags for apr_file_open */ +#define APR_OPENINFO 0x00100000 /* Open without READ or WRITE access */ +#define APR_OPENLINK 0x00200000 /* Open a link itself, if supported */ +#define APR_READCONTROL 0x00400000 /* Read the file's owner/perms */ +#define APR_WRITECONTROL 0x00800000 /* Modify the file's owner/perms */ +/* #define APR_INHERIT 0x01000000 -- Defined in apr_arch_inherit.h! */ +#define APR_STDIN_FLAG 0x02000000 /* Obtained via apr_file_open_stdin() */ +#define APR_STDOUT_FLAG 0x04000000 /* Obtained via apr_file_open_stdout() */ +#define APR_STDERR_FLAG 0x06000000 /* Obtained via apr_file_open_stderr() */ +#define APR_STD_FLAGS (APR_STDIN_FLAG | APR_STDOUT_FLAG | APR_STDERR_FLAG) +#define APR_WRITEATTRS 0x08000000 /* Modify the file's attributes */ + +/* Entries missing from the MSVC 5.0 Win32 SDK: + */ +#ifndef FILE_ATTRIBUTE_DEVICE +#define FILE_ATTRIBUTE_DEVICE 0x00000040 +#endif +#ifndef FILE_ATTRIBUTE_REPARSE_POINT +#define FILE_ATTRIBUTE_REPARSE_POINT 0x00000400 +#endif +#ifndef FILE_FLAG_OPEN_NO_RECALL +#define FILE_FLAG_OPEN_NO_RECALL 0x00100000 +#endif +#ifndef FILE_FLAG_OPEN_REPARSE_POINT +#define FILE_FLAG_OPEN_REPARSE_POINT 0x00200000 +#endif +#ifndef TRUSTEE_IS_WELL_KNOWN_GROUP +#define TRUSTEE_IS_WELL_KNOWN_GROUP 5 +#endif + +/* Information bits available from the WIN32 FindFirstFile function */ +#define APR_FINFO_WIN32_DIR (APR_FINFO_NAME | APR_FINFO_TYPE \ + | APR_FINFO_CTIME | APR_FINFO_ATIME \ + | APR_FINFO_MTIME | APR_FINFO_SIZE) + +/* Sneak the Readonly bit through finfo->protection for internal use _only_ */ +#define APR_FREADONLY 0x10000000 + +/* Private function for apr_stat/lstat/getfileinfo/dir_read */ +int fillin_fileinfo(apr_finfo_t *finfo, WIN32_FILE_ATTRIBUTE_DATA *wininfo, + int byhandle, int finddata, const char *fname, + apr_int32_t wanted); + +/* Private function that extends apr_stat/lstat/getfileinfo/dir_read */ +apr_status_t more_finfo(apr_finfo_t *finfo, const void *ufile, + apr_int32_t wanted, int whatfile); + +/* whatfile types for the ufile arg */ +#define MORE_OF_HANDLE 0 +#define MORE_OF_FSPEC 1 +#define MORE_OF_WFSPEC 2 + +/* quick run-down of fields in windows' apr_file_t structure that may have + * obvious uses. + * fname -- the filename as passed to the open call. + * dwFileAttricutes -- Attributes used to open the file. + * append -- Windows doesn't support the append concept when opening files. + * APR needs to keep track of this, and always make sure we append + * correctly when writing to a file with this flag set TRUE. + */ + +/* for apr_poll.c */ +#define filedes filehand + +struct apr_file_t { + apr_pool_t *pool; + HANDLE filehand; + BOOLEAN pipe; /* Is this a pipe of a file? */ + OVERLAPPED *pOverlapped; + apr_interval_time_t timeout; + apr_int32_t flags; + + /* File specific info */ + apr_finfo_t *finfo; + char *fname; + DWORD dwFileAttributes; + int eof_hit; + BOOLEAN buffered; /* Use buffered I/O? */ + int ungetchar; /* Last char provided by an unget op. (-1 = no char) */ + int append; + + /* Stuff for buffered mode */ + char *buffer; + apr_size_t bufpos; /* Read/Write position in buffer */ + apr_size_t bufsize; /* The size of the buffer */ + apr_size_t dataRead; /* amount of valid data read into buffer */ + int direction; /* buffer being used for 0 = read, 1 = write */ + apr_off_t filePtr; /* position in file of handle */ + apr_thread_mutex_t *mutex; /* mutex semaphore, must be owned to access + * the above fields */ + +#if APR_FILES_AS_SOCKETS + /* if there is a timeout set, then this pollset is used */ + apr_pollset_t *pollset; +#endif + /* Pipe specific info */ +}; + +struct apr_dir_t { + apr_pool_t *pool; + HANDLE dirhand; + apr_size_t rootlen; + char *dirname; + char *name; + union { +#if APR_HAS_UNICODE_FS + struct { + WIN32_FIND_DATAW *entry; + } w; +#endif +#if APR_HAS_ANSI_FS + struct { + WIN32_FIND_DATAA *entry; + } n; +#endif + }; + int bof; +}; + +/* There are many goofy characters the filesystem can't accept + * or can confound the cmd.exe shell. Here's the list + * [declared in filesys.c] + */ +extern const char apr_c_is_fnchar[256]; + +#define IS_FNCHAR(c) (apr_c_is_fnchar[(unsigned char)(c)] & 1) +#define IS_SHCHAR(c) ((apr_c_is_fnchar[(unsigned char)(c)] & 2) == 2) + + +/* If the user passes APR_FILEPATH_TRUENAME to either + * apr_filepath_root or apr_filepath_merge, this fn determines + * that the root really exists. It's expensive, wouldn't want + * to do this too frequenly. + */ +apr_status_t filepath_root_test(char *path, apr_pool_t *p); + + +/* The apr_filepath_merge wants to canonicalize the cwd to the + * addpath if the user passes NULL as the old root path (this + * isn't true of an empty string "", which won't be concatenated. + * + * But we need to figure out what the cwd of a given volume is, + * when the user passes D:foo. This fn will determine D:'s cwd. + * + * If flags includes the bit APR_FILEPATH_NATIVE, the path returned + * is in the os-native format. + */ +apr_status_t filepath_drive_get(char **rootpath, char drive, + apr_int32_t flags, apr_pool_t *p); + + +/* If the user passes d: vs. D: (or //mach/share vs. //MACH/SHARE), + * we need to fold the case to canonical form. This function is + * supposed to do so. + */ +apr_status_t filepath_root_case(char **rootpath, char *root, apr_pool_t *p); + + +apr_status_t file_cleanup(void *); + +extern apr_status_t +apr_file_socket_pipe_create(apr_file_t **in, + apr_file_t **out, + apr_pool_t *p); + +extern apr_status_t +apr_file_socket_pipe_close(apr_file_t *file); + +#endif /* ! FILE_IO_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_inherit.h b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_inherit.h new file mode 100644 index 00000000..8969af66 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_inherit.h @@ -0,0 +1,123 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INHERIT_H +#define INHERIT_H + +#include "apr_inherit.h" + +#define APR_INHERIT (1 << 24) /* Must not conflict with other bits */ + +#if APR_HAS_UNICODE_FS && APR_HAS_ANSI_FS +/* !defined(_WIN32_WCE) is implicit here */ + +#define APR_IMPLEMENT_INHERIT_SET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_set(apr_##name##_t *the##name) \ +{ \ + IF_WIN_OS_IS_UNICODE \ + { \ +/* if (!SetHandleInformation(the##name->filehand, \ + * HANDLE_FLAG_INHERIT, \ + * HANDLE_FLAG_INHERIT)) \ + * return apr_get_os_error(); \ + */ } \ + ELSE_WIN_OS_IS_ANSI \ + { \ + HANDLE temp, hproc = GetCurrentProcess(); \ + if (!DuplicateHandle(hproc, the##name->filehand, \ + hproc, &temp, 0, TRUE, \ + DUPLICATE_SAME_ACCESS)) \ + return apr_get_os_error(); \ + CloseHandle(the##name->filehand); \ + the##name->filehand = temp; \ + } \ + return APR_SUCCESS; \ +} + +#define APR_IMPLEMENT_INHERIT_UNSET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_unset(apr_##name##_t *the##name)\ +{ \ + IF_WIN_OS_IS_UNICODE \ + { \ +/* if (!SetHandleInformation(the##name->filehand, \ + * HANDLE_FLAG_INHERIT, 0)) \ + * return apr_get_os_error(); \ + */ } \ + ELSE_WIN_OS_IS_ANSI \ + { \ + HANDLE temp, hproc = GetCurrentProcess(); \ + if (!DuplicateHandle(hproc, the##name->filehand, \ + hproc, &temp, 0, FALSE, \ + DUPLICATE_SAME_ACCESS)) \ + return apr_get_os_error(); \ + CloseHandle(the##name->filehand); \ + the##name->filehand = temp; \ + } \ + return APR_SUCCESS; \ +} + +#elif APR_HAS_ANSI_FS || defined(_WIN32_WCE) + +#define APR_IMPLEMENT_INHERIT_SET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_set(apr_##name##_t *the##name) \ +{ \ + HANDLE temp, hproc = GetCurrentProcess(); \ + if (!DuplicateHandle(hproc, the##name->filehand, \ + hproc, &temp, 0, TRUE, \ + DUPLICATE_SAME_ACCESS)) \ + return apr_get_os_error(); \ + CloseHandle(the##name->filehand); \ + the##name->filehand = temp; \ + return APR_SUCCESS; \ +} + +#define APR_IMPLEMENT_INHERIT_UNSET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_unset(apr_##name##_t *the##name)\ +{ \ + HANDLE temp, hproc = GetCurrentProcess(); \ + if (!DuplicateHandle(hproc, the##name->filehand, \ + hproc, &temp, 0, FALSE, \ + DUPLICATE_SAME_ACCESS)) \ + return apr_get_os_error(); \ + CloseHandle(the##name->filehand); \ + the##name->filehand = temp; \ + return APR_SUCCESS; \ +} + +#else /* APR_HAS_UNICODE_FS && !APR_HAS_ANSI_FS && !defined(_WIN32_WCE) */ + +#define APR_IMPLEMENT_INHERIT_SET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_set(apr_##name##_t *the##name) \ +{ \ +/* if (!SetHandleInformation(the##name->filehand, \ + * HANDLE_FLAG_INHERIT, \ + * HANDLE_FLAG_INHERIT)) \ + * return apr_get_os_error(); \ + */ return APR_SUCCESS; \ +} + +#define APR_IMPLEMENT_INHERIT_UNSET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_unset(apr_##name##_t *the##name)\ +{ \ +/* if (!SetHandleInformation(the##name->filehand, \ + * HANDLE_FLAG_INHERIT, 0)) \ + * return apr_get_os_error(); \ + */ return APR_SUCCESS; \ +} + +#endif /* defined(APR_HAS_UNICODE_FS) */ + +#endif /* ! INHERIT_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_misc.h b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_misc.h new file mode 100644 index 00000000..15312adf --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_misc.h @@ -0,0 +1,509 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MISC_H +#define MISC_H + +#include "apr.h" +#include "apr_portable.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_getopt.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" +#include "apr_errno.h" +#include "apr_getopt.h" + +#if APR_HAVE_STDIO_H +#include +#endif +#if APR_HAVE_SIGNAL_H +#include +#endif +#if APR_HAVE_PTHREAD_H +#include +#endif +#if APR_HAVE_STDLIB_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#ifndef _WIN32_WCE +#include +#endif + +#if defined(HAVE_IF_INDEXTONAME) && defined(_MSC_VER) +#include +#endif + +struct apr_other_child_rec_t { + apr_pool_t *p; + struct apr_other_child_rec_t *next; + apr_proc_t *proc; + void (*maintenance) (int, void *, int); + void *data; + apr_os_file_t write_fd; +}; + +#define WSAHighByte 2 +#define WSALowByte 0 + +/* start.c and apr_app.c helpers and communication within misc.c + * + * They are not for public consumption, although apr_app_init_complete + * must be an exported symbol to avoid reinitialization. + */ +extern int APR_DECLARE_DATA apr_app_init_complete; + +int apr_wastrtoastr(char const * const * *retarr, + wchar_t const * const *arr, int args); + +/* Platform specific designation of run time os version. + * Gaps allow for specific service pack levels that + * export new kernel or winsock functions or behavior. + */ +typedef enum { + APR_WIN_UNK = 0, + APR_WIN_UNSUP = 1, + APR_WIN_95 = 10, + APR_WIN_95_B = 11, + APR_WIN_95_OSR2 = 12, + APR_WIN_98 = 14, + APR_WIN_98_SE = 16, + APR_WIN_ME = 18, + + APR_WIN_UNICODE = 20, /* Prior versions support only narrow chars */ + + APR_WIN_CE_3 = 23, /* CE is an odd beast, not supporting */ + /* some pre-NT features, such as the */ + APR_WIN_NT = 30, /* narrow charset APIs (fooA fns), while */ + APR_WIN_NT_3_5 = 35, /* not supporting some NT-family features. */ + APR_WIN_NT_3_51 = 36, + + APR_WIN_NT_4 = 40, + APR_WIN_NT_4_SP2 = 42, + APR_WIN_NT_4_SP3 = 43, + APR_WIN_NT_4_SP4 = 44, + APR_WIN_NT_4_SP5 = 45, + APR_WIN_NT_4_SP6 = 46, + + APR_WIN_2000 = 50, + APR_WIN_2000_SP1 = 51, + APR_WIN_2000_SP2 = 52, + APR_WIN_XP = 60, + APR_WIN_XP_SP1 = 61, + APR_WIN_XP_SP2 = 62, + APR_WIN_2003 = 70, + APR_WIN_VISTA = 80, + APR_WIN_7 = 90 +} apr_oslevel_e; + +extern APR_DECLARE_DATA apr_oslevel_e apr_os_level; + +apr_status_t apr_get_oslevel(apr_oslevel_e *); + +/* The APR_HAS_ANSI_FS symbol is PRIVATE, and internal to APR. + * APR only supports char data for filenames. Like most applications, + * characters >127 are essentially undefined. APR_HAS_UNICODE_FS lets + * the application know that utf-8 is the encoding method of APR, and + * only incidently hints that we have Wide OS calls. + * + * APR_HAS_ANSI_FS is simply an OS flag to tell us all calls must be + * the unicode eqivilant. + */ + +#if defined(_WIN32_WCE) || defined(WINNT) +#define APR_HAS_ANSI_FS 0 +#else +#define APR_HAS_ANSI_FS 1 +#endif + +/* IF_WIN_OS_IS_UNICODE / ELSE_WIN_OS_IS_ANSI help us keep the code trivial + * where have runtime tests for unicode-ness, that aren't needed in any + * build which supports only WINNT or WCE. + */ +#if APR_HAS_ANSI_FS && APR_HAS_UNICODE_FS +#define IF_WIN_OS_IS_UNICODE if (apr_os_level >= APR_WIN_UNICODE) +#define ELSE_WIN_OS_IS_ANSI else +#else /* APR_HAS_UNICODE_FS */ +#define IF_WIN_OS_IS_UNICODE +#define ELSE_WIN_OS_IS_ANSI +#endif /* WINNT */ + +#if defined(_MSC_VER) && !defined(_WIN32_WCE) +#include "crtdbg.h" + +static APR_INLINE void* apr_malloc_dbg(size_t size, const char* filename, + int linenumber) +{ + return _malloc_dbg(size, _CRT_BLOCK, filename, linenumber); +} + +static APR_INLINE void* apr_realloc_dbg(void* userData, size_t newSize, + const char* filename, int linenumber) +{ + return _realloc_dbg(userData, newSize, _CRT_BLOCK, filename, linenumber); +} + +#else + +static APR_INLINE void* apr_malloc_dbg(size_t size, const char* filename, + int linenumber) +{ + return malloc(size); +} + +static APR_INLINE void* apr_realloc_dbg(void* userData, size_t newSize, + const char* filename, int linenumber) +{ + return realloc(userData, newSize); +} + +#endif /* ! _MSC_VER */ + +typedef enum { + DLL_WINBASEAPI = 0, /* kernel32 From WinBase.h */ + DLL_WINADVAPI = 1, /* advapi32 From WinBase.h */ + DLL_WINSOCKAPI = 2, /* mswsock From WinSock.h */ + DLL_WINSOCK2API = 3, /* ws2_32 From WinSock2.h */ + DLL_SHSTDAPI = 4, /* shell32 From ShellAPI.h */ + DLL_NTDLL = 5, /* ntdll From our real kernel */ + DLL_IPHLPAPI = 6, /* Iphlpapi From Iphlpapi.h */ + DLL_defined = 7 /* must define as last idx_ + 1 */ +} apr_dlltoken_e; + +FARPROC apr_load_dll_func(apr_dlltoken_e fnLib, char *fnName, int ordinal); + +/* The apr_load_dll_func call WILL return 0 set error to + * ERROR_INVALID_FUNCTION if the function cannot be loaded + */ +#define APR_DECLARE_LATE_DLL_FUNC(lib, rettype, calltype, fn, ord, args, names) \ + typedef rettype (calltype *apr_winapi_fpt_##fn) args; \ + static apr_winapi_fpt_##fn apr_winapi_pfn_##fn = NULL; \ + static int apr_winapi_chk_##fn = 0; \ + static APR_INLINE int apr_winapi_ld_##fn(void) \ + { if (apr_winapi_pfn_##fn) return 1; \ + if (apr_winapi_chk_##fn ++) return 0; \ + if (!apr_winapi_pfn_##fn) \ + apr_winapi_pfn_##fn = (apr_winapi_fpt_##fn) \ + apr_load_dll_func(lib, #fn, ord); \ + if (apr_winapi_pfn_##fn) return 1; else return 0; }; \ + static APR_INLINE rettype apr_winapi_##fn args \ + { if (apr_winapi_ld_##fn()) \ + return (*(apr_winapi_pfn_##fn)) names; \ + else { SetLastError(ERROR_INVALID_FUNCTION); return 0;} }; \ + +#define APR_HAVE_LATE_DLL_FUNC(fn) apr_winapi_ld_##fn() + +/* Provide late bound declarations of every API function missing from + * one or more supported releases of the Win32 API + * + * lib is the enumerated token from apr_dlltoken_e, and must correspond + * to the string table entry in start.c used by the apr_load_dll_func(). + * Token names (attempt to) follow Windows.h declarations prefixed by DLL_ + * in order to facilitate comparison. Use the exact declaration syntax + * and names from Windows.h to prevent ambigutity and bugs. + * + * rettype and calltype follow the original declaration in Windows.h + * fn is the true function name - beware Ansi/Unicode #defined macros + * ord is the ordinal within the library, use 0 if it varies between versions + * args is the parameter list following the original declaration, in parens + * names is the parameter list sans data types, enclosed in parens + * + * #undef/re#define the Ansi/Unicode generic name to abate confusion + * In the case of non-text functions, simply #define the original name + */ + +#if !defined(_WIN32_WCE) && !defined(WINNT) +/* This group is available to all versions of WINNT 4.0 SP6 and later */ + +#ifdef GetFileAttributesExA +#undef GetFileAttributesExA +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, GetFileAttributesExA, 0, ( + IN LPCSTR lpFileName, + IN GET_FILEEX_INFO_LEVELS fInfoLevelId, + OUT LPVOID lpFileInformation), + (lpFileName, fInfoLevelId, lpFileInformation)); +#define GetFileAttributesExA apr_winapi_GetFileAttributesExA +#undef GetFileAttributesEx +#define GetFileAttributesEx apr_winapi_GetFileAttributesExA + +#ifdef GetFileAttributesExW +#undef GetFileAttributesExW +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, GetFileAttributesExW, 0, ( + IN LPCWSTR lpFileName, + IN GET_FILEEX_INFO_LEVELS fInfoLevelId, + OUT LPVOID lpFileInformation), + (lpFileName, fInfoLevelId, lpFileInformation)); +#define GetFileAttributesExW apr_winapi_GetFileAttributesExW + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, CancelIo, 0, ( + IN HANDLE hFile), + (hFile)); +#define CancelIo apr_winapi_CancelIo + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, TryEnterCriticalSection, 0, ( + LPCRITICAL_SECTION lpCriticalSection), + (lpCriticalSection)); +#define TryEnterCriticalSection apr_winapi_TryEnterCriticalSection + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, SwitchToThread, 0, ( + void), + ()); +#define SwitchToThread apr_winapi_SwitchToThread + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINADVAPI, BOOL, WINAPI, GetEffectiveRightsFromAclW, 0, ( + IN PACL pacl, + IN PTRUSTEE_W pTrustee, + OUT PACCESS_MASK pAccessRights), + (pacl, pTrustee, pAccessRights)); +#define GetEffectiveRightsFromAclW apr_winapi_GetEffectiveRightsFromAclW + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINADVAPI, BOOL, WINAPI, GetNamedSecurityInfoW, 0, ( + IN LPWSTR pObjectName, + IN SE_OBJECT_TYPE ObjectType, + IN SECURITY_INFORMATION SecurityInfo, + OUT PSID *ppsidOwner, + OUT PSID *ppsidGroup, + OUT PACL *ppDacl, + OUT PACL *ppSacl, + OUT PSECURITY_DESCRIPTOR *ppSecurityDescriptor), + (pObjectName, ObjectType, SecurityInfo, ppsidOwner, ppsidGroup, + ppDacl, ppSacl, ppSecurityDescriptor)); +#define GetNamedSecurityInfoW apr_winapi_GetNamedSecurityInfoW + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINADVAPI, BOOL, WINAPI, GetNamedSecurityInfoA, 0, ( + IN LPSTR pObjectName, + IN SE_OBJECT_TYPE ObjectType, + IN SECURITY_INFORMATION SecurityInfo, + OUT PSID *ppsidOwner, + OUT PSID *ppsidGroup, + OUT PACL *ppDacl, + OUT PACL *ppSacl, + OUT PSECURITY_DESCRIPTOR *ppSecurityDescriptor), + (pObjectName, ObjectType, SecurityInfo, ppsidOwner, ppsidGroup, + ppDacl, ppSacl, ppSecurityDescriptor)); +#define GetNamedSecurityInfoA apr_winapi_GetNamedSecurityInfoA +#undef GetNamedSecurityInfo +#define GetNamedSecurityInfo apr_winapi_GetNamedSecurityInfoA + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINADVAPI, BOOL, WINAPI, GetSecurityInfo, 0, ( + IN HANDLE handle, + IN SE_OBJECT_TYPE ObjectType, + IN SECURITY_INFORMATION SecurityInfo, + OUT PSID *ppsidOwner, + OUT PSID *ppsidGroup, + OUT PACL *ppDacl, + OUT PACL *ppSacl, + OUT PSECURITY_DESCRIPTOR *ppSecurityDescriptor), + (handle, ObjectType, SecurityInfo, ppsidOwner, ppsidGroup, + ppDacl, ppSacl, ppSecurityDescriptor)); +#define GetSecurityInfo apr_winapi_GetSecurityInfo + +APR_DECLARE_LATE_DLL_FUNC(DLL_SHSTDAPI, LPWSTR *, WINAPI, CommandLineToArgvW, 0, ( + LPCWSTR lpCmdLine, + int *pNumArgs), + (lpCmdLine, pNumArgs)); +#define CommandLineToArgvW apr_winapi_CommandLineToArgvW + +#endif /* !defined(_WIN32_WCE) && !defined(WINNT) */ + +#if !defined(_WIN32_WCE) +/* This group is NOT available to all versions of WinNT, + * these we must always look up + */ + +#ifdef GetCompressedFileSizeA +#undef GetCompressedFileSizeA +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, DWORD, WINAPI, GetCompressedFileSizeA, 0, ( + IN LPCSTR lpFileName, + OUT LPDWORD lpFileSizeHigh), + (lpFileName, lpFileSizeHigh)); +#define GetCompressedFileSizeA apr_winapi_GetCompressedFileSizeA +#undef GetCompressedFileSize +#define GetCompressedFileSize apr_winapi_GetCompressedFileSizeA + +#ifdef GetCompressedFileSizeW +#undef GetCompressedFileSizeW +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, DWORD, WINAPI, GetCompressedFileSizeW, 0, ( + IN LPCWSTR lpFileName, + OUT LPDWORD lpFileSizeHigh), + (lpFileName, lpFileSizeHigh)); +#define GetCompressedFileSizeW apr_winapi_GetCompressedFileSizeW + + +APR_DECLARE_LATE_DLL_FUNC(DLL_NTDLL, LONG, WINAPI, NtQueryTimerResolution, 0, ( + ULONG *pMaxRes, /* Minimum NS Resolution */ + ULONG *pMinRes, /* Maximum NS Resolution */ + ULONG *pCurRes), /* Current NS Resolution */ + (pMaxRes, pMinRes, pCurRes)); +#define QueryTimerResolution apr_winapi_NtQueryTimerResolution + +APR_DECLARE_LATE_DLL_FUNC(DLL_NTDLL, LONG, WINAPI, NtSetTimerResolution, 0, ( + ULONG ReqRes, /* Requested NS Clock Resolution */ + BOOL Acquire, /* Aquire (1) or Release (0) our interest */ + ULONG *pNewRes), /* The NS Clock Resolution granted */ + (ReqRes, Acquire, pNewRes)); +#define SetTimerResolution apr_winapi_NtSetTimerResolution + +typedef struct PBI { + LONG ExitStatus; + PVOID PebBaseAddress; + apr_uintptr_t AffinityMask; + LONG BasePriority; + apr_uintptr_t UniqueProcessId; + apr_uintptr_t InheritedFromUniqueProcessId; +} PBI, *PPBI; + +APR_DECLARE_LATE_DLL_FUNC(DLL_NTDLL, LONG, WINAPI, NtQueryInformationProcess, 0, ( + HANDLE hProcess, /* Obvious */ + INT info, /* Use 0 for PBI documented above */ + PVOID pPI, /* The PIB buffer */ + ULONG LenPI, /* Use sizeof(PBI) */ + ULONG *pSizePI), /* returns pPI buffer used (may pass NULL) */ + (hProcess, info, pPI, LenPI, pSizePI)); +#define QueryInformationProcess apr_winapi_NtQueryInformationProcess + +APR_DECLARE_LATE_DLL_FUNC(DLL_NTDLL, LONG, WINAPI, NtQueryObject, 0, ( + HANDLE hObject, /* Obvious */ + INT info, /* Use 0 for PBI documented above */ + PVOID pOI, /* The PIB buffer */ + ULONG LenOI, /* Use sizeof(PBI) */ + ULONG *pSizeOI), /* returns pPI buffer used (may pass NULL) */ + (hObject, info, pOI, LenOI, pSizeOI)); +#define QueryObject apr_winapi_NtQueryObject + +typedef struct IOSB { + union { + UINT Status; + PVOID reserved; + }; + apr_uintptr_t Information; /* Varies by op, consumed buffer size for FSI below */ +} IOSB, *PIOSB; + +typedef struct FSI { + LONGLONG AllocationSize; + LONGLONG EndOfFile; + ULONG NumberOfLinks; + BOOL DeletePending; + BOOL Directory; +} FSI, *PFSI; + +APR_DECLARE_LATE_DLL_FUNC(DLL_NTDLL, LONG, WINAPI, ZwQueryInformationFile, 0, ( + HANDLE hObject, /* Obvious */ + PVOID pIOSB, /* Point to the IOSB buffer for detailed return results */ + PVOID pFI, /* The buffer, using FIB above */ + ULONG LenFI, /* Use sizeof(FI) */ + ULONG info), /* Use 5 for FSI documented above*/ + (hObject, pIOSB, pFI, LenFI, info)); +#define ZwQueryInformationFile apr_winapi_ZwQueryInformationFile + +#ifdef CreateToolhelp32Snapshot +#undef CreateToolhelp32Snapshot +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, HANDLE, WINAPI, CreateToolhelp32Snapshot, 0, ( + DWORD dwFlags, + DWORD th32ProcessID), + (dwFlags, th32ProcessID)); +#define CreateToolhelp32Snapshot apr_winapi_CreateToolhelp32Snapshot + +#ifdef Process32FirstW +#undef Process32FirstW +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, Process32FirstW, 0, ( + HANDLE hSnapshot, + LPPROCESSENTRY32W lppe), + (hSnapshot, lppe)); +#define Process32FirstW apr_winapi_Process32FirstW + +#ifdef Process32NextW +#undef Process32NextW +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, Process32NextW, 0, ( + HANDLE hSnapshot, + LPPROCESSENTRY32W lppe), + (hSnapshot, lppe)); +#define Process32NextW apr_winapi_Process32NextW + +#if !defined(POLLERR) +/* Event flag definitions for WSAPoll(). */ +#define POLLRDNORM 0x0100 +#define POLLRDBAND 0x0200 +#define POLLIN (POLLRDNORM | POLLRDBAND) +#define POLLPRI 0x0400 + +#define POLLWRNORM 0x0010 +#define POLLOUT (POLLWRNORM) +#define POLLWRBAND 0x0020 + +#define POLLERR 0x0001 +#define POLLHUP 0x0002 +#define POLLNVAL 0x0004 + +typedef struct pollfd { + SOCKET fd; + SHORT events; + SHORT revents; + +} WSAPOLLFD, *PWSAPOLLFD, FAR *LPWSAPOLLFD; + +#endif /* !defined(POLLERR) */ +#ifdef WSAPoll +#undef WSAPoll +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINSOCK2API, int, WSAAPI, WSAPoll, 0, ( + IN OUT LPWSAPOLLFD fdArray, + IN ULONG fds, + IN INT timeout), + (fdArray, fds, timeout)); +#define WSAPoll apr_winapi_WSAPoll +#define HAVE_POLL 1 + +#ifdef SetDllDirectoryW +#undef SetDllDirectoryW +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, SetDllDirectoryW, 0, ( + IN LPCWSTR lpPathName), + (lpPathName)); +#define SetDllDirectoryW apr_winapi_SetDllDirectoryW + +#ifdef if_nametoindex +#undef if_nametoindex +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_IPHLPAPI, NET_IFINDEX, WINAPI, if_nametoindex, 0, ( + IN PCSTR InterfaceName), + (InterfaceName)); +#define if_nametoindex apr_winapi_if_nametoindex + +#ifdef if_indextoname +#undef if_indextoname +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_IPHLPAPI, PCHAR, NETIOAPI_API_, if_indextoname, 0, ( + NET_IFINDEX InterfaceIndex, + PCHAR InterfaceName), + (InterfaceIndex, InterfaceName)); +#define if_indextoname apr_winapi_if_indextoname + +#endif /* !defined(_WIN32_WCE) */ + +#endif /* ! MISC_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_networkio.h b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_networkio.h new file mode 100644 index 00000000..04be5559 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_networkio.h @@ -0,0 +1,90 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETWORK_IO_H +#define NETWORK_IO_H + +#include "apr_network_io.h" +#include "apr_general.h" +#include "apr_poll.h" + +typedef struct sock_userdata_t sock_userdata_t; +struct sock_userdata_t { + sock_userdata_t *next; + const char *key; + void *data; +}; + +struct apr_socket_t { + apr_pool_t *pool; + SOCKET socketdes; + int type; /* SOCK_STREAM, SOCK_DGRAM */ + int protocol; + apr_sockaddr_t *local_addr; + apr_sockaddr_t *remote_addr; + int timeout_ms; /* MUST MATCH if timeout > 0 */ + apr_interval_time_t timeout; + apr_int32_t disconnected; + int local_port_unknown; + int local_interface_unknown; + int remote_addr_unknown; + apr_int32_t options; + apr_int32_t inherit; +#if APR_HAS_SENDFILE + /* As of 07.20.04, the overlapped structure is only used by + * apr_socket_sendfile and that's where it will be allocated + * and initialized. + */ + OVERLAPPED *overlapped; +#endif + sock_userdata_t *userdata; + + /* if there is a timeout set, then this pollset is used */ + apr_pollset_t *pollset; +}; + +#ifdef _WIN32_WCE +#ifndef WSABUF +typedef struct _WSABUF { + u_long len; /* the length of the buffer */ + char FAR * buf; /* the pointer to the buffer */ +} WSABUF, FAR * LPWSABUF; +#endif +#else +#ifdef _MSC_VER +#define HAVE_STRUCT_IPMREQ +#endif +#endif + +apr_status_t status_from_res_error(int); + +const char *apr_inet_ntop(int af, const void *src, char *dst, apr_size_t size); +int apr_inet_pton(int af, const char *src, void *dst); +void apr_sockaddr_vars_set(apr_sockaddr_t *, int, apr_port_t); + +#define apr_is_option_set(skt, option) \ + (((skt)->options & (option)) == (option)) + +#define apr_set_option(skt, option, on) \ + do { \ + if (on) \ + (skt)->options |= (option); \ + else \ + (skt)->options &= ~(option); \ + } while (0) + +#endif /* ! NETWORK_IO_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_proc_mutex.h b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_proc_mutex.h new file mode 100644 index 00000000..4e3e3993 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_proc_mutex.h @@ -0,0 +1,29 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PROC_MUTEX_H +#define PROC_MUTEX_H + +#include "apr_proc_mutex.h" + +struct apr_proc_mutex_t { + apr_pool_t *pool; + HANDLE handle; + const char *fname; +}; + +#endif /* PROC_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_thread_cond.h b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_thread_cond.h new file mode 100644 index 00000000..c7f69f80 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_thread_cond.h @@ -0,0 +1,32 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_COND_H +#define THREAD_COND_H + +#include "apr_thread_cond.h" + +struct apr_thread_cond_t { + apr_pool_t *pool; + HANDLE semaphore; + CRITICAL_SECTION csection; + unsigned long num_waiting; + unsigned long num_wake; + unsigned long generation; +}; + +#endif /* THREAD_COND_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_thread_mutex.h b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_thread_mutex.h new file mode 100644 index 00000000..13d3c1cb --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_thread_mutex.h @@ -0,0 +1,40 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_MUTEX_H +#define THREAD_MUTEX_H + +#include "apr_pools.h" + +typedef enum thread_mutex_type { + thread_mutex_critical_section, + thread_mutex_unnested_event, + thread_mutex_nested_mutex +} thread_mutex_type; + +/* handle applies only to unnested_event on all platforms + * and nested_mutex on Win9x only. Otherwise critical_section + * is used for NT nexted mutexes providing optimal performance. + */ +struct apr_thread_mutex_t { + apr_pool_t *pool; + thread_mutex_type type; + HANDLE handle; + CRITICAL_SECTION section; +}; + +#endif /* THREAD_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_thread_rwlock.h b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_thread_rwlock.h new file mode 100644 index 00000000..1177e529 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_thread_rwlock.h @@ -0,0 +1,30 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_RWLOCK_H +#define THREAD_RWLOCK_H + +#include "apr_thread_rwlock.h" + +struct apr_thread_rwlock_t { + apr_pool_t *pool; + HANDLE write_mutex; + HANDLE read_event; + LONG readers; +}; + +#endif /* THREAD_RWLOCK_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_threadproc.h b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_threadproc.h new file mode 100644 index 00000000..d3ce9c51 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_threadproc.h @@ -0,0 +1,74 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr_private.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" + +#ifndef THREAD_PROC_H +#define THREAD_PROC_H + +#define SHELL_PATH "cmd.exe" + +struct apr_thread_t { + apr_pool_t *pool; + HANDLE td; + apr_int32_t cancel; + apr_int32_t cancel_how; + void *data; + apr_thread_start_t func; + apr_status_t exitval; +}; + +struct apr_threadattr_t { + apr_pool_t *pool; + apr_int32_t detach; + apr_size_t stacksize; +}; + +struct apr_threadkey_t { + apr_pool_t *pool; + DWORD key; +}; + +struct apr_procattr_t { + apr_pool_t *pool; + apr_file_t *parent_in; + apr_file_t *child_in; + apr_file_t *parent_out; + apr_file_t *child_out; + apr_file_t *parent_err; + apr_file_t *child_err; + char *currdir; + apr_int32_t cmdtype; + apr_int32_t detached; + apr_child_errfn_t *errfn; + apr_int32_t errchk; +#ifndef _WIN32_WCE + HANDLE user_token; + LPSECURITY_ATTRIBUTES sa; + LPVOID sd; +#endif +}; + +struct apr_thread_once_t { + long value; +}; + +extern apr_status_t apr_threadproc_init(apr_pool_t *pool); + +#endif /* ! THREAD_PROC_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_utf8.h b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_utf8.h new file mode 100644 index 00000000..84f8bf77 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_arch_utf8.h @@ -0,0 +1,56 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef UTF8_H +#define UTF8_H + +#include "apr.h" +#include "apr_lib.h" +#include "apr_errno.h" + +/* If we ever support anything more exciting than char... this could move. + */ +typedef apr_uint16_t apr_wchar_t; + +/** + * An APR internal function for fast utf-8 octet-encoded Unicode conversion + * to the ucs-2 wide Unicode format. This function is used for filename and + * other resource conversions for platforms providing native Unicode support. + * + * @tip Only the errors APR_EINVAL and APR_INCOMPLETE may occur, the former + * when the character code is invalid (in or out of context) and the later + * when more characters were expected, but insufficient characters remain. + */ +APR_DECLARE(apr_status_t) apr_conv_utf8_to_ucs2(const char *in, + apr_size_t *inbytes, + apr_wchar_t *out, + apr_size_t *outwords); + +/** + * An APR internal function for fast ucs-2 wide Unicode format conversion to + * the utf-8 octet-encoded Unicode. This function is used for filename and + * other resource conversions for platforms providing native Unicode support. + * + * @tip Only the errors APR_EINVAL and APR_INCOMPLETE may occur, the former + * when the character code is invalid (in or out of context) and the later + * when more words were expected, but insufficient words remain. + */ +APR_DECLARE(apr_status_t) apr_conv_ucs2_to_utf8(const apr_wchar_t *in, + apr_size_t *inwords, + char *out, + apr_size_t *outbytes); + +#endif /* def UTF8_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_dbg_win32_handles.h b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_dbg_win32_handles.h new file mode 100644 index 00000000..471cd66d --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_dbg_win32_handles.h @@ -0,0 +1,217 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_DBG_WIN32_HANDLES_H +#define APR_DBG_WIN32_HANDLES_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* USAGE: + * + * Add the following include to apr_private.h for internal debugging, + * or copy this header into apr/include add the include below to apr.h + * for really global debugging; + * + * #include "apr_dbg_win32_handles.h" + * + * apr_dbg_log is the crux of this function ... it uses Win32 API and + * no apr calls itself to log all activity to a file named for the + * executing application with a .pid suffix. Ergo several instances + * may be executing and logged at once. + * + * HANDLE apr_dbg_log(char* fn, HANDLE ha, char* fl, int ln, int nh + * [, HANDLE *hv, char *dsc...]) + * + * returns: the handle passed in ha, which is cast back to the real return type. + * + * formats one line into the debug log file if nh is zero; + * ha (hex) seq(hex) tid(hex) fn fl ln + * xxxxxxxx xxxxxxxx xxxxxxxx func() sourcefile:lineno + * The macro apr_dbg_rv makes this simple to implement for many APIs + * that simply take args that don't interest us, and return a handle. + * + * formats multiple lines (nh) into the debug log file for each hv/dsc pair + * (nh must correspond to the number of pairs); + * hv (hex) seq(hex) tid(hex) fn dsc fl ln + * xxxxxxxx xxxxxxxx xxxxxxxx func(arg) sourcefile:lineno + * In this later usage, hv is the still the return value but is not + * treated as a handle. + */ + +APR_DECLARE_NONSTD(HANDLE) apr_dbg_log(char* fn, HANDLE ha, char* fl, int ln, + int nh,/* HANDLE *hv, char *dsc */...); + +#define apr_dbg_rv(fn, args) (apr_dbg_log(#fn,(fn) args,__FILE__,__LINE__,0)) + +#define CloseHandle(h) \ + ((BOOL)apr_dbg_log("CloseHandle", \ + (HANDLE)(CloseHandle)(h), \ + __FILE__,__LINE__,1, \ + &(h),"")) + +#define CreateEventA(sd,b1,b2,nm) apr_dbg_rv(CreateEventA,(sd,b1,b2,nm)) +#define CreateEventW(sd,b1,b2,nm) apr_dbg_rv(CreateEventW,(sd,b1,b2,nm)) + +#define CreateFileA(nm,d1,d2,sd,d3,d4,h) apr_dbg_rv(CreateFileA,(nm,d1,d2,sd,d3,d4,h)) +#define CreateFileW(nm,d1,d2,sd,d3,d4,h) apr_dbg_rv(CreateFileW,(nm,d1,d2,sd,d3,d4,h)) + +#define CreateFileMappingA(fh,sd,d1,d2,d3,nm) apr_dbg_rv(CreateFileMappingA,(fh,sd,d1,d2,d3,nm)) +#define CreateFileMappingW(fh,sd,d1,d2,d3,nm) apr_dbg_rv(CreateFileMappingW,(fh,sd,d1,d2,d3,nm)) + +#define CreateMutexA(sd,b,nm) apr_dbg_rv(CreateMutexA,(sd,b,nm)) +#define CreateMutexW(sd,b,nm) apr_dbg_rv(CreateMutexW,(sd,b,nm)) + +#define CreateIoCompletionPort(h1,h2,pd1,d2) apr_dbg_rv(CreateIoCompletionPort,(h1,h2,pd1,d2)) + +#define CreateNamedPipeA(nm,d1,d2,d3,d4,d5,d6,sd) apr_dbg_rv(CreateNamedPipeA,(nm,d1,d2,d3,d4,d5,d6,sd)) +#define CreateNamedPipeW(nm,d1,d2,d3,d4,d5,d6,sd) apr_dbg_rv(CreateNamedPipeW,(nm,d1,d2,d3,d4,d5,d6,sd)) + +#define CreatePipe(ph1,ph2,sd,d) \ + ((BOOL)apr_dbg_log("CreatePipe", \ + (HANDLE)(CreatePipe)(ph1,ph2,sd,d), \ + __FILE__,__LINE__,2, \ + (ph1),"hRead", \ + (ph2),"hWrite")) + +#define CreateProcessA(s1,s2,sd1,sd2,b,d1,s3,s4,pd2,hr) \ + ((BOOL)apr_dbg_log("CreateProcessA", \ + (HANDLE)(CreateProcessA)(s1,s2,sd1,sd2,b,d1,s3,s4,pd2,hr), \ + __FILE__,__LINE__,2, \ + &((hr)->hProcess),"hProcess", \ + &((hr)->hThread),"hThread")) +#define CreateProcessW(s1,s2,sd1,sd2,b,d1,s3,s4,pd2,hr) \ + ((BOOL)apr_dbg_log("CreateProcessW", \ + (HANDLE)(CreateProcessW)(s1,s2,sd1,sd2,b,d1,s3,s4,pd2,hr), \ + __FILE__,__LINE__,2, \ + &((hr)->hProcess),"hProcess", \ + &((hr)->hThread),"hThread")) + +#define CreateSemaphoreA(sd,d1,d2,nm) apr_dbg_rv(CreateSemaphoreA,(sd,d1,d2,nm)) +#define CreateSemaphoreW(sd,d1,d2,nm) apr_dbg_rv(CreateSemaphoreW,(sd,d1,d2,nm)) + +#define CreateThread(sd,d1,fn,pv,d2,pd3) apr_dbg_rv(CreateThread,(sd,d1,fn,pv,d2,pd3)) + +#define DeregisterEventSource(h) \ + ((BOOL)apr_dbg_log("DeregisterEventSource", \ + (HANDLE)(DeregisterEventSource)(h), \ + __FILE__,__LINE__,1, \ + &(h),"")) + +#define DuplicateHandle(h1,h2,h3,ph4,d1,b,d2) \ + ((BOOL)apr_dbg_log("DuplicateHandle", \ + (HANDLE)(DuplicateHandle)(h1,h2,h3,ph4,d1,b,d2), \ + __FILE__,__LINE__,2, \ + (ph4),((h3)==GetCurrentProcess()) \ + ? "Target" : "EXTERN Target", \ + &(h2),((h1)==GetCurrentProcess()) \ + ? "Source" : "EXTERN Source")) + +#define GetCurrentProcess() \ + (apr_dbg_log("GetCurrentProcess", \ + (GetCurrentProcess)(),__FILE__,__LINE__,0)) + +#define GetCurrentThread() \ + (apr_dbg_log("GetCurrentThread", \ + (GetCurrentThread)(),__FILE__,__LINE__,0)) + +#define GetModuleHandleA(nm) apr_dbg_rv(GetModuleHandleA,(nm)) +#define GetModuleHandleW(nm) apr_dbg_rv(GetModuleHandleW,(nm)) + +#define GetStdHandle(d) apr_dbg_rv(GetStdHandle,(d)) + +#define LoadLibraryA(nm) apr_dbg_rv(LoadLibraryA,(nm)) +#define LoadLibraryW(nm) apr_dbg_rv(LoadLibraryW,(nm)) + +#define LoadLibraryExA(nm,h,d) apr_dbg_rv(LoadLibraryExA,(nm,h,d)) +#define LoadLibraryExW(nm,h,d) apr_dbg_rv(LoadLibraryExW,(nm,h,d)) + +#define OpenEventA(d,b,nm) apr_dbg_rv(OpenEventA,(d,b,nm)) +#define OpenEventW(d,b,nm) apr_dbg_rv(OpenEventW,(d,b,nm)) + +#define OpenFileMappingA(d,b,nm) apr_dbg_rv(OpenFileMappingA,(d,b,nm)) +#define OpenFileMappingW(d,b,nm) apr_dbg_rv(OpenFileMappingW,(d,b,nm)) + +#define RegisterEventSourceA(s1,s2) apr_dbg_rv(RegisterEventSourceA,(s1,s2)) +#define RegisterEventSourceW(s1,s2) apr_dbg_rv(RegisterEventSourceW,(s1,s2)) + +#define SetEvent(h) \ + ((BOOL)apr_dbg_log("SetEvent", \ + (HANDLE)(SetEvent)(h), \ + __FILE__,__LINE__,1, \ + &(h),"")) + +#define SetStdHandle(d,h) \ + ((BOOL)apr_dbg_log("SetStdHandle", \ + (HANDLE)(SetStdHandle)(d,h), \ + __FILE__,__LINE__,1,&(h),"")) + +#define socket(i1,i2,i3) \ + ((SOCKET)apr_dbg_log("socket", \ + (HANDLE)(socket)(i1,i2,i3), \ + __FILE__,__LINE__,0)) + +#define WaitForSingleObject(h,d) \ + ((DWORD)apr_dbg_log("WaitForSingleObject", \ + (HANDLE)(WaitForSingleObject)(h,d), \ + __FILE__,__LINE__,1,&(h),"Signaled")) + +#define WaitForSingleObjectEx(h,d,b) \ + ((DWORD)apr_dbg_log("WaitForSingleObjectEx", \ + (HANDLE)(WaitForSingleObjectEx)(h,d,b), \ + __FILE__,__LINE__,1,&(h),"Signaled")) + +#define WaitForMultipleObjects(d1,ah,b,d2) \ + ((DWORD)apr_dbg_log("WaitForMultipleObjects", \ + (HANDLE)(WaitForMultipleObjects)(d1,ah,b,d2), \ + __FILE__,__LINE__,1,ah,"Signaled")) + +#define WaitForMultipleObjectsEx(d1,ah,b1,d2,b2) \ + ((DWORD)apr_dbg_log("WaitForMultipleObjectsEx", \ + (HANDLE)(WaitForMultipleObjectsEx)(d1,ah,b1,d2,b2), \ + __FILE__,__LINE__,1,ah,"Signaled")) + +#define WSASocketA(i1,i2,i3,pi,g,dw) \ + ((SOCKET)apr_dbg_log("WSASocketA", \ + (HANDLE)(WSASocketA)(i1,i2,i3,pi,g,dw), \ + __FILE__,__LINE__,0)) + +#define WSASocketW(i1,i2,i3,pi,g,dw) \ + ((SOCKET)apr_dbg_log("WSASocketW", \ + (HANDLE)(WSASocketW)(i1,i2,i3,pi,g,dw), \ + __FILE__,__LINE__,0)) + +#define closesocket(sh) \ + ((int)apr_dbg_log("closesocket", \ + (HANDLE)(closesocket)(sh), \ + __FILE__,__LINE__,1,&(sh),"")) + +#define _beginthread(fn,d,pv) \ + ((unsigned long)apr_dbg_log("_beginthread", \ + (HANDLE)(_beginthread)(fn,d,pv), \ + __FILE__,__LINE__,0)) + +#define _beginthreadex(sd,d1,fn,pv,d2,pd3) \ + ((unsigned long)apr_dbg_log("_beginthreadex", \ + (HANDLE)(_beginthreadex)(sd,d1,fn,pv,d2,pd3), \ + __FILE__,__LINE__,0)) + +#ifdef __cplusplus +} +#endif + +#endif /* !defined(APR_DBG_WIN32_HANDLES_H) */ diff --git a/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_private.h b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_private.h new file mode 100644 index 00000000..c631ad43 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/arch/win32/apr_private.h @@ -0,0 +1,175 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Note: + * This is the windows specific autoconf-like config file + * which unix would create at build time. + */ + +#ifdef WIN32 + +#ifndef APR_PRIVATE_H +#define APR_PRIVATE_H + +/* Include the public APR symbols, include our idea of the 'right' + * subset of the Windows.h header. This saves us repetition. + */ +#include "apr.h" + +/* + * Add a _very_few_ declarations missing from the restricted set of headers + * (If this list becomes extensive, re-enable the required headers above!) + * winsock headers were excluded by WIN32_LEAN_AND_MEAN, so include them now + */ +#ifndef SW_HIDE +#define SW_HIDE 0 +#endif + +/* For the misc.h late-loaded dynamic symbols, we need some obscure types + * Avoid dragging in wtypes.h unless it's absolutely necessary [generally + * not with APR itself, until some GUI-related security is introduced.] + */ +#ifndef _WIN32_WCE +#define HAVE_ACLAPI 1 +#ifdef __wtypes_h__ +#include +#else +#define __wtypes_h__ +#include +#undef __wtypes_h__ +#endif +#else +#define HAVE_ACLAPI 0 +#endif + +#if APR_HAVE_SYS_TYPES_H +#include +#endif +#if APR_HAVE_STDDEF_H +#include +#endif +#include +#if APR_HAVE_TIME_H +#include +#endif + +/* Use this section to define all of the HAVE_FOO_H + * that are required to build properly. + */ +#define HAVE_LIMITS_H 1 +#define HAVE_MALLOC_H 1 +#define HAVE_SIGNAL_H 1 +/* #define HAVE_STDDEF_H 1 why not? */ +#define HAVE_STDLIB_H 1 + +#define HAVE_STRICMP 1 +#define HAVE_STRNICMP 1 +#define HAVE_STRDUP 1 +#define HAVE_STRSTR 1 +#define HAVE_MEMCHR 1 + +#define SIGHUP 1 +/* 2 is used for SIGINT on windows */ +#define SIGQUIT 3 +/* 4 is used for SIGILL on windows */ +#define SIGTRAP 5 +#define SIGIOT 6 +#define SIGBUS 7 +/* 8 is used for SIGFPE on windows */ +#define SIGKILL 9 +#define SIGUSR1 10 +/* 11 is used for SIGSEGV on windows */ +#define SIGUSR2 12 +#define SIGPIPE 13 +#define SIGALRM 14 +/* 15 is used for SIGTERM on windows */ +#define SIGSTKFLT 16 +#define SIGCHLD 17 +#define SIGCONT 18 +#define SIGSTOP 19 +#define SIGTSTP 20 +/* 21 is used for SIGBREAK on windows */ +/* 22 is used for SIGABRT on windows */ +#define SIGTTIN 23 +#define SIGTTOU 24 +#define SIGURG 25 +#define SIGXCPU 26 +#define SIGXFSZ 27 +#define SIGVTALRM 28 +#define SIGPROF 29 +#define SIGWINCH 30 +#define SIGIO 31 + +/* APR COMPATABILITY FUNCTIONS + * This section should be used to define functions and + * macros which are need to make Windows features look + * like POSIX features. + */ +typedef void (Sigfunc)(int); + +#define sleep(t) Sleep((t) * 1000) + +#define SIZEOF_SHORT 2 +#define SIZEOF_INT 4 +#define SIZEOF_LONGLONG 8 +#define SIZEOF_CHAR 1 +#define SIZEOF_SSIZE_T SIZEOF_INT + +unsigned __stdcall SignalHandling(void *); +int thread_ready(void); + +#if !APR_HAVE_ERRNO_H +APR_DECLARE_DATA int errno; +#define ENOSPC 1 +#endif + +#if APR_HAVE_IPV6 +#define HAVE_GETADDRINFO 1 +#define HAVE_GETNAMEINFO 1 +#define HAVE_IF_INDEXTONAME 1 +#define HAVE_IF_NAMETOINDEX 1 +#endif + +/* MSVC 7.0 introduced _strtoi64 */ +#if _MSC_VER >= 1300 && _INTEGRAL_MAX_BITS >= 64 && !defined(_WIN32_WCE) +#define APR_INT64_STRFN _strtoi64 +#endif + +#if APR_HAS_LARGE_FILES +#ifdef APR_INT64_STRFN +#define APR_OFF_T_STRFN APR_INT64_STRFN +#else +#define APR_OFF_T_STRFN apr_strtoi64 +#endif +#else +#if defined(_WIN32_WCE) +#define APR_OFF_T_STRFN strtol +#else +#define APR_OFF_T_STRFN strtoi +#endif +#endif + +/* used to check for DWORD overflow in 64bit compiles */ +#define APR_DWORD_MAX 0xFFFFFFFFUL + +/* + * Include common private declarations. + */ +#include "../apr_private_common.h" + +#endif /*APR_PRIVATE_H*/ +#endif /*WIN32*/ diff --git a/c/dependencies/windows/apr/x64_debug/include/private/apr_crypto_internal.h b/c/dependencies/windows/apr/x64_debug/include/private/apr_crypto_internal.h new file mode 100644 index 00000000..1ea838bf --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/private/apr_crypto_internal.h @@ -0,0 +1,297 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_CRYPTO_INTERNAL_H +#define APR_CRYPTO_INTERNAL_H + +#include + +#include "apr_crypto.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if APU_HAVE_CRYPTO + +struct apr_crypto_driver_t { + + /** name */ + const char *name; + + /** + * @brief: allow driver to perform once-only initialisation. + * Called once only. + * @param pool The pool to register the cleanup in. + * @param params Optional init parameter string. + * @param rc Driver-specific additional error code + */ + apr_status_t (*init)(apr_pool_t *pool, const char *params, + const apu_err_t **result); + + /** + * @brief Create a context for supporting encryption. Keys, certificates, + * algorithms and other parameters will be set per context. More than + * one context can be created at one time. A cleanup will be automatically + * registered with the given pool to guarantee a graceful shutdown. + * @param f - context pointer will be written here + * @param provider - provider to use + * @param params - array of key parameters + * @param pool - process pool + * @return APR_ENOENGINE when the engine specified does not exist. APR_EINITENGINE + * if the engine cannot be initialised. + */ + apr_status_t (*make)(apr_crypto_t **f, const apr_crypto_driver_t *provider, + const char *params, apr_pool_t *pool); + + /** + * @brief Get a hash table of key types, keyed by the name of the type against + * a pointer to apr_crypto_block_key_type_t. + * + * @param types - hashtable of key types keyed to constants. + * @param f - encryption context + * @return APR_SUCCESS for success + */ + apr_status_t (*get_block_key_types)(apr_hash_t **types, + const apr_crypto_t *f); + + /** + * @brief Get a hash table of key modes, keyed by the name of the mode against + * a pointer to apr_crypto_block_key_mode_t. + * + * @param modes - hashtable of key modes keyed to constants. + * @param f - encryption context + * @return APR_SUCCESS for success + */ + apr_status_t (*get_block_key_modes)(apr_hash_t **modes, + const apr_crypto_t *f); + + /** + * @brief Create a key from the given passphrase. By default, the PBKDF2 + * algorithm is used to generate the key from the passphrase. It is expected + * that the same pass phrase will generate the same key, regardless of the + * backend crypto platform used. The key is cleaned up when the context + * is cleaned, and may be reused with multiple encryption or decryption + * operations. + * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If + * *key is not NULL, *key must point at a previously created structure. + * @param key The key returned, see note. + * @param ivSize The size of the initialisation vector will be returned, based + * on whether an IV is relevant for this type of crypto. + * @param pass The passphrase to use. + * @param passLen The passphrase length in bytes + * @param salt The salt to use. + * @param saltLen The salt length in bytes + * @param type 3DES_192, AES_128, AES_192, AES_256. + * @param mode Electronic Code Book / Cipher Block Chaining. + * @param doPad Pad if necessary. + * @param iterations Iteration count + * @param f The context to use. + * @param p The pool to use. + * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend + * error occurred while generating the key. APR_ENOCIPHER if the type or mode + * is not supported by the particular backend. APR_EKEYTYPE if the key type is + * not known. APR_EPADDING if padding was requested but is not supported. + * APR_ENOTIMPL if not implemented. + */ + apr_status_t (*passphrase)(apr_crypto_key_t **key, apr_size_t *ivSize, + const char *pass, apr_size_t passLen, const unsigned char * salt, + apr_size_t saltLen, const apr_crypto_block_key_type_e type, + const apr_crypto_block_key_mode_e mode, const int doPad, + const int iterations, const apr_crypto_t *f, apr_pool_t *p); + + /** + * @brief Initialise a context for encrypting arbitrary data using the given key. + * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If + * *ctx is not NULL, *ctx must point at a previously created structure. + * @param ctx The block context returned, see note. + * @param iv Optional initialisation vector. If the buffer pointed to is NULL, + * an IV will be created at random, in space allocated from the pool. + * If the buffer pointed to is not NULL, the IV in the buffer will be + * used. + * @param key The key structure. + * @param blockSize The block size of the cipher. + * @param p The pool to use. + * @return Returns APR_ENOIV if an initialisation vector is required but not specified. + * Returns APR_EINIT if the backend failed to initialise the context. Returns + * APR_ENOTIMPL if not implemented. + */ + apr_status_t (*block_encrypt_init)(apr_crypto_block_t **ctx, + const unsigned char **iv, const apr_crypto_key_t *key, + apr_size_t *blockSize, apr_pool_t *p); + + /** + * @brief Encrypt data provided by in, write it to out. + * @note The number of bytes written will be written to outlen. If + * out is NULL, outlen will contain the maximum size of the + * buffer needed to hold the data, including any data + * generated by apr_crypto_block_encrypt_finish below. If *out points + * to NULL, a buffer sufficiently large will be created from + * the pool provided. If *out points to a not-NULL value, this + * value will be used as a buffer instead. + * @param out Address of a buffer to which data will be written, + * see note. + * @param outlen Length of the output will be written here. + * @param in Address of the buffer to read. + * @param inlen Length of the buffer to read. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if + * not implemented. + */ + apr_status_t (*block_encrypt)(unsigned char **out, apr_size_t *outlen, + const unsigned char *in, apr_size_t inlen, apr_crypto_block_t *ctx); + + /** + * @brief Encrypt final data block, write it to out. + * @note If necessary the final block will be written out after being + * padded. Typically the final block will be written to the + * same buffer used by apr_crypto_block_encrypt, offset by the + * number of bytes returned as actually written by the + * apr_crypto_block_encrypt() call. After this call, the context + * is cleaned and can be reused by apr_crypto_block_encrypt_init(). + * @param out Address of a buffer to which data will be written. This + * buffer must already exist, and is usually the same + * buffer used by apr_evp_crypt(). See note. + * @param outlen Length of the output will be written here. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. + * @return APR_EPADDING if padding was enabled and the block was incorrectly + * formatted. + * @return APR_ENOTIMPL if not implemented. + */ + apr_status_t (*block_encrypt_finish)(unsigned char *out, + apr_size_t *outlen, apr_crypto_block_t *ctx); + + /** + * @brief Initialise a context for decrypting arbitrary data using the given key. + * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If + * *ctx is not NULL, *ctx must point at a previously created structure. + * @param ctx The block context returned, see note. + * @param blockSize The block size of the cipher. + * @param iv Optional initialisation vector. If the buffer pointed to is NULL, + * an IV will be created at random, in space allocated from the pool. + * If the buffer is not NULL, the IV in the buffer will be used. + * @param key The key structure. + * @param p The pool to use. + * @return Returns APR_ENOIV if an initialisation vector is required but not specified. + * Returns APR_EINIT if the backend failed to initialise the context. Returns + * APR_ENOTIMPL if not implemented. + */ + apr_status_t (*block_decrypt_init)(apr_crypto_block_t **ctx, + apr_size_t *blockSize, const unsigned char *iv, + const apr_crypto_key_t *key, apr_pool_t *p); + + /** + * @brief Decrypt data provided by in, write it to out. + * @note The number of bytes written will be written to outlen. If + * out is NULL, outlen will contain the maximum size of the + * buffer needed to hold the data, including any data + * generated by apr_crypto_block_decrypt_finish below. If *out points + * to NULL, a buffer sufficiently large will be created from + * the pool provided. If *out points to a not-NULL value, this + * value will be used as a buffer instead. + * @param out Address of a buffer to which data will be written, + * see note. + * @param outlen Length of the output will be written here. + * @param in Address of the buffer to read. + * @param inlen Length of the buffer to read. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if + * not implemented. + */ + apr_status_t (*block_decrypt)(unsigned char **out, apr_size_t *outlen, + const unsigned char *in, apr_size_t inlen, apr_crypto_block_t *ctx); + + /** + * @brief Decrypt final data block, write it to out. + * @note If necessary the final block will be written out after being + * padded. Typically the final block will be written to the + * same buffer used by apr_crypto_block_decrypt, offset by the + * number of bytes returned as actually written by the + * apr_crypto_block_decrypt() call. After this call, the context + * is cleaned and can be reused by apr_crypto_block_decrypt_init(). + * @param out Address of a buffer to which data will be written. This + * buffer must already exist, and is usually the same + * buffer used by apr_evp_crypt(). See note. + * @param outlen Length of the output will be written here. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. + * @return APR_EPADDING if padding was enabled and the block was incorrectly + * formatted. + * @return APR_ENOTIMPL if not implemented. + */ + apr_status_t (*block_decrypt_finish)(unsigned char *out, + apr_size_t *outlen, apr_crypto_block_t *ctx); + + /** + * @brief Clean encryption / decryption context. + * @note After cleanup, a context is free to be reused if necessary. + * @param ctx The block context to use. + * @return Returns APR_ENOTIMPL if not supported. + */ + apr_status_t (*block_cleanup)(apr_crypto_block_t *ctx); + + /** + * @brief Clean encryption / decryption context. + * @note After cleanup, a context is free to be reused if necessary. + * @param f The context to use. + * @return Returns APR_ENOTIMPL if not supported. + */ + apr_status_t (*cleanup)(apr_crypto_t *f); + + /** + * @brief Clean encryption / decryption context. + * @note After cleanup, a context is free to be reused if necessary. + * @return Returns APR_ENOTIMPL if not supported. + */ + apr_status_t (*shutdown)(void); + + /** + * @brief: fetch the most recent error from this driver. + * @param result - the result structure + * @param f - context pointer + * @return APR_SUCCESS for success. + */ + apr_status_t (*error)(const apu_err_t **result, const apr_crypto_t *f); + + /** + * @brief Create a key from the provided secret or passphrase. The key is cleaned + * up when the context is cleaned, and may be reused with multiple encryption + * or decryption operations. + * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If + * *key is not NULL, *key must point at a previously created structure. + * @param key The key returned, see note. + * @param rec The key record, from which the key will be derived. + * @param f The context to use. + * @param p The pool to use. + * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend + * error occurred while generating the key. APR_ENOCIPHER if the type or mode + * is not supported by the particular backend. APR_EKEYTYPE if the key type is + * not known. APR_EPADDING if padding was requested but is not supported. + * APR_ENOTIMPL if not implemented. + */ + apr_status_t (*key)(apr_crypto_key_t **key, const apr_crypto_key_rec_t *rec, + const apr_crypto_t *f, apr_pool_t *p); + +}; + +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/c/dependencies/windows/apr/x64_debug/include/private/apr_dbd_internal.h b/c/dependencies/windows/apr/x64_debug/include/private/apr_dbd_internal.h new file mode 100644 index 00000000..671ffb21 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/private/apr_dbd_internal.h @@ -0,0 +1,365 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* Overview of what this is and does: + * http://www.apache.org/~niq/dbd.html + */ + +#ifndef APR_DBD_INTERNAL_H +#define APR_DBD_INTERNAL_H + +#include + +#include "apr_dbd.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define TXN_IGNORE_ERRORS(t) \ + ((t) && ((t)->mode & APR_DBD_TRANSACTION_IGNORE_ERRORS)) +#define TXN_NOTICE_ERRORS(t) \ + ((t) && !((t)->mode & APR_DBD_TRANSACTION_IGNORE_ERRORS)) + +#define TXN_DO_COMMIT(t) (!((t)->mode & APR_DBD_TRANSACTION_ROLLBACK)) +#define TXN_DO_ROLLBACK(t) ((t)->mode & APR_DBD_TRANSACTION_ROLLBACK) + +#define TXN_MODE_BITS \ + (APR_DBD_TRANSACTION_ROLLBACK|APR_DBD_TRANSACTION_IGNORE_ERRORS) + +struct apr_dbd_driver_t { + /** name */ + const char *name; + + /** init: allow driver to perform once-only initialisation. + * Called once only. May be NULL + */ + void (*init)(apr_pool_t *pool); + + /** native_handle: return the native database handle of the underlying db + * + * @param handle - apr_dbd handle + * @return - native handle + */ + void *(*native_handle)(apr_dbd_t *handle); + + /** open: obtain a database connection from the server rec. + * Must be explicitly closed when you're finished with it. + * WARNING: only use this when you need a connection with + * a lifetime other than a request + * + * @param pool - a pool to use for error messages (if any). + * @param params - connection parameters. + * @param error - descriptive error. + * @return database handle, or NULL on error. + */ + apr_dbd_t *(*open)(apr_pool_t *pool, const char *params, + const char **error); + + /** check_conn: check status of a database connection + * + * @param pool - a pool to use for error messages (if any). + * @param handle - the connection to check + * @return APR_SUCCESS or error + */ + apr_status_t (*check_conn)(apr_pool_t *pool, apr_dbd_t *handle); + + /** close: close/release a connection obtained from open() + * + * @param handle - the connection to release + * @return APR_SUCCESS or error + */ + apr_status_t (*close)(apr_dbd_t *handle); + + /** set_dbname: select database name. May be a no-op if not supported. + * + * @param pool - working pool + * @param handle - the connection + * @param name - the database to select + * @return 0 for success or error code + */ + int (*set_dbname)(apr_pool_t* pool, apr_dbd_t *handle, const char *name); + + /** transaction: start a transaction. May be a no-op. + * + * @param pool - a pool to use for error messages (if any). + * @param handle - the connection + * @param trans - ptr to a transaction. May be null on entry + * @return 0 for success or error code + */ + int (*start_transaction)(apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_transaction_t **trans); + + /** end_transaction: end a transaction + * (commit on success, rollback on error). + * May be a no-op. + * + * @param trans - the transaction. + * @return 0 for success or error code + */ + int (*end_transaction)(apr_dbd_transaction_t *trans); + + /** query: execute an SQL query that doesn't return a result set + * + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the SQL statement to execute + * @return 0 for success or error code + */ + int (*query)(apr_dbd_t *handle, int *nrows, const char *statement); + + /** select: execute an SQL query that returns a result set + * + * @param pool - pool to allocate the result set + * @param handle - the connection + * @param res - pointer to result set pointer. May point to NULL on entry + * @param statement - the SQL statement to execute + * @param random - 1 to support random access to results (seek any row); + * 0 to support only looping through results in order + * (async access - faster) + * @return 0 for success or error code + */ + int (*select)(apr_pool_t *pool, apr_dbd_t *handle, apr_dbd_results_t **res, + const char *statement, int random); + + /** num_cols: get the number of columns in a results set + * + * @param res - result set. + * @return number of columns + */ + int (*num_cols)(apr_dbd_results_t *res); + + /** num_tuples: get the number of rows in a results set + * of a synchronous select + * + * @param res - result set. + * @return number of rows, or -1 if the results are asynchronous + */ + int (*num_tuples)(apr_dbd_results_t *res); + + /** get_row: get a row from a result set + * + * @param pool - pool to allocate the row + * @param res - result set pointer + * @param row - pointer to row pointer. May point to NULL on entry + * @param rownum - row number, or -1 for "next row". Ignored if random + * access is not supported. + * @return 0 for success, -1 for rownum out of range or data finished + */ + int (*get_row)(apr_pool_t *pool, apr_dbd_results_t *res, + apr_dbd_row_t **row, int rownum); + + /** get_entry: get an entry from a row + * + * @param row - row pointer + * @param col - entry number + * @param val - entry to fill + * @return 0 for success, -1 for no data, +1 for general error + */ + const char* (*get_entry)(const apr_dbd_row_t *row, int col); + + /** error: get current error message (if any) + * + * @param handle - the connection + * @param errnum - error code from operation that returned an error + * @return the database current error message, or message for errnum + * (implementation-dependent whether errnum is ignored) + */ + const char *(*error)(apr_dbd_t *handle, int errnum); + + /** escape: escape a string so it is safe for use in query/select + * + * @param pool - pool to alloc the result from + * @param string - the string to escape + * @param handle - the connection + * @return the escaped, safe string + */ + const char *(*escape)(apr_pool_t *pool, const char *string, + apr_dbd_t *handle); + + /** prepare: prepare a statement + * + * @param pool - pool to alloc the result from + * @param handle - the connection + * @param query - the SQL query + * @param label - A label for the prepared statement. + * use NULL for temporary prepared statements + * (eg within a Request in httpd) + * @param nargs - number of parameters in the query + * @param nvals - number of values passed in p[b]query/select + * @param types - pointer to an array with types of parameters + * @param statement - statement to prepare. May point to null on entry. + * @return 0 for success or error code + */ + int (*prepare)(apr_pool_t *pool, apr_dbd_t *handle, const char *query, + const char *label, int nargs, int nvals, + apr_dbd_type_e *types, apr_dbd_prepared_t **statement); + + /** pvquery: query using a prepared statement + args + * + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param args - args to prepared statement + * @return 0 for success or error code + */ + int (*pvquery)(apr_pool_t *pool, apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, va_list args); + + /** pvselect: select using a prepared statement + args + * + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param args - args to prepared statement + * @return 0 for success or error code + */ + int (*pvselect)(apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, int random, va_list args); + + /** pquery: query using a prepared statement + args + * + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param args - args to prepared statement + * @return 0 for success or error code + */ + int (*pquery)(apr_pool_t *pool, apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, const char **args); + + /** pselect: select using a prepared statement + args + * + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param args - args to prepared statement + * @return 0 for success or error code + */ + int (*pselect)(apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, apr_dbd_prepared_t *statement, + int random, const char **args); + + + /** get_name: get a column title from a result set + * + * @param res - result set pointer + * @param col - entry number + * @return param name, or NULL if col is out of bounds. + */ + const char* (*get_name)(const apr_dbd_results_t *res, int col); + + /** transaction_mode_get: get the mode of transaction + * + * @param trans - the transaction. + * @return mode of transaction + */ + int (*transaction_mode_get)(apr_dbd_transaction_t *trans); + + /** transaction_mode_set: get the mode of transaction + * + * @param trans - the transaction. + * @param mode - new mode of the transaction + * @return the mode of transaction in force after the call + */ + int (*transaction_mode_set)(apr_dbd_transaction_t *trans, int mode); + + /** format of prepared statement parameters */ + const char *pformat; + + /** pvbquery: query using a prepared statement + binary args + * + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ + int (*pvbquery)(apr_pool_t *pool, apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, va_list args); + + /** pvbselect: select using a prepared statement + binary args + * + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ + int (*pvbselect)(apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, int random, va_list args); + + /** pbquery: query using a prepared statement + binary args + * + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ + int (*pbquery)(apr_pool_t *pool, apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement,const void **args); + + /** pbselect: select using a prepared statement + binary args + * + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ + int (*pbselect)(apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, apr_dbd_prepared_t *statement, + int random, const void **args); + + /** datum_get: get a binary entry from a row + * + * @param row - row pointer + * @param col - entry number + * @param type - type of data to get + * @param data - pointer to data, allocated by the caller + * @return APR_SUCCESS, an error code on error or if col is out of bounds + */ + apr_status_t (*datum_get)(const apr_dbd_row_t *row, int col, + apr_dbd_type_e type, void *data); +}; + +/* Export mutex lock/unlock for drivers that need it + * deprecated; create a per-dbd mutex within the (*init) function + * to avoid blocking other providers running on other threads + */ +APU_DECLARE(apr_status_t) apr_dbd_mutex_lock(void); +APU_DECLARE(apr_status_t) apr_dbd_mutex_unlock(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/c/dependencies/windows/apr/x64_debug/include/private/apr_dbd_odbc_v2.h b/c/dependencies/windows/apr/x64_debug/include/private/apr_dbd_odbc_v2.h new file mode 100644 index 00000000..b8da7b18 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/private/apr_dbd_odbc_v2.h @@ -0,0 +1,119 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/* ONLY USED FOR ODBC Version 2 -DODBCV2 +* +* Re-define everything to work (more-or-less) in an ODBC V2 environment +* Random access to retrieved rows is not supported - i.e. calls to apr_dbd_select() cannot +* have a 'random' argument of 1. apr_dbd_get_row() must always pass rownum as 0 (get next row) +* +*/ + +#define SQLHANDLE SQLHENV /* Presumes that ENV, DBC, and STMT handles are all the same datatype */ +#define SQL_NULL_HANDLE 0 +#define SQL_HANDLE_STMT 1 +#define SQL_HANDLE_DBC 2 +#define SQL_HANDLE_ENV 3 +#define SQL_NO_DATA SQL_NO_DATA_FOUND + +#ifndef SQL_SUCCEEDED +#define SQL_SUCCEEDED(rc) (((rc)&(~1))==0) +#endif + +#undef SQLSetEnvAttr +#define SQLSetEnvAttr(henv, Attribute, Value, StringLength) (0) + +#undef SQLAllocHandle +#define SQLAllocHandle(type, parent, hndl) \ +( (type == SQL_HANDLE_STMT) ? SQLAllocStmt(parent, hndl) \ + : (type == SQL_HANDLE_ENV) ? SQLAllocEnv(hndl) \ + : SQLAllocConnect(parent, hndl) \ +) + +#undef SQLFreeHandle +#define SQLFreeHandle(type, hndl) \ +( (type == SQL_HANDLE_STMT) ? SQLFreeStmt(hndl, SQL_DROP) \ + : (type == SQL_HANDLE_ENV) ? SQLFreeEnv(hndl) \ + : SQLFreeConnect(hndl) \ +) + +#undef SQLGetDiagRec +#define SQLGetDiagRec(type, h, i, state, native, buffer, bufsize, reslen) \ + SQLError( (type == SQL_HANDLE_ENV) ? h : NULL, \ + (type == SQL_HANDLE_DBC) ? h : NULL, \ + (type == SQL_HANDLE_STMT) ? h : NULL, \ + state, native, buffer, bufsize, reslen) + +#undef SQLCloseCursor +#define SQLCloseCursor(stmt) SQLFreeStmt(stmt, SQL_CLOSE) + +#undef SQLGetConnectAttr +#define SQLGetConnectAttr(hdbc, fOption, ValuePtr, BufferLength, NULL) \ + SQLGetConnectOption(hdbc, fOption, ValuePtr) + +#undef SQLSetConnectAttr +#define SQLSetConnectAttr(hdbc, fOption, ValuePtr, BufferLength) \ + SQLSetConnectOption(hdbc, fOption, (SQLUINTEGER) ValuePtr) + +#undef SQLSetStmtAttr +#define SQLSetStmtAttr(hstmt, fOption, ValuePtr, BufferLength) (0); return APR_ENOTIMPL; + +#undef SQLEndTran +#define SQLEndTran(hType, hdbc,type) SQLTransact(henv, hdbc, type) + +#undef SQLFetchScroll +#define SQLFetchScroll(stmt, orient, rownum) (0); return APR_ENOTIMPL; + +#define SQL_DESC_TYPE SQL_COLUMN_TYPE +#define SQL_DESC_CONCISE_TYPE SQL_COLUMN_TYPE +#define SQL_DESC_DISPLAY_SIZE SQL_COLUMN_DISPLAY_SIZE +#define SQL_DESC_OCTET_LENGTH SQL_COLUMN_LENGTH +#define SQL_DESC_UNSIGNED SQL_COLUMN_UNSIGNED + +#undef SQLColAttribute +#define SQLColAttribute(s, c, f, a, l, m, n) SQLColAttributes(s, c, f, a, l, m, n) + +#define SQL_ATTR_ACCESS_MODE SQL_ACCESS_MODE +#define SQL_ATTR_AUTOCOMMIT SQL_AUTOCOMMIT +#define SQL_ATTR_CONNECTION_TIMEOUT 113 +#define SQL_ATTR_CURRENT_CATALOG SQL_CURRENT_QUALIFIER +#define SQL_ATTR_DISCONNECT_BEHAVIOR 114 +#define SQL_ATTR_ENLIST_IN_DTC 1207 +#define SQL_ATTR_ENLIST_IN_XA 1208 + +#define SQL_ATTR_CONNECTION_DEAD 1209 +#define SQL_CD_TRUE 1L /* Connection is closed/dead */ +#define SQL_CD_FALSE 0L /* Connection is open/available */ + +#define SQL_ATTR_LOGIN_TIMEOUT SQL_LOGIN_TIMEOUT +#define SQL_ATTR_ODBC_CURSORS SQL_ODBC_CURSORS +#define SQL_ATTR_PACKET_SIZE SQL_PACKET_SIZE +#define SQL_ATTR_QUIET_MODE SQL_QUIET_MODE +#define SQL_ATTR_TRACE SQL_OPT_TRACE +#define SQL_ATTR_TRACEFILE SQL_OPT_TRACEFILE +#define SQL_ATTR_TRANSLATE_LIB SQL_TRANSLATE_DLL +#define SQL_ATTR_TRANSLATE_OPTION SQL_TRANSLATE_OPTION +#define SQL_ATTR_TXN_ISOLATION SQL_TXN_ISOLATION + +#define SQL_ATTR_CURSOR_SCROLLABLE -1 + +#define SQL_C_SBIGINT (SQL_BIGINT+SQL_SIGNED_OFFSET) /* SIGNED BIGINT */ +#define SQL_C_UBIGINT (SQL_BIGINT+SQL_UNSIGNED_OFFSET) /* UNSIGNED BIGINT */ + +#define SQL_FALSE 0 +#define SQL_TRUE 1 + diff --git a/c/dependencies/windows/apr/x64_debug/include/private/apr_dbm_private.h b/c/dependencies/windows/apr/x64_debug/include/private/apr_dbm_private.h new file mode 100644 index 00000000..020d3a6b --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/private/apr_dbm_private.h @@ -0,0 +1,121 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_DBM_PRIVATE_H +#define APR_DBM_PRIVATE_H + +#include "apr.h" +#include "apr_errno.h" +#include "apr_pools.h" +#include "apr_dbm.h" +#include "apr_file_io.h" + +#include "apu.h" + +/* ### for now, include the DBM selection; this will go away once we start + ### building and linking all of the DBMs at once. */ +#include "apu_select_dbm.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** @internal */ + +/** + * Most DBM libraries take a POSIX mode for creating files. Don't trust + * the mode_t type, some platforms may not support it, int is safe. + */ +APU_DECLARE(int) apr_posix_perms2mode(apr_fileperms_t perm); + +/** + * Structure to describe the operations of the DBM + */ +typedef struct { + /** The name of the DBM Type */ + const char *name; + + /** Open the DBM */ + apr_status_t (*open)(apr_dbm_t **pdb, const char *pathname, + apr_int32_t mode, apr_fileperms_t perm, + apr_pool_t *pool); + + /** Close the DBM */ + void (*close)(apr_dbm_t *dbm); + + /** Fetch a dbm record value by key */ + apr_status_t (*fetch)(apr_dbm_t *dbm, apr_datum_t key, + apr_datum_t * pvalue); + + /** Store a dbm record value by key */ + apr_status_t (*store)(apr_dbm_t *dbm, apr_datum_t key, apr_datum_t value); + + /** Delete a dbm record value by key */ + apr_status_t (*del)(apr_dbm_t *dbm, apr_datum_t key); + + /** Search for a key within the dbm */ + int (*exists)(apr_dbm_t *dbm, apr_datum_t key); + + /** Retrieve the first record key from a dbm */ + apr_status_t (*firstkey)(apr_dbm_t *dbm, apr_datum_t * pkey); + + /** Retrieve the next record key from a dbm */ + apr_status_t (*nextkey)(apr_dbm_t *dbm, apr_datum_t * pkey); + + /** Proactively toss any memory associated with the apr_datum_t. */ + void (*freedatum)(apr_dbm_t *dbm, apr_datum_t data); + + /** Get the names that the DBM will use for a given pathname. */ + void (*getusednames)(apr_pool_t *pool, + const char *pathname, + const char **used1, + const char **used2); + +} apr_dbm_type_t; + + +/** + * The actual DBM + */ +struct apr_dbm_t +{ + /** Associated pool */ + apr_pool_t *pool; + + /** pointer to DB Implementation Specific data */ + void *file; + + /** Current integer error code */ + int errcode; + /** Current string error code */ + const char *errmsg; + + /** the type of DBM */ + const apr_dbm_type_t *type; +}; + + +/* Declare all of the DBM provider tables */ +APU_MODULE_DECLARE_DATA extern const apr_dbm_type_t apr_dbm_type_sdbm; +APU_MODULE_DECLARE_DATA extern const apr_dbm_type_t apr_dbm_type_gdbm; +APU_MODULE_DECLARE_DATA extern const apr_dbm_type_t apr_dbm_type_ndbm; +APU_MODULE_DECLARE_DATA extern const apr_dbm_type_t apr_dbm_type_db; + +#ifdef __cplusplus +} +#endif + +#endif /* APR_DBM_PRIVATE_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/private/apr_encode_private.h b/c/dependencies/windows/apr/x64_debug/include/private/apr_encode_private.h new file mode 100644 index 00000000..8db2e016 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/private/apr_encode_private.h @@ -0,0 +1,84 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_encode_private.h + * @brief APR-UTIL Encoding Private + */ +#ifndef APR_ENCODE_PRIVATE_H +#define APR_ENCODE_PRIVATE_H + +#include "apr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Encode_Private + * @ingroup APR_Util + * @{ + */ + +#if APR_CHARSET_EBCDIC + static int convert_a2e[256] = { + 0x00, 0x01, 0x02, 0x03, 0x37, 0x2D, 0x2E, 0x2F, 0x16, 0x05, 0x15, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, + 0x10, 0x11, 0x12, 0x13, 0x3C, 0x3D, 0x32, 0x26, 0x18, 0x19, 0x3F, 0x27, 0x1C, 0x1D, 0x1E, 0x1F, + 0x40, 0x5A, 0x7F, 0x7B, 0x5B, 0x6C, 0x50, 0x7D, 0x4D, 0x5D, 0x5C, 0x4E, 0x6B, 0x60, 0x4B, 0x61, + 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0x7A, 0x5E, 0x4C, 0x7E, 0x6E, 0x6F, + 0x7C, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, + 0xD7, 0xD8, 0xD9, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xAD, 0xE0, 0xBD, 0x5F, 0x6D, + 0x79, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, + 0x97, 0x98, 0x99, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xC0, 0x4F, 0xD0, 0xA1, 0x07, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x06, 0x17, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x09, 0x0A, 0x1B, + 0x30, 0x31, 0x1A, 0x33, 0x34, 0x35, 0x36, 0x08, 0x38, 0x39, 0x3A, 0x3B, 0x04, 0x14, 0x3E, 0xFF, + 0x41, 0xAA, 0x4A, 0xB1, 0x9F, 0xB2, 0x6A, 0xB5, 0xBB, 0xB4, 0x9A, 0x8A, 0xB0, 0xCA, 0xAF, 0xBC, + 0x90, 0x8F, 0xEA, 0xFA, 0xBE, 0xA0, 0xB6, 0xB3, 0x9D, 0xDA, 0x9B, 0x8B, 0xB7, 0xB8, 0xB9, 0xAB, + 0x64, 0x65, 0x62, 0x66, 0x63, 0x67, 0x9E, 0x68, 0x74, 0x71, 0x72, 0x73, 0x78, 0x75, 0x76, 0x77, + 0xAC, 0x69, 0xED, 0xEE, 0xEB, 0xEF, 0xEC, 0xBF, 0x80, 0xFD, 0xFE, 0xFB, 0xFC, 0xBA, 0xAE, 0x59, + 0x44, 0x45, 0x42, 0x46, 0x43, 0x47, 0x9C, 0x48, 0x54, 0x51, 0x52, 0x53, 0x58, 0x55, 0x56, 0x57, + 0x8C, 0x49, 0xCD, 0xCE, 0xCB, 0xCF, 0xCC, 0xE1, 0x70, 0xDD, 0xDE, 0xDB, 0xDC, 0x8D, 0x8E, 0xDF}; + + static int convert_e2a[256] = { + 0x00, 0x01, 0x02, 0x03, 0x9C, 0x09, 0x86, 0x7F, 0x97, 0x8D, 0x8E, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, + 0x10, 0x11, 0x12, 0x13, 0x9D, 0x0A, 0x08, 0x87, 0x18, 0x19, 0x92, 0x8F, 0x1C, 0x1D, 0x1E, 0x1F, + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x17, 0x1B, 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x05, 0x06, 0x07, + 0x90, 0x91, 0x16, 0x93, 0x94, 0x95, 0x96, 0x04, 0x98, 0x99, 0x9A, 0x9B, 0x14, 0x15, 0x9E, 0x1A, + 0x20, 0xA0, 0xE2, 0xE4, 0xE0, 0xE1, 0xE3, 0xE5, 0xE7, 0xF1, 0xA2, 0x2E, 0x3C, 0x28, 0x2B, 0x7C, + 0x26, 0xE9, 0xEA, 0xEB, 0xE8, 0xED, 0xEE, 0xEF, 0xEC, 0xDF, 0x21, 0x24, 0x2A, 0x29, 0x3B, 0x5E, + 0x2D, 0x2F, 0xC2, 0xC4, 0xC0, 0xC1, 0xC3, 0xC5, 0xC7, 0xD1, 0xA6, 0x2C, 0x25, 0x5F, 0x3E, 0x3F, + 0xF8, 0xC9, 0xCA, 0xCB, 0xC8, 0xCD, 0xCE, 0xCF, 0xCC, 0x60, 0x3A, 0x23, 0x40, 0x27, 0x3D, 0x22, + 0xD8, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xAB, 0xBB, 0xF0, 0xFD, 0xFE, 0xB1, + 0xB0, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0xAA, 0xBA, 0xE6, 0xB8, 0xC6, 0xA4, + 0xB5, 0x7E, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0xA1, 0xBF, 0xD0, 0x5B, 0xDE, 0xAE, + 0xAC, 0xA3, 0xA5, 0xB7, 0xA9, 0xA7, 0xB6, 0xBC, 0xBD, 0xBE, 0xDD, 0xA8, 0xAF, 0x5D, 0xB4, 0xD7, + 0x7B, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0xAD, 0xF4, 0xF6, 0xF2, 0xF3, 0xF5, + 0x7D, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0xB9, 0xFB, 0xFC, 0xF9, 0xFA, 0xFF, + 0x5C, 0xF7, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0xB2, 0xD4, 0xD6, 0xD2, 0xD3, 0xD5, + 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0xB3, 0xDB, 0xDC, 0xD9, 0xDA, 0x9F}; +#define decode ENCODE_TO_ASCII(ch) convert_e2a[(unsigned char)ch] +#define decode ENCODE_TO_NATIVE(ch) convert_a2e[(unsigned char)ch] +#else /* APR_CHARSET_EBCDIC */ +#define ENCODE_TO_ASCII(ch) (ch) +#define ENCODE_TO_NATIVE(ch) (ch) +#endif /* !APR_CHARSET_EBCDIC */ + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ENCODE_PRIVATE_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/private/apu_config.h b/c/dependencies/windows/apr/x64_debug/include/private/apu_config.h new file mode 100644 index 00000000..b0e20393 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/private/apu_config.h @@ -0,0 +1,52 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Note: This is a Windows specific version of apu_config.hw. It is copied + * as apu_config.h at the start of a Windows build. + */ + +#ifdef WIN32 + +#ifndef APU_CONFIG_H +#define APU_CONFIG_H + +/* Compile win32 with DSO support for .dll builds */ +#ifdef APU_DECLARE_STATIC +#define APU_DSO_BUILD 0 +#else +#define APU_DSO_BUILD 1 +#endif + +/* Presume a standard, modern (5.x) mysql sdk/ +#define HAVE_MY_GLOBAL_H 1 + +/* my_sys.h is broken on VC/Win32, and apparently not required */ +/* #undef HAVE_MY_SYS_H 0 */ + +/* + * Windows does not have GDBM, and we always use the bundled (new) Expat + */ + +/* Define if you have the gdbm library (-lgdbm). */ +/* #undef HAVE_LIBGDBM */ + +/* define if Expat 1.0 or 1.1 was found */ +/* #undef APR_HAVE_OLD_EXPAT */ + + +#endif /* APU_CONFIG_H */ +#endif /* WIN32 */ diff --git a/c/dependencies/windows/apr/x64_debug/include/private/apu_config.hnw b/c/dependencies/windows/apr/x64_debug/include/private/apu_config.hnw new file mode 100644 index 00000000..c7a6124b --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/private/apu_config.hnw @@ -0,0 +1,53 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Note: This is a NetWare specific version of apu_config.hnw. It is copied + * as apu_config.h at the start of a NetWare build. + */ + +#ifdef NETWARE + +#ifndef APU_CONFIG_H +#define APU_CONFIG_H + +/* Always compile Netware with DSO support for .nlm builds */ +#define APU_DSO_BUILD 0 + +/* + * NetWare does not have GDBM, and we always use the bundled (new) Expat + */ + +/* Define if you have the gdbm library (-lgdbm). */ +/* #undef HAVE_LIBGDBM */ + +/* define if Expat 1.0 or 1.1 was found */ +/* #undef APR_HAVE_OLD_EXPAT */ + +/* NetWare uses its own ICONV implementation. */ +#define HAVE_ICONV_H 1 + +/* + * check for newer NDKs which use now correctly 'const char*' with iconv. + */ +#include +#if (CURRENT_NDK_THRESHOLD >= 705110000) +#define APU_ICONV_INBUF_CONST +#endif + +#endif /* APU_CONFIG_H */ +#endif /* NETWARE */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/private/apu_config.hw b/c/dependencies/windows/apr/x64_debug/include/private/apu_config.hw new file mode 100644 index 00000000..ac262fcb --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/private/apu_config.hw @@ -0,0 +1,52 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Note: This is a Windows specific version of apu_config.hw. It is copied + * as apu_config.h at the start of a Windows build. + */ + +#ifdef WIN32 + +#ifndef APU_CONFIG_H +#define APU_CONFIG_H + +/* Compile win32 with DSO support for .dll builds */ +#ifdef APU_DECLARE_STATIC +#define APU_DSO_BUILD 0 +#else +#define APU_DSO_BUILD 1 +#endif + +/* Presume a standard, modern (5.x) mysql sdk/ +#define HAVE_MY_GLOBAL_H 1 + +/* my_sys.h is broken on VC/Win32, and apparently not required */ +/* #undef HAVE_MY_SYS_H 0 */ + +/* + * Windows does not have GDBM, and we always use the bundled (new) Expat + */ + +/* Define if you have the gdbm library (-lgdbm). */ +/* #undef HAVE_LIBGDBM */ + +/* define if Expat 1.0 or 1.1 was found */ +/* #undef APR_HAVE_OLD_EXPAT */ + + +#endif /* APU_CONFIG_H */ +#endif /* WIN32 */ diff --git a/c/dependencies/windows/apr/x64_debug/include/private/apu_internal.h b/c/dependencies/windows/apr/x64_debug/include/private/apu_internal.h new file mode 100644 index 00000000..c95c9d50 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/private/apu_internal.h @@ -0,0 +1,73 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr.h" +#include "apr_dso.h" +#include "apu.h" + +#ifndef APU_INTERNAL_H +#define APU_INTERNAL_H + +#if APU_DSO_BUILD + +#ifdef __cplusplus +extern "C" { +#endif + +/* For modular dso loading, an internal interlock to allow us to + * continue to initialize modules by multiple threads, the caller + * of apu_dso_load must lock first, and not unlock until any init + * finalization is complete. + */ +apr_status_t apu_dso_init(apr_pool_t *pool); + +apr_status_t apu_dso_mutex_lock(void); +apr_status_t apu_dso_mutex_unlock(void); + +apr_status_t apu_dso_load(apr_dso_handle_t **dso, apr_dso_handle_sym_t *dsoptr, const char *module, + const char *modsym, apr_pool_t *pool); + +#if APR_HAS_LDAP + +/* For LDAP internal builds, wrap our LDAP namespace */ + +struct apr__ldap_dso_fntable { + int (*info)(apr_pool_t *pool, apr_ldap_err_t **result_err); + int (*init)(apr_pool_t *pool, LDAP **ldap, const char *hostname, + int portno, int secure, apr_ldap_err_t **result_err); + int (*ssl_init)(apr_pool_t *pool, const char *cert_auth_file, + int cert_file_type, apr_ldap_err_t **result_err); + int (*ssl_deinit)(void); + int (*get_option)(apr_pool_t *pool, LDAP *ldap, int option, + void *outvalue, apr_ldap_err_t **result_err); + int (*set_option)(apr_pool_t *pool, LDAP *ldap, int option, + const void *invalue, apr_ldap_err_t **result_err); + apr_status_t (*rebind_init)(apr_pool_t *pool); + apr_status_t (*rebind_add)(apr_pool_t *pool, LDAP *ld, + const char *bindDN, const char *bindPW); + apr_status_t (*rebind_remove)(LDAP *ld); +}; + +#endif /* APR_HAS_LDAP */ + +#ifdef __cplusplus +} +#endif + +#endif /* APU_DSO_BUILD */ + +#endif /* APU_INTERNAL_H */ + diff --git a/c/dependencies/windows/apr/x64_debug/include/private/apu_select_dbm.h b/c/dependencies/windows/apr/x64_debug/include/private/apu_select_dbm.h new file mode 100644 index 00000000..97c7b6c2 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/private/apu_select_dbm.h @@ -0,0 +1,28 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APU_SELECT_DBM_H +#define APU_SELECT_DBM_H + +/* +** The following macros control what features APRUTIL will use +*/ +#define APU_USE_SDBM 1 +#define APU_USE_GDBM 0 +#define APU_USE_NDBM 0 +#define APU_USE_DB 0 + +#endif /* !APU_SELECT_DBM_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/private/apu_select_dbm.h.in b/c/dependencies/windows/apr/x64_debug/include/private/apu_select_dbm.h.in new file mode 100644 index 00000000..d66be5fc --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/private/apu_select_dbm.h.in @@ -0,0 +1,28 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APU_SELECT_DBM_H +#define APU_SELECT_DBM_H + +/* +** The following macros control what features APRUTIL will use +*/ +#define APU_USE_SDBM @apu_use_sdbm@ +#define APU_USE_NDBM @apu_use_ndbm@ +#define APU_USE_GDBM @apu_use_gdbm@ +#define APU_USE_DB @apu_use_db@ + +#endif /* !APU_SELECT_DBM_H */ diff --git a/c/dependencies/windows/apr/x64_debug/include/private/apu_select_dbm.hw b/c/dependencies/windows/apr/x64_debug/include/private/apu_select_dbm.hw new file mode 100644 index 00000000..baa6c144 --- /dev/null +++ b/c/dependencies/windows/apr/x64_debug/include/private/apu_select_dbm.hw @@ -0,0 +1,28 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APU_SELECT_DBM_H +#define APU_SELECT_DBM_H + +/* +** The following macros control what features APRUTIL will use +*/ +#define APU_USE_SDBM 1 +#define APU_USE_GDBM 0 +#define APU_USE_NDBM 0 +#define APU_USE_DB 0 + +#endif /* !APU_SELECT_DBM_H */ diff --git a/c/dependencies/windows/apr/x64_debug/lib/apr.lib b/c/dependencies/windows/apr/x64_debug/lib/apr.lib new file mode 100644 index 00000000..c5fd9e66 Binary files /dev/null and b/c/dependencies/windows/apr/x64_debug/lib/apr.lib differ diff --git a/c/dependencies/windows/apr/x64_debug/lib/apr.pdb b/c/dependencies/windows/apr/x64_debug/lib/apr.pdb new file mode 100644 index 00000000..b2c6e946 Binary files /dev/null and b/c/dependencies/windows/apr/x64_debug/lib/apr.pdb differ diff --git a/c/dependencies/windows/apr/x64_debug/lib/aprapp.lib b/c/dependencies/windows/apr/x64_debug/lib/aprapp.lib new file mode 100644 index 00000000..23575a99 Binary files /dev/null and b/c/dependencies/windows/apr/x64_debug/lib/aprapp.lib differ diff --git a/c/dependencies/windows/apr/x64_debug/lib/aprapp.pdb b/c/dependencies/windows/apr/x64_debug/lib/aprapp.pdb new file mode 100644 index 00000000..7bd2e1e7 Binary files /dev/null and b/c/dependencies/windows/apr/x64_debug/lib/aprapp.pdb differ diff --git a/c/dependencies/windows/apr/x64_debug/lib/apriconv.lib b/c/dependencies/windows/apr/x64_debug/lib/apriconv.lib new file mode 100644 index 00000000..fff2881d Binary files /dev/null and b/c/dependencies/windows/apr/x64_debug/lib/apriconv.lib differ diff --git a/c/dependencies/windows/apr/x64_debug/lib/apriconv.pdb b/c/dependencies/windows/apr/x64_debug/lib/apriconv.pdb new file mode 100644 index 00000000..0bda6f3d Binary files /dev/null and b/c/dependencies/windows/apr/x64_debug/lib/apriconv.pdb differ diff --git a/c/dependencies/windows/apr/x64_debug/lib/aprutil.lib b/c/dependencies/windows/apr/x64_debug/lib/aprutil.lib new file mode 100644 index 00000000..a4244b05 Binary files /dev/null and b/c/dependencies/windows/apr/x64_debug/lib/aprutil.lib differ diff --git a/c/dependencies/windows/apr/x64_debug/lib/aprutil.pdb b/c/dependencies/windows/apr/x64_debug/lib/aprutil.pdb new file mode 100644 index 00000000..d3cd9ead Binary files /dev/null and b/c/dependencies/windows/apr/x64_debug/lib/aprutil.pdb differ diff --git a/c/dependencies/windows/apr/x64_debug/lib/libapr.lib b/c/dependencies/windows/apr/x64_debug/lib/libapr.lib new file mode 100644 index 00000000..64acd198 Binary files /dev/null and b/c/dependencies/windows/apr/x64_debug/lib/libapr.lib differ diff --git a/c/dependencies/windows/apr/x64_debug/lib/libapr.pdb b/c/dependencies/windows/apr/x64_debug/lib/libapr.pdb new file mode 100644 index 00000000..c997c6dd Binary files /dev/null and b/c/dependencies/windows/apr/x64_debug/lib/libapr.pdb differ diff --git a/c/dependencies/windows/apr/x64_debug/lib/libapr_src.pdb b/c/dependencies/windows/apr/x64_debug/lib/libapr_src.pdb new file mode 100644 index 00000000..dfbc6097 Binary files /dev/null and b/c/dependencies/windows/apr/x64_debug/lib/libapr_src.pdb differ diff --git a/c/dependencies/windows/apr/x64_debug/lib/libaprapp.lib b/c/dependencies/windows/apr/x64_debug/lib/libaprapp.lib new file mode 100644 index 00000000..adc0a2ad Binary files /dev/null and b/c/dependencies/windows/apr/x64_debug/lib/libaprapp.lib differ diff --git a/c/dependencies/windows/apr/x64_debug/lib/libaprapp.pdb b/c/dependencies/windows/apr/x64_debug/lib/libaprapp.pdb new file mode 100644 index 00000000..9475762e Binary files /dev/null and b/c/dependencies/windows/apr/x64_debug/lib/libaprapp.pdb differ diff --git a/c/dependencies/windows/apr/x64_debug/lib/libapriconv.lib b/c/dependencies/windows/apr/x64_debug/lib/libapriconv.lib new file mode 100644 index 00000000..859b93a1 Binary files /dev/null and b/c/dependencies/windows/apr/x64_debug/lib/libapriconv.lib differ diff --git a/c/dependencies/windows/apr/x64_debug/lib/libapriconv.pdb b/c/dependencies/windows/apr/x64_debug/lib/libapriconv.pdb new file mode 100644 index 00000000..4dc55773 Binary files /dev/null and b/c/dependencies/windows/apr/x64_debug/lib/libapriconv.pdb differ diff --git a/c/dependencies/windows/apr/x64_debug/lib/libapriconv_src.pdb b/c/dependencies/windows/apr/x64_debug/lib/libapriconv_src.pdb new file mode 100644 index 00000000..0ac341b4 Binary files /dev/null and b/c/dependencies/windows/apr/x64_debug/lib/libapriconv_src.pdb differ diff --git a/c/dependencies/windows/apr/x64_debug/lib/libaprutil.lib b/c/dependencies/windows/apr/x64_debug/lib/libaprutil.lib new file mode 100644 index 00000000..24b5669a Binary files /dev/null and b/c/dependencies/windows/apr/x64_debug/lib/libaprutil.lib differ diff --git a/c/dependencies/windows/apr/x64_debug/lib/libaprutil.pdb b/c/dependencies/windows/apr/x64_debug/lib/libaprutil.pdb new file mode 100644 index 00000000..476cf9c2 Binary files /dev/null and b/c/dependencies/windows/apr/x64_debug/lib/libaprutil.pdb differ diff --git a/c/dependencies/windows/apr/x64_debug/lib/libaprutil_src.pdb b/c/dependencies/windows/apr/x64_debug/lib/libaprutil_src.pdb new file mode 100644 index 00000000..185fc502 Binary files /dev/null and b/c/dependencies/windows/apr/x64_debug/lib/libaprutil_src.pdb differ diff --git a/c/dependencies/windows/apr/x86/include/api_version.h b/c/dependencies/windows/apr/x86/include/api_version.h new file mode 100644 index 00000000..c2788959 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/api_version.h @@ -0,0 +1,132 @@ +/* Copyright 2000-2017 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef API_VERSION_H +#define API_VERSION_H + +/** + * @file api_version.h + * @brief APR-iconv Versioning Interface + * + * APR-iconv's Version + * + * There are several different mechanisms for accessing the version. There + * is a string form, and a set of numbers; in addition, there are constants + * which can be compiled into your application, and you can query the library + * being used for its actual version. + * + * Note that it is possible for an application to detect that it has been + * compiled against a different version of API by use of the compile-time + * constants and the use of the run-time query function. + * + * API version numbering follows the guidelines specified in: + * + * http://apr.apache.org/versioning.html + */ + + +/* The numeric compile-time version constants. These constants are the + * authoritative version numbers for API. + */ + +/** major version + * Major API changes that could cause compatibility problems for older + * programs such as structure size changes. No binary compatibility is + * possible across a change in the major version. + */ +#define API_MAJOR_VERSION 1 + +/** minor version + * Minor API changes that do not cause binary compatibility problems. + * Reset to 0 when upgrading API_MAJOR_VERSION + */ +#define API_MINOR_VERSION 2 + +/** patch level + * The Patch Level never includes API changes, simply bug fixes. + * Reset to 0 when upgrading API_MINOR_VERSION + */ +#define API_PATCH_VERSION 2 + +/** + * The symbol API_IS_DEV_VERSION is only defined for internal, + * "development" copies of API. It is undefined for released versions + * of API. + */ +/* #undef API_IS_DEV_VERSION */ + + +#if defined(API_IS_DEV_VERSION) || defined(DOXYGEN) +/** Internal: string form of the "is dev" flag */ +#define API_IS_DEV_STRING "-dev" +#else +#define API_IS_DEV_STRING "" +#endif + +#ifndef API_STRINGIFY +/** Properly quote a value as a string in the C preprocessor */ +#define API_STRINGIFY(n) API_STRINGIFY_HELPER(n) +/** Helper macro for API_STRINGIFY */ +#define API_STRINGIFY_HELPER(n) #n +#endif + +/** The formatted string of API's version */ +#define API_VERSION_STRING \ + API_STRINGIFY(API_MAJOR_VERSION) "." \ + API_STRINGIFY(API_MINOR_VERSION) "." \ + API_STRINGIFY(API_PATCH_VERSION) \ + API_IS_DEV_STRING + +/** An alternative formatted string of APR's version */ +/* macro for Win32 .rc files using numeric csv representation */ +#define API_VERSION_STRING_CSV API_MAJOR_VERSION ##, \ + ##API_MINOR_VERSION ##, \ + ##API_PATCH_VERSION + + +#ifndef API_VERSION_ONLY + +/* The C language API to access the version at run time, + * as opposed to compile time. API_VERSION_ONLY may be defined + * externally when preprocessing apr_version.h to obtain strictly + * the C Preprocessor macro declarations. + */ + +#include "apr_version.h" + +#include "apr_iconv.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Return APR-iconv's version information information in a numeric form. + * + * @param pvsn Pointer to a version structure for returning the version + * information. + */ +API_DECLARE(void) api_version(apr_version_t *pvsn); + +/** Return API's version information as a string. */ +API_DECLARE(const char *) api_version_string(void); + +#ifdef __cplusplus +} +#endif + +#endif /* ndef API_VERSION_ONLY */ + +#endif /* ndef API_VERSION_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr.h b/c/dependencies/windows/apr/x86/include/apr.h new file mode 100644 index 00000000..3352fef3 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr.h @@ -0,0 +1,667 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef APR_H +#define APR_H + +/* GENERATED FILE WARNING! DO NOT EDIT apr.h + * + * You must modify apr.hw instead. + * + * And please, make an effort to stub apr.hnw and apr.h.in in the process. + * + * This is the Win32 specific version of apr.h. It is copied from + * apr.hw by the apr.dsp and libapr.dsp projects. + */ + +/** + * @file apr.h + * @brief APR Platform Definitions + * @remark This is a generated header generated from include/apr.h.in by + * ./configure, or copied from include/apr.hw or include/apr.hnw + * for Win32 or Netware by those build environments, respectively. + */ + +/* Make sure we have our platform identifier macro defined we ask for later. + */ +#if defined(_WIN32) && !defined(WIN32) +#define WIN32 1 +#endif + +#if defined(WIN32) || defined(DOXYGEN) + +/* Ignore most warnings (back down to /W3) for poorly constructed headers + */ +#if defined(_MSC_VER) && _MSC_VER >= 1200 +#pragma warning(push, 3) +#endif + +/* disable or reduce the frequency of... + * C4057: indirection to slightly different base types + * C4075: slight indirection changes (unsigned short* vs short[]) + * C4100: unreferenced formal parameter + * C4127: conditional expression is constant + * C4163: '_rotl64' : not available as an intrinsic function + * C4201: nonstandard extension nameless struct/unions + * C4244: int to char/short - precision loss + * C4514: unreferenced inline function removed + */ +#if defined(_MSC_VER) +#pragma warning(disable: 4100 4127 4163 4201 4514; once: 4057 4075 4244) +#endif + +/* Ignore Microsoft's interpretation of secure development + * and the POSIX string handling API + */ +#if defined(_MSC_VER) && _MSC_VER >= 1400 +#ifndef _CRT_SECURE_NO_DEPRECATE +#define _CRT_SECURE_NO_DEPRECATE +#endif +#pragma warning(disable: 4996) +#endif + +/* Has windows.h already been included? If so, our preferences don't matter, + * but we will still need the winsock things no matter what was included. + * If not, include a restricted set of windows headers to our tastes. + */ +#ifndef _WINDOWS_ +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef _WIN32_WINNT + +/* Restrict the server to a subset of Windows XP header files by default + */ +#define _WIN32_WINNT 0x0A00 +#endif +#ifndef NOUSER +#define NOUSER +#endif +#ifndef NOMCX +#define NOMCX +#endif +#ifndef NOIME +#define NOIME +#endif +#include +/* + * Add a _very_few_ declarations missing from the restricted set of headers + * (If this list becomes extensive, re-enable the required headers above!) + * winsock headers were excluded by WIN32_LEAN_AND_MEAN, so include them now + */ +#define SW_HIDE 0 +#ifndef _WIN32_WCE +#include +#include +#include +#else +#include +#endif +#endif /* !_WINDOWS_ */ + +/** + * @defgroup APR Apache Portability Runtime library + * @{ + */ +/** + * @defgroup apr_platform Platform Definitions + * @{ + * @warning + * The actual values of macros and typedefs on this page
+ * are platform specific and should NOT be relied upon!
+ */ + +#define APR_INLINE __inline +#define APR_HAS_INLINE 1 +#if !defined(__GNUC__) && !defined(__attribute__) +#define __attribute__(__x) +#endif + +#ifndef _WIN32_WCE +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_CONIO_H 1 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 1 +#define APR_HAVE_DIRENT_H 0 +#define APR_HAVE_ERRNO_H 1 +#define APR_HAVE_FCNTL_H 1 +#define APR_HAVE_IO_H 1 +#define APR_HAVE_LIMITS_H 1 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SEMAPHORE_H 0 +#define APR_HAVE_SIGNAL_H 1 +#define APR_HAVE_STDARG_H 1 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_SYS_IOCTL_H 0 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SIGNAL_H 0 +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#define APR_HAVE_SYS_TIME_H 0 +#define APR_HAVE_SYS_TYPES_H 1 +#define APR_HAVE_SYS_UIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#define APR_HAVE_SYS_WAIT_H 0 +#define APR_HAVE_TIME_H 1 +#define APR_HAVE_UNISTD_H 0 +#define APR_HAVE_STDDEF_H 1 +#define APR_HAVE_PROCESS_H 1 +#else +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_CONIO_H 0 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 0 +#define APR_HAVE_DIRENT_H 0 +#define APR_HAVE_ERRNO_H 0 +#define APR_HAVE_FCNTL_H 0 +#define APR_HAVE_IO_H 0 +#define APR_HAVE_LIMITS_H 0 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SEMAPHORE_H 0 +#define APR_HAVE_SIGNAL_H 0 +#define APR_HAVE_STDARG_H 0 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_SYS_IOCTL_H 0 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SIGNAL_H 0 +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#define APR_HAVE_SYS_TIME_H 0 +#define APR_HAVE_SYS_TYPES_H 0 +#define APR_HAVE_SYS_UIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#define APR_HAVE_SYS_WAIT_H 0 +#define APR_HAVE_TIME_H 0 +#define APR_HAVE_UNISTD_H 0 +#define APR_HAVE_STDDEF_H 0 +#define APR_HAVE_PROCESS_H 0 +#endif + +/** @} */ +/** @} */ + +/* We don't include our conditional headers within the doxyblocks + * or the extern "C" namespace + */ + +#if APR_HAVE_STDLIB_H +#include +#endif + +#if APR_HAVE_STDIO_H +#include +#endif + +#if APR_HAVE_SYS_TYPES_H +#include +#endif + +#if APR_HAVE_STDDEF_H +#include +#endif + +#if APR_HAVE_SYS_SOCKET_H +#include +#endif + +#if APR_HAVE_STDINT_H +#include +#endif + +#if APR_HAVE_SYS_WAIT_H +#include +#endif + +#if APR_HAVE_TIME_H +#include +#endif + +#if APR_HAVE_PROCESS_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @addtogroup apr_platform + * @ingroup APR + * @{ + */ + +#define APR_HAVE_SHMEM_MMAP_TMP 0 +#define APR_HAVE_SHMEM_MMAP_SHM 0 +#define APR_HAVE_SHMEM_MMAP_ZERO 0 +#define APR_HAVE_SHMEM_SHMGET_ANON 0 +#define APR_HAVE_SHMEM_SHMGET 0 +#define APR_HAVE_SHMEM_MMAP_ANON 0 +#define APR_HAVE_SHMEM_BEOS 0 + +#define APR_USE_SHMEM_MMAP_TMP 0 +#define APR_USE_SHMEM_MMAP_SHM 0 +#define APR_USE_SHMEM_MMAP_ZERO 0 +#define APR_USE_SHMEM_SHMGET_ANON 0 +#define APR_USE_SHMEM_SHMGET 0 +#define APR_USE_SHMEM_MMAP_ANON 0 +#define APR_USE_SHMEM_BEOS 0 + +#define APR_USE_FLOCK_SERIALIZE 0 +#define APR_USE_POSIXSEM_SERIALIZE 0 +#define APR_USE_SYSVSEM_SERIALIZE 0 +#define APR_USE_FCNTL_SERIALIZE 0 +#define APR_USE_PROC_PTHREAD_SERIALIZE 0 +#define APR_USE_PTHREAD_SERIALIZE 0 + +#define APR_HAS_FLOCK_SERIALIZE 0 +#define APR_HAS_SYSVSEM_SERIALIZE 0 +#define APR_HAS_POSIXSEM_SERIALIZE 0 +#define APR_HAS_FCNTL_SERIALIZE 0 +#define APR_HAS_PROC_PTHREAD_SERIALIZE 0 + +#define APR_PROCESS_LOCK_IS_GLOBAL 0 + +#define APR_HAVE_CORKABLE_TCP 0 +#define APR_HAVE_GETRLIMIT 0 +#define APR_HAVE_ICONV 0 +#define APR_HAVE_IN_ADDR 1 +#define APR_HAVE_INET_ADDR 1 +#define APR_HAVE_INET_NETWORK 0 +#define APR_HAVE_IPV6 1 +#define APR_HAVE_SOCKADDR_UN 0 +#define APR_HAVE_MEMMOVE 1 +#define APR_HAVE_SETRLIMIT 0 +#define APR_HAVE_SIGACTION 0 +#define APR_HAVE_SIGSUSPEND 0 +#define APR_HAVE_SIGWAIT 0 +#define APR_HAVE_SA_STORAGE 0 +#define APR_HAVE_STRCASECMP 0 +#define APR_HAVE_STRDUP 1 +#define APR_HAVE_STRNCASECMP 0 +#define APR_HAVE_STRSTR 1 +#define APR_HAVE_MEMCHR 1 +#define APR_HAVE_STRUCT_RLIMIT 0 +#define APR_HAVE_UNION_SEMUN 0 +#define APR_HAVE_SCTP 0 +#define APR_HAVE_IOVEC 0 + +#ifndef _WIN32_WCE +#define APR_HAVE_STRICMP 1 +#define APR_HAVE_STRNICMP 1 +#else +#define APR_HAVE_STRICMP 0 +#define APR_HAVE_STRNICMP 0 +#endif + +/* APR Feature Macros */ +#define APR_HAS_SHARED_MEMORY 1 +#define APR_HAS_THREADS 1 +#define APR_HAS_MMAP 1 +#define APR_HAS_FORK 0 +#define APR_HAS_RANDOM 1 +#define APR_HAS_OTHER_CHILD 1 +#define APR_HAS_DSO 1 +#define APR_HAS_SO_ACCEPTFILTER 0 +#define APR_HAS_UNICODE_FS 1 +#define APR_HAS_PROC_INVOKED 1 +#define APR_HAS_OS_UUID 1 +#define APR_HAS_TIMEDLOCKS 1 + +#ifndef _WIN32_WCE +#define APR_HAS_SENDFILE 1 +#define APR_HAS_USER 1 +#define APR_HAS_LARGE_FILES 1 +#define APR_HAS_XTHREAD_FILES 1 +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 1 +#else +#define APR_HAS_SENDFILE 0 +#define APR_HAS_USER 0 +#define APR_HAS_LARGE_FILES 0 +#define APR_HAS_XTHREAD_FILES 0 +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 0 +#endif + +/* APR sets APR_FILES_AS_SOCKETS to 1 on systems where it is possible + * to poll on files/pipes. + */ +#define APR_FILES_AS_SOCKETS 0 + +/* This macro indicates whether or not EBCDIC is the native character set. + */ +#define APR_CHARSET_EBCDIC 0 + +/* If we have a TCP implementation that can be "corked", what flag + * do we use? + */ +#define APR_TCP_NOPUSH_FLAG @apr_tcp_nopush_flag@ + +/* Is the TCP_NODELAY socket option inherited from listening sockets? + */ +#define APR_TCP_NODELAY_INHERITED 1 + +/* Is the O_NONBLOCK flag inherited from listening sockets? + */ +#define APR_O_NONBLOCK_INHERITED 1 + +/* Typedefs that APR needs. */ + +typedef unsigned char apr_byte_t; + +typedef short apr_int16_t; +typedef unsigned short apr_uint16_t; + +typedef int apr_int32_t; +typedef unsigned int apr_uint32_t; + +typedef __int64 apr_int64_t; +typedef unsigned __int64 apr_uint64_t; + +typedef size_t apr_size_t; +#if APR_HAVE_STDDEF_H +typedef ptrdiff_t apr_ssize_t; +#else +typedef int apr_ssize_t; +#endif +#if APR_HAS_LARGE_FILES +typedef __int64 apr_off_t; +#else +typedef int apr_off_t; +#endif +typedef int apr_socklen_t; +typedef apr_uint64_t apr_ino_t; + +#ifdef _WIN64 +#define APR_SIZEOF_VOIDP 8 +#else +#define APR_SIZEOF_VOIDP 4 +#endif + +#if APR_SIZEOF_VOIDP == 8 +typedef apr_uint64_t apr_uintptr_t; +#else +typedef apr_uint32_t apr_uintptr_t; +#endif + +/* Are we big endian? */ +/* XXX: Fatal assumption on Alpha platforms */ +#define APR_IS_BIGENDIAN 0 + +/* Mechanisms to properly type numeric literals */ + +#ifndef __GNUC__ +#define APR_INT64_C(val) (val##i64) +#define APR_UINT64_C(val) (val##Ui64) +#else +#define APR_INT64_C(val) (val##LL) +#define APR_UINT64_C(val) (val##ULL) +#endif + +#ifdef INT16_MIN +#define APR_INT16_MIN INT16_MIN +#else +#define APR_INT16_MIN (-0x7fff - 1) +#endif + +#ifdef INT16_MAX +#define APR_INT16_MAX INT16_MAX +#else +#define APR_INT16_MAX (0x7fff) +#endif + +#ifdef UINT16_MAX +#define APR_UINT16_MAX UINT16_MAX +#else +#define APR_UINT16_MAX (0xffff) +#endif + +#ifdef INT32_MIN +#define APR_INT32_MIN INT32_MIN +#else +#define APR_INT32_MIN (-0x7fffffff - 1) +#endif + +#ifdef INT32_MAX +#define APR_INT32_MAX INT32_MAX +#else +#define APR_INT32_MAX 0x7fffffff +#endif + +#ifdef UINT32_MAX +#define APR_UINT32_MAX UINT32_MAX +#else +#define APR_UINT32_MAX (0xffffffffU) +#endif + +#ifdef INT64_MIN +#define APR_INT64_MIN INT64_MIN +#else +#define APR_INT64_MIN (APR_INT64_C(-0x7fffffffffffffff) - 1) +#endif + +#ifdef INT64_MAX +#define APR_INT64_MAX INT64_MAX +#else +#define APR_INT64_MAX APR_INT64_C(0x7fffffffffffffff) +#endif + +#ifdef UINT64_MAX +#define APR_UINT64_MAX UINT64_MAX +#else +#define APR_UINT64_MAX APR_UINT64_C(0xffffffffffffffff) +#endif + +#define APR_SIZE_MAX (~((apr_size_t)0)) + +/* Definitions that APR programs need to work properly. */ + +/** + * APR public API wrap for C++ compilers. + */ +#ifdef __cplusplus +#define APR_BEGIN_DECLS extern "C" { +#define APR_END_DECLS } +#else +#define APR_BEGIN_DECLS +#define APR_END_DECLS +#endif + +/** + * Thread callbacks from APR functions must be declared with APR_THREAD_FUNC, + * so that they follow the platform's calling convention. + *
+ *
+ * void* APR_THREAD_FUNC my_thread_entry_fn(apr_thread_t *thd, void *data);
+ *
+ * 
+ */ +#define APR_THREAD_FUNC __stdcall + + +#if defined(DOXYGEN) || !defined(WIN32) + +/** + * The public APR functions are declared with APR_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APR_DECLARE_NONSTD(). + * + * @remark Both the declaration and implementations must use the same macro. + * + *
+ * APR_DECLARE(rettype) apr_func(args)
+ * 
+ * @see APR_DECLARE_NONSTD @see APR_DECLARE_DATA + * @remark Note that when APR compiles the library itself, it passes the + * symbol -DAPR_DECLARE_EXPORT to the compiler on some platforms (e.g. Win32) + * to export public symbols from the dynamic library build.\n + * The user must define the APR_DECLARE_STATIC when compiling to target + * the static APR library on some platforms (e.g. Win32.) The public symbols + * are neither exported nor imported when APR_DECLARE_STATIC is defined.\n + * By default, compiling an application and including the APR public + * headers, without defining APR_DECLARE_STATIC, will prepare the code to be + * linked to the dynamic library. + */ +#define APR_DECLARE(type) type + +/** + * The public APR functions using variable arguments are declared with + * APR_DECLARE_NONSTD(), as they must follow the C language calling convention. + * @see APR_DECLARE @see APR_DECLARE_DATA + * @remark Both the declaration and implementations must use the same macro. + *
+ *
+ * APR_DECLARE_NONSTD(rettype) apr_func(args, ...);
+ *
+ * 
+ */ +#define APR_DECLARE_NONSTD(type) type + +/** + * The public APR variables are declared with AP_MODULE_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * @see APR_DECLARE @see APR_DECLARE_NONSTD + * @remark Note that the declaration and implementations use different forms, + * but both must include the macro. + * + *
+ *
+ * extern APR_DECLARE_DATA type apr_variable;\n
+ * APR_DECLARE_DATA type apr_variable = value;
+ *
+ * 
+ */ +#define APR_DECLARE_DATA + +#elif defined(APR_DECLARE_STATIC) +#define APR_DECLARE(type) type __stdcall +#define APR_DECLARE_NONSTD(type) type __cdecl +#define APR_DECLARE_DATA +#elif defined(APR_DECLARE_EXPORT) +#define APR_DECLARE(type) __declspec(dllexport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllexport) +#else +#define APR_DECLARE(type) __declspec(dllimport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllimport) +#endif + +#ifdef _WIN64 +#define APR_SSIZE_T_FMT "I64d" +#define APR_SIZE_T_FMT "I64u" +#else +#define APR_SSIZE_T_FMT "d" +#define APR_SIZE_T_FMT "u" +#endif + +#if APR_HAS_LARGE_FILES +#define APR_OFF_T_FMT "I64d" +#else +#define APR_OFF_T_FMT "d" +#endif + +#define APR_PID_T_FMT "d" + +#define APR_INT64_T_FMT "I64d" +#define APR_UINT64_T_FMT "I64u" +#define APR_UINT64_T_HEX_FMT "I64x" + +/* No difference between PROC and GLOBAL mutex */ +#define APR_PROC_MUTEX_IS_GLOBAL 1 + +/* Local machine definition for console and log output. */ +#define APR_EOL_STR "\r\n" + +typedef int apr_wait_t; + +#if APR_HAS_UNICODE_FS +/* An arbitrary size that is digestable. True max is a bit less than 32000 */ +#define APR_PATH_MAX 8192 +#else /* !APR_HAS_UNICODE_FS */ +#define APR_PATH_MAX MAX_PATH +#endif + +#define APR_DSOPATH "PATH" + +/** @} */ + +/* Definitions that only Win32 programs need to compile properly. */ + +/* XXX These simply don't belong here, perhaps in apr_portable.h + * based on some APR_HAVE_PID/GID/UID? + */ +#ifndef __GNUC__ +typedef int pid_t; +#endif +typedef int uid_t; +typedef int gid_t; + +/* Win32 .h ommissions we really need */ +#define STDIN_FILENO 0 +#define STDOUT_FILENO 1 +#define STDERR_FILENO 2 + +#if APR_HAVE_IPV6 + +/* Appears in later flavors, not the originals. */ +#ifndef in_addr6 +#define in6_addr in_addr6 +#endif + +#ifndef WS2TCPIP_INLINE +#define IN6_IS_ADDR_V4MAPPED(a) \ + ( (*(const apr_uint64_t *)(const void *)(&(a)->s6_addr[0]) == 0) \ + && (*(const apr_uint32_t *)(const void *)(&(a)->s6_addr[8]) == ntohl(0x0000ffff))) +#endif + +#endif /* APR_HAVE_IPV6 */ + +#ifdef __cplusplus +} +#endif + +/* Done with badly written headers, leave 'deprecated CRT' undeprecated + */ +#if defined(_MSC_VER) && _MSC_VER >= 1200 +#pragma warning(pop) +#if _MSC_VER >= 1400 +#pragma warning(disable: 4996) +#endif +#endif + +#endif /* WIN32 */ + +#endif /* APR_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr.h.in b/c/dependencies/windows/apr/x86/include/apr.h.in new file mode 100644 index 00000000..47d8b55a --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr.h.in @@ -0,0 +1,656 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef APR_H +#define APR_H + +/* GENERATED FILE WARNING! DO NOT EDIT apr.h + * + * You must modify apr.h.in instead. + * + * And please, make an effort to stub apr.hw and apr.hnw in the process. + */ + +/** + * @file apr.h + * @brief APR Platform Definitions + * @remark This is a generated header generated from include/apr.h.in by + * ./configure, or copied from include/apr.hw or include/apr.hnw + * for Win32 or Netware by those build environments, respectively. + */ + +/** + * @defgroup APR Apache Portability Runtime library + * @{ + */ +/** + * @defgroup apr_platform Platform Definitions + * @{ + * @warning + * The actual values of macros and typedefs on this page
+ * are platform specific and should NOT be relied upon!
+ */ + +/* So that we can use inline on some critical functions, and use + * GNUC attributes (such as to get -Wall warnings for printf-like + * functions). Only do this in gcc 2.7 or later ... it may work + * on earlier stuff, but why chance it. + * + * We've since discovered that the gcc shipped with NeXT systems + * as "cc" is completely broken. It claims to be __GNUC__ and so + * on, but it doesn't implement half of the things that __GNUC__ + * means. In particular it's missing inline and the __attribute__ + * stuff. So we hack around it. PR#1613. -djg + */ +#if !defined(__GNUC__) || __GNUC__ < 2 || \ + (__GNUC__ == 2 && __GNUC_MINOR__ < 7) ||\ + defined(NEXT) +#ifndef __attribute__ +#define __attribute__(__x) +#endif +#define APR_INLINE +#define APR_HAS_INLINE 0 +#else +#define APR_INLINE __inline__ +#define APR_HAS_INLINE 1 +#endif + +#define APR_HAVE_ARPA_INET_H @arpa_ineth@ +#define APR_HAVE_CONIO_H @conioh@ +#define APR_HAVE_CRYPT_H @crypth@ +#define APR_HAVE_CTYPE_H @ctypeh@ +#define APR_HAVE_DIRENT_H @direnth@ +#define APR_HAVE_ERRNO_H @errnoh@ +#define APR_HAVE_FCNTL_H @fcntlh@ +#define APR_HAVE_IO_H @ioh@ +#define APR_HAVE_LIMITS_H @limitsh@ +#define APR_HAVE_NETDB_H @netdbh@ +#define APR_HAVE_NETINET_IN_H @netinet_inh@ +#define APR_HAVE_NETINET_SCTP_H @netinet_sctph@ +#define APR_HAVE_NETINET_SCTP_UIO_H @netinet_sctp_uioh@ +#define APR_HAVE_NETINET_TCP_H @netinet_tcph@ +#define APR_HAVE_PROCESS_H @processh@ +#define APR_HAVE_PTHREAD_H @pthreadh@ +#define APR_HAVE_SEMAPHORE_H @semaphoreh@ +#define APR_HAVE_SIGNAL_H @signalh@ +#define APR_HAVE_STDARG_H @stdargh@ +#define APR_HAVE_STDINT_H @stdint@ +#define APR_HAVE_STDIO_H @stdioh@ +#define APR_HAVE_STDLIB_H @stdlibh@ +#define APR_HAVE_STRING_H @stringh@ +#define APR_HAVE_STRINGS_H @stringsh@ +#define APR_HAVE_INTTYPES_H @inttypesh@ +#define APR_HAVE_SYS_IOCTL_H @sys_ioctlh@ +#define APR_HAVE_SYS_SENDFILE_H @sys_sendfileh@ +#define APR_HAVE_SYS_SIGNAL_H @sys_signalh@ +#define APR_HAVE_SYS_SOCKET_H @sys_socketh@ +#define APR_HAVE_SYS_SOCKIO_H @sys_sockioh@ +#define APR_HAVE_SYS_SYSLIMITS_H @sys_syslimitsh@ +#define APR_HAVE_SYS_TIME_H @sys_timeh@ +#define APR_HAVE_SYS_TYPES_H @sys_typesh@ +#define APR_HAVE_SYS_UIO_H @sys_uioh@ +#define APR_HAVE_SYS_UN_H @sys_unh@ +#define APR_HAVE_SYS_WAIT_H @sys_waith@ +#define APR_HAVE_TIME_H @timeh@ +#define APR_HAVE_UNISTD_H @unistdh@ +#define APR_HAVE_WINDOWS_H @windowsh@ +#define APR_HAVE_WINSOCK2_H @winsock2h@ + +/** @} */ +/** @} */ + +/* We don't include our conditional headers within the doxyblocks + * or the extern "C" namespace + */ + +#if APR_HAVE_WINDOWS_H && defined(WIN32) +/* If windows.h was already included, our preferences don't matter. + * If not, include a restricted set of windows headers to our tastes. + */ +#ifndef _WINDOWS_ + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif + +#ifndef _WIN32_WINNT +/* Restrict the server to a subset of Windows XP header files by default + */ +#define _WIN32_WINNT 0x0501 +#endif + +#ifndef NOUSER +#define NOUSER +#endif +#ifndef NOMCX +#define NOMCX +#endif +#ifndef NOIME +#define NOIME +#endif + +#include +/* + * Add a _very_few_ declarations missing from the restricted set of headers + * (If this list becomes extensive, re-enable the required headers above!) + * winsock headers were excluded by WIN32_LEAN_AND_MEAN, so include them now + */ +#define SW_HIDE 0 +#ifndef _WIN32_WCE +#include +#include +#include +#else +#include +#endif + +#endif /* ndef _WINDOWS_ */ +#endif /* APR_HAVE_WINDOWS_H */ + +#if APR_HAVE_SYS_TYPES_H +#include +#endif + +#if APR_HAVE_SYS_SOCKET_H +#include +#endif + +#if APR_HAVE_STDINT_H +#ifdef __cplusplus +/* C99 7.18.4 requires that stdint.h only exposes INT64_C + * and UINT64_C for C++ implementations if this is defined: */ +#ifndef __STDC_CONSTANT_MACROS +#define __STDC_CONSTANT_MACROS +#endif +/* C++ needs this too for PRI*NN formats: */ +#ifndef __STDC_FORMAT_MACROS +#define __STDC_FORMAT_MACROS +#endif +#endif /* __cplusplus */ +#include +#endif + +#if APR_HAVE_INTTYPES_H +#include +#endif + +#if APR_HAVE_SYS_WAIT_H +#include +#endif + +#ifdef OS2 +#define INCL_DOS +#define INCL_DOSERRORS +#include +#endif + +/* header files for PATH_MAX, _POSIX_PATH_MAX */ +#if APR_HAVE_LIMITS_H +#include +#else +#if APR_HAVE_SYS_SYSLIMITS_H +#include +#endif +#endif + +/* __APPLE__ is now the official pre-defined macro for macOS */ +#ifdef __APPLE__ +#undef DARWIN +#undef DARWIN_10 +#define DARWIN +#define DARWIN_10 +#endif /* __APPLE__ */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @addtogroup apr_platform + * @ingroup APR + * @{ + */ + +#define APR_HAVE_SHMEM_MMAP_TMP @havemmaptmp@ +#define APR_HAVE_SHMEM_MMAP_SHM @havemmapshm@ +#define APR_HAVE_SHMEM_MMAP_ZERO @havemmapzero@ +#define APR_HAVE_SHMEM_SHMGET_ANON @haveshmgetanon@ +#define APR_HAVE_SHMEM_SHMGET @haveshmget@ +#define APR_HAVE_SHMEM_MMAP_ANON @havemmapanon@ +#define APR_HAVE_SHMEM_BEOS @havebeosarea@ + +#define APR_USE_SHMEM_MMAP_TMP @usemmaptmp@ +#define APR_USE_SHMEM_MMAP_SHM @usemmapshm@ +#define APR_USE_SHMEM_MMAP_ZERO @usemmapzero@ +#define APR_USE_SHMEM_SHMGET_ANON @useshmgetanon@ +#define APR_USE_SHMEM_SHMGET @useshmget@ +#define APR_USE_SHMEM_MMAP_ANON @usemmapanon@ +#define APR_USE_SHMEM_BEOS @usebeosarea@ + +#define APR_USE_FLOCK_SERIALIZE @flockser@ +#define APR_USE_SYSVSEM_SERIALIZE @sysvser@ +#define APR_USE_POSIXSEM_SERIALIZE @posixser@ +#define APR_USE_FCNTL_SERIALIZE @fcntlser@ +#define APR_USE_PROC_PTHREAD_SERIALIZE @procpthreadser@ +#define APR_USE_PTHREAD_SERIALIZE @pthreadser@ + +#define APR_HAS_FLOCK_SERIALIZE @hasflockser@ +#define APR_HAS_SYSVSEM_SERIALIZE @hassysvser@ +#define APR_HAS_POSIXSEM_SERIALIZE @hasposixser@ +#define APR_HAS_FCNTL_SERIALIZE @hasfcntlser@ +#define APR_HAS_PROC_PTHREAD_SERIALIZE @hasprocpthreadser@ + +#define APR_PROCESS_LOCK_IS_GLOBAL @proclockglobal@ + +#define APR_HAVE_CORKABLE_TCP @have_corkable_tcp@ +#define APR_HAVE_GETRLIMIT @have_getrlimit@ +#define APR_HAVE_IN_ADDR @have_in_addr@ +#define APR_HAVE_INET_ADDR @have_inet_addr@ +#define APR_HAVE_INET_NETWORK @have_inet_network@ +#define APR_HAVE_IPV6 @have_ipv6@ +#define APR_HAVE_SOCKADDR_UN @have_sockaddr_un@ +#define APR_HAVE_MEMMOVE @have_memmove@ +#define APR_HAVE_SETRLIMIT @have_setrlimit@ +#define APR_HAVE_SIGACTION @have_sigaction@ +#define APR_HAVE_SIGSUSPEND @have_sigsuspend@ +#define APR_HAVE_SIGWAIT @have_sigwait@ +#define APR_HAVE_SA_STORAGE @have_sa_storage@ +#define APR_HAVE_STRCASECMP @have_strcasecmp@ +#define APR_HAVE_STRDUP @have_strdup@ +#define APR_HAVE_STRICMP @have_stricmp@ +#define APR_HAVE_STRNCASECMP @have_strncasecmp@ +#define APR_HAVE_STRNICMP @have_strnicmp@ +#define APR_HAVE_STRSTR @have_strstr@ +#define APR_HAVE_MEMCHR @have_memchr@ +#define APR_HAVE_STRUCT_RLIMIT @struct_rlimit@ +#define APR_HAVE_UNION_SEMUN @have_union_semun@ +#define APR_HAVE_SCTP @have_sctp@ +#define APR_HAVE_IOVEC @have_iovec@ + +/* APR Feature Macros */ +#define APR_HAS_SHARED_MEMORY @sharedmem@ +#define APR_HAS_THREADS @threads@ +#define APR_HAS_SENDFILE @sendfile@ +#define APR_HAS_MMAP @mmap@ +#define APR_HAS_FORK @fork@ +#define APR_HAS_RANDOM @rand@ +#define APR_HAS_OTHER_CHILD @oc@ +#define APR_HAS_DSO @aprdso@ +#define APR_HAS_SO_ACCEPTFILTER @acceptfilter@ +#define APR_HAS_UNICODE_FS @have_unicode_fs@ +#define APR_HAS_PROC_INVOKED @have_proc_invoked@ +#define APR_HAS_USER @apr_has_user@ +#define APR_HAS_LARGE_FILES @aprlfs@ +#define APR_HAS_XTHREAD_FILES @apr_has_xthread_files@ +#define APR_HAS_OS_UUID @osuuid@ +#define APR_HAS_TIMEDLOCKS @apr_has_timedlocks@ + +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD @apr_procattr_user_set_requires_password@ + +/* APR sets APR_FILES_AS_SOCKETS to 1 on systems where it is possible + * to poll on files/pipes. + */ +#define APR_FILES_AS_SOCKETS @file_as_socket@ + +/* This macro indicates whether or not EBCDIC is the native character set. + */ +#define APR_CHARSET_EBCDIC @apr_charset_ebcdic@ + +/* If we have a TCP implementation that can be "corked", what flag + * do we use? + */ +#define APR_TCP_NOPUSH_FLAG @apr_tcp_nopush_flag@ + +/* Is the TCP_NODELAY socket option inherited from listening sockets? +*/ +#define APR_TCP_NODELAY_INHERITED @tcp_nodelay_inherited@ + +/* Is the O_NONBLOCK flag inherited from listening sockets? +*/ +#define APR_O_NONBLOCK_INHERITED @o_nonblock_inherited@ + +/* Typedefs that APR needs. */ + +typedef unsigned char apr_byte_t; + +typedef @short_value@ apr_int16_t; +typedef unsigned @short_value@ apr_uint16_t; + +typedef @int_value@ apr_int32_t; +typedef unsigned @int_value@ apr_uint32_t; + +#define APR_SIZEOF_VOIDP @voidp_size@ + +/* + * Darwin 10's default compiler (gcc42) builds for both 64 and + * 32 bit architectures unless specifically told not to. + * In those cases, we need to override types depending on how + * we're being built at compile time. + * NOTE: This is an ugly work-around for Darwin's + * concept of universal binaries, a single package + * (executable, lib, etc...) which contains both 32 + * and 64 bit versions. The issue is that if APR is + * built universally, if something else is compiled + * against it, some bit sizes will depend on whether + * it is 32 or 64 bit. This is determined by the __LP64__ + * flag. Since we need to support both, we have to + * handle OS X unqiuely. + */ +#ifdef DARWIN_10 +#undef APR_SIZEOF_VOIDP +#undef APR_INT64_C +#undef APR_UINT64_C +#ifdef __LP64__ + typedef long apr_int64_t; + typedef unsigned long apr_uint64_t; + #define APR_SIZEOF_VOIDP 8 + #define APR_INT64_C(v) (v ## L) + #define APR_UINT64_C(v) (v ## UL) +#else + typedef long long apr_int64_t; + typedef unsigned long long apr_uint64_t; + #define APR_SIZEOF_VOIDP 4 + #define APR_INT64_C(v) (v ## LL) + #define APR_UINT64_C(v) (v ## ULL) +#endif +#else + typedef @int64_value@ apr_int64_t; + typedef @uint64_value@ apr_uint64_t; + + /* Mechanisms to properly type numeric literals */ + @int64_literal@ + @uint64_literal@ +#endif + +typedef @size_t_value@ apr_size_t; +typedef @ssize_t_value@ apr_ssize_t; +typedef @off_t_value@ apr_off_t; +typedef @socklen_t_value@ apr_socklen_t; +typedef @ino_t_value@ apr_ino_t; + +#if APR_SIZEOF_VOIDP == 8 +typedef apr_uint64_t apr_uintptr_t; +#else +typedef apr_uint32_t apr_uintptr_t; +#endif + +/* Are we big endian? */ +#define APR_IS_BIGENDIAN @bigendian@ + +#ifdef INT16_MIN +#define APR_INT16_MIN INT16_MIN +#else +#define APR_INT16_MIN (-0x7fff - 1) +#endif + +#ifdef INT16_MAX +#define APR_INT16_MAX INT16_MAX +#else +#define APR_INT16_MAX (0x7fff) +#endif + +#ifdef UINT16_MAX +#define APR_UINT16_MAX UINT16_MAX +#else +#define APR_UINT16_MAX (0xffff) +#endif + +#ifdef INT32_MIN +#define APR_INT32_MIN INT32_MIN +#else +#define APR_INT32_MIN (-0x7fffffff - 1) +#endif + +#ifdef INT32_MAX +#define APR_INT32_MAX INT32_MAX +#else +#define APR_INT32_MAX 0x7fffffff +#endif + +#ifdef UINT32_MAX +#define APR_UINT32_MAX UINT32_MAX +#else +#define APR_UINT32_MAX (0xffffffffU) +#endif + +#ifdef INT64_MIN +#define APR_INT64_MIN INT64_MIN +#else +#define APR_INT64_MIN (APR_INT64_C(-0x7fffffffffffffff) - 1) +#endif + +#ifdef INT64_MAX +#define APR_INT64_MAX INT64_MAX +#else +#define APR_INT64_MAX APR_INT64_C(0x7fffffffffffffff) +#endif + +#ifdef UINT64_MAX +#define APR_UINT64_MAX UINT64_MAX +#else +#define APR_UINT64_MAX APR_UINT64_C(0xffffffffffffffff) +#endif + +#define APR_SIZE_MAX (~((apr_size_t)0)) + + +/* Definitions that APR programs need to work properly. */ + +/** + * APR public API wrap for C++ compilers. + */ +#ifdef __cplusplus +#define APR_BEGIN_DECLS extern "C" { +#define APR_END_DECLS } +#else +#define APR_BEGIN_DECLS +#define APR_END_DECLS +#endif + +/** + * Thread callbacks from APR functions must be declared with APR_THREAD_FUNC, + * so that they follow the platform's calling convention. + *
+ *
+ * void* APR_THREAD_FUNC my_thread_entry_fn(apr_thread_t *thd, void *data);
+ *
+ * 
+ */ +#define APR_THREAD_FUNC @apr_thread_func@ + +#if defined(DOXYGEN) || !defined(WIN32) + +/** + * The public APR functions are declared with APR_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APR_DECLARE_NONSTD(). + * + * @remark Both the declaration and implementations must use the same macro. + * + *
+ * APR_DECLARE(rettype) apr_func(args)
+ * 
+ * @see APR_DECLARE_NONSTD @see APR_DECLARE_DATA + * @remark Note that when APR compiles the library itself, it passes the + * symbol -DAPR_DECLARE_EXPORT to the compiler on some platforms (e.g. Win32) + * to export public symbols from the dynamic library build.\n + * The user must define the APR_DECLARE_STATIC when compiling to target + * the static APR library on some platforms (e.g. Win32.) The public symbols + * are neither exported nor imported when APR_DECLARE_STATIC is defined.\n + * By default, compiling an application and including the APR public + * headers, without defining APR_DECLARE_STATIC, will prepare the code to be + * linked to the dynamic library. + */ +#define APR_DECLARE(type) type + +/** + * The public APR functions using variable arguments are declared with + * APR_DECLARE_NONSTD(), as they must follow the C language calling convention. + * @see APR_DECLARE @see APR_DECLARE_DATA + * @remark Both the declaration and implementations must use the same macro. + *
+ *
+ * APR_DECLARE_NONSTD(rettype) apr_func(args, ...);
+ *
+ * 
+ */ +#define APR_DECLARE_NONSTD(type) type + +/** + * The public APR variables are declared with AP_MODULE_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * @see APR_DECLARE @see APR_DECLARE_NONSTD + * @remark Note that the declaration and implementations use different forms, + * but both must include the macro. + * + *
+ *
+ * extern APR_DECLARE_DATA type apr_variable;\n
+ * APR_DECLARE_DATA type apr_variable = value;
+ *
+ * 
+ */ +#define APR_DECLARE_DATA + +#elif defined(APR_DECLARE_STATIC) +#define APR_DECLARE(type) type __stdcall +#define APR_DECLARE_NONSTD(type) type __cdecl +#define APR_DECLARE_DATA +#elif defined(APR_DECLARE_EXPORT) +#define APR_DECLARE(type) __declspec(dllexport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllexport) +#else +#define APR_DECLARE(type) __declspec(dllimport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllimport) +#endif + +/* Define APR_SSIZE_T_FMT. + * If ssize_t is an integer we define it to be "d", + * if ssize_t is a long int we define it to be "ld", + * if ssize_t is neither we declare an error here. + * I looked for a better way to define this here, but couldn't find one, so + * to find the logic for this definition search for "ssize_t_fmt" in + * configure.in. + */ + +@ssize_t_fmt@ + +/* And APR_SIZE_T_FMT */ +@size_t_fmt@ + +/* And APR_OFF_T_FMT */ +@off_t_fmt@ + +/* And APR_PID_T_FMT */ +@pid_t_fmt@ + +/* And APR_INT64_T_FMT */ +@int64_t_fmt@ + +/* And APR_UINT64_T_FMT */ +@uint64_t_fmt@ + +/* And APR_UINT64_T_HEX_FMT */ +@uint64_t_hex_fmt@ + +/* + * Ensure we work with universal binaries on Darwin + */ +#ifdef DARWIN_10 + +#undef APR_HAS_LARGE_FILES +#undef APR_SIZEOF_VOIDP +#undef APR_INT64_T_FMT +#undef APR_UINT64_T_FMT +#undef APR_UINT64_T_HEX_FMT + +#ifdef __LP64__ + #define APR_HAS_LARGE_FILES 0 + #define APR_SIZEOF_VOIDP 8 + #define APR_INT64_T_FMT "ld" + #define APR_UINT64_T_FMT "lu" + #define APR_UINT64_T_HEX_FMT "lx" +#else + #define APR_HAS_LARGE_FILES 1 + #define APR_SIZEOF_VOIDP 4 + #define APR_INT64_T_FMT "lld" + #define APR_UINT64_T_FMT "llu" + #define APR_UINT64_T_HEX_FMT "llx" +#endif + +#undef APR_IS_BIGENDIAN +#ifdef __BIG_ENDIAN__ + #define APR_IS_BIGENDIAN 1 +#else + #define APR_IS_BIGENDIAN 0 +#endif + +#undef APR_OFF_T_FMT +#define APR_OFF_T_FMT "lld" + +#endif /* DARWIN_10 */ + +/* Does the proc mutex lock threads too */ +#define APR_PROC_MUTEX_IS_GLOBAL @proc_mutex_is_global@ + +/* Local machine definition for console and log output. */ +#define APR_EOL_STR "@eolstr@" + +#if APR_HAVE_SYS_WAIT_H +#ifdef WEXITSTATUS +#define apr_wait_t int +#else +#define apr_wait_t union wait +#define WEXITSTATUS(status) (int)((status).w_retcode) +#define WTERMSIG(status) (int)((status).w_termsig) +#endif /* !WEXITSTATUS */ +#elif defined(__MINGW32__) +typedef int apr_wait_t; +#endif /* HAVE_SYS_WAIT_H */ + +#if defined(PATH_MAX) +#define APR_PATH_MAX PATH_MAX +#elif defined(_POSIX_PATH_MAX) +#define APR_PATH_MAX _POSIX_PATH_MAX +#else +#error no decision has been made on APR_PATH_MAX for your platform +#endif + +#define APR_DSOPATH "@shlibpath_var@" + +/** @} */ + +/* Definitions that only Win32 programs need to compile properly. */ + +/* XXX These simply don't belong here, perhaps in apr_portable.h + * based on some APR_HAVE_PID/GID/UID? + */ +#ifdef __MINGW32__ +#ifndef __GNUC__ +typedef int pid_t; +#endif +typedef int uid_t; +typedef int gid_t; +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* APR_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr.hnw b/c/dependencies/windows/apr/x86/include/apr.hnw new file mode 100644 index 00000000..21c8a98e --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr.hnw @@ -0,0 +1,445 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef APR_H +#define APR_H + +/* GENERATED FILE WARNING! DO NOT EDIT apr.h + * + * You must modify apr.hnw instead. + * + * And please, make an effort to stub apr.hw and apr.h.in in the process. + * + * This is the NetWare specific version of apr.h. It is copied from + * apr.hnw at the start of a NetWare build by the ./build/NWGNmakefile. + */ + +/** + * @file apr.h + * @brief APR Platform Definitions + * @remark This is a generated header generated from include/apr.h.in by + * ./configure, or copied from include/apr.hw or include/apr.hnw + * for Win32 or Netware by those build environments, respectively. + */ + +#if defined(NETWARE) || defined(DOXYGEN) + +#undef FD_SETSIZE +#define FD_SETSIZE 1024 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef USE_WINSOCK +#include +#ifdef NW_BUILD_IPV6 +#include +#endif +#else +#include +#include +#endif +#include + +#define _POSIX_THREAD_SAFE_FUNCTIONS 1 +#define READDIR_IS_THREAD_SAFE 1 + +/* Keep #include'd headers from within the __cplusplus or doxyblocks */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_platform Platform Definitions + * @ingroup APR + * @{ + */ + +#define APR_INLINE +#define APR_HAS_INLINE 0 +#ifndef __attribute__ +#define __attribute__(__x) +#endif +#define ENUM_BITFIELD(e,n,w) signed int n : w + +#define APR_HAVE_CONIO_H 0 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 1 +#define APR_HAVE_DIRENT_H 1 +#define APR_HAVE_ERRNO_H 1 +#define APR_HAVE_FCNTL_H 1 +#define APR_HAVE_IO_H 0 +#define APR_HAVE_LIMITS_H 1 +#ifdef USE_WINSOCK +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#else +#define APR_HAVE_ARPA_INET_H 1 +#define APR_HAVE_NETDB_H 1 +#define APR_HAVE_NETINET_IN_H 1 +#endif +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SIGNAL_H 1 +#define APR_HAVE_STDARG_H 1 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_STRTOLL 1 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#ifdef USE_WINSOCK +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#else +#define APR_HAVE_SYS_SOCKET_H 1 +#define APR_HAVE_SYS_SOCKIO_H 1 +#define APR_HAVE_SYS_UN_H 1 +#endif +#define APR_HAVE_SYS_SIGNAL_H 1 +#define APR_HAVE_SYS_TIME_H 1 +#define APR_HAVE_SYS_TYPES_H 1 +#define APR_HAVE_SYS_UIO_H 1 +#define APR_HAVE_SYS_WAIT_H 1 +#define APR_HAVE_TIME_H 1 +#define APR_HAVE_UNISTD_H 1 + +#define APR_HAVE_SHMEM_MMAP_TMP 0 +#define APR_HAVE_SHMEM_MMAP_SHM 0 +#define APR_HAVE_SHMEM_MMAP_ZERO 0 +#define APR_HAVE_SHMEM_SHMGET_ANON 0 +#define APR_HAVE_SHMEM_SHMGET 0 +#define APR_HAVE_SHMEM_MMAP_ANON 0 +#define APR_HAVE_SHMEM_BEOS 0 + +#define APR_USE_SHMEM_MMAP_TMP 0 +#define APR_USE_SHMEM_MMAP_SHM 0 +#define APR_USE_SHMEM_MMAP_ZERO 0 +#define APR_USE_SHMEM_SHMGET_ANON 0 +#define APR_USE_SHMEM_SHMGET 0 +#define APR_USE_SHMEM_MMAP_ANON 0 +#define APR_USE_SHMEM_BEOS 0 + +#define APR_USE_FLOCK_SERIALIZE 0 +#define APR_USE_SYSVSEM_SERIALIZE 0 +#define APR_USE_FCNTL_SERIALIZE 0 +#define APR_USE_PROC_PTHREAD_SERIALIZE 0 +#define APR_USE_PTHREAD_SERIALIZE 0 + +#define APR_HAS_FLOCK_SERIALIZE 0 +#define APR_HAS_SYSVSEM_SERIALIZE 0 +#define APR_HAS_FCNTL_SERIALIZE 0 +#define APR_HAS_PROC_PTHREAD_SERIALIZE 0 +#define APR_HAS_RWLOCK_SERIALIZE 0 + +#define APR_HAS_LOCK_CREATE_NP 0 + +#define APR_PROCESS_LOCK_IS_GLOBAL 1 + +#define APR_FILE_BASED_SHM 0 + +#define APR_HAVE_CORKABLE_TCP 0 +#define APR_HAVE_GETRLIMIT 0 +#define APR_HAVE_ICONV 0 +#define APR_HAVE_IN_ADDR 1 +#define APR_HAVE_INET_ADDR 1 +#define APR_HAVE_INET_NETWORK 0 +#ifdef NW_BUILD_IPV6 +#define APR_HAVE_IPV6 1 +#else +#define APR_HAVE_IPV6 0 +#endif +#define APR_HAVE_SOCKADDR_UN 0 +#define APR_HAVE_MEMCHR 1 +#define APR_HAVE_MEMMOVE 1 +#define APR_HAVE_SETRLIMIT 0 +#define APR_HAVE_SIGACTION 0 +#define APR_HAVE_SIGSUSPEND 0 +#define APR_HAVE_SIGWAIT 0 +#define APR_HAVE_STRCASECMP 1 +#define APR_HAVE_STRDUP 1 +#define APR_HAVE_STRICMP 1 +#define APR_HAVE_STRNCASECMP 1 +#define APR_HAVE_STRNICMP 1 +#define APR_HAVE_STRSTR 1 +#define APR_HAVE_STRUCT_RLIMIT 0 +#define APR_HAVE_UNION_SEMUN 0 +#define APR_HAVE_SCTP 0 +#define APR_HAVE_IOVEC 1 + +/* APR Feature Macros */ +#define APR_HAS_SHARED_MEMORY 0 +#define APR_HAS_THREADS 1 +#define APR_HAS_SENDFILE 0 +#define APR_HAS_MMAP 0 +#define APR_HAS_FORK 0 +#define APR_HAS_RANDOM 1 +#define APR_HAS_OTHER_CHILD 0 +#define APR_HAS_DSO 1 +#define APR_HAS_SO_ACCEPTFILTER 0 +#define APR_HAS_UNICODE_FS 0 +#define APR_HAS_PROC_INVOKED 0 +#define APR_HAS_USER 1 +#define APR_HAS_LARGE_FILES 1 +#define APR_HAS_XTHREAD_FILES 0 +#define APR_HAS_OS_UUID 0 +#define APR_HAS_TIMEDLOCKS 1 + +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 0 + +/* Netware can poll on files/pipes. + */ +#define APR_FILES_AS_SOCKETS 1 + +/* This macro indicates whether or not EBCDIC is the native character set. + */ +#define APR_CHARSET_EBCDIC 0 + +/* Is the TCP_NODELAY socket option inherited from listening sockets? +*/ +#define APR_TCP_NODELAY_INHERITED 1 + +/* Is the O_NONBLOCK flag inherited from listening sockets? +*/ +#define APR_O_NONBLOCK_INHERITED 1 + +/* Typedefs that APR needs. */ + +typedef unsigned char apr_byte_t; + +typedef short apr_int16_t; +typedef unsigned short apr_uint16_t; + +typedef int apr_int32_t; +typedef unsigned int apr_uint32_t; + +typedef long long apr_int64_t; +typedef unsigned long long apr_uint64_t; + +typedef size_t apr_size_t; +typedef ssize_t apr_ssize_t; +#if APR_HAS_LARGE_FILES +typedef off64_t apr_off_t; +#else +typedef off_t apr_off_t; +#endif +#ifdef USE_WINSOCK +typedef int apr_socklen_t; +#else +typedef size_t apr_socklen_t; +#endif +typedef apr_uint64_t apr_ino_t; + +/* Are we big endian? */ +/* XXX: Fatal assumption on Alpha platforms */ +#define APR_IS_BIGENDIAN 0 + +#ifdef UNKNOWN_NETWARE_64BIT_FLAG_NEEDED +#define APR_SIZEOF_VOIDP 8 +#else +#define APR_SIZEOF_VOIDP 4 +#endif + +#if APR_SIZEOF_VOIDP == 8 +typedef apr_uint64_t apr_uintptr_t; +#else +typedef apr_uint32_t apr_uintptr_t; +#endif + +/* Mechanisms to properly type numeric literals */ +#define APR_INT64_C(val) (val##LL) +#define APR_UINT64_C(val) (val##ULL) + +#ifdef INT16_MIN +#define APR_INT16_MIN INT16_MIN +#else +#define APR_INT16_MIN (-0x7fff - 1) +#endif + +#ifdef INT16_MAX +#define APR_INT16_MAX INT16_MAX +#else +#define APR_INT16_MAX (0x7fff) +#endif + +#ifdef UINT16_MAX +#define APR_UINT16_MAX UINT16_MAX +#else +#define APR_UINT16_MAX (0xffff) +#endif + +#ifdef INT32_MIN +#define APR_INT32_MIN INT32_MIN +#else +#define APR_INT32_MIN (-0x7fffffff - 1) +#endif + +#ifdef INT32_MAX +#define APR_INT32_MAX INT32_MAX +#else +#define APR_INT32_MAX 0x7fffffff +#endif + +#ifdef UINT32_MAX +#define APR_UINT32_MAX UINT32_MAX +#else +#define APR_UINT32_MAX (0xffffffffU) +#endif + +#ifdef INT64_MIN +#define APR_INT64_MIN INT64_MIN +#else +#define APR_INT64_MIN (APR_INT64_C(-0x7fffffffffffffff) - 1) +#endif + +#ifdef INT64_MAX +#define APR_INT64_MAX INT64_MAX +#else +#define APR_INT64_MAX APR_INT64_C(0x7fffffffffffffff) +#endif + +#ifdef UINT64_MAX +#define APR_UINT64_MAX UINT64_MAX +#else +#define APR_UINT64_MAX APR_UINT64_C(0xffffffffffffffff) +#endif + +#define APR_SIZE_MAX (~((apr_size_t)0)) + +/* PROC mutex is a GLOBAL mutex on Netware */ +#define APR_PROC_MUTEX_IS_GLOBAL 1 + +/* Definitions that APR programs need to work properly. */ + +/** + * APR public API wrap for C++ compilers. + */ +#ifdef __cplusplus +#define APR_BEGIN_DECLS extern "C" { +#define APR_END_DECLS } +#else +#define APR_BEGIN_DECLS +#define APR_END_DECLS +#endif + +/** + * Thread callbacks from APR functions must be declared with APR_THREAD_FUNC, + * so that they follow the platform's calling convention. + * @example + */ +/** void* APR_THREAD_FUNC my_thread_entry_fn(apr_thread_t *thd, void *data); + */ +#define APR_THREAD_FUNC + +/** + * The public APR functions are declared with APR_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APR_DECLARE_NONSTD(). + * + * @remark Both the declaration and implementations must use the same macro. + * @example + */ +/** APR_DECLARE(rettype) apr_func(args) + * @see APR_DECLARE_NONSTD @see APR_DECLARE_DATA + * @remark Note that when APR compiles the library itself, it passes the + * symbol -DAPR_DECLARE_EXPORT to the compiler on some platforms (e.g. Win32) + * to export public symbols from the dynamic library build.\n + * The user must define the APR_DECLARE_STATIC when compiling to target + * the static APR library on some platforms (e.g. Win32.) The public symbols + * are neither exported nor imported when APR_DECLARE_STATIC is defined.\n + * By default, compiling an application and including the APR public + * headers, without defining APR_DECLARE_STATIC, will prepare the code to be + * linked to the dynamic library. + */ +#define APR_DECLARE(type) type + +/** + * The public APR functions using variable arguments are declared with + * APR_DECLARE_NONSTD(), as they must follow the C language calling convention. + * @see APR_DECLARE @see APR_DECLARE_DATA + * @remark Both the declaration and implementations must use the same macro. + * @example + */ +/** APR_DECLARE_NONSTD(rettype) apr_func(args, ...); + */ +#define APR_DECLARE_NONSTD(type) type + +/** + * The public APR variables are declared with APR_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * @see APR_DECLARE @see APR_DECLARE_NONSTD + * @remark Note that the declaration and implementations use different forms, + * but both must include the macro. + * @example + */ +/** extern APR_DECLARE_DATA type apr_variable;\n + * APR_DECLARE_DATA type apr_variable = value; + */ +#define APR_DECLARE_DATA + +#define APR_SSIZE_T_FMT "d" + +#define APR_SIZE_T_FMT "d" + +#if APR_HAS_LARGE_FILES +#define APR_OFF_T_FMT "lld" +#else +#define APR_OFF_T_FMT "ld" +#endif + +#define APR_PID_T_FMT "d" + +/* Local machine definition for console and log output. */ +#define APR_EOL_STR "\r\n" + +typedef int apr_wait_t; + +#define APR_PATH_MAX PATH_MAX + +#define APR_DSOPATH "PATH" + +#define APR_INT64_T_FMT "lld" +#define APR_UINT64_T_FMT "llu" +#define APR_UINT64_T_HEX_FMT "llx" +#define APR_TIME_T_FMT APR_INT64_T_FMT + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* NETWARE */ + +#endif /* APR_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr.hw b/c/dependencies/windows/apr/x86/include/apr.hw new file mode 100644 index 00000000..b8d97495 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr.hw @@ -0,0 +1,667 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef APR_H +#define APR_H + +/* GENERATED FILE WARNING! DO NOT EDIT apr.h + * + * You must modify apr.hw instead. + * + * And please, make an effort to stub apr.hnw and apr.h.in in the process. + * + * This is the Win32 specific version of apr.h. It is copied from + * apr.hw by the apr.dsp and libapr.dsp projects. + */ + +/** + * @file apr.h + * @brief APR Platform Definitions + * @remark This is a generated header generated from include/apr.h.in by + * ./configure, or copied from include/apr.hw or include/apr.hnw + * for Win32 or Netware by those build environments, respectively. + */ + +/* Make sure we have our platform identifier macro defined we ask for later. + */ +#if defined(_WIN32) && !defined(WIN32) +#define WIN32 1 +#endif + +#if defined(WIN32) || defined(DOXYGEN) + +/* Ignore most warnings (back down to /W3) for poorly constructed headers + */ +#if defined(_MSC_VER) && _MSC_VER >= 1200 +#pragma warning(push, 3) +#endif + +/* disable or reduce the frequency of... + * C4057: indirection to slightly different base types + * C4075: slight indirection changes (unsigned short* vs short[]) + * C4100: unreferenced formal parameter + * C4127: conditional expression is constant + * C4163: '_rotl64' : not available as an intrinsic function + * C4201: nonstandard extension nameless struct/unions + * C4244: int to char/short - precision loss + * C4514: unreferenced inline function removed + */ +#if defined(_MSC_VER) +#pragma warning(disable: 4100 4127 4163 4201 4514; once: 4057 4075 4244) +#endif + +/* Ignore Microsoft's interpretation of secure development + * and the POSIX string handling API + */ +#if defined(_MSC_VER) && _MSC_VER >= 1400 +#ifndef _CRT_SECURE_NO_DEPRECATE +#define _CRT_SECURE_NO_DEPRECATE +#endif +#pragma warning(disable: 4996) +#endif + +/* Has windows.h already been included? If so, our preferences don't matter, + * but we will still need the winsock things no matter what was included. + * If not, include a restricted set of windows headers to our tastes. + */ +#ifndef _WINDOWS_ +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef _WIN32_WINNT + +/* Restrict the server to a subset of Windows XP header files by default + */ +#define _WIN32_WINNT 0x0A00 +#endif +#ifndef NOUSER +#define NOUSER +#endif +#ifndef NOMCX +#define NOMCX +#endif +#ifndef NOIME +#define NOIME +#endif +#include +/* + * Add a _very_few_ declarations missing from the restricted set of headers + * (If this list becomes extensive, re-enable the required headers above!) + * winsock headers were excluded by WIN32_LEAN_AND_MEAN, so include them now + */ +#define SW_HIDE 0 +#ifndef _WIN32_WCE +#include +#include +#include +#else +#include +#endif +#endif /* !_WINDOWS_ */ + +/** + * @defgroup APR Apache Portability Runtime library + * @{ + */ +/** + * @defgroup apr_platform Platform Definitions + * @{ + * @warning + * The actual values of macros and typedefs on this page
+ * are platform specific and should NOT be relied upon!
+ */ + +#define APR_INLINE __inline +#define APR_HAS_INLINE 1 +#if !defined(__GNUC__) && !defined(__attribute__) +#define __attribute__(__x) +#endif + +#ifndef _WIN32_WCE +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_CONIO_H 1 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 1 +#define APR_HAVE_DIRENT_H 0 +#define APR_HAVE_ERRNO_H 1 +#define APR_HAVE_FCNTL_H 1 +#define APR_HAVE_IO_H 1 +#define APR_HAVE_LIMITS_H 1 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SEMAPHORE_H 0 +#define APR_HAVE_SIGNAL_H 1 +#define APR_HAVE_STDARG_H 1 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_SYS_IOCTL_H 0 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SIGNAL_H 0 +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#define APR_HAVE_SYS_TIME_H 0 +#define APR_HAVE_SYS_TYPES_H 1 +#define APR_HAVE_SYS_UIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#define APR_HAVE_SYS_WAIT_H 0 +#define APR_HAVE_TIME_H 1 +#define APR_HAVE_UNISTD_H 0 +#define APR_HAVE_STDDEF_H 1 +#define APR_HAVE_PROCESS_H 1 +#else +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_CONIO_H 0 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 0 +#define APR_HAVE_DIRENT_H 0 +#define APR_HAVE_ERRNO_H 0 +#define APR_HAVE_FCNTL_H 0 +#define APR_HAVE_IO_H 0 +#define APR_HAVE_LIMITS_H 0 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SEMAPHORE_H 0 +#define APR_HAVE_SIGNAL_H 0 +#define APR_HAVE_STDARG_H 0 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_SYS_IOCTL_H 0 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SIGNAL_H 0 +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#define APR_HAVE_SYS_TIME_H 0 +#define APR_HAVE_SYS_TYPES_H 0 +#define APR_HAVE_SYS_UIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#define APR_HAVE_SYS_WAIT_H 0 +#define APR_HAVE_TIME_H 0 +#define APR_HAVE_UNISTD_H 0 +#define APR_HAVE_STDDEF_H 0 +#define APR_HAVE_PROCESS_H 0 +#endif + +/** @} */ +/** @} */ + +/* We don't include our conditional headers within the doxyblocks + * or the extern "C" namespace + */ + +#if APR_HAVE_STDLIB_H +#include +#endif + +#if APR_HAVE_STDIO_H +#include +#endif + +#if APR_HAVE_SYS_TYPES_H +#include +#endif + +#if APR_HAVE_STDDEF_H +#include +#endif + +#if APR_HAVE_SYS_SOCKET_H +#include +#endif + +#if APR_HAVE_STDINT_H +#include +#endif + +#if APR_HAVE_SYS_WAIT_H +#include +#endif + +#if APR_HAVE_TIME_H +#include +#endif + +#if APR_HAVE_PROCESS_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @addtogroup apr_platform + * @ingroup APR + * @{ + */ + +#define APR_HAVE_SHMEM_MMAP_TMP 0 +#define APR_HAVE_SHMEM_MMAP_SHM 0 +#define APR_HAVE_SHMEM_MMAP_ZERO 0 +#define APR_HAVE_SHMEM_SHMGET_ANON 0 +#define APR_HAVE_SHMEM_SHMGET 0 +#define APR_HAVE_SHMEM_MMAP_ANON 0 +#define APR_HAVE_SHMEM_BEOS 0 + +#define APR_USE_SHMEM_MMAP_TMP 0 +#define APR_USE_SHMEM_MMAP_SHM 0 +#define APR_USE_SHMEM_MMAP_ZERO 0 +#define APR_USE_SHMEM_SHMGET_ANON 0 +#define APR_USE_SHMEM_SHMGET 0 +#define APR_USE_SHMEM_MMAP_ANON 0 +#define APR_USE_SHMEM_BEOS 0 + +#define APR_USE_FLOCK_SERIALIZE 0 +#define APR_USE_POSIXSEM_SERIALIZE 0 +#define APR_USE_SYSVSEM_SERIALIZE 0 +#define APR_USE_FCNTL_SERIALIZE 0 +#define APR_USE_PROC_PTHREAD_SERIALIZE 0 +#define APR_USE_PTHREAD_SERIALIZE 0 + +#define APR_HAS_FLOCK_SERIALIZE 0 +#define APR_HAS_SYSVSEM_SERIALIZE 0 +#define APR_HAS_POSIXSEM_SERIALIZE 0 +#define APR_HAS_FCNTL_SERIALIZE 0 +#define APR_HAS_PROC_PTHREAD_SERIALIZE 0 + +#define APR_PROCESS_LOCK_IS_GLOBAL 0 + +#define APR_HAVE_CORKABLE_TCP 0 +#define APR_HAVE_GETRLIMIT 0 +#define APR_HAVE_ICONV 0 +#define APR_HAVE_IN_ADDR 1 +#define APR_HAVE_INET_ADDR 1 +#define APR_HAVE_INET_NETWORK 0 +#define APR_HAVE_IPV6 1 +#define APR_HAVE_SOCKADDR_UN 0 +#define APR_HAVE_MEMMOVE 1 +#define APR_HAVE_SETRLIMIT 0 +#define APR_HAVE_SIGACTION 0 +#define APR_HAVE_SIGSUSPEND 0 +#define APR_HAVE_SIGWAIT 0 +#define APR_HAVE_SA_STORAGE 0 +#define APR_HAVE_STRCASECMP 0 +#define APR_HAVE_STRDUP 1 +#define APR_HAVE_STRNCASECMP 0 +#define APR_HAVE_STRSTR 1 +#define APR_HAVE_MEMCHR 1 +#define APR_HAVE_STRUCT_RLIMIT 0 +#define APR_HAVE_UNION_SEMUN 0 +#define APR_HAVE_SCTP 0 +#define APR_HAVE_IOVEC 0 + +#ifndef _WIN32_WCE +#define APR_HAVE_STRICMP 1 +#define APR_HAVE_STRNICMP 1 +#else +#define APR_HAVE_STRICMP 0 +#define APR_HAVE_STRNICMP 0 +#endif + +/* APR Feature Macros */ +#define APR_HAS_SHARED_MEMORY 1 +#define APR_HAS_THREADS 1 +#define APR_HAS_MMAP 1 +#define APR_HAS_FORK 0 +#define APR_HAS_RANDOM 1 +#define APR_HAS_OTHER_CHILD 1 +#define APR_HAS_DSO 1 +#define APR_HAS_SO_ACCEPTFILTER 0 +#define APR_HAS_UNICODE_FS 1 +#define APR_HAS_PROC_INVOKED 1 +#define APR_HAS_OS_UUID 1 +#define APR_HAS_TIMEDLOCKS 1 + +#ifndef _WIN32_WCE +#define APR_HAS_SENDFILE 1 +#define APR_HAS_USER 1 +#define APR_HAS_LARGE_FILES 1 +#define APR_HAS_XTHREAD_FILES 1 +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 1 +#else +#define APR_HAS_SENDFILE 0 +#define APR_HAS_USER 0 +#define APR_HAS_LARGE_FILES 0 +#define APR_HAS_XTHREAD_FILES 0 +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 0 +#endif + +/* APR sets APR_FILES_AS_SOCKETS to 1 on systems where it is possible + * to poll on files/pipes. + */ +#define APR_FILES_AS_SOCKETS 0 + +/* This macro indicates whether or not EBCDIC is the native character set. + */ +#define APR_CHARSET_EBCDIC 0 + +/* If we have a TCP implementation that can be "corked", what flag + * do we use? + */ +#define APR_TCP_NOPUSH_FLAG @apr_tcp_nopush_flag@ + +/* Is the TCP_NODELAY socket option inherited from listening sockets? + */ +#define APR_TCP_NODELAY_INHERITED 1 + +/* Is the O_NONBLOCK flag inherited from listening sockets? + */ +#define APR_O_NONBLOCK_INHERITED 1 + +/* Typedefs that APR needs. */ + +typedef unsigned char apr_byte_t; + +typedef short apr_int16_t; +typedef unsigned short apr_uint16_t; + +typedef int apr_int32_t; +typedef unsigned int apr_uint32_t; + +typedef __int64 apr_int64_t; +typedef unsigned __int64 apr_uint64_t; + +typedef size_t apr_size_t; +#if APR_HAVE_STDDEF_H +typedef ptrdiff_t apr_ssize_t; +#else +typedef int apr_ssize_t; +#endif +#if APR_HAS_LARGE_FILES +typedef __int64 apr_off_t; +#else +typedef int apr_off_t; +#endif +typedef int apr_socklen_t; +typedef apr_uint64_t apr_ino_t; + +#ifdef _WIN64 +#define APR_SIZEOF_VOIDP 8 +#else +#define APR_SIZEOF_VOIDP 4 +#endif + +#if APR_SIZEOF_VOIDP == 8 +typedef apr_uint64_t apr_uintptr_t; +#else +typedef apr_uint32_t apr_uintptr_t; +#endif + +/* Are we big endian? */ +/* XXX: Fatal assumption on Alpha platforms */ +#define APR_IS_BIGENDIAN 0 + +/* Mechanisms to properly type numeric literals */ + +#ifndef __GNUC__ +#define APR_INT64_C(val) (val##i64) +#define APR_UINT64_C(val) (val##Ui64) +#else +#define APR_INT64_C(val) (val##LL) +#define APR_UINT64_C(val) (val##ULL) +#endif + +#ifdef INT16_MIN +#define APR_INT16_MIN INT16_MIN +#else +#define APR_INT16_MIN (-0x7fff - 1) +#endif + +#ifdef INT16_MAX +#define APR_INT16_MAX INT16_MAX +#else +#define APR_INT16_MAX (0x7fff) +#endif + +#ifdef UINT16_MAX +#define APR_UINT16_MAX UINT16_MAX +#else +#define APR_UINT16_MAX (0xffff) +#endif + +#ifdef INT32_MIN +#define APR_INT32_MIN INT32_MIN +#else +#define APR_INT32_MIN (-0x7fffffff - 1) +#endif + +#ifdef INT32_MAX +#define APR_INT32_MAX INT32_MAX +#else +#define APR_INT32_MAX 0x7fffffff +#endif + +#ifdef UINT32_MAX +#define APR_UINT32_MAX UINT32_MAX +#else +#define APR_UINT32_MAX (0xffffffffU) +#endif + +#ifdef INT64_MIN +#define APR_INT64_MIN INT64_MIN +#else +#define APR_INT64_MIN (APR_INT64_C(-0x7fffffffffffffff) - 1) +#endif + +#ifdef INT64_MAX +#define APR_INT64_MAX INT64_MAX +#else +#define APR_INT64_MAX APR_INT64_C(0x7fffffffffffffff) +#endif + +#ifdef UINT64_MAX +#define APR_UINT64_MAX UINT64_MAX +#else +#define APR_UINT64_MAX APR_UINT64_C(0xffffffffffffffff) +#endif + +#define APR_SIZE_MAX (~((apr_size_t)0)) + +/* Definitions that APR programs need to work properly. */ + +/** + * APR public API wrap for C++ compilers. + */ +#ifdef __cplusplus +#define APR_BEGIN_DECLS extern "C" { +#define APR_END_DECLS } +#else +#define APR_BEGIN_DECLS +#define APR_END_DECLS +#endif + +/** + * Thread callbacks from APR functions must be declared with APR_THREAD_FUNC, + * so that they follow the platform's calling convention. + *
+ *
+ * void* APR_THREAD_FUNC my_thread_entry_fn(apr_thread_t *thd, void *data);
+ *
+ * 
+ */ +#define APR_THREAD_FUNC __stdcall + + +#if defined(DOXYGEN) || !defined(WIN32) + +/** + * The public APR functions are declared with APR_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APR_DECLARE_NONSTD(). + * + * @remark Both the declaration and implementations must use the same macro. + * + *
+ * APR_DECLARE(rettype) apr_func(args)
+ * 
+ * @see APR_DECLARE_NONSTD @see APR_DECLARE_DATA + * @remark Note that when APR compiles the library itself, it passes the + * symbol -DAPR_DECLARE_EXPORT to the compiler on some platforms (e.g. Win32) + * to export public symbols from the dynamic library build.\n + * The user must define the APR_DECLARE_STATIC when compiling to target + * the static APR library on some platforms (e.g. Win32.) The public symbols + * are neither exported nor imported when APR_DECLARE_STATIC is defined.\n + * By default, compiling an application and including the APR public + * headers, without defining APR_DECLARE_STATIC, will prepare the code to be + * linked to the dynamic library. + */ +#define APR_DECLARE(type) type + +/** + * The public APR functions using variable arguments are declared with + * APR_DECLARE_NONSTD(), as they must follow the C language calling convention. + * @see APR_DECLARE @see APR_DECLARE_DATA + * @remark Both the declaration and implementations must use the same macro. + *
+ *
+ * APR_DECLARE_NONSTD(rettype) apr_func(args, ...);
+ *
+ * 
+ */ +#define APR_DECLARE_NONSTD(type) type + +/** + * The public APR variables are declared with AP_MODULE_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * @see APR_DECLARE @see APR_DECLARE_NONSTD + * @remark Note that the declaration and implementations use different forms, + * but both must include the macro. + * + *
+ *
+ * extern APR_DECLARE_DATA type apr_variable;\n
+ * APR_DECLARE_DATA type apr_variable = value;
+ *
+ * 
+ */ +#define APR_DECLARE_DATA + +#elif defined(APR_DECLARE_STATIC) +#define APR_DECLARE(type) type __stdcall +#define APR_DECLARE_NONSTD(type) type __cdecl +#define APR_DECLARE_DATA +#elif defined(APR_DECLARE_EXPORT) +#define APR_DECLARE(type) __declspec(dllexport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllexport) +#else +#define APR_DECLARE(type) __declspec(dllimport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllimport) +#endif + +#ifdef _WIN64 +#define APR_SSIZE_T_FMT "I64d" +#define APR_SIZE_T_FMT "I64u" +#else +#define APR_SSIZE_T_FMT "d" +#define APR_SIZE_T_FMT "u" +#endif + +#if APR_HAS_LARGE_FILES +#define APR_OFF_T_FMT "I64d" +#else +#define APR_OFF_T_FMT "d" +#endif + +#define APR_PID_T_FMT "d" + +#define APR_INT64_T_FMT "I64d" +#define APR_UINT64_T_FMT "I64u" +#define APR_UINT64_T_HEX_FMT "I64x" + +/* No difference between PROC and GLOBAL mutex */ +#define APR_PROC_MUTEX_IS_GLOBAL 1 + +/* Local machine definition for console and log output. */ +#define APR_EOL_STR "\r\n" + +typedef int apr_wait_t; + +#if APR_HAS_UNICODE_FS +/* An arbitrary size that is digestable. True max is a bit less than 32000 */ +#define APR_PATH_MAX 8192 +#else /* !APR_HAS_UNICODE_FS */ +#define APR_PATH_MAX MAX_PATH +#endif + +#define APR_DSOPATH "PATH" + +/** @} */ + +/* Definitions that only Win32 programs need to compile properly. */ + +/* XXX These simply don't belong here, perhaps in apr_portable.h + * based on some APR_HAVE_PID/GID/UID? + */ +#ifndef __GNUC__ +typedef int pid_t; +#endif +typedef int uid_t; +typedef int gid_t; + +/* Win32 .h ommissions we really need */ +#define STDIN_FILENO 0 +#define STDOUT_FILENO 1 +#define STDERR_FILENO 2 + +#if APR_HAVE_IPV6 + +/* Appears in later flavors, not the originals. */ +#ifndef in_addr6 +#define in6_addr in_addr6 +#endif + +#ifndef WS2TCPIP_INLINE +#define IN6_IS_ADDR_V4MAPPED(a) \ + ( (*(const apr_uint64_t *)(const void *)(&(a)->s6_addr[0]) == 0) \ + && (*(const apr_uint32_t *)(const void *)(&(a)->s6_addr[8]) == ntohl(0x0000ffff))) +#endif + +#endif /* APR_HAVE_IPV6 */ + +#ifdef __cplusplus +} +#endif + +/* Done with badly written headers, leave 'deprecated CRT' undeprecated + */ +#if defined(_MSC_VER) && _MSC_VER >= 1200 +#pragma warning(pop) +#if _MSC_VER >= 1400 +#pragma warning(disable: 4996) +#endif +#endif + +#endif /* WIN32 */ + +#endif /* APR_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr.hwc b/c/dependencies/windows/apr/x86/include/apr.hwc new file mode 100644 index 00000000..ffb8368b --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr.hwc @@ -0,0 +1,664 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef APR_H +#define APR_H + +/* GENERATED FILE WARNING! DO NOT EDIT apr.h + * + * You must modify apr.hwc instead. + * + * And please, make an effort to stub apr.hnw and apr.h.in in the process. + * + * This is the Win32 specific version of apr.h. It is copied from + * apr.hw by the apr.dsp and libapr.dsp projects. + */ + +/** + * @file apr.h + * @brief APR Platform Definitions + * @remark This is a generated header generated from include/apr.h.in by + * ./configure, or copied from include/apr.hw or include/apr.hnw + * for Win32 or Netware by those build environments, respectively. + */ + +/* Make sure we have our platform identifier macro defined we ask for later. + */ +#if defined(_WIN32) && !defined(WIN32) +#define WIN32 1 +#endif + +#if defined(WIN32) || defined(DOXYGEN) + +/* Ignore most warnings (back down to /W3) for poorly constructed headers + */ +#if defined(_MSC_VER) && _MSC_VER >= 1200 +#pragma warning(push, 3) +#endif + +/* disable or reduce the frequency of... + * C4057: indirection to slightly different base types + * C4075: slight indirection changes (unsigned short* vs short[]) + * C4100: unreferenced formal parameter + * C4127: conditional expression is constant + * C4163: '_rotl64' : not available as an intrinsic function + * C4201: nonstandard extension nameless struct/unions + * C4244: int to char/short - precision loss + * C4514: unreferenced inline function removed + */ +#if defined(_MSC_VER) +#pragma warning(disable: 4100 4127 4163 4201 4514; once: 4057 4075 4244) +#endif + +/* Ignore Microsoft's interpretation of secure development + * and the POSIX string handling API + */ +#if defined(_MSC_VER) && _MSC_VER >= 1400 +#ifndef _CRT_SECURE_NO_DEPRECATE +#define _CRT_SECURE_NO_DEPRECATE +#endif +#pragma warning(disable: 4996) +#endif + +/* Has windows.h already been included? If so, our preferences don't matter, + * but we will still need the winsock things no matter what was included. + * If not, include a restricted set of windows headers to our tastes. + */ +#ifndef _WINDOWS_ +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef _WIN32_WINNT +#define _WIN32_WINNT @win32_winnt_str@ +#endif +#ifndef NOUSER +#define NOUSER +#endif +#ifndef NOMCX +#define NOMCX +#endif +#ifndef NOIME +#define NOIME +#endif +#include +/* + * Add a _very_few_ declarations missing from the restricted set of headers + * (If this list becomes extensive, re-enable the required headers above!) + * winsock headers were excluded by WIN32_LEAN_AND_MEAN, so include them now + */ +#define SW_HIDE 0 +#ifndef _WIN32_WCE +#include +#include +#include +#else +#include +#endif +#endif /* !_WINDOWS_ */ + +/** + * @defgroup APR Apache Portability Runtime library + * @{ + */ +/** + * @defgroup apr_platform Platform Definitions + * @{ + * @warning + * The actual values of macros and typedefs on this page
+ * are platform specific and should NOT be relied upon!
+ */ + +#define APR_INLINE __inline +#define APR_HAS_INLINE 1 +#if !defined(__GNUC__) && !defined(__attribute__) +#define __attribute__(__x) +#endif + +#ifndef _WIN32_WCE +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_CONIO_H 1 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 1 +#define APR_HAVE_DIRENT_H 0 +#define APR_HAVE_ERRNO_H 1 +#define APR_HAVE_FCNTL_H 1 +#define APR_HAVE_IO_H 1 +#define APR_HAVE_LIMITS_H 1 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SEMAPHORE_H 0 +#define APR_HAVE_SIGNAL_H 1 +#define APR_HAVE_STDARG_H 1 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_SYS_IOCTL_H 0 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SIGNAL_H 0 +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#define APR_HAVE_SYS_TIME_H 0 +#define APR_HAVE_SYS_TYPES_H 1 +#define APR_HAVE_SYS_UIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#define APR_HAVE_SYS_WAIT_H 0 +#define APR_HAVE_TIME_H 1 +#define APR_HAVE_UNISTD_H 0 +#define APR_HAVE_STDDEF_H 1 +#define APR_HAVE_PROCESS_H 1 +#else +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_CONIO_H 0 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 0 +#define APR_HAVE_DIRENT_H 0 +#define APR_HAVE_ERRNO_H 0 +#define APR_HAVE_FCNTL_H 0 +#define APR_HAVE_IO_H 0 +#define APR_HAVE_LIMITS_H 0 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SEMAPHORE_H 0 +#define APR_HAVE_SIGNAL_H 0 +#define APR_HAVE_STDARG_H 0 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_SYS_IOCTL_H 0 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SIGNAL_H 0 +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#define APR_HAVE_SYS_TIME_H 0 +#define APR_HAVE_SYS_TYPES_H 0 +#define APR_HAVE_SYS_UIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#define APR_HAVE_SYS_WAIT_H 0 +#define APR_HAVE_TIME_H 0 +#define APR_HAVE_UNISTD_H 0 +#define APR_HAVE_STDDEF_H 0 +#define APR_HAVE_PROCESS_H 0 +#endif + +/** @} */ +/** @} */ + +/* We don't include our conditional headers within the doxyblocks + * or the extern "C" namespace + */ + +#if APR_HAVE_STDLIB_H +#include +#endif + +#if APR_HAVE_STDIO_H +#include +#endif + +#if APR_HAVE_SYS_TYPES_H +#include +#endif + +#if APR_HAVE_STDDEF_H +#include +#endif + +#if APR_HAVE_SYS_SOCKET_H +#include +#endif + +#if APR_HAVE_STDINT_H +#include +#endif + +#if APR_HAVE_SYS_WAIT_H +#include +#endif + +#if APR_HAVE_TIME_H +#include +#endif + +#if APR_HAVE_PROCESS_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @addtogroup apr_platform + * @ingroup APR + * @{ + */ + +#define APR_HAVE_SHMEM_MMAP_TMP 0 +#define APR_HAVE_SHMEM_MMAP_SHM 0 +#define APR_HAVE_SHMEM_MMAP_ZERO 0 +#define APR_HAVE_SHMEM_SHMGET_ANON 0 +#define APR_HAVE_SHMEM_SHMGET 0 +#define APR_HAVE_SHMEM_MMAP_ANON 0 +#define APR_HAVE_SHMEM_BEOS 0 + +#define APR_USE_SHMEM_MMAP_TMP 0 +#define APR_USE_SHMEM_MMAP_SHM 0 +#define APR_USE_SHMEM_MMAP_ZERO 0 +#define APR_USE_SHMEM_SHMGET_ANON 0 +#define APR_USE_SHMEM_SHMGET 0 +#define APR_USE_SHMEM_MMAP_ANON 0 +#define APR_USE_SHMEM_BEOS 0 + +#define APR_USE_FLOCK_SERIALIZE 0 +#define APR_USE_POSIXSEM_SERIALIZE 0 +#define APR_USE_SYSVSEM_SERIALIZE 0 +#define APR_USE_FCNTL_SERIALIZE 0 +#define APR_USE_PROC_PTHREAD_SERIALIZE 0 +#define APR_USE_PTHREAD_SERIALIZE 0 + +#define APR_HAS_FLOCK_SERIALIZE 0 +#define APR_HAS_SYSVSEM_SERIALIZE 0 +#define APR_HAS_POSIXSEM_SERIALIZE 0 +#define APR_HAS_FCNTL_SERIALIZE 0 +#define APR_HAS_PROC_PTHREAD_SERIALIZE 0 + +#define APR_PROCESS_LOCK_IS_GLOBAL 0 + +#define APR_HAVE_CORKABLE_TCP 0 +#define APR_HAVE_GETRLIMIT 0 +#define APR_HAVE_ICONV 0 +#define APR_HAVE_IN_ADDR 1 +#define APR_HAVE_INET_ADDR 1 +#define APR_HAVE_INET_NETWORK 0 +#define APR_HAVE_IPV6 @apr_have_ipv6_10@ +#define APR_HAVE_SOCKADDR_UN 0 +#define APR_HAVE_MEMMOVE 1 +#define APR_HAVE_SETRLIMIT 0 +#define APR_HAVE_SIGACTION 0 +#define APR_HAVE_SIGSUSPEND 0 +#define APR_HAVE_SIGWAIT 0 +#define APR_HAVE_SA_STORAGE 0 +#define APR_HAVE_STRCASECMP 0 +#define APR_HAVE_STRDUP 1 +#define APR_HAVE_STRNCASECMP 0 +#define APR_HAVE_STRSTR 1 +#define APR_HAVE_MEMCHR 1 +#define APR_HAVE_STRUCT_RLIMIT 0 +#define APR_HAVE_UNION_SEMUN 0 +#define APR_HAVE_SCTP 0 +#define APR_HAVE_IOVEC 0 + +#ifndef _WIN32_WCE +#define APR_HAVE_STRICMP 1 +#define APR_HAVE_STRNICMP 1 +#else +#define APR_HAVE_STRICMP 0 +#define APR_HAVE_STRNICMP 0 +#endif + +/* APR Feature Macros */ +#define APR_HAS_SHARED_MEMORY 1 +#define APR_HAS_THREADS 1 +#define APR_HAS_MMAP 1 +#define APR_HAS_FORK 0 +#define APR_HAS_RANDOM 1 +#define APR_HAS_OTHER_CHILD 1 +#define APR_HAS_DSO 1 +#define APR_HAS_SO_ACCEPTFILTER 0 +#define APR_HAS_UNICODE_FS 1 +#define APR_HAS_PROC_INVOKED 1 +#define APR_HAS_OS_UUID 1 +#define APR_HAS_TIMEDLOCKS 1 + +#ifndef _WIN32_WCE +#define APR_HAS_SENDFILE 1 +#define APR_HAS_USER 1 +#define APR_HAS_LARGE_FILES 1 +#define APR_HAS_XTHREAD_FILES 1 +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 1 +#else +#define APR_HAS_SENDFILE 0 +#define APR_HAS_USER 0 +#define APR_HAS_LARGE_FILES 0 +#define APR_HAS_XTHREAD_FILES 0 +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 0 +#endif + +/* APR sets APR_FILES_AS_SOCKETS to 1 on systems where it is possible + * to poll on files/pipes. + */ +#define APR_FILES_AS_SOCKETS 0 + +/* This macro indicates whether or not EBCDIC is the native character set. + */ +#define APR_CHARSET_EBCDIC 0 + +/* If we have a TCP implementation that can be "corked", what flag + * do we use? + */ +#define APR_TCP_NOPUSH_FLAG @apr_tcp_nopush_flag@ + +/* Is the TCP_NODELAY socket option inherited from listening sockets? + */ +#define APR_TCP_NODELAY_INHERITED 1 + +/* Is the O_NONBLOCK flag inherited from listening sockets? + */ +#define APR_O_NONBLOCK_INHERITED 1 + +/* Typedefs that APR needs. */ + +typedef unsigned char apr_byte_t; + +typedef short apr_int16_t; +typedef unsigned short apr_uint16_t; + +typedef int apr_int32_t; +typedef unsigned int apr_uint32_t; + +typedef __int64 apr_int64_t; +typedef unsigned __int64 apr_uint64_t; + +typedef size_t apr_size_t; +#if APR_HAVE_STDDEF_H +typedef ptrdiff_t apr_ssize_t; +#else +typedef int apr_ssize_t; +#endif +#if APR_HAS_LARGE_FILES +typedef __int64 apr_off_t; +#else +typedef int apr_off_t; +#endif +typedef int apr_socklen_t; +typedef apr_uint64_t apr_ino_t; + +#ifdef _WIN64 +#define APR_SIZEOF_VOIDP 8 +#else +#define APR_SIZEOF_VOIDP 4 +#endif + +#if APR_SIZEOF_VOIDP == 8 +typedef apr_uint64_t apr_uintptr_t; +#else +typedef apr_uint32_t apr_uintptr_t; +#endif + +/* Are we big endian? */ +/* XXX: Fatal assumption on Alpha platforms */ +#define APR_IS_BIGENDIAN 0 + +/* Mechanisms to properly type numeric literals */ + +#ifndef __GNUC__ +#define APR_INT64_C(val) (val##i64) +#define APR_UINT64_C(val) (val##Ui64) +#else +#define APR_INT64_C(val) (val##LL) +#define APR_UINT64_C(val) (val##ULL) +#endif + +#ifdef INT16_MIN +#define APR_INT16_MIN INT16_MIN +#else +#define APR_INT16_MIN (-0x7fff - 1) +#endif + +#ifdef INT16_MAX +#define APR_INT16_MAX INT16_MAX +#else +#define APR_INT16_MAX (0x7fff) +#endif + +#ifdef UINT16_MAX +#define APR_UINT16_MAX UINT16_MAX +#else +#define APR_UINT16_MAX (0xffff) +#endif + +#ifdef INT32_MIN +#define APR_INT32_MIN INT32_MIN +#else +#define APR_INT32_MIN (-0x7fffffff - 1) +#endif + +#ifdef INT32_MAX +#define APR_INT32_MAX INT32_MAX +#else +#define APR_INT32_MAX 0x7fffffff +#endif + +#ifdef UINT32_MAX +#define APR_UINT32_MAX UINT32_MAX +#else +#define APR_UINT32_MAX (0xffffffffU) +#endif + +#ifdef INT64_MIN +#define APR_INT64_MIN INT64_MIN +#else +#define APR_INT64_MIN (APR_INT64_C(-0x7fffffffffffffff) - 1) +#endif + +#ifdef INT64_MAX +#define APR_INT64_MAX INT64_MAX +#else +#define APR_INT64_MAX APR_INT64_C(0x7fffffffffffffff) +#endif + +#ifdef UINT64_MAX +#define APR_UINT64_MAX UINT64_MAX +#else +#define APR_UINT64_MAX APR_UINT64_C(0xffffffffffffffff) +#endif + +#define APR_SIZE_MAX (~((apr_size_t)0)) + +/* Definitions that APR programs need to work properly. */ + +/** + * APR public API wrap for C++ compilers. + */ +#ifdef __cplusplus +#define APR_BEGIN_DECLS extern "C" { +#define APR_END_DECLS } +#else +#define APR_BEGIN_DECLS +#define APR_END_DECLS +#endif + +/** + * Thread callbacks from APR functions must be declared with APR_THREAD_FUNC, + * so that they follow the platform's calling convention. + *
+ *
+ * void* APR_THREAD_FUNC my_thread_entry_fn(apr_thread_t *thd, void *data);
+ *
+ * 
+ */ +#define APR_THREAD_FUNC __stdcall + + +#if defined(DOXYGEN) || !defined(WIN32) + +/** + * The public APR functions are declared with APR_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APR_DECLARE_NONSTD(). + * + * @remark Both the declaration and implementations must use the same macro. + * + *
+ * APR_DECLARE(rettype) apr_func(args)
+ * 
+ * @see APR_DECLARE_NONSTD @see APR_DECLARE_DATA + * @remark Note that when APR compiles the library itself, it passes the + * symbol -DAPR_DECLARE_EXPORT to the compiler on some platforms (e.g. Win32) + * to export public symbols from the dynamic library build.\n + * The user must define the APR_DECLARE_STATIC when compiling to target + * the static APR library on some platforms (e.g. Win32.) The public symbols + * are neither exported nor imported when APR_DECLARE_STATIC is defined.\n + * By default, compiling an application and including the APR public + * headers, without defining APR_DECLARE_STATIC, will prepare the code to be + * linked to the dynamic library. + */ +#define APR_DECLARE(type) type + +/** + * The public APR functions using variable arguments are declared with + * APR_DECLARE_NONSTD(), as they must follow the C language calling convention. + * @see APR_DECLARE @see APR_DECLARE_DATA + * @remark Both the declaration and implementations must use the same macro. + *
+ *
+ * APR_DECLARE_NONSTD(rettype) apr_func(args, ...);
+ *
+ * 
+ */ +#define APR_DECLARE_NONSTD(type) type + +/** + * The public APR variables are declared with AP_MODULE_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * @see APR_DECLARE @see APR_DECLARE_NONSTD + * @remark Note that the declaration and implementations use different forms, + * but both must include the macro. + * + *
+ *
+ * extern APR_DECLARE_DATA type apr_variable;\n
+ * APR_DECLARE_DATA type apr_variable = value;
+ *
+ * 
+ */ +#define APR_DECLARE_DATA + +#elif defined(APR_DECLARE_STATIC) +#define APR_DECLARE(type) type __stdcall +#define APR_DECLARE_NONSTD(type) type __cdecl +#define APR_DECLARE_DATA +#elif defined(APR_DECLARE_EXPORT) +#define APR_DECLARE(type) __declspec(dllexport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllexport) +#else +#define APR_DECLARE(type) __declspec(dllimport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllimport) +#endif + +#ifdef _WIN64 +#define APR_SSIZE_T_FMT "I64d" +#define APR_SIZE_T_FMT "I64u" +#else +#define APR_SSIZE_T_FMT "d" +#define APR_SIZE_T_FMT "u" +#endif + +#if APR_HAS_LARGE_FILES +#define APR_OFF_T_FMT "I64d" +#else +#define APR_OFF_T_FMT "d" +#endif + +#define APR_PID_T_FMT "d" + +#define APR_INT64_T_FMT "I64d" +#define APR_UINT64_T_FMT "I64u" +#define APR_UINT64_T_HEX_FMT "I64x" + +/* No difference between PROC and GLOBAL mutex */ +#define APR_PROC_MUTEX_IS_GLOBAL 1 + +/* Local machine definition for console and log output. */ +#define APR_EOL_STR "\r\n" + +typedef int apr_wait_t; + +#if APR_HAS_UNICODE_FS +/* An arbitrary size that is digestable. True max is a bit less than 32000 */ +#define APR_PATH_MAX 8192 +#else /* !APR_HAS_UNICODE_FS */ +#define APR_PATH_MAX MAX_PATH +#endif + +#define APR_DSOPATH "PATH" + +/** @} */ + +/* Definitions that only Win32 programs need to compile properly. */ + +/* XXX These simply don't belong here, perhaps in apr_portable.h + * based on some APR_HAVE_PID/GID/UID? + */ +#ifndef __GNUC__ +typedef int pid_t; +#endif +typedef int uid_t; +typedef int gid_t; + +/* Win32 .h ommissions we really need */ +#define STDIN_FILENO 0 +#define STDOUT_FILENO 1 +#define STDERR_FILENO 2 + +#if APR_HAVE_IPV6 + +/* Appears in later flavors, not the originals. */ +#ifndef in_addr6 +#define in6_addr in_addr6 +#endif + +#ifndef WS2TCPIP_INLINE +#define IN6_IS_ADDR_V4MAPPED(a) \ + ( (*(const apr_uint64_t *)(const void *)(&(a)->s6_addr[0]) == 0) \ + && (*(const apr_uint32_t *)(const void *)(&(a)->s6_addr[8]) == ntohl(0x0000ffff))) +#endif + +#endif /* APR_HAVE_IPV6 */ + +#ifdef __cplusplus +} +#endif + +/* Done with badly written headers, leave 'deprecated CRT' undeprecated + */ +#if defined(_MSC_VER) && _MSC_VER >= 1200 +#pragma warning(pop) +#if _MSC_VER >= 1400 +#pragma warning(disable: 4996) +#endif +#endif + +#endif /* WIN32 */ + +#endif /* APR_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_allocator.h b/c/dependencies/windows/apr/x86/include/apr_allocator.h new file mode 100644 index 00000000..be05d0e4 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_allocator.h @@ -0,0 +1,179 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ALLOCATOR_H +#define APR_ALLOCATOR_H + +/** + * @file apr_allocator.h + * @brief APR Internal Memory Allocation + */ + +#include "apr.h" +#include "apr_errno.h" +#define APR_WANT_MEMFUNC /**< For no good reason? */ +#include "apr_want.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_allocator Internal Memory Allocation + * @ingroup APR + * @{ + */ + +/** the allocator structure */ +typedef struct apr_allocator_t apr_allocator_t; +/** the structure which holds information about the allocation */ +typedef struct apr_memnode_t apr_memnode_t; + +/** basic memory node structure + * @note The next, ref and first_avail fields are available for use by the + * caller of apr_allocator_alloc(), the remaining fields are read-only. + * The next field has to be used with caution and sensibly set when the + * memnode is passed back to apr_allocator_free(). See apr_allocator_free() + * for details. + * The ref and first_avail fields will be properly restored by + * apr_allocator_free(). + */ +struct apr_memnode_t { + apr_memnode_t *next; /**< next memnode */ + apr_memnode_t **ref; /**< reference to self */ + apr_uint32_t index; /**< size */ + apr_uint32_t free_index; /**< how much free */ + char *first_avail; /**< pointer to first free memory */ + char *endp; /**< pointer to end of free memory */ +}; + +/** The base size of a memory node - aligned. */ +#define APR_MEMNODE_T_SIZE APR_ALIGN_DEFAULT(sizeof(apr_memnode_t)) + +/** Symbolic constants */ +#define APR_ALLOCATOR_MAX_FREE_UNLIMITED 0 + +/** + * Create a new allocator + * @param allocator The allocator we have just created. + * + */ +APR_DECLARE(apr_status_t) apr_allocator_create(apr_allocator_t **allocator) + __attribute__((nonnull(1))); + +/** + * Destroy an allocator + * @param allocator The allocator to be destroyed + * @remark Any memnodes not given back to the allocator prior to destroying + * will _not_ be free()d. + */ +APR_DECLARE(void) apr_allocator_destroy(apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +/** + * Allocate a block of mem from the allocator + * @param allocator The allocator to allocate from + * @param size The size of the mem to allocate (excluding the + * memnode structure) + */ +APR_DECLARE(apr_memnode_t *) apr_allocator_alloc(apr_allocator_t *allocator, + apr_size_t size) + __attribute__((nonnull(1))); + +/** + * Free a list of blocks of mem, giving them back to the allocator. + * The list is typically terminated by a memnode with its next field + * set to NULL. + * @param allocator The allocator to give the mem back to + * @param memnode The memory node to return + */ +APR_DECLARE(void) apr_allocator_free(apr_allocator_t *allocator, + apr_memnode_t *memnode) + __attribute__((nonnull(1,2))); + +/** + * Get the true size that would be allocated for the given size (including + * the header and alignment). + * @param allocator The allocator from which to the memory would be allocated + * @param size The size to align + * @return The aligned size (or zero on apr_size_t overflow) + */ +APR_DECLARE(apr_size_t) apr_allocator_align(apr_allocator_t *allocator, + apr_size_t size); + +#include "apr_pools.h" + +/** + * Set the owner of the allocator + * @param allocator The allocator to set the owner for + * @param pool The pool that is to own the allocator + * @remark Typically pool is the highest level pool using the allocator + */ +/* + * XXX: see if we can come up with something a bit better. Currently + * you can make a pool an owner, but if the pool doesn't use the allocator + * the allocator will never be destroyed. + */ +APR_DECLARE(void) apr_allocator_owner_set(apr_allocator_t *allocator, + apr_pool_t *pool) + __attribute__((nonnull(1))); + +/** + * Get the current owner of the allocator + * @param allocator The allocator to get the owner from + */ +APR_DECLARE(apr_pool_t *) apr_allocator_owner_get(apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +/** + * Set the current threshold at which the allocator should start + * giving blocks back to the system. + * @param allocator The allocator to set the threshold on + * @param size The threshold. 0 == unlimited. + */ +APR_DECLARE(void) apr_allocator_max_free_set(apr_allocator_t *allocator, + apr_size_t size) + __attribute__((nonnull(1))); + +#include "apr_thread_mutex.h" + +#if APR_HAS_THREADS +/** + * Set a mutex for the allocator to use + * @param allocator The allocator to set the mutex for + * @param mutex The mutex + */ +APR_DECLARE(void) apr_allocator_mutex_set(apr_allocator_t *allocator, + apr_thread_mutex_t *mutex) + __attribute__((nonnull(1))); + +/** + * Get the mutex currently set for the allocator + * @param allocator The allocator + */ +APR_DECLARE(apr_thread_mutex_t *) apr_allocator_mutex_get( + apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ALLOCATOR_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_anylock.h b/c/dependencies/windows/apr/x86/include/apr_anylock.h new file mode 100644 index 00000000..51e97ff3 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_anylock.h @@ -0,0 +1,128 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_anylock.h + * @brief APR-Util transparent any lock flavor wrapper + */ +#ifndef APR_ANYLOCK_H +#define APR_ANYLOCK_H + +#include "apr_proc_mutex.h" +#include "apr_thread_mutex.h" +#include "apr_thread_rwlock.h" + +/** Structure that may contain any APR lock type */ +typedef struct apr_anylock_t { + /** Indicates what type of lock is in lock */ + enum tm_lock { + apr_anylock_none, /**< None */ + apr_anylock_procmutex, /**< Process-based */ + apr_anylock_threadmutex, /**< Thread-based */ + apr_anylock_readlock, /**< Read lock */ + apr_anylock_writelock /**< Write lock */ + } type; + /** Union of all possible APR locks */ + union apr_anylock_u_t { + apr_proc_mutex_t *pm; /**< Process mutex */ +#if APR_HAS_THREADS + apr_thread_mutex_t *tm; /**< Thread mutex */ + apr_thread_rwlock_t *rw; /**< Read-write lock */ +#endif + } lock; +} apr_anylock_t; + +#if APR_HAS_THREADS + +/** Lock an apr_anylock_t structure */ +#define APR_ANYLOCK_LOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_threadmutex) \ + ? apr_thread_mutex_lock((lck)->lock.tm) \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_lock((lck)->lock.pm) \ + : (((lck)->type == apr_anylock_readlock) \ + ? apr_thread_rwlock_rdlock((lck)->lock.rw) \ + : (((lck)->type == apr_anylock_writelock) \ + ? apr_thread_rwlock_wrlock((lck)->lock.rw) \ + : APR_EINVAL))))) + +#else /* APR_HAS_THREADS */ + +#define APR_ANYLOCK_LOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_lock((lck)->lock.pm) \ + : APR_EINVAL)) + +#endif /* APR_HAS_THREADS */ + +#if APR_HAS_THREADS + +/** Try to lock an apr_anylock_t structure */ +#define APR_ANYLOCK_TRYLOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_threadmutex) \ + ? apr_thread_mutex_trylock((lck)->lock.tm) \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_trylock((lck)->lock.pm) \ + : (((lck)->type == apr_anylock_readlock) \ + ? apr_thread_rwlock_tryrdlock((lck)->lock.rw) \ + : (((lck)->type == apr_anylock_writelock) \ + ? apr_thread_rwlock_trywrlock((lck)->lock.rw) \ + : APR_EINVAL))))) + +#else /* APR_HAS_THREADS */ + +#define APR_ANYLOCK_TRYLOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_trylock((lck)->lock.pm) \ + : APR_EINVAL)) + +#endif /* APR_HAS_THREADS */ + +#if APR_HAS_THREADS + +/** Unlock an apr_anylock_t structure */ +#define APR_ANYLOCK_UNLOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_threadmutex) \ + ? apr_thread_mutex_unlock((lck)->lock.tm) \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_unlock((lck)->lock.pm) \ + : ((((lck)->type == apr_anylock_readlock) || \ + ((lck)->type == apr_anylock_writelock)) \ + ? apr_thread_rwlock_unlock((lck)->lock.rw) \ + : APR_EINVAL)))) + +#else /* APR_HAS_THREADS */ + +#define APR_ANYLOCK_UNLOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_unlock((lck)->lock.pm) \ + : APR_EINVAL)) + +#endif /* APR_HAS_THREADS */ + +#endif /* !APR_ANYLOCK_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_atomic.h b/c/dependencies/windows/apr/x86/include/apr_atomic.h new file mode 100644 index 00000000..3d203edc --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_atomic.h @@ -0,0 +1,207 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ATOMIC_H +#define APR_ATOMIC_H + +/** + * @file apr_atomic.h + * @brief APR Atomic Operations + */ + +#include "apr.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_atomic Atomic Operations + * @ingroup APR + * @{ + */ + +/** + * this function is required on some platforms to initialize the + * atomic operation's internal structures + * @param p pool + * @return APR_SUCCESS on successful completion + * @remark Programs do NOT need to call this directly. APR will call this + * automatically from apr_initialize(). + * @internal + */ +APR_DECLARE(apr_status_t) apr_atomic_init(apr_pool_t *p); + +/* + * Atomic operations on 32-bit values + * Note: Each of these functions internally implements a memory barrier + * on platforms that require it + */ + +/** + * atomically read an apr_uint32_t from memory + * @param mem the pointer + */ +APR_DECLARE(apr_uint32_t) apr_atomic_read32(volatile apr_uint32_t *mem); + +/** + * atomically set an apr_uint32_t in memory + * @param mem pointer to the object + * @param val value that the object will assume + */ +APR_DECLARE(void) apr_atomic_set32(volatile apr_uint32_t *mem, apr_uint32_t val); + +/** + * atomically add 'val' to an apr_uint32_t + * @param mem pointer to the object + * @param val amount to add + * @return old value pointed to by mem + */ +APR_DECLARE(apr_uint32_t) apr_atomic_add32(volatile apr_uint32_t *mem, apr_uint32_t val); + +/** + * atomically subtract 'val' from an apr_uint32_t + * @param mem pointer to the object + * @param val amount to subtract + */ +APR_DECLARE(void) apr_atomic_sub32(volatile apr_uint32_t *mem, apr_uint32_t val); + +/** + * atomically increment an apr_uint32_t by 1 + * @param mem pointer to the object + * @return old value pointed to by mem + */ +APR_DECLARE(apr_uint32_t) apr_atomic_inc32(volatile apr_uint32_t *mem); + +/** + * atomically decrement an apr_uint32_t by 1 + * @param mem pointer to the atomic value + * @return zero if the value becomes zero on decrement, otherwise non-zero + */ +APR_DECLARE(int) apr_atomic_dec32(volatile apr_uint32_t *mem); + +/** + * compare an apr_uint32_t's value with 'cmp'. + * If they are the same swap the value with 'with' + * @param mem pointer to the value + * @param with what to swap it with + * @param cmp the value to compare it to + * @return the old value of *mem + */ +APR_DECLARE(apr_uint32_t) apr_atomic_cas32(volatile apr_uint32_t *mem, apr_uint32_t with, + apr_uint32_t cmp); + +/** + * exchange an apr_uint32_t's value with 'val'. + * @param mem pointer to the value + * @param val what to swap it with + * @return the old value of *mem + */ +APR_DECLARE(apr_uint32_t) apr_atomic_xchg32(volatile apr_uint32_t *mem, apr_uint32_t val); + +/* + * Atomic operations on 64-bit values + * Note: Each of these functions internally implements a memory barrier + * on platforms that require it + */ + +/** + * atomically read an apr_uint64_t from memory + * @param mem the pointer + */ +APR_DECLARE(apr_uint64_t) apr_atomic_read64(volatile apr_uint64_t *mem); + +/** + * atomically set an apr_uint64_t in memory + * @param mem pointer to the object + * @param val value that the object will assume + */ +APR_DECLARE(void) apr_atomic_set64(volatile apr_uint64_t *mem, apr_uint64_t val); + +/** + * atomically add 'val' to an apr_uint64_t + * @param mem pointer to the object + * @param val amount to add + * @return old value pointed to by mem + */ +APR_DECLARE(apr_uint64_t) apr_atomic_add64(volatile apr_uint64_t *mem, apr_uint64_t val); + +/** + * atomically subtract 'val' from an apr_uint64_t + * @param mem pointer to the object + * @param val amount to subtract + */ +APR_DECLARE(void) apr_atomic_sub64(volatile apr_uint64_t *mem, apr_uint64_t val); + +/** + * atomically increment an apr_uint64_t by 1 + * @param mem pointer to the object + * @return old value pointed to by mem + */ +APR_DECLARE(apr_uint64_t) apr_atomic_inc64(volatile apr_uint64_t *mem); + +/** + * atomically decrement an apr_uint64_t by 1 + * @param mem pointer to the atomic value + * @return zero if the value becomes zero on decrement, otherwise non-zero + */ +APR_DECLARE(int) apr_atomic_dec64(volatile apr_uint64_t *mem); + +/** + * compare an apr_uint64_t's value with 'cmp'. + * If they are the same swap the value with 'with' + * @param mem pointer to the value + * @param with what to swap it with + * @param cmp the value to compare it to + * @return the old value of *mem + */ +APR_DECLARE(apr_uint64_t) apr_atomic_cas64(volatile apr_uint64_t *mem, apr_uint64_t with, + apr_uint64_t cmp); + +/** + * exchange an apr_uint64_t's value with 'val'. + * @param mem pointer to the value + * @param val what to swap it with + * @return the old value of *mem + */ +APR_DECLARE(apr_uint64_t) apr_atomic_xchg64(volatile apr_uint64_t *mem, apr_uint64_t val); + +/** + * compare the pointer's value with cmp. + * If they are the same swap the value with 'with' + * @param mem pointer to the pointer + * @param with what to swap it with + * @param cmp the value to compare it to + * @return the old value of the pointer + */ +APR_DECLARE(void*) apr_atomic_casptr(volatile void **mem, void *with, const void *cmp); + +/** + * exchange a pair of pointer values + * @param mem pointer to the pointer + * @param with what to swap it with + * @return the old value of the pointer + */ +APR_DECLARE(void*) apr_atomic_xchgptr(volatile void **mem, void *with); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ATOMIC_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_base64.h b/c/dependencies/windows/apr/x86/include/apr_base64.h new file mode 100644 index 00000000..17de1c58 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_base64.h @@ -0,0 +1,113 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * The apr_vsnprintf/apr_snprintf functions are based on, and used with the + * permission of, the SIO stdio-replacement strx_* functions by Panos + * Tsirigotis for xinetd. + */ + +/** + * @file apr_base64.h + * @brief APR-UTIL Base64 Encoding + */ +#ifndef APR_BASE64_H +#define APR_BASE64_H + +#include "apu.h" +#include "apr_general.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Base64 Base64 Encoding + * @ingroup APR_Util + * @{ + */ + +/* Simple BASE64 encode/decode functions. + * + * As we might encode binary strings, hence we require the length of + * the incoming plain source. And return the length of what we decoded. + * + * The decoding function takes any non valid char (i.e. whitespace, \0 + * or anything non A-Z,0-9 etc as terminal. + * + * plain strings/binary sequences are not assumed '\0' terminated. Encoded + * strings are neither. But probably should. + * + */ + +/** + * Given the length of an un-encoded string, get the length of the + * encoded string. + * @param len the length of an unencoded string. + * @return the length of the string after it is encoded, including the + * trailing \0 + */ +APU_DECLARE(int) apr_base64_encode_len(int len); + +/** + * Encode a text string using base64encoding. + * @param coded_dst The destination string for the encoded string. + * @param plain_src The original string in plain text + * @param len_plain_src The length of the plain text string + * @return the length of the encoded string + */ +APU_DECLARE(int) apr_base64_encode(char * coded_dst, const char *plain_src, + int len_plain_src); + +/** + * Encode an EBCDIC string using base64encoding. + * @param coded_dst The destination string for the encoded string. + * @param plain_src The original string in plain text + * @param len_plain_src The length of the plain text string + * @return the length of the encoded string + */ +APU_DECLARE(int) apr_base64_encode_binary(char * coded_dst, + const unsigned char *plain_src, + int len_plain_src); + +/** + * Determine the maximum buffer length required to decode the plain text + * string given the encoded string. + * @param coded_src The encoded string + * @return the maximum required buffer length for the plain text string + */ +APU_DECLARE(int) apr_base64_decode_len(const char * coded_src); + +/** + * Decode a string to plain text + * @param plain_dst The destination string for the plain text + * @param coded_src The encoded string + * @return the length of the plain text string + */ +APU_DECLARE(int) apr_base64_decode(char * plain_dst, const char *coded_src); + +/** + * Decode an EBCDIC string to plain text + * @param plain_dst The destination string for the plain text + * @param coded_src The encoded string + * @return the length of the plain text string + */ +APU_DECLARE(int) apr_base64_decode_binary(unsigned char * plain_dst, + const char *coded_src); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_BASE64_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_buckets.h b/c/dependencies/windows/apr/x86/include/apr_buckets.h new file mode 100644 index 00000000..ce64b78d --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_buckets.h @@ -0,0 +1,1598 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file apr_buckets.h + * @brief APR-UTIL Buckets/Bucket Brigades + */ + +#ifndef APR_BUCKETS_H +#define APR_BUCKETS_H + +#if defined(APR_BUCKET_DEBUG) && !defined(APR_RING_DEBUG) +#define APR_RING_DEBUG +#endif + +#include "apu.h" +#include "apr_network_io.h" +#include "apr_file_io.h" +#include "apr_general.h" +#include "apr_mmap.h" +#include "apr_errno.h" +#include "apr_ring.h" +#include "apr.h" +#if APR_HAVE_SYS_UIO_H +#include /* for struct iovec */ +#endif +#if APR_HAVE_STDARG_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Bucket_Brigades Bucket Brigades + * @ingroup APR_Util + * @{ + */ + +/** default bucket buffer size - 8KB minus room for memory allocator headers */ +#define APR_BUCKET_BUFF_SIZE 8000 + +/** Determines how a bucket or brigade should be read */ +typedef enum { + APR_BLOCK_READ, /**< block until data becomes available */ + APR_NONBLOCK_READ /**< return immediately if no data is available */ +} apr_read_type_e; + +/** + * The one-sentence buzzword-laden overview: Bucket brigades represent + * a complex data stream that can be passed through a layered IO + * system without unnecessary copying. A longer overview follows... + * + * A bucket brigade is a doubly linked list (ring) of buckets, so we + * aren't limited to inserting at the front and removing at the end. + * Buckets are only passed around as members of a brigade, although + * singleton buckets can occur for short periods of time. + * + * Buckets are data stores of various types. They can refer to data in + * memory, or part of a file or mmap area, or the output of a process, + * etc. Buckets also have some type-dependent accessor functions: + * read, split, copy, setaside, and destroy. + * + * read returns the address and size of the data in the bucket. If the + * data isn't in memory then it is read in and the bucket changes type + * so that it can refer to the new location of the data. If all the + * data doesn't fit in the bucket then a new bucket is inserted into + * the brigade to hold the rest of it. + * + * split divides the data in a bucket into two regions. After a split + * the original bucket refers to the first part of the data and a new + * bucket inserted into the brigade after the original bucket refers + * to the second part of the data. Reference counts are maintained as + * necessary. + * + * setaside ensures that the data in the bucket has a long enough + * lifetime. Sometimes it is convenient to create a bucket referring + * to data on the stack in the expectation that it will be consumed + * (output to the network) before the stack is unwound. If that + * expectation turns out not to be valid, the setaside function is + * called to move the data somewhere safer. + * + * copy makes a duplicate of the bucket structure as long as it's + * possible to have multiple references to a single copy of the + * data itself. Not all bucket types can be copied. + * + * destroy maintains the reference counts on the resources used by a + * bucket and frees them if necessary. + * + * Note: all of the above functions have wrapper macros (apr_bucket_read(), + * apr_bucket_destroy(), etc), and those macros should be used rather + * than using the function pointers directly. + * + * To write a bucket brigade, they are first made into an iovec, so that we + * don't write too little data at one time. Currently we ignore compacting the + * buckets into as few buckets as possible, but if we really want good + * performance, then we need to compact the buckets before we convert to an + * iovec, or possibly while we are converting to an iovec. + */ + +/* + * Forward declaration of the main types. + */ + +/** @see apr_bucket_brigade */ +typedef struct apr_bucket_brigade apr_bucket_brigade; +/** @see apr_bucket */ +typedef struct apr_bucket apr_bucket; +/** @see apr_bucket_alloc_t */ +typedef struct apr_bucket_alloc_t apr_bucket_alloc_t; + +/** @see apr_bucket_type_t */ +typedef struct apr_bucket_type_t apr_bucket_type_t; + +/** + * Basic bucket type + */ +struct apr_bucket_type_t { + /** + * The name of the bucket type + */ + const char *name; + /** + * The number of functions this bucket understands. Can not be less than + * five. + */ + int num_func; + /** + * Whether the bucket contains metadata (ie, information that + * describes the regular contents of the brigade). The metadata + * is not returned by apr_bucket_read() and is not indicated by + * the ->length of the apr_bucket itself. In other words, an + * empty bucket is safe to arbitrarily remove if and only if it + * contains no metadata. In this sense, "data" is just raw bytes + * that are the "content" of the brigade and "metadata" describes + * that data but is not a proper part of it. + */ + enum { + /** This bucket type represents actual data to send to the client. */ + APR_BUCKET_DATA = 0, + /** This bucket type represents metadata. */ + APR_BUCKET_METADATA = 1 + } is_metadata; + /** + * Free the private data and any resources used by the bucket (if they + * aren't shared with another bucket). This function is required to be + * implemented for all bucket types, though it might be a no-op on some + * of them (namely ones that never allocate any private data structures). + * @param data The private data pointer from the bucket to be destroyed + */ + void (*destroy)(void *data); + + /** + * Read the data from the bucket. This is required to be implemented + * for all bucket types. + * @param b The bucket to read from + * @param str A place to store the data read. Allocation should only be + * done if absolutely necessary. + * @param len The amount of data read. + * @param block Should this read function block if there is more data that + * cannot be read immediately. + */ + apr_status_t (*read)(apr_bucket *b, const char **str, apr_size_t *len, + apr_read_type_e block); + + /** + * Make it possible to set aside the data for at least as long as the + * given pool. Buckets containing data that could potentially die before + * this pool (e.g. the data resides on the stack, in a child pool of + * the given pool, or in a disjoint pool) must somehow copy, shift, or + * transform the data to have the proper lifetime. + * @param e The bucket to convert + * @remark Some bucket types contain data that will always outlive the + * bucket itself. For example no data (EOS and FLUSH), or the data + * resides in global, constant memory (IMMORTAL), or the data is on + * the heap (HEAP). For these buckets, apr_bucket_setaside_noop can + * be used. + */ + apr_status_t (*setaside)(apr_bucket *e, apr_pool_t *pool); + + /** + * Split one bucket in two at the specified position by duplicating + * the bucket structure (not the data) and modifying any necessary + * start/end/offset information. If it's not possible to do this + * for the bucket type (perhaps the length of the data is indeterminate, + * as with pipe and socket buckets), then APR_ENOTIMPL is returned. + * @param e The bucket to split + * @param point The offset of the first byte in the new bucket + */ + apr_status_t (*split)(apr_bucket *e, apr_size_t point); + + /** + * Copy the bucket structure (not the data), assuming that this is + * possible for the bucket type. If it's not, APR_ENOTIMPL is returned. + * @param e The bucket to copy + * @param c Returns a pointer to the new bucket + */ + apr_status_t (*copy)(apr_bucket *e, apr_bucket **c); + +}; + +/** + * apr_bucket structures are allocated on the malloc() heap and + * their lifetime is controlled by the parent apr_bucket_brigade + * structure. Buckets can move from one brigade to another e.g. by + * calling APR_BRIGADE_CONCAT(). In general the data in a bucket has + * the same lifetime as the bucket and is freed when the bucket is + * destroyed; if the data is shared by more than one bucket (e.g. + * after a split) the data is freed when the last bucket goes away. + */ +struct apr_bucket { + /** Links to the rest of the brigade */ + APR_RING_ENTRY(apr_bucket) link; + /** The type of bucket. */ + const apr_bucket_type_t *type; + /** The length of the data in the bucket. This could have been implemented + * with a function, but this is an optimization, because the most + * common thing to do will be to get the length. If the length is unknown, + * the value of this field will be (apr_size_t)(-1). + */ + apr_size_t length; + /** The start of the data in the bucket relative to the private base + * pointer. The vast majority of bucket types allow a fixed block of + * data to be referenced by multiple buckets, each bucket pointing to + * a different segment of the data. That segment starts at base+start + * and ends at base+start+length. + * If the length == (apr_size_t)(-1), then start == -1. + */ + apr_off_t start; + /** type-dependent data hangs off this pointer */ + void *data; + /** + * Pointer to function used to free the bucket. This function should + * always be defined and it should be consistent with the memory + * function used to allocate the bucket. For example, if malloc() is + * used to allocate the bucket, this pointer should point to free(). + * @param e Pointer to the bucket being freed + */ + void (*free)(void *e); + /** The freelist from which this bucket was allocated */ + apr_bucket_alloc_t *list; +}; + +/** A list of buckets */ +struct apr_bucket_brigade { + /** The pool to associate the brigade with. The data is not allocated out + * of the pool, but a cleanup is registered with this pool. If the + * brigade is destroyed by some mechanism other than pool destruction, + * the destroying function is responsible for killing the cleanup. + */ + apr_pool_t *p; + /** The buckets in the brigade are on this list. */ + /* + * The apr_bucket_list structure doesn't actually need a name tag + * because it has no existence independent of struct apr_bucket_brigade; + * the ring macros are designed so that you can leave the name tag + * argument empty in this situation but apparently the Windows compiler + * doesn't like that. + */ + APR_RING_HEAD(apr_bucket_list, apr_bucket) list; + /** The freelist from which this bucket was allocated */ + apr_bucket_alloc_t *bucket_alloc; +}; + + +/** + * Function called when a brigade should be flushed + */ +typedef apr_status_t (*apr_brigade_flush)(apr_bucket_brigade *bb, void *ctx); + +/* + * define APR_BUCKET_DEBUG if you want your brigades to be checked for + * validity at every possible instant. this will slow your code down + * substantially but is a very useful debugging tool. + */ +#ifdef APR_BUCKET_DEBUG + +#define APR_BRIGADE_CHECK_CONSISTENCY(b) \ + APR_RING_CHECK_CONSISTENCY(&(b)->list, apr_bucket, link) + +#define APR_BUCKET_CHECK_CONSISTENCY(e) \ + APR_RING_CHECK_ELEM_CONSISTENCY((e), apr_bucket, link) + +#else +/** + * checks the ring pointers in a bucket brigade for consistency. an + * abort() will be triggered if any inconsistencies are found. + * note: this is a no-op unless APR_BUCKET_DEBUG is defined. + * @param b The brigade + */ +#define APR_BRIGADE_CHECK_CONSISTENCY(b) +/** + * checks the brigade a bucket is in for ring consistency. an + * abort() will be triggered if any inconsistencies are found. + * note: this is a no-op unless APR_BUCKET_DEBUG is defined. + * @param e The bucket + */ +#define APR_BUCKET_CHECK_CONSISTENCY(e) +#endif + + +/** + * Wrappers around the RING macros to reduce the verbosity of the code + * that handles bucket brigades. + */ +/** + * The magic pointer value that indicates the head of the brigade + * @remark This is used to find the beginning and end of the brigade, eg: + *
+ *      while (e != APR_BRIGADE_SENTINEL(b)) {
+ *          ...
+ *          e = APR_BUCKET_NEXT(e);
+ *      }
+ * 
+ * @param b The brigade + * @return The magic pointer value + */ +#define APR_BRIGADE_SENTINEL(b) APR_RING_SENTINEL(&(b)->list, apr_bucket, link) + +/** + * Determine if the bucket brigade is empty + * @param b The brigade to check + * @return true or false + */ +#define APR_BRIGADE_EMPTY(b) APR_RING_EMPTY(&(b)->list, apr_bucket, link) + +/** + * Return the first bucket in a brigade + * @param b The brigade to query + * @return The first bucket in the brigade + */ +#define APR_BRIGADE_FIRST(b) APR_RING_FIRST(&(b)->list) +/** + * Return the last bucket in a brigade + * @param b The brigade to query + * @return The last bucket in the brigade + */ +#define APR_BRIGADE_LAST(b) APR_RING_LAST(&(b)->list) + +/** + * Insert a single bucket at the front of a brigade + * @param b The brigade to add to + * @param e The bucket to insert + */ +#define APR_BRIGADE_INSERT_HEAD(b, e) do { \ + apr_bucket *ap__b = (e); \ + APR_RING_INSERT_HEAD(&(b)->list, ap__b, apr_bucket, link); \ + APR_BRIGADE_CHECK_CONSISTENCY((b)); \ + } while (0) + +/** + * Insert a single bucket at the end of a brigade + * @param b The brigade to add to + * @param e The bucket to insert + */ +#define APR_BRIGADE_INSERT_TAIL(b, e) do { \ + apr_bucket *ap__b = (e); \ + APR_RING_INSERT_TAIL(&(b)->list, ap__b, apr_bucket, link); \ + APR_BRIGADE_CHECK_CONSISTENCY((b)); \ + } while (0) + +/** + * Concatenate brigade b onto the end of brigade a, leaving brigade b empty + * @param a The first brigade + * @param b The second brigade + */ +#define APR_BRIGADE_CONCAT(a, b) do { \ + APR_RING_CONCAT(&(a)->list, &(b)->list, apr_bucket, link); \ + APR_BRIGADE_CHECK_CONSISTENCY((a)); \ + } while (0) + +/** + * Prepend brigade b onto the beginning of brigade a, leaving brigade b empty + * @param a The first brigade + * @param b The second brigade + */ +#define APR_BRIGADE_PREPEND(a, b) do { \ + APR_RING_PREPEND(&(a)->list, &(b)->list, apr_bucket, link); \ + APR_BRIGADE_CHECK_CONSISTENCY((a)); \ + } while (0) + +/** + * Insert a single bucket before a specified bucket + * @param a The bucket to insert before + * @param b The bucket to insert + */ +#define APR_BUCKET_INSERT_BEFORE(a, b) do { \ + apr_bucket *ap__a = (a), *ap__b = (b); \ + APR_RING_INSERT_BEFORE(ap__a, ap__b, link); \ + APR_BUCKET_CHECK_CONSISTENCY(ap__a); \ + } while (0) + +/** + * Insert a single bucket after a specified bucket + * @param a The bucket to insert after + * @param b The bucket to insert + */ +#define APR_BUCKET_INSERT_AFTER(a, b) do { \ + apr_bucket *ap__a = (a), *ap__b = (b); \ + APR_RING_INSERT_AFTER(ap__a, ap__b, link); \ + APR_BUCKET_CHECK_CONSISTENCY(ap__a); \ + } while (0) + +/** + * Get the next bucket in the list + * @param e The current bucket + * @return The next bucket + */ +#define APR_BUCKET_NEXT(e) APR_RING_NEXT((e), link) +/** + * Get the previous bucket in the list + * @param e The current bucket + * @return The previous bucket + */ +#define APR_BUCKET_PREV(e) APR_RING_PREV((e), link) + +/** + * Remove a bucket from its bucket brigade + * @param e The bucket to remove + */ +#define APR_BUCKET_REMOVE(e) APR_RING_REMOVE((e), link) + +/** + * Initialize a new bucket's prev/next pointers + * @param e The bucket to initialize + */ +#define APR_BUCKET_INIT(e) APR_RING_ELEM_INIT((e), link) + +/** + * Determine if a bucket contains metadata. An empty bucket is + * safe to arbitrarily remove if and only if this is false. + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_METADATA(e) ((e)->type->is_metadata) + +/** + * Determine if a bucket is a FLUSH bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_FLUSH(e) ((e)->type == &apr_bucket_type_flush) +/** + * Determine if a bucket is an EOS bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_EOS(e) ((e)->type == &apr_bucket_type_eos) +/** + * Determine if a bucket is a FILE bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_FILE(e) ((e)->type == &apr_bucket_type_file) +/** + * Determine if a bucket is a PIPE bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_PIPE(e) ((e)->type == &apr_bucket_type_pipe) +/** + * Determine if a bucket is a SOCKET bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_SOCKET(e) ((e)->type == &apr_bucket_type_socket) +/** + * Determine if a bucket is a HEAP bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_HEAP(e) ((e)->type == &apr_bucket_type_heap) +/** + * Determine if a bucket is a TRANSIENT bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_TRANSIENT(e) ((e)->type == &apr_bucket_type_transient) +/** + * Determine if a bucket is a IMMORTAL bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_IMMORTAL(e) ((e)->type == &apr_bucket_type_immortal) +#if APR_HAS_MMAP +/** + * Determine if a bucket is a MMAP bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_MMAP(e) ((e)->type == &apr_bucket_type_mmap) +#endif +/** + * Determine if a bucket is a POOL bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_POOL(e) ((e)->type == &apr_bucket_type_pool) + +/* + * General-purpose reference counting for the various bucket types. + * + * Any bucket type that keeps track of the resources it uses (i.e. + * most of them except for IMMORTAL, TRANSIENT, and EOS) needs to + * attach a reference count to the resource so that it can be freed + * when the last bucket that uses it goes away. Resource-sharing may + * occur because of bucket splits or buckets that refer to globally + * cached data. */ + +/** @see apr_bucket_refcount */ +typedef struct apr_bucket_refcount apr_bucket_refcount; +/** + * The structure used to manage the shared resource must start with an + * apr_bucket_refcount which is updated by the general-purpose refcount + * code. A pointer to the bucket-type-dependent private data structure + * can be cast to a pointer to an apr_bucket_refcount and vice versa. + */ +struct apr_bucket_refcount { + /** The number of references to this bucket */ + int refcount; +}; + +/* ***** Reference-counted bucket types ***** */ + +/** @see apr_bucket_heap */ +typedef struct apr_bucket_heap apr_bucket_heap; +/** + * A bucket referring to data allocated off the heap. + */ +struct apr_bucket_heap { + /** Number of buckets using this memory */ + apr_bucket_refcount refcount; + /** The start of the data actually allocated. This should never be + * modified, it is only used to free the bucket. + */ + char *base; + /** how much memory was allocated */ + apr_size_t alloc_len; + /** function to use to delete the data */ + void (*free_func)(void *data); +}; + +/** @see apr_bucket_pool */ +typedef struct apr_bucket_pool apr_bucket_pool; +/** + * A bucket referring to data allocated from a pool + */ +struct apr_bucket_pool { + /** The pool bucket must be able to be easily morphed to a heap + * bucket if the pool gets cleaned up before all references are + * destroyed. This apr_bucket_heap structure is populated automatically + * when the pool gets cleaned up, and subsequent calls to pool_read() + * will result in the apr_bucket in question being morphed into a + * regular heap bucket. (To avoid having to do many extra refcount + * manipulations and b->data manipulations, the apr_bucket_pool + * struct actually *contains* the apr_bucket_heap struct that it + * will become as its first element; the two share their + * apr_bucket_refcount members.) + */ + apr_bucket_heap heap; + /** The block of data actually allocated from the pool. + * Segments of this block are referenced by adjusting + * the start and length of the apr_bucket accordingly. + * This will be NULL after the pool gets cleaned up. + */ + const char *base; + /** The pool the data was allocated from. When the pool + * is cleaned up, this gets set to NULL as an indicator + * to pool_read() that the data is now on the heap and + * so it should morph the bucket into a regular heap + * bucket before continuing. + */ + apr_pool_t *pool; + /** The freelist this structure was allocated from, which is + * needed in the cleanup phase in order to allocate space on the heap + */ + apr_bucket_alloc_t *list; +}; + +#if APR_HAS_MMAP +/** @see apr_bucket_mmap */ +typedef struct apr_bucket_mmap apr_bucket_mmap; +/** + * A bucket referring to an mmap()ed file + */ +struct apr_bucket_mmap { + /** Number of buckets using this memory */ + apr_bucket_refcount refcount; + /** The mmap this sub_bucket refers to */ + apr_mmap_t *mmap; +}; +#endif + +/** @see apr_bucket_file */ +typedef struct apr_bucket_file apr_bucket_file; +/** + * A bucket referring to an file + */ +struct apr_bucket_file { + /** Number of buckets using this memory */ + apr_bucket_refcount refcount; + /** The file this bucket refers to */ + apr_file_t *fd; + /** The pool into which any needed structures should + * be created while reading from this file bucket */ + apr_pool_t *readpool; +#if APR_HAS_MMAP + /** Whether this bucket should be memory-mapped if + * a caller tries to read from it */ + int can_mmap; +#endif /* APR_HAS_MMAP */ + /** File read block size */ + apr_size_t read_size; +}; + +/** @see apr_bucket_structs */ +typedef union apr_bucket_structs apr_bucket_structs; +/** + * A union of all bucket structures so we know what + * the max size is. + */ +union apr_bucket_structs { + apr_bucket b; /**< Bucket */ + apr_bucket_heap heap; /**< Heap */ + apr_bucket_pool pool; /**< Pool */ +#if APR_HAS_MMAP + apr_bucket_mmap mmap; /**< MMap */ +#endif + apr_bucket_file file; /**< File */ +}; + +/** + * The amount that apr_bucket_alloc() should allocate in the common case. + * Note: this is twice as big as apr_bucket_structs to allow breathing + * room for third-party bucket types. + */ +#define APR_BUCKET_ALLOC_SIZE APR_ALIGN_DEFAULT(2*sizeof(apr_bucket_structs)) + +/* ***** Bucket Brigade Functions ***** */ +/** + * Create a new bucket brigade. The bucket brigade is originally empty. + * @param p The pool to associate with the brigade. Data is not allocated out + * of the pool, but a cleanup is registered. + * @param list The bucket allocator to use + * @return The empty bucket brigade + */ +APU_DECLARE(apr_bucket_brigade *) apr_brigade_create(apr_pool_t *p, + apr_bucket_alloc_t *list); + +/** + * destroy an entire bucket brigade. This includes destroying all of the + * buckets within the bucket brigade's bucket list. + * @param b The bucket brigade to destroy + */ +APU_DECLARE(apr_status_t) apr_brigade_destroy(apr_bucket_brigade *b); + +/** + * empty out an entire bucket brigade. This includes destroying all of the + * buckets within the bucket brigade's bucket list. This is similar to + * apr_brigade_destroy(), except that it does not deregister the brigade's + * pool cleanup function. + * @param data The bucket brigade to clean up + * @remark Generally, you should use apr_brigade_destroy(). This function + * can be useful in situations where you have a single brigade that + * you wish to reuse many times by destroying all of the buckets in + * the brigade and putting new buckets into it later. + */ +APU_DECLARE(apr_status_t) apr_brigade_cleanup(void *data); + +/** + * Move the buckets from the tail end of the existing brigade @a b into + * the brigade @a a. If @a a is NULL a new brigade is created. Buckets + * from @a e to the last bucket (inclusively) of brigade @a b are moved + * from @a b to the returned brigade @a a. + * + * @param b The brigade to split + * @param e The first bucket to move + * @param a The brigade which should be used for the result or NULL if + * a new brigade should be created. The brigade @a a will be + * cleared if it is not empty. + * @return The brigade supplied in @a a or a new one if @a a was NULL. + * @warning Note that this function allocates a new brigade if @a a is + * NULL so memory consumption should be carefully considered. + */ +APU_DECLARE(apr_bucket_brigade *) apr_brigade_split_ex(apr_bucket_brigade *b, + apr_bucket *e, + apr_bucket_brigade *a); + +/** + * Create a new bucket brigade and move the buckets from the tail end + * of an existing brigade into the new brigade. Buckets from + * @a e to the last bucket (inclusively) of brigade @a b + * are moved from @a b to the returned brigade. + * @param b The brigade to split + * @param e The first bucket to move + * @return The new brigade + * @warning Note that this function always allocates a new brigade + * so memory consumption should be carefully considered. + */ +APU_DECLARE(apr_bucket_brigade *) apr_brigade_split(apr_bucket_brigade *b, + apr_bucket *e); + +/** + * Partition a bucket brigade at a given offset (in bytes from the start of + * the brigade). This is useful whenever a filter wants to use known ranges + * of bytes from the brigade; the ranges can even overlap. + * @param b The brigade to partition + * @param point The offset at which to partition the brigade + * @param after_point Returns a pointer to the first bucket after the partition + * @return APR_SUCCESS on success, APR_INCOMPLETE if the contents of the + * brigade were shorter than @a point, or an error code. + * @remark if APR_INCOMPLETE is returned, @a after_point will be set to + * the brigade sentinel. + */ +APU_DECLARE(apr_status_t) apr_brigade_partition(apr_bucket_brigade *b, + apr_off_t point, + apr_bucket **after_point); + +/** + * Return the total length of the brigade. + * @param bb The brigade to compute the length of + * @param read_all Read unknown-length buckets to force a size + * @param length Returns the length of the brigade (up to the end, or up + * to a bucket read error), or -1 if the brigade has buckets + * of indeterminate length and read_all is 0. + */ +APU_DECLARE(apr_status_t) apr_brigade_length(apr_bucket_brigade *bb, + int read_all, + apr_off_t *length); + +/** + * Take a bucket brigade and store the data in a flat char* + * @param bb The bucket brigade to create the char* from + * @param c The char* to write into + * @param len The maximum length of the char array. On return, it is the + * actual length of the char array. + */ +APU_DECLARE(apr_status_t) apr_brigade_flatten(apr_bucket_brigade *bb, + char *c, + apr_size_t *len); + +/** + * Creates a pool-allocated string representing a flat bucket brigade + * @param bb The bucket brigade to create the char array from + * @param c On return, the allocated char array + * @param len On return, the length of the char array. + * @param pool The pool to allocate the string from. + */ +APU_DECLARE(apr_status_t) apr_brigade_pflatten(apr_bucket_brigade *bb, + char **c, + apr_size_t *len, + apr_pool_t *pool); + +/** + * Split a brigade to represent one LF line. + * @param bbOut The bucket brigade that will have the LF line appended to. + * @param bbIn The input bucket brigade to search for a LF-line. + * @param block The blocking mode to be used to split the line. + * @param maxbytes The maximum bytes to read. If this many bytes are seen + * without a LF, the brigade will contain a partial line. + */ +APU_DECLARE(apr_status_t) apr_brigade_split_line(apr_bucket_brigade *bbOut, + apr_bucket_brigade *bbIn, + apr_read_type_e block, + apr_off_t maxbytes); + +/** + * Create an iovec of the elements in a bucket_brigade... return number + * of elements used. This is useful for writing to a file or to the + * network efficiently. + * @param b The bucket brigade to create the iovec from + * @param vec The iovec to create + * @param nvec The number of elements in the iovec. On return, it is the + * number of iovec elements actually filled out. + */ +APU_DECLARE(apr_status_t) apr_brigade_to_iovec(apr_bucket_brigade *b, + struct iovec *vec, int *nvec); + +/** + * This function writes a list of strings into a bucket brigade. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param va A list of strings to add + * @return APR_SUCCESS or error code. + */ +APU_DECLARE(apr_status_t) apr_brigade_vputstrs(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, + va_list va); + +/** + * This function writes a string into a bucket brigade. + * + * The apr_brigade_write function attempts to be efficient with the + * handling of heap buckets. Regardless of the amount of data stored + * inside a heap bucket, heap buckets are a fixed size to promote their + * reuse. + * + * If an attempt is made to write a string to a brigade that already + * ends with a heap bucket, this function will attempt to pack the + * string into the remaining space in the previous heap bucket, before + * allocating a new heap bucket. + * + * This function always returns APR_SUCCESS, unless a flush function is + * passed, in which case the return value of the flush function will be + * returned if used. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param str The string to add + * @param nbyte The number of bytes to write + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_write(apr_bucket_brigade *b, + apr_brigade_flush flush, void *ctx, + const char *str, apr_size_t nbyte); + +/** + * This function writes multiple strings into a bucket brigade. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param vec The strings to add (address plus length for each) + * @param nvec The number of entries in iovec + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_writev(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, + const struct iovec *vec, + apr_size_t nvec); + +/** + * This function writes a string into a bucket brigade. + * @param bb The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param str The string to add + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_puts(apr_bucket_brigade *bb, + apr_brigade_flush flush, void *ctx, + const char *str); + +/** + * This function writes a character into a bucket brigade. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param c The character to add + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_putc(apr_bucket_brigade *b, + apr_brigade_flush flush, void *ctx, + const char c); + +/** + * This function writes an unspecified number of strings into a bucket brigade. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param ... The strings to add + * @return APR_SUCCESS or error code + */ +APU_DECLARE_NONSTD(apr_status_t) apr_brigade_putstrs(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, ...); + +/** + * Evaluate a printf and put the resulting string at the end + * of the bucket brigade. + * @param b The brigade to write to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param fmt The format of the string to write + * @param ... The arguments to fill out the format + * @return APR_SUCCESS or error code + */ +APU_DECLARE_NONSTD(apr_status_t) apr_brigade_printf(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, + const char *fmt, ...) + __attribute__((format(printf,4,5))); + +/** + * Evaluate a printf and put the resulting string at the end + * of the bucket brigade. + * @param b The brigade to write to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param fmt The format of the string to write + * @param va The arguments to fill out the format + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_vprintf(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, + const char *fmt, va_list va); + +/** + * Utility function to insert a file (or a segment of a file) onto the + * end of the brigade. The file is split into multiple buckets if it + * is larger than the maximum size which can be represented by a + * single bucket. + * @param bb the brigade to insert into + * @param f the file to insert + * @param start the offset of the start of the segment + * @param len the length of the segment of the file to insert + * @param p pool from which file buckets are allocated + * @return the last bucket inserted + */ +APU_DECLARE(apr_bucket *) apr_brigade_insert_file(apr_bucket_brigade *bb, + apr_file_t *f, + apr_off_t start, + apr_off_t len, + apr_pool_t *p); + + + +/* ***** Bucket freelist functions ***** */ +/** + * Create a bucket allocator. + * @param p This pool's underlying apr_allocator_t is used to allocate memory + * for the bucket allocator. When the pool is destroyed, the bucket + * allocator's cleanup routine will free all memory that has been + * allocated from it. + * @remark The reason the allocator gets its memory from the pool's + * apr_allocator_t rather than from the pool itself is because + * the bucket allocator will free large memory blocks back to the + * allocator when it's done with them, thereby preventing memory + * footprint growth that would occur if we allocated from the pool. + * @warning The allocator must never be used by more than one thread at a time. + */ +APU_DECLARE_NONSTD(apr_bucket_alloc_t *) apr_bucket_alloc_create(apr_pool_t *p); + +/** + * Create a bucket allocator. + * @param allocator This apr_allocator_t is used to allocate both the bucket + * allocator and all memory handed out by the bucket allocator. The + * caller is responsible for destroying the bucket allocator and the + * apr_allocator_t -- no automatic cleanups will happen. + * @warning The allocator must never be used by more than one thread at a time. + */ +APU_DECLARE_NONSTD(apr_bucket_alloc_t *) apr_bucket_alloc_create_ex(apr_allocator_t *allocator); + +/** + * Destroy a bucket allocator. + * @param list The allocator to be destroyed + */ +APU_DECLARE_NONSTD(void) apr_bucket_alloc_destroy(apr_bucket_alloc_t *list); + +/** + * Get the aligned size corresponding to the requested size, but minus the + * allocator(s) overhead such that the allocation would remain in the + * same boundary. + * @param list The allocator from which to the memory would be allocated. + * @param size The requested size. + * @return The corresponding aligned/floored size. + */ +APU_DECLARE_NONSTD(apr_size_t) apr_bucket_alloc_aligned_floor(apr_bucket_alloc_t *list, + apr_size_t size) + __attribute__((nonnull(1))); + +/** + * Allocate memory for use by the buckets. + * @param size The amount to allocate. + * @param list The allocator from which to allocate the memory. + */ +APU_DECLARE_NONSTD(void *) apr_bucket_alloc(apr_size_t size, apr_bucket_alloc_t *list); + +/** + * Free memory previously allocated with apr_bucket_alloc(). + * @param block The block of memory to be freed. + */ +APU_DECLARE_NONSTD(void) apr_bucket_free(void *block); + + +/* ***** Bucket Functions ***** */ +/** + * Free the resources used by a bucket. If multiple buckets refer to + * the same resource it is freed when the last one goes away. + * @see apr_bucket_delete() + * @param e The bucket to destroy + */ +#define apr_bucket_destroy(e) do { \ + (e)->type->destroy((e)->data); \ + (e)->free(e); \ + } while (0) + +/** + * Delete a bucket by removing it from its brigade (if any) and then + * destroying it. + * @remark This mainly acts as an aid in avoiding code verbosity. It is + * the preferred exact equivalent to: + *
+ *      APR_BUCKET_REMOVE(e);
+ *      apr_bucket_destroy(e);
+ * 
+ * @param e The bucket to delete + */ +#define apr_bucket_delete(e) do { \ + APR_BUCKET_REMOVE(e); \ + apr_bucket_destroy(e); \ + } while (0) + +/** + * Read some data from the bucket. + * + * The apr_bucket_read function returns a convenient amount of data + * from the bucket provided, writing the address and length of the + * data to the pointers provided by the caller. The function tries + * as hard as possible to avoid a memory copy. + * + * Buckets are expected to be a member of a brigade at the time they + * are read. + * + * In typical application code, buckets are read in a loop, and after + * each bucket is read and processed, it is moved or deleted from the + * brigade and the next bucket read. + * + * The definition of "convenient" depends on the type of bucket that + * is being read, and is decided by APR. In the case of memory based + * buckets such as heap and immortal buckets, a pointer will be + * returned to the location of the buffer containing the complete + * contents of the bucket. + * + * Some buckets, such as the socket bucket, might have no concept + * of length. If an attempt is made to read such a bucket, the + * apr_bucket_read function will read a convenient amount of data + * from the socket. The socket bucket is magically morphed into a + * heap bucket containing the just-read data, and a new socket bucket + * is inserted just after this heap bucket. + * + * To understand why apr_bucket_read might do this, consider the loop + * described above to read and process buckets. The current bucket + * is magically morphed into a heap bucket and returned to the caller. + * The caller processes the data, and deletes the heap bucket, moving + * onto the next bucket, the new socket bucket. This process repeats, + * giving the illusion of a bucket brigade that contains potentially + * infinite amounts of data. It is up to the caller to decide at what + * point to stop reading buckets. + * + * Some buckets, such as the file bucket, might have a fixed size, + * but be significantly larger than is practical to store in RAM in + * one go. As with the socket bucket, if an attempt is made to read + * from a file bucket, the file bucket is magically morphed into a + * heap bucket containing a convenient amount of data read from the + * current offset in the file. During the read, the offset will be + * moved forward on the file, and a new file bucket will be inserted + * directly after the current bucket representing the remainder of the + * file. If the heap bucket was large enough to store the whole + * remainder of the file, no more file buckets are inserted, and the + * file bucket will disappear completely. + * + * The pattern for reading buckets described above does create the + * illusion that the code is willing to swallow buckets that might be + * too large for the system to handle in one go. This however is just + * an illusion: APR will always ensure that large (file) or infinite + * (socket) buckets are broken into convenient bite sized heap buckets + * before data is returned to the caller. + * + * There is a potential gotcha to watch for: if buckets are read in a + * loop, and aren't deleted after being processed, the potentially large + * bucket will slowly be converted into RAM resident heap buckets. If + * the file is larger than available RAM, an out of memory condition + * could be caused if the application is not careful to manage this. + * + * @param e The bucket to read from + * @param str The location to store a pointer to the data in + * @param len The location to store the amount of data read + * @param block Whether the read function blocks + */ +#define apr_bucket_read(e,str,len,block) (e)->type->read(e, str, len, block) + +/** + * Setaside data so that stack data is not destroyed on returning from + * the function + * @param e The bucket to setaside + * @param p The pool to setaside into + */ +#define apr_bucket_setaside(e,p) (e)->type->setaside(e,p) + +/** + * Split one bucket in two at the point provided. + * + * Once split, the original bucket becomes the first of the two new buckets. + * + * (It is assumed that the bucket is a member of a brigade when this + * function is called). + * @param e The bucket to split + * @param point The offset to split the bucket at + */ +#define apr_bucket_split(e,point) (e)->type->split(e, point) + +/** + * Copy a bucket. + * @param e The bucket to copy + * @param c Returns a pointer to the new bucket + */ +#define apr_bucket_copy(e,c) (e)->type->copy(e, c) + +/* Bucket type handling */ + +/** + * This function simply returns APR_SUCCESS to denote that the bucket does + * not require anything to happen for its setaside() function. This is + * appropriate for buckets that have "immortal" data -- the data will live + * at least as long as the bucket. + * @param data The bucket to setaside + * @param pool The pool defining the desired lifetime of the bucket data + * @return APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_setaside_noop(apr_bucket *data, + apr_pool_t *pool); + +/** + * A place holder function that signifies that the setaside function was not + * implemented for this bucket + * @param data The bucket to setaside + * @param pool The pool defining the desired lifetime of the bucket data + * @return APR_ENOTIMPL + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_setaside_notimpl(apr_bucket *data, + apr_pool_t *pool); + +/** + * A place holder function that signifies that the split function was not + * implemented for this bucket + * @param data The bucket to split + * @param point The location to split the bucket + * @return APR_ENOTIMPL + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_split_notimpl(apr_bucket *data, + apr_size_t point); + +/** + * A place holder function that signifies that the copy function was not + * implemented for this bucket + * @param e The bucket to copy + * @param c Returns a pointer to the new bucket + * @return APR_ENOTIMPL + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_copy_notimpl(apr_bucket *e, + apr_bucket **c); + +/** + * A place holder function that signifies that this bucket does not need + * to do anything special to be destroyed. That's only the case for buckets + * that either have no data (metadata buckets) or buckets whose data pointer + * points to something that's not a bucket-type-specific structure, as with + * simple buckets where data points to a string and pipe buckets where data + * points directly to the apr_file_t. + * @param data The bucket data to destroy + */ +APU_DECLARE_NONSTD(void) apr_bucket_destroy_noop(void *data); + +/** + * There is no apr_bucket_destroy_notimpl, because destruction is required + * to be implemented (it could be a noop, but only if that makes sense for + * the bucket type) + */ + +/* There is no apr_bucket_read_notimpl, because it is a required function + */ + + +/* All of the bucket types implemented by the core */ +/** + * The flush bucket type. This signifies that all data should be flushed to + * the next filter. The flush bucket should be sent with the other buckets. + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_flush; +/** + * The EOS bucket type. This signifies that there will be no more data, ever. + * All filters MUST send all data to the next filter when they receive a + * bucket of this type + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_eos; +/** + * The FILE bucket type. This bucket represents a file on disk + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_file; +/** + * The HEAP bucket type. This bucket represents a data allocated from the + * heap. + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_heap; +#if APR_HAS_MMAP +/** + * The MMAP bucket type. This bucket represents an MMAP'ed file + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_mmap; +#endif +/** + * The POOL bucket type. This bucket represents a data that was allocated + * from a pool. IF this bucket is still available when the pool is cleared, + * the data is copied on to the heap. + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_pool; +/** + * The PIPE bucket type. This bucket represents a pipe to another program. + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_pipe; +/** + * The IMMORTAL bucket type. This bucket represents a segment of data that + * the creator is willing to take responsibility for. The core will do + * nothing with the data in an immortal bucket + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_immortal; +/** + * The TRANSIENT bucket type. This bucket represents a data allocated off + * the stack. When the setaside function is called, this data is copied on + * to the heap + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_transient; +/** + * The SOCKET bucket type. This bucket represents a socket to another machine + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_socket; + + +/* ***** Simple buckets ***** */ + +/** + * Split a simple bucket into two at the given point. Most non-reference + * counting buckets that allow multiple references to the same block of + * data (eg transient and immortal) will use this as their split function + * without any additional type-specific handling. + * @param b The bucket to be split + * @param point The offset of the first byte in the new bucket + * @return APR_EINVAL if the point is not within the bucket; + * APR_ENOMEM if allocation failed; + * or APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_simple_split(apr_bucket *b, + apr_size_t point); + +/** + * Copy a simple bucket. Most non-reference-counting buckets that allow + * multiple references to the same block of data (eg transient and immortal) + * will use this as their copy function without any additional type-specific + * handling. + * @param a The bucket to copy + * @param b Returns a pointer to the new bucket + * @return APR_ENOMEM if allocation failed; + * or APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_simple_copy(apr_bucket *a, + apr_bucket **b); + + +/* ***** Shared, reference-counted buckets ***** */ + +/** + * Initialize a bucket containing reference-counted data that may be + * shared. The caller must allocate the bucket if necessary and + * initialize its type-dependent fields, and allocate and initialize + * its own private data structure. This function should only be called + * by type-specific bucket creation functions. + * @param b The bucket to initialize + * @param data A pointer to the private data structure + * with the reference count at the start + * @param start The start of the data in the bucket + * relative to the private base pointer + * @param length The length of the data in the bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_shared_make(apr_bucket *b, void *data, + apr_off_t start, + apr_size_t length); + +/** + * Decrement the refcount of the data in the bucket. This function + * should only be called by type-specific bucket destruction functions. + * @param data The private data pointer from the bucket to be destroyed + * @return TRUE or FALSE; TRUE if the reference count is now + * zero, indicating that the shared resource itself can + * be destroyed by the caller. + */ +APU_DECLARE(int) apr_bucket_shared_destroy(void *data); + +/** + * Split a bucket into two at the given point, and adjust the refcount + * to the underlying data. Most reference-counting bucket types will + * be able to use this function as their split function without any + * additional type-specific handling. + * @param b The bucket to be split + * @param point The offset of the first byte in the new bucket + * @return APR_EINVAL if the point is not within the bucket; + * APR_ENOMEM if allocation failed; + * or APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_shared_split(apr_bucket *b, + apr_size_t point); + +/** + * Copy a refcounted bucket, incrementing the reference count. Most + * reference-counting bucket types will be able to use this function + * as their copy function without any additional type-specific handling. + * @param a The bucket to copy + * @param b Returns a pointer to the new bucket + * @return APR_ENOMEM if allocation failed; + or APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_shared_copy(apr_bucket *a, + apr_bucket **b); + + +/* ***** Functions to Create Buckets of varying types ***** */ +/* + * Each bucket type foo has two initialization functions: + * apr_bucket_foo_make which sets up some already-allocated memory as a + * bucket of type foo; and apr_bucket_foo_create which allocates memory + * for the bucket, calls apr_bucket_make_foo, and initializes the + * bucket's list pointers. The apr_bucket_foo_make functions are used + * inside the bucket code to change the type of buckets in place; + * other code should call apr_bucket_foo_create. All the initialization + * functions change nothing if they fail. + */ + +/** + * Create an End of Stream bucket. This indicates that there is no more data + * coming from down the filter stack. All filters should flush at this point. + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_eos_create(apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in an EOS bucket. This indicates that there is no + * more data coming from down the filter stack. All filters should flush at + * this point. + * @param b The bucket to make into an EOS bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_eos_make(apr_bucket *b); + +/** + * Create a flush bucket. This indicates that filters should flush their + * data. There is no guarantee that they will flush it, but this is the + * best we can do. + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_flush_create(apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a FLUSH bucket. This indicates that filters + * should flush their data. There is no guarantee that they will flush it, + * but this is the best we can do. + * @param b The bucket to make into a FLUSH bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_flush_make(apr_bucket *b); + +/** + * Create a bucket referring to long-lived data. + * @param buf The data to insert into the bucket + * @param nbyte The size of the data to insert. + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_immortal_create(const char *buf, + apr_size_t nbyte, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to long-lived data + * @param b The bucket to make into a IMMORTAL bucket + * @param buf The data to insert into the bucket + * @param nbyte The size of the data to insert. + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_immortal_make(apr_bucket *b, + const char *buf, + apr_size_t nbyte); + +/** + * Create a bucket referring to data on the stack. + * @param buf The data to insert into the bucket + * @param nbyte The size of the data to insert. + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_transient_create(const char *buf, + apr_size_t nbyte, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to stack data + * @param b The bucket to make into a TRANSIENT bucket + * @param buf The data to insert into the bucket + * @param nbyte The size of the data to insert. + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_transient_make(apr_bucket *b, + const char *buf, + apr_size_t nbyte); + +/** + * Create a bucket referring to memory on the heap. If the caller asks + * for the data to be copied, this function always allocates 4K of + * memory so that more data can be added to the bucket without + * requiring another allocation. Therefore not all the data may be put + * into the bucket. If copying is not requested then the bucket takes + * over responsibility for free()ing the memory. + * @param buf The buffer to insert into the bucket + * @param nbyte The size of the buffer to insert. + * @param free_func Function to use to free the data; NULL indicates that the + * bucket should make a copy of the data + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_heap_create(const char *buf, + apr_size_t nbyte, + void (*free_func)(void *data), + apr_bucket_alloc_t *list); +/** + * Make the bucket passed in a bucket refer to heap data + * @param b The bucket to make into a HEAP bucket + * @param buf The buffer to insert into the bucket + * @param nbyte The size of the buffer to insert. + * @param free_func Function to use to free the data; NULL indicates that the + * bucket should make a copy of the data + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_heap_make(apr_bucket *b, const char *buf, + apr_size_t nbyte, + void (*free_func)(void *data)); + +/** + * Create a bucket referring to memory allocated from a pool. + * + * @param buf The buffer to insert into the bucket + * @param length The number of bytes referred to by this bucket + * @param pool The pool the memory was allocated from + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_pool_create(const char *buf, + apr_size_t length, + apr_pool_t *pool, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to pool data + * @param b The bucket to make into a pool bucket + * @param buf The buffer to insert into the bucket + * @param length The number of bytes referred to by this bucket + * @param pool The pool the memory was allocated from + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_pool_make(apr_bucket *b, const char *buf, + apr_size_t length, + apr_pool_t *pool); + +#if APR_HAS_MMAP +/** + * Create a bucket referring to mmap()ed memory. + * @param mm The mmap to insert into the bucket + * @param start The offset of the first byte in the mmap + * that this bucket refers to + * @param length The number of bytes referred to by this bucket + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_mmap_create(apr_mmap_t *mm, + apr_off_t start, + apr_size_t length, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to an MMAP'ed file + * @param b The bucket to make into a MMAP bucket + * @param mm The mmap to insert into the bucket + * @param start The offset of the first byte in the mmap + * that this bucket refers to + * @param length The number of bytes referred to by this bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_mmap_make(apr_bucket *b, apr_mmap_t *mm, + apr_off_t start, + apr_size_t length); +#endif + +/** + * Create a bucket referring to a socket. + * @param thissock The socket to put in the bucket + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_socket_create(apr_socket_t *thissock, + apr_bucket_alloc_t *list); +/** + * Make the bucket passed in a bucket refer to a socket + * @param b The bucket to make into a SOCKET bucket + * @param thissock The socket to put in the bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_socket_make(apr_bucket *b, + apr_socket_t *thissock); + +/** + * Create a bucket referring to a pipe. + * @param thispipe The pipe to put in the bucket + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_pipe_create(apr_file_t *thispipe, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to a pipe + * @param b The bucket to make into a PIPE bucket + * @param thispipe The pipe to put in the bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_pipe_make(apr_bucket *b, + apr_file_t *thispipe); + +/** + * Create a bucket referring to a file. + * @param fd The file to put in the bucket + * @param offset The offset where the data of interest begins in the file + * @param len The amount of data in the file we are interested in + * @param p The pool into which any needed structures should be created + * while reading from this file bucket + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + * @remark If the file is truncated such that the segment of the file + * referenced by the bucket no longer exists, an attempt to read + * from the bucket will fail with APR_EOF. + * @remark apr_brigade_insert_file() should generally be used to + * insert files into brigades, since that function can correctly + * handle large file issues. + */ +APU_DECLARE(apr_bucket *) apr_bucket_file_create(apr_file_t *fd, + apr_off_t offset, + apr_size_t len, + apr_pool_t *p, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to a file + * @param b The bucket to make into a FILE bucket + * @param fd The file to put in the bucket + * @param offset The offset where the data of interest begins in the file + * @param len The amount of data in the file we are interested in + * @param p The pool into which any needed structures should be created + * while reading from this file bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_file_make(apr_bucket *b, apr_file_t *fd, + apr_off_t offset, + apr_size_t len, apr_pool_t *p); + +/** + * Enable or disable memory-mapping for a FILE bucket (default is enabled) + * @param b The bucket + * @param enabled Whether memory-mapping should be enabled + * @return APR_SUCCESS normally, or an error code if the operation fails + */ +APU_DECLARE(apr_status_t) apr_bucket_file_enable_mmap(apr_bucket *b, + int enabled); + +/** + * Set the size of the read buffer allocated by a FILE bucket (default + * is @a APR_BUCKET_BUFF_SIZE) + * memory-mapping is disabled only) + * @param b The bucket + * @param size Size of the allocated buffers + * @return APR_SUCCESS normally, or an error code if the operation fails + * @remark Relevant/used only when memory-mapping is disabled (@see + * apr_bucket_file_enable_mmap) + */ +APU_DECLARE(apr_status_t) apr_bucket_file_set_buf_size(apr_bucket *e, + apr_size_t size); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_BUCKETS_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_crypto.h b/c/dependencies/windows/apr/x86/include/apr_crypto.h new file mode 100644 index 00000000..b90f3fec --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_crypto.h @@ -0,0 +1,507 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_CRYPTO_H +#define APR_CRYPTO_H + +#include "apu.h" +#include "apr_pools.h" +#include "apr_tables.h" +#include "apr_hash.h" +#include "apu_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_crypto.h + * @brief APR-UTIL Crypto library + */ +/** + * @defgroup APR_Util_Crypto Crypto routines + * @ingroup APR_Util + * @{ + */ + +#if APU_HAVE_CRYPTO + +#ifndef APU_CRYPTO_RECOMMENDED_DRIVER +#if APU_HAVE_COMMONCRYPTO +#define APU_CRYPTO_RECOMMENDED_DRIVER "commoncrypto" +#else +#if APU_HAVE_OPENSSL +#define APU_CRYPTO_RECOMMENDED_DRIVER "openssl" +#else +#if APU_HAVE_NSS +#define APU_CRYPTO_RECOMMENDED_DRIVER "nss" +#else +#if APU_HAVE_MSCNG +#define APU_CRYPTO_RECOMMENDED_DRIVER "mscng" +#else +#if APU_HAVE_MSCAPI +#define APU_CRYPTO_RECOMMENDED_DRIVER "mscapi" +#else +#endif +#endif +#endif +#endif +#endif +#endif + +/** + * Symmetric Key types understood by the library. + * + * NOTE: It is expected that this list will grow over time. + * + * Interoperability Matrix: + * + * The matrix is based on the testcrypto.c unit test, which attempts to + * test whether a simple encrypt/decrypt will succeed, as well as testing + * whether an encrypted string by one library can be decrypted by the + * others. + * + * Some libraries will successfully encrypt and decrypt their own data, + * but won't decrypt data from another library. It is hoped that over + * time these anomalies will be found and fixed, but until then it is + * recommended that ciphers are chosen that interoperate across platform. + * + * An X below means the test passes, it does not necessarily mean that + * encryption performed is correct or secure. Applications should stick + * to ciphers that pass the interoperablity tests on the right hand side + * of the table. + * + * Aligned data is data whose length is a multiple of the block size for + * the chosen cipher. Padded data is data that is not aligned by block + * size and must be padded by the crypto library. + * + * OpenSSL CommonCrypto NSS Interop + * Align Pad Align Pad Align Pad Align Pad + * 3DES_192/CBC X X X X X X X X + * 3DES_192/ECB X X X X + * AES_256/CBC X X X X X X X X + * AES_256/ECB X X X X X X + * AES_192/CBC X X X X X X + * AES_192/ECB X X X X X + * AES_128/CBC X X X X X X + * AES_128/ECB X X X X X + * + * Conclusion: for padded data, use 3DES_192/CBC or AES_256/CBC. For + * aligned data, use 3DES_192/CBC, AES_256/CBC or AES_256/ECB. + */ + +typedef enum +{ + APR_KEY_NONE, APR_KEY_3DES_192, /** 192 bit (3-Key) 3DES */ + APR_KEY_AES_128, /** 128 bit AES */ + APR_KEY_AES_192, /** 192 bit AES */ + APR_KEY_AES_256 +/** 256 bit AES */ +} apr_crypto_block_key_type_e; + +typedef enum +{ + APR_MODE_NONE, /** An error condition */ + APR_MODE_ECB, /** Electronic Code Book */ + APR_MODE_CBC +/** Cipher Block Chaining */ +} apr_crypto_block_key_mode_e; + +/* These are opaque structs. Instantiation is up to each backend */ +typedef struct apr_crypto_driver_t apr_crypto_driver_t; +typedef struct apr_crypto_t apr_crypto_t; +typedef struct apr_crypto_config_t apr_crypto_config_t; +typedef struct apr_crypto_key_t apr_crypto_key_t; +typedef struct apr_crypto_block_t apr_crypto_block_t; + +typedef struct apr_crypto_block_key_type_t { + apr_crypto_block_key_type_e type; + int keysize; + int blocksize; + int ivsize; +} apr_crypto_block_key_type_t; + +typedef struct apr_crypto_block_key_mode_t { + apr_crypto_block_key_mode_e mode; +} apr_crypto_block_key_mode_t; + +typedef struct apr_crypto_passphrase_t { + const char *pass; + apr_size_t passLen; + const unsigned char * salt; + apr_size_t saltLen; + int iterations; +} apr_crypto_passphrase_t; + +typedef struct apr_crypto_secret_t { + const unsigned char *secret; + apr_size_t secretLen; +} apr_crypto_secret_t; + +typedef enum { + /** Key is derived from a passphrase */ + APR_CRYPTO_KTYPE_PASSPHRASE = 1, + /** Key is derived from a raw key */ + APR_CRYPTO_KTYPE_SECRET = 2, +} apr_crypto_key_type; + +typedef struct apr_crypto_key_rec_t { + apr_crypto_key_type ktype; + apr_crypto_block_key_type_e type; + apr_crypto_block_key_mode_e mode; + int pad; + union { + apr_crypto_passphrase_t passphrase; + apr_crypto_secret_t secret; + } k; +} apr_crypto_key_rec_t; + +/** + * @brief Perform once-only initialisation. Call once only. + * + * @param pool - pool to register any shutdown cleanups, etc + * @return APR_NOTIMPL in case of no crypto support. + */ +APU_DECLARE(apr_status_t) apr_crypto_init(apr_pool_t *pool); + +/** + * @brief Zero out the buffer provided when the pool is cleaned up. + * + * @param pool - pool to register the cleanup + * @param buffer - buffer to zero out + * @param size - size of the buffer to zero out + */ +APU_DECLARE(apr_status_t) apr_crypto_clear(apr_pool_t *pool, void *buffer, + apr_size_t size); + +/** + * @brief Always zero out the buffer provided, without being optimized out by + * the compiler. + * + * @param buffer - buffer to zero out + * @param size - size of the buffer to zero out + */ +APU_DECLARE(apr_status_t) apr_crypto_memzero(void *buffer, apr_size_t size); + +/** + * @brief Timing attacks safe buffers comparison, where the executing time does + * not depend on the bytes compared but solely on the number of bytes. + * + * @param buf1 - first buffer to compare + * @param buf2 - second buffer to compare + * @param size - size of the buffers to compare + * @return 1 if the buffers are equals, 0 otherwise. + */ +APU_DECLARE(int) apr_crypto_equals(const void *buf1, const void *buf2, + apr_size_t size); + +/** + * @brief Get the driver struct for a name + * + * @param driver - pointer to driver struct. + * @param name - driver name + * @param params - array of initialisation parameters + * @param result - result and error message on failure + * @param pool - (process) pool to register cleanup + * @return APR_SUCCESS for success + * @return APR_ENOTIMPL for no driver (when DSO not enabled) + * @return APR_EDSOOPEN if DSO driver file can't be opened + * @return APR_ESYMNOTFOUND if the driver file doesn't contain a driver + * @remarks NSS: the params can have "dir", "key3", "cert7" and "secmod" + * keys, each followed by an equal sign and a value. Such key/value pairs can + * be delimited by space or tab. If the value contains a space, surround the + * whole key value pair in quotes: "dir=My Directory". + * @remarks OpenSSL: currently no params are supported. + */ +APU_DECLARE(apr_status_t) apr_crypto_get_driver( + const apr_crypto_driver_t **driver, + const char *name, const char *params, const apu_err_t **result, + apr_pool_t *pool); + +/** + * @brief Return the name of the driver. + * + * @param driver - The driver in use. + * @return The name of the driver. + */ +APU_DECLARE(const char *) apr_crypto_driver_name( + const apr_crypto_driver_t *driver); + +/** + * @brief Get the result of the last operation on a context. If the result + * is NULL, the operation was successful. + * @param result - the result structure + * @param f - context pointer + * @return APR_SUCCESS for success + */ +APU_DECLARE(apr_status_t) apr_crypto_error(const apu_err_t **result, + const apr_crypto_t *f); + +/** + * @brief Create a context for supporting encryption. Keys, certificates, + * algorithms and other parameters will be set per context. More than + * one context can be created at one time. A cleanup will be automatically + * registered with the given pool to guarantee a graceful shutdown. + * @param f - context pointer will be written here + * @param driver - driver to use + * @param params - array of key parameters + * @param pool - process pool + * @return APR_ENOENGINE when the engine specified does not exist. APR_EINITENGINE + * if the engine cannot be initialised. + * @remarks NSS: currently no params are supported. + * @remarks OpenSSL: the params can have "engine" as a key, followed by an equal + * sign and a value. + */ +APU_DECLARE(apr_status_t) apr_crypto_make(apr_crypto_t **f, + const apr_crypto_driver_t *driver, const char *params, + apr_pool_t *pool); + +/** + * @brief Get a hash table of key types, keyed by the name of the type against + * a pointer to apr_crypto_block_key_type_t, which in turn begins with an + * integer. + * + * @param types - hashtable of key types keyed to constants. + * @param f - encryption context + * @return APR_SUCCESS for success + */ +APU_DECLARE(apr_status_t) apr_crypto_get_block_key_types(apr_hash_t **types, + const apr_crypto_t *f); + +/** + * @brief Get a hash table of key modes, keyed by the name of the mode against + * a pointer to apr_crypto_block_key_mode_t, which in turn begins with an + * integer. + * + * @param modes - hashtable of key modes keyed to constants. + * @param f - encryption context + * @return APR_SUCCESS for success + */ +APU_DECLARE(apr_status_t) apr_crypto_get_block_key_modes(apr_hash_t **modes, + const apr_crypto_t *f); + +/** + * @brief Create a key from the provided secret or passphrase. The key is cleaned + * up when the context is cleaned, and may be reused with multiple encryption + * or decryption operations. + * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If + * *key is not NULL, *key must point at a previously created structure. + * @param key The key returned, see note. + * @param rec The key record, from which the key will be derived. + * @param f The context to use. + * @param p The pool to use. + * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend + * error occurred while generating the key. APR_ENOCIPHER if the type or mode + * is not supported by the particular backend. APR_EKEYTYPE if the key type is + * not known. APR_EPADDING if padding was requested but is not supported. + * APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_key(apr_crypto_key_t **key, + const apr_crypto_key_rec_t *rec, const apr_crypto_t *f, apr_pool_t *p); + +/** + * @brief Create a key from the given passphrase. By default, the PBKDF2 + * algorithm is used to generate the key from the passphrase. It is expected + * that the same pass phrase will generate the same key, regardless of the + * backend crypto platform used. The key is cleaned up when the context + * is cleaned, and may be reused with multiple encryption or decryption + * operations. + * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If + * *key is not NULL, *key must point at a previously created structure. + * @param key The key returned, see note. + * @param ivSize The size of the initialisation vector will be returned, based + * on whether an IV is relevant for this type of crypto. + * @param pass The passphrase to use. + * @param passLen The passphrase length in bytes + * @param salt The salt to use. + * @param saltLen The salt length in bytes + * @param type 3DES_192, AES_128, AES_192, AES_256. + * @param mode Electronic Code Book / Cipher Block Chaining. + * @param doPad Pad if necessary. + * @param iterations Number of iterations to use in algorithm + * @param f The context to use. + * @param p The pool to use. + * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend + * error occurred while generating the key. APR_ENOCIPHER if the type or mode + * is not supported by the particular backend. APR_EKEYTYPE if the key type is + * not known. APR_EPADDING if padding was requested but is not supported. + * APR_ENOTIMPL if not implemented. + * @deprecated Replaced by apr_crypto_key(). + */ +APU_DECLARE(apr_status_t) apr_crypto_passphrase(apr_crypto_key_t **key, + apr_size_t *ivSize, const char *pass, apr_size_t passLen, + const unsigned char * salt, apr_size_t saltLen, + const apr_crypto_block_key_type_e type, + const apr_crypto_block_key_mode_e mode, const int doPad, + const int iterations, const apr_crypto_t *f, apr_pool_t *p); + +/** + * @brief Initialise a context for encrypting arbitrary data using the given key. + * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If + * *ctx is not NULL, *ctx must point at a previously created structure. + * @param ctx The block context returned, see note. + * @param iv Optional initialisation vector. If the buffer pointed to is NULL, + * an IV will be created at random, in space allocated from the pool. + * If the buffer pointed to is not NULL, the IV in the buffer will be + * used. + * @param key The key structure to use. + * @param blockSize The block size of the cipher. + * @param p The pool to use. + * @return Returns APR_ENOIV if an initialisation vector is required but not specified. + * Returns APR_EINIT if the backend failed to initialise the context. Returns + * APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_encrypt_init( + apr_crypto_block_t **ctx, const unsigned char **iv, + const apr_crypto_key_t *key, apr_size_t *blockSize, apr_pool_t *p); + +/** + * @brief Encrypt data provided by in, write it to out. + * @note The number of bytes written will be written to outlen. If + * out is NULL, outlen will contain the maximum size of the + * buffer needed to hold the data, including any data + * generated by apr_crypto_block_encrypt_finish below. If *out points + * to NULL, a buffer sufficiently large will be created from + * the pool provided. If *out points to a not-NULL value, this + * value will be used as a buffer instead. + * @param out Address of a buffer to which data will be written, + * see note. + * @param outlen Length of the output will be written here. + * @param in Address of the buffer to read. + * @param inlen Length of the buffer to read. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if + * not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_encrypt(unsigned char **out, + apr_size_t *outlen, const unsigned char *in, apr_size_t inlen, + apr_crypto_block_t *ctx); + +/** + * @brief Encrypt final data block, write it to out. + * @note If necessary the final block will be written out after being + * padded. Typically the final block will be written to the + * same buffer used by apr_crypto_block_encrypt, offset by the + * number of bytes returned as actually written by the + * apr_crypto_block_encrypt() call. After this call, the context + * is cleaned and can be reused by apr_crypto_block_encrypt_init(). + * @param out Address of a buffer to which data will be written. This + * buffer must already exist, and is usually the same + * buffer used by apr_evp_crypt(). See note. + * @param outlen Length of the output will be written here. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. + * @return APR_EPADDING if padding was enabled and the block was incorrectly + * formatted. + * @return APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_encrypt_finish(unsigned char *out, + apr_size_t *outlen, apr_crypto_block_t *ctx); + +/** + * @brief Initialise a context for decrypting arbitrary data using the given key. + * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If + * *ctx is not NULL, *ctx must point at a previously created structure. + * @param ctx The block context returned, see note. + * @param blockSize The block size of the cipher. + * @param iv Optional initialisation vector. + * @param key The key structure to use. + * @param p The pool to use. + * @return Returns APR_ENOIV if an initialisation vector is required but not specified. + * Returns APR_EINIT if the backend failed to initialise the context. Returns + * APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_decrypt_init( + apr_crypto_block_t **ctx, apr_size_t *blockSize, + const unsigned char *iv, const apr_crypto_key_t *key, apr_pool_t *p); + +/** + * @brief Decrypt data provided by in, write it to out. + * @note The number of bytes written will be written to outlen. If + * out is NULL, outlen will contain the maximum size of the + * buffer needed to hold the data, including any data + * generated by apr_crypto_block_decrypt_finish below. If *out points + * to NULL, a buffer sufficiently large will be created from + * the pool provided. If *out points to a not-NULL value, this + * value will be used as a buffer instead. + * @param out Address of a buffer to which data will be written, + * see note. + * @param outlen Length of the output will be written here. + * @param in Address of the buffer to read. + * @param inlen Length of the buffer to read. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if + * not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_decrypt(unsigned char **out, + apr_size_t *outlen, const unsigned char *in, apr_size_t inlen, + apr_crypto_block_t *ctx); + +/** + * @brief Decrypt final data block, write it to out. + * @note If necessary the final block will be written out after being + * padded. Typically the final block will be written to the + * same buffer used by apr_crypto_block_decrypt, offset by the + * number of bytes returned as actually written by the + * apr_crypto_block_decrypt() call. After this call, the context + * is cleaned and can be reused by apr_crypto_block_decrypt_init(). + * @param out Address of a buffer to which data will be written. This + * buffer must already exist, and is usually the same + * buffer used by apr_evp_crypt(). See note. + * @param outlen Length of the output will be written here. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. + * @return APR_EPADDING if padding was enabled and the block was incorrectly + * formatted. + * @return APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_decrypt_finish(unsigned char *out, + apr_size_t *outlen, apr_crypto_block_t *ctx); + +/** + * @brief Clean encryption / decryption context. + * @note After cleanup, a context is free to be reused if necessary. + * @param ctx The block context to use. + * @return Returns APR_ENOTIMPL if not supported. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_cleanup(apr_crypto_block_t *ctx); + +/** + * @brief Clean encryption / decryption context. + * @note After cleanup, a context is free to be reused if necessary. + * @param f The context to use. + * @return Returns APR_ENOTIMPL if not supported. + */ +APU_DECLARE(apr_status_t) apr_crypto_cleanup(apr_crypto_t *f); + +/** + * @brief Shutdown the crypto library. + * @note After shutdown, it is expected that the init function can be called again. + * @param driver - driver to use + * @return Returns APR_ENOTIMPL if not supported. + */ +APU_DECLARE(apr_status_t) apr_crypto_shutdown( + const apr_crypto_driver_t *driver); + +#endif /* APU_HAVE_CRYPTO */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/c/dependencies/windows/apr/x86/include/apr_cstr.h b/c/dependencies/windows/apr/x86/include/apr_cstr.h new file mode 100644 index 00000000..3f1b1a09 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_cstr.h @@ -0,0 +1,292 @@ +/* ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * ==================================================================== + */ + +/** + * @file apr_cstr.h + * @brief C string goodies. + */ + +#ifndef APR_CSTR_H +#define APR_CSTR_H + +#include /* for apr_size_t */ +#include /* for apr_pool_t */ +#include /* for apr_array_header_t */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_cstr C (POSIX) locale string functions + * @ingroup apr_strings + * + * The apr_cstr_* functions provide traditional C char * string text handling, + * and notabilty they treat all text in the C (a.k.a. POSIX) locale using the + * minimal POSIX character set, represented in either ASCII or a corresponding + * EBCDIC subset. + * + * Character values outside of that set are treated as opaque bytes, and all + * multi-byte character sequences are handled as individual distinct octets. + * + * Multi-byte characters sequences whose octets fall in the ASCII range cause + * unexpected results, such as in the ISO-2022-JP code page where ASCII octets + * occur within both shift-state and multibyte sequences. + * + * In the case of the UTF-8 encoding, all multibyte characters all fall outside + * of the C/POSIX range of characters, so these functions are generally safe + * to use on UTF-8 strings. The programmer must be aware that each octet may + * not represent a distinct printable character in such encodings. + * + * The standard C99/POSIX string functions, rather than apr_cstr, should be + * used in all cases where the current locale and encoding of the text is + * significant. + * @{ + */ + + +/** Divide @a input into substrings, interpreting any char from @a sep + * as a token separator. + * + * Return an array of copies of those substrings (plain const char*), + * allocating both the array and the copies in @a pool. + * + * None of the elements added to the array contain any of the + * characters in @a sep_chars, and none of the new elements are empty + * (thus, it is possible that the returned array will have length + * zero). + * + * If @a chop_whitespace is TRUE, then remove leading and trailing + * whitespace from the returned strings. + * + * @since New in 1.6 + */ +APR_DECLARE(apr_array_header_t *) apr_cstr_split(const char *input, + const char *sep_chars, + int chop_whitespace, + apr_pool_t *pool); + +/** Like apr_cstr_split(), but append to existing @a array instead of + * creating a new one. Allocate the copied substrings in @a pool + * (i.e., caller decides whether or not to pass @a array->pool as @a pool). + * + * @since New in 1.6 + */ +APR_DECLARE(void) apr_cstr_split_append(apr_array_header_t *array, + const char *input, + const char *sep_chars, + int chop_whitespace, + apr_pool_t *pool); + + +/** Return @c TRUE iff @a str matches any of the elements of @a list, a list + * of zero or more glob patterns. + * + * @since New in 1.6 + */ +APR_DECLARE(int) apr_cstr_match_glob_list(const char *str, + const apr_array_header_t *list); + +/** Return @c TRUE iff @a str exactly matches any of the elements of @a list. + * + * @since New in 1.6 + */ +APR_DECLARE(int) apr_cstr_match_list(const char *str, + const apr_array_header_t *list); + +/** + * Get the next token from @a *str interpreting any char from @a sep as a + * token separator. Separators at the beginning of @a str will be skipped. + * Returns a pointer to the beginning of the first token in @a *str or NULL + * if no token is left. Modifies @a str such that the next call will return + * the next token. + * + * @note The content of @a *str may be modified by this function. + * + * @since New in 1.6. + */ +APR_DECLARE(char *) apr_cstr_tokenize(const char *sep, char **str); + +/** + * Return the number of line breaks in @a msg, allowing any kind of newline + * termination (CR, LF, CRLF, or LFCR), even inconsistent. + * + * @since New in 1.6. + */ +APR_DECLARE(int) apr_cstr_count_newlines(const char *msg); + +#if 0 /* XXX: stringbuf logic is not present in APR */ +/** + * Return a cstring which is the concatenation of @a strings (an array + * of char *) each followed by @a separator (that is, @a separator + * will also end the resulting string). Allocate the result in @a pool. + * If @a strings is empty, then return the empty string. + * + * @since New in 1.6. + */ +APR_DECLARE(char *) apr_cstr_join(const apr_array_header_t *strings, + const char *separator, + apr_pool_t *pool); +#endif + +/** + * Perform a case-insensitive comparison of two strings @a atr1 and @a atr2, + * treating upper and lower case values of the 26 standard C/POSIX alphabetic + * characters as equivalent. Extended latin characters outside of this set + * are treated as unique octets, irrespective of the current locale. + * + * Returns in integer greater than, equal to, or less than 0, + * according to whether @a str1 is considered greater than, equal to, + * or less than @a str2. + * + * @since New in 1.6. + */ +APR_DECLARE(int) apr_cstr_casecmp(const char *str1, const char *str2); + +/** + * Perform a case-insensitive comparison of two strings @a atr1 and @a atr2, + * treating upper and lower case values of the 26 standard C/POSIX alphabetic + * characters as equivalent. Extended latin characters outside of this set + * are treated as unique octets, irrespective of the current locale. + * + * Returns in integer greater than, equal to, or less than 0, + * according to whether @a str1 is considered greater than, equal to, + * or less than @a str2. + * + * @since New in 1.6. + */ +APR_DECLARE(int) apr_cstr_casecmpn(const char *str1, + const char *str2, + apr_size_t n); + +/** + * Parse the C string @a str into a 64 bit number, and return it in @a *n. + * Assume that the number is represented in base @a base. + * Raise an error if conversion fails (e.g. due to overflow), or if the + * converted number is smaller than @a minval or larger than @a maxval. + * + * Leading whitespace in @a str is skipped in a locale-dependent way. + * After that, the string may contain an optional '+' (positive, default) + * or '-' (negative) character, followed by an optional '0x' prefix if + * @a base is 0 or 16, followed by numeric digits appropriate for the base. + * If there are any more characters after the numeric digits, an error is + * returned. + * + * If @a base is zero, then a leading '0x' or '0X' prefix means hexadecimal, + * else a leading '0' means octal (implemented, though not documented, in + * apr_strtoi64() in APR 0.9.0 through 1.5.0), else use base ten. + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_strtoi64(apr_int64_t *n, const char *str, + apr_int64_t minval, + apr_int64_t maxval, + int base); + +/** + * Parse the C string @a str into a 64 bit number, and return it in @a *n. + * Assume that the number is represented in base 10. + * Raise an error if conversion fails (e.g. due to overflow). + * + * The behaviour otherwise is as described for apr_cstr_strtoi64(). + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_atoi64(apr_int64_t *n, const char *str); + +/** + * Parse the C string @a str into a 32 bit number, and return it in @a *n. + * Assume that the number is represented in base 10. + * Raise an error if conversion fails (e.g. due to overflow). + * + * The behaviour otherwise is as described for apr_cstr_strtoi64(). + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_atoi(int *n, const char *str); + +/** + * Parse the C string @a str into an unsigned 64 bit number, and return + * it in @a *n. Assume that the number is represented in base @a base. + * Raise an error if conversion fails (e.g. due to overflow), or if the + * converted number is smaller than @a minval or larger than @a maxval. + * + * Leading whitespace in @a str is skipped in a locale-dependent way. + * After that, the string may contain an optional '+' (positive, default) + * or '-' (negative) character, followed by an optional '0x' prefix if + * @a base is 0 or 16, followed by numeric digits appropriate for the base. + * If there are any more characters after the numeric digits, an error is + * returned. + * + * If @a base is zero, then a leading '0x' or '0X' prefix means hexadecimal, + * else a leading '0' means octal (as implemented, though not documented, in + * apr_strtoi64(), else use base ten. + * + * @warning The implementation returns APR_ERANGE if the parsed number + * is greater than APR_INT64_MAX, even if it is not greater than @a maxval. + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_strtoui64(apr_uint64_t *n, const char *str, + apr_uint64_t minval, + apr_uint64_t maxval, + int base); + +/** + * Parse the C string @a str into an unsigned 64 bit number, and return + * it in @a *n. Assume that the number is represented in base 10. + * Raise an error if conversion fails (e.g. due to overflow). + * + * The behaviour otherwise is as described for apr_cstr_strtoui64(), + * including the upper limit of APR_INT64_MAX. + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_atoui64(apr_uint64_t *n, const char *str); + +/** + * Parse the C string @a str into an unsigned 32 bit number, and return + * it in @a *n. Assume that the number is represented in base 10. + * Raise an error if conversion fails (e.g. due to overflow). + * + * The behaviour otherwise is as described for apr_cstr_strtoui64(), + * including the upper limit of APR_INT64_MAX. + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_atoui(unsigned int *n, const char *str); + +/** + * Skip the common prefix @a prefix from the C string @a str, and return + * a pointer to the next character after the prefix. + * Return @c NULL if @a str does not start with @a prefix. + * + * @since New in 1.6. + */ +APR_DECLARE(const char *) apr_cstr_skip_prefix(const char *str, + const char *prefix); + +/** @} */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* SVN_STRING_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_date.h b/c/dependencies/windows/apr/x86/include/apr_date.h new file mode 100644 index 00000000..b098b542 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_date.h @@ -0,0 +1,106 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_DATE_H +#define APR_DATE_H + +/** + * @file apr_date.h + * @brief APR-UTIL date routines + */ + +/** + * @defgroup APR_Util_Date Date routines + * @ingroup APR_Util + * @{ + */ + +/* + * apr_date.h: prototypes for date parsing utility routines + */ + +#include "apu.h" +#include "apr_time.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** A bad date. */ +#define APR_DATE_BAD ((apr_time_t)0) + +/** + * Compare a string to a mask + * @param data The string to compare + * @param mask Mask characters (arbitrary maximum is 256 characters): + *
+ *   '\@' - uppercase letter
+ *   '\$' - lowercase letter
+ *   '\&' - hex digit
+ *   '#' - digit
+ *   '~' - digit or space
+ *   '*' - swallow remaining characters
+ * 
+ * @remark The mask tests for an exact match for any other character + * @return 1 if the string matches, 0 otherwise + */ +APU_DECLARE(int) apr_date_checkmask(const char *data, const char *mask); + +/** + * Parses an HTTP date in one of three standard forms: + *
+ *     Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
+ *     Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
+ *     Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format
+ * 
+ * @param date The date in one of the three formats above + * @return the apr_time_t number of microseconds since 1 Jan 1970 GMT, or + * 0 if this would be out of range or if the date is invalid. + */ +APU_DECLARE(apr_time_t) apr_date_parse_http(const char *date); + +/** + * Parses a string resembling an RFC 822 date. This is meant to be + * leinent in its parsing of dates. Hence, this will parse a wider + * range of dates than apr_date_parse_http. + * + * The prominent mailer (or poster, if mailer is unknown) that has + * been seen in the wild is included for the unknown formats. + *
+ *     Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
+ *     Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
+ *     Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format
+ *     Sun, 6 Nov 1994 08:49:37 GMT   ; RFC 822, updated by RFC 1123
+ *     Sun, 06 Nov 94 08:49:37 GMT    ; RFC 822
+ *     Sun, 6 Nov 94 08:49:37 GMT     ; RFC 822
+ *     Sun, 06 Nov 94 08:49 GMT       ; Unknown [drtr\@ast.cam.ac.uk] 
+ *     Sun, 6 Nov 94 08:49 GMT        ; Unknown [drtr\@ast.cam.ac.uk]
+ *     Sun, 06 Nov 94 8:49:37 GMT     ; Unknown [Elm 70.85]
+ *     Sun, 6 Nov 94 8:49:37 GMT      ; Unknown [Elm 70.85] 
+ * 
+ * + * @param date The date in one of the formats above + * @return the apr_time_t number of microseconds since 1 Jan 1970 GMT, or + * 0 if this would be out of range or if the date is invalid. + */ +APU_DECLARE(apr_time_t) apr_date_parse_rfc(const char *date); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_DATE_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_dbd.h b/c/dependencies/windows/apr/x86/include/apr_dbd.h new file mode 100644 index 00000000..9912612b --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_dbd.h @@ -0,0 +1,549 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* Overview of what this is and does: + * http://www.apache.org/~niq/dbd.html + */ + +#ifndef APR_DBD_H +#define APR_DBD_H + +#include "apu.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_dbd.h + * @brief APR-UTIL DBD library + */ +/** + * @defgroup APR_Util_DBD DBD routines + * @ingroup APR_Util + * @{ + */ + +/** + * Mapping of C to SQL types, used for prepared statements. + * @remarks + * For apr_dbd_p[v]query/select functions, in and out parameters are always + * const char * (i.e. regular nul terminated strings). LOB types are passed + * with four (4) arguments: payload, length, table and column, all as const + * char *, where table and column are reserved for future use by Oracle. + * @remarks + * For apr_dbd_p[v]bquery/select functions, in and out parameters are + * described next to each enumeration constant and are generally native binary + * types or some APR data type. LOB types are passed with four (4) arguments: + * payload (char*), length (apr_size_t*), table (char*) and column (char*). + * Table and column are reserved for future use by Oracle. + */ +typedef enum { + APR_DBD_TYPE_NONE, + APR_DBD_TYPE_TINY, /**< \%hhd : in, out: char* */ + APR_DBD_TYPE_UTINY, /**< \%hhu : in, out: unsigned char* */ + APR_DBD_TYPE_SHORT, /**< \%hd : in, out: short* */ + APR_DBD_TYPE_USHORT, /**< \%hu : in, out: unsigned short* */ + APR_DBD_TYPE_INT, /**< \%d : in, out: int* */ + APR_DBD_TYPE_UINT, /**< \%u : in, out: unsigned int* */ + APR_DBD_TYPE_LONG, /**< \%ld : in, out: long* */ + APR_DBD_TYPE_ULONG, /**< \%lu : in, out: unsigned long* */ + APR_DBD_TYPE_LONGLONG, /**< \%lld : in, out: apr_int64_t* */ + APR_DBD_TYPE_ULONGLONG, /**< \%llu : in, out: apr_uint64_t* */ + APR_DBD_TYPE_FLOAT, /**< \%f : in, out: float* */ + APR_DBD_TYPE_DOUBLE, /**< \%lf : in, out: double* */ + APR_DBD_TYPE_STRING, /**< \%s : in: char*, out: char** */ + APR_DBD_TYPE_TEXT, /**< \%pDt : in: char*, out: char** */ + APR_DBD_TYPE_TIME, /**< \%pDi : in: char*, out: char** */ + APR_DBD_TYPE_DATE, /**< \%pDd : in: char*, out: char** */ + APR_DBD_TYPE_DATETIME, /**< \%pDa : in: char*, out: char** */ + APR_DBD_TYPE_TIMESTAMP, /**< \%pDs : in: char*, out: char** */ + APR_DBD_TYPE_ZTIMESTAMP, /**< \%pDz : in: char*, out: char** */ + APR_DBD_TYPE_BLOB, /**< \%pDb : in: char* apr_size_t* char* char*, out: apr_bucket_brigade* */ + APR_DBD_TYPE_CLOB, /**< \%pDc : in: char* apr_size_t* char* char*, out: apr_bucket_brigade* */ + APR_DBD_TYPE_NULL /**< \%pDn : in: void*, out: void** */ +} apr_dbd_type_e; + +/* These are opaque structs. Instantiation is up to each backend */ +typedef struct apr_dbd_driver_t apr_dbd_driver_t; +typedef struct apr_dbd_t apr_dbd_t; +typedef struct apr_dbd_transaction_t apr_dbd_transaction_t; +typedef struct apr_dbd_results_t apr_dbd_results_t; +typedef struct apr_dbd_row_t apr_dbd_row_t; +typedef struct apr_dbd_prepared_t apr_dbd_prepared_t; + +/** apr_dbd_init: perform once-only initialisation. Call once only. + * + * @param pool - pool to register any shutdown cleanups, etc + */ +APU_DECLARE(apr_status_t) apr_dbd_init(apr_pool_t *pool); + +/** apr_dbd_get_driver: get the driver struct for a name + * + * @param pool - (process) pool to register cleanup + * @param name - driver name + * @param driver - pointer to driver struct. + * @return APR_SUCCESS for success + * @return APR_ENOTIMPL for no driver (when DSO not enabled) + * @return APR_EDSOOPEN if DSO driver file can't be opened + * @return APR_ESYMNOTFOUND if the driver file doesn't contain a driver + */ +APU_DECLARE(apr_status_t) apr_dbd_get_driver(apr_pool_t *pool, const char *name, + const apr_dbd_driver_t **driver); + +/** apr_dbd_open_ex: open a connection to a backend + * + * @param driver - driver struct. + * @param pool - working pool + * @param params - arguments to driver (implementation-dependent) + * @param handle - pointer to handle to return + * @param error - descriptive error. + * @return APR_SUCCESS for success + * @return APR_EGENERAL if driver exists but connection failed + * @remarks PostgreSQL: the params is passed directly to the PQconnectdb() + * function (check PostgreSQL documentation for more details on the syntax). + * @remarks SQLite2: the params is split on a colon, with the first part used + * as the filename and second part converted to an integer and used as file + * mode. + * @remarks SQLite3: the params is passed directly to the sqlite3_open() + * function as a filename to be opened (check SQLite3 documentation for more + * details). + * @remarks Oracle: the params can have "user", "pass", "dbname" and "server" + * keys, each followed by an equal sign and a value. Such key/value pairs can + * be delimited by space, CR, LF, tab, semicolon, vertical bar or comma. + * @remarks MySQL: the params can have "host", "port", "user", "pass", + * "dbname", "sock", "flags" "fldsz", "group" and "reconnect" keys, each + * followed by an equal sign and a value. Such key/value pairs can be + * delimited by space, CR, LF, tab, semicolon, vertical bar or comma. For + * now, "flags" can only recognise CLIENT_FOUND_ROWS (check MySQL manual for + * details). The value associated with "fldsz" determines maximum amount of + * memory (in bytes) for each of the fields in the result set of prepared + * statements. By default, this value is 1 MB. The value associated with + * "group" determines which group from configuration file to use (see + * MYSQL_READ_DEFAULT_GROUP option of mysql_options() in MySQL manual). + * Reconnect is set to 1 by default (i.e. true). + */ +APU_DECLARE(apr_status_t) apr_dbd_open_ex(const apr_dbd_driver_t *driver, + apr_pool_t *pool, const char *params, + apr_dbd_t **handle, + const char **error); + +/** apr_dbd_open: open a connection to a backend + * + * @param driver - driver struct. + * @param pool - working pool + * @param params - arguments to driver (implementation-dependent) + * @param handle - pointer to handle to return + * @return APR_SUCCESS for success + * @return APR_EGENERAL if driver exists but connection failed + * @see apr_dbd_open_ex + */ +APU_DECLARE(apr_status_t) apr_dbd_open(const apr_dbd_driver_t *driver, + apr_pool_t *pool, const char *params, + apr_dbd_t **handle); + +/** apr_dbd_close: close a connection to a backend + * + * @param driver - driver struct. + * @param handle - handle to close + * @return APR_SUCCESS for success or error status + */ +APU_DECLARE(apr_status_t) apr_dbd_close(const apr_dbd_driver_t *driver, + apr_dbd_t *handle); + +/* apr-function-shaped versions of things */ + +/** apr_dbd_name: get the name of the driver + * + * @param driver - the driver + * @return - name + */ +APU_DECLARE(const char*) apr_dbd_name(const apr_dbd_driver_t *driver); + +/** apr_dbd_native_handle: get native database handle of the underlying db + * + * @param driver - the driver + * @param handle - apr_dbd handle + * @return - native handle + */ +APU_DECLARE(void*) apr_dbd_native_handle(const apr_dbd_driver_t *driver, + apr_dbd_t *handle); + +/** check_conn: check status of a database connection + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection to check + * @return APR_SUCCESS or error + */ +APU_DECLARE(int) apr_dbd_check_conn(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle); + +/** apr_dbd_set_dbname: select database name. May be a no-op if not supported. + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param name - the database to select + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_set_dbname(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, const char *name); + +/** apr_dbd_transaction_start: start a transaction. May be a no-op. + * + * @param driver - the driver + * @param pool - a pool to use for error messages (if any). + * @param handle - the db connection + * @param trans - ptr to a transaction. May be null on entry + * @return 0 for success or error code + * @remarks Note that transaction modes, set by calling + * apr_dbd_transaction_mode_set(), will affect all query/select calls within + * a transaction. By default, any error in query/select during a transaction + * will cause the transaction to inherit the error code and any further + * query/select calls will fail immediately. Put transaction in "ignore + * errors" mode to avoid that. Use "rollback" mode to do explicit rollback. + */ +APU_DECLARE(int) apr_dbd_transaction_start(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_t *handle, + apr_dbd_transaction_t **trans); + +/** apr_dbd_transaction_end: end a transaction + * (commit on success, rollback on error). + * May be a no-op. + * + * @param driver - the driver + * @param handle - the db connection + * @param trans - the transaction. + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_transaction_end(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_transaction_t *trans); + +#define APR_DBD_TRANSACTION_COMMIT 0x00 /**< commit the transaction */ +#define APR_DBD_TRANSACTION_ROLLBACK 0x01 /**< rollback the transaction */ +#define APR_DBD_TRANSACTION_IGNORE_ERRORS 0x02 /**< ignore transaction errors */ + +/** apr_dbd_transaction_mode_get: get the mode of transaction + * + * @param driver - the driver + * @param trans - the transaction + * @return mode of transaction + */ +APU_DECLARE(int) apr_dbd_transaction_mode_get(const apr_dbd_driver_t *driver, + apr_dbd_transaction_t *trans); + +/** apr_dbd_transaction_mode_set: set the mode of transaction + * + * @param driver - the driver + * @param trans - the transaction + * @param mode - new mode of the transaction + * @return the mode of transaction in force after the call + */ +APU_DECLARE(int) apr_dbd_transaction_mode_set(const apr_dbd_driver_t *driver, + apr_dbd_transaction_t *trans, + int mode); + +/** apr_dbd_query: execute an SQL query that doesn't return a result set + * + * @param driver - the driver + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the SQL statement to execute + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_query(const apr_dbd_driver_t *driver, apr_dbd_t *handle, + int *nrows, const char *statement); + +/** apr_dbd_select: execute an SQL query that returns a result set + * + * @param driver - the driver + * @param pool - pool to allocate the result set + * @param handle - the connection + * @param res - pointer to result set pointer. May point to NULL on entry + * @param statement - the SQL statement to execute + * @param random - 1 to support random access to results (seek any row); + * 0 to support only looping through results in order + * (async access - faster) + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_select(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, apr_dbd_results_t **res, + const char *statement, int random); + +/** apr_dbd_num_cols: get the number of columns in a results set + * + * @param driver - the driver + * @param res - result set. + * @return number of columns + */ +APU_DECLARE(int) apr_dbd_num_cols(const apr_dbd_driver_t *driver, + apr_dbd_results_t *res); + +/** apr_dbd_num_tuples: get the number of rows in a results set + * of a synchronous select + * + * @param driver - the driver + * @param res - result set. + * @return number of rows, or -1 if the results are asynchronous + */ +APU_DECLARE(int) apr_dbd_num_tuples(const apr_dbd_driver_t *driver, + apr_dbd_results_t *res); + +/** apr_dbd_get_row: get a row from a result set + * + * @param driver - the driver + * @param pool - pool to allocate the row + * @param res - result set pointer + * @param row - pointer to row pointer. May point to NULL on entry + * @param rownum - row number (counting from 1), or -1 for "next row". + * Ignored if random access is not supported. + * @return 0 for success, -1 for rownum out of range or data finished + */ +APU_DECLARE(int) apr_dbd_get_row(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_results_t *res, apr_dbd_row_t **row, + int rownum); + +/** apr_dbd_get_entry: get an entry from a row + * + * @param driver - the driver + * @param row - row pointer + * @param col - entry number + * @return value from the row, or NULL if col is out of bounds. + */ +APU_DECLARE(const char*) apr_dbd_get_entry(const apr_dbd_driver_t *driver, + apr_dbd_row_t *row, int col); + +/** apr_dbd_get_name: get an entry name from a result set + * + * @param driver - the driver + * @param res - result set pointer + * @param col - entry number + * @return name of the entry, or NULL if col is out of bounds. + */ +APU_DECLARE(const char*) apr_dbd_get_name(const apr_dbd_driver_t *driver, + apr_dbd_results_t *res, int col); + + +/** apr_dbd_error: get current error message (if any) + * + * @param driver - the driver + * @param handle - the connection + * @param errnum - error code from operation that returned an error + * @return the database current error message, or message for errnum + * (implementation-dependent whether errnum is ignored) + */ +APU_DECLARE(const char*) apr_dbd_error(const apr_dbd_driver_t *driver, + apr_dbd_t *handle, int errnum); + +/** apr_dbd_escape: escape a string so it is safe for use in query/select + * + * @param driver - the driver + * @param pool - pool to alloc the result from + * @param string - the string to escape + * @param handle - the connection + * @return the escaped, safe string + */ +APU_DECLARE(const char*) apr_dbd_escape(const apr_dbd_driver_t *driver, + apr_pool_t *pool, const char *string, + apr_dbd_t *handle); + +/** apr_dbd_prepare: prepare a statement + * + * @param driver - the driver + * @param pool - pool to alloc the result from + * @param handle - the connection + * @param query - the SQL query + * @param label - A label for the prepared statement. + * use NULL for temporary prepared statements + * (eg within a Request in httpd) + * @param statement - statement to prepare. May point to null on entry. + * @return 0 for success or error code + * @remarks To specify parameters of the prepared query, use \%s, \%d etc. + * (see below for full list) in place of database specific parameter syntax + * (e.g. for PostgreSQL, this would be $1, $2, for SQLite3 this would be ? + * etc.). For instance: "SELECT name FROM customers WHERE name=%s" would be + * a query that this function understands. + * @remarks Here is the full list of format specifiers that this function + * understands and what they map to in SQL: \%hhd (TINY INT), \%hhu (UNSIGNED + * TINY INT), \%hd (SHORT), \%hu (UNSIGNED SHORT), \%d (INT), \%u (UNSIGNED + * INT), \%ld (LONG), \%lu (UNSIGNED LONG), \%lld (LONG LONG), \%llu + * (UNSIGNED LONG LONG), \%f (FLOAT, REAL), \%lf (DOUBLE PRECISION), \%s + * (VARCHAR), \%pDt (TEXT), \%pDi (TIME), \%pDd (DATE), \%pDa (DATETIME), + * \%pDs (TIMESTAMP), \%pDz (TIMESTAMP WITH TIME ZONE), \%pDb (BLOB), \%pDc + * (CLOB) and \%pDn (NULL). Not all databases have support for all these + * types, so the underlying driver will attempt the "best match" where + * possible. A \% followed by any letter not in the above list will be + * interpreted as VARCHAR (i.e. \%s). + */ +APU_DECLARE(int) apr_dbd_prepare(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, const char *query, + const char *label, + apr_dbd_prepared_t **statement); + + +/** apr_dbd_pquery: query using a prepared statement + args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param nargs - ignored (for backward compatibility only) + * @param args - args to prepared statement + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_pquery(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, int nargs, + const char **args); + +/** apr_dbd_pselect: select using a prepared statement + args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param nargs - ignored (for backward compatibility only) + * @param args - args to prepared statement + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_pselect(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, int random, + int nargs, const char **args); + +/** apr_dbd_pvquery: query using a prepared statement + args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param ... - varargs list + * @return 0 for success or error code + */ +APU_DECLARE_NONSTD(int) apr_dbd_pvquery(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, ...); + +/** apr_dbd_pvselect: select using a prepared statement + args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param ... - varargs list + * @return 0 for success or error code + */ +APU_DECLARE_NONSTD(int) apr_dbd_pvselect(const apr_dbd_driver_t *driver, + apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, + int random, ...); + +/** apr_dbd_pbquery: query using a prepared statement + binary args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_pbquery(const apr_dbd_driver_t *driver, + apr_pool_t *pool, apr_dbd_t *handle, + int *nrows, apr_dbd_prepared_t *statement, + const void **args); + +/** apr_dbd_pbselect: select using a prepared statement + binary args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_pbselect(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_t *handle, apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, int random, + const void **args); + +/** apr_dbd_pvbquery: query using a prepared statement + binary args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param ... - varargs list of binary args + * @return 0 for success or error code + */ +APU_DECLARE_NONSTD(int) apr_dbd_pvbquery(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, ...); + +/** apr_dbd_pvbselect: select using a prepared statement + binary args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param ... - varargs list of binary args + * @return 0 for success or error code + */ +APU_DECLARE_NONSTD(int) apr_dbd_pvbselect(const apr_dbd_driver_t *driver, + apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, + int random, ...); + +/** apr_dbd_datum_get: get a binary entry from a row + * + * @param driver - the driver + * @param row - row pointer + * @param col - entry number + * @param type - type of data to get + * @param data - pointer to data, allocated by the caller + * @return APR_SUCCESS on success, APR_ENOENT if data is NULL or APR_EGENERAL + */ +APU_DECLARE(apr_status_t) apr_dbd_datum_get(const apr_dbd_driver_t *driver, + apr_dbd_row_t *row, int col, + apr_dbd_type_e type, void *data); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/c/dependencies/windows/apr/x86/include/apr_dbm.h b/c/dependencies/windows/apr/x86/include/apr_dbm.h new file mode 100644 index 00000000..ad1b4f39 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_dbm.h @@ -0,0 +1,227 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_DBM_H +#define APR_DBM_H + +#include "apu.h" +#include "apr.h" +#include "apr_errno.h" +#include "apr_pools.h" +#include "apr_file_info.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_dbm.h + * @brief APR-UTIL DBM library + */ +/** + * @defgroup APR_Util_DBM DBM routines + * @ingroup APR_Util + * @{ + */ +/** + * Structure for referencing a dbm + */ +typedef struct apr_dbm_t apr_dbm_t; + +/** + * Structure for referencing the datum record within a dbm + */ +typedef struct +{ + /** pointer to the 'data' to retrieve/store in the DBM */ + char *dptr; + /** size of the 'data' to retrieve/store in the DBM */ + apr_size_t dsize; +} apr_datum_t; + +/* modes to open the DB */ +#define APR_DBM_READONLY 1 /**< open for read-only access */ +#define APR_DBM_READWRITE 2 /**< open for read-write access */ +#define APR_DBM_RWCREATE 3 /**< open for r/w, create if needed */ +#define APR_DBM_RWTRUNC 4 /**< open for r/w, truncating an existing + DB if present */ +/** + * Open a dbm file by file name and type of DBM + * @param dbm The newly opened database + * @param type The type of the DBM (not all may be available at run time) + *
+ *  db   for Berkeley DB files
+ *  gdbm for GDBM files
+ *  ndbm for NDBM files
+ *  sdbm for SDBM files (always available)
+ *  default for the default DBM type
+ *  
+ * @param name The dbm file name to open + * @param mode The flag value + *
+ *           APR_DBM_READONLY   open for read-only access
+ *           APR_DBM_READWRITE  open for read-write access
+ *           APR_DBM_RWCREATE   open for r/w, create if needed
+ *           APR_DBM_RWTRUNC    open for r/w, truncate if already there
+ * 
+ * @param perm Permissions to apply to if created + * @param cntxt The pool to use when creating the dbm + * @remark The dbm name may not be a true file name, as many dbm packages + * append suffixes for seperate data and index files. + * @bug In apr-util 0.9 and 1.x, the type arg was case insensitive. This + * was highly inefficient, and as of 2.x the dbm name must be provided in + * the correct case (lower case for all bundled providers) + */ + +APU_DECLARE(apr_status_t) apr_dbm_open_ex(apr_dbm_t **dbm, const char* type, + const char *name, + apr_int32_t mode, apr_fileperms_t perm, + apr_pool_t *cntxt); + + +/** + * Open a dbm file by file name + * @param dbm The newly opened database + * @param name The dbm file name to open + * @param mode The flag value + *
+ *           APR_DBM_READONLY   open for read-only access
+ *           APR_DBM_READWRITE  open for read-write access
+ *           APR_DBM_RWCREATE   open for r/w, create if needed
+ *           APR_DBM_RWTRUNC    open for r/w, truncate if already there
+ * 
+ * @param perm Permissions to apply to if created + * @param cntxt The pool to use when creating the dbm + * @remark The dbm name may not be a true file name, as many dbm packages + * append suffixes for seperate data and index files. + */ +APU_DECLARE(apr_status_t) apr_dbm_open(apr_dbm_t **dbm, const char *name, + apr_int32_t mode, apr_fileperms_t perm, + apr_pool_t *cntxt); + +/** + * Close a dbm file previously opened by apr_dbm_open + * @param dbm The database to close + */ +APU_DECLARE(void) apr_dbm_close(apr_dbm_t *dbm); + +/** + * Fetch a dbm record value by key + * @param dbm The database + * @param key The key datum to find this record + * @param pvalue The value datum retrieved for this record + */ +APU_DECLARE(apr_status_t) apr_dbm_fetch(apr_dbm_t *dbm, apr_datum_t key, + apr_datum_t *pvalue); +/** + * Store a dbm record value by key + * @param dbm The database + * @param key The key datum to store this record by + * @param value The value datum to store in this record + */ +APU_DECLARE(apr_status_t) apr_dbm_store(apr_dbm_t *dbm, apr_datum_t key, + apr_datum_t value); + +/** + * Delete a dbm record value by key + * @param dbm The database + * @param key The key datum of the record to delete + * @remark It is not an error to delete a non-existent record. + */ +APU_DECLARE(apr_status_t) apr_dbm_delete(apr_dbm_t *dbm, apr_datum_t key); + +/** + * Search for a key within the dbm + * @param dbm The database + * @param key The datum describing a key to test + */ +APU_DECLARE(int) apr_dbm_exists(apr_dbm_t *dbm, apr_datum_t key); + +/** + * Retrieve the first record key from a dbm + * @param dbm The database + * @param pkey The key datum of the first record + */ +APU_DECLARE(apr_status_t) apr_dbm_firstkey(apr_dbm_t *dbm, apr_datum_t *pkey); + +/** + * Retrieve the next record key from a dbm + * @param dbm The database + * @param pkey The key datum of the next record + */ +APU_DECLARE(apr_status_t) apr_dbm_nextkey(apr_dbm_t *dbm, apr_datum_t *pkey); + +/** + * Proactively toss any memory associated with the apr_datum_t. + * @param dbm The database + * @param data The datum to free. + */ +APU_DECLARE(void) apr_dbm_freedatum(apr_dbm_t *dbm, apr_datum_t data); + +/** + * Report more information when an apr_dbm function fails. + * @param dbm The database + * @param errcode A DBM-specific value for the error (for logging). If this + * isn't needed, it may be NULL. + * @param errbuf Location to store the error text + * @param errbufsize The size of the provided buffer + * @return The errbuf parameter, for convenience. + */ +APU_DECLARE(char *) apr_dbm_geterror(apr_dbm_t *dbm, int *errcode, + char *errbuf, apr_size_t errbufsize); +/** + * If the specified file/path were passed to apr_dbm_open(), return the + * actual file/path names which would be (created and) used. At most, two + * files may be used; used2 may be NULL if only one file is used. + * @param pool The pool for allocating used1 and used2. + * @param type The type of DBM you require info on @see apr_dbm_open_ex + * @param pathname The path name to generate used-names from. + * @param used1 The first pathname used by the apr_dbm implementation. + * @param used2 The second pathname used by apr_dbm. If only one file is + * used by the specific implementation, this will be set to NULL. + * @return An error if the specified type is invalid. + * @remark The dbm file(s) don't need to exist. This function only manipulates + * the pathnames. + */ +APU_DECLARE(apr_status_t) apr_dbm_get_usednames_ex(apr_pool_t *pool, + const char *type, + const char *pathname, + const char **used1, + const char **used2); + +/** + * If the specified file/path were passed to apr_dbm_open(), return the + * actual file/path names which would be (created and) used. At most, two + * files may be used; used2 may be NULL if only one file is used. + * @param pool The pool for allocating used1 and used2. + * @param pathname The path name to generate used-names from. + * @param used1 The first pathname used by the apr_dbm implementation. + * @param used2 The second pathname used by apr_dbm. If only one file is + * used by the specific implementation, this will be set to NULL. + * @remark The dbm file(s) don't need to exist. This function only manipulates + * the pathnames. + */ +APU_DECLARE(void) apr_dbm_get_usednames(apr_pool_t *pool, + const char *pathname, + const char **used1, + const char **used2); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_DBM_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_dso.h b/c/dependencies/windows/apr/x86/include/apr_dso.h new file mode 100644 index 00000000..ac701cfd --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_dso.h @@ -0,0 +1,94 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_DSO_DOT_H +#define APR_DSO_DOT_H + +/** + * @file apr_dso.h + * @brief APR Dynamic Object Handling Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_dso Dynamic Object Handling + * @ingroup APR + * @{ + */ + +#if APR_HAS_DSO || defined(DOXYGEN) + +/** + * Structure for referencing dynamic objects + */ +typedef struct apr_dso_handle_t apr_dso_handle_t; + +/** + * Structure for referencing symbols from dynamic objects + */ +typedef void * apr_dso_handle_sym_t; + +/** + * Load a DSO library. + * @param res_handle Location to store new handle for the DSO. + * @param path Path to the DSO library + * @param ctx Pool to use. + * @bug We aught to provide an alternative to RTLD_GLOBAL, which + * is the only supported method of loading DSOs today. + */ +APR_DECLARE(apr_status_t) apr_dso_load(apr_dso_handle_t **res_handle, + const char *path, apr_pool_t *ctx); + +/** + * Close a DSO library. + * @param handle handle to close. + */ +APR_DECLARE(apr_status_t) apr_dso_unload(apr_dso_handle_t *handle); + +/** + * Load a symbol from a DSO handle. + * @param ressym Location to store the loaded symbol + * @param handle handle to load the symbol from. + * @param symname Name of the symbol to load. + */ +APR_DECLARE(apr_status_t) apr_dso_sym(apr_dso_handle_sym_t *ressym, + apr_dso_handle_t *handle, + const char *symname); + +/** + * Report more information when a DSO function fails. + * @param dso The dso handle that has been opened + * @param buf Location to store the dso error + * @param bufsize The size of the provided buffer + */ +APR_DECLARE(const char *) apr_dso_error(apr_dso_handle_t *dso, char *buf, apr_size_t bufsize); + +#endif /* APR_HAS_DSO */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/c/dependencies/windows/apr/x86/include/apr_encode.h b/c/dependencies/windows/apr/x86/include/apr_encode.h new file mode 100644 index 00000000..20fc932f --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_encode.h @@ -0,0 +1,569 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_encode.h + * @brief APR-UTIL Encoding + */ +#ifndef APR_ENCODE_H +#define APR_ENCODE_H + +#include "apr.h" +#include "apr_general.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Encode Base64/Base64Url/Base32/Base32Hex/Base16 Encoding + * @ingroup APR_Util + * @{ + */ + +/** + * RFC4648 and RFC7515 compliant BASE64, BASE64URL, BASE32, BASE32HEX + * and BASE16 encode/decode functions. + * + * The following encodings are supported: + * + * - Base 64 Encoding + * + * o Use flag APR_ENCODE_NONE + * o https://tools.ietf.org/html/rfc4648#section-4 + * + * - Base 64 Encoding with URL and Filename Safe Alphabet + * + * o Use flag APR_ENCODE_URL + * o https://tools.ietf.org/html/rfc4648#section-5 + * + * - Base 64 URL Encoding without Padding + * + * o Use flag APR_ENCODE_BASE64URL + * o https://tools.ietf.org/html/rfc7515#appendix-C + * + * - Base 32 Encoding + * + * o Use flag APR_ENCODE_NONE + * o https://tools.ietf.org/html/rfc4648#section-6 + * + * - Base 32 Encoding with Extended Hex Alphabet + * + * o Use flag APR_ENCODE_BASE32HEX + * o https://tools.ietf.org/html/rfc4648#section-7 + * + * - Base 16 Encoding + * + * o Use flags APR_ENCODE_NONE/APR_ENCODE_COLON + * o https://tools.ietf.org/html/rfc4648#section-8 + * + * If a non valid character of any kind including whitespace is passed to any + * of the decoder functions, APR_BADCH will be returned. In this case decoding + * will still take place, but the results can not be trusted. + * + * If APR_ENCODE_RELAXED is passed to the decoder functions, decoding will be + * attempted up until the first non valid character. If this results in an + * invalid state in the decoder, such as but not limited to an odd number of + * base16 characters, APR_BADCH will still be returned. + * + * If APR_ENCODE_RELAXED is not passed to a decoder function, the decoding will + * be done in constant time regardless of whether the result returns APR_SUCCESS + * or APR_BADCH. + * + * If the dest parameter is NULL, the maximum theoretical buffer size is + * returned in the len field, including space for a terminating zero character + * if the destination is a string. This value can be used to allocate buffers + * of a suitable safe size. + * + * If the dest parameter is provided, the encoding or decoding will take place, + * and the actual number of characters written is returned in the len field, + * ignoring any terminating zero. + * + * Plain strings are not assumed '\0' terminated unless APR_ENCODE_STRING is + * provided. + * + */ + +/** + * When passing a string to one of the encode functions, this value can be + * passed to indicate a string-valued key, and have the length computed + * automatically. + */ +#define APR_ENCODE_STRING (-1) + +/** + * Generate RFC4648 base16/base32/base64. + */ +#define APR_ENCODE_NONE 0 + +/** + * If relaxed, decode up until the first non base16/base32/base64 character. + */ +#define APR_ENCODE_RELAXED 1 + +/** + * Omit the padding character (=) while encoding. + */ +#define APR_ENCODE_NOPADDING 2 + +/** + * Generate RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet + */ +#define APR_ENCODE_URL 4 + +/** + * Generate RFC7515 BASE64URL + */ +#define APR_ENCODE_BASE64URL (APR_ENCODE_NOPADDING | APR_ENCODE_URL) + +/** + * Generate base32hex encoding instead of base32 encoding + */ +#define APR_ENCODE_BASE32HEX 8 + +/** + * Generate base16 with colons between each token. + */ +#define APR_ENCODE_COLON 16 + +/** + * Generate base16 with lower case characters. + */ +#define APR_ENCODE_LOWER 32 + +/** + * Convert text data to base64. + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 64 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_URL, + * use RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet. + * If APR_ENCODE_BASE64URL, use RFC7515 base64url Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination string, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base64(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert binary data to base64. + * @param dest The destination string, can be NULL. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 64 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_URL, + * use RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet. + * If APR_ENCODE_BASE64URL, use RFC7515 base64url Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination string, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base64_binary(char *dest, const unsigned char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert text data to base64, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 64 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_URL, + * use RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet. + * If APR_ENCODE_BASE64URL, use RFC7515 base64url Encoding. + * @param len If present, returns the number of characters written excluding + * the zero pad. + * @return A zero padded string allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *)apr_pencode_base64(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len)__attribute__((nonnull(1))); + +/** + * Convert binary data to base64, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 64 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_URL, + * use RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet. + * If APR_ENCODE_BASE64URL, use RFC7515 base64url Encoding. + * @param len If present, returns the number of characters written excluding + * the zero pad. + * @return A zero padded string allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *)apr_pencode_base64_binary(apr_pool_t * p, const unsigned char *src, + apr_ssize_t slen, int flags, apr_size_t * len)__attribute__((nonnull(1))); + +/** + * Convert base64 or base64url with or without padding to text data. + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, attempt to decode the full original buffer, + * and return NULL if any bad character is detected. If APR_ENCODE_RELAXED, + * decode until the first non base64/base64url character. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination string, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL, or APR_BADCH + * if a non hex character is present. + */ +APR_DECLARE(apr_status_t) apr_decode_base64(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base64 or base64url with or without padding to binary data. + * @param dest The destination buffer, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, attempt to decode the full original buffer, + * and return NULL if any bad character is detected. If APR_ENCODE_RELAXED, + * decode until the first non base64/base64url character. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the src was NULL, or APR_BADCH + * if a non base64 character is present. + */ +APR_DECLARE(apr_status_t) apr_decode_base64_binary(unsigned char *dest, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base64 or base64url with or without padding to text data, and + * return the results from a pool. + * @param p Pool to allocate from. + * @param src The base64 string to decode. + * @param slen The length of the base64 string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, attempt to decode the full original buffer, + * and return NULL if any bad character is detected. If APR_ENCODE_RELAXED, + * decode until the first non base64/base64url character. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A string allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const char *)apr_pdecode_base64(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert base64 or base64url with or without padding to binary data, and + * return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, attempt to decode the full original buffer, + * and return NULL if any bad character is detected. If APR_ENCODE_RELAXED, + * decode until the first non base64/base64url character. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A buffer allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const unsigned char *)apr_pdecode_base64_binary(apr_pool_t * p, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert text data to base32. + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 32 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_BASE32HEX, + * use RFC4648 base32hex Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination string, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base32(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert binary data to base32. + * @param dest The destination string, can be NULL. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 32 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_BASE32HEX, + * use RFC4648 base32hex Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination string, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base32_binary(char *dest, const unsigned char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert text data to base32, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 32 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_BASE32HEX, + * use RFC4648 base32hex Encoding. + * @param len If present, returns the number of characters written excluding + * the zero pad. + * @return A zero padded string allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *)apr_pencode_base32(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert binary data to base32, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 32 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_BASE32HEX, + * use RFC7515 base32hex Encoding. + * @param len If present, returns the number of characters written excluding + * the zero pad. + * @return A zero padded string allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *)apr_pencode_base32_binary(apr_pool_t * p, const unsigned char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert base32 or base32hex with or without padding to text data. + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 32 Encoding. If + * APR_ENCODE_BASE32HEX, use RFC4648 base32hex Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL, or APR_BADCH + * if a non base32 character is present. + */ +APR_DECLARE(apr_status_t) apr_decode_base32(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base32 or base32hex with or without padding to binary data. + * @param dest The destination buffer, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 32 Encoding. If + * APR_ENCODE_BASE32HEX, use RFC4648 base32hex Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the src was NULL, or APR_BADCH + * if a non base32 character is present. + */ +APR_DECLARE(apr_status_t) apr_decode_base32_binary(unsigned char *dest, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base32 or base32hex with or without padding to text data, and + * return the results from a pool. + * @param p Pool to allocate from. + * @param src The base32 string to decode. + * @param slen The length of the base32 string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 32 Encoding. If + * APR_ENCODE_BASE32HEX, use RFC4648 base32hex Encoding. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A string allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const char *)apr_pdecode_base32(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert base32 or base32hex with or without padding to binary data, and + * return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 32 Encoding. If + * APR_ENCODE_BASE32HEX, use RFC4648 base32hex Encoding. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A buffer allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const unsigned char *)apr_pdecode_base32_binary(apr_pool_t * p, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert text data to base16 (hex). + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, separate each token with a colon. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base16(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert binary data to base16 (hex). + * @param dest The destination string, can be NULL. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, separate each token with a colon. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base16_binary(char *dest, + const unsigned char *src, apr_ssize_t slen, int flags, + apr_size_t * len); + +/** + * Convert text data to base16 (hex), and return the results from a + * pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, separate each token with a colon. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A string allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const char *)apr_pencode_base16(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert binary data to base16 (hex), and return the results from a + * pool. + * @param p Pool to allocate from. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, separate each token with a colon. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A string allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const char *)apr_pencode_base16_binary(apr_pool_t * p, + const unsigned char *src, apr_ssize_t slen, + int flags, apr_size_t * len)__attribute__((nonnull(1))); + +/** + * Convert base16 (hex) to text data. + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, allow tokens to be separated with a colon. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL, or APR_BADCH + * if a non hex character is present. A zero pad is appended to the buffer. + */ +APR_DECLARE(apr_status_t) apr_decode_base16(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base16 (hex) to binary data. + * @param dest The destination buffer, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, allow tokens to be separated with a colon. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL, or APR_BADCH + * if a non hex character is present. No zero pad is written to the buffer. + */ +APR_DECLARE(apr_status_t) apr_decode_base16_binary(unsigned char *dest, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base16 (hex) and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, allow tokens to be separated with a colon. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A buffer allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const char *)apr_pdecode_base16(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert base16 (hex) to binary data, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, allow tokens to be separated with a colon. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A buffer allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const unsigned char *)apr_pdecode_base16_binary(apr_pool_t * p, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ENCODE_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_env.h b/c/dependencies/windows/apr/x86/include/apr_env.h new file mode 100644 index 00000000..85ab6704 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_env.h @@ -0,0 +1,67 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ENV_H +#define APR_ENV_H +/** + * @file apr_env.h + * @brief APR Environment functions + */ +#include "apr_errno.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_env Functions for manipulating the environment + * @ingroup APR + * @{ + */ + +/** + * Get the value of an environment variable + * @param value the returned value, allocated from @a pool + * @param envvar the name of the environment variable + * @param pool where to allocate @a value and any temporary storage from + */ +APR_DECLARE(apr_status_t) apr_env_get(char **value, const char *envvar, + apr_pool_t *pool); + +/** + * Set the value of an environment variable + * @param envvar the name of the environment variable + * @param value the value to set + * @param pool where to allocate temporary storage from + */ +APR_DECLARE(apr_status_t) apr_env_set(const char *envvar, const char *value, + apr_pool_t *pool); + +/** + * Delete a variable from the environment + * @param envvar the name of the environment variable + * @param pool where to allocate temporary storage from + */ +APR_DECLARE(apr_status_t) apr_env_delete(const char *envvar, apr_pool_t *pool); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_ENV_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_errno.h b/c/dependencies/windows/apr/x86/include/apr_errno.h new file mode 100644 index 00000000..8fa6628b --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_errno.h @@ -0,0 +1,1342 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ERRNO_H +#define APR_ERRNO_H + +/** + * @file apr_errno.h + * @brief APR Error Codes + */ + +#include "apr.h" + +#if APR_HAVE_ERRNO_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_errno Error Codes + * @ingroup APR + * @{ + */ + +/** + * Type for specifying an error or status code. + */ +typedef int apr_status_t; + +/** + * Return a human readable string describing the specified error. + * @param statcode The error code to get a string for. + * @param buf A buffer to hold the error string. + * @param bufsize Size of the buffer to hold the string. + */ +APR_DECLARE(char *) apr_strerror(apr_status_t statcode, char *buf, + apr_size_t bufsize); + +#if defined(DOXYGEN) +/** + * @def APR_FROM_OS_ERROR(os_err_type syserr) + * Fold a platform specific error into an apr_status_t code. + * @return apr_status_t + * @param e The platform os error code. + * @warning macro implementation; the syserr argument may be evaluated + * multiple times. + */ +#define APR_FROM_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e + APR_OS_START_SYSERR) + +/** + * @def APR_TO_OS_ERROR(apr_status_t statcode) + * @return os_err_type + * Fold an apr_status_t code back to the native platform defined error. + * @param e The apr_status_t folded platform os error code. + * @warning macro implementation; the statcode argument may be evaluated + * multiple times. If the statcode was not created by apr_get_os_error + * or APR_FROM_OS_ERROR, the results are undefined. + */ +#define APR_TO_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e - APR_OS_START_SYSERR) + +/** @def apr_get_os_error() + * @return apr_status_t the last platform error, folded into apr_status_t, on most platforms + * @remark This retrieves errno, or calls a GetLastError() style function, and + * folds it with APR_FROM_OS_ERROR. Some platforms (such as OS2) have no + * such mechanism, so this call may be unsupported. Do NOT use this + * call for socket errors from socket, send, recv etc! + */ + +/** @def apr_set_os_error(e) + * Reset the last platform error, unfolded from an apr_status_t, on some platforms + * @param e The OS error folded in a prior call to APR_FROM_OS_ERROR() + * @warning This is a macro implementation; the statcode argument may be evaluated + * multiple times. If the statcode was not created by apr_get_os_error + * or APR_FROM_OS_ERROR, the results are undefined. This macro sets + * errno, or calls a SetLastError() style function, unfolding statcode + * with APR_TO_OS_ERROR. Some platforms (such as OS2) have no such + * mechanism, so this call may be unsupported. + */ + +/** @def apr_get_netos_error() + * Return the last socket error, folded into apr_status_t, on all platforms + * @remark This retrieves errno or calls a GetLastSocketError() style function, + * and folds it with APR_FROM_OS_ERROR. + */ + +/** @def apr_set_netos_error(e) + * Reset the last socket error, unfolded from an apr_status_t + * @param e The socket error folded in a prior call to APR_FROM_OS_ERROR() + * @warning This is a macro implementation; the statcode argument may be evaluated + * multiple times. If the statcode was not created by apr_get_os_error + * or APR_FROM_OS_ERROR, the results are undefined. This macro sets + * errno, or calls a WSASetLastError() style function, unfolding + * socketcode with APR_TO_OS_ERROR. + */ + +#endif /* defined(DOXYGEN) */ + +/** + * APR_OS_START_ERROR is where the APR specific error values start. + */ +#define APR_OS_START_ERROR 20000 +/** + * APR_OS_ERRSPACE_SIZE is the maximum number of errors you can fit + * into one of the error/status ranges below -- except for + * APR_OS_START_USERERR, which see. + */ +#define APR_OS_ERRSPACE_SIZE 50000 +/** + * APR_UTIL_ERRSPACE_SIZE is the size of the space that is reserved for + * use within apr-util. This space is reserved above that used by APR + * internally. + * @note This number MUST be smaller than APR_OS_ERRSPACE_SIZE by a + * large enough amount that APR has sufficient room for its + * codes. + */ +#define APR_UTIL_ERRSPACE_SIZE 20000 +/** + * APR_OS_START_STATUS is where the APR specific status codes start. + */ +#define APR_OS_START_STATUS (APR_OS_START_ERROR + APR_OS_ERRSPACE_SIZE) +/** + * APR_UTIL_START_STATUS is where APR-Util starts defining its + * status codes. + */ +#define APR_UTIL_START_STATUS (APR_OS_START_STATUS + \ + (APR_OS_ERRSPACE_SIZE - APR_UTIL_ERRSPACE_SIZE)) +/** + * APR_OS_START_USERERR are reserved for applications that use APR that + * layer their own error codes along with APR's. Note that the + * error immediately following this one is set ten times farther + * away than usual, so that users of apr have a lot of room in + * which to declare custom error codes. + * + * In general applications should try and create unique error codes. To try + * and assist in finding suitable ranges of numbers to use, the following + * ranges are known to be used by the listed applications. If your + * application defines error codes please advise the range of numbers it + * uses to dev@apr.apache.org for inclusion in this list. + * + * Ranges shown are in relation to APR_OS_START_USERERR + * + * Subversion - Defined ranges, of less than 100, at intervals of 5000 + * starting at an offset of 5000, e.g. + * +5000 to 5100, +10000 to 10100 + * + * Apache HTTPD - +2000 to 2999 + */ +#define APR_OS_START_USERERR (APR_OS_START_STATUS + APR_OS_ERRSPACE_SIZE) +/** + * APR_OS_START_USEERR is obsolete, defined for compatibility only. + * Use APR_OS_START_USERERR instead. + */ +#define APR_OS_START_USEERR APR_OS_START_USERERR +/** + * APR_OS_START_CANONERR is where APR versions of errno values are defined + * on systems which don't have the corresponding errno. + */ +#define APR_OS_START_CANONERR (APR_OS_START_USERERR \ + + (APR_OS_ERRSPACE_SIZE * 10)) +/** + * APR_OS_START_EAIERR folds EAI_ error codes from getaddrinfo() into + * apr_status_t values. + */ +#define APR_OS_START_EAIERR (APR_OS_START_CANONERR + APR_OS_ERRSPACE_SIZE) +/** + * APR_OS_START_SYSERR folds platform-specific system error values into + * apr_status_t values. + */ +#define APR_OS_START_SYSERR (APR_OS_START_EAIERR + APR_OS_ERRSPACE_SIZE) + +/** + * @defgroup APR_ERROR_map APR Error Space + *
+ * The following attempts to show the relation of the various constants
+ * used for mapping APR Status codes.
+ *
+ *       0
+ *
+ *  20,000     APR_OS_START_ERROR
+ *
+ *         + APR_OS_ERRSPACE_SIZE (50,000)
+ *
+ *  70,000      APR_OS_START_STATUS
+ *
+ *         + APR_OS_ERRSPACE_SIZE - APR_UTIL_ERRSPACE_SIZE (30,000)
+ *
+ * 100,000      APR_UTIL_START_STATUS
+ *
+ *         + APR_UTIL_ERRSPACE_SIZE (20,000)
+ *
+ * 120,000      APR_OS_START_USERERR
+ *
+ *         + 10 x APR_OS_ERRSPACE_SIZE (50,000 * 10)
+ *
+ * 620,000      APR_OS_START_CANONERR
+ *
+ *         + APR_OS_ERRSPACE_SIZE (50,000)
+ *
+ * 670,000      APR_OS_START_EAIERR
+ *
+ *         + APR_OS_ERRSPACE_SIZE (50,000)
+ *
+ * 720,000      APR_OS_START_SYSERR
+ *
+ * 
+ */ + +/** no error. */ +#define APR_SUCCESS 0 + +/** + * @defgroup APR_Error APR Error Values + *
+ * APR ERROR VALUES
+ * APR_ENOSTAT      APR was unable to perform a stat on the file
+ * APR_ENOPOOL      APR was not provided a pool with which to allocate memory
+ * APR_EBADDATE     APR was given an invalid date
+ * APR_EINVALSOCK   APR was given an invalid socket
+ * APR_ENOPROC      APR was not given a process structure
+ * APR_ENOTIME      APR was not given a time structure
+ * APR_ENODIR       APR was not given a directory structure
+ * APR_ENOLOCK      APR was not given a lock structure
+ * APR_ENOPOLL      APR was not given a poll structure
+ * APR_ENOSOCKET    APR was not given a socket
+ * APR_ENOTHREAD    APR was not given a thread structure
+ * APR_ENOTHDKEY    APR was not given a thread key structure
+ * APR_ENOSHMAVAIL  There is no more shared memory available
+ * APR_EDSOOPEN     APR was unable to open the dso object.  For more
+ *                  information call apr_dso_error().
+ * APR_EGENERAL     General failure (specific information not available)
+ * APR_EBADIP       The specified IP address is invalid
+ * APR_EBADMASK     The specified netmask is invalid
+ * APR_ESYMNOTFOUND Could not find the requested symbol
+ * APR_ENOTENOUGHENTROPY Not enough entropy to continue
+ * 
+ * + *
+ * APR STATUS VALUES
+ * APR_INCHILD        Program is currently executing in the child
+ * APR_INPARENT       Program is currently executing in the parent
+ * APR_DETACH         The thread is detached
+ * APR_NOTDETACH      The thread is not detached
+ * APR_CHILD_DONE     The child has finished executing
+ * APR_CHILD_NOTDONE  The child has not finished executing
+ * APR_TIMEUP         The operation did not finish before the timeout
+ * APR_INCOMPLETE     The operation was incomplete although some processing
+ *                    was performed and the results are partially valid
+ * APR_BADCH          Getopt found an option not in the option string
+ * APR_BADARG         Getopt found an option that is missing an argument
+ *                    and an argument was specified in the option string
+ * APR_EOF            APR has encountered the end of the file
+ * APR_NOTFOUND       APR was unable to find the socket in the poll structure
+ * APR_ANONYMOUS      APR is using anonymous shared memory
+ * APR_FILEBASED      APR is using a file name as the key to the shared memory
+ * APR_KEYBASED       APR is using a shared key as the key to the shared memory
+ * APR_EINIT          Ininitalizer value.  If no option has been found, but
+ *                    the status variable requires a value, this should be used
+ * APR_ENOTIMPL       The APR function has not been implemented on this
+ *                    platform, either because nobody has gotten to it yet,
+ *                    or the function is impossible on this platform.
+ * APR_EMISMATCH      Two passwords do not match.
+ * APR_EABSOLUTE      The given path was absolute.
+ * APR_ERELATIVE      The given path was relative.
+ * APR_EINCOMPLETE    The given path was neither relative nor absolute.
+ * APR_EABOVEROOT     The given path was above the root path.
+ * APR_EBUSY          The given lock was busy.
+ * APR_EPROC_UNKNOWN  The given process wasn't recognized by APR
+ * 
+ * @{ + */ +/** @see APR_STATUS_IS_ENOSTAT */ +#define APR_ENOSTAT (APR_OS_START_ERROR + 1) +/** @see APR_STATUS_IS_ENOPOOL */ +#define APR_ENOPOOL (APR_OS_START_ERROR + 2) +/* empty slot: +3 */ +/** @see APR_STATUS_IS_EBADDATE */ +#define APR_EBADDATE (APR_OS_START_ERROR + 4) +/** @see APR_STATUS_IS_EINVALSOCK */ +#define APR_EINVALSOCK (APR_OS_START_ERROR + 5) +/** @see APR_STATUS_IS_ENOPROC */ +#define APR_ENOPROC (APR_OS_START_ERROR + 6) +/** @see APR_STATUS_IS_ENOTIME */ +#define APR_ENOTIME (APR_OS_START_ERROR + 7) +/** @see APR_STATUS_IS_ENODIR */ +#define APR_ENODIR (APR_OS_START_ERROR + 8) +/** @see APR_STATUS_IS_ENOLOCK */ +#define APR_ENOLOCK (APR_OS_START_ERROR + 9) +/** @see APR_STATUS_IS_ENOPOLL */ +#define APR_ENOPOLL (APR_OS_START_ERROR + 10) +/** @see APR_STATUS_IS_ENOSOCKET */ +#define APR_ENOSOCKET (APR_OS_START_ERROR + 11) +/** @see APR_STATUS_IS_ENOTHREAD */ +#define APR_ENOTHREAD (APR_OS_START_ERROR + 12) +/** @see APR_STATUS_IS_ENOTHDKEY */ +#define APR_ENOTHDKEY (APR_OS_START_ERROR + 13) +/** @see APR_STATUS_IS_EGENERAL */ +#define APR_EGENERAL (APR_OS_START_ERROR + 14) +/** @see APR_STATUS_IS_ENOSHMAVAIL */ +#define APR_ENOSHMAVAIL (APR_OS_START_ERROR + 15) +/** @see APR_STATUS_IS_EBADIP */ +#define APR_EBADIP (APR_OS_START_ERROR + 16) +/** @see APR_STATUS_IS_EBADMASK */ +#define APR_EBADMASK (APR_OS_START_ERROR + 17) +/* empty slot: +18 */ +/** @see APR_STATUS_IS_EDSOPEN */ +#define APR_EDSOOPEN (APR_OS_START_ERROR + 19) +/** @see APR_STATUS_IS_EABSOLUTE */ +#define APR_EABSOLUTE (APR_OS_START_ERROR + 20) +/** @see APR_STATUS_IS_ERELATIVE */ +#define APR_ERELATIVE (APR_OS_START_ERROR + 21) +/** @see APR_STATUS_IS_EINCOMPLETE */ +#define APR_EINCOMPLETE (APR_OS_START_ERROR + 22) +/** @see APR_STATUS_IS_EABOVEROOT */ +#define APR_EABOVEROOT (APR_OS_START_ERROR + 23) +/** @see APR_STATUS_IS_EBADPATH */ +#define APR_EBADPATH (APR_OS_START_ERROR + 24) +/** @see APR_STATUS_IS_EPATHWILD */ +#define APR_EPATHWILD (APR_OS_START_ERROR + 25) +/** @see APR_STATUS_IS_ESYMNOTFOUND */ +#define APR_ESYMNOTFOUND (APR_OS_START_ERROR + 26) +/** @see APR_STATUS_IS_EPROC_UNKNOWN */ +#define APR_EPROC_UNKNOWN (APR_OS_START_ERROR + 27) +/** @see APR_STATUS_IS_ENOTENOUGHENTROPY */ +#define APR_ENOTENOUGHENTROPY (APR_OS_START_ERROR + 28) +/** @} */ + +/** + * @defgroup APR_STATUS_IS Status Value Tests + * @warning For any particular error condition, more than one of these tests + * may match. This is because platform-specific error codes may not + * always match the semantics of the POSIX codes these tests (and the + * corresponding APR error codes) are named after. A notable example + * are the APR_STATUS_IS_ENOENT and APR_STATUS_IS_ENOTDIR tests on + * Win32 platforms. The programmer should always be aware of this and + * adjust the order of the tests accordingly. + * @{ + */ +/** + * APR was unable to perform a stat on the file + * @warning always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_ENOSTAT(s) ((s) == APR_ENOSTAT) +/** + * APR was not provided a pool with which to allocate memory + * @warning always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_ENOPOOL(s) ((s) == APR_ENOPOOL) +/** APR was given an invalid date */ +#define APR_STATUS_IS_EBADDATE(s) ((s) == APR_EBADDATE) +/** APR was given an invalid socket */ +#define APR_STATUS_IS_EINVALSOCK(s) ((s) == APR_EINVALSOCK) +/** APR was not given a process structure */ +#define APR_STATUS_IS_ENOPROC(s) ((s) == APR_ENOPROC) +/** APR was not given a time structure */ +#define APR_STATUS_IS_ENOTIME(s) ((s) == APR_ENOTIME) +/** APR was not given a directory structure */ +#define APR_STATUS_IS_ENODIR(s) ((s) == APR_ENODIR) +/** APR was not given a lock structure */ +#define APR_STATUS_IS_ENOLOCK(s) ((s) == APR_ENOLOCK) +/** APR was not given a poll structure */ +#define APR_STATUS_IS_ENOPOLL(s) ((s) == APR_ENOPOLL) +/** APR was not given a socket */ +#define APR_STATUS_IS_ENOSOCKET(s) ((s) == APR_ENOSOCKET) +/** APR was not given a thread structure */ +#define APR_STATUS_IS_ENOTHREAD(s) ((s) == APR_ENOTHREAD) +/** APR was not given a thread key structure */ +#define APR_STATUS_IS_ENOTHDKEY(s) ((s) == APR_ENOTHDKEY) +/** Generic Error which can not be put into another spot */ +#define APR_STATUS_IS_EGENERAL(s) ((s) == APR_EGENERAL) +/** There is no more shared memory available */ +#define APR_STATUS_IS_ENOSHMAVAIL(s) ((s) == APR_ENOSHMAVAIL) +/** The specified IP address is invalid */ +#define APR_STATUS_IS_EBADIP(s) ((s) == APR_EBADIP) +/** The specified netmask is invalid */ +#define APR_STATUS_IS_EBADMASK(s) ((s) == APR_EBADMASK) +/* empty slot: +18 */ +/** + * APR was unable to open the dso object. + * For more information call apr_dso_error(). + */ +#if defined(WIN32) +#define APR_STATUS_IS_EDSOOPEN(s) ((s) == APR_EDSOOPEN \ + || APR_TO_OS_ERROR(s) == ERROR_MOD_NOT_FOUND) +#else +#define APR_STATUS_IS_EDSOOPEN(s) ((s) == APR_EDSOOPEN) +#endif +/** The given path was absolute. */ +#define APR_STATUS_IS_EABSOLUTE(s) ((s) == APR_EABSOLUTE) +/** The given path was relative. */ +#define APR_STATUS_IS_ERELATIVE(s) ((s) == APR_ERELATIVE) +/** The given path was neither relative nor absolute. */ +#define APR_STATUS_IS_EINCOMPLETE(s) ((s) == APR_EINCOMPLETE) +/** The given path was above the root path. */ +#define APR_STATUS_IS_EABOVEROOT(s) ((s) == APR_EABOVEROOT) +/** The given path was bad. */ +#define APR_STATUS_IS_EBADPATH(s) ((s) == APR_EBADPATH) +/** The given path contained wildcards. */ +#define APR_STATUS_IS_EPATHWILD(s) ((s) == APR_EPATHWILD) +/** Could not find the requested symbol. + * For more information call apr_dso_error(). + */ +#if defined(WIN32) +#define APR_STATUS_IS_ESYMNOTFOUND(s) ((s) == APR_ESYMNOTFOUND \ + || APR_TO_OS_ERROR(s) == ERROR_PROC_NOT_FOUND) +#else +#define APR_STATUS_IS_ESYMNOTFOUND(s) ((s) == APR_ESYMNOTFOUND) +#endif +/** The given process was not recognized by APR. */ +#define APR_STATUS_IS_EPROC_UNKNOWN(s) ((s) == APR_EPROC_UNKNOWN) +/** APR could not gather enough entropy to continue. */ +#define APR_STATUS_IS_ENOTENOUGHENTROPY(s) ((s) == APR_ENOTENOUGHENTROPY) + +/** @} */ + +/** + * @addtogroup APR_Error + * @{ + */ +/** @see APR_STATUS_IS_INCHILD */ +#define APR_INCHILD (APR_OS_START_STATUS + 1) +/** @see APR_STATUS_IS_INPARENT */ +#define APR_INPARENT (APR_OS_START_STATUS + 2) +/** @see APR_STATUS_IS_DETACH */ +#define APR_DETACH (APR_OS_START_STATUS + 3) +/** @see APR_STATUS_IS_NOTDETACH */ +#define APR_NOTDETACH (APR_OS_START_STATUS + 4) +/** @see APR_STATUS_IS_CHILD_DONE */ +#define APR_CHILD_DONE (APR_OS_START_STATUS + 5) +/** @see APR_STATUS_IS_CHILD_NOTDONE */ +#define APR_CHILD_NOTDONE (APR_OS_START_STATUS + 6) +/** @see APR_STATUS_IS_TIMEUP */ +#define APR_TIMEUP (APR_OS_START_STATUS + 7) +/** @see APR_STATUS_IS_INCOMPLETE */ +#define APR_INCOMPLETE (APR_OS_START_STATUS + 8) +/* empty slot: +9 */ +/* empty slot: +10 */ +/* empty slot: +11 */ +/** @see APR_STATUS_IS_BADCH */ +#define APR_BADCH (APR_OS_START_STATUS + 12) +/** @see APR_STATUS_IS_BADARG */ +#define APR_BADARG (APR_OS_START_STATUS + 13) +/** @see APR_STATUS_IS_EOF */ +#define APR_EOF (APR_OS_START_STATUS + 14) +/** @see APR_STATUS_IS_NOTFOUND */ +#define APR_NOTFOUND (APR_OS_START_STATUS + 15) +/* empty slot: +16 */ +/* empty slot: +17 */ +/* empty slot: +18 */ +/** @see APR_STATUS_IS_ANONYMOUS */ +#define APR_ANONYMOUS (APR_OS_START_STATUS + 19) +/** @see APR_STATUS_IS_FILEBASED */ +#define APR_FILEBASED (APR_OS_START_STATUS + 20) +/** @see APR_STATUS_IS_KEYBASED */ +#define APR_KEYBASED (APR_OS_START_STATUS + 21) +/** @see APR_STATUS_IS_EINIT */ +#define APR_EINIT (APR_OS_START_STATUS + 22) +/** @see APR_STATUS_IS_ENOTIMPL */ +#define APR_ENOTIMPL (APR_OS_START_STATUS + 23) +/** @see APR_STATUS_IS_EMISMATCH */ +#define APR_EMISMATCH (APR_OS_START_STATUS + 24) +/** @see APR_STATUS_IS_EBUSY */ +#define APR_EBUSY (APR_OS_START_STATUS + 25) +/** @} */ + +/** + * @addtogroup APR_STATUS_IS + * @{ + */ +/** + * Program is currently executing in the child + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code */ +#define APR_STATUS_IS_INCHILD(s) ((s) == APR_INCHILD) +/** + * Program is currently executing in the parent + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_INPARENT(s) ((s) == APR_INPARENT) +/** + * The thread is detached + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_DETACH(s) ((s) == APR_DETACH) +/** + * The thread is not detached + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_NOTDETACH(s) ((s) == APR_NOTDETACH) +/** + * The child has finished executing + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_CHILD_DONE(s) ((s) == APR_CHILD_DONE) +/** + * The child has not finished executing + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_CHILD_NOTDONE(s) ((s) == APR_CHILD_NOTDONE) +/** + * The operation did not finish before the timeout + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_TIMEUP(s) ((s) == APR_TIMEUP) +/** + * The operation was incomplete although some processing was performed + * and the results are partially valid. + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_INCOMPLETE(s) ((s) == APR_INCOMPLETE) +/* empty slot: +9 */ +/* empty slot: +10 */ +/* empty slot: +11 */ +/** + * Getopt found an option not in the option string + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_BADCH(s) ((s) == APR_BADCH) +/** + * Getopt found an option not in the option string and an argument was + * specified in the option string + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_BADARG(s) ((s) == APR_BADARG) +/** + * APR has encountered the end of the file + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_EOF(s) ((s) == APR_EOF) +/** + * APR was unable to find the socket in the poll structure + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_NOTFOUND(s) ((s) == APR_NOTFOUND) +/* empty slot: +16 */ +/* empty slot: +17 */ +/* empty slot: +18 */ +/** + * APR is using anonymous shared memory + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_ANONYMOUS(s) ((s) == APR_ANONYMOUS) +/** + * APR is using a file name as the key to the shared memory + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_FILEBASED(s) ((s) == APR_FILEBASED) +/** + * APR is using a shared key as the key to the shared memory + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_KEYBASED(s) ((s) == APR_KEYBASED) +/** + * Ininitalizer value. If no option has been found, but + * the status variable requires a value, this should be used + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_EINIT(s) ((s) == APR_EINIT) +/** + * The APR function has not been implemented on this + * platform, either because nobody has gotten to it yet, + * or the function is impossible on this platform. + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_ENOTIMPL(s) ((s) == APR_ENOTIMPL) +/** + * Two passwords do not match. + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_EMISMATCH(s) ((s) == APR_EMISMATCH) +/** + * The given lock was busy + * @warning always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_EBUSY(s) ((s) == APR_EBUSY) + +/** @} */ + +/** + * @addtogroup APR_Error APR Error Values + * @{ + */ +/* APR CANONICAL ERROR VALUES */ +/** @see APR_STATUS_IS_EACCES */ +#ifdef EACCES +#define APR_EACCES EACCES +#else +#define APR_EACCES (APR_OS_START_CANONERR + 1) +#endif + +/** @see APR_STATUS_IS_EEXIST */ +#ifdef EEXIST +#define APR_EEXIST EEXIST +#else +#define APR_EEXIST (APR_OS_START_CANONERR + 2) +#endif + +/** @see APR_STATUS_IS_ENAMETOOLONG */ +#ifdef ENAMETOOLONG +#define APR_ENAMETOOLONG ENAMETOOLONG +#else +#define APR_ENAMETOOLONG (APR_OS_START_CANONERR + 3) +#endif + +/** @see APR_STATUS_IS_ENOENT */ +#ifdef ENOENT +#define APR_ENOENT ENOENT +#else +#define APR_ENOENT (APR_OS_START_CANONERR + 4) +#endif + +/** @see APR_STATUS_IS_ENOTDIR */ +#ifdef ENOTDIR +#define APR_ENOTDIR ENOTDIR +#else +#define APR_ENOTDIR (APR_OS_START_CANONERR + 5) +#endif + +/** @see APR_STATUS_IS_ENOSPC */ +#ifdef ENOSPC +#define APR_ENOSPC ENOSPC +#else +#define APR_ENOSPC (APR_OS_START_CANONERR + 6) +#endif + +/** @see APR_STATUS_IS_ENOMEM */ +#ifdef ENOMEM +#define APR_ENOMEM ENOMEM +#else +#define APR_ENOMEM (APR_OS_START_CANONERR + 7) +#endif + +/** @see APR_STATUS_IS_EMFILE */ +#ifdef EMFILE +#define APR_EMFILE EMFILE +#else +#define APR_EMFILE (APR_OS_START_CANONERR + 8) +#endif + +/** @see APR_STATUS_IS_ENFILE */ +#ifdef ENFILE +#define APR_ENFILE ENFILE +#else +#define APR_ENFILE (APR_OS_START_CANONERR + 9) +#endif + +/** @see APR_STATUS_IS_EBADF */ +#ifdef EBADF +#define APR_EBADF EBADF +#else +#define APR_EBADF (APR_OS_START_CANONERR + 10) +#endif + +/** @see APR_STATUS_IS_EINVAL */ +#ifdef EINVAL +#define APR_EINVAL EINVAL +#else +#define APR_EINVAL (APR_OS_START_CANONERR + 11) +#endif + +/** @see APR_STATUS_IS_ESPIPE */ +#ifdef ESPIPE +#define APR_ESPIPE ESPIPE +#else +#define APR_ESPIPE (APR_OS_START_CANONERR + 12) +#endif + +/** + * @see APR_STATUS_IS_EAGAIN + * @warning use APR_STATUS_IS_EAGAIN instead of just testing this value + */ +#ifdef EAGAIN +#define APR_EAGAIN EAGAIN +#elif defined(EWOULDBLOCK) +#define APR_EAGAIN EWOULDBLOCK +#else +#define APR_EAGAIN (APR_OS_START_CANONERR + 13) +#endif + +/** @see APR_STATUS_IS_EINTR */ +#ifdef EINTR +#define APR_EINTR EINTR +#else +#define APR_EINTR (APR_OS_START_CANONERR + 14) +#endif + +/** @see APR_STATUS_IS_ENOTSOCK */ +#ifdef ENOTSOCK +#define APR_ENOTSOCK ENOTSOCK +#else +#define APR_ENOTSOCK (APR_OS_START_CANONERR + 15) +#endif + +/** @see APR_STATUS_IS_ECONNREFUSED */ +#ifdef ECONNREFUSED +#define APR_ECONNREFUSED ECONNREFUSED +#else +#define APR_ECONNREFUSED (APR_OS_START_CANONERR + 16) +#endif + +/** @see APR_STATUS_IS_EINPROGRESS */ +#ifdef EINPROGRESS +#define APR_EINPROGRESS EINPROGRESS +#else +#define APR_EINPROGRESS (APR_OS_START_CANONERR + 17) +#endif + +/** + * @see APR_STATUS_IS_ECONNABORTED + * @warning use APR_STATUS_IS_ECONNABORTED instead of just testing this value + */ + +#ifdef ECONNABORTED +#define APR_ECONNABORTED ECONNABORTED +#else +#define APR_ECONNABORTED (APR_OS_START_CANONERR + 18) +#endif + +/** @see APR_STATUS_IS_ECONNRESET */ +#ifdef ECONNRESET +#define APR_ECONNRESET ECONNRESET +#else +#define APR_ECONNRESET (APR_OS_START_CANONERR + 19) +#endif + +/** @see APR_STATUS_IS_ETIMEDOUT + * @deprecated */ +#ifdef ETIMEDOUT +#define APR_ETIMEDOUT ETIMEDOUT +#else +#define APR_ETIMEDOUT (APR_OS_START_CANONERR + 20) +#endif + +/** @see APR_STATUS_IS_EHOSTUNREACH */ +#ifdef EHOSTUNREACH +#define APR_EHOSTUNREACH EHOSTUNREACH +#else +#define APR_EHOSTUNREACH (APR_OS_START_CANONERR + 21) +#endif + +/** @see APR_STATUS_IS_ENETUNREACH */ +#ifdef ENETUNREACH +#define APR_ENETUNREACH ENETUNREACH +#else +#define APR_ENETUNREACH (APR_OS_START_CANONERR + 22) +#endif + +/** @see APR_STATUS_IS_EFTYPE */ +#ifdef EFTYPE +#define APR_EFTYPE EFTYPE +#else +#define APR_EFTYPE (APR_OS_START_CANONERR + 23) +#endif + +/** @see APR_STATUS_IS_EPIPE */ +#ifdef EPIPE +#define APR_EPIPE EPIPE +#else +#define APR_EPIPE (APR_OS_START_CANONERR + 24) +#endif + +/** @see APR_STATUS_IS_EXDEV */ +#ifdef EXDEV +#define APR_EXDEV EXDEV +#else +#define APR_EXDEV (APR_OS_START_CANONERR + 25) +#endif + +/** @see APR_STATUS_IS_ENOTEMPTY */ +#ifdef ENOTEMPTY +#define APR_ENOTEMPTY ENOTEMPTY +#else +#define APR_ENOTEMPTY (APR_OS_START_CANONERR + 26) +#endif + +/** @see APR_STATUS_IS_EAFNOSUPPORT */ +#ifdef EAFNOSUPPORT +#define APR_EAFNOSUPPORT EAFNOSUPPORT +#else +#define APR_EAFNOSUPPORT (APR_OS_START_CANONERR + 27) +#endif + +/** @see APR_STATUS_IS_EOPNOTSUPP */ +#ifdef EOPNOTSUPP +#define APR_EOPNOTSUPP EOPNOTSUPP +#else +#define APR_EOPNOTSUPP (APR_OS_START_CANONERR + 28) +#endif + +/** @see APR_STATUS_IS_ERANGE */ +#ifdef ERANGE +#define APR_ERANGE ERANGE +#else +#define APR_ERANGE (APR_OS_START_CANONERR + 29) +#endif + +/** @} */ + +#if defined(OS2) && !defined(DOXYGEN) + +#define APR_FROM_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e + APR_OS_START_SYSERR) +#define APR_TO_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e - APR_OS_START_SYSERR) + +#define INCL_DOSERRORS +#define INCL_DOS + +/* Leave these undefined. + * OS2 doesn't rely on the errno concept. + * The API calls always return a result codes which + * should be filtered through APR_FROM_OS_ERROR(). + * + * #define apr_get_os_error() (APR_FROM_OS_ERROR(GetLastError())) + * #define apr_set_os_error(e) (SetLastError(APR_TO_OS_ERROR(e))) + */ + +/* A special case, only socket calls require this; + */ +#define apr_get_netos_error() (APR_FROM_OS_ERROR(errno)) +#define apr_set_netos_error(e) (errno = APR_TO_OS_ERROR(e)) + +/* And this needs to be greped away for good: + */ +#define APR_OS2_STATUS(e) (APR_FROM_OS_ERROR(e)) + +/* These can't sit in a private header, so in spite of the extra size, + * they need to be made available here. + */ +#define SOCBASEERR 10000 +#define SOCEPERM (SOCBASEERR+1) /* Not owner */ +#define SOCESRCH (SOCBASEERR+3) /* No such process */ +#define SOCEINTR (SOCBASEERR+4) /* Interrupted system call */ +#define SOCENXIO (SOCBASEERR+6) /* No such device or address */ +#define SOCEBADF (SOCBASEERR+9) /* Bad file number */ +#define SOCEACCES (SOCBASEERR+13) /* Permission denied */ +#define SOCEFAULT (SOCBASEERR+14) /* Bad address */ +#define SOCEINVAL (SOCBASEERR+22) /* Invalid argument */ +#define SOCEMFILE (SOCBASEERR+24) /* Too many open files */ +#define SOCEPIPE (SOCBASEERR+32) /* Broken pipe */ +#define SOCEOS2ERR (SOCBASEERR+100) /* OS/2 Error */ +#define SOCEWOULDBLOCK (SOCBASEERR+35) /* Operation would block */ +#define SOCEINPROGRESS (SOCBASEERR+36) /* Operation now in progress */ +#define SOCEALREADY (SOCBASEERR+37) /* Operation already in progress */ +#define SOCENOTSOCK (SOCBASEERR+38) /* Socket operation on non-socket */ +#define SOCEDESTADDRREQ (SOCBASEERR+39) /* Destination address required */ +#define SOCEMSGSIZE (SOCBASEERR+40) /* Message too long */ +#define SOCEPROTOTYPE (SOCBASEERR+41) /* Protocol wrong type for socket */ +#define SOCENOPROTOOPT (SOCBASEERR+42) /* Protocol not available */ +#define SOCEPROTONOSUPPORT (SOCBASEERR+43) /* Protocol not supported */ +#define SOCESOCKTNOSUPPORT (SOCBASEERR+44) /* Socket type not supported */ +#define SOCEOPNOTSUPP (SOCBASEERR+45) /* Operation not supported on socket */ +#define SOCEPFNOSUPPORT (SOCBASEERR+46) /* Protocol family not supported */ +#define SOCEAFNOSUPPORT (SOCBASEERR+47) /* Address family not supported by protocol family */ +#define SOCEADDRINUSE (SOCBASEERR+48) /* Address already in use */ +#define SOCEADDRNOTAVAIL (SOCBASEERR+49) /* Can't assign requested address */ +#define SOCENETDOWN (SOCBASEERR+50) /* Network is down */ +#define SOCENETUNREACH (SOCBASEERR+51) /* Network is unreachable */ +#define SOCENETRESET (SOCBASEERR+52) /* Network dropped connection on reset */ +#define SOCECONNABORTED (SOCBASEERR+53) /* Software caused connection abort */ +#define SOCECONNRESET (SOCBASEERR+54) /* Connection reset by peer */ +#define SOCENOBUFS (SOCBASEERR+55) /* No buffer space available */ +#define SOCEISCONN (SOCBASEERR+56) /* Socket is already connected */ +#define SOCENOTCONN (SOCBASEERR+57) /* Socket is not connected */ +#define SOCESHUTDOWN (SOCBASEERR+58) /* Can't send after socket shutdown */ +#define SOCETOOMANYREFS (SOCBASEERR+59) /* Too many references: can't splice */ +#define SOCETIMEDOUT (SOCBASEERR+60) /* Connection timed out */ +#define SOCECONNREFUSED (SOCBASEERR+61) /* Connection refused */ +#define SOCELOOP (SOCBASEERR+62) /* Too many levels of symbolic links */ +#define SOCENAMETOOLONG (SOCBASEERR+63) /* File name too long */ +#define SOCEHOSTDOWN (SOCBASEERR+64) /* Host is down */ +#define SOCEHOSTUNREACH (SOCBASEERR+65) /* No route to host */ +#define SOCENOTEMPTY (SOCBASEERR+66) /* Directory not empty */ + +/* APR CANONICAL ERROR TESTS */ +#define APR_STATUS_IS_EACCES(s) ((s) == APR_EACCES \ + || (s) == APR_OS_START_SYSERR + ERROR_ACCESS_DENIED \ + || (s) == APR_OS_START_SYSERR + ERROR_SHARING_VIOLATION) +#define APR_STATUS_IS_EEXIST(s) ((s) == APR_EEXIST \ + || (s) == APR_OS_START_SYSERR + ERROR_OPEN_FAILED \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_EXISTS \ + || (s) == APR_OS_START_SYSERR + ERROR_ALREADY_EXISTS \ + || (s) == APR_OS_START_SYSERR + ERROR_ACCESS_DENIED) +#define APR_STATUS_IS_ENAMETOOLONG(s) ((s) == APR_ENAMETOOLONG \ + || (s) == APR_OS_START_SYSERR + ERROR_FILENAME_EXCED_RANGE \ + || (s) == APR_OS_START_SYSERR + SOCENAMETOOLONG) +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_PATH_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_MORE_FILES \ + || (s) == APR_OS_START_SYSERR + ERROR_OPEN_FAILED) +#define APR_STATUS_IS_ENOTDIR(s) ((s) == APR_ENOTDIR) +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC \ + || (s) == APR_OS_START_SYSERR + ERROR_DISK_FULL) +#define APR_STATUS_IS_ENOMEM(s) ((s) == APR_ENOMEM) +#define APR_STATUS_IS_EMFILE(s) ((s) == APR_EMFILE \ + || (s) == APR_OS_START_SYSERR + ERROR_TOO_MANY_OPEN_FILES) +#define APR_STATUS_IS_ENFILE(s) ((s) == APR_ENFILE) +#define APR_STATUS_IS_EBADF(s) ((s) == APR_EBADF \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_HANDLE) +#define APR_STATUS_IS_EINVAL(s) ((s) == APR_EINVAL \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_PARAMETER \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_FUNCTION) +#define APR_STATUS_IS_ESPIPE(s) ((s) == APR_ESPIPE \ + || (s) == APR_OS_START_SYSERR + ERROR_NEGATIVE_SEEK) +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_DATA \ + || (s) == APR_OS_START_SYSERR + SOCEWOULDBLOCK \ + || (s) == APR_OS_START_SYSERR + ERROR_LOCK_VIOLATION) +#define APR_STATUS_IS_EINTR(s) ((s) == APR_EINTR \ + || (s) == APR_OS_START_SYSERR + SOCEINTR) +#define APR_STATUS_IS_ENOTSOCK(s) ((s) == APR_ENOTSOCK \ + || (s) == APR_OS_START_SYSERR + SOCENOTSOCK) +#define APR_STATUS_IS_ECONNREFUSED(s) ((s) == APR_ECONNREFUSED \ + || (s) == APR_OS_START_SYSERR + SOCECONNREFUSED) +#define APR_STATUS_IS_EINPROGRESS(s) ((s) == APR_EINPROGRESS \ + || (s) == APR_OS_START_SYSERR + SOCEINPROGRESS) +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED \ + || (s) == APR_OS_START_SYSERR + SOCECONNABORTED) +#define APR_STATUS_IS_ECONNRESET(s) ((s) == APR_ECONNRESET \ + || (s) == APR_OS_START_SYSERR + SOCECONNRESET) +/* XXX deprecated */ +#define APR_STATUS_IS_ETIMEDOUT(s) ((s) == APR_ETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + SOCETIMEDOUT) +#undef APR_STATUS_IS_TIMEUP +#define APR_STATUS_IS_TIMEUP(s) ((s) == APR_TIMEUP \ + || (s) == APR_OS_START_SYSERR + SOCETIMEDOUT) +#define APR_STATUS_IS_EHOSTUNREACH(s) ((s) == APR_EHOSTUNREACH \ + || (s) == APR_OS_START_SYSERR + SOCEHOSTUNREACH) +#define APR_STATUS_IS_ENETUNREACH(s) ((s) == APR_ENETUNREACH \ + || (s) == APR_OS_START_SYSERR + SOCENETUNREACH) +#define APR_STATUS_IS_EFTYPE(s) ((s) == APR_EFTYPE) +#define APR_STATUS_IS_EPIPE(s) ((s) == APR_EPIPE \ + || (s) == APR_OS_START_SYSERR + ERROR_BROKEN_PIPE \ + || (s) == APR_OS_START_SYSERR + SOCEPIPE) +#define APR_STATUS_IS_EXDEV(s) ((s) == APR_EXDEV \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_SAME_DEVICE) +#define APR_STATUS_IS_ENOTEMPTY(s) ((s) == APR_ENOTEMPTY \ + || (s) == APR_OS_START_SYSERR + ERROR_DIR_NOT_EMPTY \ + || (s) == APR_OS_START_SYSERR + ERROR_ACCESS_DENIED) +#define APR_STATUS_IS_EAFNOSUPPORT(s) ((s) == APR_AFNOSUPPORT \ + || (s) == APR_OS_START_SYSERR + SOCEAFNOSUPPORT) +#define APR_STATUS_IS_EOPNOTSUPP(s) ((s) == APR_EOPNOTSUPP \ + || (s) == APR_OS_START_SYSERR + SOCEOPNOTSUPP) +#define APR_STATUS_IS_ERANGE(s) ((s) == APR_ERANGE) + +/* + Sorry, too tired to wrap this up for OS2... feel free to + fit the following into their best matches. + + { ERROR_NO_SIGNAL_SENT, ESRCH }, + { SOCEALREADY, EALREADY }, + { SOCEDESTADDRREQ, EDESTADDRREQ }, + { SOCEMSGSIZE, EMSGSIZE }, + { SOCEPROTOTYPE, EPROTOTYPE }, + { SOCENOPROTOOPT, ENOPROTOOPT }, + { SOCEPROTONOSUPPORT, EPROTONOSUPPORT }, + { SOCESOCKTNOSUPPORT, ESOCKTNOSUPPORT }, + { SOCEPFNOSUPPORT, EPFNOSUPPORT }, + { SOCEADDRINUSE, EADDRINUSE }, + { SOCEADDRNOTAVAIL, EADDRNOTAVAIL }, + { SOCENETDOWN, ENETDOWN }, + { SOCENETRESET, ENETRESET }, + { SOCENOBUFS, ENOBUFS }, + { SOCEISCONN, EISCONN }, + { SOCENOTCONN, ENOTCONN }, + { SOCESHUTDOWN, ESHUTDOWN }, + { SOCETOOMANYREFS, ETOOMANYREFS }, + { SOCELOOP, ELOOP }, + { SOCEHOSTDOWN, EHOSTDOWN }, + { SOCENOTEMPTY, ENOTEMPTY }, + { SOCEPIPE, EPIPE } +*/ + +#elif defined(WIN32) && !defined(DOXYGEN) /* !defined(OS2) */ + +#define APR_FROM_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e + APR_OS_START_SYSERR) +#define APR_TO_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e - APR_OS_START_SYSERR) + +#define apr_get_os_error() (APR_FROM_OS_ERROR(GetLastError())) +#define apr_set_os_error(e) (SetLastError(APR_TO_OS_ERROR(e))) + +/* A special case, only socket calls require this: + */ +#define apr_get_netos_error() (APR_FROM_OS_ERROR(WSAGetLastError())) +#define apr_set_netos_error(e) (WSASetLastError(APR_TO_OS_ERROR(e))) + +/* APR CANONICAL ERROR TESTS */ +#define APR_STATUS_IS_EACCES(s) ((s) == APR_EACCES \ + || (s) == APR_OS_START_SYSERR + ERROR_ACCESS_DENIED \ + || (s) == APR_OS_START_SYSERR + ERROR_CANNOT_MAKE \ + || (s) == APR_OS_START_SYSERR + ERROR_CURRENT_DIRECTORY \ + || (s) == APR_OS_START_SYSERR + ERROR_DRIVE_LOCKED \ + || (s) == APR_OS_START_SYSERR + ERROR_FAIL_I24 \ + || (s) == APR_OS_START_SYSERR + ERROR_LOCK_VIOLATION \ + || (s) == APR_OS_START_SYSERR + ERROR_LOCK_FAILED \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_LOCKED \ + || (s) == APR_OS_START_SYSERR + ERROR_NETWORK_ACCESS_DENIED \ + || (s) == APR_OS_START_SYSERR + ERROR_SHARING_VIOLATION) +#define APR_STATUS_IS_EEXIST(s) ((s) == APR_EEXIST \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_EXISTS \ + || (s) == APR_OS_START_SYSERR + ERROR_ALREADY_EXISTS) +#define APR_STATUS_IS_ENAMETOOLONG(s) ((s) == APR_ENAMETOOLONG \ + || (s) == APR_OS_START_SYSERR + ERROR_FILENAME_EXCED_RANGE \ + || (s) == APR_OS_START_SYSERR + WSAENAMETOOLONG) +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_PATH_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_OPEN_FAILED \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_MORE_FILES) +#define APR_STATUS_IS_ENOTDIR(s) ((s) == APR_ENOTDIR \ + || (s) == APR_OS_START_SYSERR + ERROR_PATH_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_NETPATH \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_NET_NAME \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_PATHNAME \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_DRIVE \ + || (s) == APR_OS_START_SYSERR + ERROR_DIRECTORY) +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC \ + || (s) == APR_OS_START_SYSERR + ERROR_DISK_FULL) +#define APR_STATUS_IS_ENOMEM(s) ((s) == APR_ENOMEM \ + || (s) == APR_OS_START_SYSERR + ERROR_ARENA_TRASHED \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_ENOUGH_MEMORY \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_BLOCK \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_ENOUGH_QUOTA \ + || (s) == APR_OS_START_SYSERR + ERROR_OUTOFMEMORY) +#define APR_STATUS_IS_EMFILE(s) ((s) == APR_EMFILE \ + || (s) == APR_OS_START_SYSERR + ERROR_TOO_MANY_OPEN_FILES) +#define APR_STATUS_IS_ENFILE(s) ((s) == APR_ENFILE) +#define APR_STATUS_IS_EBADF(s) ((s) == APR_EBADF \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_HANDLE \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_TARGET_HANDLE) +#define APR_STATUS_IS_EINVAL(s) ((s) == APR_EINVAL \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_ACCESS \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_DATA \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_FUNCTION \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_HANDLE \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_PARAMETER \ + || (s) == APR_OS_START_SYSERR + ERROR_NEGATIVE_SEEK) +#define APR_STATUS_IS_ESPIPE(s) ((s) == APR_ESPIPE \ + || (s) == APR_OS_START_SYSERR + ERROR_SEEK_ON_DEVICE \ + || (s) == APR_OS_START_SYSERR + ERROR_NEGATIVE_SEEK) +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_DATA \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_PROC_SLOTS \ + || (s) == APR_OS_START_SYSERR + ERROR_NESTING_NOT_ALLOWED \ + || (s) == APR_OS_START_SYSERR + ERROR_MAX_THRDS_REACHED \ + || (s) == APR_OS_START_SYSERR + ERROR_LOCK_VIOLATION \ + || (s) == APR_OS_START_SYSERR + WSAEWOULDBLOCK) +#define APR_STATUS_IS_EINTR(s) ((s) == APR_EINTR \ + || (s) == APR_OS_START_SYSERR + WSAEINTR) +#define APR_STATUS_IS_ENOTSOCK(s) ((s) == APR_ENOTSOCK \ + || (s) == APR_OS_START_SYSERR + WSAENOTSOCK) +#define APR_STATUS_IS_ECONNREFUSED(s) ((s) == APR_ECONNREFUSED \ + || (s) == APR_OS_START_SYSERR + WSAECONNREFUSED) +#define APR_STATUS_IS_EINPROGRESS(s) ((s) == APR_EINPROGRESS \ + || (s) == APR_OS_START_SYSERR + WSAEINPROGRESS) +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED \ + || (s) == APR_OS_START_SYSERR + WSAECONNABORTED) +#define APR_STATUS_IS_ECONNRESET(s) ((s) == APR_ECONNRESET \ + || (s) == APR_OS_START_SYSERR + ERROR_NETNAME_DELETED \ + || (s) == APR_OS_START_SYSERR + WSAECONNRESET) +/* XXX deprecated */ +#define APR_STATUS_IS_ETIMEDOUT(s) ((s) == APR_ETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WSAETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WAIT_TIMEOUT) +#undef APR_STATUS_IS_TIMEUP +#define APR_STATUS_IS_TIMEUP(s) ((s) == APR_TIMEUP \ + || (s) == APR_OS_START_SYSERR + WSAETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WAIT_TIMEOUT) +#define APR_STATUS_IS_EHOSTUNREACH(s) ((s) == APR_EHOSTUNREACH \ + || (s) == APR_OS_START_SYSERR + WSAEHOSTUNREACH) +#define APR_STATUS_IS_ENETUNREACH(s) ((s) == APR_ENETUNREACH \ + || (s) == APR_OS_START_SYSERR + WSAENETUNREACH) +#define APR_STATUS_IS_EFTYPE(s) ((s) == APR_EFTYPE \ + || (s) == APR_OS_START_SYSERR + ERROR_EXE_MACHINE_TYPE_MISMATCH \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_DLL \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_MODULETYPE \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_EXE_FORMAT \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_EXE_SIGNATURE \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_CORRUPT \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_FORMAT) +#define APR_STATUS_IS_EPIPE(s) ((s) == APR_EPIPE \ + || (s) == APR_OS_START_SYSERR + ERROR_BROKEN_PIPE) +#define APR_STATUS_IS_EXDEV(s) ((s) == APR_EXDEV \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_SAME_DEVICE) +#define APR_STATUS_IS_ENOTEMPTY(s) ((s) == APR_ENOTEMPTY \ + || (s) == APR_OS_START_SYSERR + ERROR_DIR_NOT_EMPTY) +#define APR_STATUS_IS_EAFNOSUPPORT(s) ((s) == APR_EAFNOSUPPORT \ + || (s) == APR_OS_START_SYSERR + WSAEAFNOSUPPORT) +#define APR_STATUS_IS_EOPNOTSUPP(s) ((s) == APR_EOPNOTSUPP \ + || (s) == APR_OS_START_SYSERR + WSAEOPNOTSUPP) +#define APR_STATUS_IS_ERANGE(s) ((s) == APR_ERANGE) + +#elif defined(NETWARE) && defined(USE_WINSOCK) && !defined(DOXYGEN) /* !defined(OS2) && !defined(WIN32) */ + +#define APR_FROM_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e + APR_OS_START_SYSERR) +#define APR_TO_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e - APR_OS_START_SYSERR) + +#define apr_get_os_error() (errno) +#define apr_set_os_error(e) (errno = (e)) + +/* A special case, only socket calls require this: */ +#define apr_get_netos_error() (APR_FROM_OS_ERROR(WSAGetLastError())) +#define apr_set_netos_error(e) (WSASetLastError(APR_TO_OS_ERROR(e))) + +/* APR CANONICAL ERROR TESTS */ +#define APR_STATUS_IS_EACCES(s) ((s) == APR_EACCES) +#define APR_STATUS_IS_EEXIST(s) ((s) == APR_EEXIST) +#define APR_STATUS_IS_ENAMETOOLONG(s) ((s) == APR_ENAMETOOLONG) +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT) +#define APR_STATUS_IS_ENOTDIR(s) ((s) == APR_ENOTDIR) +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC) +#define APR_STATUS_IS_ENOMEM(s) ((s) == APR_ENOMEM) +#define APR_STATUS_IS_EMFILE(s) ((s) == APR_EMFILE) +#define APR_STATUS_IS_ENFILE(s) ((s) == APR_ENFILE) +#define APR_STATUS_IS_EBADF(s) ((s) == APR_EBADF) +#define APR_STATUS_IS_EINVAL(s) ((s) == APR_EINVAL) +#define APR_STATUS_IS_ESPIPE(s) ((s) == APR_ESPIPE) + +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN \ + || (s) == EWOULDBLOCK \ + || (s) == APR_OS_START_SYSERR + WSAEWOULDBLOCK) +#define APR_STATUS_IS_EINTR(s) ((s) == APR_EINTR \ + || (s) == APR_OS_START_SYSERR + WSAEINTR) +#define APR_STATUS_IS_ENOTSOCK(s) ((s) == APR_ENOTSOCK \ + || (s) == APR_OS_START_SYSERR + WSAENOTSOCK) +#define APR_STATUS_IS_ECONNREFUSED(s) ((s) == APR_ECONNREFUSED \ + || (s) == APR_OS_START_SYSERR + WSAECONNREFUSED) +#define APR_STATUS_IS_EINPROGRESS(s) ((s) == APR_EINPROGRESS \ + || (s) == APR_OS_START_SYSERR + WSAEINPROGRESS) +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED \ + || (s) == APR_OS_START_SYSERR + WSAECONNABORTED) +#define APR_STATUS_IS_ECONNRESET(s) ((s) == APR_ECONNRESET \ + || (s) == APR_OS_START_SYSERR + WSAECONNRESET) +/* XXX deprecated */ +#define APR_STATUS_IS_ETIMEDOUT(s) ((s) == APR_ETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WSAETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WAIT_TIMEOUT) +#undef APR_STATUS_IS_TIMEUP +#define APR_STATUS_IS_TIMEUP(s) ((s) == APR_TIMEUP \ + || (s) == APR_OS_START_SYSERR + WSAETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WAIT_TIMEOUT) +#define APR_STATUS_IS_EHOSTUNREACH(s) ((s) == APR_EHOSTUNREACH \ + || (s) == APR_OS_START_SYSERR + WSAEHOSTUNREACH) +#define APR_STATUS_IS_ENETUNREACH(s) ((s) == APR_ENETUNREACH \ + || (s) == APR_OS_START_SYSERR + WSAENETUNREACH) +#define APR_STATUS_IS_ENETDOWN(s) ((s) == APR_OS_START_SYSERR + WSAENETDOWN) +#define APR_STATUS_IS_EFTYPE(s) ((s) == APR_EFTYPE) +#define APR_STATUS_IS_EPIPE(s) ((s) == APR_EPIPE) +#define APR_STATUS_IS_EXDEV(s) ((s) == APR_EXDEV) +#define APR_STATUS_IS_ENOTEMPTY(s) ((s) == APR_ENOTEMPTY) +#define APR_STATUS_IS_EAFNOSUPPORT(s) ((s) == APR_EAFNOSUPPORT \ + || (s) == APR_OS_START_SYSERR + WSAEAFNOSUPPORT) +#define APR_STATUS_IS_EOPNOTSUPP(s) ((s) == APR_EOPNOTSUPP \ + || (s) == APR_OS_START_SYSERR + WSAEOPNOTSUPP) +#define APR_STATUS_IS_ERANGE(s) ((s) == APR_ERANGE) + +#else /* !defined(NETWARE) && !defined(OS2) && !defined(WIN32) */ + +/* + * os error codes are clib error codes + */ +#define APR_FROM_OS_ERROR(e) (e) +#define APR_TO_OS_ERROR(e) (e) + +#define apr_get_os_error() (errno) +#define apr_set_os_error(e) (errno = (e)) + +/* A special case, only socket calls require this: + */ +#define apr_get_netos_error() (errno) +#define apr_set_netos_error(e) (errno = (e)) + +/** + * @addtogroup APR_STATUS_IS + * @{ + */ + +/** permission denied */ +#define APR_STATUS_IS_EACCES(s) ((s) == APR_EACCES) +/** file exists */ +#define APR_STATUS_IS_EEXIST(s) ((s) == APR_EEXIST) +/** path name is too long */ +#define APR_STATUS_IS_ENAMETOOLONG(s) ((s) == APR_ENAMETOOLONG) +/** + * no such file or directory + * @remark + * EMVSCATLG can be returned by the automounter on z/OS for + * paths which do not exist. + */ +#ifdef EMVSCATLG +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT \ + || (s) == EMVSCATLG) +#else +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT) +#endif +/** not a directory */ +#define APR_STATUS_IS_ENOTDIR(s) ((s) == APR_ENOTDIR) +/** no space left on device */ +#ifdef EDQUOT +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC \ + || (s) == EDQUOT) +#else +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC) +#endif +/** not enough memory */ +#define APR_STATUS_IS_ENOMEM(s) ((s) == APR_ENOMEM) +/** too many open files */ +#define APR_STATUS_IS_EMFILE(s) ((s) == APR_EMFILE) +/** file table overflow */ +#define APR_STATUS_IS_ENFILE(s) ((s) == APR_ENFILE) +/** bad file # */ +#define APR_STATUS_IS_EBADF(s) ((s) == APR_EBADF) +/** invalid argument */ +#define APR_STATUS_IS_EINVAL(s) ((s) == APR_EINVAL) +/** illegal seek */ +#define APR_STATUS_IS_ESPIPE(s) ((s) == APR_ESPIPE) + +/** operation would block */ +#if !defined(EWOULDBLOCK) || !defined(EAGAIN) +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN) +#elif (EWOULDBLOCK == EAGAIN) +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN) +#else +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN \ + || (s) == EWOULDBLOCK) +#endif + +/** interrupted system call */ +#define APR_STATUS_IS_EINTR(s) ((s) == APR_EINTR) +/** socket operation on a non-socket */ +#define APR_STATUS_IS_ENOTSOCK(s) ((s) == APR_ENOTSOCK) +/** Connection Refused */ +#define APR_STATUS_IS_ECONNREFUSED(s) ((s) == APR_ECONNREFUSED) +/** operation now in progress */ +#define APR_STATUS_IS_EINPROGRESS(s) ((s) == APR_EINPROGRESS) + +/** + * Software caused connection abort + * @remark + * EPROTO on certain older kernels really means ECONNABORTED, so we need to + * ignore it for them. See discussion in new-httpd archives nh.9701 & nh.9603 + * + * There is potentially a bug in Solaris 2.x x<6, and other boxes that + * implement tcp sockets in userland (i.e. on top of STREAMS). On these + * systems, EPROTO can actually result in a fatal loop. See PR#981 for + * example. It's hard to handle both uses of EPROTO. + */ +#ifdef EPROTO +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED \ + || (s) == EPROTO) +#else +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED) +#endif + +/** Connection Reset by peer */ +#define APR_STATUS_IS_ECONNRESET(s) ((s) == APR_ECONNRESET) +/** Operation timed out + * @deprecated */ +#define APR_STATUS_IS_ETIMEDOUT(s) ((s) == APR_ETIMEDOUT) +/** no route to host */ +#define APR_STATUS_IS_EHOSTUNREACH(s) ((s) == APR_EHOSTUNREACH) +/** network is unreachable */ +#define APR_STATUS_IS_ENETUNREACH(s) ((s) == APR_ENETUNREACH) +/** inappropriate file type or format */ +#define APR_STATUS_IS_EFTYPE(s) ((s) == APR_EFTYPE) +/** broken pipe */ +#define APR_STATUS_IS_EPIPE(s) ((s) == APR_EPIPE) +/** cross device link */ +#define APR_STATUS_IS_EXDEV(s) ((s) == APR_EXDEV) +/** Directory Not Empty */ +#define APR_STATUS_IS_ENOTEMPTY(s) ((s) == APR_ENOTEMPTY || \ + (s) == APR_EEXIST) +/** Address Family not supported */ +#define APR_STATUS_IS_EAFNOSUPPORT(s) ((s) == APR_EAFNOSUPPORT) +/** Socket operation not supported */ +#define APR_STATUS_IS_EOPNOTSUPP(s) ((s) == APR_EOPNOTSUPP) + +/** Numeric value not representable */ +#define APR_STATUS_IS_ERANGE(s) ((s) == APR_ERANGE) +/** @} */ + +#endif /* !defined(NETWARE) && !defined(OS2) && !defined(WIN32) */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_ERRNO_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_escape.h b/c/dependencies/windows/apr/x86/include/apr_escape.h new file mode 100644 index 00000000..ed048c95 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_escape.h @@ -0,0 +1,431 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file apr_escape.h + * @brief APR-UTIL Escaping + */ +#ifndef APR_ESCAPE_H +#define APR_ESCAPE_H +#include "apr.h" +#include "apr_general.h" +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Escaping Escape functions + * @ingroup APR + * @{ + */ + +/* Simple escape/unescape functions. + * + * The design goal of these functions are: + * + * - Avoid unnecessary work. + * + * In most cases the strings passed in do not need to be escaped at all. In + * these cases the original string will be returned. + * + * - Lowest possible memory footprint. + * + * The amount of memory allocated for a given encoding is calculated based + * on the exact amount of memory needed, and not the theoretical worst case + * scenario. + * + */ + +/** + * When passing a string to one of the escape functions, this value can be + * passed to indicate a string-valued key, and have the length computed + * automatically. + */ +#define APR_ESCAPE_STRING (-1) + +/** + * Apply LDAP distinguished name escaping as per RFC4514. + */ +#define APR_ESCAPE_LDAP_DN (0x01) + +/** + * Apply LDAP filter escaping as per RFC4515. + */ +#define APR_ESCAPE_LDAP_FILTER (0x02) + +/** + * Apply both RFC4514 and RFC4515 LDAP escaping. + */ +#define APR_ESCAPE_LDAP_ALL (0x03) + +/** + * Perform shell escaping on the provided string. + * + * Shell escaping causes characters to be prefixed with a '\' character. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_shell(char *escaped, const char *str, + apr_ssize_t slen, apr_size_t *len); + +/** + * Perform shell escaping on the provided string, returning the result + * from the pool. + * + * Shell escaping causes characters to be prefixed with a '\' character. + * + * If no characters were escaped, the original string is returned. + * @param p Pool to allocate from + * @param str The original string + * @return the encoded string, allocated from the pool, or the original + * string if no escaping took place or the string was NULL. + */ +APR_DECLARE(const char *) apr_pescape_shell(apr_pool_t *p, const char *str) + __attribute__((nonnull(1))); + +/** + * Unescapes a URL, leaving reserved characters intact. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param url String to be unescaped + * @param slen The length of the original url, or APR_ESCAPE_STRING + * @param forbid Optional list of forbidden characters, in addition to + * 0x00 + * @param reserved Optional list of reserved characters that will be + * left unescaped + * @param plus If non zero, '+' is converted to ' ' as per + * application/x-www-form-urlencoded encoding + * @param len If set, the length of the escaped string will be returned + * @return APR_SUCCESS on success, APR_NOTFOUND if no characters are + * decoded or the string is NULL, APR_EINVAL if a bad escape sequence is + * found, APR_BADCH if a character on the forbid list is found. + */ +APR_DECLARE(apr_status_t) apr_unescape_url(char *escaped, const char *url, + apr_ssize_t slen, const char *forbid, const char *reserved, int plus, + apr_size_t *len); + +/** + * Unescapes a URL, leaving reserved characters intact, returning the + * result from a pool. + * @param p Pool to allocate from + * @param url String to be unescaped in place + * @param forbid Optional list of forbidden characters, in addition to + * 0x00 + * @param reserved Optional list of reserved characters that will be + * left unescaped + * @param plus If non zero, '+' is converted to ' ' as per + * application/x-www-form-urlencoded encoding + * @return A string allocated from the pool on success, the original string + * if no characters are decoded, or NULL if a bad escape sequence is found + * or if a character on the forbid list is found, or if the original string + * was NULL. + */ +APR_DECLARE(const char *) apr_punescape_url(apr_pool_t *p, const char *url, + const char *forbid, const char *reserved, int plus) + __attribute__((nonnull(1))); + +/** + * Escape a path segment, as defined in RFC1808. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_path_segment(char *escaped, + const char *str, apr_ssize_t slen, apr_size_t *len); + +/** + * Escape a path segment, as defined in RFC1808, returning the result from a + * pool. + * @param p Pool to allocate from + * @param str String to be escaped + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or the string is NULL. + */ +APR_DECLARE(const char *) apr_pescape_path_segment(apr_pool_t *p, + const char *str) __attribute__((nonnull(1))); + +/** + * Converts an OS path to a URL, in an OS dependent way, as defined in RFC1808. + * In all cases if a ':' occurs before the first '/' in the URL, the URL should + * be prefixed with "./" (or the ':' escaped). In the case of Unix, this means + * leaving '/' alone, but otherwise doing what escape_path_segment() does. For + * efficiency reasons, we don't use escape_path_segment(), which is provided for + * reference. Again, RFC 1808 is where this stuff is defined. + * + * If partial is set, os_escape_path() assumes that the path will be appended to + * something with a '/' in it (and thus does not prefix "./"). + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param path The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param partial If non zero, suppresses the prepending of "./" + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or if the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_path(char *escaped, const char *path, + apr_ssize_t slen, int partial, apr_size_t *len); + +/** + * Converts an OS path to a URL, in an OS dependent way, as defined in RFC1808, + * returning the result from a pool. + * + * In all cases if a ':' occurs before the first '/' in the URL, the URL should + * be prefixed with "./" (or the ':' escaped). In the case of Unix, this means + * leaving '/' alone, but otherwise doing what escape_path_segment() does. For + * efficiency reasons, we don't use escape_path_segment(), which is provided for + * reference. Again, RFC 1808 is where this stuff is defined. + * + * If partial is set, os_escape_path() assumes that the path will be appended to + * something with a '/' in it (and thus does not prefix "./"). + * @param p Pool to allocate from + * @param str The original string + * @param partial If non zero, suppresses the prepending of "./" + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or if the string was NULL. + */ +APR_DECLARE(const char *) apr_pescape_path(apr_pool_t *p, const char *str, + int partial) __attribute__((nonnull(1))); + +/** + * Urlencode a string, as defined in + * http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or if the stirng was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_urlencoded(char *escaped, const char *str, + apr_ssize_t slen, apr_size_t *len); + +/** + * Urlencode a string, as defined in + * http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1, returning + * the result from a pool. + * @param p Pool to allocate from + * @param str String to be escaped + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or if the string was NULL. + */ +APR_DECLARE(const char *) apr_pescape_urlencoded(apr_pool_t *p, + const char *str) __attribute__((nonnull(1))); + +/** + * Apply entity encoding to a string. Characters are replaced as follows: + * '<' becomes '\<', '>' becomes '\>', '&' becomes '\&', the + * double quote becomes '\"" and the single quote becomes '\''. + * + * If toasc is not zero, any non ascii character will be encoded as + * '%\#ddd;', where ddd is the decimal code of the character. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param toasc If non zero, encode non ascii characters + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_entity(char *escaped, const char *str, + apr_ssize_t slen, int toasc, apr_size_t *len); + +/** + * Apply entity encoding to a string, returning the result from a pool. + * Characters are replaced as follows: '<' becomes '\<', '>' becomes + * '\>', '&' becomes '\&', the double quote becomes '\"" and the + * single quote becomes '\''. + * @param p Pool to allocate from + * @param str The original string + * @param toasc If non zero, encode non ascii characters + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or the string is NULL. + */ +APR_DECLARE(const char *) apr_pescape_entity(apr_pool_t *p, const char *str, + int toasc) __attribute__((nonnull(1))); + +/** + * Decodes html entities or numeric character references in a string. If + * the string to be unescaped is syntactically incorrect, then the + * following fixups will be made: + * unknown entities will be left undecoded; + * references to unused numeric characters will be deleted. + * In particular, � will not be decoded, but will be deleted. + * @param unescaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_unescape_entity(char *unescaped, const char *str, + apr_ssize_t slen, apr_size_t *len); + +/** + * Decodes html entities or numeric character references in a string. If + * the string to be unescaped is syntactically incorrect, then the + * following fixups will be made: + * unknown entities will be left undecoded; + * references to unused numeric characters will be deleted. + * In particular, � will not be decoded, but will be deleted. + * @param p Pool to allocate from + * @param str The original string + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or the string is NULL. + */ +APR_DECLARE(const char *) apr_punescape_entity(apr_pool_t *p, const char *str) + __attribute__((nonnull(1))); + +/** + * Escape control characters in a string, as performed by the shell's + * 'echo' command. Characters are replaced as follows: + * \\a alert (bell), \\b backspace, \\f form feed, \\n new line, \\r carriage + * return, \\t horizontal tab, \\v vertical tab, \\ backslash. + * + * Any non ascii character will be encoded as '\\xHH', where HH is the hex + * code of the character. + * + * If quote is not zero, the double quote character will also be escaped. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param quote If non zero, encode double quotes + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_echo(char *escaped, const char *str, + apr_ssize_t slen, int quote, apr_size_t *len); + +/** + * Escape control characters in a string, as performed by the shell's + * 'echo' command, and return the results from a pool. Characters are + * replaced as follows: \\a alert (bell), \\b backspace, \\f form feed, + * \\n new line, \\r carriage return, \\t horizontal tab, \\v vertical tab, + * \\ backslash. + * + * Any non ascii character will be encoded as '\\xHH', where HH is the hex + * code of the character. + * + * If quote is not zero, the double quote character will also be escaped. + * @param p Pool to allocate from + * @param str The original string + * @param quote If non zero, encode double quotes + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or the string is NULL. + */ +APR_DECLARE(const char *) apr_pescape_echo(apr_pool_t *p, const char *str, + int quote); + +/** + * Convert binary data to a hex encoding. + * @param dest The destination buffer, can be NULL + * @param src The original buffer + * @param srclen The length of the original buffer + * @param colon If not zero, insert colon characters between hex digits. + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_hex(char *dest, const void *src, + apr_size_t srclen, int colon, apr_size_t *len); + +/** + * Convert binary data to a hex encoding, and return the results from a + * pool. + * @param p Pool to allocate from + * @param src The original buffer + * @param slen The length of the original buffer + * @param colon If not zero, insert colon characters between hex digits. + * @return A zero padded buffer allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *) apr_pescape_hex(apr_pool_t *p, const void *src, + apr_size_t slen, int colon) __attribute__((nonnull(1))); + +/** + * Convert hex encoded string to binary data. + * @param dest The destination buffer, can be NULL + * @param str The original buffer + * @param slen The length of the original buffer + * @param colon If not zero, ignore colon characters between hex digits. + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL, or APR_BADCH + * if a non hex character is present. + */ +APR_DECLARE(apr_status_t) apr_unescape_hex(void *dest, const char *str, + apr_ssize_t slen, int colon, apr_size_t *len); + +/** + * Convert hex encoding to binary data, and return the results from a pool. + * If the colon character appears between pairs of hex digits, it will be + * ignored. + * @param p Pool to allocate from + * @param str The original string + * @param colon If not zero, ignore colon characters between hex digits. + * @param len If present, returns the length of the final buffer + * @return A buffer allocated from the pool on success, or NULL if src was + * NULL, or a bad character was present. + */ +APR_DECLARE(const void *) apr_punescape_hex(apr_pool_t *p, const char *str, + int colon, apr_size_t *len); + +/** + * Apply LDAP escaping to binary data. Characters from RFC4514 and RFC4515 + * are escaped with their hex equivalents. + * @param dest The destination buffer, can be NULL + * @param src The original buffer + * @param srclen The length of the original buffer + * @param flags APR_ESCAPE_LDAP_DN for RFC4514, APR_ESCAPE_LDAP_FILTER for + * RFC4515, APR_ESCAPE_LDAP_ALL for both + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_ldap(char *dest, const void *src, + apr_ssize_t srclen, int flags, apr_size_t *len); + +/** + * Apply LDAP escaping to binary data, and return the results from a + * pool. Characters from RFC4514 and RFC4515 are escaped with their hex + * equivalents. + * @param p Pool to allocate from + * @param src The original buffer + * @param slen The length of the original buffer + * @param flags APR_ESCAPE_LDAP_DN for RFC4514, APR_ESCAPE_LDAP_FILTER for + * RFC4515, APR_ESCAPE_LDAP_ALL for both + * @return A zero padded buffer allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *) apr_pescape_ldap(apr_pool_t *p, const void *src, + apr_ssize_t slen, int flags) __attribute__((nonnull(1))); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ESCAPE_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_escape_test_char.h b/c/dependencies/windows/apr/x86/include/apr_escape_test_char.h new file mode 100644 index 00000000..ad36c615 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_escape_test_char.h @@ -0,0 +1,25 @@ +/* this file is automatically generated by gen_test_char, do not edit. "make include/private/apr_escape_test_char.h" to regenerate. */ +#define T_ESCAPE_SHELL_CMD (1) +#define T_ESCAPE_PATH_SEGMENT (2) +#define T_OS_ESCAPE_PATH (4) +#define T_ESCAPE_ECHO (8) +#define T_ESCAPE_URLENCODED (16) +#define T_ESCAPE_XML (32) +#define T_ESCAPE_LDAP_DN (64) +#define T_ESCAPE_LDAP_FILTER (128) + +static const unsigned char test_char_table[256] = { + 224,222,222,222,222,222,222,222,222,222,223,222,222,223,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,6,16,127,22,17,23,49,17, + 145,145,129,80,80,0,0,18,0,0,0,0,0,0,0,0,0,0,16,87, + 119,16,119,23,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,23,223,23,23,0,23,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,23,23,23,17,222,222,222,222,222,222,222,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222 +}; diff --git a/c/dependencies/windows/apr/x86/include/apr_file_info.h b/c/dependencies/windows/apr/x86/include/apr_file_info.h new file mode 100644 index 00000000..cfddc68d --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_file_info.h @@ -0,0 +1,428 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_FILE_INFO_H +#define APR_FILE_INFO_H + +/** + * @file apr_file_info.h + * @brief APR File Information + */ + +#include "apr.h" +#include "apr_user.h" +#include "apr_pools.h" +#include "apr_tables.h" +#include "apr_time.h" +#include "apr_errno.h" + +#if APR_HAVE_SYS_UIO_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_file_info File Information + * @ingroup APR + * @{ + */ + +/* Many applications use the type member to determine the + * existance of a file or initialization of the file info, + * so the APR_NOFILE value must be distinct from APR_UNKFILE. + */ + +/** apr_filetype_e values for the filetype member of the + * apr_file_info_t structure + * @warning Not all of the filetypes below can be determined. + * For example, a given platform might not correctly report + * a socket descriptor as APR_SOCK if that type isn't + * well-identified on that platform. In such cases where + * a filetype exists but cannot be described by the recognized + * flags below, the filetype will be APR_UNKFILE. If the + * filetype member is not determined, the type will be APR_NOFILE. + */ + +typedef enum { + APR_NOFILE = 0, /**< no file type determined */ + APR_REG, /**< a regular file */ + APR_DIR, /**< a directory */ + APR_CHR, /**< a character device */ + APR_BLK, /**< a block device */ + APR_PIPE, /**< a FIFO / pipe */ + APR_LNK, /**< a symbolic link */ + APR_SOCK, /**< a [unix domain] socket */ + APR_UNKFILE = 127 /**< a file of some other unknown type */ +} apr_filetype_e; + +/** + * @defgroup apr_file_permissions File Permissions flags + * @{ + */ + +#define APR_FPROT_USETID 0x8000 /**< Set user id */ +#define APR_FPROT_UREAD 0x0400 /**< Read by user */ +#define APR_FPROT_UWRITE 0x0200 /**< Write by user */ +#define APR_FPROT_UEXECUTE 0x0100 /**< Execute by user */ + +#define APR_FPROT_GSETID 0x4000 /**< Set group id */ +#define APR_FPROT_GREAD 0x0040 /**< Read by group */ +#define APR_FPROT_GWRITE 0x0020 /**< Write by group */ +#define APR_FPROT_GEXECUTE 0x0010 /**< Execute by group */ + +#define APR_FPROT_WSTICKY 0x2000 /**< Sticky bit */ +#define APR_FPROT_WREAD 0x0004 /**< Read by others */ +#define APR_FPROT_WWRITE 0x0002 /**< Write by others */ +#define APR_FPROT_WEXECUTE 0x0001 /**< Execute by others */ + +#define APR_FPROT_OS_DEFAULT 0x0FFF /**< use OS's default permissions */ + +/* additional permission flags for apr_file_copy and apr_file_append */ +#define APR_FPROT_FILE_SOURCE_PERMS 0x1000 /**< Copy source file's permissions */ + +/* backcompat */ +#define APR_USETID APR_FPROT_USETID /**< @deprecated @see APR_FPROT_USETID */ +#define APR_UREAD APR_FPROT_UREAD /**< @deprecated @see APR_FPROT_UREAD */ +#define APR_UWRITE APR_FPROT_UWRITE /**< @deprecated @see APR_FPROT_UWRITE */ +#define APR_UEXECUTE APR_FPROT_UEXECUTE /**< @deprecated @see APR_FPROT_UEXECUTE */ +#define APR_GSETID APR_FPROT_GSETID /**< @deprecated @see APR_FPROT_GSETID */ +#define APR_GREAD APR_FPROT_GREAD /**< @deprecated @see APR_FPROT_GREAD */ +#define APR_GWRITE APR_FPROT_GWRITE /**< @deprecated @see APR_FPROT_GWRITE */ +#define APR_GEXECUTE APR_FPROT_GEXECUTE /**< @deprecated @see APR_FPROT_GEXECUTE */ +#define APR_WSTICKY APR_FPROT_WSTICKY /**< @deprecated @see APR_FPROT_WSTICKY */ +#define APR_WREAD APR_FPROT_WREAD /**< @deprecated @see APR_FPROT_WREAD */ +#define APR_WWRITE APR_FPROT_WWRITE /**< @deprecated @see APR_FPROT_WWRITE */ +#define APR_WEXECUTE APR_FPROT_WEXECUTE /**< @deprecated @see APR_FPROT_WEXECUTE */ +#define APR_OS_DEFAULT APR_FPROT_OS_DEFAULT /**< @deprecated @see APR_FPROT_OS_DEFAULT */ +#define APR_FILE_SOURCE_PERMS APR_FPROT_FILE_SOURCE_PERMS /**< @deprecated @see APR_FPROT_FILE_SOURCE_PERMS */ + +/** @} */ + + +/** + * Structure for referencing directories. + */ +typedef struct apr_dir_t apr_dir_t; +/** + * Structure for determining file permissions. + */ +typedef apr_int32_t apr_fileperms_t; +#if (defined WIN32) || (defined NETWARE) +/** + * Structure for determining the device the file is on. + */ +typedef apr_uint32_t apr_dev_t; +#else +/** + * Structure for determining the device the file is on. + */ +typedef dev_t apr_dev_t; +#endif + +/** + * @defgroup apr_file_stat Stat Functions + * @{ + */ +/** file info structure */ +typedef struct apr_finfo_t apr_finfo_t; + +#define APR_FINFO_LINK 0x00000001 /**< Stat the link not the file itself if it is a link */ +#define APR_FINFO_MTIME 0x00000010 /**< Modification Time */ +#define APR_FINFO_CTIME 0x00000020 /**< Creation or inode-changed time */ +#define APR_FINFO_ATIME 0x00000040 /**< Access Time */ +#define APR_FINFO_SIZE 0x00000100 /**< Size of the file */ +#define APR_FINFO_CSIZE 0x00000200 /**< Storage size consumed by the file */ +#define APR_FINFO_DEV 0x00001000 /**< Device */ +#define APR_FINFO_INODE 0x00002000 /**< Inode */ +#define APR_FINFO_NLINK 0x00004000 /**< Number of links */ +#define APR_FINFO_TYPE 0x00008000 /**< Type */ +#define APR_FINFO_USER 0x00010000 /**< User */ +#define APR_FINFO_GROUP 0x00020000 /**< Group */ +#define APR_FINFO_UPROT 0x00100000 /**< User protection bits */ +#define APR_FINFO_GPROT 0x00200000 /**< Group protection bits */ +#define APR_FINFO_WPROT 0x00400000 /**< World protection bits */ +#define APR_FINFO_ICASE 0x01000000 /**< if dev is case insensitive */ +#define APR_FINFO_NAME 0x02000000 /**< ->name in proper case */ + +#define APR_FINFO_MIN 0x00008170 /**< type, mtime, ctime, atime, size */ +#define APR_FINFO_IDENT 0x00003000 /**< dev and inode */ +#define APR_FINFO_OWNER 0x00030000 /**< user and group */ +#define APR_FINFO_PROT 0x00700000 /**< all protections */ +#define APR_FINFO_NORM 0x0073b170 /**< an atomic unix apr_stat() */ +#define APR_FINFO_DIRENT 0x02000000 /**< an atomic unix apr_dir_read() */ + +/** + * The file information structure. This is analogous to the POSIX + * stat structure. + */ +struct apr_finfo_t { + /** Allocates memory and closes lingering handles in the specified pool */ + apr_pool_t *pool; + /** The bitmask describing valid fields of this apr_finfo_t structure + * including all available 'wanted' fields and potentially more */ + apr_int32_t valid; + /** The access permissions of the file. Mimics Unix access rights. */ + apr_fileperms_t protection; + /** The type of file. One of APR_REG, APR_DIR, APR_CHR, APR_BLK, APR_PIPE, + * APR_LNK or APR_SOCK. If the type is undetermined, the value is APR_NOFILE. + * If the type cannot be determined, the value is APR_UNKFILE. + */ + apr_filetype_e filetype; + /** The user id that owns the file */ + apr_uid_t user; + /** The group id that owns the file */ + apr_gid_t group; + /** The inode of the file. */ + apr_ino_t inode; + /** The id of the device the file is on. */ + apr_dev_t device; + /** The number of hard links to the file. */ + apr_int32_t nlink; + /** The size of the file */ + apr_off_t size; + /** The storage size consumed by the file */ + apr_off_t csize; + /** The time the file was last accessed */ + apr_time_t atime; + /** The time the file was last modified */ + apr_time_t mtime; + /** The time the file was created, or the inode was last changed */ + apr_time_t ctime; + /** The pathname of the file (possibly unrooted) */ + const char *fname; + /** The file's name (no path) in filesystem case */ + const char *name; + /** Unused */ + struct apr_file_t *filehand; +}; + +/** + * get the specified file's stats. The file is specified by filename, + * instead of using a pre-opened file. + * @param finfo Where to store the information about the file, which is + * never touched if the call fails. + * @param fname The name of the file to stat. + * @param wanted The desired apr_finfo_t fields, as a bit flag of APR_FINFO_ + values + * @param pool the pool to use to allocate the new file. + * + * @note If @c APR_INCOMPLETE is returned all the fields in @a finfo may + * not be filled in, and you need to check the @c finfo->valid bitmask + * to verify that what you're looking for is there. + */ +APR_DECLARE(apr_status_t) apr_stat(apr_finfo_t *finfo, const char *fname, + apr_int32_t wanted, apr_pool_t *pool); + +/** @} */ +/** + * @defgroup apr_dir Directory Manipulation Functions + * @{ + */ + +/** + * Open the specified directory. + * @param new_dir The opened directory descriptor. + * @param dirname The full path to the directory (use / on all systems) + * @param pool The pool to use. + */ +APR_DECLARE(apr_status_t) apr_dir_open(apr_dir_t **new_dir, + const char *dirname, + apr_pool_t *pool); + +/** + * close the specified directory. + * @param thedir the directory descriptor to close. + */ +APR_DECLARE(apr_status_t) apr_dir_close(apr_dir_t *thedir); + +/** + * Read the next entry from the specified directory. + * @param finfo the file info structure and filled in by apr_dir_read + * @param wanted The desired apr_finfo_t fields, as a bit flag of APR_FINFO_ + values + * @param thedir the directory descriptor returned from apr_dir_open + * @remark No ordering is guaranteed for the entries read. + * + * @note If @c APR_INCOMPLETE is returned all the fields in @a finfo may + * not be filled in, and you need to check the @c finfo->valid bitmask + * to verify that what you're looking for is there. When no more + * entries are available, APR_ENOENT is returned. + */ +APR_DECLARE(apr_status_t) apr_dir_read(apr_finfo_t *finfo, apr_int32_t wanted, + apr_dir_t *thedir); + +/** + * Rewind the directory to the first entry. + * @param thedir the directory descriptor to rewind. + */ +APR_DECLARE(apr_status_t) apr_dir_rewind(apr_dir_t *thedir); +/** @} */ + +/** + * @defgroup apr_filepath Filepath Manipulation Functions + * @{ + */ + +/** Cause apr_filepath_merge to fail if addpath is above rootpath + * @bug in APR 0.9 and 1.x, this flag's behavior is undefined + * if the rootpath is NULL or empty. In APR 2.0 this should be + * changed to imply NOTABSOLUTE if the rootpath is NULL or empty. + */ +#define APR_FILEPATH_NOTABOVEROOT 0x01 + +/** internal: Only meaningful with APR_FILEPATH_NOTABOVEROOT */ +#define APR_FILEPATH_SECUREROOTTEST 0x02 + +/** Cause apr_filepath_merge to fail if addpath is above rootpath, + * even given a rootpath /foo/bar and an addpath ../bar/bash + */ +#define APR_FILEPATH_SECUREROOT 0x03 + +/** Fail apr_filepath_merge if the merged path is relative */ +#define APR_FILEPATH_NOTRELATIVE 0x04 + +/** Fail apr_filepath_merge if the merged path is absolute */ +#define APR_FILEPATH_NOTABSOLUTE 0x08 + +/** Return the file system's native path format (e.g. path delimiters + * of ':' on MacOS9, '\' on Win32, etc.) */ +#define APR_FILEPATH_NATIVE 0x10 + +/** Resolve the true case of existing directories and file elements + * of addpath, (resolving any aliases on Win32) and append a proper + * trailing slash if a directory + */ +#define APR_FILEPATH_TRUENAME 0x20 + +/** + * Extract the rootpath from the given filepath + * @param rootpath the root file path returned with APR_SUCCESS or APR_EINCOMPLETE + * @param filepath the pathname to parse for its root component + * @param flags the desired rules to apply, from + *
+ *      APR_FILEPATH_NATIVE    Use native path separators (e.g. '\' on Win32)
+ *      APR_FILEPATH_TRUENAME  Tests that the root exists, and makes it proper
+ * 
+ * @param p the pool to allocate the new path string from + * @remark on return, filepath points to the first non-root character in the + * given filepath. In the simplest example, given a filepath of "/foo", + * returns the rootpath of "/" and filepath points at "foo". This is far + * more complex on other platforms, which will canonicalize the root form + * to a consistant format, given the APR_FILEPATH_TRUENAME flag, and also + * test for the validity of that root (e.g., that a drive d:/ or network + * share //machine/foovol/). + * The function returns APR_ERELATIVE if filepath isn't rooted (an + * error), APR_EINCOMPLETE if the root path is ambiguous (but potentially + * legitimate, e.g. "/" on Windows is incomplete because it doesn't specify + * the drive letter), or APR_EBADPATH if the root is simply invalid. + * APR_SUCCESS is returned if filepath is an absolute path. + */ +APR_DECLARE(apr_status_t) apr_filepath_root(const char **rootpath, + const char **filepath, + apr_int32_t flags, + apr_pool_t *p); + +/** + * Merge additional file path onto the previously processed rootpath + * @param newpath the merged paths returned + * @param rootpath the root file path (NULL uses the current working path) + * @param addpath the path to add to the root path + * @param flags the desired APR_FILEPATH_ rules to apply when merging + * @param p the pool to allocate the new path string from + * @remark if the flag APR_FILEPATH_TRUENAME is given, and the addpath + * contains wildcard characters ('*', '?') on platforms that don't support + * such characters within filenames, the paths will be merged, but the + * result code will be APR_EPATHWILD, and all further segments will not + * reflect the true filenames including the wildcard and following segments. + */ +APR_DECLARE(apr_status_t) apr_filepath_merge(char **newpath, + const char *rootpath, + const char *addpath, + apr_int32_t flags, + apr_pool_t *p); + +/** + * Split a search path into separate components + * @param pathelts the returned components of the search path + * @param liststr the search path (e.g., getenv("PATH")) + * @param p the pool to allocate the array and path components from + * @remark empty path components do not become part of @a pathelts. + * @remark the path separator in @a liststr is system specific; + * e.g., ':' on Unix, ';' on Windows, etc. + */ +APR_DECLARE(apr_status_t) apr_filepath_list_split(apr_array_header_t **pathelts, + const char *liststr, + apr_pool_t *p); + +/** + * Merge a list of search path components into a single search path + * @param liststr the returned search path; may be NULL if @a pathelts is empty + * @param pathelts the components of the search path + * @param p the pool to allocate the search path from + * @remark emtpy strings in the source array are ignored. + * @remark the path separator in @a liststr is system specific; + * e.g., ':' on Unix, ';' on Windows, etc. + */ +APR_DECLARE(apr_status_t) apr_filepath_list_merge(char **liststr, + apr_array_header_t *pathelts, + apr_pool_t *p); + +/** + * Return the default file path (for relative file names) + * @param path the default path string returned + * @param flags optional flag APR_FILEPATH_NATIVE to retrieve the + * default file path in os-native format. + * @param p the pool to allocate the default path string from + */ +APR_DECLARE(apr_status_t) apr_filepath_get(char **path, apr_int32_t flags, + apr_pool_t *p); + +/** + * Set the default file path (for relative file names) + * @param path the default path returned + * @param p the pool to allocate any working storage + */ +APR_DECLARE(apr_status_t) apr_filepath_set(const char *path, apr_pool_t *p); + +/** The FilePath character encoding is unknown */ +#define APR_FILEPATH_ENCODING_UNKNOWN 0 + +/** The FilePath character encoding is locale-dependent */ +#define APR_FILEPATH_ENCODING_LOCALE 1 + +/** The FilePath character encoding is UTF-8 */ +#define APR_FILEPATH_ENCODING_UTF8 2 + +/** + * Determine the encoding used internally by the FilePath functions + * @param style points to a variable which receives the encoding style flag + * @param p the pool to allocate any working storage + * @remark Use apr_os_locale_encoding() and/or apr_os_default_encoding() + * to get the name of the path encoding if it's not UTF-8. + */ +APR_DECLARE(apr_status_t) apr_filepath_encoding(int *style, apr_pool_t *p); +/** @} */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_FILE_INFO_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_file_io.h b/c/dependencies/windows/apr/x86/include/apr_file_io.h new file mode 100644 index 00000000..af931939 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_file_io.h @@ -0,0 +1,1005 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_FILE_IO_H +#define APR_FILE_IO_H + +/** + * @file apr_file_io.h + * @brief APR File I/O Handling + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_time.h" +#include "apr_errno.h" +#include "apr_file_info.h" +#include "apr_inherit.h" + +#define APR_WANT_STDIO /**< for SEEK_* */ +#define APR_WANT_IOVEC /**< for apr_file_writev */ +#include "apr_want.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_file_io File I/O Handling Functions + * @ingroup APR + * @{ + */ + +/** + * @defgroup apr_file_open_flags File Open Flags/Routines + * @{ + */ + +/* Note to implementors: Values in the range 0x00100000--0x80000000 + are reserved for platform-specific values. */ + +#define APR_FOPEN_READ 0x00001 /**< Open the file for reading */ +#define APR_FOPEN_WRITE 0x00002 /**< Open the file for writing */ +#define APR_FOPEN_CREATE 0x00004 /**< Create the file if not there */ +#define APR_FOPEN_APPEND 0x00008 /**< Append to the end of the file */ +#define APR_FOPEN_TRUNCATE 0x00010 /**< Open the file and truncate + to 0 length */ +#define APR_FOPEN_BINARY 0x00020 /**< Open the file in binary mode + (This flag is ignored on UNIX + because it has no meaning)*/ +#define APR_FOPEN_EXCL 0x00040 /**< Open should fail if #APR_FOPEN_CREATE + and file exists. */ +#define APR_FOPEN_BUFFERED 0x00080 /**< Open the file for buffered I/O */ +#define APR_FOPEN_DELONCLOSE 0x00100 /**< Delete the file after close */ +#define APR_FOPEN_XTHREAD 0x00200 /**< Platform dependent tag to open + the file for use across multiple + threads */ +#define APR_FOPEN_SHARELOCK 0x00400 /**< Platform dependent support for + higher level locked read/write + access to support writes across + process/machines */ +#define APR_FOPEN_NOCLEANUP 0x00800 /**< Do not register a cleanup + when the file is opened. The + apr_os_file_t handle in apr_file_t + will not be closed when the pool + is destroyed. */ +#define APR_FOPEN_SENDFILE_ENABLED 0x01000 /**< Advisory flag that this + file should support + apr_socket_sendfile operation */ +#define APR_FOPEN_LARGEFILE 0x04000 /**< Platform dependent flag to enable + * large file support, see WARNING below + */ +#define APR_FOPEN_SPARSE 0x08000 /**< Platform dependent flag to enable + * sparse file support, see WARNING below + */ +#define APR_FOPEN_NONBLOCK 0x40000 /**< Platform dependent flag to enable + * non blocking file io */ + + +/* backcompat */ +#define APR_READ APR_FOPEN_READ /**< @deprecated @see APR_FOPEN_READ */ +#define APR_WRITE APR_FOPEN_WRITE /**< @deprecated @see APR_FOPEN_WRITE */ +#define APR_CREATE APR_FOPEN_CREATE /**< @deprecated @see APR_FOPEN_CREATE */ +#define APR_APPEND APR_FOPEN_APPEND /**< @deprecated @see APR_FOPEN_APPEND */ +#define APR_TRUNCATE APR_FOPEN_TRUNCATE /**< @deprecated @see APR_FOPEN_TRUNCATE */ +#define APR_BINARY APR_FOPEN_BINARY /**< @deprecated @see APR_FOPEN_BINARY */ +#define APR_EXCL APR_FOPEN_EXCL /**< @deprecated @see APR_FOPEN_EXCL */ +#define APR_BUFFERED APR_FOPEN_BUFFERED /**< @deprecated @see APR_FOPEN_BUFFERED */ +#define APR_DELONCLOSE APR_FOPEN_DELONCLOSE /**< @deprecated @see APR_FOPEN_DELONCLOSE */ +#define APR_XTHREAD APR_FOPEN_XTHREAD /**< @deprecated @see APR_FOPEN_XTHREAD */ +#define APR_SHARELOCK APR_FOPEN_SHARELOCK /**< @deprecated @see APR_FOPEN_SHARELOCK */ +#define APR_FILE_NOCLEANUP APR_FOPEN_NOCLEANUP /**< @deprecated @see APR_FOPEN_NOCLEANUP */ +#define APR_SENDFILE_ENABLED APR_FOPEN_SENDFILE_ENABLED /**< @deprecated @see APR_FOPEN_SENDFILE_ENABLED */ +#define APR_LARGEFILE APR_FOPEN_LARGEFILE /**< @deprecated @see APR_FOPEN_LARGEFILE */ + +/** @def APR_FOPEN_LARGEFILE + * @warning APR_FOPEN_LARGEFILE flag only has effect on some + * platforms where sizeof(apr_off_t) == 4. Where implemented, it + * allows opening and writing to a file which exceeds the size which + * can be represented by apr_off_t (2 gigabytes). When a file's size + * does exceed 2Gb, apr_file_info_get() will fail with an error on the + * descriptor, likewise apr_stat()/apr_lstat() will fail on the + * filename. apr_dir_read() will fail with #APR_INCOMPLETE on a + * directory entry for a large file depending on the particular + * APR_FINFO_* flags. Generally, it is not recommended to use this + * flag. + * + * @def APR_FOPEN_SPARSE + * @warning APR_FOPEN_SPARSE may, depending on platform, convert a + * normal file to a sparse file. Some applications may be unable + * to decipher a sparse file, so it's critical that the sparse file + * flag should only be used for files accessed only by APR or other + * applications known to be able to decipher them. APR does not + * guarantee that it will compress the file into sparse segments + * if it was previously created and written without the sparse flag. + * On platforms which do not understand, or on file systems which + * cannot handle sparse files, the flag is ignored by apr_file_open(). + * + * @def APR_FOPEN_NONBLOCK + * @warning APR_FOPEN_NONBLOCK is not implemented on all platforms. + * Callers should be prepared for it to fail with #APR_ENOTIMPL. + */ + +/** @} */ + +/** + * @defgroup apr_file_seek_flags File Seek Flags + * @{ + */ + +/* flags for apr_file_seek */ +/** Set the file position */ +#define APR_SET SEEK_SET +/** Current */ +#define APR_CUR SEEK_CUR +/** Go to end of file */ +#define APR_END SEEK_END +/** @} */ + +/** + * @defgroup apr_file_attrs_set_flags File Attribute Flags + * @{ + */ + +/* flags for apr_file_attrs_set */ +#define APR_FILE_ATTR_READONLY 0x01 /**< File is read-only */ +#define APR_FILE_ATTR_EXECUTABLE 0x02 /**< File is executable */ +#define APR_FILE_ATTR_HIDDEN 0x04 /**< File is hidden */ +/** @} */ + +/** + * @defgroup apr_file_writev{_full} max iovec size + * @{ + */ +#if defined(DOXYGEN) +#define APR_MAX_IOVEC_SIZE 1024 /**< System dependent maximum + size of an iovec array */ +#elif defined(IOV_MAX) +#define APR_MAX_IOVEC_SIZE IOV_MAX +#elif defined(MAX_IOVEC) +#define APR_MAX_IOVEC_SIZE MAX_IOVEC +#else +#define APR_MAX_IOVEC_SIZE 1024 +#endif +/** @} */ + +/** File attributes */ +typedef apr_uint32_t apr_fileattrs_t; + +/** Type to pass as whence argument to apr_file_seek. */ +typedef int apr_seek_where_t; + +/** + * Structure for referencing files. + */ +typedef struct apr_file_t apr_file_t; + +/* File lock types/flags */ +/** + * @defgroup apr_file_lock_types File Lock Types + * @{ + */ + +#define APR_FLOCK_SHARED 1 /**< Shared lock. More than one process + or thread can hold a shared lock + at any given time. Essentially, + this is a "read lock", preventing + writers from establishing an + exclusive lock. */ +#define APR_FLOCK_EXCLUSIVE 2 /**< Exclusive lock. Only one process + may hold an exclusive lock at any + given time. This is analogous to + a "write lock". */ + +#define APR_FLOCK_TYPEMASK 0x000F /**< mask to extract lock type */ +#define APR_FLOCK_NONBLOCK 0x0010 /**< do not block while acquiring the + file lock */ +/** @} */ + +/** + * Open the specified file. + * @param newf The opened file descriptor. + * @param fname The full path to the file (using / on all systems) + * @param flag Or'ed value of: + * @li #APR_FOPEN_READ open for reading + * @li #APR_FOPEN_WRITE open for writing + * @li #APR_FOPEN_CREATE create the file if not there + * @li #APR_FOPEN_APPEND file ptr is set to end prior to all writes + * @li #APR_FOPEN_TRUNCATE set length to zero if file exists + * @li #APR_FOPEN_BINARY not a text file + * @li #APR_FOPEN_BUFFERED buffer the data. Default is non-buffered + * @li #APR_FOPEN_EXCL return error if #APR_FOPEN_CREATE and file exists + * @li #APR_FOPEN_DELONCLOSE delete the file after closing + * @li #APR_FOPEN_XTHREAD Platform dependent tag to open the file + * for use across multiple threads + * @li #APR_FOPEN_SHARELOCK Platform dependent support for higher + * level locked read/write access to support + * writes across process/machines + * @li #APR_FOPEN_NOCLEANUP Do not register a cleanup with the pool + * passed in on the @a pool argument (see below) + * @li #APR_FOPEN_SENDFILE_ENABLED Open with appropriate platform semantics + * for sendfile operations. Advisory only, + * apr_socket_sendfile does not check this flag + * @li #APR_FOPEN_LARGEFILE Platform dependent flag to enable large file + * support, see WARNING below + * @li #APR_FOPEN_SPARSE Platform dependent flag to enable sparse file + * support, see WARNING below + * @li #APR_FOPEN_NONBLOCK Platform dependent flag to enable + * non blocking file io + * @param perm Access permissions for file. + * @param pool The pool to use. + * @remark If perm is #APR_FPROT_OS_DEFAULT and the file is being created, + * appropriate default permissions will be used. + * @remark By default, the returned file descriptor will not be + * inherited by child processes created by apr_proc_create(). This + * can be changed using apr_file_inherit_set(). + */ +APR_DECLARE(apr_status_t) apr_file_open(apr_file_t **newf, const char *fname, + apr_int32_t flag, apr_fileperms_t perm, + apr_pool_t *pool); + +/** + * Close the specified file. + * @param file The file descriptor to close. + */ +APR_DECLARE(apr_status_t) apr_file_close(apr_file_t *file); + +/** + * Delete the specified file. + * @param path The full path to the file (using / on all systems) + * @param pool The pool to use. + * @remark If the file is open, it won't be removed until all + * instances are closed. + */ +APR_DECLARE(apr_status_t) apr_file_remove(const char *path, apr_pool_t *pool); + +/** + * Rename the specified file. + * @param from_path The full path to the original file (using / on all systems) + * @param to_path The full path to the new file (using / on all systems) + * @param pool The pool to use. + * @warning If a file exists at the new location, then it will be + * overwritten. Moving files or directories across devices may not be + * possible. + */ +APR_DECLARE(apr_status_t) apr_file_rename(const char *from_path, + const char *to_path, + apr_pool_t *pool); + +/** + * Create a hard link to the specified file. + * @param from_path The full path to the original file (using / on all systems) + * @param to_path The full path to the new file (using / on all systems) + * @remark Both files must reside on the same device. + */ +APR_DECLARE(apr_status_t) apr_file_link(const char *from_path, + const char *to_path); + +/** + * Copy the specified file to another file. + * @param from_path The full path to the original file (using / on all systems) + * @param to_path The full path to the new file (using / on all systems) + * @param perms Access permissions for the new file if it is created. + * In place of the usual or'd combination of file permissions, the + * value #APR_FPROT_FILE_SOURCE_PERMS may be given, in which case the source + * file's permissions are copied. + * @param pool The pool to use. + * @remark The new file does not need to exist, it will be created if required. + * @warning If the new file already exists, its contents will be overwritten. + */ +APR_DECLARE(apr_status_t) apr_file_copy(const char *from_path, + const char *to_path, + apr_fileperms_t perms, + apr_pool_t *pool); + +/** + * Append the specified file to another file. + * @param from_path The full path to the source file (use / on all systems) + * @param to_path The full path to the destination file (use / on all systems) + * @param perms Access permissions for the destination file if it is created. + * In place of the usual or'd combination of file permissions, the + * value #APR_FPROT_FILE_SOURCE_PERMS may be given, in which case the source + * file's permissions are copied. + * @param pool The pool to use. + * @remark The new file does not need to exist, it will be created if required. + * @remark Note that advanced filesystem permissions such as ACLs are not + * duplicated by this API. The target permissions (including duplicating the + * source file permissions) are assigned only when the target file does not yet + * exist. + */ +APR_DECLARE(apr_status_t) apr_file_append(const char *from_path, + const char *to_path, + apr_fileperms_t perms, + apr_pool_t *pool); + +/** + * Are we at the end of the file + * @param fptr The apr file we are testing. + * @remark Returns #APR_EOF if we are at the end of file, #APR_SUCCESS otherwise. + */ +APR_DECLARE(apr_status_t) apr_file_eof(apr_file_t *fptr); + +/** + * Open standard error as an apr file pointer. + * @param thefile The apr file to use as stderr. + * @param pool The pool to allocate the file out of. + * + * @remark The only reason that the apr_file_open_std* functions exist + * is that you may not always have a stderr/out/in on Windows. This + * is generally a problem with newer versions of Windows and services. + * + * @remark The other problem is that the C library functions generally work + * differently on Windows and Unix. So, by using apr_file_open_std* + * functions, you can get a handle to an APR struct that works with + * the APR functions which are supposed to work identically on all + * platforms. + */ +APR_DECLARE(apr_status_t) apr_file_open_stderr(apr_file_t **thefile, + apr_pool_t *pool); + +/** + * open standard output as an apr file pointer. + * @param thefile The apr file to use as stdout. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_stdout(apr_file_t **thefile, + apr_pool_t *pool); + +/** + * open standard input as an apr file pointer. + * @param thefile The apr file to use as stdin. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_stdin(apr_file_t **thefile, + apr_pool_t *pool); + +/** + * open standard error as an apr file pointer, with flags. + * @param thefile The apr file to use as stderr. + * @param flags The flags to open the file with. Only the + * @li #APR_FOPEN_EXCL + * @li #APR_FOPEN_BUFFERED + * @li #APR_FOPEN_XTHREAD + * @li #APR_FOPEN_SHARELOCK + * @li #APR_FOPEN_SENDFILE_ENABLED + * @li #APR_FOPEN_LARGEFILE + * + * flags should be used. The #APR_FOPEN_WRITE flag will + * be set unconditionally. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_flags_stderr(apr_file_t **thefile, + apr_int32_t flags, + apr_pool_t *pool); + +/** + * open standard output as an apr file pointer, with flags. + * @param thefile The apr file to use as stdout. + * @param flags The flags to open the file with. Only the + * @li #APR_FOPEN_EXCL + * @li #APR_FOPEN_BUFFERED + * @li #APR_FOPEN_XTHREAD + * @li #APR_FOPEN_SHARELOCK + * @li #APR_FOPEN_SENDFILE_ENABLED + * @li #APR_FOPEN_LARGEFILE + * + * flags should be used. The #APR_FOPEN_WRITE flag will + * be set unconditionally. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_flags_stdout(apr_file_t **thefile, + apr_int32_t flags, + apr_pool_t *pool); + +/** + * open standard input as an apr file pointer, with flags. + * @param thefile The apr file to use as stdin. + * @param flags The flags to open the file with. Only the + * @li #APR_FOPEN_EXCL + * @li #APR_FOPEN_BUFFERED + * @li #APR_FOPEN_XTHREAD + * @li #APR_FOPEN_SHARELOCK + * @li #APR_FOPEN_SENDFILE_ENABLED + * @li #APR_FOPEN_LARGEFILE + * + * flags should be used. The #APR_FOPEN_WRITE flag will + * be set unconditionally. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_flags_stdin(apr_file_t **thefile, + apr_int32_t flags, + apr_pool_t *pool); + +/** + * Read data from the specified file. + * @param thefile The file descriptor to read from. + * @param buf The buffer to store the data to. + * @param nbytes On entry, the number of bytes to read; on exit, the number + * of bytes read. + * + * @remark apr_file_read() will read up to the specified number of + * bytes, but never more. If there isn't enough data to fill that + * number of bytes, all of the available data is read. The third + * argument is modified to reflect the number of bytes read. If a + * char was put back into the stream via ungetc, it will be the first + * character returned. + * + * @remark It is not possible for both bytes to be read and an #APR_EOF + * or other error to be returned. #APR_EINTR is never returned. + */ +APR_DECLARE(apr_status_t) apr_file_read(apr_file_t *thefile, void *buf, + apr_size_t *nbytes); + +/** + * Write data to the specified file. + * @param thefile The file descriptor to write to. + * @param buf The buffer which contains the data. + * @param nbytes On entry, the number of bytes to write; on exit, the number + * of bytes written. + * + * @remark apr_file_write() will write up to the specified number of + * bytes, but never more. If the OS cannot write that many bytes, it + * will write as many as it can. The third argument is modified to + * reflect the * number of bytes written. + * + * @remark It is possible for both bytes to be written and an error to + * be returned. #APR_EINTR is never returned. + */ +APR_DECLARE(apr_status_t) apr_file_write(apr_file_t *thefile, const void *buf, + apr_size_t *nbytes); + +/** + * Write data from iovec array to the specified file. + * @param thefile The file descriptor to write to. + * @param vec The array from which to get the data to write to the file. + * @param nvec The number of elements in the struct iovec array. This must + * be smaller than #APR_MAX_IOVEC_SIZE. If it isn't, the function + * will fail with #APR_EINVAL. + * @param nbytes The number of bytes written. + * + * @remark It is possible for both bytes to be written and an error to + * be returned. #APR_EINTR is never returned. + * + * @remark apr_file_writev() is available even if the underlying + * operating system doesn't provide writev(). + */ +APR_DECLARE(apr_status_t) apr_file_writev(apr_file_t *thefile, + const struct iovec *vec, + apr_size_t nvec, apr_size_t *nbytes); + +/** + * Read data from the specified file, ensuring that the buffer is filled + * before returning. + * @param thefile The file descriptor to read from. + * @param buf The buffer to store the data to. + * @param nbytes The number of bytes to read. + * @param bytes_read If non-NULL, this will contain the number of bytes read. + * + * @remark apr_file_read_full() will read up to the specified number of + * bytes, but never more. If there isn't enough data to fill that + * number of bytes, then the process/thread will block until it is + * available or EOF is reached. If a char was put back into the + * stream via ungetc, it will be the first character returned. + * + * @remark It is possible for both bytes to be read and an error to be + * returned. And if *bytes_read is less than nbytes, an accompanying + * error is _always_ returned. + * + * @remark #APR_EINTR is never returned. + */ +APR_DECLARE(apr_status_t) apr_file_read_full(apr_file_t *thefile, void *buf, + apr_size_t nbytes, + apr_size_t *bytes_read); + +/** + * Write data to the specified file, ensuring that all of the data is + * written before returning. + * @param thefile The file descriptor to write to. + * @param buf The buffer which contains the data. + * @param nbytes The number of bytes to write. + * @param bytes_written If non-NULL, set to the number of bytes written. + * + * @remark apr_file_write_full() will write up to the specified number of + * bytes, but never more. If the OS cannot write that many bytes, the + * process/thread will block until they can be written. Exceptional + * error such as "out of space" or "pipe closed" will terminate with + * an error. + * + * @remark It is possible for both bytes to be written and an error to + * be returned. And if *bytes_written is less than nbytes, an + * accompanying error is _always_ returned. + * + * @remark #APR_EINTR is never returned. + */ +APR_DECLARE(apr_status_t) apr_file_write_full(apr_file_t *thefile, + const void *buf, + apr_size_t nbytes, + apr_size_t *bytes_written); + + +/** + * Write data from iovec array to the specified file, ensuring that all of the + * data is written before returning. + * @param thefile The file descriptor to write to. + * @param vec The array from which to get the data to write to the file. + * @param nvec The number of elements in the struct iovec array. This must + * be smaller than #APR_MAX_IOVEC_SIZE. If it isn't, the function + * will fail with #APR_EINVAL. + * @param nbytes The number of bytes written. + * + * @remark apr_file_writev_full() is available even if the underlying + * operating system doesn't provide writev(). + */ +APR_DECLARE(apr_status_t) apr_file_writev_full(apr_file_t *thefile, + const struct iovec *vec, + apr_size_t nvec, + apr_size_t *nbytes); +/** + * Write a character into the specified file. + * @param ch The character to write. + * @param thefile The file descriptor to write to + */ +APR_DECLARE(apr_status_t) apr_file_putc(char ch, apr_file_t *thefile); + +/** + * Read a character from the specified file. + * @param ch The character to read into + * @param thefile The file descriptor to read from + */ +APR_DECLARE(apr_status_t) apr_file_getc(char *ch, apr_file_t *thefile); + +/** + * Put a character back onto a specified stream. + * @param ch The character to write. + * @param thefile The file descriptor to write to + */ +APR_DECLARE(apr_status_t) apr_file_ungetc(char ch, apr_file_t *thefile); + +/** + * Read a line from the specified file + * @param str The buffer to store the string in. + * @param len The length of the string + * @param thefile The file descriptor to read from + * @remark The buffer will be NUL-terminated if any characters are stored. + * The newline at the end of the line will not be stripped. + */ +APR_DECLARE(apr_status_t) apr_file_gets(char *str, int len, + apr_file_t *thefile); + +/** + * Write the string into the specified file. + * @param str The string to write. + * @param thefile The file descriptor to write to + */ +APR_DECLARE(apr_status_t) apr_file_puts(const char *str, apr_file_t *thefile); + +/** + * Flush the file's buffer. + * @param thefile The file descriptor to flush + */ +APR_DECLARE(apr_status_t) apr_file_flush(apr_file_t *thefile); + +/** + * Transfer all file modified data and metadata to disk. + * @param thefile The file descriptor to sync + */ +APR_DECLARE(apr_status_t) apr_file_sync(apr_file_t *thefile); + +/** + * Transfer all file modified data to disk. + * @param thefile The file descriptor to sync + */ +APR_DECLARE(apr_status_t) apr_file_datasync(apr_file_t *thefile); + +/** + * Duplicate the specified file descriptor. + * @param new_file The structure to duplicate into. + * @param old_file The file to duplicate. + * @param p The pool to use for the new file. + * @remark *new_file must point to a valid apr_file_t, or point to NULL. + */ +APR_DECLARE(apr_status_t) apr_file_dup(apr_file_t **new_file, + apr_file_t *old_file, + apr_pool_t *p); + +/** + * Duplicate the specified file descriptor and close the original + * @param new_file The old file that is to be closed and reused + * @param old_file The file to duplicate + * @param p The pool to use for the new file + * + * @remark new_file MUST point at a valid apr_file_t. It cannot be NULL. + */ +APR_DECLARE(apr_status_t) apr_file_dup2(apr_file_t *new_file, + apr_file_t *old_file, + apr_pool_t *p); + +/** + * Move the specified file descriptor to a new pool + * @param new_file Pointer in which to return the new apr_file_t + * @param old_file The file to move + * @param p The pool to which the descriptor is to be moved + * @remark Unlike apr_file_dup2(), this function doesn't do an + * OS dup() operation on the underlying descriptor; it just + * moves the descriptor's apr_file_t wrapper to a new pool. + * @remark The new pool need not be an ancestor of old_file's pool. + * @remark After calling this function, old_file may not be used + */ +APR_DECLARE(apr_status_t) apr_file_setaside(apr_file_t **new_file, + apr_file_t *old_file, + apr_pool_t *p); + +/** + * Give the specified apr file handle a new buffer + * @param thefile The file handle that is to be modified + * @param buffer The buffer + * @param bufsize The size of the buffer + * @remark It is possible to add a buffer to previously unbuffered + * file handles, the #APR_FOPEN_BUFFERED flag will be added to + * the file handle's flags. Likewise, with buffer=NULL and + * bufsize=0 arguments it is possible to make a previously + * buffered file handle unbuffered. + */ +APR_DECLARE(apr_status_t) apr_file_buffer_set(apr_file_t *thefile, + char * buffer, + apr_size_t bufsize); + +/** + * Get the size of any buffer for the specified apr file handle + * @param thefile The file handle + */ +APR_DECLARE(apr_size_t) apr_file_buffer_size_get(apr_file_t *thefile); + +/** + * Move the read/write file offset to a specified byte within a file. + * @param thefile The file descriptor + * @param where How to move the pointer, one of: + * @li #APR_SET -- set the offset to offset + * @li #APR_CUR -- add the offset to the current position + * @li #APR_END -- add the offset to the current file size + * @param offset The offset to move the pointer to. + * @remark The third argument is modified to be the offset the pointer + was actually moved to. + */ +APR_DECLARE(apr_status_t) apr_file_seek(apr_file_t *thefile, + apr_seek_where_t where, + apr_off_t *offset); + +/** + * Create an anonymous pipe. + * @param in The newly created pipe's file for reading. + * @param out The newly created pipe's file for writing. + * @param pool The pool to operate on. + * @remark By default, the returned file descriptors will be inherited + * by child processes created using apr_proc_create(). This can be + * changed using apr_file_inherit_unset(). + * @bug Some platforms cannot toggle between blocking and nonblocking, + * and when passing a pipe as a standard handle to an application which + * does not expect it, a non-blocking stream will fluxor the client app. + * @deprecated @see apr_file_pipe_create_pools() + */ +APR_DECLARE(apr_status_t) apr_file_pipe_create(apr_file_t **in, + apr_file_t **out, + apr_pool_t *pool); + +/** + * Create an anonymous pipe which portably supports async timeout options. + * @param in The newly created pipe's file for reading. + * @param out The newly created pipe's file for writing. + * @param blocking one of these values defined in apr_thread_proc.h; + * @li #APR_FULL_BLOCK + * @li #APR_READ_BLOCK + * @li #APR_WRITE_BLOCK + * @li #APR_FULL_NONBLOCK + * @param pool The pool to operate on. + * @remark By default, the returned file descriptors will be inherited + * by child processes created using apr_proc_create(). This can be + * changed using apr_file_inherit_unset(). + * @remark Some platforms cannot toggle between blocking and nonblocking, + * and when passing a pipe as a standard handle to an application which + * does not expect it, a non-blocking stream will fluxor the client app. + * Use this function rather than apr_file_pipe_create() to create pipes + * where one or both ends require non-blocking semantics. + * @deprecated @see apr_file_pipe_create_pools() + */ +APR_DECLARE(apr_status_t) apr_file_pipe_create_ex(apr_file_t **in, + apr_file_t **out, + apr_int32_t blocking, + apr_pool_t *pool); + +/** + * Create an anonymous pipe which portably supports async timeout options, + * placing each side of the pipe in a different pool. + * @param in The newly created pipe's file for reading. + * @param out The newly created pipe's file for writing. + * @param blocking one of these values defined in apr_thread_proc.h; + * @li #APR_FULL_BLOCK + * @li #APR_READ_BLOCK + * @li #APR_WRITE_BLOCK + * @li #APR_FULL_NONBLOCK + * @param pool_in The pool for the reading pipe. + * @param pool_out The pool for the writing pipe. + * @remark By default, the returned file descriptors will be inherited + * by child processes created using apr_proc_create(). This can be + * changed using apr_file_inherit_unset(). + * @remark Some platforms cannot toggle between blocking and nonblocking, + * and when passing a pipe as a standard handle to an application which + * does not expect it, a non-blocking stream will fluxor the client app. + * Use this function rather than apr_file_pipe_create() to create pipes + * where one or both ends require non-blocking semantics. + */ +APR_DECLARE(apr_status_t) apr_file_pipe_create_pools(apr_file_t **in, + apr_file_t **out, + apr_int32_t blocking, + apr_pool_t *pool_in, + apr_pool_t *pool_out); + +/** + * Create a named pipe. + * @param filename The filename of the named pipe + * @param perm The permissions for the newly created pipe. + * @param pool The pool to operate on. + */ +APR_DECLARE(apr_status_t) apr_file_namedpipe_create(const char *filename, + apr_fileperms_t perm, + apr_pool_t *pool); + +/** + * Get the timeout value for a pipe or manipulate the blocking state. + * @param thepipe The pipe we are getting a timeout for. + * @param timeout The current timeout value in microseconds. + */ +APR_DECLARE(apr_status_t) apr_file_pipe_timeout_get(apr_file_t *thepipe, + apr_interval_time_t *timeout); + +/** + * Set the timeout value for a pipe or manipulate the blocking state. + * @param thepipe The pipe we are setting a timeout on. + * @param timeout The timeout value in microseconds. Values < 0 mean wait + * forever, 0 means do not wait at all. + */ +APR_DECLARE(apr_status_t) apr_file_pipe_timeout_set(apr_file_t *thepipe, + apr_interval_time_t timeout); + +/** file (un)locking functions. */ + +/** + * Establish a lock on the specified, open file. The lock may be advisory + * or mandatory, at the discretion of the platform. The lock applies to + * the file as a whole, rather than a specific range. Locks are established + * on a per-thread/process basis; a second lock by the same thread will not + * block. + * @param thefile The file to lock. + * @param type The type of lock to establish on the file. + */ +APR_DECLARE(apr_status_t) apr_file_lock(apr_file_t *thefile, int type); + +/** + * Remove any outstanding locks on the file. + * @param thefile The file to unlock. + */ +APR_DECLARE(apr_status_t) apr_file_unlock(apr_file_t *thefile); + +/**accessor and general file_io functions. */ + +/** + * return the file name of the current file. + * @param new_path The path of the file. + * @param thefile The currently open file. + */ +APR_DECLARE(apr_status_t) apr_file_name_get(const char **new_path, + apr_file_t *thefile); + +/** + * Return the data associated with the current file. + * @param data The user data associated with the file. + * @param key The key to use for retrieving data associated with this file. + * @param file The currently open file. + */ +APR_DECLARE(apr_status_t) apr_file_data_get(void **data, const char *key, + apr_file_t *file); + +/** + * Set the data associated with the current file. + * @param file The currently open file. + * @param data The user data to associate with the file. + * @param key The key to use for associating data with the file. + * @param cleanup The cleanup routine to use when the file is destroyed. + */ +APR_DECLARE(apr_status_t) apr_file_data_set(apr_file_t *file, void *data, + const char *key, + apr_status_t (*cleanup)(void *)); + +/** + * Write a string to a file using a printf format. + * @param fptr The file to write to. + * @param format The format string + * @param ... The values to substitute in the format string + * @return The number of bytes written + */ +APR_DECLARE_NONSTD(int) apr_file_printf(apr_file_t *fptr, + const char *format, ...) + __attribute__((format(printf,2,3))); + +/** + * set the specified file's permission bits. + * @param fname The file (name) to apply the permissions to. + * @param perms The permission bits to apply to the file. + * + * @warning Some platforms may not be able to apply all of the + * available permission bits; #APR_INCOMPLETE will be returned if some + * permissions are specified which could not be set. + * + * @warning Platforms which do not implement this feature will return + * #APR_ENOTIMPL. + */ +APR_DECLARE(apr_status_t) apr_file_perms_set(const char *fname, + apr_fileperms_t perms); + +/** + * Set attributes of the specified file. + * @param fname The full path to the file (using / on all systems) + * @param attributes Or'd combination of + * @li #APR_FILE_ATTR_READONLY - make the file readonly + * @li #APR_FILE_ATTR_EXECUTABLE - make the file executable + * @li #APR_FILE_ATTR_HIDDEN - make the file hidden + * @param attr_mask Mask of valid bits in attributes. + * @param pool the pool to use. + * @remark This function should be used in preference to explicit manipulation + * of the file permissions, because the operations to provide these + * attributes are platform specific and may involve more than simply + * setting permission bits. + * @warning Platforms which do not implement this feature will return + * #APR_ENOTIMPL. + */ +APR_DECLARE(apr_status_t) apr_file_attrs_set(const char *fname, + apr_fileattrs_t attributes, + apr_fileattrs_t attr_mask, + apr_pool_t *pool); + +/** + * Set the mtime of the specified file. + * @param fname The full path to the file (using / on all systems) + * @param mtime The mtime to apply to the file. + * @param pool The pool to use. + * @warning Platforms which do not implement this feature will return + * #APR_ENOTIMPL. + */ +APR_DECLARE(apr_status_t) apr_file_mtime_set(const char *fname, + apr_time_t mtime, + apr_pool_t *pool); + +/** + * Create a new directory on the file system. + * @param path the path for the directory to be created. (use / on all systems) + * @param perm Permissions for the new directory. + * @param pool the pool to use. + */ +APR_DECLARE(apr_status_t) apr_dir_make(const char *path, apr_fileperms_t perm, + apr_pool_t *pool); + +/** Creates a new directory on the file system, but behaves like + * 'mkdir -p'. Creates intermediate directories as required. No error + * will be reported if PATH already exists. + * @param path the path for the directory to be created. (use / on all systems) + * @param perm Permissions for the new directory. + * @param pool the pool to use. + */ +APR_DECLARE(apr_status_t) apr_dir_make_recursive(const char *path, + apr_fileperms_t perm, + apr_pool_t *pool); + +/** + * Remove directory from the file system. + * @param path the path for the directory to be removed. (use / on all systems) + * @param pool the pool to use. + * @remark Removing a directory which is in-use (e.g., the current working + * directory, or during apr_dir_read, or with an open file) is not portable. + */ +APR_DECLARE(apr_status_t) apr_dir_remove(const char *path, apr_pool_t *pool); + +/** + * get the specified file's stats. + * @param finfo Where to store the information about the file. + * @param wanted The desired apr_finfo_t fields, as a bit flag of APR_FINFO_* values + * @param thefile The file to get information about. + */ +APR_DECLARE(apr_status_t) apr_file_info_get(apr_finfo_t *finfo, + apr_int32_t wanted, + apr_file_t *thefile); + + +/** + * Truncate the file's length to the specified offset + * @param fp The file to truncate + * @param offset The offset to truncate to. + * @remark The read/write file offset is repositioned to offset. + */ +APR_DECLARE(apr_status_t) apr_file_trunc(apr_file_t *fp, apr_off_t offset); + +/** + * Retrieve the flags that were passed into apr_file_open() + * when the file was opened. + * @return apr_int32_t the flags + */ +APR_DECLARE(apr_int32_t) apr_file_flags_get(apr_file_t *f); + +/** + * Get the pool used by the file. + */ +APR_POOL_DECLARE_ACCESSOR(file); + +/** + * Set a file to be inherited by child processes. + * + */ +APR_DECLARE_INHERIT_SET(file); + +/** + * Unset a file from being inherited by child processes. + */ +APR_DECLARE_INHERIT_UNSET(file); + +/** + * Open a temporary file + * @param fp The apr file to use as a temporary file. + * @param templ The template to use when creating a temp file. + * @param flags The flags to open the file with. If this is zero, + * the file is opened with + * #APR_FOPEN_CREATE | #APR_FOPEN_READ | #APR_FOPEN_WRITE | + * #APR_FOPEN_EXCL | #APR_FOPEN_DELONCLOSE + * @param p The pool to allocate the file out of. + * @remark + * This function generates a unique temporary file name from template. + * The last six characters of template must be XXXXXX and these are replaced + * with a string that makes the filename unique. Since it will be modified, + * template must not be a string constant, but should be declared as a character + * array. + * + */ +APR_DECLARE(apr_status_t) apr_file_mktemp(apr_file_t **fp, char *templ, + apr_int32_t flags, apr_pool_t *p); + + +/** + * Find an existing directory suitable as a temporary storage location. + * @param temp_dir The temp directory. + * @param p The pool to use for any necessary allocations. + * @remark + * This function uses an algorithm to search for a directory that an + * an application can use for temporary storage. + * + */ +APR_DECLARE(apr_status_t) apr_temp_dir_get(const char **temp_dir, + apr_pool_t *p); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_FILE_IO_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_fnmatch.h b/c/dependencies/windows/apr/x86/include/apr_fnmatch.h new file mode 100644 index 00000000..e8f6b03c --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_fnmatch.h @@ -0,0 +1,153 @@ +/* + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)fnmatch.h 8.1 (Berkeley) 6/2/93 + */ + +/* This file has been modified by the Apache Software Foundation. */ +#ifndef _APR_FNMATCH_H_ +#define _APR_FNMATCH_H_ + +/** + * @file apr_fnmatch.h + * @brief APR FNMatch Functions + */ + +#include "apr_errno.h" +#include "apr_tables.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_fnmatch Filename Matching Functions + * @ingroup APR + * @{ + */ + +#define APR_FNM_NOMATCH 1 /**< Match failed. */ + +#define APR_FNM_NOESCAPE 0x01 /**< Disable backslash escaping. */ +#define APR_FNM_PATHNAME 0x02 /**< Slash must be matched by slash. */ +#define APR_FNM_PERIOD 0x04 /**< Period must be matched by period. */ +#define APR_FNM_CASE_BLIND 0x08 /**< Compare characters case-insensitively. */ + +/** + * Try to match the string to the given pattern, return APR_SUCCESS if + * match, else return APR_FNM_NOMATCH. Note that there is no such thing as + * an illegal pattern. + * + * With all flags unset, a pattern is interpreted as such: + * + * PATTERN: Backslash followed by any character, including another + * backslash.
+ * MATCHES: That character exactly. + * + *

+ * PATTERN: ?
+ * MATCHES: Any single character. + *

+ * + *

+ * PATTERN: *
+ * MATCHES: Any sequence of zero or more characters. (Note that multiple + * *s in a row are equivalent to one.) + * + * PATTERN: Any character other than \?*[ or a \ at the end of the pattern
+ * MATCHES: That character exactly. (Case sensitive.) + * + * PATTERN: [ followed by a class description followed by ]
+ * MATCHES: A single character described by the class description. + * (Never matches, if the class description reaches until the + * end of the string without a ].) If the first character of + * the class description is ^ or !, the sense of the description + * is reversed. The rest of the class description is a list of + * single characters or pairs of characters separated by -. Any + * of those characters can have a backslash in front of them, + * which is ignored; this lets you use the characters ] and - + * in the character class, as well as ^ and ! at the + * beginning. The pattern matches a single character if it + * is one of the listed characters or falls into one of the + * listed ranges (inclusive, case sensitive). Ranges with + * the first character larger than the second are legal but + * never match. Edge cases: [] never matches, and [^] and [!] + * always match without consuming a character. + * + * Note that these patterns attempt to match the entire string, not + * just find a substring matching the pattern. + * + * @param pattern The pattern to match to + * @param strings The string we are trying to match + * @param flags flags to use in the match. Bitwise OR of: + *

+ *              APR_FNM_NOESCAPE       Disable backslash escaping
+ *              APR_FNM_PATHNAME       Slash must be matched by slash
+ *              APR_FNM_PERIOD         Period must be matched by period
+ *              APR_FNM_CASE_BLIND     Compare characters case-insensitively.
+ * 
+ */ + +APR_DECLARE(apr_status_t) apr_fnmatch(const char *pattern, + const char *strings, int flags); + +/** + * Determine if the given pattern is a regular expression. + * @param pattern The pattern to search for glob characters. + * @return non-zero if pattern has any glob characters in it + */ +APR_DECLARE(int) apr_fnmatch_test(const char *pattern); + +/** + * Find all files that match a specified pattern in a directory. + * @param dir_pattern The pattern to use for finding files, appended + * to the search directory. The pattern is anything following the + * final forward or backward slash in the parameter. If no slash + * is found, the current directory is searched. + * @param result Array to use when storing the results + * @param p The pool to use. + * @return APR_SUCCESS if no processing errors occurred, APR error + * code otherwise + * @remark The returned array may be empty even if APR_SUCCESS was + * returned. + */ +APR_DECLARE(apr_status_t) apr_match_glob(const char *dir_pattern, + apr_array_header_t **result, + apr_pool_t *p); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !_APR_FNMATCH_H_ */ diff --git a/c/dependencies/windows/apr/x86/include/apr_general.h b/c/dependencies/windows/apr/x86/include/apr_general.h new file mode 100644 index 00000000..fa073c85 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_general.h @@ -0,0 +1,244 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_GENERAL_H +#define APR_GENERAL_H + +/** + * @file apr_general.h + * This is collection of oddballs that didn't fit anywhere else, + * and might move to more appropriate headers with the release + * of APR 1.0. + * @brief APR Miscellaneous library routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" + +#if APR_HAVE_SIGNAL_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_general Miscellaneous library routines + * @ingroup APR + * This is collection of oddballs that didn't fit anywhere else, + * and might move to more appropriate headers with the release + * of APR 1.0. + * @{ + */ + +/** FALSE */ +#ifndef FALSE +#define FALSE 0 +#endif +/** TRUE */ +#ifndef TRUE +#define TRUE (!FALSE) +#endif + +/** a space */ +#define APR_ASCII_BLANK '\040' +/** a carrige return */ +#define APR_ASCII_CR '\015' +/** a line feed */ +#define APR_ASCII_LF '\012' +/** a tab */ +#define APR_ASCII_TAB '\011' + +/** signal numbers typedef */ +typedef int apr_signum_t; + +/** + * Finding offsets of elements within structures. + * Taken from the X code... they've sweated portability of this stuff + * so we don't have to. Sigh... + * @param p_type pointer type name + * @param field data field within the structure pointed to + * @return offset + */ + +#if defined(CRAY) || (defined(__arm) && !(defined(LINUX) || defined(__FreeBSD__))) +#ifdef __STDC__ +#define APR_OFFSET(p_type,field) _Offsetof(p_type,field) +#else +#ifdef CRAY2 +#define APR_OFFSET(p_type,field) \ + (sizeof(int)*((unsigned int)&(((p_type)NULL)->field))) + +#else /* !CRAY2 */ + +#define APR_OFFSET(p_type,field) ((unsigned int)&(((p_type)NULL)->field)) + +#endif /* !CRAY2 */ +#endif /* __STDC__ */ +#else /* ! (CRAY || __arm) */ + +#define APR_OFFSET(p_type,field) \ + ((long) (((char *) (&(((p_type)NULL)->field))) - ((char *) NULL))) + +#endif /* !CRAY */ + +/** + * Finding offsets of elements within structures. + * @param s_type structure type name + * @param field data field within the structure + * @return offset + */ +#if defined(offsetof) && !defined(__cplusplus) +#define APR_OFFSETOF(s_type,field) offsetof(s_type,field) +#else +#define APR_OFFSETOF(s_type,field) APR_OFFSET(s_type*,field) +#endif + +#ifndef DOXYGEN + +/* A couple of prototypes for functions in case some platform doesn't + * have it + */ +#if (!APR_HAVE_STRCASECMP) && (APR_HAVE_STRICMP) +#define strcasecmp(s1, s2) stricmp(s1, s2) +#elif (!APR_HAVE_STRCASECMP) +int strcasecmp(const char *a, const char *b); +#endif + +#if (!APR_HAVE_STRNCASECMP) && (APR_HAVE_STRNICMP) +#define strncasecmp(s1, s2, n) strnicmp(s1, s2, n) +#elif (!APR_HAVE_STRNCASECMP) +int strncasecmp(const char *a, const char *b, size_t n); +#endif + +#endif + +/** + * Alignment macros + */ + +/* APR_ALIGN() is only to be used to align on a power of 2 boundary */ +#define APR_ALIGN(size, boundary) \ + (((size) + ((boundary) - 1)) & ~((boundary) - 1)) + +/** Default alignment */ +#define APR_ALIGN_DEFAULT(size) APR_ALIGN(size, 8) + + +/** + * String and memory functions + */ + +/* APR_STRINGIFY is defined here, and also in apr_release.h, so wrap it */ +#ifndef APR_STRINGIFY +/** Properly quote a value as a string in the C preprocessor */ +#define APR_STRINGIFY(n) APR_STRINGIFY_HELPER(n) +/** Helper macro for APR_STRINGIFY */ +#define APR_STRINGIFY_HELPER(n) #n +#endif + +#if (!APR_HAVE_MEMMOVE) +#define memmove(a,b,c) bcopy(b,a,c) +#endif + +#if (!APR_HAVE_MEMCHR) +void *memchr(const void *s, int c, size_t n); +#endif + +/** @} */ + +/** + * @defgroup apr_library Library initialization and termination + * @{ + */ + +/** + * Setup any APR internal data structures. This MUST be the first function + * called for any APR library. It is safe to call apr_initialize several + * times as long as apr_terminate() is called the same number of times. + * @remark See apr_app_initialize() if this is an application, rather than + * a library consumer of apr. + */ +APR_DECLARE(apr_status_t) apr_initialize(void); + +/** + * Set up an application with normalized argc, argv (and optionally env) in + * order to deal with platform-specific oddities, such as Win32 services, + * code pages and signals. This must be the first function called for any + * APR program. + * @param argc Pointer to the argc that may be corrected + * @param argv Pointer to the argv that may be corrected + * @param env Pointer to the env that may be corrected, may be NULL + * @remark See apr_initialize() if this is a library consumer of apr. + * Otherwise, this call is identical to apr_initialize(), and must be closed + * with a call to apr_terminate() at the end of program execution. + */ +APR_DECLARE(apr_status_t) apr_app_initialize(int *argc, + char const * const * *argv, + char const * const * *env); + +/** + * Tear down any APR internal data structures which aren't torn down + * automatically. apr_terminate must be called once for every call to + * apr_initialize() or apr_app_initialize(). + * @remark An APR program must call this function at termination once it + * has stopped using APR services. The APR developers suggest using + * @c atexit(apr_terminate) to ensure this is called. When using APR + * from a language other than C that has problems with the calling + * convention, use apr_terminate2() instead. + * @see apr_terminate2 + */ +APR_DECLARE_NONSTD(void) apr_terminate(void); + +/** + * Tear down any APR internal data structures which aren't torn down + * automatically, same as apr_terminate() + * @remark An APR program must call either the apr_terminate() or apr_terminate2 + * function once it it has finished using APR services. The APR + * developers suggest using @c atexit(apr_terminate) to ensure this is done. + * apr_terminate2 exists to allow non-c language apps to tear down apr, + * while apr_terminate() is recommended from c language applications. + */ +APR_DECLARE(void) apr_terminate2(void); + +/** @} */ + +/** + * @defgroup apr_random Random Functions + * @{ + */ + +#if APR_HAS_RANDOM || defined(DOXYGEN) + +/* TODO: I'm not sure this is the best place to put this prototype...*/ +/** + * Generate random bytes. + * @param buf Buffer to fill with random bytes + * @param length Length of buffer in bytes + */ +APR_DECLARE(apr_status_t) apr_generate_random_bytes(unsigned char * buf, + apr_size_t length); + +#endif +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_GENERAL_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_getopt.h b/c/dependencies/windows/apr/x86/include/apr_getopt.h new file mode 100644 index 00000000..75ad5663 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_getopt.h @@ -0,0 +1,160 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_GETOPT_H +#define APR_GETOPT_H + +/** + * @file apr_getopt.h + * @brief APR Command Arguments (getopt) + */ + +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_getopt Command Argument Parsing + * @ingroup APR + * @{ + */ + +/** + * An @c apr_getopt_t error callback function. + * + * @a arg is this @c apr_getopt_t's @c errarg member. + */ +typedef void (apr_getopt_err_fn_t)(void *arg, const char *err, ...); + +/** @see apr_getopt_t */ +typedef struct apr_getopt_t apr_getopt_t; + +/** + * Structure to store command line argument information. + */ +struct apr_getopt_t { + /** context for processing */ + apr_pool_t *cont; + /** function to print error message (NULL == no messages) */ + apr_getopt_err_fn_t *errfn; + /** user defined first arg to pass to error message */ + void *errarg; + /** index into parent argv vector */ + int ind; + /** character checked for validity */ + int opt; + /** reset getopt */ + int reset; + /** count of arguments */ + int argc; + /** array of pointers to arguments */ + const char **argv; + /** argument associated with option */ + char const* place; + /** set to nonzero to support interleaving options with regular args */ + int interleave; + /** start of non-option arguments skipped for interleaving */ + int skip_start; + /** end of non-option arguments skipped for interleaving */ + int skip_end; +}; + +/** @see apr_getopt_option_t */ +typedef struct apr_getopt_option_t apr_getopt_option_t; + +/** + * Structure used to describe options that getopt should search for. + */ +struct apr_getopt_option_t { + /** long option name, or NULL if option has no long name */ + const char *name; + /** option letter, or a value greater than 255 if option has no letter */ + int optch; + /** nonzero if option takes an argument */ + int has_arg; + /** a description of the option */ + const char *description; +}; + +/** + * Initialize the arguments for parsing by apr_getopt(). + * @param os The options structure created for apr_getopt() + * @param cont The pool to operate on + * @param argc The number of arguments to parse + * @param argv The array of arguments to parse + * @remark Arguments 3 and 4 are most commonly argc and argv from main(argc, argv) + * The (*os)->errfn is initialized to fprintf(stderr... but may be overridden. + */ +APR_DECLARE(apr_status_t) apr_getopt_init(apr_getopt_t **os, apr_pool_t *cont, + int argc, const char * const *argv); + +/** + * Parse the options initialized by apr_getopt_init(). + * @param os The apr_opt_t structure returned by apr_getopt_init() + * @param opts A string of characters that are acceptable options to the + * program. Characters followed by ":" are required to have an + * option associated + * @param option_ch The next option character parsed + * @param option_arg The argument following the option character: + * @return There are four potential status values on exit. They are: + *
+ *             APR_EOF      --  No more options to parse
+ *             APR_BADCH    --  Found a bad option character
+ *             APR_BADARG   --  No argument followed the option flag
+ *             APR_SUCCESS  --  The next option was found.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_getopt(apr_getopt_t *os, const char *opts, + char *option_ch, const char **option_arg); + +/** + * Parse the options initialized by apr_getopt_init(), accepting long + * options beginning with "--" in addition to single-character + * options beginning with "-". + * @param os The apr_getopt_t structure created by apr_getopt_init() + * @param opts A pointer to a list of apr_getopt_option_t structures, which + * can be initialized with { "name", optch, has_args }. has_args + * is nonzero if the option requires an argument. A structure + * with an optch value of 0 terminates the list. + * @param option_ch Receives the value of "optch" from the apr_getopt_option_t + * structure corresponding to the next option matched. + * @param option_arg Receives the argument following the option, if any. + * @return There are four potential status values on exit. They are: + *
+ *             APR_EOF      --  No more options to parse
+ *             APR_BADCH    --  Found a bad option character
+ *             APR_BADARG   --  No argument followed the option flag
+ *             APR_SUCCESS  --  The next option was found.
+ * 
+ * When APR_SUCCESS is returned, os->ind gives the index of the first + * non-option argument. On error, a message will be printed to stdout unless + * os->err is set to 0. If os->interleave is set to nonzero, options can come + * after arguments, and os->argv will be permuted to leave non-option arguments + * at the end (the original argv is unaffected). + */ +APR_DECLARE(apr_status_t) apr_getopt_long(apr_getopt_t *os, + const apr_getopt_option_t *opts, + int *option_ch, + const char **option_arg); +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_GETOPT_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_global_mutex.h b/c/dependencies/windows/apr/x86/include/apr_global_mutex.h new file mode 100644 index 00000000..e3cba23f --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_global_mutex.h @@ -0,0 +1,195 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_GLOBAL_MUTEX_H +#define APR_GLOBAL_MUTEX_H + +/** + * @file apr_global_mutex.h + * @brief APR Global Locking Routines + */ + +#include "apr.h" +#include "apr_proc_mutex.h" /* only for apr_lockmech_e */ +#include "apr_pools.h" +#include "apr_errno.h" +#if APR_PROC_MUTEX_IS_GLOBAL +#include "apr_proc_mutex.h" +#endif +#include "apr_time.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_GlobalMutex Global Locking Routines + * @ingroup APR + * @{ + */ + +#if !APR_PROC_MUTEX_IS_GLOBAL || defined(DOXYGEN) + +/** Opaque global mutex structure. */ +typedef struct apr_global_mutex_t apr_global_mutex_t; + +/* Function definitions */ + +/** + * Create and initialize a mutex that can be used to synchronize both + * processes and threads. Note: There is considerable overhead in using + * this API if only cross-process or cross-thread mutual exclusion is + * required. See apr_proc_mutex.h and apr_thread_mutex.h for more + * specialized lock routines. + * @param mutex the memory address where the newly created mutex will be + * stored. + * @param fname A file name to use if the lock mechanism requires one. This + * argument should always be provided. The lock code itself will + * determine if it should be used. + * @param mech The mechanism to use for the interprocess lock, if any; one of + *
+ *            APR_LOCK_FCNTL
+ *            APR_LOCK_FLOCK
+ *            APR_LOCK_SYSVSEM
+ *            APR_LOCK_POSIXSEM
+ *            APR_LOCK_PROC_PTHREAD
+ *            APR_LOCK_DEFAULT     pick the default mechanism for the platform
+ *            APR_LOCK_DEFAULT_TIMED pick the default timed mechanism
+ * 
+ * @param pool the pool from which to allocate the mutex. + * @warning Check APR_HAS_foo_SERIALIZE defines to see if the platform supports + * APR_LOCK_foo. Only APR_LOCK_DEFAULT is portable. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_create(apr_global_mutex_t **mutex, + const char *fname, + apr_lockmech_e mech, + apr_pool_t *pool); + +/** + * Re-open a mutex in a child process. + * @param mutex The newly re-opened mutex structure. + * @param fname A file name to use if the mutex mechanism requires one. This + * argument should always be provided. The mutex code itself will + * determine if it should be used. This filename should be the + * same one that was passed to apr_global_mutex_create(). + * @param pool The pool to operate on. + * @remark This function must be called to maintain portability, even + * if the underlying lock mechanism does not require it. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_child_init( + apr_global_mutex_t **mutex, + const char *fname, + apr_pool_t *pool); + +/** + * Acquire the lock for the given mutex. If the mutex is already locked, + * the current thread will be put to sleep until the lock becomes available. + * @param mutex the mutex on which to acquire the lock. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_lock(apr_global_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex. If the mutex has already + * been acquired, the call returns immediately with APR_EBUSY. Note: it + * is important that the APR_STATUS_IS_EBUSY(s) macro be used to determine + * if the return value was APR_EBUSY, for portability reasons. + * @param mutex the mutex on which to attempt the lock acquiring. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_trylock(apr_global_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex until timeout expires. + * If the acquisition time outs, the call returns with APR_TIMEUP. + * @param mutex the mutex on which to attempt the lock acquiring. + * @param timeout the relative timeout (microseconds). + * @note A negative or nul timeout means immediate attempt, returning + * APR_TIMEUP without blocking if it the lock is already acquired. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_timedlock(apr_global_mutex_t *mutex, + apr_interval_time_t timeout); + +/** + * Release the lock for the given mutex. + * @param mutex the mutex from which to release the lock. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_unlock(apr_global_mutex_t *mutex); + +/** + * Destroy the mutex and free the memory associated with the lock. + * @param mutex the mutex to destroy. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_destroy(apr_global_mutex_t *mutex); + +/** + * Return the name of the lockfile for the mutex, or NULL + * if the mutex doesn't use a lock file + */ +APR_DECLARE(const char *) apr_global_mutex_lockfile(apr_global_mutex_t *mutex); + +/** + * Get the mechanism of the mutex, as it relates to the actual method + * used for the underlying apr_proc_mutex_t. + * @param mutex the mutex to get the mechanism from. + */ +APR_DECLARE(apr_lockmech_e) apr_global_mutex_mech(apr_global_mutex_t *mutex); + +/** + * Get the mechanism's name of the mutex, as it relates to the actual method + * used for the underlying apr_proc_mutex_t. + * @param mutex the mutex to get the mechanism's name from. + */ +APR_DECLARE(const char *) apr_global_mutex_name(apr_global_mutex_t *mutex); + +/** + * Set mutex permissions. + */ +APR_PERMS_SET_IMPLEMENT(global_mutex); + +/** + * Get the pool used by this global_mutex. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(global_mutex); + +#else /* APR_PROC_MUTEX_IS_GLOBAL */ + +/* Some platforms [e.g. Win32] have cross process locks that are truly + * global locks, since there isn't the concept of cross-process locks. + * Define these platforms in terms of an apr_proc_mutex_t. + */ + +#define apr_global_mutex_t apr_proc_mutex_t +#define apr_global_mutex_create apr_proc_mutex_create +#define apr_global_mutex_child_init apr_proc_mutex_child_init +#define apr_global_mutex_lock apr_proc_mutex_lock +#define apr_global_mutex_trylock apr_proc_mutex_trylock +#define apr_global_mutex_unlock apr_proc_mutex_unlock +#define apr_global_mutex_destroy apr_proc_mutex_destroy +#define apr_global_mutex_lockfile apr_proc_mutex_lockfile +#define apr_global_mutex_mech apr_proc_mutex_mech +#define apr_global_mutex_name apr_proc_mutex_name +#define apr_global_mutex_perms_set apr_proc_mutex_perms_set +#define apr_global_mutex_pool_get apr_proc_mutex_pool_get + +#endif + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ndef APR_GLOBAL_MUTEX_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_hash.h b/c/dependencies/windows/apr/x86/include/apr_hash.h new file mode 100644 index 00000000..2276f84c --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_hash.h @@ -0,0 +1,283 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_HASH_H +#define APR_HASH_H + +/** + * @file apr_hash.h + * @brief APR Hash Tables + */ + +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_hash Hash Tables + * @ingroup APR + * @{ + */ + +/** + * When passing a key to apr_hash_set or apr_hash_get, this value can be + * passed to indicate a string-valued key, and have apr_hash compute the + * length automatically. + * + * @remark apr_hash will use strlen(key) for the length. The NUL terminator + * is not included in the hash value (why throw a constant in?). + * Since the hash table merely references the provided key (rather + * than copying it), apr_hash_this() will return the NUL-term'd key. + */ +#define APR_HASH_KEY_STRING (-1) + +/** + * Abstract type for hash tables. + */ +typedef struct apr_hash_t apr_hash_t; + +/** + * Abstract type for scanning hash tables. + */ +typedef struct apr_hash_index_t apr_hash_index_t; + +/** + * Callback functions for calculating hash values. + * @param key The key. + * @param klen The length of the key, or APR_HASH_KEY_STRING to use the string + * length. If APR_HASH_KEY_STRING then returns the actual key length. + */ +typedef unsigned int (*apr_hashfunc_t)(const char *key, apr_ssize_t *klen); + +/** + * The default hash function. + */ +APR_DECLARE_NONSTD(unsigned int) apr_hashfunc_default(const char *key, + apr_ssize_t *klen); + +/** + * Create a hash table. + * @param pool The pool to allocate the hash table out of + * @return The hash table just created + */ +APR_DECLARE(apr_hash_t *) apr_hash_make(apr_pool_t *pool); + +/** + * Create a hash table with a custom hash function + * @param pool The pool to allocate the hash table out of + * @param hash_func A custom hash function. + * @return The hash table just created + */ +APR_DECLARE(apr_hash_t *) apr_hash_make_custom(apr_pool_t *pool, + apr_hashfunc_t hash_func); + +/** + * Make a copy of a hash table + * @param pool The pool from which to allocate the new hash table + * @param h The hash table to clone + * @return The hash table just created + * @remark Makes a shallow copy + */ +APR_DECLARE(apr_hash_t *) apr_hash_copy(apr_pool_t *pool, + const apr_hash_t *h); + +/** + * Associate a value with a key in a hash table. + * @param ht The hash table + * @param key Pointer to the key + * @param klen Length of the key. Can be APR_HASH_KEY_STRING to use the string length. + * @param val Value to associate with the key + * @remark If the value is NULL the hash entry is deleted. The key is stored as is, + * and so must have a lifetime at least as long as the hash table's pool. + */ +APR_DECLARE(void) apr_hash_set(apr_hash_t *ht, const void *key, + apr_ssize_t klen, const void *val); + +/** + * Look up the value associated with a key in a hash table. + * @param ht The hash table + * @param key Pointer to the key + * @param klen Length of the key. Can be APR_HASH_KEY_STRING to use the string length. + * @return Returns NULL if the key is not present. + */ +APR_DECLARE(void *) apr_hash_get(apr_hash_t *ht, const void *key, + apr_ssize_t klen); + +/** + * Start iterating over the entries in a hash table. + * @param p The pool to allocate the apr_hash_index_t iterator. If this + * pool is NULL, then an internal, non-thread-safe iterator is used. + * @param ht The hash table + * @return The iteration state + * @remark There is no restriction on adding or deleting hash entries during + * an iteration (although the results may be unpredictable unless all you do + * is delete the current entry) and multiple iterations can be in + * progress at the same time. + * + * @par Example: + * + * @code + * int sum_values(apr_pool_t *p, apr_hash_t *ht) + * { + * apr_hash_index_t *hi; + * void *val; + * int sum = 0; + * for (hi = apr_hash_first(p, ht); hi; hi = apr_hash_next(hi)) { + * apr_hash_this(hi, NULL, NULL, &val); + * sum += *(int *)val; + * } + * return sum; + * } + * @endcode + */ +APR_DECLARE(apr_hash_index_t *) apr_hash_first(apr_pool_t *p, apr_hash_t *ht); + +/** + * Continue iterating over the entries in a hash table. + * @param hi The iteration state + * @return a pointer to the updated iteration state. NULL if there are no more + * entries. + */ +APR_DECLARE(apr_hash_index_t *) apr_hash_next(apr_hash_index_t *hi); + +/** + * Get the current entry's details from the iteration state. + * @param hi The iteration state + * @param key Return pointer for the pointer to the key. + * @param klen Return pointer for the key length. + * @param val Return pointer for the associated value. + * @remark The return pointers should point to a variable that will be set to the + * corresponding data, or they may be NULL if the data isn't interesting. + */ +APR_DECLARE(void) apr_hash_this(apr_hash_index_t *hi, const void **key, + apr_ssize_t *klen, void **val); + +/** + * Get the current entry's key from the iteration state. + * @param hi The iteration state + * @return The pointer to the key + */ +APR_DECLARE(const void*) apr_hash_this_key(apr_hash_index_t *hi); + +/** + * Get the current entry's key length from the iteration state. + * @param hi The iteration state + * @return The key length + */ +APR_DECLARE(apr_ssize_t) apr_hash_this_key_len(apr_hash_index_t *hi); + +/** + * Get the current entry's value from the iteration state. + * @param hi The iteration state + * @return The pointer to the value + */ +APR_DECLARE(void*) apr_hash_this_val(apr_hash_index_t *hi); + +/** + * Get the number of key/value pairs in the hash table. + * @param ht The hash table + * @return The number of key/value pairs in the hash table. + */ +APR_DECLARE(unsigned int) apr_hash_count(apr_hash_t *ht); + +/** + * Clear any key/value pairs in the hash table. + * @param ht The hash table + */ +APR_DECLARE(void) apr_hash_clear(apr_hash_t *ht); + +/** + * Merge two hash tables into one new hash table. The values of the overlay + * hash override the values of the base if both have the same key. Both + * hash tables must use the same hash function. + * @param p The pool to use for the new hash table + * @param overlay The table to add to the initial table + * @param base The table that represents the initial values of the new table + * @return A new hash table containing all of the data from the two passed in + */ +APR_DECLARE(apr_hash_t *) apr_hash_overlay(apr_pool_t *p, + const apr_hash_t *overlay, + const apr_hash_t *base); + +/** + * Merge two hash tables into one new hash table. If the same key + * is present in both tables, call the supplied merge function to + * produce a merged value for the key in the new table. Both + * hash tables must use the same hash function. + * @param p The pool to use for the new hash table + * @param h1 The first of the tables to merge + * @param h2 The second of the tables to merge + * @param merger A callback function to merge values, or NULL to + * make values from h1 override values from h2 (same semantics as + * apr_hash_overlay()) + * @param data Client data to pass to the merger function + * @return A new hash table containing all of the data from the two passed in + */ +APR_DECLARE(apr_hash_t *) apr_hash_merge(apr_pool_t *p, + const apr_hash_t *h1, + const apr_hash_t *h2, + void * (*merger)(apr_pool_t *p, + const void *key, + apr_ssize_t klen, + const void *h1_val, + const void *h2_val, + const void *data), + const void *data); + +/** + * Declaration prototype for the iterator callback function of apr_hash_do(). + * + * @param rec The data passed as the first argument to apr_hash_[v]do() + * @param key The key from this iteration of the hash table + * @param klen The key length from this iteration of the hash table + * @param value The value from this iteration of the hash table + * @remark Iteration continues while this callback function returns non-zero. + * To export the callback function for apr_hash_do() it must be declared + * in the _NONSTD convention. + */ +typedef int (apr_hash_do_callback_fn_t)(void *rec, const void *key, + apr_ssize_t klen, + const void *value); + +/** + * Iterate over a hash table running the provided function once for every + * element in the hash table. The @param comp function will be invoked for + * every element in the hash table. + * + * @param comp The function to run + * @param rec The data to pass as the first argument to the function + * @param ht The hash table to iterate over + * @return FALSE if one of the comp() iterations returned zero; TRUE if all + * iterations returned non-zero + * @see apr_hash_do_callback_fn_t + */ +APR_DECLARE(int) apr_hash_do(apr_hash_do_callback_fn_t *comp, + void *rec, const apr_hash_t *ht); + +/** + * Get a pointer to the pool which the hash table was created in + */ +APR_POOL_DECLARE_ACCESSOR(hash); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_HASH_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_hooks.h b/c/dependencies/windows/apr/x86/include/apr_hooks.h new file mode 100644 index 00000000..eee16e3c --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_hooks.h @@ -0,0 +1,358 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_HOOKS_H +#define APR_HOOKS_H + +#include "apu.h" +/* For apr_array_header_t */ +#include "apr_tables.h" + +/** + * @file apr_hooks.h + * @brief Apache hook functions + */ + +#ifdef __cplusplus +extern "C" { +#endif +/** + * @defgroup APR_Util_Hook Hook Functions + * @ingroup APR_Util + * @{ + */ + +/** + * @defgroup apr_hook_probes Hook probe capability + * APR hooks provide a trace probe capability for capturing + * the flow of control and return values with hooks. + * + * In order to use this facility, the application must define + * the symbol APR_HOOK_PROBES_ENABLED and the four APR_HOOK_PROBE_ + * macros described below before including apr_hooks.h in files + * that use the APR_IMPLEMENT_EXTERNAL_HOOK_* macros. + * + * This probe facility is not provided for APR optional hooks. + * @{ + */ + +#ifdef APR_HOOK_PROBES_ENABLED +#define APR_HOOK_INT_DCL_UD void *ud = NULL +#else +/** internal implementation detail to avoid the ud declaration when + * hook probes are not used + */ +#define APR_HOOK_INT_DCL_UD +/** + * User-defined hook probe macro that is invoked when the hook + * is run, before calling any hook functions. + * @param ud A void * user data field that should be filled in by + * this macro, and will be provided to the other hook probe macros. + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param args The argument list to the hook functions, with enclosing + * parens. + */ +#define APR_HOOK_PROBE_ENTRY(ud,ns,name,args) +/** + * User-defined hook probe macro that is invoked after the hook + * has run. + * @param ud A void * user data field that was filled in by the user- + * provided APR_HOOK_PROBE_ENTRY(). + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param rv The return value of the hook, or 0 if the hook is void. + * @param args The argument list to the hook functions, with enclosing + * parens. + */ +#define APR_HOOK_PROBE_RETURN(ud,ns,name,rv,args) +/** + * User-defined hook probe macro that is invoked before calling a + * hook function. + * @param ud A void * user data field that was filled in by the user- + * provided APR_HOOK_PROBE_ENTRY(). + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param src The value of apr_hook_debug_current at the time the function + * was hooked (usually the source file implementing the hook function). + * @param args The argument list to the hook functions, with enclosing + * parens. + */ +#define APR_HOOK_PROBE_INVOKE(ud,ns,name,src,args) +/** + * User-defined hook probe macro that is invoked after calling a + * hook function. + * @param ud A void * user data field that was filled in by the user- + * provided APR_HOOK_PROBE_ENTRY(). + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param src The value of apr_hook_debug_current at the time the function + * was hooked (usually the source file implementing the hook function). + * @param rv The return value of the hook function, or 0 if the hook is void. + * @param args The argument list to the hook functions, with enclosing + * parens. + */ +#define APR_HOOK_PROBE_COMPLETE(ud,ns,name,src,rv,args) +#endif + +/** @} */ + +/** macro to return the prototype of the hook function */ +#define APR_IMPLEMENT_HOOK_GET_PROTO(ns,link,name) \ +link##_DECLARE(apr_array_header_t *) ns##_hook_get_##name(void) + +/** macro to declare the hook correctly */ +#define APR_DECLARE_EXTERNAL_HOOK(ns,link,ret,name,args) \ +typedef ret ns##_HOOK_##name##_t args; \ +link##_DECLARE(void) ns##_hook_##name(ns##_HOOK_##name##_t *pf, \ + const char * const *aszPre, \ + const char * const *aszSucc, int nOrder); \ +link##_DECLARE(ret) ns##_run_##name args; \ +APR_IMPLEMENT_HOOK_GET_PROTO(ns,link,name); \ +typedef struct ns##_LINK_##name##_t \ + { \ + ns##_HOOK_##name##_t *pFunc; \ + const char *szName; \ + const char * const *aszPredecessors; \ + const char * const *aszSuccessors; \ + int nOrder; \ + } ns##_LINK_##name##_t; + +/** macro to declare the hook structure */ +#define APR_HOOK_STRUCT(members) \ +static struct { members } _hooks; + +/** macro to link the hook structure */ +#define APR_HOOK_LINK(name) \ + apr_array_header_t *link_##name; + +/** macro to implement the hook */ +#define APR_IMPLEMENT_EXTERNAL_HOOK_BASE(ns,link,name) \ +link##_DECLARE(void) ns##_hook_##name(ns##_HOOK_##name##_t *pf,const char * const *aszPre, \ + const char * const *aszSucc,int nOrder) \ + { \ + ns##_LINK_##name##_t *pHook; \ + if(!_hooks.link_##name) \ + { \ + _hooks.link_##name=apr_array_make(apr_hook_global_pool,1,sizeof(ns##_LINK_##name##_t)); \ + apr_hook_sort_register(#name,&_hooks.link_##name); \ + } \ + pHook=apr_array_push(_hooks.link_##name); \ + pHook->pFunc=pf; \ + pHook->aszPredecessors=aszPre; \ + pHook->aszSuccessors=aszSucc; \ + pHook->nOrder=nOrder; \ + pHook->szName=apr_hook_debug_current; \ + if(apr_hook_debug_enabled) \ + apr_hook_debug_show(#name,aszPre,aszSucc); \ + } \ + APR_IMPLEMENT_HOOK_GET_PROTO(ns,link,name) \ + { \ + return _hooks.link_##name; \ + } + +/** + * Implement a hook that has no return code, and therefore runs all of the + * registered functions + * @param ns The namespace prefix of the hook functions + * @param link The linkage declaration prefix of the hook + * @param name The name of the hook + * @param args_decl The declaration of the arguments for the hook + * @param args_use The names for the arguments for the hook + * @note The link prefix FOO corresponds to FOO_DECLARE() macros, which + * provide export linkage from the module that IMPLEMENTs the hook, and + * import linkage from external modules that link to the hook's module. + */ +#define APR_IMPLEMENT_EXTERNAL_HOOK_VOID(ns,link,name,args_decl,args_use) \ +APR_IMPLEMENT_EXTERNAL_HOOK_BASE(ns,link,name) \ +link##_DECLARE(void) ns##_run_##name args_decl \ + { \ + ns##_LINK_##name##_t *pHook; \ + int n; \ + APR_HOOK_INT_DCL_UD; \ +\ + APR_HOOK_PROBE_ENTRY(ud, ns, name, args_use); \ +\ + if(_hooks.link_##name) \ + { \ + pHook=(ns##_LINK_##name##_t *)_hooks.link_##name->elts; \ + for(n=0 ; n < _hooks.link_##name->nelts ; ++n) \ + { \ + APR_HOOK_PROBE_INVOKE(ud, ns, name, (char *)pHook[n].szName, args_use); \ + pHook[n].pFunc args_use; \ + APR_HOOK_PROBE_COMPLETE(ud, ns, name, (char *)pHook[n].szName, 0, args_use); \ + } \ + } \ +\ + APR_HOOK_PROBE_RETURN(ud, ns, name, 0, args_use); \ +\ + } + +/* FIXME: note that this returns ok when nothing is run. I suspect it should + really return decline, but that breaks Apache currently - Ben +*/ +/** + * Implement a hook that runs until one of the functions returns something + * other than OK or DECLINE + * @param ns The namespace prefix of the hook functions + * @param link The linkage declaration prefix of the hook + * @param ret Type to return + * @param name The name of the hook + * @param args_decl The declaration of the arguments for the hook + * @param args_use The names for the arguments for the hook + * @param ok Success value + * @param decline Decline value + * @note The link prefix FOO corresponds to FOO_DECLARE() macros, which + * provide export linkage from the module that IMPLEMENTs the hook, and + * import linkage from external modules that link to the hook's module. + */ +#define APR_IMPLEMENT_EXTERNAL_HOOK_RUN_ALL(ns,link,ret,name,args_decl,args_use,ok,decline) \ +APR_IMPLEMENT_EXTERNAL_HOOK_BASE(ns,link,name) \ +link##_DECLARE(ret) ns##_run_##name args_decl \ + { \ + ns##_LINK_##name##_t *pHook; \ + int n; \ + ret rv = ok; \ + APR_HOOK_INT_DCL_UD; \ +\ + APR_HOOK_PROBE_ENTRY(ud, ns, name, args_use); \ +\ + if(_hooks.link_##name) \ + { \ + pHook=(ns##_LINK_##name##_t *)_hooks.link_##name->elts; \ + for(n=0 ; n < _hooks.link_##name->nelts ; ++n) \ + { \ + APR_HOOK_PROBE_INVOKE(ud, ns, name, (char *)pHook[n].szName, args_use); \ + rv=pHook[n].pFunc args_use; \ + APR_HOOK_PROBE_COMPLETE(ud, ns, name, (char *)pHook[n].szName, rv, args_use); \ + if(rv != ok && rv != decline) \ + break; \ + rv = ok; \ + } \ + } \ +\ + APR_HOOK_PROBE_RETURN(ud, ns, name, rv, args_use); \ +\ + return rv; \ + } + + +/** + * Implement a hook that runs until the first function returns something + * other than the value of decline + * @param ns The namespace prefix of the hook functions + * @param link The linkage declaration prefix of the hook + * @param name The name of the hook + * @param ret Type to return + * @param args_decl The declaration of the arguments for the hook + * @param args_use The names for the arguments for the hook + * @param decline Decline value + * @note The link prefix FOO corresponds to FOO_DECLARE() macros, which + * provide export linkage from the module that IMPLEMENTs the hook, and + * import linkage from external modules that link to the hook's module. + */ +#define APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(ns,link,ret,name,args_decl,args_use,decline) \ +APR_IMPLEMENT_EXTERNAL_HOOK_BASE(ns,link,name) \ +link##_DECLARE(ret) ns##_run_##name args_decl \ + { \ + ns##_LINK_##name##_t *pHook; \ + int n; \ + ret rv = decline; \ + APR_HOOK_INT_DCL_UD; \ +\ + APR_HOOK_PROBE_ENTRY(ud, ns, name, args_use); \ +\ + if(_hooks.link_##name) \ + { \ + pHook=(ns##_LINK_##name##_t *)_hooks.link_##name->elts; \ + for(n=0 ; n < _hooks.link_##name->nelts ; ++n) \ + { \ + APR_HOOK_PROBE_INVOKE(ud, ns, name, (char *)pHook[n].szName, args_use); \ + rv=pHook[n].pFunc args_use; \ + APR_HOOK_PROBE_COMPLETE(ud, ns, name, (char *)pHook[n].szName, rv, args_use); \ +\ + if(rv != decline) \ + break; \ + } \ + } \ +\ + APR_HOOK_PROBE_RETURN(ud, ns, name, rv, args_use); \ +\ + return rv; \ + } + + /* Hook orderings */ +/** run this hook first, before ANYTHING */ +#define APR_HOOK_REALLY_FIRST (-10) +/** run this hook first */ +#define APR_HOOK_FIRST 0 +/** run this hook somewhere */ +#define APR_HOOK_MIDDLE 10 +/** run this hook after every other hook which is defined*/ +#define APR_HOOK_LAST 20 +/** run this hook last, after EVERYTHING */ +#define APR_HOOK_REALLY_LAST 30 + +/** + * The global pool used to allocate any memory needed by the hooks. + */ +APU_DECLARE_DATA extern apr_pool_t *apr_hook_global_pool; + +/** + * A global variable to determine if debugging information about the + * hooks functions should be printed. + */ +APU_DECLARE_DATA extern int apr_hook_debug_enabled; + +/** + * The name of the module that is currently registering a function. + */ +APU_DECLARE_DATA extern const char *apr_hook_debug_current; + +/** + * Register a hook function to be sorted. + * @param szHookName The name of the Hook the function is registered for + * @param aHooks The array which stores all of the functions for this hook + */ +APU_DECLARE(void) apr_hook_sort_register(const char *szHookName, + apr_array_header_t **aHooks); +/** + * Sort all of the registered functions for a given hook. + */ +APU_DECLARE(void) apr_hook_sort_all(void); + +/** + * Print all of the information about the current hook. This is used for + * debugging purposes. + * @param szName The name of the hook + * @param aszPre All of the functions in the predecessor array + * @param aszSucc All of the functions in the successor array + */ +APU_DECLARE(void) apr_hook_debug_show(const char *szName, + const char * const *aszPre, + const char * const *aszSucc); + +/** + * Remove all currently registered functions. + */ +APU_DECLARE(void) apr_hook_deregister_all(void); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_HOOKS_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_iconv.h b/c/dependencies/windows/apr/x86/include/apr_iconv.h new file mode 100644 index 00000000..81a0d315 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_iconv.h @@ -0,0 +1,150 @@ +/*- + * Copyright (c) 1999,2000 + * Konstantin Chuguev. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Konstantin Chuguev + * and its contributors. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + */ + +#ifndef APR_ICONV_H +#define APR_ICONV_H + +/** + * @file apr_iconv.h + * @brief APR-iconv substitute iconv library implementation + */ + +#include "apr.h" +#include "apr_pools.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_iconv substitute iconv implementation + * @ingroup APR-iconv + * @{ + */ + +/** + * API_DECLARE_EXPORT is defined when building the libapriconv dynamic + * library, so that all public symbols are exported. + * + * API_DECLARE_STATIC is defined when including the apriconv public headers, + * to provide static linkage when the dynamic library may be unavailable. + * + * API_DECLARE_STATIC and API_DECLARE_EXPORT are left undefined when + * including the apr-iconv public headers, to import and link the symbols + * from the dynamic libapriconv library and assure appropriate indirection + * and calling conventions at compile time. + */ + +#if defined(DOXYGEN) || !defined(WIN32) +/** + * The public apr-iconv functions are declared with API_DECLARE(), so they + * use the most portable calling convention. Public apr-iconv functions + * with variable arguments must use API_DECLARE_NONSTD(). + * + * @deffunc API_DECLARE(rettype) apr_func(args); + */ +#define API_DECLARE(type) type +/** + * The private apr-iconv functions are declared with API_DECLARE_NONSTD(), + * so they use the most optimal C language calling conventions. + * + * @deffunc API_DECLARE(rettype) apr_func(args); + */ +#define API_DECLARE_NONSTD(type) type +/** + * All exported apr-iconv variables are declared with API_DECLARE_DATA + * This assures the appropriate indirection is invoked at compile time. + * + * @deffunc API_DECLARE_DATA type apr_variable; + * @tip extern API_DECLARE_DATA type apr_variable; syntax is required for + * declarations within headers to properly import the variable. + */ +#define API_DECLARE_DATA +#elif defined(API_DECLARE_STATIC) +#define API_DECLARE(type) type __stdcall +#define API_DECLARE_NONSTD(type) type __cdecl +#define API_DECLARE_DATA +#elif defined(API_DECLARE_EXPORT) +#define API_DECLARE(type) __declspec(dllexport) type __stdcall +#define API_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define API_DECLARE_DATA __declspec(dllexport) +#else +#define API_DECLARE(type) __declspec(dllimport) type __stdcall +#define API_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define API_DECLARE_DATA __declspec(dllimport) +#endif + +/* + * apr_iconv_t: charset conversion descriptor type + */ +typedef void *apr_iconv_t; + +/* __BEGIN_DECLS */ + +/** + * Create a conversion descriptor. + * @param to name of charset to convert to. + * @param from name of charset of the input bytes. + * @param pool pool to alloc memory. + * @param cd conversion descriptor created in pool. + */ +API_DECLARE(apr_status_t) apr_iconv_open(const char *to, const char *from, + apr_pool_t *pool, apr_iconv_t *cd); +/** + * Perform character set conversion. + * @param cd conversion descriptor created by apr_iconv_open(). + * @param inbuf input buffer. + * @param inbytesleft bytes to convert. + * @param outbuf output buffer. + * @param outbytesleft space (in bytes) available in outbuf. + * @param translated number of input bytes converted. + */ +API_DECLARE(apr_status_t) apr_iconv(apr_iconv_t cd, + const char **inbuf, apr_size_t *inbytesleft, + char **outbuf, apr_size_t *outbytesleft, + apr_size_t *translated); +/** + * Deallocate descriptor for character set conversion. + * @param cd conversion descriptor. + * @param pool pool used in the apr_iconv_open(). + */ +API_DECLARE(apr_status_t) apr_iconv_close(apr_iconv_t cd, apr_pool_t *pool); + +/* __END_DECLS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_ICONV_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_inherit.h b/c/dependencies/windows/apr/x86/include/apr_inherit.h new file mode 100644 index 00000000..b9fe56fe --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_inherit.h @@ -0,0 +1,51 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_INHERIT_H +#define APR_INHERIT_H + +/** + * @file apr_inherit.h + * @brief APR File Handle Inheritance Helpers + * @remark This internal header includes internal declaration helpers + * for other headers to declare apr_foo_inherit_[un]set functions. + */ + +/** + * Prototype for type-specific declarations of apr_foo_inherit_set + * functions. + * @remark Doxygen unwraps this macro (via doxygen.conf) to provide + * actual help for each specific occurrence of apr_foo_inherit_set. + * @remark the linkage is specified for APR. It would be possible to expand + * the macros to support other linkages. + */ +#define APR_DECLARE_INHERIT_SET(type) \ + APR_DECLARE(apr_status_t) apr_##type##_inherit_set( \ + apr_##type##_t *the##type) + +/** + * Prototype for type-specific declarations of apr_foo_inherit_unset + * functions. + * @remark Doxygen unwraps this macro (via doxygen.conf) to provide + * actual help for each specific occurrence of apr_foo_inherit_unset. + * @remark the linkage is specified for APR. It would be possible to expand + * the macros to support other linkages. + */ +#define APR_DECLARE_INHERIT_UNSET(type) \ + APR_DECLARE(apr_status_t) apr_##type##_inherit_unset( \ + apr_##type##_t *the##type) + +#endif /* ! APR_INHERIT_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_ldap.h b/c/dependencies/windows/apr/x86/include/apr_ldap.h new file mode 100644 index 00000000..c1bd0d4b --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_ldap.h @@ -0,0 +1,197 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_ldap.h is generated from apr_ldap.h.in by configure -- do not edit apr_ldap.h + */ +/** + * @file apr_ldap.h + * @brief APR-UTIL LDAP + */ +#ifndef APU_LDAP_H +#define APU_LDAP_H + +/** + * @defgroup APR_Util_LDAP LDAP + * @ingroup APR_Util + * @{ + */ + +/* this will be defined if LDAP support was compiled into apr-util */ +#define APR_HAS_LDAP 1 + +/* identify the LDAP toolkit used */ +#define APR_HAS_NETSCAPE_LDAPSDK 0 +#define APR_HAS_SOLARIS_LDAPSDK 0 +#define APR_HAS_NOVELL_LDAPSDK 0 +#define APR_HAS_MOZILLA_LDAPSDK 0 +#define APR_HAS_OPENLDAP_LDAPSDK 0 +#define APR_HAS_MICROSOFT_LDAPSDK 1 +#define APR_HAS_TIVOLI_LDAPSDK 0 +#define APR_HAS_ZOS_LDAPSDK 0 +#define APR_HAS_OTHER_LDAPSDK 0 + + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/* + * The following #defines are DEPRECATED and should not be used for + * anything. They remain to maintain binary compatibility. + * The original code defined the OPENLDAP SDK as present regardless + * of what really was there, which was way bogus. In addition, the + * apr_ldap_url_parse*() functions have been rewritten specifically for + * APR, so the APR_HAS_LDAP_URL_PARSE macro is forced to zero. + */ +#if APR_HAS_TIVOLI_LDAPSDK +#define APR_HAS_LDAP_SSL 0 +#else +#define APR_HAS_LDAP_SSL 1 +#endif +#define APR_HAS_LDAP_URL_PARSE 0 + +#if APR_HAS_OPENLDAP_LDAPSDK && !defined(LDAP_DEPRECATED) +/* Ensure that the "deprecated" interfaces are still exposed + * with OpenLDAP >= 2.3; these were exposed by default in earlier + * releases. */ +#define LDAP_DEPRECATED 1 +#endif + +/* + * Include the standard LDAP header files. + */ + +#include + + +/* + * Detected standard functions + */ +#define APR_HAS_LDAPSSL_CLIENT_INIT 0 +#define APR_HAS_LDAPSSL_CLIENT_DEINIT 0 +#define APR_HAS_LDAPSSL_ADD_TRUSTED_CERT 0 +#define APR_HAS_LDAP_START_TLS_S 0 +#define APR_HAS_LDAP_SSLINIT 1 +#define APR_HAS_LDAPSSL_INIT 0 +#define APR_HAS_LDAPSSL_INSTALL_ROUTINES 0 + + +/* + * Make sure the secure LDAP port is defined + */ +#ifndef LDAPS_PORT +#define LDAPS_PORT 636 /* ldaps:/// default LDAP over TLS port */ +#endif + + +/* + * For ldap function calls that input a size limit on the number of returned elements + * Some SDKs do not have the define for LDAP_DEFAULT_LIMIT (-1) or LDAP_NO_LIMIT (0) + * LDAP_DEFAULT_LIMIT is preferred as it allows inheritance from whatever the SDK + * or process is configured for. + */ +#ifdef LDAP_DEFAULT_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_DEFAULT_LIMIT +#else +#ifdef LDAP_NO_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_NO_LIMIT +#endif +#endif + +#ifndef APR_LDAP_SIZELIMIT +#define APR_LDAP_SIZELIMIT 0 /* equivalent to LDAP_NO_LIMIT, and what goes on the wire */ +#endif + +/* + * z/OS is missing some defines + */ +#ifndef LDAP_VERSION_MAX +#define LDAP_VERSION_MAX LDAP_VERSION +#endif +#if APR_HAS_ZOS_LDAPSDK +#define LDAP_VENDOR_NAME "IBM z/OS" +#endif + +/* Note: Macros defining const casting has been removed in APR v1.0, + * pending real support for LDAP v2.0 toolkits. + * + * In the mean time, please use an LDAP v3.0 toolkit. + */ +#if LDAP_VERSION_MAX <= 2 +#error Support for LDAP v2.0 toolkits has been removed from apr-util. Please use an LDAP v3.0 toolkit. +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * This structure allows the C LDAP API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apr_ldap_err_t { + const char *reason; + const char *msg; + int rc; +} apr_ldap_err_t; + +#ifdef __cplusplus +} +#endif + +/* The MS SDK returns LDAP_UNAVAILABLE when the backend has closed the connection + * between LDAP calls. Protect with APR_HAS_MICROSOFT_LDAPSDK in case someone + * manually chooses another SDK on Windows + */ +#if APR_HAS_MICROSOFT_LDAPSDK +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN \ + || (s) == LDAP_UNAVAILABLE) +#else +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN) +#endif + +/* These symbols are not actually exported in a DSO build, but mapped into + * a private exported function array for apr_ldap_stub to bind dynamically. + * Rename them appropriately to protect the global namespace. + */ +#ifdef APU_DSO_LDAP_BUILD + +#define apr_ldap_info apr__ldap_info +#define apr_ldap_init apr__ldap_init +#define apr_ldap_ssl_init apr__ldap_ssl_init +#define apr_ldap_ssl_deinit apr__ldap_ssl_deinit +#define apr_ldap_get_option apr__ldap_get_option +#define apr_ldap_set_option apr__ldap_set_option +#define apr_ldap_rebind_init apr__ldap_rebind_init +#define apr_ldap_rebind_add apr__ldap_rebind_add +#define apr_ldap_rebind_remove apr__ldap_rebind_remove + +#define APU_DECLARE_LDAP(type) type +#else +#define APU_DECLARE_LDAP(type) APU_DECLARE(type) +#endif + +#include "apr_ldap_url.h" +#include "apr_ldap_init.h" +#include "apr_ldap_option.h" +#include "apr_ldap_rebind.h" + +/** @} */ +#endif /* APR_HAS_LDAP */ +#endif /* APU_LDAP_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_ldap.h.in b/c/dependencies/windows/apr/x86/include/apr_ldap.h.in new file mode 100644 index 00000000..6c62d601 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_ldap.h.in @@ -0,0 +1,197 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_ldap.h is generated from apr_ldap.h.in by configure -- do not edit apr_ldap.h + */ +/** + * @file apr_ldap.h + * @brief APR-UTIL LDAP + */ +#ifndef APU_LDAP_H +#define APU_LDAP_H + +/** + * @defgroup APR_Util_LDAP LDAP + * @ingroup APR_Util + * @{ + */ + +/* this will be defined if LDAP support was compiled into apr-util */ +#define APR_HAS_LDAP @apu_has_ldap@ + +/* identify the LDAP toolkit used */ +#define APR_HAS_NETSCAPE_LDAPSDK @apu_has_ldap_netscape@ +#define APR_HAS_SOLARIS_LDAPSDK @apu_has_ldap_solaris@ +#define APR_HAS_NOVELL_LDAPSDK @apu_has_ldap_novell@ +#define APR_HAS_MOZILLA_LDAPSDK @apu_has_ldap_mozilla@ +#define APR_HAS_OPENLDAP_LDAPSDK @apu_has_ldap_openldap@ +#define APR_HAS_MICROSOFT_LDAPSDK @apu_has_ldap_microsoft@ +#define APR_HAS_TIVOLI_LDAPSDK @apu_has_ldap_tivoli@ +#define APR_HAS_ZOS_LDAPSDK @apu_has_ldap_zos@ +#define APR_HAS_OTHER_LDAPSDK @apu_has_ldap_other@ + + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/* + * The following #defines are DEPRECATED and should not be used for + * anything. They remain to maintain binary compatibility. + * The original code defined the OPENLDAP SDK as present regardless + * of what really was there, which was way bogus. In addition, the + * apr_ldap_url_parse*() functions have been rewritten specifically for + * APR, so the APR_HAS_LDAP_URL_PARSE macro is forced to zero. + */ +#if APR_HAS_TIVOLI_LDAPSDK +#define APR_HAS_LDAP_SSL 0 +#else +#define APR_HAS_LDAP_SSL 1 +#endif +#define APR_HAS_LDAP_URL_PARSE 0 + +#if APR_HAS_OPENLDAP_LDAPSDK && !defined(LDAP_DEPRECATED) +/* Ensure that the "deprecated" interfaces are still exposed + * with OpenLDAP >= 2.3; these were exposed by default in earlier + * releases. */ +#define LDAP_DEPRECATED 1 +#endif + +/* + * Include the standard LDAP header files. + */ + +@lber_h@ +@ldap_h@ +@ldap_ssl_h@ + + +/* + * Detected standard functions + */ +#define APR_HAS_LDAPSSL_CLIENT_INIT @apu_has_ldapssl_client_init@ +#define APR_HAS_LDAPSSL_CLIENT_DEINIT @apu_has_ldapssl_client_deinit@ +#define APR_HAS_LDAPSSL_ADD_TRUSTED_CERT @apu_has_ldapssl_add_trusted_cert@ +#define APR_HAS_LDAP_START_TLS_S @apu_has_ldap_start_tls_s@ +#define APR_HAS_LDAP_SSLINIT @apu_has_ldap_sslinit@ +#define APR_HAS_LDAPSSL_INIT @apu_has_ldapssl_init@ +#define APR_HAS_LDAPSSL_INSTALL_ROUTINES @apu_has_ldapssl_install_routines@ + +/* + * Make sure the secure LDAP port is defined + */ +#ifndef LDAPS_PORT +#define LDAPS_PORT 636 /* ldaps:/// default LDAP over TLS port */ +#endif + +/* + * For ldap function calls that input a size limit on the number of returned elements + * Some SDKs do not have the define for LDAP_DEFAULT_LIMIT (-1) or LDAP_NO_LIMIT (0) + * LDAP_DEFAULT_LIMIT is preferred as it allows inheritance from whatever the SDK + * or process is configured for. + */ +#ifdef LDAP_DEFAULT_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_DEFAULT_LIMIT +#else +#ifdef LDAP_NO_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_NO_LIMIT +#endif +#endif + +#ifndef APR_LDAP_SIZELIMIT +#define APR_LDAP_SIZELIMIT 0 /* equivalent to LDAP_NO_LIMIT, and what goes on the wire */ +#endif + +/* + * z/OS is missing some defines + */ +#ifndef LDAP_VERSION_MAX +#define LDAP_VERSION_MAX LDAP_VERSION +#endif +#if APR_HAS_ZOS_LDAPSDK +#define LDAP_VENDOR_NAME "IBM z/OS" +#endif + +/* Note: Macros defining const casting has been removed in APR v1.0, + * pending real support for LDAP v2.0 toolkits. + * + * In the mean time, please use an LDAP v3.0 toolkit. + */ +#if LDAP_VERSION_MAX <= 2 +#error Support for LDAP v2.0 toolkits has been removed from apr-util. Please use an LDAP v3.0 toolkit. +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * This structure allows the C LDAP API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apr_ldap_err_t { + const char *reason; + const char *msg; + int rc; +} apr_ldap_err_t; + +#ifdef __cplusplus +} +#endif + +/* The MS SDK returns LDAP_UNAVAILABLE when the backend has closed the connection + * between LDAP calls. Protect with APR_HAS_MICROSOFT_LDAPSDK in case someone + * manually chooses another SDK on Windows + */ +#if APR_HAS_MICROSOFT_LDAPSDK +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN \ + || (s) == LDAP_UNAVAILABLE) +#else +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN) +#endif + +/* These symbols are not actually exported in a DSO build, but mapped into + * a private exported function array for apr_ldap_stub to bind dynamically. + * Rename them appropriately to protect the global namespace. + */ +#ifdef APU_DSO_LDAP_BUILD + +#define apr_ldap_info apr__ldap_info +#define apr_ldap_init apr__ldap_init +#define apr_ldap_ssl_init apr__ldap_ssl_init +#define apr_ldap_ssl_deinit apr__ldap_ssl_deinit +#define apr_ldap_get_option apr__ldap_get_option +#define apr_ldap_set_option apr__ldap_set_option +#define apr_ldap_rebind_init apr__ldap_rebind_init +#define apr_ldap_rebind_add apr__ldap_rebind_add +#define apr_ldap_rebind_remove apr__ldap_rebind_remove + +#define APU_DECLARE_LDAP(type) type +#else +#define APU_DECLARE_LDAP(type) APU_DECLARE(type) +#endif + +#include "apr_ldap_url.h" +#include "apr_ldap_init.h" +#include "apr_ldap_option.h" +#include "apr_ldap_rebind.h" + +#endif /* APR_HAS_LDAP */ +/** @} */ +#endif /* APU_LDAP_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_ldap.hnw b/c/dependencies/windows/apr/x86/include/apr_ldap.hnw new file mode 100644 index 00000000..2148c90f --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_ldap.hnw @@ -0,0 +1,158 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_ldap.h is generated from apr_ldap.h.in by configure -- do not edit apr_ldap.h + */ +/** + * @file apr_ldap.h + * @brief APR-UTIL LDAP + */ +#ifndef APU_LDAP_H +#define APU_LDAP_H + +/** + * @defgroup APR_Util_LDAP LDAP + * @ingroup APR_Util + * @{ + */ + +/* this will be defined if LDAP support was compiled into apr-util */ +#define APR_HAS_LDAP 1 + +/* identify the LDAP toolkit used */ +#define APR_HAS_NETSCAPE_LDAPSDK 0 +#define APR_HAS_SOLARIS_LDAPSDK 0 +#define APR_HAS_NOVELL_LDAPSDK 1 +#define APR_HAS_MOZILLA_LDAPSDK 0 +#define APR_HAS_OPENLDAP_LDAPSDK 0 +#define APR_HAS_MICROSOFT_LDAPSDK 0 +#define APR_HAS_OTHER_LDAPSDK 0 + + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/* + * The following #defines are DEPRECATED and should not be used for + * anything. They remain to maintain binary compatibility. + * The original code defined the OPENLDAP SDK as present regardless + * of what really was there, which was way bogus. In addition, the + * apr_ldap_url_parse*() functions have been rewritten specifically for + * APR, so the APR_HAS_LDAP_URL_PARSE macro is forced to zero. + */ +#define APR_HAS_LDAP_SSL 1 +#define APR_HAS_LDAP_URL_PARSE 0 + + +/* + * Include the standard LDAP header files. + */ + +#ifdef GENEXPORTS +#define LDAP_VERSION_MAX 3 +#define LDAP_INSUFFICIENT_ACCESS +#else +#include +#include +#if APR_HAS_LDAP_SSL +#include +#endif +#endif + + +/* + * Detected standard functions + */ +#define APR_HAS_LDAPSSL_CLIENT_INIT 1 +#define APR_HAS_LDAPSSL_CLIENT_DEINIT 1 +#define APR_HAS_LDAPSSL_ADD_TRUSTED_CERT 1 +#define APR_HAS_LDAP_START_TLS_S 0 +#define APR_HAS_LDAP_SSLINIT 0 +#define APR_HAS_LDAPSSL_INIT 1 +#define APR_HAS_LDAPSSL_INSTALL_ROUTINES 0 + + +/* + * Make sure the secure LDAP port is defined + */ +#ifndef LDAPS_PORT +#define LDAPS_PORT 636 /* ldaps:/// default LDAP over TLS port */ +#endif + + +/* Note: Macros defining const casting has been removed in APR v1.0, + * pending real support for LDAP v2.0 toolkits. + * + * In the mean time, please use an LDAP v3.0 toolkit. + */ +#if LDAP_VERSION_MAX <= 2 +#error Support for LDAP v2.0 toolkits has been removed from apr-util. Please use an LDAP v3.0 toolkit. +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * This structure allows the C LDAP API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apr_ldap_err_t { + const char *reason; + const char *msg; + int rc; +} apr_ldap_err_t; + +#ifdef __cplusplus +} +#endif + +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN) + +/* These symbols are not actually exported in a DSO build, but mapped into + * a private exported function array for apr_ldap_stub to bind dynamically. + * Rename them appropriately to protect the global namespace. + */ +#ifdef APU_DSO_LDAP_BUILD + +#define apr_ldap_info apr__ldap_info +#define apr_ldap_init apr__ldap_init +#define apr_ldap_ssl_init apr__ldap_ssl_init +#define apr_ldap_ssl_deinit apr__ldap_ssl_deinit +#define apr_ldap_get_option apr__ldap_get_option +#define apr_ldap_set_option apr__ldap_set_option +#define apr_ldap_rebind_init apr__ldap_rebind_init +#define apr_ldap_rebind_add apr__ldap_rebind_add +#define apr_ldap_rebind_remove apr__ldap_rebind_remove + +#define APU_DECLARE_LDAP(type) type +#else +#define APU_DECLARE_LDAP(type) APU_DECLARE(type) +#endif + +#include "apr_ldap_url.h" +#include "apr_ldap_init.h" +#include "apr_ldap_option.h" +#include "apr_ldap_rebind.h" + +/** @} */ +#endif /* APR_HAS_LDAP */ +#endif /* APU_LDAP_H */ + diff --git a/c/dependencies/windows/apr/x86/include/apr_ldap.hw b/c/dependencies/windows/apr/x86/include/apr_ldap.hw new file mode 100644 index 00000000..fcef8b17 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_ldap.hw @@ -0,0 +1,197 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_ldap.h is generated from apr_ldap.h.in by configure -- do not edit apr_ldap.h + */ +/** + * @file apr_ldap.h + * @brief APR-UTIL LDAP + */ +#ifndef APU_LDAP_H +#define APU_LDAP_H + +/** + * @defgroup APR_Util_LDAP LDAP + * @ingroup APR_Util + * @{ + */ + +/* this will be defined if LDAP support was compiled into apr-util */ +#define APR_HAS_LDAP 1 + +/* identify the LDAP toolkit used */ +#define APR_HAS_NETSCAPE_LDAPSDK 0 +#define APR_HAS_SOLARIS_LDAPSDK 0 +#define APR_HAS_NOVELL_LDAPSDK 0 +#define APR_HAS_MOZILLA_LDAPSDK 0 +#define APR_HAS_OPENLDAP_LDAPSDK 0 +#define APR_HAS_MICROSOFT_LDAPSDK 1 +#define APR_HAS_TIVOLI_LDAPSDK 0 +#define APR_HAS_ZOS_LDAPSDK 0 +#define APR_HAS_OTHER_LDAPSDK 0 + + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/* + * The following #defines are DEPRECATED and should not be used for + * anything. They remain to maintain binary compatibility. + * The original code defined the OPENLDAP SDK as present regardless + * of what really was there, which was way bogus. In addition, the + * apr_ldap_url_parse*() functions have been rewritten specifically for + * APR, so the APR_HAS_LDAP_URL_PARSE macro is forced to zero. + */ +#if APR_HAS_TIVOLI_LDAPSDK +#define APR_HAS_LDAP_SSL 0 +#else +#define APR_HAS_LDAP_SSL 1 +#endif +#define APR_HAS_LDAP_URL_PARSE 0 + +#if APR_HAS_OPENLDAP_LDAPSDK && !defined(LDAP_DEPRECATED) +/* Ensure that the "deprecated" interfaces are still exposed + * with OpenLDAP >= 2.3; these were exposed by default in earlier + * releases. */ +#define LDAP_DEPRECATED 1 +#endif + +/* + * Include the standard LDAP header files. + */ + +#include + + +/* + * Detected standard functions + */ +#define APR_HAS_LDAPSSL_CLIENT_INIT 0 +#define APR_HAS_LDAPSSL_CLIENT_DEINIT 0 +#define APR_HAS_LDAPSSL_ADD_TRUSTED_CERT 0 +#define APR_HAS_LDAP_START_TLS_S 0 +#define APR_HAS_LDAP_SSLINIT 1 +#define APR_HAS_LDAPSSL_INIT 0 +#define APR_HAS_LDAPSSL_INSTALL_ROUTINES 0 + + +/* + * Make sure the secure LDAP port is defined + */ +#ifndef LDAPS_PORT +#define LDAPS_PORT 636 /* ldaps:/// default LDAP over TLS port */ +#endif + + +/* + * For ldap function calls that input a size limit on the number of returned elements + * Some SDKs do not have the define for LDAP_DEFAULT_LIMIT (-1) or LDAP_NO_LIMIT (0) + * LDAP_DEFAULT_LIMIT is preferred as it allows inheritance from whatever the SDK + * or process is configured for. + */ +#ifdef LDAP_DEFAULT_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_DEFAULT_LIMIT +#else +#ifdef LDAP_NO_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_NO_LIMIT +#endif +#endif + +#ifndef APR_LDAP_SIZELIMIT +#define APR_LDAP_SIZELIMIT 0 /* equivalent to LDAP_NO_LIMIT, and what goes on the wire */ +#endif + +/* + * z/OS is missing some defines + */ +#ifndef LDAP_VERSION_MAX +#define LDAP_VERSION_MAX LDAP_VERSION +#endif +#if APR_HAS_ZOS_LDAPSDK +#define LDAP_VENDOR_NAME "IBM z/OS" +#endif + +/* Note: Macros defining const casting has been removed in APR v1.0, + * pending real support for LDAP v2.0 toolkits. + * + * In the mean time, please use an LDAP v3.0 toolkit. + */ +#if LDAP_VERSION_MAX <= 2 +#error Support for LDAP v2.0 toolkits has been removed from apr-util. Please use an LDAP v3.0 toolkit. +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * This structure allows the C LDAP API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apr_ldap_err_t { + const char *reason; + const char *msg; + int rc; +} apr_ldap_err_t; + +#ifdef __cplusplus +} +#endif + +/* The MS SDK returns LDAP_UNAVAILABLE when the backend has closed the connection + * between LDAP calls. Protect with APR_HAS_MICROSOFT_LDAPSDK in case someone + * manually chooses another SDK on Windows + */ +#if APR_HAS_MICROSOFT_LDAPSDK +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN \ + || (s) == LDAP_UNAVAILABLE) +#else +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN) +#endif + +/* These symbols are not actually exported in a DSO build, but mapped into + * a private exported function array for apr_ldap_stub to bind dynamically. + * Rename them appropriately to protect the global namespace. + */ +#ifdef APU_DSO_LDAP_BUILD + +#define apr_ldap_info apr__ldap_info +#define apr_ldap_init apr__ldap_init +#define apr_ldap_ssl_init apr__ldap_ssl_init +#define apr_ldap_ssl_deinit apr__ldap_ssl_deinit +#define apr_ldap_get_option apr__ldap_get_option +#define apr_ldap_set_option apr__ldap_set_option +#define apr_ldap_rebind_init apr__ldap_rebind_init +#define apr_ldap_rebind_add apr__ldap_rebind_add +#define apr_ldap_rebind_remove apr__ldap_rebind_remove + +#define APU_DECLARE_LDAP(type) type +#else +#define APU_DECLARE_LDAP(type) APU_DECLARE(type) +#endif + +#include "apr_ldap_url.h" +#include "apr_ldap_init.h" +#include "apr_ldap_option.h" +#include "apr_ldap_rebind.h" + +/** @} */ +#endif /* APR_HAS_LDAP */ +#endif /* APU_LDAP_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_ldap.hwc b/c/dependencies/windows/apr/x86/include/apr_ldap.hwc new file mode 100644 index 00000000..4d07b296 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_ldap.hwc @@ -0,0 +1,197 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_ldap.h is generated from apr_ldap.h.in by configure -- do not edit apr_ldap.h + */ +/** + * @file apr_ldap.h + * @brief APR-UTIL LDAP + */ +#ifndef APU_LDAP_H +#define APU_LDAP_H + +/** + * @defgroup APR_Util_LDAP LDAP + * @ingroup APR_Util + * @{ + */ + +/* this will be defined if LDAP support was compiled into apr-util */ +#define APR_HAS_LDAP @apr_has_ldap_10@ + +/* identify the LDAP toolkit used */ +#define APR_HAS_NETSCAPE_LDAPSDK 0 +#define APR_HAS_SOLARIS_LDAPSDK 0 +#define APR_HAS_NOVELL_LDAPSDK 0 +#define APR_HAS_MOZILLA_LDAPSDK 0 +#define APR_HAS_OPENLDAP_LDAPSDK 0 +#define APR_HAS_MICROSOFT_LDAPSDK 1 +#define APR_HAS_TIVOLI_LDAPSDK 0 +#define APR_HAS_ZOS_LDAPSDK 0 +#define APR_HAS_OTHER_LDAPSDK 0 + + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/* + * The following #defines are DEPRECATED and should not be used for + * anything. They remain to maintain binary compatibility. + * The original code defined the OPENLDAP SDK as present regardless + * of what really was there, which was way bogus. In addition, the + * apr_ldap_url_parse*() functions have been rewritten specifically for + * APR, so the APR_HAS_LDAP_URL_PARSE macro is forced to zero. + */ +#if APR_HAS_TIVOLI_LDAPSDK +#define APR_HAS_LDAP_SSL 0 +#else +#define APR_HAS_LDAP_SSL 1 +#endif +#define APR_HAS_LDAP_URL_PARSE 0 + +#if APR_HAS_OPENLDAP_LDAPSDK && !defined(LDAP_DEPRECATED) +/* Ensure that the "deprecated" interfaces are still exposed + * with OpenLDAP >= 2.3; these were exposed by default in earlier + * releases. */ +#define LDAP_DEPRECATED 1 +#endif + +/* + * Include the standard LDAP header files. + */ + +#include + + +/* + * Detected standard functions + */ +#define APR_HAS_LDAPSSL_CLIENT_INIT 0 +#define APR_HAS_LDAPSSL_CLIENT_DEINIT 0 +#define APR_HAS_LDAPSSL_ADD_TRUSTED_CERT 0 +#define APR_HAS_LDAP_START_TLS_S 0 +#define APR_HAS_LDAP_SSLINIT 1 +#define APR_HAS_LDAPSSL_INIT 0 +#define APR_HAS_LDAPSSL_INSTALL_ROUTINES 0 + + +/* + * Make sure the secure LDAP port is defined + */ +#ifndef LDAPS_PORT +#define LDAPS_PORT 636 /* ldaps:/// default LDAP over TLS port */ +#endif + + +/* + * For ldap function calls that input a size limit on the number of returned elements + * Some SDKs do not have the define for LDAP_DEFAULT_LIMIT (-1) or LDAP_NO_LIMIT (0) + * LDAP_DEFAULT_LIMIT is preferred as it allows inheritance from whatever the SDK + * or process is configured for. + */ +#ifdef LDAP_DEFAULT_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_DEFAULT_LIMIT +#else +#ifdef LDAP_NO_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_NO_LIMIT +#endif +#endif + +#ifndef APR_LDAP_SIZELIMIT +#define APR_LDAP_SIZELIMIT 0 /* equivalent to LDAP_NO_LIMIT, and what goes on the wire */ +#endif + +/* + * z/OS is missing some defines + */ +#ifndef LDAP_VERSION_MAX +#define LDAP_VERSION_MAX LDAP_VERSION +#endif +#if APR_HAS_ZOS_LDAPSDK +#define LDAP_VENDOR_NAME "IBM z/OS" +#endif + +/* Note: Macros defining const casting has been removed in APR v1.0, + * pending real support for LDAP v2.0 toolkits. + * + * In the mean time, please use an LDAP v3.0 toolkit. + */ +#if LDAP_VERSION_MAX <= 2 +#error Support for LDAP v2.0 toolkits has been removed from apr-util. Please use an LDAP v3.0 toolkit. +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * This structure allows the C LDAP API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apr_ldap_err_t { + const char *reason; + const char *msg; + int rc; +} apr_ldap_err_t; + +#ifdef __cplusplus +} +#endif + +/* The MS SDK returns LDAP_UNAVAILABLE when the backend has closed the connection + * between LDAP calls. Protect with APR_HAS_MICROSOFT_LDAPSDK in case someone + * manually chooses another SDK on Windows + */ +#if APR_HAS_MICROSOFT_LDAPSDK +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN \ + || (s) == LDAP_UNAVAILABLE) +#else +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN) +#endif + +/* These symbols are not actually exported in a DSO build, but mapped into + * a private exported function array for apr_ldap_stub to bind dynamically. + * Rename them appropriately to protect the global namespace. + */ +#ifdef APU_DSO_LDAP_BUILD + +#define apr_ldap_info apr__ldap_info +#define apr_ldap_init apr__ldap_init +#define apr_ldap_ssl_init apr__ldap_ssl_init +#define apr_ldap_ssl_deinit apr__ldap_ssl_deinit +#define apr_ldap_get_option apr__ldap_get_option +#define apr_ldap_set_option apr__ldap_set_option +#define apr_ldap_rebind_init apr__ldap_rebind_init +#define apr_ldap_rebind_add apr__ldap_rebind_add +#define apr_ldap_rebind_remove apr__ldap_rebind_remove + +#define APU_DECLARE_LDAP(type) type +#else +#define APU_DECLARE_LDAP(type) APU_DECLARE(type) +#endif + +#include "apr_ldap_url.h" +#include "apr_ldap_init.h" +#include "apr_ldap_option.h" +#include "apr_ldap_rebind.h" + +/** @} */ +#endif /* APR_HAS_LDAP */ +#endif /* APU_LDAP_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_ldap_init.h b/c/dependencies/windows/apr/x86/include/apr_ldap_init.h new file mode 100644 index 00000000..aeb6d9bb --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_ldap_init.h @@ -0,0 +1,165 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_ldap_init.h + * @brief APR-UTIL LDAP ldap_init() functions + */ +#ifndef APR_LDAP_INIT_H +#define APR_LDAP_INIT_H + +/** + * @addtogroup APR_Util_LDAP + * @{ + */ + +#include "apr_ldap.h" + +#if APR_HAS_LDAP + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + + +/** + * Macro to detect security related return values. + */ +#if defined(LDAP_INSUFFICIENT_ACCESS) +#define APU_LDAP_INSUFFICIENT_ACCESS LDAP_INSUFFICIENT_ACCESS +#elif defined(LDAP_INSUFFICIENT_RIGHTS) +#define APU_LDAP_INSUFFICIENT_ACCESS LDAP_INSUFFICIENT_RIGHTS +#elif defined(APR_HAS_MICROSOFT_LDAPSDK) +/* The macros above fail to contemplate that LDAP_RETCODE values + * may be represented by an enum. autoconf tests would be much + * more robust. + */ +#define APU_LDAP_INSUFFICIENT_ACCESS LDAP_INSUFFICIENT_RIGHTS +#else +#error The security return codes must be added to support this LDAP toolkit. +#endif + +#if defined(LDAP_SECURITY_ERROR) +#define APU_LDAP_SECURITY_ERROR LDAP_SECURITY_ERROR +#else +#define APU_LDAP_SECURITY_ERROR(n) \ + (LDAP_INAPPROPRIATE_AUTH == n) ? 1 \ + : (LDAP_INVALID_CREDENTIALS == n) ? 1 \ + : (APU_LDAP_INSUFFICIENT_ACCESS == n) ? 1 \ + : 0 +#endif + + +/** + * APR LDAP SSL Initialise function + * + * This function initialises SSL on the underlying LDAP toolkit + * if this is necessary. + * + * If a CA certificate is provided, this is set, however the setting + * of certificates via this method has been deprecated and will be removed in + * APR v2.0. + * + * The apr_ldap_set_option() function with the APR_LDAP_OPT_TLS_CERT option + * should be used instead to set certificates. + * + * If SSL support is not available on this platform, or a problem + * was encountered while trying to set the certificate, the function + * will return APR_EGENERAL. Further LDAP specific error information + * can be found in result_err. + * @param pool The pool to use + * @param cert_auth_file The name of the certificate to use, can be NULL + * @param cert_file_type The type of certificate specified. See the + * apr_ldap_set_option() APR_LDAP_OPT_TLS_CERT option for details. + * @param result_err The returned result + */ +APU_DECLARE_LDAP(int) apr_ldap_ssl_init(apr_pool_t *pool, + const char *cert_auth_file, + int cert_file_type, + apr_ldap_err_t **result_err); + +/** + * APR LDAP SSL De-Initialise function + * + * This function tears down any SSL certificate setup previously + * set using apr_ldap_ssl_init(). It should be called to clean + * up if a graceful restart of a service is attempted. + * @todo currently we do not check whether apr_ldap_ssl_init() + * has been called first - we probably should. + */ +APU_DECLARE_LDAP(int) apr_ldap_ssl_deinit(void); + +/** + * APR LDAP initialise function + * + * This function is responsible for initialising an LDAP + * connection in a toolkit independant way. It does the + * job of ldap_init() from the C api. + * + * It handles both the SSL and non-SSL case, and attempts + * to hide the complexity setup from the user. This function + * assumes that any certificate setup necessary has already + * been done. + * + * If SSL or STARTTLS needs to be enabled, and the underlying + * toolkit supports it, the following values are accepted for + * secure: + * + * APR_LDAP_NONE: No encryption + * APR_LDAP_SSL: SSL encryption (ldaps://) + * APR_LDAP_STARTTLS: Force STARTTLS on ldap:// + * @remark The Novell toolkit is only able to set the SSL mode via this + * function. To work around this limitation, set the SSL mode here if no + * per connection client certificates are present, otherwise set secure + * APR_LDAP_NONE here, then set the per connection client certificates, + * followed by setting the SSL mode via apr_ldap_set_option(). As Novell + * does not support per connection client certificates, this problem is + * worked around while still being compatible with other LDAP toolkits. + * @param pool The pool to use + * @param ldap The LDAP handle + * @param hostname The name of the host to connect to. This can be either a + * DNS name, or an IP address. + * @param portno The port to connect to + * @param secure The security mode to set + * @param result_err The returned result + */ +APU_DECLARE_LDAP(int) apr_ldap_init(apr_pool_t *pool, + LDAP **ldap, + const char *hostname, + int portno, + int secure, + apr_ldap_err_t **result_err); + +/** + * APR LDAP info function + * + * This function returns a string describing the LDAP toolkit + * currently in use. The string is placed inside result_err->reason. + * @param pool The pool to use + * @param result_err The returned result + */ +APU_DECLARE_LDAP(int) apr_ldap_info(apr_pool_t *pool, + apr_ldap_err_t **result_err); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_HAS_LDAP */ + +/** @} */ + +#endif /* APR_LDAP_URL_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_ldap_option.h b/c/dependencies/windows/apr/x86/include/apr_ldap_option.h new file mode 100644 index 00000000..0ff8a862 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_ldap_option.h @@ -0,0 +1,254 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_ldap_option.h + * @brief APR-UTIL LDAP ldap_*_option() functions + */ +#ifndef APR_LDAP_OPTION_H +#define APR_LDAP_OPTION_H + +/** + * @addtogroup APR_Util_LDAP + * @{ + */ + +#include "apr_ldap.h" + +#if APR_HAS_LDAP + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* + * The following defines handle the different TLS certificate + * options available. If these options are missing, APR will try and + * emulate support for this using the deprecated ldap_start_tls_s() + * function. + */ +/** + * Set SSL mode to one of APR_LDAP_NONE, APR_LDAP_SSL, APR_LDAP_STARTTLS + * or APR_LDAP_STOPTLS. + */ +#define APR_LDAP_OPT_TLS 0x6fff +/** + * Set zero or more CA certificates, client certificates or private + * keys globally, or per connection (where supported). + */ +#define APR_LDAP_OPT_TLS_CERT 0x6ffe +/** + * Set the LDAP library to no verify the server certificate. This means + * all servers are considered trusted. + */ +#define APR_LDAP_OPT_VERIFY_CERT 0x6ffd +/** + * Set the LDAP library to indicate if referrals should be chased during + * LDAP searches. + */ +#define APR_LDAP_OPT_REFERRALS 0x6ffc +/** + * Set the LDAP library to indicate a maximum number of referral hops to + * chase before giving up on the search. + */ +#define APR_LDAP_OPT_REFHOPLIMIT 0x6ffb + +/** + * Structures for the apr_set_option() cases + */ + +/** + * APR_LDAP_OPT_TLS_CERT + * + * This structure includes possible options to set certificates on + * system initialisation. Different SDKs have different certificate + * requirements, and to achieve this multiple certificates must be + * specified at once passed as an (apr_array_header_t *). + * + * Netscape: + * Needs the CA cert database (cert7.db), the client cert database (key3.db) + * and the security module file (secmod.db) set at the system initialisation + * time. Three types are supported: APR_LDAP_CERT7_DB, APR_LDAP_KEY3_DB and + * APR_LDAP_SECMOD. + * + * To specify a client cert connection, a certificate nickname needs to be + * provided with a type of APR_LDAP_CERT. + * int ldapssl_enable_clientauth( LDAP *ld, char *keynickname, + * char *keypasswd, char *certnickname ); + * keynickname is currently not used, and should be set to "" + * + * Novell: + * Needs CA certificates and client certificates set at system initialisation + * time. Three types are supported: APR_LDAP_CA*, APR_LDAP_CERT* and + * APR_LDAP_KEY*. + * + * Certificates cannot be specified per connection. + * + * The functions used are: + * ldapssl_add_trusted_cert(serverTrustedRoot, serverTrustedRootEncoding); + * Clients certs and keys are set at system initialisation time with + * int ldapssl_set_client_cert ( + * void *cert, + * int type + * void *password); + * type can be LDAPSSL_CERT_FILETYPE_B64 or LDAPSSL_CERT_FILETYPE_DER + * ldapssl_set_client_private_key(clientPrivateKey, + * clientPrivateKeyEncoding, + * clientPrivateKeyPassword); + * + * OpenSSL: + * Needs one or more CA certificates to be set at system initialisation time + * with a type of APR_LDAP_CA*. + * + * May have one or more client certificates set per connection with a type of + * APR_LDAP_CERT*, and keys with APR_LDAP_KEY*. + */ +/** CA certificate type unknown */ +#define APR_LDAP_CA_TYPE_UNKNOWN 0 +/** binary DER encoded CA certificate */ +#define APR_LDAP_CA_TYPE_DER 1 +/** PEM encoded CA certificate */ +#define APR_LDAP_CA_TYPE_BASE64 2 +/** Netscape/Mozilla cert7.db CA certificate database */ +#define APR_LDAP_CA_TYPE_CERT7_DB 3 +/** Netscape/Mozilla secmod file */ +#define APR_LDAP_CA_TYPE_SECMOD 4 +/** Client certificate type unknown */ +#define APR_LDAP_CERT_TYPE_UNKNOWN 5 +/** binary DER encoded client certificate */ +#define APR_LDAP_CERT_TYPE_DER 6 +/** PEM encoded client certificate */ +#define APR_LDAP_CERT_TYPE_BASE64 7 +/** Netscape/Mozilla key3.db client certificate database */ +#define APR_LDAP_CERT_TYPE_KEY3_DB 8 +/** Netscape/Mozilla client certificate nickname */ +#define APR_LDAP_CERT_TYPE_NICKNAME 9 +/** Private key type unknown */ +#define APR_LDAP_KEY_TYPE_UNKNOWN 10 +/** binary DER encoded private key */ +#define APR_LDAP_KEY_TYPE_DER 11 +/** PEM encoded private key */ +#define APR_LDAP_KEY_TYPE_BASE64 12 +/** PKCS#12 encoded client certificate */ +#define APR_LDAP_CERT_TYPE_PFX 13 +/** PKCS#12 encoded private key */ +#define APR_LDAP_KEY_TYPE_PFX 14 +/** Openldap directory full of base64-encoded cert + * authorities with hashes in corresponding .0 directory + */ +#define APR_LDAP_CA_TYPE_CACERTDIR_BASE64 15 + + +/** + * Certificate structure. + * + * This structure is used to store certificate details. An array of + * these structures is passed to apr_ldap_set_option() to set CA + * and client certificates. + * @param type Type of certificate APR_LDAP_*_TYPE_* + * @param path Path, file or nickname of the certificate + * @param password Optional password, can be NULL + */ +typedef struct apr_ldap_opt_tls_cert_t apr_ldap_opt_tls_cert_t; +struct apr_ldap_opt_tls_cert_t { + int type; + const char *path; + const char *password; +}; + +/** + * APR_LDAP_OPT_TLS + * + * This sets the SSL level on the LDAP handle. + * + * Netscape/Mozilla: + * Supports SSL, but not STARTTLS + * SSL is enabled by calling ldapssl_install_routines(). + * + * Novell: + * Supports SSL and STARTTLS. + * SSL is enabled by calling ldapssl_install_routines(). Note that calling + * other ldap functions before ldapssl_install_routines() may cause this + * function to fail. + * STARTTLS is enabled by calling ldapssl_start_tls_s() after calling + * ldapssl_install_routines() (check this). + * + * OpenLDAP: + * Supports SSL and supports STARTTLS, but none of this is documented: + * http://www.openldap.org/lists/openldap-software/200409/msg00618.html + * Documentation for both SSL support and STARTTLS has been deleted from + * the OpenLDAP documentation and website. + */ + +/** No encryption */ +#define APR_LDAP_NONE 0 +/** SSL encryption (ldaps://) */ +#define APR_LDAP_SSL 1 +/** TLS encryption (STARTTLS) */ +#define APR_LDAP_STARTTLS 2 +/** end TLS encryption (STOPTLS) */ +#define APR_LDAP_STOPTLS 3 + +/** + * APR LDAP get option function + * + * This function gets option values from a given LDAP session if + * one was specified. It maps to the native ldap_get_option() function. + * @param pool The pool to use + * @param ldap The LDAP handle + * @param option The LDAP_OPT_* option to return + * @param outvalue The value returned (if any) + * @param result_err The apr_ldap_err_t structure contained detailed results + * of the operation. + */ +APU_DECLARE_LDAP(int) apr_ldap_get_option(apr_pool_t *pool, + LDAP *ldap, + int option, + void *outvalue, + apr_ldap_err_t **result_err); + +/** + * APR LDAP set option function + * + * This function sets option values to a given LDAP session if + * one was specified. It maps to the native ldap_set_option() function. + * + * Where an option is not supported by an LDAP toolkit, this function + * will try and apply legacy functions to achieve the same effect, + * depending on the platform. + * @param pool The pool to use + * @param ldap The LDAP handle + * @param option The LDAP_OPT_* option to set + * @param invalue The value to set + * @param result_err The apr_ldap_err_t structure contained detailed results + * of the operation. + */ +APU_DECLARE_LDAP(int) apr_ldap_set_option(apr_pool_t *pool, + LDAP *ldap, + int option, + const void *invalue, + apr_ldap_err_t **result_err); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_HAS_LDAP */ + +/** @} */ + +#endif /* APR_LDAP_OPTION_H */ + diff --git a/c/dependencies/windows/apr/x86/include/apr_ldap_rebind.h b/c/dependencies/windows/apr/x86/include/apr_ldap_rebind.h new file mode 100644 index 00000000..342a17c3 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_ldap_rebind.h @@ -0,0 +1,98 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The APR LDAP rebind functions provide an implementation of + * a rebind procedure that can be used to allow clients to chase referrals, + * using the same credentials used to log in originally. + * + * Use of this implementation is optional. + * + * @file apr_ldap_rebind.h + * @brief Apache LDAP library + */ + +#ifndef APU_LDAP_REBIND_H +#define APU_LDAP_REBIND_H + +/** + * @addtogroup APR_Util_LDAP + * @{ + **/ + +#if defined(DOXYGEN) +#include "apr_ldap.h" +#endif + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/** + * APR LDAP initialize rebind lock + * + * This function creates the lock for controlling access to the xref list.. + * @param pool Pool to use when creating the xref_lock. + */ +APU_DECLARE_LDAP(apr_status_t) apr_ldap_rebind_init(apr_pool_t *pool); + + +/** + * APR LDAP rebind_add function + * + * This function creates a cross reference entry for the specified ldap + * connection. The rebind callback function will look up this ldap + * connection so it can retrieve the bindDN and bindPW for use in any + * binds while referrals are being chased. + * + * This function will add the callback to the LDAP handle passed in. + * + * A cleanup is registered within the pool provided to remove this + * entry when the pool is removed. Alternatively apr_ldap_rebind_remove() + * can be called to explicitly remove the entry at will. + * + * @param pool The pool to use + * @param ld The LDAP connectionhandle + * @param bindDN The bind DN to be used for any binds while chasing + * referrals on this ldap connection. + * @param bindPW The bind Password to be used for any binds while + * chasing referrals on this ldap connection. + */ +APU_DECLARE_LDAP(apr_status_t) apr_ldap_rebind_add(apr_pool_t *pool, + LDAP *ld, + const char *bindDN, + const char *bindPW); + +/** + * APR LDAP rebind_remove function + * + * This function removes the rebind cross reference entry for the + * specified ldap connection. + * + * If not explicitly removed, this function will be called automatically + * when the pool is cleaned up. + * + * @param ld The LDAP connectionhandle + */ +APU_DECLARE_LDAP(apr_status_t) apr_ldap_rebind_remove(LDAP *ld); + +#endif /* APR_HAS_LDAP */ + +/** @} */ + +#endif /* APU_LDAP_REBIND_H */ + diff --git a/c/dependencies/windows/apr/x86/include/apr_ldap_url.h b/c/dependencies/windows/apr/x86/include/apr_ldap_url.h new file mode 100644 index 00000000..a71f5b3c --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_ldap_url.h @@ -0,0 +1,120 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_ldap_url.h + * @brief APR-UTIL LDAP ldap_init() functions + */ +#ifndef APR_LDAP_URL_H +#define APR_LDAP_URL_H + +/** + * @addtogroup APR_Util_LDAP + * @{ + */ + +#if defined(DOXYGEN) +#include "apr_ldap.h" +#endif + +#if APR_HAS_LDAP + +#include "apu.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** Structure to access an exploded LDAP URL */ +typedef struct apr_ldap_url_desc_t { + struct apr_ldap_url_desc_t *lud_next; + char *lud_scheme; + char *lud_host; + int lud_port; + char *lud_dn; + char **lud_attrs; + int lud_scope; + char *lud_filter; + char **lud_exts; + int lud_crit_exts; +} apr_ldap_url_desc_t; + +#ifndef APR_LDAP_URL_SUCCESS +#define APR_LDAP_URL_SUCCESS 0x00 /* Success */ +#define APR_LDAP_URL_ERR_MEM 0x01 /* can't allocate memory space */ +#define APR_LDAP_URL_ERR_PARAM 0x02 /* parameter is bad */ +#define APR_LDAP_URL_ERR_BADSCHEME 0x03 /* URL doesn't begin with "ldap[si]://" */ +#define APR_LDAP_URL_ERR_BADENCLOSURE 0x04 /* URL is missing trailing ">" */ +#define APR_LDAP_URL_ERR_BADURL 0x05 /* URL is bad */ +#define APR_LDAP_URL_ERR_BADHOST 0x06 /* host port is bad */ +#define APR_LDAP_URL_ERR_BADATTRS 0x07 /* bad (or missing) attributes */ +#define APR_LDAP_URL_ERR_BADSCOPE 0x08 /* scope string is invalid (or missing) */ +#define APR_LDAP_URL_ERR_BADFILTER 0x09 /* bad or missing filter */ +#define APR_LDAP_URL_ERR_BADEXTS 0x0a /* bad or missing extensions */ +#endif + +/** + * Is this URL an ldap url? ldap:// + * @param url The url to test + */ +APU_DECLARE(int) apr_ldap_is_ldap_url(const char *url); + +/** + * Is this URL an SSL ldap url? ldaps:// + * @param url The url to test + */ +APU_DECLARE(int) apr_ldap_is_ldaps_url(const char *url); + +/** + * Is this URL an ldap socket url? ldapi:// + * @param url The url to test + */ +APU_DECLARE(int) apr_ldap_is_ldapi_url(const char *url); + +/** + * Parse an LDAP URL. + * @param pool The pool to use + * @param url_in The URL to parse + * @param ludpp The structure to return the exploded URL + * @param result_err The result structure of the operation + */ +APU_DECLARE(int) apr_ldap_url_parse_ext(apr_pool_t *pool, + const char *url_in, + apr_ldap_url_desc_t **ludpp, + apr_ldap_err_t **result_err); + +/** + * Parse an LDAP URL. + * @param pool The pool to use + * @param url_in The URL to parse + * @param ludpp The structure to return the exploded URL + * @param result_err The result structure of the operation + */ +APU_DECLARE(int) apr_ldap_url_parse(apr_pool_t *pool, + const char *url_in, + apr_ldap_url_desc_t **ludpp, + apr_ldap_err_t **result_err); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_HAS_LDAP */ + +/** @} */ + +#endif /* APR_LDAP_URL_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_lib.h b/c/dependencies/windows/apr/x86/include/apr_lib.h new file mode 100644 index 00000000..466e8185 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_lib.h @@ -0,0 +1,241 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_LIB_H +#define APR_LIB_H + +/** + * @file apr_lib.h + * This is collection of oddballs that didn't fit anywhere else, + * and might move to more appropriate headers with the release + * of APR 1.0. + * @brief APR general purpose library routines + */ + +#include "apr.h" +#include "apr_errno.h" + +#if APR_HAVE_CTYPE_H +#include +#endif +#if APR_HAVE_STDARG_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_lib General Purpose Library Routines + * @ingroup APR + * This is collection of oddballs that didn't fit anywhere else, + * and might move to more appropriate headers with the release + * of APR 1.0. + * @{ + */ + +/** A constant representing a 'large' string. */ +#define HUGE_STRING_LEN 8192 + +/* + * Define the structures used by the APR general-purpose library. + */ + +/** @see apr_vformatter_buff_t */ +typedef struct apr_vformatter_buff_t apr_vformatter_buff_t; + +/** + * Structure used by the variable-formatter routines. + */ +struct apr_vformatter_buff_t { + /** The current position */ + char *curpos; + /** The end position of the format string */ + char *endpos; +}; + +/** + * return the final element of the pathname + * @param pathname The path to get the final element of + * @return the final element of the path + * @remark + *
+ * For example:
+ *                 "/foo/bar/gum"    -> "gum"
+ *                 "/foo/bar/gum/"   -> ""
+ *                 "gum"             -> "gum"
+ *                 "bs\\path\\stuff" -> "stuff"
+ * 
+ */ +APR_DECLARE(const char *) apr_filepath_name_get(const char *pathname); + +/** + * apr_killpg + * Small utility macros to make things easier to read. Not usually a + * goal, to be sure.. + */ + +#ifdef WIN32 +#define apr_killpg(x, y) +#else /* WIN32 */ +#ifdef NO_KILLPG +#define apr_killpg(x, y) (kill (-(x), (y))) +#else /* NO_KILLPG */ +#define apr_killpg(x, y) (killpg ((x), (y))) +#endif /* NO_KILLPG */ +#endif /* WIN32 */ + +/** + * apr_vformatter() is a generic printf-style formatting routine + * with some extensions. + * @param flush_func The function to call when the buffer is full + * @param c The buffer to write to + * @param fmt The format string + * @param ap The arguments to use to fill out the format string. + * + * @remark + *
+ * The extensions are:
+ *
+ * - %%pA takes a struct in_addr *, and prints it as a.b.c.d
+ * - %%pI takes an apr_sockaddr_t * and prints it as a.b.c.d:port or
+ * \[ipv6-address\]:port
+ * - %%pT takes an apr_os_thread_t * and prints it in decimal
+ * ('0' is printed if !APR_HAS_THREADS)
+ * - %%pt takes an apr_os_thread_t * and prints it in hexadecimal
+ * ('0' is printed if !APR_HAS_THREADS)
+ * - %%pm takes an apr_status_t * and prints the appropriate error
+ * string (from apr_strerror) corresponding to that error code.
+ * - %%pp takes a void * and outputs it in hex
+ * - %%pB takes a apr_uint32_t * as bytes and outputs it's apr_strfsize
+ * - %%pF same as above, but takes a apr_off_t *
+ * - %%pS same as above, but takes a apr_size_t *
+ *
+ * %%pA, %%pI, %%pT, %%pp are available from APR 1.0.0 onwards (and in 0.9.x).
+ * %%pt is only available from APR 1.2.0 onwards.
+ * %%pm, %%pB, %%pF and %%pS are only available from APR 1.3.0 onwards.
+ *
+ * The %%p hacks are to force gcc's printf warning code to skip
+ * over a pointer argument without complaining.  This does
+ * mean that the ANSI-style %%p (output a void * in hex format) won't
+ * work as expected at all, but that seems to be a fair trade-off
+ * for the increased robustness of having printf-warnings work.
+ *
+ * Additionally, apr_vformatter allows for arbitrary output methods
+ * using the apr_vformatter_buff and flush_func.
+ *
+ * The apr_vformatter_buff has two elements curpos and endpos.
+ * curpos is where apr_vformatter will write the next byte of output.
+ * It proceeds writing output to curpos, and updating curpos, until
+ * either the end of output is reached, or curpos == endpos (i.e. the
+ * buffer is full).
+ *
+ * If the end of output is reached, apr_vformatter returns the
+ * number of bytes written.
+ *
+ * When the buffer is full, the flush_func is called.  The flush_func
+ * can return -1 to indicate that no further output should be attempted,
+ * and apr_vformatter will return immediately with -1.  Otherwise
+ * the flush_func should flush the buffer in whatever manner is
+ * appropriate, re apr_pool_t nitialize curpos and endpos, and return 0.
+ *
+ * Note that flush_func is only invoked as a result of attempting to
+ * write another byte at curpos when curpos >= endpos.  So for
+ * example, it's possible when the output exactly matches the buffer
+ * space available that curpos == endpos will be true when
+ * apr_vformatter returns.
+ *
+ * apr_vformatter does not call out to any other code, it is entirely
+ * self-contained.  This allows the callers to do things which are
+ * otherwise "unsafe".  For example, apr_psprintf uses the "scratch"
+ * space at the unallocated end of a block, and doesn't actually
+ * complete the allocation until apr_vformatter returns.  apr_psprintf
+ * would be completely broken if apr_vformatter were to call anything
+ * that used this same pool.  Similarly http_bprintf() uses the "scratch"
+ * space at the end of its output buffer, and doesn't actually note
+ * that the space is in use until it either has to flush the buffer
+ * or until apr_vformatter returns.
+ * 
+ */ +APR_DECLARE(int) apr_vformatter(int (*flush_func)(apr_vformatter_buff_t *b), + apr_vformatter_buff_t *c, const char *fmt, + va_list ap); + +/** + * Display a prompt and read in the password from stdin. + * @param prompt The prompt to display + * @param pwbuf Buffer to store the password + * @param bufsize The length of the password buffer. + * @remark If the password entered must be truncated to fit in + * the provided buffer, APR_ENAMETOOLONG will be returned. + * Note that the bufsize paramater is passed by reference for no + * reason; its value will never be modified by the apr_password_get() + * function. + */ +APR_DECLARE(apr_status_t) apr_password_get(const char *prompt, char *pwbuf, + apr_size_t *bufsize); + +/** @} */ + +/** + * @defgroup apr_ctype ctype functions + * These macros allow correct support of 8-bit characters on systems which + * support 8-bit characters. Pretty dumb how the cast is required, but + * that's legacy libc for ya. These new macros do not support EOF like + * the standard macros do. Tough. + * @{ + */ +/** @see isalnum */ +#define apr_isalnum(c) (isalnum(((unsigned char)(c)))) +/** @see isalpha */ +#define apr_isalpha(c) (isalpha(((unsigned char)(c)))) +/** @see iscntrl */ +#define apr_iscntrl(c) (iscntrl(((unsigned char)(c)))) +/** @see isdigit */ +#define apr_isdigit(c) (isdigit(((unsigned char)(c)))) +/** @see isgraph */ +#define apr_isgraph(c) (isgraph(((unsigned char)(c)))) +/** @see islower*/ +#define apr_islower(c) (islower(((unsigned char)(c)))) +/** @see isascii */ +#ifdef isascii +#define apr_isascii(c) (isascii(((unsigned char)(c)))) +#else +#define apr_isascii(c) (((c) & ~0x7f)==0) +#endif +/** @see isprint */ +#define apr_isprint(c) (isprint(((unsigned char)(c)))) +/** @see ispunct */ +#define apr_ispunct(c) (ispunct(((unsigned char)(c)))) +/** @see isspace */ +#define apr_isspace(c) (isspace(((unsigned char)(c)))) +/** @see isupper */ +#define apr_isupper(c) (isupper(((unsigned char)(c)))) +/** @see isxdigit */ +#define apr_isxdigit(c) (isxdigit(((unsigned char)(c)))) +/** @see tolower */ +#define apr_tolower(c) (tolower(((unsigned char)(c)))) +/** @see toupper */ +#define apr_toupper(c) (toupper(((unsigned char)(c)))) + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_LIB_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_md4.h b/c/dependencies/windows/apr/x86/include/apr_md4.h new file mode 100644 index 00000000..43fb33e3 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_md4.h @@ -0,0 +1,135 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* This is derived from material copyright RSA Data Security, Inc. + * Their notice is reproduced below in its entirety. + * + * Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All + * rights reserved. + * + * License to copy and use this software is granted provided that it + * is identified as the "RSA Data Security, Inc. MD4 Message-Digest + * Algorithm" in all material mentioning or referencing this software + * or this function. + * + * License is also granted to make and use derivative works provided + * that such works are identified as "derived from the RSA Data + * Security, Inc. MD4 Message-Digest Algorithm" in all material + * mentioning or referencing the derived work. + * + * RSA Data Security, Inc. makes no representations concerning either + * the merchantability of this software or the suitability of this + * software for any particular purpose. It is provided "as is" + * without express or implied warranty of any kind. + * + * These notices must be retained in any copies of any part of this + * documentation and/or software. + */ + +#ifndef APR_MD4_H +#define APR_MD4_H + +#include "apu.h" +#include "apr_xlate.h" +/** + * @file apr_md4.h + * @brief APR-UTIL MD4 Library + */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_MD4 MD4 Library + * @ingroup APR_Util + * @{ + */ + +/** The digestsize for MD4 */ +#define APR_MD4_DIGESTSIZE 16 + +/** @see apr_md4_ctx_t */ +typedef struct apr_md4_ctx_t apr_md4_ctx_t; + +/** MD4 context. */ +struct apr_md4_ctx_t { + /** state (ABCD) */ + apr_uint32_t state[4]; + /** number of bits, modulo 2^64 (lsb first) */ + apr_uint32_t count[2]; + /** input buffer */ + unsigned char buffer[64]; +#if APR_HAS_XLATE + /** translation handle */ + apr_xlate_t *xlate; +#endif +}; + +/** + * MD4 Initialize. Begins an MD4 operation, writing a new context. + * @param context The MD4 context to initialize. + */ +APU_DECLARE(apr_status_t) apr_md4_init(apr_md4_ctx_t *context); + +#if APR_HAS_XLATE +/** + * MDr4 translation setup. Provides the APR translation handle to be used + * for translating the content before calculating the digest. + * @param context The MD4 content to set the translation for. + * @param xlate The translation handle to use for this MD4 context + */ +APU_DECLARE(apr_status_t) apr_md4_set_xlate(apr_md4_ctx_t *context, + apr_xlate_t *xlate); +#else +#define apr_md4_set_xlate(context, xlate) APR_ENOTIMPL +#endif + +/** + * MD4 block update operation. Continue an MD4 message-digest operation, + * processing another message block, and updating the context. + * @param context The MD4 content to update. + * @param input next message block to update + * @param inputLen The length of the next message block + */ +APU_DECLARE(apr_status_t) apr_md4_update(apr_md4_ctx_t *context, + const unsigned char *input, + apr_size_t inputLen); + +/** + * MD4 finalization. Ends an MD4 message-digest operation, writing the + * message digest and zeroing the context + * @param digest The final MD4 digest + * @param context The MD4 content we are finalizing. + */ +APU_DECLARE(apr_status_t) apr_md4_final( + unsigned char digest[APR_MD4_DIGESTSIZE], + apr_md4_ctx_t *context); + +/** + * MD4 digest computation + * @param digest The MD4 digest + * @param input message block to use + * @param inputLen The length of the message block + */ +APU_DECLARE(apr_status_t) apr_md4(unsigned char digest[APR_MD4_DIGESTSIZE], + const unsigned char *input, + apr_size_t inputLen); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_MD4_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_md5.h b/c/dependencies/windows/apr/x86/include/apr_md5.h new file mode 100644 index 00000000..e0202dfd --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_md5.h @@ -0,0 +1,176 @@ +/* + * This is work is derived from material Copyright RSA Data Security, Inc. + * + * The RSA copyright statement and Licence for that original material is + * included below. This is followed by the Apache copyright statement and + * licence for the modifications made to that material. + */ + +/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All + rights reserved. + + License to copy and use this software is granted provided that it + is identified as the "RSA Data Security, Inc. MD5 Message-Digest + Algorithm" in all material mentioning or referencing this software + or this function. + + License is also granted to make and use derivative works provided + that such works are identified as "derived from the RSA Data + Security, Inc. MD5 Message-Digest Algorithm" in all material + mentioning or referencing the derived work. + + RSA Data Security, Inc. makes no representations concerning either + the merchantability of this software or the suitability of this + software for any particular purpose. It is provided "as is" + without express or implied warranty of any kind. + + These notices must be retained in any copies of any part of this + documentation and/or software. + */ + +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_MD5_H +#define APR_MD5_H + +#include "apu.h" +#include "apr_xlate.h" + +#ifdef __cplusplus +extern "C" { +#endif +/** + * @file apr_md5.h + * @brief APR MD5 Routines + */ + +/** + * @defgroup APR_MD5 MD5 Routines + * @ingroup APR + * @{ + */ + +/** The MD5 digest size */ +#define APR_MD5_DIGESTSIZE 16 + +/** @see apr_md5_ctx_t */ +typedef struct apr_md5_ctx_t apr_md5_ctx_t; + +/** MD5 context. */ +struct apr_md5_ctx_t { + /** state (ABCD) */ + apr_uint32_t state[4]; + /** number of bits, modulo 2^64 (lsb first) */ + apr_uint32_t count[2]; + /** input buffer */ + unsigned char buffer[64]; + /** translation handle + * ignored if xlate is unsupported + */ + apr_xlate_t *xlate; +}; + +/** + * MD5 Initialize. Begins an MD5 operation, writing a new context. + * @param context The MD5 context to initialize. + */ +APU_DECLARE(apr_status_t) apr_md5_init(apr_md5_ctx_t *context); + +/** + * MD5 translation setup. Provides the APR translation handle to be used + * for translating the content before calculating the digest. + * @param context The MD5 content to set the translation for. + * @param xlate The translation handle to use for this MD5 context + */ +APU_DECLARE(apr_status_t) apr_md5_set_xlate(apr_md5_ctx_t *context, + apr_xlate_t *xlate); + +/** + * MD5 block update operation. Continue an MD5 message-digest operation, + * processing another message block, and updating the context. + * @param context The MD5 content to update. + * @param input next message block to update + * @param inputLen The length of the next message block + */ +APU_DECLARE(apr_status_t) apr_md5_update(apr_md5_ctx_t *context, + const void *input, + apr_size_t inputLen); + +/** + * MD5 finalization. Ends an MD5 message-digest operation, writing the + * message digest and zeroing the context + * @param digest The final MD5 digest + * @param context The MD5 content we are finalizing. + */ +APU_DECLARE(apr_status_t) apr_md5_final(unsigned char digest[APR_MD5_DIGESTSIZE], + apr_md5_ctx_t *context); + +/** + * MD5 in one step + * @param digest The final MD5 digest + * @param input The message block to use + * @param inputLen The length of the message block + */ +APU_DECLARE(apr_status_t) apr_md5(unsigned char digest[APR_MD5_DIGESTSIZE], + const void *input, + apr_size_t inputLen); + +/** + * Encode a password using an MD5 algorithm + * @param password The password to encode + * @param salt The salt string to use for the encoding + * @param result The string to store the encoded password in + * @param nbytes The size of the result buffer + */ +APU_DECLARE(apr_status_t) apr_md5_encode(const char *password, const char *salt, + char *result, apr_size_t nbytes); + +/** + * Encode a password using the bcrypt algorithm + * @param password The password to encode + * @param count The cost of the encoding, possible values are 4 to 31 + * @param salt Pointer to binary data to be used as salt for the encoding + * @param salt_len The size of the salt data (must be >= 16) + * @param out The string to store the encoded password in + * @param out_len The size of the result buffer (must be >= 61) + */ +APU_DECLARE(apr_status_t) apr_bcrypt_encode(const char *pw, + unsigned int count, + const unsigned char *salt, + apr_size_t salt_len, + char *out, apr_size_t out_len); + +/** + * Validate hashes created by APR-supported algorithms: md5, bcrypt, and sha1. + * hashes created by crypt are supported only on platforms that provide + * crypt(3), so don't rely on that function unless you know that your + * application will be run only on platforms that support it. On platforms + * that don't support crypt(3), this falls back to a clear text string + * comparison. + * @param passwd The password to validate + * @param hash The password to validate against + */ +APU_DECLARE(apr_status_t) apr_password_validate(const char *passwd, + const char *hash); + + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_MD5_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_memcache.h b/c/dependencies/windows/apr/x86/include/apr_memcache.h new file mode 100644 index 00000000..82878825 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_memcache.h @@ -0,0 +1,444 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_MEMCACHE_H +#define APR_MEMCACHE_H + +/** + * @file apr_memcache.h + * @brief Client interface for memcached + * @remark To use this interface you must have a separate memcached + * server running. See the memcached website at http://www.danga.com/memcached/ + * for more information. + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_time.h" +#include "apr_strings.h" +#include "apr_network_io.h" +#include "apr_ring.h" +#include "apr_buckets.h" +#include "apr_reslist.h" +#include "apr_hash.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_Util_MC Memcached Client Routines + * @ingroup APR_Util + * @{ + */ + +/** Specifies the status of a memcached server */ +typedef enum +{ + APR_MC_SERVER_LIVE, /**< Server is alive and responding to requests */ + APR_MC_SERVER_DEAD /**< Server is not responding to requests */ +} apr_memcache_server_status_t; + +/** Opaque memcache client connection object */ +typedef struct apr_memcache_conn_t apr_memcache_conn_t; + +/** Memcache Server Info Object */ +typedef struct apr_memcache_server_t apr_memcache_server_t; +struct apr_memcache_server_t +{ + const char *host; /**< Hostname of this Server */ + apr_port_t port; /**< Port of this Server */ + apr_memcache_server_status_t status; /**< @see apr_memcache_server_status_t */ +#if APR_HAS_THREADS || defined(DOXYGEN) + apr_reslist_t *conns; /**< Resource list of actual client connections */ +#else + apr_memcache_conn_t *conn; +#endif + apr_pool_t *p; /** Pool to use for private allocations */ +#if APR_HAS_THREADS + apr_thread_mutex_t *lock; +#endif + apr_time_t btime; +}; + +/* Custom hash callback function prototype, user for server selection. +* @param baton user selected baton +* @param data data to hash +* @param data_len length of data +*/ +typedef apr_uint32_t (*apr_memcache_hash_func)(void *baton, + const char *data, + const apr_size_t data_len); + +typedef struct apr_memcache_t apr_memcache_t; + +/* Custom Server Select callback function prototype. +* @param baton user selected baton +* @param mc memcache instance, use mc->live_servers to select a node +* @param hash hash of the selected key. +*/ +typedef apr_memcache_server_t* (*apr_memcache_server_func)(void *baton, + apr_memcache_t *mc, + const apr_uint32_t hash); + +/** Container for a set of memcached servers */ +struct apr_memcache_t +{ + apr_uint32_t flags; /**< Flags, Not currently used */ + apr_uint16_t nalloc; /**< Number of Servers Allocated */ + apr_uint16_t ntotal; /**< Number of Servers Added */ + apr_memcache_server_t **live_servers; /**< Array of Servers */ + apr_pool_t *p; /** Pool to use for allocations */ + void *hash_baton; + apr_memcache_hash_func hash_func; + void *server_baton; + apr_memcache_server_func server_func; +}; + +/** Returned Data from a multiple get */ +typedef struct +{ + apr_status_t status; + const char* key; + apr_size_t len; + char *data; + apr_uint16_t flags; +} apr_memcache_value_t; + +/** + * Creates a crc32 hash used to split keys between servers + * @param mc The memcache client object to use + * @param data Data to be hashed + * @param data_len Length of the data to use + * @return crc32 hash of data + * @remark The crc32 hash is not compatible with old memcached clients. + */ +APU_DECLARE(apr_uint32_t) apr_memcache_hash(apr_memcache_t *mc, + const char *data, + const apr_size_t data_len); + +/** + * Pure CRC32 Hash. Used by some clients. + */ +APU_DECLARE(apr_uint32_t) apr_memcache_hash_crc32(void *baton, + const char *data, + const apr_size_t data_len); + +/** + * hash compatible with the standard Perl Client. + */ +APU_DECLARE(apr_uint32_t) apr_memcache_hash_default(void *baton, + const char *data, + const apr_size_t data_len); + +/** + * Picks a server based on a hash + * @param mc The memcache client object to use + * @param hash Hashed value of a Key + * @return server that controls specified hash + * @see apr_memcache_hash + */ +APU_DECLARE(apr_memcache_server_t *) apr_memcache_find_server_hash(apr_memcache_t *mc, + const apr_uint32_t hash); + +/** + * server selection compatible with the standard Perl Client. + */ +APU_DECLARE(apr_memcache_server_t *) apr_memcache_find_server_hash_default(void *baton, + apr_memcache_t *mc, + const apr_uint32_t hash); + +/** + * Adds a server to a client object + * @param mc The memcache client object to use + * @param server Server to add + * @remark Adding servers is not thread safe, and should be done once at startup. + * @warning Changing servers after startup may cause keys to go to + * different servers. + */ +APU_DECLARE(apr_status_t) apr_memcache_add_server(apr_memcache_t *mc, + apr_memcache_server_t *server); + + +/** + * Finds a Server object based on a hostname/port pair + * @param mc The memcache client object to use + * @param host Hostname of the server + * @param port Port of the server + * @return Server with matching Hostname and Port, or NULL if none was found. + */ +APU_DECLARE(apr_memcache_server_t *) apr_memcache_find_server(apr_memcache_t *mc, + const char *host, + apr_port_t port); + +/** + * Enables a Server for use again + * @param mc The memcache client object to use + * @param ms Server to Activate + */ +APU_DECLARE(apr_status_t) apr_memcache_enable_server(apr_memcache_t *mc, + apr_memcache_server_t *ms); + + +/** + * Disable a Server + * @param mc The memcache client object to use + * @param ms Server to Disable + */ +APU_DECLARE(apr_status_t) apr_memcache_disable_server(apr_memcache_t *mc, + apr_memcache_server_t *ms); + +/** + * Creates a new Server Object + * @param p Pool to use + * @param host hostname of the server + * @param port port of the server + * @param min minimum number of client sockets to open + * @param smax soft maximum number of client connections to open + * @param max hard maximum number of client connections + * @param ttl time to live in microseconds of a client connection + * @param ns location of the new server object + * @see apr_reslist_create + * @remark min, smax, and max are only used when APR_HAS_THREADS + */ +APU_DECLARE(apr_status_t) apr_memcache_server_create(apr_pool_t *p, + const char *host, + apr_port_t port, + apr_uint32_t min, + apr_uint32_t smax, + apr_uint32_t max, + apr_uint32_t ttl, + apr_memcache_server_t **ns); +/** + * Creates a new memcached client object + * @param p Pool to use + * @param max_servers maximum number of servers + * @param flags Not currently used + * @param mc location of the new memcache client object + */ +APU_DECLARE(apr_status_t) apr_memcache_create(apr_pool_t *p, + apr_uint16_t max_servers, + apr_uint32_t flags, + apr_memcache_t **mc); + +/** + * Gets a value from the server, allocating the value out of p + * @param mc client to use + * @param p Pool to use + * @param key null terminated string containing the key + * @param baton location of the allocated value + * @param len length of data at baton + * @param flags any flags set by the client for this key + * @return + */ +APU_DECLARE(apr_status_t) apr_memcache_getp(apr_memcache_t *mc, + apr_pool_t *p, + const char* key, + char **baton, + apr_size_t *len, + apr_uint16_t *flags); + + +/** + * Add a key to a hash for a multiget query + * if the hash (*value) is NULL it will be created + * @param data_pool pool from where the hash and their items are created from + * @param key null terminated string containing the key + * @param values hash of keys and values that this key will be added to + * @return + */ +APU_DECLARE(void) apr_memcache_add_multget_key(apr_pool_t *data_pool, + const char* key, + apr_hash_t **values); + +/** + * Gets multiple values from the server, allocating the values out of p + * @param mc client to use + * @param temp_pool Pool used for temporary allocations. May be cleared inside this + * call. + * @param data_pool Pool used to allocate data for the returned values. + * @param values hash of apr_memcache_value_t keyed by strings, contains the + * result of the multiget call. + * @return + */ +APU_DECLARE(apr_status_t) apr_memcache_multgetp(apr_memcache_t *mc, + apr_pool_t *temp_pool, + apr_pool_t *data_pool, + apr_hash_t *values); + +/** + * Sets a value by key on the server + * @param mc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param timeout time in seconds for the data to live on the server + * @param flags any flags set by the client for this key + */ +APU_DECLARE(apr_status_t) apr_memcache_set(apr_memcache_t *mc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint32_t timeout, + apr_uint16_t flags); + +/** + * Adds value by key on the server + * @param mc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param timeout time for the data to live on the server + * @param flags any flags set by the client for this key + * @return APR_SUCCESS if the key was added, APR_EEXIST if the key + * already exists on the server. + */ +APU_DECLARE(apr_status_t) apr_memcache_add(apr_memcache_t *mc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint32_t timeout, + apr_uint16_t flags); + +/** + * Replaces value by key on the server + * @param mc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param timeout time for the data to live on the server + * @param flags any flags set by the client for this key + * @return APR_SUCCESS if the key was added, APR_EEXIST if the key + * did not exist on the server. + */ +APU_DECLARE(apr_status_t) apr_memcache_replace(apr_memcache_t *mc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint32_t timeout, + apr_uint16_t flags); +/** + * Deletes a key from a server + * @param mc client to use + * @param key null terminated string containing the key + * @param timeout time for the delete to stop other clients from adding + */ +APU_DECLARE(apr_status_t) apr_memcache_delete(apr_memcache_t *mc, + const char *key, + apr_uint32_t timeout); + +/** + * Increments a value + * @param mc client to use + * @param key null terminated string containing the key + * @param n number to increment by + * @param nv new value after incrementing + */ +APU_DECLARE(apr_status_t) apr_memcache_incr(apr_memcache_t *mc, + const char *key, + apr_int32_t n, + apr_uint32_t *nv); + +/** + * Decrements a value + * @param mc client to use + * @param key null terminated string containing the key + * @param n number to decrement by + * @param new_value new value after decrementing + */ +APU_DECLARE(apr_status_t) apr_memcache_decr(apr_memcache_t *mc, + const char *key, + apr_int32_t n, + apr_uint32_t *new_value); + +/** + * Query a server's version + * @param ms server to query + * @param p Pool to allocate answer from + * @param baton location to store server version string + * @param len length of the server version string + */ +APU_DECLARE(apr_status_t) apr_memcache_version(apr_memcache_server_t *ms, + apr_pool_t *p, + char **baton); + +typedef struct +{ + /** Version string of this server */ + const char *version; + /** Process id of this server process */ + apr_uint32_t pid; + /** Number of seconds this server has been running */ + apr_uint32_t uptime; + /** current UNIX time according to the server */ + apr_time_t time; + /** The size of a pointer on the current machine */ + apr_uint32_t pointer_size; + /** Accumulated user time for this process */ + apr_time_t rusage_user; + /** Accumulated system time for this process */ + apr_time_t rusage_system; + /** Current number of items stored by the server */ + apr_uint32_t curr_items; + /** Total number of items stored by this server */ + apr_uint32_t total_items; + /** Current number of bytes used by this server to store items */ + apr_uint64_t bytes; + /** Number of open connections */ + apr_uint32_t curr_connections; + /** Total number of connections opened since the server started running */ + apr_uint32_t total_connections; + /** Number of connection structures allocated by the server */ + apr_uint32_t connection_structures; + /** Cumulative number of retrieval requests */ + apr_uint32_t cmd_get; + /** Cumulative number of storage requests */ + apr_uint32_t cmd_set; + /** Number of keys that have been requested and found present */ + apr_uint32_t get_hits; + /** Number of items that have been requested and not found */ + apr_uint32_t get_misses; + /** Number of items removed from cache because they passed their + expiration time */ + apr_uint64_t evictions; + /** Total number of bytes read by this server */ + apr_uint64_t bytes_read; + /** Total number of bytes sent by this server */ + apr_uint64_t bytes_written; + /** Number of bytes this server is allowed to use for storage. */ + apr_uint32_t limit_maxbytes; + /** Number of threads the server is running (if built with threading) */ + apr_uint32_t threads; +} apr_memcache_stats_t; + +/** + * Query a server for statistics + * @param ms server to query + * @param p Pool to allocate answer from + * @param stats location of the new statistics structure + */ +APU_DECLARE(apr_status_t) apr_memcache_stats(apr_memcache_server_t *ms, + apr_pool_t *p, + apr_memcache_stats_t **stats); + + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_MEMCACHE_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_mmap.h b/c/dependencies/windows/apr/x86/include/apr_mmap.h new file mode 100644 index 00000000..c14de192 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_mmap.h @@ -0,0 +1,171 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_MMAP_H +#define APR_MMAP_H + +/** + * @file apr_mmap.h + * @brief APR MMAP routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_ring.h" +#include "apr_file_io.h" /* for apr_file_t */ + +#ifdef BEOS +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_mmap MMAP (Memory Map) Routines + * @ingroup APR + * @{ + */ + +/** MMap opened for reading */ +#define APR_MMAP_READ 1 +/** MMap opened for writing */ +#define APR_MMAP_WRITE 2 + +/** @see apr_mmap_t */ +typedef struct apr_mmap_t apr_mmap_t; + +/** + * @remark + * As far as I can tell the only really sane way to store an MMAP is as a + * void * and a length. BeOS requires this area_id, but that's just a little + * something extra. I am exposing this type, because it doesn't make much + * sense to keep it private, and opening it up makes some stuff easier in + * Apache. + */ +/** The MMAP structure */ +struct apr_mmap_t { + /** The pool the mmap structure was allocated out of. */ + apr_pool_t *cntxt; +#ifdef BEOS + /** An area ID. Only valid on BeOS */ + area_id area; +#endif +#ifdef WIN32 + /** The handle of the file mapping */ + HANDLE mhandle; + /** The start of the real memory page area (mapped view) */ + void *mv; + /** The physical start, size and offset */ + apr_off_t pstart; + apr_size_t psize; + apr_off_t poffset; +#endif + /** The start of the memory mapped area */ + void *mm; + /** The amount of data in the mmap */ + apr_size_t size; + /** ring of apr_mmap_t's that reference the same + * mmap'ed region; acts in place of a reference count */ + APR_RING_ENTRY(apr_mmap_t) link; +}; + +#if APR_HAS_MMAP || defined(DOXYGEN) + +/** @def APR_MMAP_THRESHOLD + * Files have to be at least this big before they're mmap()d. This is to deal + * with systems where the expense of doing an mmap() and an munmap() outweighs + * the benefit for small files. It shouldn't be set lower than 1. + */ +#ifdef MMAP_THRESHOLD +# define APR_MMAP_THRESHOLD MMAP_THRESHOLD +#else +# ifdef SUNOS4 +# define APR_MMAP_THRESHOLD (8*1024) +# else +# define APR_MMAP_THRESHOLD 1 +# endif /* SUNOS4 */ +#endif /* MMAP_THRESHOLD */ + +/** @def APR_MMAP_LIMIT + * Maximum size of MMap region + */ +#ifdef MMAP_LIMIT +# define APR_MMAP_LIMIT MMAP_LIMIT +#else +# define APR_MMAP_LIMIT (4*1024*1024) +#endif /* MMAP_LIMIT */ + +/** Can this file be MMaped */ +#define APR_MMAP_CANDIDATE(filelength) \ + ((filelength >= APR_MMAP_THRESHOLD) && (filelength < APR_MMAP_LIMIT)) + +/* Function definitions */ + +/** + * Create a new mmap'ed file out of an existing APR file. + * @param newmmap The newly created mmap'ed file. + * @param file The file to turn into an mmap. + * @param offset The offset into the file to start the data pointer at. + * @param size The size of the file + * @param flag bit-wise or of: + *
+ *          APR_MMAP_READ       MMap opened for reading
+ *          APR_MMAP_WRITE      MMap opened for writing
+ * 
+ * @param cntxt The pool to use when creating the mmap. + */ +APR_DECLARE(apr_status_t) apr_mmap_create(apr_mmap_t **newmmap, + apr_file_t *file, apr_off_t offset, + apr_size_t size, apr_int32_t flag, + apr_pool_t *cntxt); + +/** + * Duplicate the specified MMAP. + * @param new_mmap The structure to duplicate into. + * @param old_mmap The mmap to duplicate. + * @param p The pool to use for new_mmap. + */ +APR_DECLARE(apr_status_t) apr_mmap_dup(apr_mmap_t **new_mmap, + apr_mmap_t *old_mmap, + apr_pool_t *p); + +/** + * Remove a mmap'ed. + * @param mm The mmap'ed file. + */ +APR_DECLARE(apr_status_t) apr_mmap_delete(apr_mmap_t *mm); + +/** + * Move the pointer into the mmap'ed file to the specified offset. + * @param addr The pointer to the offset specified. + * @param mm The mmap'ed file. + * @param offset The offset to move to. + */ +APR_DECLARE(apr_status_t) apr_mmap_offset(void **addr, apr_mmap_t *mm, + apr_off_t offset); + +#endif /* APR_HAS_MMAP */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_MMAP_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_network_io.h b/c/dependencies/windows/apr/x86/include/apr_network_io.h new file mode 100644 index 00000000..7d6957bc --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_network_io.h @@ -0,0 +1,951 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_NETWORK_IO_H +#define APR_NETWORK_IO_H +/** + * @file apr_network_io.h + * @brief APR Network library + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_file_io.h" +#include "apr_errno.h" +#include "apr_inherit.h" +#include "apr_perms_set.h" + +#if APR_HAVE_NETINET_IN_H +#include +#endif +#if APR_HAVE_SYS_UN_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_network_io Network Routines + * @ingroup APR + * @{ + */ + +#ifndef APR_MAX_SECS_TO_LINGER +/** Maximum seconds to linger */ +#define APR_MAX_SECS_TO_LINGER 30 +#endif + +#ifndef APRMAXHOSTLEN +/** Maximum hostname length */ +#define APRMAXHOSTLEN 256 +#endif + +#ifndef APR_ANYADDR +/** Default 'any' address */ +#define APR_ANYADDR "0.0.0.0" +#endif + +/** + * @defgroup apr_sockopt Socket option definitions + * @{ + */ +#define APR_SO_LINGER 1 /**< Linger */ +#define APR_SO_KEEPALIVE 2 /**< Keepalive */ +#define APR_SO_DEBUG 4 /**< Debug */ +#define APR_SO_NONBLOCK 8 /**< Non-blocking IO */ +#define APR_SO_REUSEADDR 16 /**< Reuse addresses */ +#define APR_SO_SNDBUF 64 /**< Send buffer */ +#define APR_SO_RCVBUF 128 /**< Receive buffer */ +#define APR_SO_DISCONNECTED 256 /**< Disconnected */ +#define APR_TCP_NODELAY 512 /**< For SCTP sockets, this is mapped + * to STCP_NODELAY internally. + */ +#define APR_TCP_NOPUSH 1024 /**< No push */ +#define APR_RESET_NODELAY 2048 /**< This flag is ONLY set internally + * when we set APR_TCP_NOPUSH with + * APR_TCP_NODELAY set to tell us that + * APR_TCP_NODELAY should be turned on + * again when NOPUSH is turned off + */ +#define APR_INCOMPLETE_READ 4096 /**< Set on non-blocking sockets + * (timeout != 0) on which the + * previous read() did not fill a buffer + * completely. the next apr_socket_recv() + * will first call select()/poll() rather than + * going straight into read(). (Can also + * be set by an application to force a + * select()/poll() call before the next + * read, in cases where the app expects + * that an immediate read would fail.) + */ +#define APR_INCOMPLETE_WRITE 8192 /**< like APR_INCOMPLETE_READ, but for write + * @see APR_INCOMPLETE_READ + */ +#define APR_IPV6_V6ONLY 16384 /**< Don't accept IPv4 connections on an + * IPv6 listening socket. + */ +#define APR_TCP_DEFER_ACCEPT 32768 /**< Delay accepting of new connections + * until data is available. + * @see apr_socket_accept_filter + */ +#define APR_SO_BROADCAST 65536 /**< Allow broadcast + */ +#define APR_SO_FREEBIND 131072 /**< Allow binding to addresses not owned + * by any interface + */ + +/** @} */ + +/** Define what type of socket shutdown should occur. */ +typedef enum { + APR_SHUTDOWN_READ, /**< no longer allow read request */ + APR_SHUTDOWN_WRITE, /**< no longer allow write requests */ + APR_SHUTDOWN_READWRITE /**< no longer allow read or write requests */ +} apr_shutdown_how_e; + +#define APR_IPV4_ADDR_OK 0x01 /**< @see apr_sockaddr_info_get() */ +#define APR_IPV6_ADDR_OK 0x02 /**< @see apr_sockaddr_info_get() */ + +#if (!APR_HAVE_IN_ADDR) +/** + * We need to make sure we always have an in_addr type, so APR will just + * define it ourselves, if the platform doesn't provide it. + */ +struct in_addr { + apr_uint32_t s_addr; /**< storage to hold the IP# */ +}; +#endif + +/** @def APR_INADDR_NONE + * Not all platforms have a real INADDR_NONE. This macro replaces + * INADDR_NONE on all platforms. + */ +#ifdef INADDR_NONE +#define APR_INADDR_NONE INADDR_NONE +#else +#define APR_INADDR_NONE ((unsigned int) 0xffffffff) +#endif + +/** + * @def APR_INET + * Not all platforms have these defined, so we'll define them here + * The default values come from FreeBSD 4.1.1 + */ +#define APR_INET AF_INET +/** @def APR_UNSPEC + * Let the system decide which address family to use + */ +#ifdef AF_UNSPEC +#define APR_UNSPEC AF_UNSPEC +#else +#define APR_UNSPEC 0 +#endif +#if APR_HAVE_IPV6 +/** @def APR_INET6 +* IPv6 Address Family. Not all platforms may have this defined. +*/ + +#define APR_INET6 AF_INET6 +#endif + +#if APR_HAVE_SOCKADDR_UN +#if defined (AF_UNIX) +#define APR_UNIX AF_UNIX +#elif defined(AF_LOCAL) +#define APR_UNIX AF_LOCAL +#else +#error "Neither AF_UNIX nor AF_LOCAL is defined" +#endif +#else /* !APR_HAVE_SOCKADDR_UN */ +#if defined (AF_UNIX) +#define APR_UNIX AF_UNIX +#elif defined(AF_LOCAL) +#define APR_UNIX AF_LOCAL +#else +/* TODO: Use a smarter way to detect unique APR_UNIX value */ +#define APR_UNIX 1234 +#endif +#endif + +/** + * @defgroup IP_Proto IP Protocol Definitions for use when creating sockets + * @{ + */ +#define APR_PROTO_TCP 6 /**< TCP */ +#define APR_PROTO_UDP 17 /**< UDP */ +#define APR_PROTO_SCTP 132 /**< SCTP */ +/** @} */ + +/** + * Enum used to denote either the local and remote endpoint of a + * connection. + */ +typedef enum { + APR_LOCAL, /**< Socket information for local end of connection */ + APR_REMOTE /**< Socket information for remote end of connection */ +} apr_interface_e; + +/** + * The specific declaration of inet_addr's ... some platforms fall back + * inet_network (this is not good, but necessary) + */ + +#if APR_HAVE_INET_ADDR +#define apr_inet_addr inet_addr +#elif APR_HAVE_INET_NETWORK /* only DGUX, as far as I know */ +/** + * @warning + * not generally safe... inet_network() and inet_addr() perform + * different functions */ +#define apr_inet_addr inet_network +#endif + +/** A structure to represent sockets */ +typedef struct apr_socket_t apr_socket_t; +/** + * A structure to encapsulate headers and trailers for apr_socket_sendfile + */ +typedef struct apr_hdtr_t apr_hdtr_t; +/** A structure to represent in_addr */ +typedef struct in_addr apr_in_addr_t; +/** A structure to represent an IP subnet */ +typedef struct apr_ipsubnet_t apr_ipsubnet_t; + +/** @remark use apr_uint16_t just in case some system has a short that isn't 16 bits... */ +typedef apr_uint16_t apr_port_t; + +/** @remark It's defined here as I think it should all be platform safe... + * @see apr_sockaddr_t + */ +typedef struct apr_sockaddr_t apr_sockaddr_t; +/** + * APRs socket address type, used to ensure protocol independence + */ +struct apr_sockaddr_t { + /** The pool to use... */ + apr_pool_t *pool; + /** The hostname */ + char *hostname; + /** Either a string of the port number or the service name for the port */ + char *servname; + /** The numeric port */ + apr_port_t port; + /** The family */ + apr_int32_t family; + /** How big is the sockaddr we're using? */ + apr_socklen_t salen; + /** How big is the ip address structure we're using? */ + int ipaddr_len; + /** How big should the address buffer be? 16 for v4 or 46 for v6 + * used in inet_ntop... */ + int addr_str_len; + /** This points to the IP address structure within the appropriate + * sockaddr structure. */ + void *ipaddr_ptr; + /** If multiple addresses were found by apr_sockaddr_info_get(), this + * points to a representation of the next address. */ + apr_sockaddr_t *next; + /** Union of either IPv4 or IPv6 sockaddr. */ + union { + /** IPv4 sockaddr structure */ + struct sockaddr_in sin; +#if APR_HAVE_IPV6 + /** IPv6 sockaddr structure */ + struct sockaddr_in6 sin6; +#endif +#if APR_HAVE_SA_STORAGE + /** Placeholder to ensure that the size of this union is not + * dependent on whether APR_HAVE_IPV6 is defined. */ + struct sockaddr_storage sas; +#endif +#if APR_HAVE_SOCKADDR_UN + /** Unix domain socket sockaddr structure */ + struct sockaddr_un unx; +#endif + } sa; +}; + +#if APR_HAS_SENDFILE +/** + * Support reusing the socket on platforms which support it (from disconnect, + * specifically Win32. + * @remark Optional flag passed into apr_socket_sendfile() + */ +#define APR_SENDFILE_DISCONNECT_SOCKET 1 +#endif + +/** A structure to encapsulate headers and trailers for apr_socket_sendfile */ +struct apr_hdtr_t { + /** An iovec to store the headers sent before the file. */ + struct iovec* headers; + /** number of headers in the iovec */ + int numheaders; + /** An iovec to store the trailers sent after the file. */ + struct iovec* trailers; + /** number of trailers in the iovec */ + int numtrailers; +}; + +/* function definitions */ + +/** + * Create a socket. + * @param new_sock The new socket that has been set up. + * @param family The address family of the socket (e.g., APR_INET). + * @param type The type of the socket (e.g., SOCK_STREAM). + * @param protocol The protocol of the socket (e.g., APR_PROTO_TCP). + * @param cont The pool for the apr_socket_t and associated storage. + * @note The pool will be used by various functions that operate on the + * socket. The caller must ensure that it is not used by other threads + * at the same time. + */ +APR_DECLARE(apr_status_t) apr_socket_create(apr_socket_t **new_sock, + int family, int type, + int protocol, + apr_pool_t *cont); + +/** + * Shutdown either reading, writing, or both sides of a socket. + * @param thesocket The socket to close + * @param how How to shutdown the socket. One of: + *
+ *            APR_SHUTDOWN_READ         no longer allow read requests
+ *            APR_SHUTDOWN_WRITE        no longer allow write requests
+ *            APR_SHUTDOWN_READWRITE    no longer allow read or write requests 
+ * 
+ * @see apr_shutdown_how_e + * @remark This does not actually close the socket descriptor, it just + * controls which calls are still valid on the socket. + */ +APR_DECLARE(apr_status_t) apr_socket_shutdown(apr_socket_t *thesocket, + apr_shutdown_how_e how); + +/** + * Close a socket. + * @param thesocket The socket to close + */ +APR_DECLARE(apr_status_t) apr_socket_close(apr_socket_t *thesocket); + +/** + * Bind the socket to its associated port + * @param sock The socket to bind + * @param sa The socket address to bind to + * @remark This may be where we will find out if there is any other process + * using the selected port. + */ +APR_DECLARE(apr_status_t) apr_socket_bind(apr_socket_t *sock, + apr_sockaddr_t *sa); + +/** + * Listen to a bound socket for connections. + * @param sock The socket to listen on + * @param backlog The number of outstanding connections allowed in the sockets + * listen queue. If this value is less than zero, the listen + * queue size is set to zero. + */ +APR_DECLARE(apr_status_t) apr_socket_listen(apr_socket_t *sock, + apr_int32_t backlog); + +/** + * Accept a new connection request + * @param new_sock A copy of the socket that is connected to the socket that + * made the connection request. This is the socket which should + * be used for all future communication. + * @param sock The socket we are listening on. + * @param connection_pool The pool for the new socket. + * @note The pool will be used by various functions that operate on the + * socket. The caller must ensure that it is not used by other threads + * at the same time. + */ +APR_DECLARE(apr_status_t) apr_socket_accept(apr_socket_t **new_sock, + apr_socket_t *sock, + apr_pool_t *connection_pool); + +/** + * Issue a connection request to a socket either on the same machine + * or a different one. + * @param sock The socket we wish to use for our side of the connection + * @param sa The address of the machine we wish to connect to. + */ +APR_DECLARE(apr_status_t) apr_socket_connect(apr_socket_t *sock, + apr_sockaddr_t *sa); + +/** + * Determine whether the receive part of the socket has been closed by + * the peer (such that a subsequent call to apr_socket_read would + * return APR_EOF), if the socket's receive buffer is empty. This + * function does not block waiting for I/O. + * + * @param sock The socket to check + * @param atreadeof If APR_SUCCESS is returned, *atreadeof is set to + * non-zero if a subsequent read would return APR_EOF + * @return an error is returned if it was not possible to determine the + * status, in which case *atreadeof is not changed. + */ +APR_DECLARE(apr_status_t) apr_socket_atreadeof(apr_socket_t *sock, + int *atreadeof); + +/** + * Create apr_sockaddr_t from hostname, address family, and port. + * @param sa The new apr_sockaddr_t. + * @param hostname The hostname or numeric address string to resolve/parse, or + * NULL to build an address that corresponds to 0.0.0.0 or :: + * or in case of APR_UNIX family it is absolute socket filename. + * @param family The address family to use, or APR_UNSPEC if the system should + * decide. + * @param port The port number. + * @param flags Special processing flags: + *
+ *       APR_IPV4_ADDR_OK          first query for IPv4 addresses; only look
+ *                                 for IPv6 addresses if the first query failed;
+ *                                 only valid if family is APR_UNSPEC and hostname
+ *                                 isn't NULL; mutually exclusive with
+ *                                 APR_IPV6_ADDR_OK
+ *       APR_IPV6_ADDR_OK          first query for IPv6 addresses; only look
+ *                                 for IPv4 addresses if the first query failed;
+ *                                 only valid if family is APR_UNSPEC and hostname
+ *                                 isn't NULL and APR_HAVE_IPV6; mutually exclusive
+ *                                 with APR_IPV4_ADDR_OK
+ * 
+ * @param p The pool for the apr_sockaddr_t and associated storage. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_info_get(apr_sockaddr_t **sa, + const char *hostname, + apr_int32_t family, + apr_port_t port, + apr_int32_t flags, + apr_pool_t *p); + +/** + * Copy apr_sockaddr_t src to dst on pool p. + * @param dst The destination apr_sockaddr_t. + * @param src The source apr_sockaddr_t. + * @param p The pool for the apr_sockaddr_t and associated storage. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_info_copy(apr_sockaddr_t **dst, + const apr_sockaddr_t *src, + apr_pool_t *p); + +/* Set the zone of an IPv6 link-local address object. + * @param sa Socket address object + * @param zone_id Zone ID (textual "eth0" or numeric "3"). + * @return Returns APR_EBADIP for non-IPv6 socket or an IPv6 address + * which isn't link-local. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_zone_set(apr_sockaddr_t *sa, + const char *zone_id); + + +/* Retrieve the zone of an IPv6 link-local address object. + * @param sa Socket address object + * @param name If non-NULL, set to the textual representation of the zone id + * @param id If non-NULL, set to the integer zone id + * @param p Pool from which *name is allocated if used. + * @return Returns APR_EBADIP for non-IPv6 socket or socket without any zone id + * set, or other error if the interface could not be mapped to a name. + * @remark Both name and id may be NULL, neither are modified if + * non-NULL in error cases. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_zone_get(const apr_sockaddr_t *sa, + const char **name, + apr_uint32_t *id, + apr_pool_t *p); + +/** + * Look up the host name from an apr_sockaddr_t. + * @param hostname The hostname. + * @param sa The apr_sockaddr_t. + * @param flags Special processing flags. + * @remark Results can vary significantly between platforms + * when processing wildcard socket addresses. + */ +APR_DECLARE(apr_status_t) apr_getnameinfo(char **hostname, + apr_sockaddr_t *sa, + apr_int32_t flags); + +/** + * Parse hostname/IP address with scope id and port. + * + * Any of the following strings are accepted: + * 8080 (just the port number) + * www.apache.org (just the hostname) + * www.apache.org:8080 (hostname and port number) + * [fe80::1]:80 (IPv6 numeric address string only) + * [fe80::1%eth0] (IPv6 numeric address string and scope id) + * + * Invalid strings: + * (empty string) + * [abc] (not valid IPv6 numeric address string) + * abc:65536 (invalid port number) + * + * @param addr The new buffer containing just the hostname. On output, *addr + * will be NULL if no hostname/IP address was specfied. + * @param scope_id The new buffer containing just the scope id. On output, + * *scope_id will be NULL if no scope id was specified. + * @param port The port number. On output, *port will be 0 if no port was + * specified. + * ### FIXME: 0 is a legal port (per RFC 1700). this should + * ### return something besides zero if the port is missing. + * @param str The input string to be parsed. + * @param p The pool from which *addr and *scope_id are allocated. + * @remark If scope id shouldn't be allowed, check for scope_id != NULL in + * addition to checking the return code. If addr/hostname should be + * required, check for addr == NULL in addition to checking the + * return code. + */ +APR_DECLARE(apr_status_t) apr_parse_addr_port(char **addr, + char **scope_id, + apr_port_t *port, + const char *str, + apr_pool_t *p); + +/** + * Get name of the current machine + * @param buf A buffer to store the hostname in. + * @param len The maximum length of the hostname that can be stored in the + * buffer provided. The suggested length is APRMAXHOSTLEN + 1. + * @param cont The pool to use. + * @remark If the buffer was not large enough, an error will be returned. + */ +APR_DECLARE(apr_status_t) apr_gethostname(char *buf, int len, apr_pool_t *cont); + +/** + * Return the data associated with the current socket + * @param data The user data associated with the socket. + * @param key The key to associate with the user data. + * @param sock The currently open socket. + */ +APR_DECLARE(apr_status_t) apr_socket_data_get(void **data, const char *key, + apr_socket_t *sock); + +/** + * Set the data associated with the current socket. + * @param sock The currently open socket. + * @param data The user data to associate with the socket. + * @param key The key to associate with the data. + * @param cleanup The cleanup to call when the socket is destroyed. + */ +APR_DECLARE(apr_status_t) apr_socket_data_set(apr_socket_t *sock, void *data, + const char *key, + apr_status_t (*cleanup)(void*)); + +/** + * Send data over a network. + * @param sock The socket to send the data over. + * @param buf The buffer which contains the data to be sent. + * @param len On entry, the number of bytes to send; on exit, the number + * of bytes sent. + * @remark + *
+ * This functions acts like a blocking write by default.  To change 
+ * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK
+ * socket option.
+ *
+ * It is possible for both bytes to be sent and an error to be returned.
+ *
+ * APR_EINTR is never returned.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_socket_send(apr_socket_t *sock, const char *buf, + apr_size_t *len); + +/** + * Send multiple buffers over a network. + * @param sock The socket to send the data over. + * @param vec The array of iovec structs containing the data to send + * @param nvec The number of iovec structs in the array + * @param len Receives the number of bytes actually written + * @remark + *
+ * This functions acts like a blocking write by default.  To change 
+ * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK
+ * socket option.
+ * The number of bytes actually sent is stored in argument 4.
+ *
+ * It is possible for both bytes to be sent and an error to be returned.
+ *
+ * APR_EINTR is never returned.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_socket_sendv(apr_socket_t *sock, + const struct iovec *vec, + apr_int32_t nvec, apr_size_t *len); + +/** + * @param sock The socket to send from + * @param where The apr_sockaddr_t describing where to send the data + * @param flags The flags to use + * @param buf The data to send + * @param len The length of the data to send + */ +APR_DECLARE(apr_status_t) apr_socket_sendto(apr_socket_t *sock, + apr_sockaddr_t *where, + apr_int32_t flags, const char *buf, + apr_size_t *len); + +/** + * Read data from a socket. On success, the address of the peer from + * which the data was sent is copied into the @a from parameter, and the + * @a len parameter is updated to give the number of bytes written to + * @a buf. + * + * @param from Updated with the address from which the data was received + * @param sock The socket to use + * @param flags The flags to use + * @param buf The buffer to use + * @param len The length of the available buffer + */ + +APR_DECLARE(apr_status_t) apr_socket_recvfrom(apr_sockaddr_t *from, + apr_socket_t *sock, + apr_int32_t flags, char *buf, + apr_size_t *len); + +#if APR_HAS_SENDFILE || defined(DOXYGEN) + +/** + * Send a file from an open file descriptor to a socket, along with + * optional headers and trailers + * @param sock The socket to which we're writing + * @param file The open file from which to read + * @param hdtr A structure containing the headers and trailers to send + * @param offset Offset into the file where we should begin writing + * @param len (input) - Number of bytes to send from the file + * (output) - Number of bytes actually sent, + * including headers, file, and trailers + * @param flags APR flags that are mapped to OS specific flags + * @remark This functions acts like a blocking write by default. To change + * this behavior, use apr_socket_timeout_set() or the + * APR_SO_NONBLOCK socket option. + * The number of bytes actually sent is stored in the len parameter. + * The offset parameter is passed by reference for no reason; its + * value will never be modified by the apr_socket_sendfile() function. + */ +APR_DECLARE(apr_status_t) apr_socket_sendfile(apr_socket_t *sock, + apr_file_t *file, + apr_hdtr_t *hdtr, + apr_off_t *offset, + apr_size_t *len, + apr_int32_t flags); + +#endif /* APR_HAS_SENDFILE */ + +/** + * Read data from a network. + * @param sock The socket to read the data from. + * @param buf The buffer to store the data in. + * @param len On entry, the number of bytes to receive; on exit, the number + * of bytes received. + * @remark + *
+ * This functions acts like a blocking read by default.  To change 
+ * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK
+ * socket option.
+ * The number of bytes actually received is stored in argument 3.
+ *
+ * It is possible for both bytes to be received and an APR_EOF or
+ * other error to be returned.
+ *
+ * APR_EINTR is never returned.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_socket_recv(apr_socket_t *sock, + char *buf, apr_size_t *len); + +/** + * Setup socket options for the specified socket + * @param sock The socket to set up. + * @param opt The option we would like to configure. One of: + *
+ *            APR_SO_DEBUG      --  turn on debugging information 
+ *            APR_SO_KEEPALIVE  --  keep connections active
+ *            APR_SO_LINGER     --  lingers on close if data is present
+ *            APR_SO_NONBLOCK   --  Turns blocking on/off for socket
+ *                                  When this option is enabled, use
+ *                                  the APR_STATUS_IS_EAGAIN() macro to
+ *                                  see if a send or receive function
+ *                                  could not transfer data without
+ *                                  blocking.
+ *            APR_SO_REUSEADDR  --  The rules used in validating addresses
+ *                                  supplied to bind should allow reuse
+ *                                  of local addresses.
+ *            APR_SO_SNDBUF     --  Set the SendBufferSize
+ *            APR_SO_RCVBUF     --  Set the ReceiveBufferSize
+ *            APR_SO_FREEBIND   --  Allow binding to non-local IP address.
+ * 
+ * @param on Value for the option. + */ +APR_DECLARE(apr_status_t) apr_socket_opt_set(apr_socket_t *sock, + apr_int32_t opt, apr_int32_t on); + +/** + * Setup socket timeout for the specified socket + * @param sock The socket to set up. + * @param t Value for the timeout. + *
+ *   t > 0  -- read and write calls return APR_TIMEUP if specified time
+ *             elapsess with no data read or written
+ *   t == 0 -- read and write calls never block
+ *   t < 0  -- read and write calls block
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_socket_timeout_set(apr_socket_t *sock, + apr_interval_time_t t); + +/** + * Query socket options for the specified socket + * @param sock The socket to query + * @param opt The option we would like to query. One of: + *
+ *            APR_SO_DEBUG      --  turn on debugging information 
+ *            APR_SO_KEEPALIVE  --  keep connections active
+ *            APR_SO_LINGER     --  lingers on close if data is present
+ *            APR_SO_NONBLOCK   --  Turns blocking on/off for socket
+ *            APR_SO_REUSEADDR  --  The rules used in validating addresses
+ *                                  supplied to bind should allow reuse
+ *                                  of local addresses.
+ *            APR_SO_SNDBUF     --  Set the SendBufferSize
+ *            APR_SO_RCVBUF     --  Set the ReceiveBufferSize
+ *            APR_SO_DISCONNECTED -- Query the disconnected state of the socket.
+ *                                  (Currently only used on Windows)
+ * 
+ * @param on Socket option returned on the call. + */ +APR_DECLARE(apr_status_t) apr_socket_opt_get(apr_socket_t *sock, + apr_int32_t opt, apr_int32_t *on); + +/** + * Query socket timeout for the specified socket + * @param sock The socket to query + * @param t Socket timeout returned from the query. + */ +APR_DECLARE(apr_status_t) apr_socket_timeout_get(apr_socket_t *sock, + apr_interval_time_t *t); + +/** + * Query the specified socket if at the OOB/Urgent data mark + * @param sock The socket to query + * @param atmark Is set to true if socket is at the OOB/urgent mark, + * otherwise is set to false. + */ +APR_DECLARE(apr_status_t) apr_socket_atmark(apr_socket_t *sock, + int *atmark); + +/** + * Return an address associated with a socket; either the address to + * which the socket is bound locally or the address of the peer + * to which the socket is connected. + * @param sa The returned apr_sockaddr_t. + * @param which Whether to retrieve the local or remote address + * @param sock The socket to use + */ +APR_DECLARE(apr_status_t) apr_socket_addr_get(apr_sockaddr_t **sa, + apr_interface_e which, + apr_socket_t *sock); + +/** + * Return the IP address (in numeric address string format) in + * an APR socket address. APR will allocate storage for the IP address + * string from the pool of the apr_sockaddr_t. + * @param addr The IP address. + * @param sockaddr The socket address to reference. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_ip_get(char **addr, + apr_sockaddr_t *sockaddr); + +/** + * Write the IP address (in numeric address string format) of the APR + * socket address @a sockaddr into the buffer @a buf (of size @a buflen). + * @param sockaddr The socket address to reference. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_ip_getbuf(char *buf, apr_size_t buflen, + apr_sockaddr_t *sockaddr); + +/** + * See if the IP addresses in two APR socket addresses are + * equivalent. Appropriate logic is present for comparing + * IPv4-mapped IPv6 addresses with IPv4 addresses. + * + * @param addr1 One of the APR socket addresses. + * @param addr2 The other APR socket address. + * @remark The return value will be non-zero if the addresses + * are equivalent. + */ +APR_DECLARE(int) apr_sockaddr_equal(const apr_sockaddr_t *addr1, + const apr_sockaddr_t *addr2); + +/** + * See if the IP address in an APR socket address refers to the wildcard + * address for the protocol family (e.g., INADDR_ANY for IPv4). + * + * @param addr The APR socket address to examine. + * @remark The return value will be non-zero if the address is + * initialized and is the wildcard address. + */ +APR_DECLARE(int) apr_sockaddr_is_wildcard(const apr_sockaddr_t *addr); + +/** +* Return the type of the socket. +* @param sock The socket to query. +* @param type The returned type (e.g., SOCK_STREAM). +*/ +APR_DECLARE(apr_status_t) apr_socket_type_get(apr_socket_t *sock, + int *type); + +/** + * Given an apr_sockaddr_t and a service name, set the port for the service + * @param sockaddr The apr_sockaddr_t that will have its port set + * @param servname The name of the service you wish to use + */ +APR_DECLARE(apr_status_t) apr_getservbyname(apr_sockaddr_t *sockaddr, + const char *servname); +/** + * Build an ip-subnet representation from an IP address and optional netmask or + * number-of-bits. + * @param ipsub The new ip-subnet representation + * @param ipstr The input IP address string + * @param mask_or_numbits The input netmask or number-of-bits string, or NULL + * @param p The pool to allocate from + */ +APR_DECLARE(apr_status_t) apr_ipsubnet_create(apr_ipsubnet_t **ipsub, + const char *ipstr, + const char *mask_or_numbits, + apr_pool_t *p); + +/** + * Test the IP address in an apr_sockaddr_t against a pre-built ip-subnet + * representation. + * @param ipsub The ip-subnet representation + * @param sa The socket address to test + * @return non-zero if the socket address is within the subnet, 0 otherwise + */ +APR_DECLARE(int) apr_ipsubnet_test(apr_ipsubnet_t *ipsub, apr_sockaddr_t *sa); + +#if APR_HAS_SO_ACCEPTFILTER || defined(DOXYGEN) +/** + * Set an OS level accept filter. + * @param sock The socket to put the accept filter on. + * @param name The accept filter + * @param args Any extra args to the accept filter. Passing NULL here removes + * the accept filter. + * @bug name and args should have been declared as const char *, as they are in + * APR 2.0 + */ +apr_status_t apr_socket_accept_filter(apr_socket_t *sock, char *name, + char *args); +#endif + +/** + * Return the protocol of the socket. + * @param sock The socket to query. + * @param protocol The returned protocol (e.g., APR_PROTO_TCP). + */ +APR_DECLARE(apr_status_t) apr_socket_protocol_get(apr_socket_t *sock, + int *protocol); + +/** + * Get the pool used by the socket. + */ +APR_POOL_DECLARE_ACCESSOR(socket); + +/** + * Set a socket to be inherited by child processes. + */ +APR_DECLARE_INHERIT_SET(socket); + +/** + * Unset a socket from being inherited by child processes. + */ +APR_DECLARE_INHERIT_UNSET(socket); + +/** + * Set socket permissions. + */ +APR_PERMS_SET_IMPLEMENT(socket); + +/** + * @defgroup apr_mcast IP Multicast + * @{ + */ + +/** + * Join a Multicast Group + * @param sock The socket to join a multicast group + * @param join The address of the multicast group to join + * @param iface Address of the interface to use. If NULL is passed, the + * default multicast interface will be used. (OS Dependent) + * @param source Source Address to accept transmissions from (non-NULL + * implies Source-Specific Multicast) + */ +APR_DECLARE(apr_status_t) apr_mcast_join(apr_socket_t *sock, + apr_sockaddr_t *join, + apr_sockaddr_t *iface, + apr_sockaddr_t *source); + +/** + * Leave a Multicast Group. All arguments must be the same as + * apr_mcast_join. + * @param sock The socket to leave a multicast group + * @param addr The address of the multicast group to leave + * @param iface Address of the interface to use. If NULL is passed, the + * default multicast interface will be used. (OS Dependent) + * @param source Source Address to accept transmissions from (non-NULL + * implies Source-Specific Multicast) + */ +APR_DECLARE(apr_status_t) apr_mcast_leave(apr_socket_t *sock, + apr_sockaddr_t *addr, + apr_sockaddr_t *iface, + apr_sockaddr_t *source); + +/** + * Set the Multicast Time to Live (ttl) for a multicast transmission. + * @param sock The socket to set the multicast ttl + * @param ttl Time to live to Assign. 0-255, default=1 + * @remark If the TTL is 0, packets will only be seen by sockets on + * the local machine, and only when multicast loopback is enabled. + */ +APR_DECLARE(apr_status_t) apr_mcast_hops(apr_socket_t *sock, + apr_byte_t ttl); + +/** + * Toggle IP Multicast Loopback + * @param sock The socket to set multicast loopback + * @param opt 0=disable, 1=enable + */ +APR_DECLARE(apr_status_t) apr_mcast_loopback(apr_socket_t *sock, + apr_byte_t opt); + + +/** + * Set the Interface to be used for outgoing Multicast Transmissions. + * @param sock The socket to set the multicast interface on + * @param iface Address of the interface to use for Multicast + */ +APR_DECLARE(apr_status_t) apr_mcast_interface(apr_socket_t *sock, + apr_sockaddr_t *iface); + +/** @} */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_NETWORK_IO_H */ + diff --git a/c/dependencies/windows/apr/x86/include/apr_optional.h b/c/dependencies/windows/apr/x86/include/apr_optional.h new file mode 100644 index 00000000..3301d66e --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_optional.h @@ -0,0 +1,92 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_OPTIONAL_H +#define APR_OPTIONAL_H + +#include "apu.h" +/** + * @file apr_optional.h + * @brief APR-UTIL registration of functions exported by modules + */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Opt Optional Functions + * @ingroup APR_Util + * + * Typesafe registration and retrieval of functions that may not be present + * (i.e. functions exported by optional modules) + * @{ + */ + +/** + * The type of an optional function. + * @param name The name of the function + */ +#define APR_OPTIONAL_FN_TYPE(name) apr_OFN_##name##_t + +/** + * Declare an optional function. + * @param ret The return type of the function + * @param name The name of the function + * @param args The function arguments (including brackets) + */ +#define APR_DECLARE_OPTIONAL_FN(ret,name,args) \ +typedef ret (APR_OPTIONAL_FN_TYPE(name)) args + +/** + * XXX: This doesn't belong here, then! + * Private function! DO NOT USE! + * @internal + */ + +typedef void (apr_opt_fn_t)(void); +/** @internal */ +APU_DECLARE_NONSTD(void) apr_dynamic_fn_register(const char *szName, + apr_opt_fn_t *pfn); + +/** + * Register an optional function. This can be later retrieved, type-safely, by + * name. Like all global functions, the name must be unique. Note that, + * confusingly but correctly, the function itself can be static! + * @param name The name of the function + */ +#define APR_REGISTER_OPTIONAL_FN(name) do { \ + APR_OPTIONAL_FN_TYPE(name) *apu__opt = name; \ + apr_dynamic_fn_register(#name,(apr_opt_fn_t *)apu__opt); \ +} while (0) + +/** @internal + * Private function! DO NOT USE! + */ +APU_DECLARE(apr_opt_fn_t *) apr_dynamic_fn_retrieve(const char *szName); + +/** + * Retrieve an optional function. Returns NULL if the function is not present. + * @param name The name of the function + */ +#define APR_RETRIEVE_OPTIONAL_FN(name) \ + (APR_OPTIONAL_FN_TYPE(name) *)apr_dynamic_fn_retrieve(#name) + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_OPTIONAL_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_optional_hooks.h b/c/dependencies/windows/apr/x86/include/apr_optional_hooks.h new file mode 100644 index 00000000..8265f03f --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_optional_hooks.h @@ -0,0 +1,117 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file apr_optional_hooks.h + * @brief Apache optional hook functions + */ + + +#ifndef APR_OPTIONAL_HOOK_H +#define APR_OPTIONAL_HOOK_H + +#include "apr_tables.h" + +#ifdef __cplusplus +extern "C" { +#endif +/** + * @defgroup APR_Util_OPT_HOOK Optional Hook Functions + * @ingroup APR_Util_Hook + * @{ + */ +/** + * Function to implement the APR_OPTIONAL_HOOK Macro + * @internal + * @see APR_OPTIONAL_HOOK + * + * @param szName The name of the hook + * @param pfn A pointer to a function that will be called + * @param aszPre a NULL-terminated array of strings that name modules whose hooks should precede this one + * @param aszSucc a NULL-terminated array of strings that name modules whose hooks should succeed this one + * @param nOrder an integer determining order before honouring aszPre and aszSucc (for example HOOK_MIDDLE) + */ + + +APU_DECLARE(void) apr_optional_hook_add(const char *szName,void (*pfn)(void), + const char * const *aszPre, + const char * const *aszSucc, + int nOrder); + +/** + * Hook to an optional hook. + * + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param pfn A pointer to a function that will be called + * @param aszPre a NULL-terminated array of strings that name modules whose hooks should precede this one + * @param aszSucc a NULL-terminated array of strings that name modules whose hooks should succeed this one + * @param nOrder an integer determining order before honouring aszPre and aszSucc (for example HOOK_MIDDLE) + */ + +#define APR_OPTIONAL_HOOK(ns,name,pfn,aszPre,aszSucc,nOrder) do { \ + ns##_HOOK_##name##_t *apu__hook = pfn; \ + apr_optional_hook_add(#name,(void (*)(void))apu__hook,aszPre, aszSucc, nOrder); \ +} while (0) + +/** + * @internal + * @param szName - the name of the function + * @return the hook structure for a given hook + */ +APU_DECLARE(apr_array_header_t *) apr_optional_hook_get(const char *szName); + +/** + * Implement an optional hook that runs until one of the functions + * returns something other than OK or DECLINE. + * + * @param ns The namespace prefix of the hook functions + * @param link The linkage declaration prefix of the hook + * @param ret The type of the return value of the hook + * @param ret The type of the return value of the hook + * @param name The name of the hook + * @param args_decl The declaration of the arguments for the hook + * @param args_use The names for the arguments for the hook + * @param ok Success value + * @param decline Decline value + */ +#define APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(ns,link,ret,name,args_decl,args_use,ok,decline) \ +link##_DECLARE(ret) ns##_run_##name args_decl \ + { \ + ns##_LINK_##name##_t *pHook; \ + int n; \ + ret rv; \ + apr_array_header_t *pHookArray=apr_optional_hook_get(#name); \ +\ + if(!pHookArray) \ + return ok; \ +\ + pHook=(ns##_LINK_##name##_t *)pHookArray->elts; \ + for(n=0 ; n < pHookArray->nelts ; ++n) \ + { \ + rv=(pHook[n].pFunc)args_use; \ +\ + if(rv != ok && rv != decline) \ + return rv; \ + } \ + return ok; \ + } + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_OPTIONAL_HOOK_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_perms_set.h b/c/dependencies/windows/apr/x86/include/apr_perms_set.h new file mode 100644 index 00000000..92a1362b --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_perms_set.h @@ -0,0 +1,65 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_PERMS_SET_H +#define APR_PERMS_SET_H + +/** + * @file apr_perms_set.h + * @brief APR Process Locking Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_user.h" +#include "apr_file_info.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_perms_set Object permission set functions + * @ingroup APR + * @{ + */ + +/** Permission set callback function. */ +typedef apr_status_t (apr_perms_setfn_t)(void *object, apr_fileperms_t perms, + apr_uid_t uid, apr_gid_t gid); + +#define APR_PERMS_SET_IMPLEMENT(type) \ + APR_DECLARE(apr_status_t) apr_##type##_perms_set \ + (void *the##type, apr_fileperms_t perms, \ + apr_uid_t uid, apr_gid_t gid) + +#define APR_PERMS_SET_ENOTIMPL(type) \ + APR_DECLARE(apr_status_t) apr_##type##_perms_set \ + (void *the##type, apr_fileperms_t perms, \ + apr_uid_t uid, apr_gid_t gid) \ + { return APR_ENOTIMPL ; } + +#define APR_PERMS_SET_FN(type) apr_##type##_perms_set + + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_PERMS_SET */ diff --git a/c/dependencies/windows/apr/x86/include/apr_poll.h b/c/dependencies/windows/apr/x86/include/apr_poll.h new file mode 100644 index 00000000..482d6ee1 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_poll.h @@ -0,0 +1,446 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_POLL_H +#define APR_POLL_H +/** + * @file apr_poll.h + * @brief APR Poll interface + */ +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_inherit.h" +#include "apr_file_io.h" +#include "apr_network_io.h" + +#if APR_HAVE_NETINET_IN_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_poll Poll Routines + * @ingroup APR + * @{ + */ + +/** + * @defgroup pollopts Poll options + * @ingroup apr_poll + * @{ + */ +#define APR_POLLIN 0x001 /**< Can read without blocking */ +#define APR_POLLPRI 0x002 /**< Priority data available */ +#define APR_POLLOUT 0x004 /**< Can write without blocking */ +#define APR_POLLERR 0x010 /**< Pending error */ +#define APR_POLLHUP 0x020 /**< Hangup occurred */ +#define APR_POLLNVAL 0x040 /**< Descriptor invalid */ +/** @} */ + +/** + * @defgroup pollflags Pollset Flags + * @ingroup apr_poll + * @{ + */ +#define APR_POLLSET_THREADSAFE 0x001 /**< Adding or removing a descriptor is + * thread-safe + */ +#define APR_POLLSET_NOCOPY 0x002 /**< Descriptors passed to apr_pollset_add() + * are not copied + */ +#define APR_POLLSET_WAKEABLE 0x004 /**< Poll operations are interruptable by + * apr_pollset_wakeup() or apr_pollcb_wakeup() + */ +#define APR_POLLSET_NODEFAULT 0x010 /**< Do not try to use the default method if + * the specified non-default method cannot be + * used + */ +/** @} */ + +/** + * Pollset Methods + */ +typedef enum { + APR_POLLSET_DEFAULT, /**< Platform default poll method */ + APR_POLLSET_SELECT, /**< Poll uses select method */ + APR_POLLSET_KQUEUE, /**< Poll uses kqueue method */ + APR_POLLSET_PORT, /**< Poll uses Solaris event port method */ + APR_POLLSET_EPOLL, /**< Poll uses epoll method */ + APR_POLLSET_POLL, /**< Poll uses poll method */ + APR_POLLSET_AIO_MSGQ /**< Poll uses z/OS asio method */ +} apr_pollset_method_e; + +/** Used in apr_pollfd_t to determine what the apr_descriptor is */ +typedef enum { + APR_NO_DESC, /**< nothing here */ + APR_POLL_SOCKET, /**< descriptor refers to a socket */ + APR_POLL_FILE, /**< descriptor refers to a file */ + APR_POLL_LASTDESC /**< @deprecated descriptor is the last one in the list */ +} apr_datatype_e ; + +/** Union of either an APR file or socket. */ +typedef union { + apr_file_t *f; /**< file */ + apr_socket_t *s; /**< socket */ +} apr_descriptor; + +/** @see apr_pollfd_t */ +typedef struct apr_pollfd_t apr_pollfd_t; + +/** Poll descriptor set. */ +struct apr_pollfd_t { + apr_pool_t *p; /**< associated pool */ + apr_datatype_e desc_type; /**< descriptor type */ + apr_int16_t reqevents; /**< requested events */ + apr_int16_t rtnevents; /**< returned events */ + apr_descriptor desc; /**< @see apr_descriptor */ + void *client_data; /**< allows app to associate context */ +}; + + +/* General-purpose poll API for arbitrarily large numbers of + * file descriptors + */ + +/** Opaque structure used for pollset API */ +typedef struct apr_pollset_t apr_pollset_t; + +/** + * Set up a pollset object + * @param pollset The pointer in which to return the newly created object + * @param size The maximum number of descriptors that this pollset can hold + * @param p The pool from which to allocate the pollset + * @param flags Optional flags to modify the operation of the pollset. + * + * @remark If flags contains APR_POLLSET_THREADSAFE, then a pollset is + * created on which it is safe to make concurrent calls to + * apr_pollset_add(), apr_pollset_remove() and apr_pollset_poll() + * from separate threads. This feature is only supported on some + * platforms; the apr_pollset_create() call will fail with + * APR_ENOTIMPL on platforms where it is not supported. + * @remark If flags contains APR_POLLSET_WAKEABLE, then a pollset is + * created with an additional internal pipe object used for the + * apr_pollset_wakeup() call. The actual size of pollset is + * in that case @a size + 1. This feature is only supported on some + * platforms; the apr_pollset_create() call will fail with + * APR_ENOTIMPL on platforms where it is not supported. + * @remark If flags contains APR_POLLSET_NOCOPY, then the apr_pollfd_t + * structures passed to apr_pollset_add() are not copied and + * must have a lifetime at least as long as the pollset. + * @remark Some poll methods (including APR_POLLSET_KQUEUE, + * APR_POLLSET_PORT, and APR_POLLSET_EPOLL) do not have a + * fixed limit on the size of the pollset. For these methods, + * the size parameter controls the maximum number of + * descriptors that will be returned by a single call to + * apr_pollset_poll(). + */ +APR_DECLARE(apr_status_t) apr_pollset_create(apr_pollset_t **pollset, + apr_uint32_t size, + apr_pool_t *p, + apr_uint32_t flags); + +/** + * Set up a pollset object + * @param pollset The pointer in which to return the newly created object + * @param size The maximum number of descriptors that this pollset can hold + * @param p The pool from which to allocate the pollset + * @param flags Optional flags to modify the operation of the pollset. + * @param method Poll method to use. See #apr_pollset_method_e. If this + * method cannot be used, the default method will be used unless the + * APR_POLLSET_NODEFAULT flag has been specified. + * + * @remark If flags contains APR_POLLSET_THREADSAFE, then a pollset is + * created on which it is safe to make concurrent calls to + * apr_pollset_add(), apr_pollset_remove() and apr_pollset_poll() + * from separate threads. This feature is only supported on some + * platforms; the apr_pollset_create_ex() call will fail with + * APR_ENOTIMPL on platforms where it is not supported. + * @remark If flags contains APR_POLLSET_WAKEABLE, then a pollset is + * created with additional internal pipe object used for the + * apr_pollset_wakeup() call. The actual size of pollset is + * in that case size + 1. This feature is only supported on some + * platforms; the apr_pollset_create_ex() call will fail with + * APR_ENOTIMPL on platforms where it is not supported. + * @remark If flags contains APR_POLLSET_NOCOPY, then the apr_pollfd_t + * structures passed to apr_pollset_add() are not copied and + * must have a lifetime at least as long as the pollset. + * @remark Some poll methods (including APR_POLLSET_KQUEUE, + * APR_POLLSET_PORT, and APR_POLLSET_EPOLL) do not have a + * fixed limit on the size of the pollset. For these methods, + * the size parameter controls the maximum number of + * descriptors that will be returned by a single call to + * apr_pollset_poll(). + */ +APR_DECLARE(apr_status_t) apr_pollset_create_ex(apr_pollset_t **pollset, + apr_uint32_t size, + apr_pool_t *p, + apr_uint32_t flags, + apr_pollset_method_e method); + +/** + * Destroy a pollset object + * @param pollset The pollset to destroy + */ +APR_DECLARE(apr_status_t) apr_pollset_destroy(apr_pollset_t *pollset); + +/** + * Add a socket or file descriptor to a pollset + * @param pollset The pollset to which to add the descriptor + * @param descriptor The descriptor to add + * @remark If you set client_data in the descriptor, that value + * will be returned in the client_data field whenever this + * descriptor is signalled in apr_pollset_poll(). + * @remark If the pollset has been created with APR_POLLSET_THREADSAFE + * and thread T1 is blocked in a call to apr_pollset_poll() for + * this same pollset that is being modified via apr_pollset_add() + * in thread T2, the currently executing apr_pollset_poll() call in + * T1 will either: (1) automatically include the newly added descriptor + * in the set of descriptors it is watching or (2) return immediately + * with APR_EINTR. Option (1) is recommended, but option (2) is + * allowed for implementations where option (1) is impossible + * or impractical. + * @remark If the pollset has been created with APR_POLLSET_NOCOPY, the + * apr_pollfd_t structure referenced by descriptor will not be copied + * and must have a lifetime at least as long as the pollset. + * @remark Do not add the same socket or file descriptor to the same pollset + * multiple times, even if the requested events differ for the + * different calls to apr_pollset_add(). If the events of interest + * for a descriptor change, you must first remove the descriptor + * from the pollset with apr_pollset_remove(), then add it again + * specifying all requested events. + */ +APR_DECLARE(apr_status_t) apr_pollset_add(apr_pollset_t *pollset, + const apr_pollfd_t *descriptor); + +/** + * Remove a descriptor from a pollset + * @param pollset The pollset from which to remove the descriptor + * @param descriptor The descriptor to remove + * @remark If the descriptor is not found, APR_NOTFOUND is returned. + * @remark If the pollset has been created with APR_POLLSET_THREADSAFE + * and thread T1 is blocked in a call to apr_pollset_poll() for + * this same pollset that is being modified via apr_pollset_remove() + * in thread T2, the currently executing apr_pollset_poll() call in + * T1 will either: (1) automatically exclude the newly added descriptor + * in the set of descriptors it is watching or (2) return immediately + * with APR_EINTR. Option (1) is recommended, but option (2) is + * allowed for implementations where option (1) is impossible + * or impractical. + * @remark apr_pollset_remove() cannot be used to remove a subset of requested + * events for a descriptor. The reqevents field in the apr_pollfd_t + * parameter must contain the same value when removing as when adding. + */ +APR_DECLARE(apr_status_t) apr_pollset_remove(apr_pollset_t *pollset, + const apr_pollfd_t *descriptor); + +/** + * Block for activity on the descriptor(s) in a pollset + * @param pollset The pollset to use + * @param timeout The amount of time in microseconds to wait. This is a + * maximum, not a minimum. If a descriptor is signalled, the + * function will return before this time. If timeout is + * negative, the function will block until a descriptor is + * signalled or until apr_pollset_wakeup() has been called. + * @param num Number of signalled descriptors (output parameter) + * @param descriptors Array of signalled descriptors (output parameter) + * @remark APR_EINTR will be returned if the pollset has been created with + * APR_POLLSET_WAKEABLE, apr_pollset_wakeup() has been called while + * waiting for activity, and there were no signalled descriptors at the + * time of the wakeup call. + * @remark Multiple signalled conditions for the same descriptor may be reported + * in one or more returned apr_pollfd_t structures, depending on the + * implementation. + */ +APR_DECLARE(apr_status_t) apr_pollset_poll(apr_pollset_t *pollset, + apr_interval_time_t timeout, + apr_int32_t *num, + const apr_pollfd_t **descriptors); + +/** + * Interrupt the blocked apr_pollset_poll() call. + * @param pollset The pollset to use + * @remark If the pollset was not created with APR_POLLSET_WAKEABLE the + * return value is APR_EINIT. + */ +APR_DECLARE(apr_status_t) apr_pollset_wakeup(apr_pollset_t *pollset); + +/** + * Poll the descriptors in the poll structure + * @param aprset The poll structure we will be using. + * @param numsock The number of descriptors we are polling + * @param nsds The number of descriptors signalled (output parameter) + * @param timeout The amount of time in microseconds to wait. This is a + * maximum, not a minimum. If a descriptor is signalled, the + * function will return before this time. If timeout is + * negative, the function will block until a descriptor is + * signalled or until apr_pollset_wakeup() has been called. + * @remark The number of descriptors signalled is returned in the third argument. + * This is a blocking call, and it will not return until either a + * descriptor has been signalled or the timeout has expired. + * @remark The rtnevents field in the apr_pollfd_t array will only be filled- + * in if the return value is APR_SUCCESS. + */ +APR_DECLARE(apr_status_t) apr_poll(apr_pollfd_t *aprset, apr_int32_t numsock, + apr_int32_t *nsds, + apr_interval_time_t timeout); + +/** + * Return a printable representation of the pollset method. + * @param pollset The pollset to use + */ +APR_DECLARE(const char *) apr_pollset_method_name(apr_pollset_t *pollset); + +/** + * Return a printable representation of the default pollset method + * (APR_POLLSET_DEFAULT). + */ +APR_DECLARE(const char *) apr_poll_method_defname(void); + +/** Opaque structure used for pollcb API */ +typedef struct apr_pollcb_t apr_pollcb_t; + +/** + * Set up a pollcb object + * @param pollcb The pointer in which to return the newly created object + * @param size The maximum number of descriptors that a single _poll can return. + * @param p The pool from which to allocate the pollcb + * @param flags Optional flags to modify the operation of the pollcb. + * + * @remark If flags contains APR_POLLSET_WAKEABLE, then a pollcb is + * created with an additional internal pipe object used for the + * apr_pollcb_wakeup() call. The actual size of pollcb is + * in that case @a size + 1. + * @remark Pollcb is only supported on some platforms; the apr_pollcb_create() + * call will fail with APR_ENOTIMPL on platforms where it is not supported. + */ +APR_DECLARE(apr_status_t) apr_pollcb_create(apr_pollcb_t **pollcb, + apr_uint32_t size, + apr_pool_t *p, + apr_uint32_t flags); + +/** + * Set up a pollcb object + * @param pollcb The pointer in which to return the newly created object + * @param size The maximum number of descriptors that a single _poll can return. + * @param p The pool from which to allocate the pollcb + * @param flags Optional flags to modify the operation of the pollcb. + * @param method Poll method to use. See #apr_pollset_method_e. If this + * method cannot be used, the default method will be used unless the + * APR_POLLSET_NODEFAULT flag has been specified. + * + * @remark If flags contains APR_POLLSET_WAKEABLE, then a pollcb is + * created with an additional internal pipe object used for the + * apr_pollcb_wakeup() call. The actual size of pollcb is + * in that case @a size + 1. + * @remark Pollcb is only supported on some platforms; the apr_pollcb_create_ex() + * call will fail with APR_ENOTIMPL on platforms where it is not supported. + */ +APR_DECLARE(apr_status_t) apr_pollcb_create_ex(apr_pollcb_t **pollcb, + apr_uint32_t size, + apr_pool_t *p, + apr_uint32_t flags, + apr_pollset_method_e method); + +/** + * Add a socket or file descriptor to a pollcb + * @param pollcb The pollcb to which to add the descriptor + * @param descriptor The descriptor to add + * @remark If you set client_data in the descriptor, that value will be + * returned in the client_data field whenever this descriptor is + * signalled in apr_pollcb_poll(). + * @remark Unlike the apr_pollset API, the descriptor is not copied, and users + * must retain the memory used by descriptor, as the same pointer will + * be returned to them from apr_pollcb_poll. + * @remark Do not add the same socket or file descriptor to the same pollcb + * multiple times, even if the requested events differ for the + * different calls to apr_pollcb_add(). If the events of interest + * for a descriptor change, you must first remove the descriptor + * from the pollcb with apr_pollcb_remove(), then add it again + * specifying all requested events. + */ +APR_DECLARE(apr_status_t) apr_pollcb_add(apr_pollcb_t *pollcb, + apr_pollfd_t *descriptor); +/** + * Remove a descriptor from a pollcb + * @param pollcb The pollcb from which to remove the descriptor + * @param descriptor The descriptor to remove + * @remark If the descriptor is not found, APR_NOTFOUND is returned. + * @remark apr_pollcb_remove() cannot be used to remove a subset of requested + * events for a descriptor. The reqevents field in the apr_pollfd_t + * parameter must contain the same value when removing as when adding. + */ +APR_DECLARE(apr_status_t) apr_pollcb_remove(apr_pollcb_t *pollcb, + apr_pollfd_t *descriptor); + +/** + * Function prototype for pollcb handlers + * @param baton Opaque baton passed into apr_pollcb_poll() + * @param descriptor Contains the notification for an active descriptor. + * The @a rtnevents member describes which events were triggered + * for this descriptor. + * @remark If the pollcb handler does not return APR_SUCCESS, the apr_pollcb_poll() + * call returns with the handler's return value. + */ +typedef apr_status_t (*apr_pollcb_cb_t)(void *baton, apr_pollfd_t *descriptor); + +/** + * Block for activity on the descriptor(s) in a pollcb + * @param pollcb The pollcb to use + * @param timeout The amount of time in microseconds to wait. This is a + * maximum, not a minimum. If a descriptor is signalled, the + * function will return before this time. If timeout is + * negative, the function will block until a descriptor is + * signalled or until apr_pollcb_wakeup() has been called. + * @param func Callback function to call for each active descriptor. + * @param baton Opaque baton passed to the callback function. + * @remark Multiple signalled conditions for the same descriptor may be reported + * in one or more calls to the callback function, depending on the + * implementation. + * @remark APR_EINTR will be returned if the pollset has been created with + * APR_POLLSET_WAKEABLE and apr_pollcb_wakeup() has been called while + * waiting for activity. + */ +APR_DECLARE(apr_status_t) apr_pollcb_poll(apr_pollcb_t *pollcb, + apr_interval_time_t timeout, + apr_pollcb_cb_t func, + void *baton); + +/** + * Interrupt the blocked apr_pollcb_poll() call. + * @param pollcb The pollcb to use + * @remark If the pollcb was not created with APR_POLLSET_WAKEABLE the + * return value is APR_EINIT. + */ +APR_DECLARE(apr_status_t) apr_pollcb_wakeup(apr_pollcb_t *pollcb); + +/** + * Return a printable representation of the pollcb method. + * @param pollcb The pollcb to use + */ +APR_DECLARE(const char *) apr_pollcb_method_name(apr_pollcb_t *pollcb); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_POLL_H */ + diff --git a/c/dependencies/windows/apr/x86/include/apr_pools.h b/c/dependencies/windows/apr/x86/include/apr_pools.h new file mode 100644 index 00000000..783c9c42 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_pools.h @@ -0,0 +1,815 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_POOLS_H +#define APR_POOLS_H + +/** + * @file apr_pools.h + * @brief APR memory allocation + * + * Resource allocation routines... + * + * designed so that we don't have to keep track of EVERYTHING so that + * it can be explicitly freed later (a fundamentally unsound strategy --- + * particularly in the presence of die()). + * + * Instead, we maintain pools, and allocate items (both memory and I/O + * handlers) from the pools --- currently there are two, one for + * per-transaction info, and one for config info. When a transaction is + * over, we can delete everything in the per-transaction apr_pool_t without + * fear, and without thinking too hard about it either. + * + * Note that most operations on pools are not thread-safe: a single pool + * should only be accessed by a single thread at any given time. The one + * exception to this rule is creating a subpool of a given pool: one or more + * threads can safely create subpools at the same time that another thread + * accesses the parent pool. + */ + +#include "apr.h" +#include "apr_errno.h" +#include "apr_general.h" /* for APR_STRINGIFY */ +#define APR_WANT_MEMFUNC /**< for no good reason? */ +#include "apr_want.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_pools Memory Pool Functions + * @ingroup APR + * @{ + */ + +/** The fundamental pool type */ +typedef struct apr_pool_t apr_pool_t; + + +/** + * Declaration helper macro to construct apr_foo_pool_get()s. + * + * This standardized macro is used by opaque (APR) data types to return + * the apr_pool_t that is associated with the data type. + * + * APR_POOL_DECLARE_ACCESSOR() is used in a header file to declare the + * accessor function. A typical usage and result would be: + *
+ *    APR_POOL_DECLARE_ACCESSOR(file);
+ * becomes:
+ *    APR_DECLARE(apr_pool_t *) apr_file_pool_get(const apr_file_t *thefile);
+ * 
+ * @remark Doxygen unwraps this macro (via doxygen.conf) to provide + * actual help for each specific occurrence of apr_foo_pool_get. + * @remark the linkage is specified for APR. It would be possible to expand + * the macros to support other linkages. + */ +#define APR_POOL_DECLARE_ACCESSOR(type) \ + APR_DECLARE(apr_pool_t *) apr_##type##_pool_get \ + (const apr_##type##_t *the##type) + +/** + * Implementation helper macro to provide apr_foo_pool_get()s. + * + * In the implementation, the APR_POOL_IMPLEMENT_ACCESSOR() is used to + * actually define the function. It assumes the field is named "pool". + */ +#define APR_POOL_IMPLEMENT_ACCESSOR(type) \ + APR_DECLARE(apr_pool_t *) apr_##type##_pool_get \ + (const apr_##type##_t *the##type) \ + { return the##type->pool; } + + +/** + * Pool debug levels + * + *
+ * | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
+ * ---------------------------------
+ * |   |   |   |   |   |   |   | x |  General debug code enabled (useful in
+ *                                    combination with --with-efence).
+ *
+ * |   |   |   |   |   |   | x |   |  Verbose output on stderr (report
+ *                                    CREATE, CLEAR, DESTROY).
+ *
+ * |   |   |   | x |   |   |   |   |  Verbose output on stderr (report
+ *                                    PALLOC, PCALLOC).
+ *
+ * |   |   |   |   |   | x |   |   |  Lifetime checking. On each use of a
+ *                                    pool, check its lifetime.  If the pool
+ *                                    is out of scope, abort().
+ *                                    In combination with the verbose flag
+ *                                    above, it will output LIFE in such an
+ *                                    event prior to aborting.
+ *
+ * |   |   |   |   | x |   |   |   |  Pool owner checking.  On each use of a
+ *                                    pool, check if the current thread is the
+ *                                    pool's owner.  If not, abort().  In
+ *                                    combination with the verbose flag above,
+ *                                    it will output OWNER in such an event
+ *                                    prior to aborting.  Use the debug
+ *                                    function apr_pool_owner_set() to switch
+ *                                    a pool's ownership.
+ *
+ * When no debug level was specified, assume general debug mode.
+ * If level 0 was specified, debugging is switched off.
+ * 
+ */ +#if defined(APR_POOL_DEBUG) +/* If APR_POOL_DEBUG is blank, we get 1; if it is a number, we get -1. */ +#if (APR_POOL_DEBUG - APR_POOL_DEBUG -1 == 1) +#undef APR_POOL_DEBUG +#define APR_POOL_DEBUG 1 +#endif +#else +#define APR_POOL_DEBUG 0 +#endif + +/** the place in the code where the particular function was called */ +#define APR_POOL__FILE_LINE__ __FILE__ ":" APR_STRINGIFY(__LINE__) + + + +/** A function that is called when allocation fails. */ +typedef int (*apr_abortfunc_t)(int retcode); + +/* + * APR memory structure manipulators (pools, tables, and arrays). + */ + +/* + * Initialization + */ + +/** + * Setup all of the internal structures required to use pools + * @remark Programs do NOT need to call this directly. APR will call this + * automatically from apr_initialize. + * @internal + */ +APR_DECLARE(apr_status_t) apr_pool_initialize(void); + +/** + * Tear down all of the internal structures required to use pools + * @remark Programs do NOT need to call this directly. APR will call this + * automatically from apr_terminate. + * @internal + */ +APR_DECLARE(void) apr_pool_terminate(void); + + +/* + * Pool creation/destruction + */ + +#include "apr_allocator.h" + +/** + * Create a new pool. + * @param newpool The pool we have just created. + * @param parent The parent pool. If this is NULL, the new pool is a root + * pool. If it is non-NULL, the new pool will inherit all + * of its parent pool's attributes, except the apr_pool_t will + * be a sub-pool. + * @param abort_fn A function to use if the pool cannot allocate more memory. + * @param allocator The allocator to use with the new pool. If NULL the + * allocator of the parent pool will be used. + * @remark This function is thread-safe, in the sense that multiple threads + * can safely create subpools of the same parent pool concurrently. + * Similarly, a subpool can be created by one thread at the same + * time that another thread accesses the parent pool. + */ +APR_DECLARE(apr_status_t) apr_pool_create_ex(apr_pool_t **newpool, + apr_pool_t *parent, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +/** + * Create a new pool. + * @deprecated @see apr_pool_create_unmanaged_ex. + */ +APR_DECLARE(apr_status_t) apr_pool_create_core_ex(apr_pool_t **newpool, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator); + +/** + * Create a new unmanaged pool. + * @param newpool The pool we have just created. + * @param abort_fn A function to use if the pool cannot allocate more memory. + * @param allocator The allocator to use with the new pool. If NULL a + * new allocator will be created with the new pool as owner. + * @remark An unmanaged pool is a special pool without a parent; it will + * NOT be destroyed upon apr_terminate. It must be explicitly + * destroyed by calling apr_pool_destroy, to prevent memory leaks. + * Use of this function is discouraged, think twice about whether + * you really really need it. + * @warning Any child cleanups registered against the new pool, or + * against sub-pools thereof, will not be executed during an + * invocation of apr_proc_create(), so resources created in an + * "unmanaged" pool hierarchy will leak to child processes. + */ +APR_DECLARE(apr_status_t) apr_pool_create_unmanaged_ex(apr_pool_t **newpool, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +/** + * Debug version of apr_pool_create_ex. + * @param newpool @see apr_pool_create. + * @param parent @see apr_pool_create. + * @param abort_fn @see apr_pool_create. + * @param allocator @see apr_pool_create. + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @remark Only available when APR_POOL_DEBUG is defined. + * Call this directly if you have your apr_pool_create_ex + * calls in a wrapper function and wish to override + * the file_line argument to reflect the caller of + * your wrapper function. If you do not have + * apr_pool_create_ex in a wrapper, trust the macro + * and don't call apr_pool_create_ex_debug directly. + */ +APR_DECLARE(apr_status_t) apr_pool_create_ex_debug(apr_pool_t **newpool, + apr_pool_t *parent, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pool_create_ex(newpool, parent, abort_fn, allocator) \ + apr_pool_create_ex_debug(newpool, parent, abort_fn, allocator, \ + APR_POOL__FILE_LINE__) +#endif + +/** + * Debug version of apr_pool_create_core_ex. + * @deprecated @see apr_pool_create_unmanaged_ex_debug. + */ +APR_DECLARE(apr_status_t) apr_pool_create_core_ex_debug(apr_pool_t **newpool, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator, + const char *file_line); + +/** + * Debug version of apr_pool_create_unmanaged_ex. + * @param newpool @see apr_pool_create_unmanaged. + * @param abort_fn @see apr_pool_create_unmanaged. + * @param allocator @see apr_pool_create_unmanaged. + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @remark Only available when APR_POOL_DEBUG is defined. + * Call this directly if you have your apr_pool_create_unmanaged_ex + * calls in a wrapper function and wish to override + * the file_line argument to reflect the caller of + * your wrapper function. If you do not have + * apr_pool_create_core_ex in a wrapper, trust the macro + * and don't call apr_pool_create_core_ex_debug directly. + */ +APR_DECLARE(apr_status_t) apr_pool_create_unmanaged_ex_debug(apr_pool_t **newpool, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pool_create_core_ex(newpool, abort_fn, allocator) \ + apr_pool_create_unmanaged_ex_debug(newpool, abort_fn, allocator, \ + APR_POOL__FILE_LINE__) + +#define apr_pool_create_unmanaged_ex(newpool, abort_fn, allocator) \ + apr_pool_create_unmanaged_ex_debug(newpool, abort_fn, allocator, \ + APR_POOL__FILE_LINE__) + +#endif + +/** + * Create a new pool. + * @param newpool The pool we have just created. + * @param parent The parent pool. If this is NULL, the new pool is a root + * pool. If it is non-NULL, the new pool will inherit all + * of its parent pool's attributes, except the apr_pool_t will + * be a sub-pool. + * @remark This function is thread-safe, in the sense that multiple threads + * can safely create subpools of the same parent pool concurrently. + * Similarly, a subpool can be created by one thread at the same + * time that another thread accesses the parent pool. + */ +#if defined(DOXYGEN) +APR_DECLARE(apr_status_t) apr_pool_create(apr_pool_t **newpool, + apr_pool_t *parent); +#else +#if APR_POOL_DEBUG +#define apr_pool_create(newpool, parent) \ + apr_pool_create_ex_debug(newpool, parent, NULL, NULL, \ + APR_POOL__FILE_LINE__) +#else +#define apr_pool_create(newpool, parent) \ + apr_pool_create_ex(newpool, parent, NULL, NULL) +#endif +#endif + +/** + * Create a new unmanaged pool. + * @param newpool The pool we have just created. + */ +#if defined(DOXYGEN) +APR_DECLARE(apr_status_t) apr_pool_create_core(apr_pool_t **newpool); +APR_DECLARE(apr_status_t) apr_pool_create_unmanaged(apr_pool_t **newpool); +#else +#if APR_POOL_DEBUG +#define apr_pool_create_core(newpool) \ + apr_pool_create_unmanaged_ex_debug(newpool, NULL, NULL, \ + APR_POOL__FILE_LINE__) +#define apr_pool_create_unmanaged(newpool) \ + apr_pool_create_unmanaged_ex_debug(newpool, NULL, NULL, \ + APR_POOL__FILE_LINE__) +#else +#define apr_pool_create_core(newpool) \ + apr_pool_create_unmanaged_ex(newpool, NULL, NULL) +#define apr_pool_create_unmanaged(newpool) \ + apr_pool_create_unmanaged_ex(newpool, NULL, NULL) +#endif +#endif + +/** + * Find the pool's allocator + * @param pool The pool to get the allocator from. + */ +APR_DECLARE(apr_allocator_t *) apr_pool_allocator_get(apr_pool_t *pool) + __attribute__((nonnull(1))); + +/** + * Clear all memory in the pool and run all the cleanups. This also destroys all + * subpools. + * @param p The pool to clear + * @remark This does not actually free the memory, it just allows the pool + * to re-use this memory for the next allocation. + * @see apr_pool_destroy() + */ +APR_DECLARE(void) apr_pool_clear(apr_pool_t *p) __attribute__((nonnull(1))); + +/** + * Debug version of apr_pool_clear. + * @param p See: apr_pool_clear. + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @remark Only available when APR_POOL_DEBUG is defined. + * Call this directly if you have your apr_pool_clear + * calls in a wrapper function and wish to override + * the file_line argument to reflect the caller of + * your wrapper function. If you do not have + * apr_pool_clear in a wrapper, trust the macro + * and don't call apr_pool_destroy_clear directly. + */ +APR_DECLARE(void) apr_pool_clear_debug(apr_pool_t *p, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pool_clear(p) \ + apr_pool_clear_debug(p, APR_POOL__FILE_LINE__) +#endif + +/** + * Destroy the pool. This takes similar action as apr_pool_clear() and then + * frees all the memory. + * @param p The pool to destroy + * @remark This will actually free the memory + */ +APR_DECLARE(void) apr_pool_destroy(apr_pool_t *p) __attribute__((nonnull(1))); + +/** + * Debug version of apr_pool_destroy. + * @param p See: apr_pool_destroy. + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @remark Only available when APR_POOL_DEBUG is defined. + * Call this directly if you have your apr_pool_destroy + * calls in a wrapper function and wish to override + * the file_line argument to reflect the caller of + * your wrapper function. If you do not have + * apr_pool_destroy in a wrapper, trust the macro + * and don't call apr_pool_destroy_debug directly. + */ +APR_DECLARE(void) apr_pool_destroy_debug(apr_pool_t *p, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pool_destroy(p) \ + apr_pool_destroy_debug(p, APR_POOL__FILE_LINE__) +#endif + + +/* + * Memory allocation + */ + +/** + * Allocate a block of memory from a pool + * @param p The pool to allocate from + * @param size The amount of memory to allocate + * @return The allocated memory + */ +APR_DECLARE(void *) apr_palloc(apr_pool_t *p, apr_size_t size) +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) + __attribute__((alloc_size(2))) +#endif + __attribute__((nonnull(1))); + +/** + * Debug version of apr_palloc + * @param p See: apr_palloc + * @param size See: apr_palloc + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @return See: apr_palloc + */ +APR_DECLARE(void *) apr_palloc_debug(apr_pool_t *p, apr_size_t size, + const char *file_line) +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) + __attribute__((alloc_size(2))) +#endif + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_palloc(p, size) \ + apr_palloc_debug(p, size, APR_POOL__FILE_LINE__) +#endif + +/** + * Allocate a block of memory from a pool and set all of the memory to 0 + * @param p The pool to allocate from + * @param size The amount of memory to allocate + * @return The allocated memory + */ +#if defined(DOXYGEN) +APR_DECLARE(void *) apr_pcalloc(apr_pool_t *p, apr_size_t size); +#elif !APR_POOL_DEBUG +#define apr_pcalloc(p, size) memset(apr_palloc(p, size), 0, size) +#endif + +/** + * Debug version of apr_pcalloc + * @param p See: apr_pcalloc + * @param size See: apr_pcalloc + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @return See: apr_pcalloc + */ +APR_DECLARE(void *) apr_pcalloc_debug(apr_pool_t *p, apr_size_t size, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pcalloc(p, size) \ + apr_pcalloc_debug(p, size, APR_POOL__FILE_LINE__) +#endif + + +/* + * Pool Properties + */ + +/** + * Set the function to be called when an allocation failure occurs. + * @remark If the program wants APR to exit on a memory allocation error, + * then this function can be called to set the callback to use (for + * performing cleanup and then exiting). If this function is not called, + * then APR will return an error and expect the calling program to + * deal with the error accordingly. + */ +APR_DECLARE(void) apr_pool_abort_set(apr_abortfunc_t abortfunc, + apr_pool_t *pool) + __attribute__((nonnull(2))); + +/** + * Get the abort function associated with the specified pool. + * @param pool The pool for retrieving the abort function. + * @return The abort function for the given pool. + */ +APR_DECLARE(apr_abortfunc_t) apr_pool_abort_get(apr_pool_t *pool) + __attribute__((nonnull(1))); + +/** + * Get the parent pool of the specified pool. + * @param pool The pool for retrieving the parent pool. + * @return The parent of the given pool. + */ +APR_DECLARE(apr_pool_t *) apr_pool_parent_get(apr_pool_t *pool) + __attribute__((nonnull(1))); + +/** + * Determine if pool a is an ancestor of pool b. + * @param a The pool to search + * @param b The pool to search for + * @return True if a is an ancestor of b, NULL is considered an ancestor + * of all pools. + * @remark if compiled with APR_POOL_DEBUG, this function will also + * return true if A is a pool which has been guaranteed by the caller + * (using apr_pool_join) to have a lifetime at least as long as some + * ancestor of pool B. + */ +APR_DECLARE(int) apr_pool_is_ancestor(apr_pool_t *a, apr_pool_t *b); + +/** + * Tag a pool (give it a name) + * @param pool The pool to tag + * @param tag The tag + */ +APR_DECLARE(void) apr_pool_tag(apr_pool_t *pool, const char *tag) + __attribute__((nonnull(1))); + + +/* + * User data management + */ + +/** + * Set the data associated with the current pool + * @param data The user data associated with the pool. + * @param key The key to use for association + * @param cleanup The cleanup program to use to cleanup the data (NULL if none) + * @param pool The current pool + * @warning The data to be attached to the pool should have a life span + * at least as long as the pool it is being attached to. + * + * Users of APR must take EXTREME care when choosing a key to + * use for their data. It is possible to accidentally overwrite + * data by choosing a key that another part of the program is using. + * Therefore it is advised that steps are taken to ensure that unique + * keys are used for all of the userdata objects in a particular pool + * (the same key in two different pools or a pool and one of its + * subpools is okay) at all times. Careful namespace prefixing of + * key names is a typical way to help ensure this uniqueness. + * + */ +APR_DECLARE(apr_status_t) apr_pool_userdata_set(const void *data, + const char *key, + apr_status_t (*cleanup)(void *), + apr_pool_t *pool) + __attribute__((nonnull(2,4))); + +/** + * Set the data associated with the current pool + * @param data The user data associated with the pool. + * @param key The key to use for association + * @param cleanup The cleanup program to use to cleanup the data (NULL if none) + * @param pool The current pool + * @note same as apr_pool_userdata_set(), except that this version doesn't + * make a copy of the key (this function is useful, for example, when + * the key is a string literal) + * @warning This should NOT be used if the key could change addresses by + * any means between the apr_pool_userdata_setn() call and a + * subsequent apr_pool_userdata_get() on that key, such as if a + * static string is used as a userdata key in a DSO and the DSO could + * be unloaded and reloaded between the _setn() and the _get(). You + * MUST use apr_pool_userdata_set() in such cases. + * @warning More generally, the key and the data to be attached to the + * pool should have a life span at least as long as the pool itself. + * + */ +APR_DECLARE(apr_status_t) apr_pool_userdata_setn( + const void *data, const char *key, + apr_status_t (*cleanup)(void *), + apr_pool_t *pool) + __attribute__((nonnull(2,4))); + +/** + * Return the data associated with the current pool. + * @param data The user data associated with the pool. + * @param key The key for the data to retrieve + * @param pool The current pool. + */ +APR_DECLARE(apr_status_t) apr_pool_userdata_get(void **data, const char *key, + apr_pool_t *pool) + __attribute__((nonnull(1,2,3))); + + +/** + * @defgroup PoolCleanup Pool Cleanup Functions + * + * Cleanups are performed in the reverse order they were registered. That is: + * Last In, First Out. A cleanup function can safely allocate memory from + * the pool that is being cleaned up. It can also safely register additional + * cleanups which will be run LIFO, directly after the current cleanup + * terminates. Cleanups have to take caution in calling functions that + * create subpools. Subpools, created during cleanup will NOT automatically + * be cleaned up. In other words, cleanups are to clean up after themselves. + * + * @{ + */ + +/** + * Register a function to be called when a pool is cleared or destroyed + * @param p The pool to register the cleanup with + * @param data The data to pass to the cleanup function. + * @param plain_cleanup The function to call when the pool is cleared + * or destroyed + * @param child_cleanup The function to call when a child process is about + * to exec - this function is called in the child, obviously! + */ +APR_DECLARE(void) apr_pool_cleanup_register( + apr_pool_t *p, const void *data, + apr_status_t (*plain_cleanup)(void *), + apr_status_t (*child_cleanup)(void *)) + __attribute__((nonnull(3,4))); + +/** + * Register a function to be called when a pool is cleared or destroyed. + * + * Unlike apr_pool_cleanup_register which registers a cleanup + * that is called AFTER all subpools are destroyed, this function registers + * a function that will be called before any of the subpools are destroyed. + * + * @param p The pool to register the cleanup with + * @param data The data to pass to the cleanup function. + * @param plain_cleanup The function to call when the pool is cleared + * or destroyed + */ +APR_DECLARE(void) apr_pool_pre_cleanup_register( + apr_pool_t *p, const void *data, + apr_status_t (*plain_cleanup)(void *)) + __attribute__((nonnull(3))); + +/** + * Remove a previously registered cleanup function. + * + * The cleanup most recently registered with @a p having the same values of + * @a data and @a cleanup will be removed. + * + * @param p The pool to remove the cleanup from + * @param data The data of the registered cleanup + * @param cleanup The function to remove from cleanup + * @remarks For some strange reason only the plain_cleanup is handled by this + * function + */ +APR_DECLARE(void) apr_pool_cleanup_kill(apr_pool_t *p, const void *data, + apr_status_t (*cleanup)(void *)) + __attribute__((nonnull(3))); + +/** + * Replace the child cleanup function of a previously registered cleanup. + * + * The cleanup most recently registered with @a p having the same values of + * @a data and @a plain_cleanup will have the registered child cleanup + * function replaced with @a child_cleanup. + * + * @param p The pool of the registered cleanup + * @param data The data of the registered cleanup + * @param plain_cleanup The plain cleanup function of the registered cleanup + * @param child_cleanup The function to register as the child cleanup + */ +APR_DECLARE(void) apr_pool_child_cleanup_set( + apr_pool_t *p, const void *data, + apr_status_t (*plain_cleanup)(void *), + apr_status_t (*child_cleanup)(void *)) + __attribute__((nonnull(3,4))); + +/** + * Run the specified cleanup function immediately and unregister it. + * + * The cleanup most recently registered with @a p having the same values of + * @a data and @a cleanup will be removed and @a cleanup will be called + * with @a data as the argument. + * + * @param p The pool to remove the cleanup from + * @param data The data to remove from cleanup + * @param cleanup The function to remove from cleanup + */ +APR_DECLARE(apr_status_t) apr_pool_cleanup_run(apr_pool_t *p, void *data, + apr_status_t (*cleanup)(void *)) + __attribute__((nonnull(3))); + +/** + * An empty cleanup function. + * + * Passed to apr_pool_cleanup_register() when no cleanup is required. + * + * @param data The data to cleanup, will not be used by this function. + */ +APR_DECLARE_NONSTD(apr_status_t) apr_pool_cleanup_null(void *data); + +/** + * Run all registered child cleanups, in preparation for an exec() + * call in a forked child -- close files, etc., but *don't* flush I/O + * buffers, *don't* wait for subprocesses, and *don't* free any + * memory. + */ +APR_DECLARE(void) apr_pool_cleanup_for_exec(void); + +/** @} */ + +/** + * @defgroup PoolDebug Pool Debugging functions. + * + * pools have nested lifetimes -- sub_pools are destroyed when the + * parent pool is cleared. We allow certain liberties with operations + * on things such as tables (and on other structures in a more general + * sense) where we allow the caller to insert values into a table which + * were not allocated from the table's pool. The table's data will + * remain valid as long as all the pools from which its values are + * allocated remain valid. + * + * For example, if B is a sub pool of A, and you build a table T in + * pool B, then it's safe to insert data allocated in A or B into T + * (because B lives at most as long as A does, and T is destroyed when + * B is cleared/destroyed). On the other hand, if S is a table in + * pool A, it is safe to insert data allocated in A into S, but it + * is *not safe* to insert data allocated from B into S... because + * B can be cleared/destroyed before A is (which would leave dangling + * pointers in T's data structures). + * + * In general we say that it is safe to insert data into a table T + * if the data is allocated in any ancestor of T's pool. This is the + * basis on which the APR_POOL_DEBUG code works -- it tests these ancestor + * relationships for all data inserted into tables. APR_POOL_DEBUG also + * provides tools (apr_pool_find, and apr_pool_is_ancestor) for other + * folks to implement similar restrictions for their own data + * structures. + * + * However, sometimes this ancestor requirement is inconvenient -- + * sometimes it's necessary to create a sub pool where the sub pool is + * guaranteed to have the same lifetime as the parent pool. This is a + * guarantee implemented by the *caller*, not by the pool code. That + * is, the caller guarantees they won't destroy the sub pool + * individually prior to destroying the parent pool. + * + * In this case the caller must call apr_pool_join() to indicate this + * guarantee to the APR_POOL_DEBUG code. + * + * These functions are only implemented when #APR_POOL_DEBUG is set. + * + * @{ + */ +#if APR_POOL_DEBUG || defined(DOXYGEN) +/** + * Guarantee that a subpool has the same lifetime as the parent. + * @param p The parent pool + * @param sub The subpool + */ +APR_DECLARE(void) apr_pool_join(apr_pool_t *p, apr_pool_t *sub) + __attribute__((nonnull(2))); + +/** + * Find a pool from something allocated in it. + * @param mem The thing allocated in the pool + * @return The pool it is allocated in + */ +APR_DECLARE(apr_pool_t *) apr_pool_find(const void *mem); + +/** + * Report the number of bytes currently in the pool + * @param p The pool to inspect + * @param recurse Recurse/include the subpools' sizes + * @return The number of bytes + */ +APR_DECLARE(apr_size_t) apr_pool_num_bytes(apr_pool_t *p, int recurse) + __attribute__((nonnull(1))); + +/** + * Lock a pool + * @param pool The pool to lock + * @param flag The flag + */ +APR_DECLARE(void) apr_pool_lock(apr_pool_t *pool, int flag); + +/* @} */ + +#else /* APR_POOL_DEBUG or DOXYGEN */ + +#ifdef apr_pool_join +#undef apr_pool_join +#endif +#define apr_pool_join(a,b) + +#ifdef apr_pool_lock +#undef apr_pool_lock +#endif +#define apr_pool_lock(pool, lock) + +#endif /* APR_POOL_DEBUG or DOXYGEN */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_POOLS_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_portable.h b/c/dependencies/windows/apr/x86/include/apr_portable.h new file mode 100644 index 00000000..f56997e4 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_portable.h @@ -0,0 +1,549 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* This header file is where you should put ANY platform specific information. + * This should be the only header file that programs need to include that + * actually has platform dependent code which refers to the . + */ +#ifndef APR_PORTABLE_H +#define APR_PORTABLE_H +/** + * @file apr_portable.h + * @brief APR Portability Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" +#include "apr_network_io.h" +#include "apr_errno.h" +#include "apr_global_mutex.h" +#include "apr_proc_mutex.h" +#include "apr_time.h" +#include "apr_dso.h" +#include "apr_shm.h" + +#if APR_HAVE_DIRENT_H +#include +#endif +#if APR_HAVE_FCNTL_H +#include +#endif +#if APR_HAVE_PTHREAD_H +#include +#endif +#if APR_HAVE_SEMAPHORE_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_portabile Portability Routines + * @ingroup APR + * @{ + */ + +#ifdef WIN32 +/* The primitives for Windows types */ +typedef HANDLE apr_os_file_t; +typedef HANDLE apr_os_dir_t; +typedef SOCKET apr_os_sock_t; +typedef HANDLE apr_os_proc_mutex_t; +typedef HANDLE apr_os_thread_t; +typedef HANDLE apr_os_proc_t; +typedef DWORD apr_os_threadkey_t; +typedef FILETIME apr_os_imp_time_t; +typedef SYSTEMTIME apr_os_exp_time_t; +typedef HANDLE apr_os_dso_handle_t; +typedef HANDLE apr_os_shm_t; + +#elif defined(OS2) +typedef HFILE apr_os_file_t; +typedef HDIR apr_os_dir_t; +typedef int apr_os_sock_t; +typedef HMTX apr_os_proc_mutex_t; +typedef TID apr_os_thread_t; +typedef PID apr_os_proc_t; +typedef PULONG apr_os_threadkey_t; +typedef struct timeval apr_os_imp_time_t; +typedef struct tm apr_os_exp_time_t; +typedef HMODULE apr_os_dso_handle_t; +typedef void* apr_os_shm_t; + +#elif defined(__BEOS__) +#include +#include + +struct apr_os_proc_mutex_t { + sem_id sem; + int32 ben; +}; + +typedef int apr_os_file_t; +typedef DIR apr_os_dir_t; +typedef int apr_os_sock_t; +typedef struct apr_os_proc_mutex_t apr_os_proc_mutex_t; +typedef thread_id apr_os_thread_t; +typedef thread_id apr_os_proc_t; +typedef int apr_os_threadkey_t; +typedef struct timeval apr_os_imp_time_t; +typedef struct tm apr_os_exp_time_t; +typedef image_id apr_os_dso_handle_t; +typedef void* apr_os_shm_t; + +#elif defined(NETWARE) +typedef int apr_os_file_t; +typedef DIR apr_os_dir_t; +typedef int apr_os_sock_t; +typedef NXMutex_t apr_os_proc_mutex_t; +typedef NXThreadId_t apr_os_thread_t; +typedef long apr_os_proc_t; +typedef NXKey_t apr_os_threadkey_t; +typedef struct timeval apr_os_imp_time_t; +typedef struct tm apr_os_exp_time_t; +typedef void * apr_os_dso_handle_t; +typedef void* apr_os_shm_t; + +#else +/* Any other OS should go above this one. This is the lowest common + * denominator typedefs for all UNIX-like systems. :) + */ + +/** Basic OS process mutex structure. */ +struct apr_os_proc_mutex_t { +#if APR_HAS_SYSVSEM_SERIALIZE || APR_HAS_FCNTL_SERIALIZE || APR_HAS_FLOCK_SERIALIZE + /** Value used for SYS V Semaphore, FCNTL and FLOCK serialization */ + int crossproc; +#endif +#if APR_HAS_PROC_PTHREAD_SERIALIZE + /** Value used for PTHREAD serialization */ + pthread_mutex_t *pthread_interproc; +#endif +#if APR_HAS_THREADS + /* If no threads, no need for thread locks */ +#if APR_USE_PTHREAD_SERIALIZE + /** This value is currently unused within APR and Apache */ + pthread_mutex_t *intraproc; +#endif +#endif +#if APR_HAS_POSIXSEM_SERIALIZE + /** Value used for POSIX semaphores serialization */ + sem_t *psem_interproc; +#endif +}; + +typedef int apr_os_file_t; /**< native file */ +typedef DIR apr_os_dir_t; /**< native dir */ +typedef int apr_os_sock_t; /**< native dir */ +typedef struct apr_os_proc_mutex_t apr_os_proc_mutex_t; /**< native process + * mutex + */ +#if APR_HAS_THREADS && APR_HAVE_PTHREAD_H +typedef pthread_t apr_os_thread_t; /**< native thread */ +typedef pthread_key_t apr_os_threadkey_t; /**< native thread address + * space */ +#endif +typedef pid_t apr_os_proc_t; /**< native pid */ +typedef struct timeval apr_os_imp_time_t; /**< native timeval */ +typedef struct tm apr_os_exp_time_t; /**< native tm */ +/** @var apr_os_dso_handle_t + * native dso types + */ +#if defined(HPUX) || defined(HPUX10) || defined(HPUX11) +#include +typedef shl_t apr_os_dso_handle_t; +#elif defined(DARWIN) +#include +typedef NSModule apr_os_dso_handle_t; +#else +typedef void * apr_os_dso_handle_t; +#endif +typedef void* apr_os_shm_t; /**< native SHM */ + +#endif + +/** + * @typedef apr_os_sock_info_t + * @brief alias for local OS socket + */ +/** + * everything APR needs to know about an active socket to construct + * an APR socket from it; currently, this is platform-independent + */ +struct apr_os_sock_info_t { + apr_os_sock_t *os_sock; /**< always required */ + struct sockaddr *local; /**< NULL if not yet bound */ + struct sockaddr *remote; /**< NULL if not connected */ + int family; /**< always required (APR_INET, APR_INET6, etc.) */ + int type; /**< always required (SOCK_STREAM, SOCK_DGRAM, etc.) */ + int protocol; /**< 0 or actual protocol (APR_PROTO_SCTP, APR_PROTO_TCP, etc.) */ +}; + +typedef struct apr_os_sock_info_t apr_os_sock_info_t; + +#if APR_PROC_MUTEX_IS_GLOBAL || defined(DOXYGEN) +/** Opaque global mutex type */ +#define apr_os_global_mutex_t apr_os_proc_mutex_t +/** @return apr_os_global_mutex */ +#define apr_os_global_mutex_get apr_os_proc_mutex_get +#else + /** Thread and process mutex for those platforms where process mutexes + * are not held in threads. + */ + struct apr_os_global_mutex_t { + apr_pool_t *pool; + apr_proc_mutex_t *proc_mutex; +#if APR_HAS_THREADS + apr_thread_mutex_t *thread_mutex; +#endif /* APR_HAS_THREADS */ + }; + typedef struct apr_os_global_mutex_t apr_os_global_mutex_t; + +APR_DECLARE(apr_status_t) apr_os_global_mutex_get(apr_os_global_mutex_t *ospmutex, + apr_global_mutex_t *pmutex); +#endif + + +/** + * convert the file from apr type to os specific type. + * @param thefile The os specific file we are converting to + * @param file The apr file to convert. + * @remark On Unix, it is only possible to get a file descriptor from + * an apr file type. + */ +APR_DECLARE(apr_status_t) apr_os_file_get(apr_os_file_t *thefile, + apr_file_t *file); + +/** + * convert the dir from apr type to os specific type. + * @param thedir The os specific dir we are converting to + * @param dir The apr dir to convert. + */ +APR_DECLARE(apr_status_t) apr_os_dir_get(apr_os_dir_t **thedir, + apr_dir_t *dir); + +/** + * Convert the socket from an apr type to an OS specific socket + * @param thesock The socket to convert. + * @param sock The os specific equivalent of the apr socket.. + */ +APR_DECLARE(apr_status_t) apr_os_sock_get(apr_os_sock_t *thesock, + apr_socket_t *sock); + +/** + * Convert the proc mutex from apr type to os specific type + * @param ospmutex The os specific proc mutex we are converting to. + * @param pmutex The apr proc mutex to convert. + */ +APR_DECLARE(apr_status_t) apr_os_proc_mutex_get(apr_os_proc_mutex_t *ospmutex, + apr_proc_mutex_t *pmutex); + +/** + * Convert the proc mutex from apr type to os specific type, also + * providing the mechanism used by the apr mutex. + * @param ospmutex The os specific proc mutex we are converting to. + * @param pmutex The apr proc mutex to convert. + * @param mech The mechanism used by the apr proc mutex (if not NULL). + * @remark Allows for disambiguation for platforms with multiple mechanisms + * available. + */ +APR_DECLARE(apr_status_t) apr_os_proc_mutex_get_ex(apr_os_proc_mutex_t *ospmutex, + apr_proc_mutex_t *pmutex, + apr_lockmech_e *mech); + +/** + * Get the exploded time in the platforms native format. + * @param ostime the native time format + * @param aprtime the time to convert + */ +APR_DECLARE(apr_status_t) apr_os_exp_time_get(apr_os_exp_time_t **ostime, + apr_time_exp_t *aprtime); + +/** + * Get the imploded time in the platforms native format. + * @param ostime the native time format + * @param aprtime the time to convert + */ +APR_DECLARE(apr_status_t) apr_os_imp_time_get(apr_os_imp_time_t **ostime, + apr_time_t *aprtime); + +/** + * convert the shm from apr type to os specific type. + * @param osshm The os specific shm representation + * @param shm The apr shm to convert. + */ +APR_DECLARE(apr_status_t) apr_os_shm_get(apr_os_shm_t *osshm, + apr_shm_t *shm); + +#if APR_HAS_THREADS || defined(DOXYGEN) +/** + * @defgroup apr_os_thread Thread portability Routines + * @{ + */ +/** + * convert the thread to os specific type from apr type. + * @param thethd The apr thread to convert + * @param thd The os specific thread we are converting to + */ +APR_DECLARE(apr_status_t) apr_os_thread_get(apr_os_thread_t **thethd, + apr_thread_t *thd); + +/** + * convert the thread private memory key to os specific type from an apr type. + * @param thekey The apr handle we are converting from. + * @param key The os specific handle we are converting to. + */ +APR_DECLARE(apr_status_t) apr_os_threadkey_get(apr_os_threadkey_t *thekey, + apr_threadkey_t *key); + +/** + * convert the thread from os specific type to apr type. + * @param thd The apr thread we are converting to. + * @param thethd The os specific thread to convert + * @param cont The pool to use if it is needed. + */ +APR_DECLARE(apr_status_t) apr_os_thread_put(apr_thread_t **thd, + apr_os_thread_t *thethd, + apr_pool_t *cont); + +/** + * convert the thread private memory key from os specific type to apr type. + * @param key The apr handle we are converting to. + * @param thekey The os specific handle to convert + * @param cont The pool to use if it is needed. + */ +APR_DECLARE(apr_status_t) apr_os_threadkey_put(apr_threadkey_t **key, + apr_os_threadkey_t *thekey, + apr_pool_t *cont); +/** + * Get the thread ID + */ +APR_DECLARE(apr_os_thread_t) apr_os_thread_current(void); + +/** + * Compare two thread id's + * @param tid1 1st Thread ID to compare + * @param tid2 2nd Thread ID to compare + * @return non-zero if the two threads are equal, zero otherwise + */ +APR_DECLARE(int) apr_os_thread_equal(apr_os_thread_t tid1, + apr_os_thread_t tid2); + +/** @} */ +#endif /* APR_HAS_THREADS */ + +/** + * convert the file from os specific type to apr type. + * @param file The apr file we are converting to. + * @param thefile The os specific file to convert + * @param flags The flags that were used to open this file. + * @param cont The pool to use if it is needed. + * @remark On Unix, it is only possible to put a file descriptor into + * an apr file type. + */ +APR_DECLARE(apr_status_t) apr_os_file_put(apr_file_t **file, + apr_os_file_t *thefile, + apr_int32_t flags, apr_pool_t *cont); + +/** + * convert the file from os specific type to apr type. + * @param file The apr file we are converting to. + * @param thefile The os specific pipe to convert + * @param cont The pool to use if it is needed. + * @remark On Unix, it is only possible to put a file descriptor into + * an apr file type. + */ +APR_DECLARE(apr_status_t) apr_os_pipe_put(apr_file_t **file, + apr_os_file_t *thefile, + apr_pool_t *cont); + +/** + * convert the file from os specific type to apr type. + * @param file The apr file we are converting to. + * @param thefile The os specific pipe to convert + * @param register_cleanup A cleanup will be registered on the apr_file_t + * to issue apr_file_close(). + * @param cont The pool to use if it is needed. + * @remark On Unix, it is only possible to put a file descriptor into + * an apr file type. + */ +APR_DECLARE(apr_status_t) apr_os_pipe_put_ex(apr_file_t **file, + apr_os_file_t *thefile, + int register_cleanup, + apr_pool_t *cont); + +/** + * convert the dir from os specific type to apr type. + * @param dir The apr dir we are converting to. + * @param thedir The os specific dir to convert + * @param cont The pool to use when creating to apr directory. + */ +APR_DECLARE(apr_status_t) apr_os_dir_put(apr_dir_t **dir, + apr_os_dir_t *thedir, + apr_pool_t *cont); + +/** + * Convert a socket from the os specific type to the APR type. If + * sock points to NULL, a socket will be created from the pool + * provided. If **sock does not point to NULL, the structure pointed + * to by sock will be reused and updated with the given socket. + * @param sock The pool to use. + * @param thesock The socket to convert to. + * @param cont The socket we are converting to an apr type. + * @remark If it is a true socket, it is best to call apr_os_sock_make() + * and provide APR with more information about the socket. + */ +APR_DECLARE(apr_status_t) apr_os_sock_put(apr_socket_t **sock, + apr_os_sock_t *thesock, + apr_pool_t *cont); + +/** + * Create a socket from an existing descriptor and local and remote + * socket addresses. + * @param apr_sock The new socket that has been set up + * @param os_sock_info The os representation of the socket handle and + * other characteristics of the socket + * @param cont The pool to use + * @remark If you only know the descriptor/handle or if it isn't really + * a true socket, use apr_os_sock_put() instead. + */ +APR_DECLARE(apr_status_t) apr_os_sock_make(apr_socket_t **apr_sock, + apr_os_sock_info_t *os_sock_info, + apr_pool_t *cont); + +/** + * Convert the proc mutex from os specific type to apr type + * @param pmutex The apr proc mutex we are converting to. + * @param ospmutex The os specific proc mutex to convert. + * @param cont The pool to use if it is needed. + */ +APR_DECLARE(apr_status_t) apr_os_proc_mutex_put(apr_proc_mutex_t **pmutex, + apr_os_proc_mutex_t *ospmutex, + apr_pool_t *cont); + +/** + * Convert the proc mutex from os specific type to apr type, using the + * specified mechanism. + * @param pmutex The apr proc mutex we are converting to. + * @param ospmutex The os specific proc mutex to convert. + * @param mech The apr mutex locking mechanism + * @param register_cleanup Whether to destroy the os mutex with the apr + * one (either on explicit destroy or pool cleanup). + * @param cont The pool to use if it is needed. + * @remark Allows for disambiguation for platforms with multiple mechanisms + * available. + */ +APR_DECLARE(apr_status_t) apr_os_proc_mutex_put_ex(apr_proc_mutex_t **pmutex, + apr_os_proc_mutex_t *ospmutex, + apr_lockmech_e mech, + int register_cleanup, + apr_pool_t *cont); + +/** + * Put the imploded time in the APR format. + * @param aprtime the APR time format + * @param ostime the time to convert + * @param cont the pool to use if necessary + */ +APR_DECLARE(apr_status_t) apr_os_imp_time_put(apr_time_t *aprtime, + apr_os_imp_time_t **ostime, + apr_pool_t *cont); + +/** + * Put the exploded time in the APR format. + * @param aprtime the APR time format + * @param ostime the time to convert + * @param cont the pool to use if necessary + */ +APR_DECLARE(apr_status_t) apr_os_exp_time_put(apr_time_exp_t *aprtime, + apr_os_exp_time_t **ostime, + apr_pool_t *cont); + +/** + * convert the shared memory from os specific type to apr type. + * @param shm The apr shm representation of osshm + * @param osshm The os specific shm identity + * @param cont The pool to use if it is needed. + * @remark On fork()ed architectures, this is typically nothing more than + * the memory block mapped. On non-fork architectures, this is typically + * some internal handle to pass the mapping from process to process. + */ +APR_DECLARE(apr_status_t) apr_os_shm_put(apr_shm_t **shm, + apr_os_shm_t *osshm, + apr_pool_t *cont); + + +#if APR_HAS_DSO || defined(DOXYGEN) +/** + * @defgroup apr_os_dso DSO (Dynamic Loading) Portability Routines + * @{ + */ +/** + * convert the dso handle from os specific to apr + * @param dso The apr handle we are converting to + * @param thedso the os specific handle to convert + * @param pool the pool to use if it is needed + */ +APR_DECLARE(apr_status_t) apr_os_dso_handle_put(apr_dso_handle_t **dso, + apr_os_dso_handle_t thedso, + apr_pool_t *pool); + +/** + * convert the apr dso handle into an os specific one + * @param aprdso The apr dso handle to convert + * @param dso The os specific dso to return + */ +APR_DECLARE(apr_status_t) apr_os_dso_handle_get(apr_os_dso_handle_t *dso, + apr_dso_handle_t *aprdso); + +/** @} */ +#endif /* APR_HAS_DSO */ + + +#if APR_HAS_OS_UUID +/** + * Private: apr-util's apr_uuid module when supported by the platform + */ +APR_DECLARE(apr_status_t) apr_os_uuid_get(unsigned char *uuid_data); +#endif + + +/** + * Get the name of the system default character set. + * @param pool the pool to allocate the name from, if needed + */ +APR_DECLARE(const char*) apr_os_default_encoding(apr_pool_t *pool); + + +/** + * Get the name of the current locale character set. + * @param pool the pool to allocate the name from, if needed + * @remark Defers to apr_os_default_encoding() if the current locale's + * data can't be retrieved on this system. + */ +APR_DECLARE(const char*) apr_os_locale_encoding(apr_pool_t *pool); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_PORTABLE_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_proc_mutex.h b/c/dependencies/windows/apr/x86/include/apr_proc_mutex.h new file mode 100644 index 00000000..418c9504 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_proc_mutex.h @@ -0,0 +1,192 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_PROC_MUTEX_H +#define APR_PROC_MUTEX_H + +/** + * @file apr_proc_mutex.h + * @brief APR Process Locking Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_perms_set.h" +#include "apr_time.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_proc_mutex Process Locking Routines + * @ingroup APR + * @{ + */ + +/** + * Enumerated potential types for APR process locking methods + * @warning Check APR_HAS_foo_SERIALIZE defines to see if the platform supports + * APR_LOCK_foo. Only APR_LOCK_DEFAULT is portable. + */ +typedef enum { + APR_LOCK_FCNTL, /**< fcntl() */ + APR_LOCK_FLOCK, /**< flock() */ + APR_LOCK_SYSVSEM, /**< System V Semaphores */ + APR_LOCK_PROC_PTHREAD, /**< POSIX pthread process-based locking */ + APR_LOCK_POSIXSEM, /**< POSIX semaphore process-based locking */ + APR_LOCK_DEFAULT, /**< Use the default process lock */ + APR_LOCK_DEFAULT_TIMED /**< Use the default process timed lock */ +} apr_lockmech_e; + +/** Opaque structure representing a process mutex. */ +typedef struct apr_proc_mutex_t apr_proc_mutex_t; + +/* Function definitions */ + +/** + * Create and initialize a mutex that can be used to synchronize processes. + * @param mutex the memory address where the newly created mutex will be + * stored. + * @param fname A file name to use if the lock mechanism requires one. This + * argument should always be provided. The lock code itself will + * determine if it should be used. + * @param mech The mechanism to use for the interprocess lock, if any; one of + *
+ *            APR_LOCK_FCNTL
+ *            APR_LOCK_FLOCK
+ *            APR_LOCK_SYSVSEM
+ *            APR_LOCK_POSIXSEM
+ *            APR_LOCK_PROC_PTHREAD
+ *            APR_LOCK_DEFAULT     pick the default mechanism for the platform
+ * 
+ * @param pool the pool from which to allocate the mutex. + * @see apr_lockmech_e + * @warning Check APR_HAS_foo_SERIALIZE defines to see if the platform supports + * APR_LOCK_foo. Only APR_LOCK_DEFAULT is portable. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_create(apr_proc_mutex_t **mutex, + const char *fname, + apr_lockmech_e mech, + apr_pool_t *pool); + +/** + * Re-open a mutex in a child process. + * @param mutex The newly re-opened mutex structure. + * @param fname A file name to use if the mutex mechanism requires one. This + * argument should always be provided. The mutex code itself will + * determine if it should be used. This filename should be the + * same one that was passed to apr_proc_mutex_create(). + * @param pool The pool to operate on. + * @remark This function must be called to maintain portability, even + * if the underlying lock mechanism does not require it. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_child_init(apr_proc_mutex_t **mutex, + const char *fname, + apr_pool_t *pool); + +/** + * Acquire the lock for the given mutex. If the mutex is already locked, + * the current thread will be put to sleep until the lock becomes available. + * @param mutex the mutex on which to acquire the lock. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_lock(apr_proc_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex. If the mutex has already + * been acquired, the call returns immediately with APR_EBUSY. Note: it + * is important that the APR_STATUS_IS_EBUSY(s) macro be used to determine + * if the return value was APR_EBUSY, for portability reasons. + * @param mutex the mutex on which to attempt the lock acquiring. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_trylock(apr_proc_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex until timeout expires. + * If the acquisition time outs, the call returns with APR_TIMEUP. + * @param mutex the mutex on which to attempt the lock acquiring. + * @param timeout the relative timeout (microseconds). + * @note A negative or nul timeout means immediate attempt, returning + * APR_TIMEUP without blocking if it the lock is already acquired. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_timedlock(apr_proc_mutex_t *mutex, + apr_interval_time_t timeout); + +/** + * Release the lock for the given mutex. + * @param mutex the mutex from which to release the lock. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_unlock(apr_proc_mutex_t *mutex); + +/** + * Destroy the mutex and free the memory associated with the lock. + * @param mutex the mutex to destroy. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_destroy(apr_proc_mutex_t *mutex); + +/** + * Destroy the mutex and free the memory associated with the lock. + * @param mutex the mutex to destroy. + * @note This function is generally used to kill a cleanup on an already + * created mutex + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_cleanup(void *mutex); + +/** + * Return the name of the lockfile for the mutex, or NULL + * if the mutex doesn't use a lock file + */ + +APR_DECLARE(const char *) apr_proc_mutex_lockfile(apr_proc_mutex_t *mutex); + +/** + * Get the mechanism of the mutex, as it relates to the actual method + * used for the underlying apr_proc_mutex_t. + * @param mutex the mutex to get the mechanism from. + */ +APR_DECLARE(apr_lockmech_e) apr_proc_mutex_mech(apr_proc_mutex_t *mutex); + +/** + * Get the mechanism's name of the mutex, as it relates to the actual method + * used for the underlying apr_proc_mutex_t. + * @param mutex the mutex to get the mechanism's name from. + */ +APR_DECLARE(const char *) apr_proc_mutex_name(apr_proc_mutex_t *mutex); + +/** + * Display the name of the default mutex: APR_LOCK_DEFAULT + */ +APR_DECLARE(const char *) apr_proc_mutex_defname(void); + +/** + * Set mutex permissions. + */ +APR_PERMS_SET_IMPLEMENT(proc_mutex); + +/** + * Get the pool used by this proc_mutex. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(proc_mutex); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_PROC_MUTEX_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_queue.h b/c/dependencies/windows/apr/x86/include/apr_queue.h new file mode 100644 index 00000000..a3a41704 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_queue.h @@ -0,0 +1,138 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_QUEUE_H +#define APR_QUEUE_H + +/** + * @file apr_queue.h + * @brief Thread Safe FIFO bounded queue + * @note Since most implementations of the queue are backed by a condition + * variable implementation, it isn't available on systems without threads. + * Although condition variables are sometimes available without threads. + */ + +#include "apu.h" +#include "apr_errno.h" +#include "apr_pools.h" + +#if APR_HAS_THREADS + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_Util_FIFO Thread Safe FIFO bounded queue + * @ingroup APR_Util + * @{ + */ + +/** + * opaque structure + */ +typedef struct apr_queue_t apr_queue_t; + +/** + * create a FIFO queue + * @param queue The new queue + * @param queue_capacity maximum size of the queue + * @param a pool to allocate queue from + */ +APU_DECLARE(apr_status_t) apr_queue_create(apr_queue_t **queue, + unsigned int queue_capacity, + apr_pool_t *a); + +/** + * push/add an object to the queue, blocking if the queue is already full + * + * @param queue the queue + * @param data the data + * @returns APR_EINTR the blocking was interrupted (try again) + * @returns APR_EOF the queue has been terminated + * @returns APR_SUCCESS on a successful push + */ +APU_DECLARE(apr_status_t) apr_queue_push(apr_queue_t *queue, void *data); + +/** + * pop/get an object from the queue, blocking if the queue is already empty + * + * @param queue the queue + * @param data the data + * @returns APR_EINTR the blocking was interrupted (try again) + * @returns APR_EOF if the queue has been terminated + * @returns APR_SUCCESS on a successful pop + */ +APU_DECLARE(apr_status_t) apr_queue_pop(apr_queue_t *queue, void **data); + +/** + * push/add an object to the queue, returning immediately if the queue is full + * + * @param queue the queue + * @param data the data + * @returns APR_EINTR the blocking operation was interrupted (try again) + * @returns APR_EAGAIN the queue is full + * @returns APR_EOF the queue has been terminated + * @returns APR_SUCCESS on a successful push + */ +APU_DECLARE(apr_status_t) apr_queue_trypush(apr_queue_t *queue, void *data); + +/** + * pop/get an object to the queue, returning immediately if the queue is empty + * + * @param queue the queue + * @param data the data + * @returns APR_EINTR the blocking operation was interrupted (try again) + * @returns APR_EAGAIN the queue is empty + * @returns APR_EOF the queue has been terminated + * @returns APR_SUCCESS on a successful pop + */ +APU_DECLARE(apr_status_t) apr_queue_trypop(apr_queue_t *queue, void **data); + +/** + * returns the size of the queue. + * + * @warning this is not threadsafe, and is intended for reporting/monitoring + * of the queue. + * @param queue the queue + * @returns the size of the queue + */ +APU_DECLARE(unsigned int) apr_queue_size(apr_queue_t *queue); + +/** + * interrupt all the threads blocking on this queue. + * + * @param queue the queue + */ +APU_DECLARE(apr_status_t) apr_queue_interrupt_all(apr_queue_t *queue); + +/** + * terminate the queue, sending an interrupt to all the + * blocking threads + * + * @param queue the queue + */ +APU_DECLARE(apr_status_t) apr_queue_term(apr_queue_t *queue); + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif /* APR_HAS_THREADS */ + +#endif /* APRQUEUE_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_random.h b/c/dependencies/windows/apr/x86/include/apr_random.h new file mode 100644 index 00000000..29154358 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_random.h @@ -0,0 +1,153 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_RANDOM_H +#define APR_RANDOM_H + +/** + * @file apr_random.h + * @brief APR PRNG routines + */ + +#include "apr_pools.h" +#include "apr_thread_proc.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_random PRNG Routines + * @ingroup APR + * @{ + */ + +typedef struct apr_crypto_hash_t apr_crypto_hash_t; + +typedef void apr_crypto_hash_init_t(apr_crypto_hash_t *hash); +typedef void apr_crypto_hash_add_t(apr_crypto_hash_t *hash, const void *data, + apr_size_t bytes); +typedef void apr_crypto_hash_finish_t(apr_crypto_hash_t *hash, + unsigned char *result); + + +/* FIXME: make this opaque */ +struct apr_crypto_hash_t { + apr_crypto_hash_init_t *init; + apr_crypto_hash_add_t *add; + apr_crypto_hash_finish_t *finish; + apr_size_t size; + void *data; +}; + +/** + * Allocate and initialize the SHA-256 context + * @param p The pool to allocate from + */ +APR_DECLARE(apr_crypto_hash_t *) apr_crypto_sha256_new(apr_pool_t *p); + +/** Opaque PRNG structure. */ +typedef struct apr_random_t apr_random_t; + +/** + * Initialize a PRNG state + * @param g The PRNG state + * @param p The pool to allocate from + * @param pool_hash Pool hash functions + * @param key_hash Key hash functions + * @param prng_hash PRNG hash functions + */ +APR_DECLARE(void) apr_random_init(apr_random_t *g, apr_pool_t *p, + apr_crypto_hash_t *pool_hash, + apr_crypto_hash_t *key_hash, + apr_crypto_hash_t *prng_hash); +/** + * Allocate and initialize (apr_crypto_sha256_new) a new PRNG state. + * @param p The pool to allocate from + */ +APR_DECLARE(apr_random_t *) apr_random_standard_new(apr_pool_t *p); + +/** + * Mix the randomness pools. + * @param g The PRNG state + * @param entropy_ Entropy buffer + * @param bytes Length of entropy_ in bytes + */ +APR_DECLARE(void) apr_random_add_entropy(apr_random_t *g, + const void *entropy_, + apr_size_t bytes); +/** + * Generate cryptographically insecure random bytes. + * @param g The RNG state + * @param random Buffer to fill with random bytes + * @param bytes Length of buffer in bytes + */ +APR_DECLARE(apr_status_t) apr_random_insecure_bytes(apr_random_t *g, + void *random, + apr_size_t bytes); + +/** + * Generate cryptographically secure random bytes. + * @param g The RNG state + * @param random Buffer to fill with random bytes + * @param bytes Length of buffer in bytes + */ +APR_DECLARE(apr_status_t) apr_random_secure_bytes(apr_random_t *g, + void *random, + apr_size_t bytes); +/** + * Ensures that E bits of conditional entropy are mixed into the PRNG + * before any further randomness is extracted. + * @param g The RNG state + */ +APR_DECLARE(void) apr_random_barrier(apr_random_t *g); + +/** + * Return APR_SUCCESS if the cryptographic PRNG has been seeded with + * enough data, APR_ENOTENOUGHENTROPY otherwise. + * @param r The RNG state + */ +APR_DECLARE(apr_status_t) apr_random_secure_ready(apr_random_t *r); + +/** + * Return APR_SUCCESS if the PRNG has been seeded with enough data, + * APR_ENOTENOUGHENTROPY otherwise. + * @param r The PRNG state + */ +APR_DECLARE(apr_status_t) apr_random_insecure_ready(apr_random_t *r); + +/** + * Mix the randomness pools after forking. + * @param proc The resulting process handle from apr_proc_fork() + * @remark Call this in the child after forking to mix the randomness + * pools. Note that its generally a bad idea to fork a process with a + * real PRNG in it - better to have the PRNG externally and get the + * randomness from there. However, if you really must do it, then you + * should supply all your entropy to all the PRNGs - don't worry, they + * won't produce the same output. + * @remark Note that apr_proc_fork() calls this for you, so only weird + * applications need ever call it themselves. + * @internal + */ +APR_DECLARE(void) apr_random_after_fork(apr_proc_t *proc); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_RANDOM_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_redis.h b/c/dependencies/windows/apr/x86/include/apr_redis.h new file mode 100644 index 00000000..66a828b0 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_redis.h @@ -0,0 +1,459 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_redis.h + * @brief Client interface for redis + * @remark To use this interface you must have a separate redis + * for more information. + */ + +#ifndef APR_REDIS_H +#define APR_REDIS_H + +#include "apr.h" +#include "apr_pools.h" +#include "apr_time.h" +#include "apr_strings.h" +#include "apr_network_io.h" +#include "apr_ring.h" +#include "apr_buckets.h" +#include "apr_reslist.h" +#include "apr_hash.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#ifndef RC_DEFAULT_SERVER_PORT +#define RC_DEFAULT_SERVER_PORT 6379 +#endif + +#ifndef RC_DEFAULT_SERVER_MIN +#define RC_DEFAULT_SERVER_MIN 0 +#endif + +#ifndef RC_DEFAULT_SERVER_SMAX +#define RC_DEFAULT_SERVER_SMAX 1 +#endif + +#ifndef RC_DEFAULT_SERVER_TTL +#define RC_DEFAULT_SERVER_TTL 600 +#endif + +/** + * @defgroup APR_Util_RC Redis Client Routines + * @ingroup APR_Util + * @{ + */ + +/** Specifies the status of a redis server */ +typedef enum +{ + APR_RC_SERVER_LIVE, /**< Server is alive and responding to requests */ + APR_RC_SERVER_DEAD /**< Server is not responding to requests */ +} apr_redis_server_status_t; + +/** Opaque redis client connection object */ +typedef struct apr_redis_conn_t apr_redis_conn_t; + +/** Redis Server Info Object */ +typedef struct apr_redis_server_t apr_redis_server_t; +struct apr_redis_server_t +{ + const char *host; /**< Hostname of this Server */ + apr_port_t port; /**< Port of this Server */ + apr_redis_server_status_t status; /**< @see apr_redis_server_status_t */ +#if APR_HAS_THREADS || defined(DOXYGEN) + apr_reslist_t *conns; /**< Resource list of actual client connections */ +#else + apr_redis_conn_t *conn; +#endif + apr_pool_t *p; /** Pool to use for private allocations */ +#if APR_HAS_THREADS + apr_thread_mutex_t *lock; +#endif + apr_time_t btime; + apr_uint32_t rwto; + struct + { + int major; + int minor; + int patch; + char *number; + } version; +}; + +typedef struct apr_redis_t apr_redis_t; + +/* Custom hash callback function prototype, user for server selection. +* @param baton user selected baton +* @param data data to hash +* @param data_len length of data +*/ +typedef apr_uint32_t (*apr_redis_hash_func)(void *baton, + const char *data, + const apr_size_t data_len); +/* Custom Server Select callback function prototype. +* @param baton user selected baton +* @param rc redis instance, use rc->live_servers to select a node +* @param hash hash of the selected key. +*/ +typedef apr_redis_server_t* (*apr_redis_server_func)(void *baton, + apr_redis_t *rc, + const apr_uint32_t hash); + +/** Container for a set of redis servers */ +struct apr_redis_t +{ + apr_uint32_t flags; /**< Flags, Not currently used */ + apr_uint16_t nalloc; /**< Number of Servers Allocated */ + apr_uint16_t ntotal; /**< Number of Servers Added */ + apr_redis_server_t **live_servers; /**< Array of Servers */ + apr_pool_t *p; /** Pool to use for allocations */ + void *hash_baton; + apr_redis_hash_func hash_func; + void *server_baton; + apr_redis_server_func server_func; +}; + +/** + * Creates a crc32 hash used to split keys between servers + * @param rc The redis client object to use + * @param data Data to be hashed + * @param data_len Length of the data to use + * @return crc32 hash of data + * @remark The crc32 hash is not compatible with old redisd clients. + */ +APU_DECLARE(apr_uint32_t) apr_redis_hash(apr_redis_t *rc, + const char *data, + const apr_size_t data_len); + +/** + * Pure CRC32 Hash. Used by some clients. + */ +APU_DECLARE(apr_uint32_t) apr_redis_hash_crc32(void *baton, + const char *data, + const apr_size_t data_len); + +/** + * hash compatible with the standard Perl Client. + */ +APU_DECLARE(apr_uint32_t) apr_redis_hash_default(void *baton, + const char *data, + const apr_size_t data_len); + +/** + * Picks a server based on a hash + * @param rc The redis client object to use + * @param hash Hashed value of a Key + * @return server that controls specified hash + * @see apr_redis_hash + */ +APU_DECLARE(apr_redis_server_t *) apr_redis_find_server_hash(apr_redis_t *rc, + const apr_uint32_t hash); + +/** + * server selection compatible with the standard Perl Client. + */ +APU_DECLARE(apr_redis_server_t *) apr_redis_find_server_hash_default(void *baton, + apr_redis_t *rc, + const apr_uint32_t hash); + +/** + * Adds a server to a client object + * @param rc The redis client object to use + * @param server Server to add + * @remark Adding servers is not thread safe, and should be done once at startup. + * @warning Changing servers after startup may cause keys to go to + * different servers. + */ +APU_DECLARE(apr_status_t) apr_redis_add_server(apr_redis_t *rc, + apr_redis_server_t *server); + + +/** + * Finds a Server object based on a hostname/port pair + * @param rc The redis client object to use + * @param host Hostname of the server + * @param port Port of the server + * @return Server with matching Hostname and Port, or NULL if none was found. + */ +APU_DECLARE(apr_redis_server_t *) apr_redis_find_server(apr_redis_t *rc, + const char *host, + apr_port_t port); + +/** + * Enables a Server for use again + * @param rc The redis client object to use + * @param rs Server to Activate + */ +APU_DECLARE(apr_status_t) apr_redis_enable_server(apr_redis_t *rc, + apr_redis_server_t *rs); + + +/** + * Disable a Server + * @param rc The redis client object to use + * @param rs Server to Disable + */ +APU_DECLARE(apr_status_t) apr_redis_disable_server(apr_redis_t *rc, + apr_redis_server_t *rs); + +/** + * Creates a new Server Object + * @param p Pool to use + * @param host hostname of the server + * @param port port of the server + * @param min minimum number of client sockets to open + * @param smax soft maximum number of client connections to open + * @param max hard maximum number of client connections + * @param ttl time to live in microseconds of a client connection + * @param rwto r/w timeout value in seconds of a client connection + * @param ns location of the new server object + * @see apr_reslist_create + * @remark min, smax, and max are only used when APR_HAS_THREADS + */ +APU_DECLARE(apr_status_t) apr_redis_server_create(apr_pool_t *p, + const char *host, + apr_port_t port, + apr_uint32_t min, + apr_uint32_t smax, + apr_uint32_t max, + apr_uint32_t ttl, + apr_uint32_t rwto, + apr_redis_server_t **ns); +/** + * Creates a new redisd client object + * @param p Pool to use + * @param max_servers maximum number of servers + * @param flags Not currently used + * @param rc location of the new redis client object + */ +APU_DECLARE(apr_status_t) apr_redis_create(apr_pool_t *p, + apr_uint16_t max_servers, + apr_uint32_t flags, + apr_redis_t **rc); + +/** + * Gets a value from the server, allocating the value out of p + * @param rc client to use + * @param p Pool to use + * @param key null terminated string containing the key + * @param baton location of the allocated value + * @param len length of data at baton + * @param flags any flags set by the client for this key + * @return + */ +APU_DECLARE(apr_status_t) apr_redis_getp(apr_redis_t *rc, + apr_pool_t *p, + const char* key, + char **baton, + apr_size_t *len, + apr_uint16_t *flags); + +/** + * Sets a value by key on the server + * @param rc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param flags any flags set by the client for this key + */ +APU_DECLARE(apr_status_t) apr_redis_set(apr_redis_t *rc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint16_t flags); + +/** + * Sets a value by key on the server + * @param rc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param timeout time in seconds for the data to live on the server + * @param flags any flags set by the client for this key + */ +APU_DECLARE(apr_status_t) apr_redis_setex(apr_redis_t *rc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint32_t timeout, + apr_uint16_t flags); + +/** + * Deletes a key from a server + * @param rc client to use + * @param key null terminated string containing the key + * @param timeout time for the delete to stop other clients from adding + */ +APU_DECLARE(apr_status_t) apr_redis_delete(apr_redis_t *rc, + const char *key, + apr_uint32_t timeout); + +/** + * Query a server's version + * @param rs server to query + * @param p Pool to allocate answer from + * @param baton location to store server version string + */ +APU_DECLARE(apr_status_t) apr_redis_version(apr_redis_server_t *rs, + apr_pool_t *p, + char **baton); + +/** + * Query a server's INFO + * @param rs server to query + * @param p Pool to allocate answer from + * @param baton location to store server INFO response string + */ +APU_DECLARE(apr_status_t) apr_redis_info(apr_redis_server_t *rs, + apr_pool_t *p, + char **baton); + +/** + * Increments a value + * @param rc client to use + * @param key null terminated string containing the key + * @param inc number to increment by + * @param new_value new value after incrementing + */ +APU_DECLARE(apr_status_t) apr_redis_incr(apr_redis_t *rc, + const char *key, + apr_int32_t inc, + apr_uint32_t *new_value); +/** + * Decrements a value + * @param rc client to use + * @param key null terminated string containing the key + * @param inc number to decrement by + * @param new_value new value after decrementing + */ +APU_DECLARE(apr_status_t) apr_redis_decr(apr_redis_t *rc, + const char *key, + apr_int32_t inc, + apr_uint32_t *new_value); + + +/** + * Pings the server + * @param rs Server to ping + */ +APU_DECLARE(apr_status_t) apr_redis_ping(apr_redis_server_t *rs); + +/** + * Gets multiple values from the server, allocating the values out of p + * @param rc client to use + * @param temp_pool Pool used for temporary allocations. May be cleared inside this + * call. + * @param data_pool Pool used to allocate data for the returned values. + * @param values hash of apr_redis_value_t keyed by strings, contains the + * result of the multiget call. + * @return + */ +APU_DECLARE(apr_status_t) apr_redis_multgetp(apr_redis_t *rc, + apr_pool_t *temp_pool, + apr_pool_t *data_pool, + apr_hash_t *values); + +typedef enum +{ + APR_RS_SERVER_MASTER, /**< Server is a master */ + APR_RS_SERVER_SLAVE, /**< Server is a slave */ + APR_RS_SERVER_UNKNOWN /**< Server role is unknown */ +} apr_redis_server_role_t; + +typedef struct +{ +/* # Server */ + /** Major version number of this server */ + apr_uint32_t major; + /** Minor version number of this server */ + apr_uint32_t minor; + /** Patch version number of this server */ + apr_uint32_t patch; + /** Process id of this server process */ + apr_uint32_t process_id; + /** Number of seconds this server has been running */ + apr_uint32_t uptime_in_seconds; + /** Bitsize of the arch on the current machine */ + apr_uint32_t arch_bits; + +/* # Clients */ + /** Number of connected clients */ + apr_uint32_t connected_clients; + /** Number of blocked clients */ + apr_uint32_t blocked_clients; + +/* # Memory */ + /** Max memory of this server */ + apr_uint64_t maxmemory; + /** Amount of used memory */ + apr_uint64_t used_memory; + /** Total memory available on this server */ + apr_uint64_t total_system_memory; + +/* # Stats */ + /** Total connections received */ + apr_uint64_t total_connections_received; + /** Total commands processed */ + apr_uint64_t total_commands_processed; + /** Total commands rejected */ + apr_uint64_t rejected_connections; + /** Total net input bytes */ + apr_uint64_t total_net_input_bytes; + /** Total net output bytes */ + apr_uint64_t total_net_output_bytes; + /** Keyspace hits */ + apr_uint64_t keyspace_hits; + /** Keyspace misses */ + apr_uint64_t keyspace_misses; + +/* # Replication */ + /** Role */ + apr_redis_server_role_t role; + /** Number of connected slave */ + apr_uint32_t connected_slaves; + +/* # CPU */ + /** Accumulated CPU user time for this process */ + apr_uint32_t used_cpu_sys; + /** Accumulated CPU system time for this process */ + apr_uint32_t used_cpu_user; + +/* # Cluster */ + /** Is cluster enabled */ + apr_uint32_t cluster_enabled; +} apr_redis_stats_t; + +/** + * Query a server for statistics + * @param rs server to query + * @param p Pool to allocate answer from + * @param stats location of the new statistics structure + */ +APU_DECLARE(apr_status_t) apr_redis_stats(apr_redis_server_t *rs, + apr_pool_t *p, + apr_redis_stats_t **stats); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_REDIS_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_reslist.h b/c/dependencies/windows/apr/x86/include/apr_reslist.h new file mode 100644 index 00000000..02a8192b --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_reslist.h @@ -0,0 +1,183 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_RESLIST_H +#define APR_RESLIST_H + +/** + * @file apr_reslist.h + * @brief APR-UTIL Resource List Routines + */ + +#include "apr.h" +#include "apu.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_time.h" + +/** + * @defgroup APR_Util_RL Resource List Routines + * @ingroup APR_Util + * @{ + */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** Opaque resource list object */ +typedef struct apr_reslist_t apr_reslist_t; + +/* Generic constructor called by resource list when it needs to create a + * resource. + * @param resource opaque resource + * @param params flags + * @param pool Pool + */ +typedef apr_status_t (*apr_reslist_constructor)(void **resource, void *params, + apr_pool_t *pool); + +/* Generic destructor called by resource list when it needs to destroy a + * resource. + * @param resource opaque resource + * @param params flags + * @param pool Pool + */ +typedef apr_status_t (*apr_reslist_destructor)(void *resource, void *params, + apr_pool_t *pool); + +/* Cleanup order modes */ +#define APR_RESLIST_CLEANUP_DEFAULT 0 /**< default pool cleanup */ +#define APR_RESLIST_CLEANUP_FIRST 1 /**< use pool pre cleanup */ + +/** + * Create a new resource list with the following parameters: + * @param reslist An address where the pointer to the new resource + * list will be stored. + * @param min Allowed minimum number of available resources. Zero + * creates new resources only when needed. + * @param smax Resources will be destroyed during reslist maintenance to + * meet this maximum restriction as they expire (reach their ttl). + * @param hmax Absolute maximum limit on the number of total resources. + * @param ttl If non-zero, sets the maximum amount of time in microseconds an + * unused resource is valid. Any resource which has exceeded this + * time will be destroyed, either when encountered by + * apr_reslist_acquire() or during reslist maintenance. + * @param con Constructor routine that is called to create a new resource. + * @param de Destructor routine that is called to destroy an expired resource. + * @param params Passed to constructor and deconstructor + * @param pool The pool from which to create this resource list. Also the + * same pool that is passed to the constructor and destructor + * routines. + * @remark If APR has been compiled without thread support, hmax will be + * automatically set to 1 and values of min and smax will be forced to + * 1 for any non-zero value. + */ +APU_DECLARE(apr_status_t) apr_reslist_create(apr_reslist_t **reslist, + int min, int smax, int hmax, + apr_interval_time_t ttl, + apr_reslist_constructor con, + apr_reslist_destructor de, + void *params, + apr_pool_t *pool); + +/** + * Destroy the given resource list and all resources controlled by + * this list. + * FIXME: Should this block until all resources become available, + * or maybe just destroy all the free ones, or maybe destroy + * them even though they might be in use by something else? + * Currently it will abort if there are resources that haven't + * been released, so there is an assumption that all resources + * have been released to the list before calling this function. + * @param reslist The reslist to destroy + */ +APU_DECLARE(apr_status_t) apr_reslist_destroy(apr_reslist_t *reslist); + +/** + * Retrieve a resource from the list, creating a new one if necessary. + * If we have met our maximum number of resources, we will block + * until one becomes available. + * @param reslist The resource list. + * @param resource An address where the pointer to the resource + * will be stored. + */ +APU_DECLARE(apr_status_t) apr_reslist_acquire(apr_reslist_t *reslist, + void **resource); + +/** + * Return a resource back to the list of available resources. + * @param reslist The resource list. + * @param resource The resource to return to the list. + */ +APU_DECLARE(apr_status_t) apr_reslist_release(apr_reslist_t *reslist, + void *resource); + +/** + * Set the timeout the acquire will wait for a free resource + * when the maximum number of resources is exceeded. + * @param reslist The resource list. + * @param timeout Timeout to wait. The zero waits forever. + */ +APU_DECLARE(void) apr_reslist_timeout_set(apr_reslist_t *reslist, + apr_interval_time_t timeout); + +/** + * Return the number of outstanding resources. + * @param reslist The resource list. + */ +APU_DECLARE(apr_uint32_t) apr_reslist_acquired_count(apr_reslist_t *reslist); + +/** + * Invalidate a resource in the pool - e.g. a database connection + * that returns a "lost connection" error and can't be restored. + * Use this instead of apr_reslist_release if the resource is bad. + * @param reslist The resource list. + * @param resource The resource to invalidate. + */ +APU_DECLARE(apr_status_t) apr_reslist_invalidate(apr_reslist_t *reslist, + void *resource); + +/** + * Perform routine maintenance on the resource list. This call + * may instantiate new resources or expire old resources. + * @param reslist The resource list. + */ +APU_DECLARE(apr_status_t) apr_reslist_maintain(apr_reslist_t *reslist); + +/** + * Set reslist cleanup order. + * @param reslist The resource list. + * @param mode Cleanup order mode + *
+ *           APR_RESLIST_CLEANUP_DEFAULT  default pool cleanup order
+ *           APR_RESLIST_CLEANUP_FIRST    use pool pre cleanup
+ * 
+ * @remark If APR_RESLIST_CLEANUP_FIRST is used the destructors will + * be called before child pools of the pool used to create the reslist + * are destroyed. This allows to explicitly destroy the child pools + * inside reslist destructors. + */ +APU_DECLARE(void) apr_reslist_cleanup_order_set(apr_reslist_t *reslist, + apr_uint32_t mode); + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif /* ! APR_RESLIST_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_ring.h b/c/dependencies/windows/apr/x86/include/apr_ring.h new file mode 100644 index 00000000..eec735fc --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_ring.h @@ -0,0 +1,513 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * This code draws heavily from the 4.4BSD macros + * and Dean Gaudet's "splim/ring.h". + * + * + * + * We'd use Dean's code directly if we could guarantee the + * availability of inline functions. + */ + +#ifndef APR_RING_H +#define APR_RING_H + +/** + * @file apr_ring.h + * @brief APR Rings + */ + +/* + * for offsetof() + */ +#include "apr_general.h" + +/** + * @defgroup apr_ring Ring Macro Implementations + * @ingroup APR + * A ring is a kind of doubly-linked list that can be manipulated + * without knowing where its head is. + * @{ + */ + +/** + * The Ring Element + * + * A ring element struct is linked to the other elements in the ring + * through its ring entry field, e.g. + *
+ *      struct my_element_t {
+ *          APR_RING_ENTRY(my_element_t) link;
+ *          int foo;
+ *          char *bar;
+ *      };
+ * 
+ * + * An element struct may be put on more than one ring if it has more + * than one APR_RING_ENTRY field. Each APR_RING_ENTRY has a corresponding + * APR_RING_HEAD declaration. + * + * @warning For strict C standards compliance you should put the APR_RING_ENTRY + * first in the element struct unless the head is always part of a larger + * object with enough earlier fields to accommodate the offsetof() used + * to compute the ring sentinel below. You can usually ignore this caveat. + */ +#define APR_RING_ENTRY(elem) \ + struct { \ + struct elem * volatile next; \ + struct elem * volatile prev; \ + } + +/** + * The Ring Head + * + * Each ring is managed via its head, which is a struct declared like this: + *
+ *      APR_RING_HEAD(my_ring_t, my_element_t);
+ *      struct my_ring_t ring, *ringp;
+ * 
+ * + * This struct looks just like the element link struct so that we can + * be sure that the typecasting games will work as expected. + * + * The first element in the ring is next after the head, and the last + * element is just before the head. + */ +#define APR_RING_HEAD(head, elem) \ + struct head { \ + struct elem * volatile next; \ + struct elem * volatile prev; \ + } + +/** + * The Ring Sentinel + * + * This is the magic pointer value that occurs before the first and + * after the last elements in the ring, computed from the address of + * the ring's head. The head itself isn't an element, but in order to + * get rid of all the special cases when dealing with the ends of the + * ring, we play typecasting games to make it look like one. + * + * Here is a diagram to illustrate the arrangements of the next and + * prev pointers of each element in a single ring. Note that they point + * to the start of each element, not to the APR_RING_ENTRY structure. + * + *
+ *     +->+------+<-+  +->+------+<-+  +->+------+<-+
+ *     |  |struct|  |  |  |struct|  |  |  |struct|  |
+ *    /   | elem |   \/   | elem |   \/   | elem |  \
+ * ...    |      |   /\   |      |   /\   |      |   ...
+ *        +------+  |  |  +------+  |  |  +------+
+ *   ...--|prev  |  |  +--|ring  |  |  +--|prev  |
+ *        |  next|--+     | entry|--+     |  next|--...
+ *        +------+        +------+        +------+
+ *        | etc. |        | etc. |        | etc. |
+ *        :      :        :      :        :      :
+ * 
+ * + * The APR_RING_HEAD is nothing but a bare APR_RING_ENTRY. The prev + * and next pointers in the first and last elements don't actually + * point to the head, they point to a phantom place called the + * sentinel. Its value is such that last->next->next == first because + * the offset from the sentinel to the head's next pointer is the same + * as the offset from the start of an element to its next pointer. + * This also works in the opposite direction. + * + *
+ *        last                            first
+ *     +->+------+<-+  +->sentinel<-+  +->+------+<-+
+ *     |  |struct|  |  |            |  |  |struct|  |
+ *    /   | elem |   \/              \/   | elem |  \
+ * ...    |      |   /\              /\   |      |   ...
+ *        +------+  |  |  +------+  |  |  +------+
+ *   ...--|prev  |  |  +--|ring  |  |  +--|prev  |
+ *        |  next|--+     |  head|--+     |  next|--...
+ *        +------+        +------+        +------+
+ *        | etc. |                        | etc. |
+ *        :      :                        :      :
+ * 
+ * + * Note that the offset mentioned above is different for each kind of + * ring that the element may be on, and each kind of ring has a unique + * name for its APR_RING_ENTRY in each element, and has its own type + * for its APR_RING_HEAD. + * + * Note also that if the offset is non-zero (which is required if an + * element has more than one APR_RING_ENTRY), the unreality of the + * sentinel may have bad implications on very perverse implementations + * of C -- see the warning in APR_RING_ENTRY. + * + * @param hp The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SENTINEL(hp, elem, link) \ + (struct elem *)((char *)(&(hp)->next) - APR_OFFSETOF(struct elem, link)) + +/** + * The first element of the ring + * @param hp The head of the ring + */ +#define APR_RING_FIRST(hp) (hp)->next +/** + * The last element of the ring + * @param hp The head of the ring + */ +#define APR_RING_LAST(hp) (hp)->prev +/** + * The next element in the ring + * @param ep The current element + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_NEXT(ep, link) (ep)->link.next +/** + * The previous element in the ring + * @param ep The current element + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_PREV(ep, link) (ep)->link.prev + + +/** + * Initialize a ring + * @param hp The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INIT(hp, elem, link) do { \ + APR_RING_FIRST((hp)) = APR_RING_SENTINEL((hp), elem, link); \ + APR_RING_LAST((hp)) = APR_RING_SENTINEL((hp), elem, link); \ + } while (0) + +/** + * Determine if a ring is empty + * @param hp The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + * @return true or false + */ +#define APR_RING_EMPTY(hp, elem, link) \ + (APR_RING_FIRST((hp)) == APR_RING_SENTINEL((hp), elem, link)) + +/** + * Initialize a singleton element + * @param ep The element + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_ELEM_INIT(ep, link) do { \ + APR_RING_NEXT((ep), link) = (ep); \ + APR_RING_PREV((ep), link) = (ep); \ + } while (0) + + +/** + * Splice the sequence ep1..epN into the ring before element lep + * (..lep.. becomes ..ep1..epN..lep..) + * @warning This doesn't work for splicing before the first element or on + * empty rings... see APR_RING_SPLICE_HEAD for one that does + * @param lep Element in the ring to splice before + * @param ep1 First element in the sequence to splice in + * @param epN Last element in the sequence to splice in + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SPLICE_BEFORE(lep, ep1, epN, link) do { \ + APR_RING_NEXT((epN), link) = (lep); \ + APR_RING_PREV((ep1), link) = APR_RING_PREV((lep), link); \ + APR_RING_NEXT(APR_RING_PREV((lep), link), link) = (ep1); \ + APR_RING_PREV((lep), link) = (epN); \ + } while (0) + +/** + * Splice the sequence ep1..epN into the ring after element lep + * (..lep.. becomes ..lep..ep1..epN..) + * @warning This doesn't work for splicing after the last element or on + * empty rings... see APR_RING_SPLICE_TAIL for one that does + * @param lep Element in the ring to splice after + * @param ep1 First element in the sequence to splice in + * @param epN Last element in the sequence to splice in + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SPLICE_AFTER(lep, ep1, epN, link) do { \ + APR_RING_PREV((ep1), link) = (lep); \ + APR_RING_NEXT((epN), link) = APR_RING_NEXT((lep), link); \ + APR_RING_PREV(APR_RING_NEXT((lep), link), link) = (epN); \ + APR_RING_NEXT((lep), link) = (ep1); \ + } while (0) + +/** + * Insert the element nep into the ring before element lep + * (..lep.. becomes ..nep..lep..) + * @warning This doesn't work for inserting before the first element or on + * empty rings... see APR_RING_INSERT_HEAD for one that does + * @param lep Element in the ring to insert before + * @param nep Element to insert + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INSERT_BEFORE(lep, nep, link) \ + APR_RING_SPLICE_BEFORE((lep), (nep), (nep), link) + +/** + * Insert the element nep into the ring after element lep + * (..lep.. becomes ..lep..nep..) + * @warning This doesn't work for inserting after the last element or on + * empty rings... see APR_RING_INSERT_TAIL for one that does + * @param lep Element in the ring to insert after + * @param nep Element to insert + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INSERT_AFTER(lep, nep, link) \ + APR_RING_SPLICE_AFTER((lep), (nep), (nep), link) + + +/** + * Splice the sequence ep1..epN into the ring before the first element + * (..hp.. becomes ..hp..ep1..epN..) + * @param hp Head of the ring + * @param ep1 First element in the sequence to splice in + * @param epN Last element in the sequence to splice in + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SPLICE_HEAD(hp, ep1, epN, elem, link) \ + APR_RING_SPLICE_AFTER(APR_RING_SENTINEL((hp), elem, link), \ + (ep1), (epN), link) + +/** + * Splice the sequence ep1..epN into the ring after the last element + * (..hp.. becomes ..ep1..epN..hp..) + * @param hp Head of the ring + * @param ep1 First element in the sequence to splice in + * @param epN Last element in the sequence to splice in + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SPLICE_TAIL(hp, ep1, epN, elem, link) \ + APR_RING_SPLICE_BEFORE(APR_RING_SENTINEL((hp), elem, link), \ + (ep1), (epN), link) + +/** + * Insert the element nep into the ring before the first element + * (..hp.. becomes ..hp..nep..) + * @param hp Head of the ring + * @param nep Element to insert + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INSERT_HEAD(hp, nep, elem, link) \ + APR_RING_SPLICE_HEAD((hp), (nep), (nep), elem, link) + +/** + * Insert the element nep into the ring after the last element + * (..hp.. becomes ..nep..hp..) + * @param hp Head of the ring + * @param nep Element to insert + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INSERT_TAIL(hp, nep, elem, link) \ + APR_RING_SPLICE_TAIL((hp), (nep), (nep), elem, link) + +/** + * Concatenate ring h2 onto the end of ring h1, leaving h2 empty. + * @param h1 Head of the ring to concatenate onto + * @param h2 Head of the ring to concatenate + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_CONCAT(h1, h2, elem, link) do { \ + if (!APR_RING_EMPTY((h2), elem, link)) { \ + APR_RING_SPLICE_BEFORE(APR_RING_SENTINEL((h1), elem, link), \ + APR_RING_FIRST((h2)), \ + APR_RING_LAST((h2)), link); \ + APR_RING_INIT((h2), elem, link); \ + } \ + } while (0) + +/** + * Prepend ring h2 onto the beginning of ring h1, leaving h2 empty. + * @param h1 Head of the ring to prepend onto + * @param h2 Head of the ring to prepend + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_PREPEND(h1, h2, elem, link) do { \ + if (!APR_RING_EMPTY((h2), elem, link)) { \ + APR_RING_SPLICE_AFTER(APR_RING_SENTINEL((h1), elem, link), \ + APR_RING_FIRST((h2)), \ + APR_RING_LAST((h2)), link); \ + APR_RING_INIT((h2), elem, link); \ + } \ + } while (0) + +/** + * Unsplice a sequence of elements from a ring + * @warning The unspliced sequence is left with dangling pointers at either end + * @param ep1 First element in the sequence to unsplice + * @param epN Last element in the sequence to unsplice + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_UNSPLICE(ep1, epN, link) do { \ + APR_RING_NEXT(APR_RING_PREV((ep1), link), link) = \ + APR_RING_NEXT((epN), link); \ + APR_RING_PREV(APR_RING_NEXT((epN), link), link) = \ + APR_RING_PREV((ep1), link); \ + } while (0) + +/** + * Remove a single element from a ring + * @warning The unspliced element is left with dangling pointers at either end + * @param ep Element to remove + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_REMOVE(ep, link) \ + APR_RING_UNSPLICE((ep), (ep), link) + +/** + * Iterate over a ring + * @param ep The current element + * @param head The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_FOREACH(ep, head, elem, link) \ + for (ep = APR_RING_FIRST(head); \ + ep != APR_RING_SENTINEL(head, elem, link); \ + ep = APR_RING_NEXT(ep, link)) + +/** + * Iterate over a ring safe against removal of the current element + * @param ep1 The current element + * @param ep2 Iteration cursor + * @param head The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_FOREACH_SAFE(ep1, ep2, head, elem, link) \ + for (ep1 = APR_RING_FIRST(head), ep2 = APR_RING_NEXT(ep1, link); \ + ep1 != APR_RING_SENTINEL(head, elem, link); \ + ep1 = ep2, ep2 = APR_RING_NEXT(ep1, link)) + +/* Debugging tools: */ + +#ifdef APR_RING_DEBUG +#include +#include + +#define APR_RING_CHECK_ONE(msg, ptr) \ + fprintf(stderr, "*** %s %p\n", msg, ptr) + +#define APR_RING_CHECK(hp, elem, link, msg) \ + APR_RING_CHECK_ELEM(APR_RING_SENTINEL(hp, elem, link), elem, link, msg) + +#define APR_RING_CHECK_ELEM(ep, elem, link, msg) do { \ + struct elem *start = (ep); \ + struct elem *here = start; \ + fprintf(stderr, "*** ring check start -- %s\n", msg); \ + do { \ + fprintf(stderr, "\telem %p\n", here); \ + fprintf(stderr, "\telem->next %p\n", \ + APR_RING_NEXT(here, link)); \ + fprintf(stderr, "\telem->prev %p\n", \ + APR_RING_PREV(here, link)); \ + fprintf(stderr, "\telem->next->prev %p\n", \ + APR_RING_PREV(APR_RING_NEXT(here, link), link)); \ + fprintf(stderr, "\telem->prev->next %p\n", \ + APR_RING_NEXT(APR_RING_PREV(here, link), link)); \ + if (APR_RING_PREV(APR_RING_NEXT(here, link), link) != here) { \ + fprintf(stderr, "\t*** elem->next->prev != elem\n"); \ + break; \ + } \ + if (APR_RING_NEXT(APR_RING_PREV(here, link), link) != here) { \ + fprintf(stderr, "\t*** elem->prev->next != elem\n"); \ + break; \ + } \ + here = APR_RING_NEXT(here, link); \ + } while (here != start); \ + fprintf(stderr, "*** ring check end\n"); \ + } while (0) + +#define APR_RING_CHECK_CONSISTENCY(hp, elem, link) \ + APR_RING_CHECK_ELEM_CONSISTENCY(APR_RING_SENTINEL(hp, elem, link),\ + elem, link) + +#define APR_RING_CHECK_ELEM_CONSISTENCY(ep, elem, link) do { \ + struct elem *start = (ep); \ + struct elem *here = start; \ + do { \ + assert(APR_RING_PREV(APR_RING_NEXT(here, link), link) == here); \ + assert(APR_RING_NEXT(APR_RING_PREV(here, link), link) == here); \ + here = APR_RING_NEXT(here, link); \ + } while (here != start); \ + } while (0) + +#else +/** + * Print a single pointer value to STDERR + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param msg Descriptive message + * @param ptr Pointer value to print + */ +#define APR_RING_CHECK_ONE(msg, ptr) +/** + * Dump all ring pointers to STDERR, starting with the head and looping all + * the way around the ring back to the head. Aborts if an inconsistency + * is found. + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param hp Head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + * @param msg Descriptive message + */ +#define APR_RING_CHECK(hp, elem, link, msg) +/** + * Loops around a ring and checks all the pointers for consistency. Pops + * an assertion if any inconsistency is found. Same idea as APR_RING_CHECK() + * except that it's silent if all is well. + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param hp Head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_CHECK_CONSISTENCY(hp, elem, link) +/** + * Dump all ring pointers to STDERR, starting with the given element and + * looping all the way around the ring back to that element. Aborts if + * an inconsistency is found. + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param ep The element + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + * @param msg Descriptive message + */ +#define APR_RING_CHECK_ELEM(ep, elem, link, msg) +/** + * Loops around a ring, starting with the given element, and checks all + * the pointers for consistency. Pops an assertion if any inconsistency + * is found. Same idea as APR_RING_CHECK_ELEM() except that it's silent + * if all is well. + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param ep The element + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_CHECK_ELEM_CONSISTENCY(ep, elem, link) +#endif + +/** @} */ + +#endif /* !APR_RING_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_rmm.h b/c/dependencies/windows/apr/x86/include/apr_rmm.h new file mode 100644 index 00000000..976fe9c5 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_rmm.h @@ -0,0 +1,137 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_RMM_H +#define APR_RMM_H +/** + * @file apr_rmm.h + * @brief APR-UTIL Relocatable Memory Management Routines + */ +/** + * @defgroup APR_Util_RMM Relocatable Memory Management Routines + * @ingroup APR_Util + * @{ + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apu.h" +#include "apr_anylock.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** Structure to access Relocatable, Managed Memory */ +typedef struct apr_rmm_t apr_rmm_t; + +/** Fundamental allocation unit, within a specific apr_rmm_t */ +typedef apr_size_t apr_rmm_off_t; + +/** + * Initialize a relocatable memory block to be managed by the apr_rmm API. + * @param rmm The relocatable memory block + * @param lock An apr_anylock_t of the appropriate type of lock, or NULL + * if no locking is required. + * @param membuf The block of relocatable memory to be managed + * @param memsize The size of relocatable memory block to be managed + * @param cont The pool to use for local storage and management + * @remark Both @param membuf and @param memsize must be aligned + * (for instance using APR_ALIGN_DEFAULT). + */ +APU_DECLARE(apr_status_t) apr_rmm_init(apr_rmm_t **rmm, apr_anylock_t *lock, + void *membuf, apr_size_t memsize, + apr_pool_t *cont); + +/** + * Destroy a managed memory block. + * @param rmm The relocatable memory block to destroy + */ +APU_DECLARE(apr_status_t) apr_rmm_destroy(apr_rmm_t *rmm); + +/** + * Attach to a relocatable memory block already managed by the apr_rmm API. + * @param rmm The relocatable memory block + * @param lock An apr_anylock_t of the appropriate type of lock + * @param membuf The block of relocatable memory already under management + * @param cont The pool to use for local storage and management + */ +APU_DECLARE(apr_status_t) apr_rmm_attach(apr_rmm_t **rmm, apr_anylock_t *lock, + void *membuf, apr_pool_t *cont); + +/** + * Detach from the managed block of memory. + * @param rmm The relocatable memory block to detach from + */ +APU_DECLARE(apr_status_t) apr_rmm_detach(apr_rmm_t *rmm); + +/** + * Allocate memory from the block of relocatable memory. + * @param rmm The relocatable memory block + * @param reqsize How much memory to allocate + */ +APU_DECLARE(apr_rmm_off_t) apr_rmm_malloc(apr_rmm_t *rmm, apr_size_t reqsize); + +/** + * Realloc memory from the block of relocatable memory. + * @param rmm The relocatable memory block + * @param entity The memory allocation to realloc + * @param reqsize The new size + */ +APU_DECLARE(apr_rmm_off_t) apr_rmm_realloc(apr_rmm_t *rmm, void *entity, apr_size_t reqsize); + +/** + * Allocate memory from the block of relocatable memory and initialize it to zero. + * @param rmm The relocatable memory block + * @param reqsize How much memory to allocate + */ +APU_DECLARE(apr_rmm_off_t) apr_rmm_calloc(apr_rmm_t *rmm, apr_size_t reqsize); + +/** + * Free allocation returned by apr_rmm_malloc or apr_rmm_calloc. + * @param rmm The relocatable memory block + * @param entity The memory allocation to free + */ +APU_DECLARE(apr_status_t) apr_rmm_free(apr_rmm_t *rmm, apr_rmm_off_t entity); + +/** + * Retrieve the physical address of a relocatable allocation of memory + * @param rmm The relocatable memory block + * @param entity The memory allocation to free + * @return address The address, aligned with APR_ALIGN_DEFAULT. + */ +APU_DECLARE(void *) apr_rmm_addr_get(apr_rmm_t *rmm, apr_rmm_off_t entity); + +/** + * Compute the offset of a relocatable allocation of memory + * @param rmm The relocatable memory block + * @param entity The physical address to convert to an offset + */ +APU_DECLARE(apr_rmm_off_t) apr_rmm_offset_get(apr_rmm_t *rmm, void *entity); + +/** + * Compute the required overallocation of memory needed to fit n allocs + * @param n The number of alloc/calloc regions desired + */ +APU_DECLARE(apr_size_t) apr_rmm_overhead_get(int n); + +#ifdef __cplusplus +} +#endif +/** @} */ +#endif /* ! APR_RMM_H */ + diff --git a/c/dependencies/windows/apr/x86/include/apr_sdbm.h b/c/dependencies/windows/apr/x86/include/apr_sdbm.h new file mode 100644 index 00000000..5759508b --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_sdbm.h @@ -0,0 +1,176 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * sdbm - ndbm work-alike hashed database library + * based on Per-Ake Larson's Dynamic Hashing algorithms. BIT 18 (1978). + * author: oz@nexus.yorku.ca + * status: ex-public domain + */ + +#ifndef APR_SDBM_H +#define APR_SDBM_H + +#include "apu.h" +#include "apr_errno.h" +#include "apr_file_io.h" /* for apr_fileperms_t */ + +/** + * @file apr_sdbm.h + * @brief apr-util SDBM library + */ +/** + * @defgroup APR_Util_DBM_SDBM SDBM library + * @ingroup APR_Util_DBM + * @{ + */ + +/** + * Structure for referencing an sdbm + */ +typedef struct apr_sdbm_t apr_sdbm_t; + +/** + * Structure for referencing the datum record within an sdbm + */ +typedef struct { + /** pointer to the data stored/retrieved */ + char *dptr; + /** size of data */ + /* apr_ssize_t for release 2.0??? */ + int dsize; +} apr_sdbm_datum_t; + +/* The extensions used for the database files */ +/** SDBM Directory file extension */ +#define APR_SDBM_DIRFEXT ".dir" +/** SDBM page file extension */ +#define APR_SDBM_PAGFEXT ".pag" + +/* flags to sdbm_store */ +#define APR_SDBM_INSERT 0 /**< Insert */ +#define APR_SDBM_REPLACE 1 /**< Replace */ +#define APR_SDBM_INSERTDUP 2 /**< Insert with duplicates */ + +/** + * Open an sdbm database by file name + * @param db The newly opened database + * @param name The sdbm file to open + * @param mode The flag values (APR_READ and APR_BINARY flags are implicit) + *
+ *           APR_WRITE          open for read-write access
+ *           APR_CREATE         create the sdbm if it does not exist
+ *           APR_TRUNCATE       empty the contents of the sdbm
+ *           APR_EXCL           fail for APR_CREATE if the file exists
+ *           APR_DELONCLOSE     delete the sdbm when closed
+ *           APR_SHARELOCK      support locking across process/machines
+ * 
+ * @param perms Permissions to apply to if created + * @param p The pool to use when creating the sdbm + * @remark The sdbm name is not a true file name, as sdbm appends suffixes + * for seperate data and index files. + */ +APU_DECLARE(apr_status_t) apr_sdbm_open(apr_sdbm_t **db, const char *name, + apr_int32_t mode, + apr_fileperms_t perms, apr_pool_t *p); + +/** + * Close an sdbm file previously opened by apr_sdbm_open + * @param db The database to close + */ +APU_DECLARE(apr_status_t) apr_sdbm_close(apr_sdbm_t *db); + +/** + * Lock an sdbm database for concurency of multiple operations + * @param db The database to lock + * @param type The lock type + *
+ *           APR_FLOCK_SHARED
+ *           APR_FLOCK_EXCLUSIVE
+ * 
+ * @remark Calls to apr_sdbm_lock may be nested. All apr_sdbm functions + * perform implicit locking. Since an APR_FLOCK_SHARED lock cannot be + * portably promoted to an APR_FLOCK_EXCLUSIVE lock, apr_sdbm_store and + * apr_sdbm_delete calls will fail if an APR_FLOCK_SHARED lock is held. + * The apr_sdbm_lock call requires the database to be opened with the + * APR_SHARELOCK mode value. + */ +APU_DECLARE(apr_status_t) apr_sdbm_lock(apr_sdbm_t *db, int type); + +/** + * Release an sdbm lock previously aquired by apr_sdbm_lock + * @param db The database to unlock + */ +APU_DECLARE(apr_status_t) apr_sdbm_unlock(apr_sdbm_t *db); + +/** + * Fetch an sdbm record value by key + * @param db The database + * @param value The value datum retrieved for this record + * @param key The key datum to find this record + */ +APU_DECLARE(apr_status_t) apr_sdbm_fetch(apr_sdbm_t *db, + apr_sdbm_datum_t *value, + apr_sdbm_datum_t key); + +/** + * Store an sdbm record value by key + * @param db The database + * @param key The key datum to store this record by + * @param value The value datum to store in this record + * @param opt The method used to store the record + *
+ *           APR_SDBM_INSERT     return an error if the record exists
+ *           APR_SDBM_REPLACE    overwrite any existing record for key
+ * 
+ */ +APU_DECLARE(apr_status_t) apr_sdbm_store(apr_sdbm_t *db, apr_sdbm_datum_t key, + apr_sdbm_datum_t value, int opt); + +/** + * Delete an sdbm record value by key + * @param db The database + * @param key The key datum of the record to delete + * @remark It is not an error to delete a non-existent record. + */ +APU_DECLARE(apr_status_t) apr_sdbm_delete(apr_sdbm_t *db, + const apr_sdbm_datum_t key); + +/** + * Retrieve the first record key from a dbm + * @param db The database + * @param key The key datum of the first record + * @remark The keys returned are not ordered. To traverse the list of keys + * for an sdbm opened with APR_SHARELOCK, the caller must use apr_sdbm_lock + * prior to retrieving the first record, and hold the lock until after the + * last call to apr_sdbm_nextkey. + */ +APU_DECLARE(apr_status_t) apr_sdbm_firstkey(apr_sdbm_t *db, apr_sdbm_datum_t *key); + +/** + * Retrieve the next record key from an sdbm + * @param db The database + * @param key The key datum of the next record + */ +APU_DECLARE(apr_status_t) apr_sdbm_nextkey(apr_sdbm_t *db, apr_sdbm_datum_t *key); + +/** + * Returns true if the sdbm database opened for read-only access + * @param db The database to test + */ +APU_DECLARE(int) apr_sdbm_rdonly(apr_sdbm_t *db); +/** @} */ +#endif /* APR_SDBM_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_sha1.h b/c/dependencies/windows/apr/x86/include/apr_sha1.h new file mode 100644 index 00000000..2a4edf36 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_sha1.h @@ -0,0 +1,121 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* NIST Secure Hash Algorithm + * heavily modified by Uwe Hollerbach uh@alumni.caltech edu + * from Peter C. Gutmann's implementation as found in + * Applied Cryptography by Bruce Schneier + * This code is hereby placed in the public domain + */ + +#ifndef APR_SHA1_H +#define APR_SHA1_H + +#include "apu.h" +#include "apr_general.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_sha1.h + * @brief APR-UTIL SHA1 library + */ + +/** size of the SHA1 DIGEST */ +#define APR_SHA1_DIGESTSIZE 20 + +/** + * Define the Magic String prefix that identifies a password as being + * hashed using our algorithm. + */ +#define APR_SHA1PW_ID "{SHA}" + +/** length of the SHA Password */ +#define APR_SHA1PW_IDLEN 5 + +/** @see apr_sha1_ctx_t */ +typedef struct apr_sha1_ctx_t apr_sha1_ctx_t; + +/** + * SHA1 context structure + */ +struct apr_sha1_ctx_t { + /** message digest */ + apr_uint32_t digest[5]; + /** 64-bit bit counts */ + apr_uint32_t count_lo, count_hi; + /** SHA data buffer */ + apr_uint32_t data[16]; + /** unprocessed amount in data */ + int local; +}; + +/** + * Provide a means to SHA1 crypt/encode a plaintext password in a way which + * makes password file compatible with those commonly use in netscape web + * and ldap installations. + * @param clear The plaintext password + * @param len The length of the plaintext password + * @param out The encrypted/encoded password + * @note SHA1 support is useful for migration purposes, but is less + * secure than Apache's password format, since Apache's (MD5) + * password format uses a random eight character salt to generate + * one of many possible hashes for the same password. Netscape + * uses plain SHA1 without a salt, so the same password + * will always generate the same hash, making it easier + * to break since the search space is smaller. + */ +APU_DECLARE(void) apr_sha1_base64(const char *clear, int len, char *out); + +/** + * Initialize the SHA digest + * @param context The SHA context to initialize + */ +APU_DECLARE(void) apr_sha1_init(apr_sha1_ctx_t *context); + +/** + * Update the SHA digest + * @param context The SHA1 context to update + * @param input The buffer to add to the SHA digest + * @param inputLen The length of the input buffer + */ +APU_DECLARE(void) apr_sha1_update(apr_sha1_ctx_t *context, const char *input, + unsigned int inputLen); + +/** + * Update the SHA digest with binary data + * @param context The SHA1 context to update + * @param input The buffer to add to the SHA digest + * @param inputLen The length of the input buffer + */ +APU_DECLARE(void) apr_sha1_update_binary(apr_sha1_ctx_t *context, + const unsigned char *input, + unsigned int inputLen); + +/** + * Finish computing the SHA digest + * @param digest the output buffer in which to store the digest + * @param context The context to finalize + */ +APU_DECLARE(void) apr_sha1_final(unsigned char digest[APR_SHA1_DIGESTSIZE], + apr_sha1_ctx_t *context); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_SHA1_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_shm.h b/c/dependencies/windows/apr/x86/include/apr_shm.h new file mode 100644 index 00000000..635c654b --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_shm.h @@ -0,0 +1,229 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_SHM_H +#define APR_SHM_H + +/** + * @file apr_shm.h + * @brief APR Shared Memory Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_perms_set.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_shm Shared Memory Routines + * @ingroup APR + * @{ + */ + +/** + * Private, platform-specific data struture representing a shared memory + * segment. + */ +typedef struct apr_shm_t apr_shm_t; + +/** + * Create and make accessible a shared memory segment with default + * properties. + * @param m The shared memory structure to create. + * @param reqsize The desired size of the segment. + * @param filename The file to use for shared memory on platforms that + * require it. + * @param pool the pool from which to allocate the shared memory + * structure. + * @remark A note about Anonymous vs. Named shared memory segments: + * Not all plaforms support anonymous shared memory segments, but in + * some cases it is prefered over other types of shared memory + * implementations. Passing a NULL 'file' parameter to this function + * will cause the subsystem to use anonymous shared memory segments. + * If such a system is not available, APR_ENOTIMPL is returned. + * @remark A note about allocation sizes: + * On some platforms it is necessary to store some metainformation + * about the segment within the actual segment. In order to supply + * the caller with the requested size it may be necessary for the + * implementation to request a slightly greater segment length + * from the subsystem. In all cases, the apr_shm_baseaddr_get() + * function will return the first usable byte of memory. + * + */ +APR_DECLARE(apr_status_t) apr_shm_create(apr_shm_t **m, + apr_size_t reqsize, + const char *filename, + apr_pool_t *pool); + +/** + * Special processing flags for apr_shm_create_ex() and apr_shm_attach_ex(). + */ +#define APR_SHM_NS_LOCAL 1 /* Create or attach to named shared memory + * segment in the "Local" namespace on + * Windows. (Ignored on other platforms.) + * By default, the "Global" namespace is + * used for privileged processes and the + * "Local" namespace is used otherwise. + */ +#define APR_SHM_NS_GLOBAL 2 /* Create or attach to named shared memory + * segment in the "Global" namespace on + * Windows. (Ignored on other platforms.) + */ + +/** + * Create and make accessible a shared memory segment with platform- + * specific processing. + * @param m The shared memory structure to create. + * @param reqsize The desired size of the segment. + * @param filename The file to use for shared memory on platforms that + * require it. + * @param pool the pool from which to allocate the shared memory + * structure. + * @param flags mask of APR_SHM_* (defined above) + * @remark A note about Anonymous vs. Named shared memory segments: + * Not all plaforms support anonymous shared memory segments, but in + * some cases it is prefered over other types of shared memory + * implementations. Passing a NULL 'file' parameter to this function + * will cause the subsystem to use anonymous shared memory segments. + * If such a system is not available, APR_ENOTIMPL is returned. + * @remark A note about allocation sizes: + * On some platforms it is necessary to store some metainformation + * about the segment within the actual segment. In order to supply + * the caller with the requested size it may be necessary for the + * implementation to request a slightly greater segment length + * from the subsystem. In all cases, the apr_shm_baseaddr_get() + * function will return the first usable byte of memory. + * + */ +APR_DECLARE(apr_status_t) apr_shm_create_ex(apr_shm_t **m, + apr_size_t reqsize, + const char *filename, + apr_pool_t *pool, + apr_int32_t flags); + +/** + * Remove named resource associated with a shared memory segment, + * preventing attachments to the resource, but not destroying it. + * @param filename The filename associated with shared-memory segment which + * needs to be removed + * @param pool The pool used for file operations + * @remark This function is only supported on platforms which support + * name-based shared memory segments, and will return APR_ENOTIMPL on + * platforms without such support. Removing the file while the shm + * is in use is not entirely portable, caller may use this to enhance + * obscurity of the resource, but be prepared for the call to fail, + * and for concurrent attempts to create a resource of the same name + * to also fail. The pool cleanup of apr_shm_create (apr_shm_destroy) + * also removes the named resource. + */ +APR_DECLARE(apr_status_t) apr_shm_remove(const char *filename, + apr_pool_t *pool); + +/** + * Delete named resource associated with a shared memory segment, + * preventing attachments to the resource. + * @param m The shared memory segment structure to delete. + * @remark This function is only supported on platforms which support + * name-based shared memory segments, and will return APR_ENOTIMPL on + * platforms without such support. Removing the file while the shm + * is in use is not entirely portable, caller may use this to enhance + * obscurity of the resource, but be prepared for the call to fail, + * and for concurrent attempts to create a resource of the same name + * to also fail. The pool cleanup of apr_shm_create (apr_shm_destroy) + * also removes the named resource. + */ +APR_DECLARE(apr_status_t) apr_shm_delete(apr_shm_t *m); + +/** + * Destroy a shared memory segment and associated memory. + * @param m The shared memory segment structure to destroy. + */ +APR_DECLARE(apr_status_t) apr_shm_destroy(apr_shm_t *m); + +/** + * Attach to a shared memory segment that was created + * by another process. + * @param m The shared memory structure to create. + * @param filename The file used to create the original segment. + * (This MUST match the original filename.) + * @param pool the pool from which to allocate the shared memory + * structure for this process. + */ +APR_DECLARE(apr_status_t) apr_shm_attach(apr_shm_t **m, + const char *filename, + apr_pool_t *pool); + +/** + * Attach to a shared memory segment that was created + * by another process, with platform-specific processing. + * @param m The shared memory structure to create. + * @param filename The file used to create the original segment. + * (This MUST match the original filename.) + * @param pool the pool from which to allocate the shared memory + * structure for this process. + * @param flags mask of APR_SHM_* (defined above) + */ +APR_DECLARE(apr_status_t) apr_shm_attach_ex(apr_shm_t **m, + const char *filename, + apr_pool_t *pool, + apr_int32_t flags); + +/** + * Detach from a shared memory segment without destroying it. + * @param m The shared memory structure representing the segment + * to detach from. + */ +APR_DECLARE(apr_status_t) apr_shm_detach(apr_shm_t *m); + +/** + * Retrieve the base address of the shared memory segment. + * NOTE: This address is only usable within the callers address + * space, since this API does not guarantee that other attaching + * processes will maintain the same address mapping. + * @param m The shared memory segment from which to retrieve + * the base address. + * @return address, aligned by APR_ALIGN_DEFAULT. + */ +APR_DECLARE(void *) apr_shm_baseaddr_get(const apr_shm_t *m); + +/** + * Retrieve the length of a shared memory segment in bytes. + * @param m The shared memory segment from which to retrieve + * the segment length. + */ +APR_DECLARE(apr_size_t) apr_shm_size_get(const apr_shm_t *m); + +/** + * Set shared memory permissions. + */ +APR_PERMS_SET_IMPLEMENT(shm); + +/** + * Get the pool used by this shared memory segment. + */ +APR_POOL_DECLARE_ACCESSOR(shm); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_SHM_T */ diff --git a/c/dependencies/windows/apr/x86/include/apr_signal.h b/c/dependencies/windows/apr/x86/include/apr_signal.h new file mode 100644 index 00000000..20631333 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_signal.h @@ -0,0 +1,109 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_SIGNAL_H +#define APR_SIGNAL_H + +/** + * @file apr_signal.h + * @brief APR Signal Handling + */ + +#include "apr.h" +#include "apr_pools.h" + +#if APR_HAVE_SIGNAL_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_signal Signal Handling + * @ingroup APR + * @{ + */ + +#if APR_HAVE_SIGACTION || defined(DOXYGEN) + +#if defined(DARWIN) && !defined(__cplusplus) && !defined(_ANSI_SOURCE) +/* work around Darwin header file bugs + * http://www.opensource.apple.com/bugs/X/BSD%20Kernel/2657228.html + */ +#undef SIG_DFL +#undef SIG_IGN +#undef SIG_ERR +#define SIG_DFL (void (*)(int))0 +#define SIG_IGN (void (*)(int))1 +#define SIG_ERR (void (*)(int))-1 +#endif + +/** Function prototype for signal handlers */ +typedef void apr_sigfunc_t(int); + +/** + * Set the signal handler function for a given signal + * @param signo The signal (eg... SIGWINCH) + * @param func the function to get called + */ +APR_DECLARE(apr_sigfunc_t *) apr_signal(int signo, apr_sigfunc_t * func); + +#if defined(SIG_IGN) && !defined(SIG_ERR) +#define SIG_ERR ((apr_sigfunc_t *) -1) +#endif + +#else /* !APR_HAVE_SIGACTION */ +#define apr_signal(a, b) signal(a, b) +#endif + + +/** + * Get the description for a specific signal number + * @param signum The signal number + * @return The description of the signal + */ +APR_DECLARE(const char *) apr_signal_description_get(int signum); + +/** + * APR-private function for initializing the signal package + * @internal + * @param pglobal The internal, global pool + */ +void apr_signal_init(apr_pool_t *pglobal); + +/** + * Block the delivery of a particular signal + * @param signum The signal number + * @return status + */ +APR_DECLARE(apr_status_t) apr_signal_block(int signum); + +/** + * Enable the delivery of a particular signal + * @param signum The signal number + * @return status + */ +APR_DECLARE(apr_status_t) apr_signal_unblock(int signum); + +/** @} */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* APR_SIGNAL_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_siphash.h b/c/dependencies/windows/apr/x86/include/apr_siphash.h new file mode 100644 index 00000000..42aa8874 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_siphash.h @@ -0,0 +1,148 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + SipHash reference C implementation + Copyright (c) 2012-2014 Jean-Philippe Aumasson + + Copyright (c) 2012-2014 Daniel J. Bernstein + To the extent possible under law, the author(s) have dedicated all copyright + and related and neighboring rights to this software to the public domain + worldwide. This software is distributed without any warranty. + You should have received a copy of the CC0 Public Domain Dedication along + with this software. If not, see + . + */ + +#ifndef APR_SIPHASH_H +#define APR_SIPHASH_H + +#include "apr.h" +#include "apu.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_siphash.h + * @brief APR-UTIL siphash library + * "SipHash-c-d is a family of pseudorandom functions (a.k.a. keyed + * hash functions) optimized for speed on short messages", designed by + * Jean-Philippe Aumasson and Daniel J. Bernstein. It generates a 64bit + * hash (or MAC) from the message and a 128bit key. + * See http://cr.yp.to/siphash/siphash-20120620.pdf for the details, + * c is the number of compression rounds, d the number of finalization + * rounds; we also define fast implementations for c = 2 with d = 4 (aka + * siphash-2-4), and c = 4 with d = 8 (aka siphash-4-8), as recommended + * parameters per the authors. + */ + +/** size of the siphash digest */ +#define APR_SIPHASH_DSIZE 8 + +/** size of the siphash key */ +#define APR_SIPHASH_KSIZE 16 + + +/** + * @brief Computes SipHash-c-d, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key. + * @param src The message + * @param len The length of the message + * @param key The secret key + * @param c The number of compression rounds + * @param d The number of finalization rounds + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(apr_uint64_t) apr_siphash(const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE], + unsigned int c, unsigned int d); + +/** + * @brief Computes SipHash-c-d, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key, into a possibly + * unaligned buffer (using the little endian representation as defined by the + * authors for interoperabilty) usable as a MAC. + * @param out The output buffer (or MAC) + * @param src The message + * @param len The length of the message + * @param key The secret key + * @param c The number of compression rounds + * @param d The number of finalization rounds + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(void) apr_siphash_auth(unsigned char out[APR_SIPHASH_DSIZE], + const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE], + unsigned int c, unsigned int d); + +/** + * @brief Computes SipHash-2-4, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key. + * @param src The message to hash + * @param len The length of the message + * @param key The secret key + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(apr_uint64_t) apr_siphash24(const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE]); + +/** + * @brief Computes SipHash-2-4, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key, into a possibly + * unaligned buffer (using the little endian representation as defined by the + * authors for interoperabilty) usable as a MAC. + * @param out The output buffer (or MAC) + * @param src The message + * @param len The length of the message + * @param key The secret key + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(void) apr_siphash24_auth(unsigned char out[APR_SIPHASH_DSIZE], + const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE]); + +/** + * @brief Computes SipHash-4-8, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key. + * @param src The message + * @param len The length of the message + * @param key The secret key + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(apr_uint64_t) apr_siphash48(const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE]); + +/** + * @brief Computes SipHash-4-8, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key, into a possibly + * unaligned buffer (using the little endian representation as defined by the + * authors for interoperabilty) usable as a MAC. + * @param out The output buffer (or MAC) + * @param src The message + * @param len The length of the message + * @param key The secret key + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(void) apr_siphash48_auth(unsigned char out[APR_SIPHASH_DSIZE], + const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE]); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_SIPHASH_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_skiplist.h b/c/dependencies/windows/apr/x86/include/apr_skiplist.h new file mode 100644 index 00000000..eeab10bf --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_skiplist.h @@ -0,0 +1,381 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_SKIPLIST_H +#define APR_SKIPLIST_H +/** + * @file apr_skiplist.h + * @brief APR skip list implementation + */ + +#include "apr.h" +#include "apr_portable.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_skiplist Skip list implementation + * Refer to http://en.wikipedia.org/wiki/Skip_list for information + * about the purpose of and ideas behind skip lists. + * @ingroup APR + * @{ + */ + +/** + * apr_skiplist_compare is the function type that must be implemented + * per object type that is used in a skip list for comparisons to maintain + * order + * */ +typedef int (*apr_skiplist_compare) (void *, void *); + +/** + * apr_skiplist_freefunc is the function type that must be implemented + * to handle elements as they are removed from a skip list. + */ +typedef void (*apr_skiplist_freefunc) (void *); + +/** Opaque structure used to represent the skip list */ +struct apr_skiplist; +/** Opaque structure used to represent the skip list */ +typedef struct apr_skiplist apr_skiplist; + +/** + * Opaque structure used to represent abstract nodes in the skip list + * (an abstraction above the raw elements which are collected in the + * skip list). + */ +struct apr_skiplistnode; +/** Opaque structure */ +typedef struct apr_skiplistnode apr_skiplistnode; + +/** + * Allocate memory using the same mechanism as the skip list. + * @param sl The skip list + * @param size The amount to allocate + * @remark If a pool was provided to apr_skiplist_init(), memory will + * be allocated from the pool or from a free list maintained with + * the skip list. Otherwise, memory will be allocated using the + * C standard library heap functions. + */ +APR_DECLARE(void *) apr_skiplist_alloc(apr_skiplist *sl, size_t size); + +/** + * Free memory using the same mechanism as the skip list. + * @param sl The skip list + * @param mem The object to free + * @remark If a pool was provided to apr_skiplist_init(), memory will + * be added to a free list maintained with the skip list and be available + * to operations on the skip list or to other calls to apr_skiplist_alloc(). + * Otherwise, memory will be freed using the C standard library heap + * functions. + */ +APR_DECLARE(void) apr_skiplist_free(apr_skiplist *sl, void *mem); + +/** + * Allocate a new skip list + * @param sl The pointer in which to return the newly created skip list + * @param p The pool from which to allocate the skip list (optional). + * @remark Unlike most APR functions, a pool is optional. If no pool + * is provided, the C standard library heap functions will be used instead. + */ +APR_DECLARE(apr_status_t) apr_skiplist_init(apr_skiplist **sl, apr_pool_t *p); + +/** + * Set the comparison functions to be used for searching the skip list. + * @param sl The skip list + * @param XXX1 FIXME + * @param XXX2 FIXME + * + * @remark If existing comparison functions are being replaced, the index + * will be replaced during this call. That is a potentially expensive + * operation. + */ +APR_DECLARE(void) apr_skiplist_set_compare(apr_skiplist *sl, apr_skiplist_compare XXX1, + apr_skiplist_compare XXX2); + +/** + * Set the indexing functions to the specified comparison functions and + * rebuild the index. + * @param sl The skip list + * @param XXX1 FIXME + * @param XXX2 FIXME + * + * @remark If an index already exists, it will not be replaced and the + * comparison functions will not be changed. + */ +APR_DECLARE(void) apr_skiplist_add_index(apr_skiplist *sl, apr_skiplist_compare XXX1, + apr_skiplist_compare XXX2); + +/** + * Return the list maintained by the skip list abstraction. + * @param sl The skip list + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_getlist(apr_skiplist *sl); + +/** + * Return the next matching element in the skip list using the specified + * comparison function. + * @param sl The skip list + * @param data The value to search for + * @param iter A pointer to the returned skip list node representing the element + * found + * @param func The comparison function to use + */ +APR_DECLARE(void *) apr_skiplist_find_compare(apr_skiplist *sl, + void *data, + apr_skiplistnode **iter, + apr_skiplist_compare func); + +/** + * Return the next matching element in the skip list using the current comparison + * function. + * @param sl The skip list + * @param data The value to search for + * @param iter A pointer to the returned skip list node representing the element + * found + */ +APR_DECLARE(void *) apr_skiplist_find(apr_skiplist *sl, void *data, apr_skiplistnode **iter); + +/** + * Return the last matching element in the skip list using the specified + * comparison function. + * @param sl The skip list + * @param data The value to search for + * @param iter A pointer to the returned skip list node representing the element + * found + * @param comp The comparison function to use + */ +APR_DECLARE(void *) apr_skiplist_last_compare(apr_skiplist *sl, void *data, + apr_skiplistnode **iter, + apr_skiplist_compare comp); + +/** + * Return the last matching element in the skip list using the current comparison + * function. + * @param sl The skip list + * @param data The value to search for + * @param iter A pointer to the returned skip list node representing the element + * found + */ +APR_DECLARE(void *) apr_skiplist_last(apr_skiplist *sl, void *data, + apr_skiplistnode **iter); + +/** + * Return the next element in the skip list. + * @param sl The skip list + * @param iter On entry, a pointer to the skip list node to start with; on return, + * a pointer to the skip list node representing the element returned + * @remark If iter points to a NULL value on entry, NULL will be returned. + */ +APR_DECLARE(void *) apr_skiplist_next(apr_skiplist *sl, apr_skiplistnode **iter); + +/** + * Return the previous element in the skip list. + * @param sl The skip list + * @param iter On entry, a pointer to the skip list node to start with; on return, + * a pointer to the skip list node representing the element returned + * @remark If iter points to a NULL value on entry, NULL will be returned. + */ +APR_DECLARE(void *) apr_skiplist_previous(apr_skiplist *sl, apr_skiplistnode **iter); + +/** + * Return the element of the skip list node + * @param iter The skip list node + */ +APR_DECLARE(void *) apr_skiplist_element(apr_skiplistnode *iter); + +/** + * Insert an element into the skip list using the specified comparison function + * if it does not already exist. + * @param sl The skip list + * @param data The element to insert + * @param comp The comparison function to use for placement into the skip list + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_insert_compare(apr_skiplist *sl, + void *data, apr_skiplist_compare comp); + +/** + * Insert an element into the skip list using the existing comparison function + * if it does not already exist. + * @param sl The skip list + * @param data The element to insert + * @remark If no comparison function has been set for the skip list, the element + * will not be inserted and NULL will be returned. + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_insert(apr_skiplist* sl, void *data); + +/** + * Add an element into the skip list using the specified comparison function + * allowing for duplicates. + * @param sl The skip list + * @param data The element to add + * @param comp The comparison function to use for placement into the skip list + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_add_compare(apr_skiplist *sl, + void *data, apr_skiplist_compare comp); + +/** + * Add an element into the skip list using the existing comparison function + * allowing for duplicates. + * @param sl The skip list + * @param data The element to insert + * @remark If no comparison function has been set for the skip list, the element + * will not be inserted and NULL will be returned. + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_add(apr_skiplist* sl, void *data); + +/** + * Add an element into the skip list using the specified comparison function + * removing the existing duplicates. + * @param sl The skip list + * @param data The element to insert + * @param comp The comparison function to use for placement into the skip list + * @param myfree A function to be called for each removed duplicate + * @remark If no comparison function has been set for the skip list, the element + * will not be inserted, none will be replaced, and NULL will be returned. + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_replace_compare(apr_skiplist *sl, + void *data, apr_skiplist_freefunc myfree, + apr_skiplist_compare comp); + +/** + * Add an element into the skip list using the existing comparison function + * removing the existing duplicates. + * @param sl The skip list + * @param data The element to insert + * @param myfree A function to be called for each removed duplicate + * @remark If no comparison function has been set for the skip list, the element + * will not be inserted, none will be replaced, and NULL will be returned. + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_replace(apr_skiplist *sl, + void *data, apr_skiplist_freefunc myfree); + +/** + * Remove a node from the skip list. + * @param sl The skip list + * @param iter The skip list node to remove + * @param myfree A function to be called for the removed element + */ +APR_DECLARE(int) apr_skiplist_remove_node(apr_skiplist *sl, + apr_skiplistnode *iter, + apr_skiplist_freefunc myfree); + +/** + * Remove an element from the skip list using the specified comparison function for + * locating the element. In the case of duplicates, the 1st entry will be removed. + * @param sl The skip list + * @param data The element to remove + * @param myfree A function to be called for each removed element + * @param comp The comparison function to use for placement into the skip list + * @remark If the element is not found, 0 will be returned. Otherwise, the heightXXX + * will be returned. + */ +APR_DECLARE(int) apr_skiplist_remove_compare(apr_skiplist *sl, void *data, + apr_skiplist_freefunc myfree, apr_skiplist_compare comp); + +/** + * Remove an element from the skip list using the existing comparison function for + * locating the element. In the case of duplicates, the 1st entry will be removed. + * @param sl The skip list + * @param data The element to remove + * @param myfree A function to be called for each removed element + * @remark If the element is not found, 0 will be returned. Otherwise, the heightXXX + * will be returned. + * @remark If no comparison function has been set for the skip list, the element + * will not be removed and 0 will be returned. + */ +APR_DECLARE(int) apr_skiplist_remove(apr_skiplist *sl, void *data, apr_skiplist_freefunc myfree); + +/** + * Remove all elements from the skip list. + * @param sl The skip list + * @param myfree A function to be called for each removed element + */ +APR_DECLARE(void) apr_skiplist_remove_all(apr_skiplist *sl, apr_skiplist_freefunc myfree); + +/** + * Remove each element from the skip list. + * @param sl The skip list + * @param myfree A function to be called for each removed element + */ +APR_DECLARE(void) apr_skiplist_destroy(apr_skiplist *sl, apr_skiplist_freefunc myfree); + +/** + * Return the first element in the skip list, removing the element from the skip list. + * @param sl The skip list + * @param myfree A function to be called for the removed element + * @remark NULL will be returned if there are no elements + */ +APR_DECLARE(void *) apr_skiplist_pop(apr_skiplist *sl, apr_skiplist_freefunc myfree); + +/** + * Return the first element in the skip list, leaving the element in the skip list. + * @param sl The skip list + * @remark NULL will be returned if there are no elements + */ +APR_DECLARE(void *) apr_skiplist_peek(apr_skiplist *sl); + +/** + * Return the size of the list (number of elements), in O(1). + * @param sl The skip list + */ +APR_DECLARE(size_t) apr_skiplist_size(const apr_skiplist *sl); + +/** + * Return the height of the list (number of skip paths), in O(1). + * @param sl The skip list + */ +APR_DECLARE(int) apr_skiplist_height(const apr_skiplist *sl); + +/** + * Return the predefined maximum height of the skip list. + * @param sl The skip list + */ +APR_DECLARE(int) apr_skiplist_preheight(const apr_skiplist *sl); + +/** + * Set a predefined maximum height for the skip list. + * @param sl The skip list + * @param to The preheight to set, or a nul/negative value to disable. + * @remark When a preheight is used, the height of each inserted element is + * computed randomly up to this preheight instead of the current skip list's + * height plus one used by the default implementation. Using a preheight can + * probably ensure more fairness with long living elements (since with an + * adaptative height, former elements may have been created with a low height, + * hence a longest path to reach them while the skip list grows). On the other + * hand, the default behaviour (preheight <= 0) with a growing and decreasing + * maximum height is more adaptative/suitable for short living values. + * @note Should be called before any insertion/add. + */ +APR_DECLARE(void) apr_skiplist_set_preheight(apr_skiplist *sl, int to); + +/** + * Merge two skip lists. XXX SEMANTICS + * @param sl1 One of two skip lists to be merged + * @param sl2 The other of two skip lists to be merged + */ +APR_DECLARE(apr_skiplist *) apr_skiplist_merge(apr_skiplist *sl1, apr_skiplist *sl2); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_SKIPLIST_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_strings.h b/c/dependencies/windows/apr/x86/include/apr_strings.h new file mode 100644 index 00000000..d5f8719d --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_strings.h @@ -0,0 +1,380 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* Portions of this file are covered by */ +/* -*- mode: c; c-file-style: "k&r" -*- + + strnatcmp.c -- Perform 'natural order' comparisons of strings in C. + Copyright (C) 2000 by Martin Pool + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef APR_STRINGS_H +#define APR_STRINGS_H + +/** + * @file apr_strings.h + * @brief APR Strings library + */ + +#include "apr.h" +#include "apr_errno.h" +#include "apr_pools.h" +#define APR_WANT_IOVEC +#include "apr_want.h" + +#if APR_HAVE_STDARG_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_strings String routines + * @ingroup APR + * @{ + */ + +/** + * Do a natural order comparison of two strings. + * @param a The first string to compare + * @param b The second string to compare + * @return Either <0, 0, or >0. If the first string is less than the second + * this returns <0, if they are equivalent it returns 0, and if the + * first string is greater than second string it retuns >0. + */ +APR_DECLARE(int) apr_strnatcmp(char const *a, char const *b); + +/** + * Do a natural order comparison of two strings ignoring the case of the + * strings. + * @param a The first string to compare + * @param b The second string to compare + * @return Either <0, 0, or >0. If the first string is less than the second + * this returns <0, if they are equivalent it returns 0, and if the + * first string is greater than second string it retuns >0. + */ +APR_DECLARE(int) apr_strnatcasecmp(char const *a, char const *b); + +/** + * duplicate a string into memory allocated out of a pool + * @param p The pool to allocate out of + * @param s The string to duplicate + * @return The new string or NULL if s == NULL + */ +APR_DECLARE(char *) apr_pstrdup(apr_pool_t *p, const char *s); + +/** + * Create a null-terminated string by making a copy of a sequence + * of characters and appending a null byte + * @param p The pool to allocate out of + * @param s The block of characters to duplicate + * @param n The number of characters to duplicate + * @return The new string or NULL if s == NULL + * @remark This is a faster alternative to apr_pstrndup(), for use + * when you know that the string being duplicated really + * has 'n' or more characters. If the string might contain + * fewer characters, use apr_pstrndup(). + */ +APR_DECLARE(char *) apr_pstrmemdup(apr_pool_t *p, const char *s, apr_size_t n) +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) + __attribute__((alloc_size(3))) +#endif + ; + +/** + * Duplicate at most n characters of a string into memory allocated + * out of a pool; the new string will be NUL-terminated + * @param p The pool to allocate out of + * @param s The string to duplicate + * @param n The maximum number of characters to duplicate + * @return The new string or NULL if s == NULL + * @remark The amount of memory allocated from the pool is the length + * of the returned string including the NUL terminator + */ +APR_DECLARE(char *) apr_pstrndup(apr_pool_t *p, const char *s, apr_size_t n); + +/** + * Duplicate a block of memory. + * + * @param p The pool to allocate from + * @param m The memory to duplicate + * @param n The number of bytes to duplicate + * @return The new block of memory or NULL if m == NULL + */ +APR_DECLARE(void *) apr_pmemdup(apr_pool_t *p, const void *m, apr_size_t n) +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) + __attribute__((alloc_size(3))) +#endif + ; + +/** + * Concatenate multiple strings, allocating memory out a pool + * @param p The pool to allocate out of + * @param ... The strings to concatenate. The final string must be NULL + * @return The new string + */ +APR_DECLARE_NONSTD(char *) apr_pstrcat(apr_pool_t *p, ...) +#if defined(__GNUC__) && __GNUC__ >= 4 + __attribute__((sentinel)) +#endif + ; + +/** + * Concatenate multiple strings specified in a writev-style vector + * @param p The pool from which to allocate + * @param vec The strings to concatenate + * @param nvec The number of strings to concatenate + * @param nbytes (output) strlen of new string (pass in NULL to omit) + * @return The new string + */ +APR_DECLARE(char *) apr_pstrcatv(apr_pool_t *p, const struct iovec *vec, + apr_size_t nvec, apr_size_t *nbytes); + +/** + * printf-style style printing routine. The data is output to a string + * allocated from a pool + * @param p The pool to allocate out of + * @param fmt The format of the string + * @param ap The arguments to use while printing the data + * @return The new string + */ +APR_DECLARE(char *) apr_pvsprintf(apr_pool_t *p, const char *fmt, va_list ap); + +/** + * printf-style style printing routine. The data is output to a string + * allocated from a pool + * @param p The pool to allocate out of + * @param fmt The format of the string + * @param ... The arguments to use while printing the data + * @return The new string + */ +APR_DECLARE_NONSTD(char *) apr_psprintf(apr_pool_t *p, const char *fmt, ...) + __attribute__((format(printf,2,3))); + +/** + * Copy up to dst_size characters from src to dst; does not copy + * past a NUL terminator in src, but always terminates dst with a NUL + * regardless. + * @param dst The destination string + * @param src The source string + * @param dst_size The space available in dst; dst always receives + * NUL termination, so if src is longer than + * dst_size, the actual number of characters copied is + * dst_size - 1. + * @return Pointer to the NUL terminator of the destination string, dst + * @remark + *
+ * Note the differences between this function and strncpy():
+ *  1) strncpy() doesn't always NUL terminate; apr_cpystrn() does.
+ *  2) strncpy() pads the destination string with NULs, which is often 
+ *     unnecessary; apr_cpystrn() does not.
+ *  3) strncpy() returns a pointer to the beginning of the dst string;
+ *     apr_cpystrn() returns a pointer to the NUL terminator of dst, 
+ *     to allow a check for truncation.
+ * 
+ */ +APR_DECLARE(char *) apr_cpystrn(char *dst, const char *src, + apr_size_t dst_size); + +/** + * Remove all whitespace from a string + * @param dest The destination string. It is okay to modify the string + * in place. Namely dest == src + * @param src The string to rid the spaces from. + * @return A pointer to the destination string's null terminator. + */ +APR_DECLARE(char *) apr_collapse_spaces(char *dest, const char *src); + +/** + * Convert the arguments to a program from one string to an array of + * strings terminated by a NULL pointer + * @param arg_str The arguments to convert + * @param argv_out Output location. This is a pointer to an array of strings. + * @param token_context Pool to use. + */ +APR_DECLARE(apr_status_t) apr_tokenize_to_argv(const char *arg_str, + char ***argv_out, + apr_pool_t *token_context); + +/** + * Split a string into separate null-terminated tokens. The tokens are + * delimited in the string by one or more characters from the sep + * argument. + * @param str The string to separate; this should be specified on the + * first call to apr_strtok() for a given string, and NULL + * on subsequent calls. + * @param sep The set of delimiters + * @param last State saved by apr_strtok() between calls. + * @return The next token from the string + * @note the 'last' state points to the trailing NUL char of the final + * token, otherwise it points to the character following the current + * token (all successive or empty occurances of sep are skiped on the + * subsequent call to apr_strtok). Therefore it is possible to avoid + * a strlen() determination, with the following logic; + * toklen = last - retval; if (*last) --toklen; + */ +APR_DECLARE(char *) apr_strtok(char *str, const char *sep, char **last); + +/** + * @defgroup APR_Strings_Snprintf snprintf implementations + * @warning + * These are snprintf implementations based on apr_vformatter(). + * + * Note that various standards and implementations disagree on the return + * value of snprintf, and side-effects due to %n in the formatting string. + * apr_snprintf (and apr_vsnprintf) behaves as follows: + * + * Process the format string until the entire string is exhausted, or + * the buffer fills. If the buffer fills then stop processing immediately + * (so no further %n arguments are processed), and return the buffer + * length. In all cases the buffer is NUL terminated. It will return the + * number of characters inserted into the buffer, not including the + * terminating NUL. As a special case, if len is 0, apr_snprintf will + * return the number of characters that would have been inserted if + * the buffer had been infinite (in this case, *buffer can be NULL) + * + * In no event does apr_snprintf return a negative number. + * @{ + */ + +/** + * snprintf routine based on apr_vformatter. This means it understands the + * same extensions. + * @param buf The buffer to write to + * @param len The size of the buffer + * @param format The format string + * @param ... The arguments to use to fill out the format string. + */ +APR_DECLARE_NONSTD(int) apr_snprintf(char *buf, apr_size_t len, + const char *format, ...) + __attribute__((format(printf,3,4))); + +/** + * vsnprintf routine based on apr_vformatter. This means it understands the + * same extensions. + * @param buf The buffer to write to + * @param len The size of the buffer + * @param format The format string + * @param ap The arguments to use to fill out the format string. + */ +APR_DECLARE(int) apr_vsnprintf(char *buf, apr_size_t len, const char *format, + va_list ap); +/** @} */ + +/** + * create a string representation of an int, allocated from a pool + * @param p The pool from which to allocate + * @param n The number to format + * @return The string representation of the number + */ +APR_DECLARE(char *) apr_itoa(apr_pool_t *p, int n); + +/** + * create a string representation of a long, allocated from a pool + * @param p The pool from which to allocate + * @param n The number to format + * @return The string representation of the number + */ +APR_DECLARE(char *) apr_ltoa(apr_pool_t *p, long n); + +/** + * create a string representation of an apr_off_t, allocated from a pool + * @param p The pool from which to allocate + * @param n The number to format + * @return The string representation of the number + */ +APR_DECLARE(char *) apr_off_t_toa(apr_pool_t *p, apr_off_t n); + +/** + * Convert a numeric string into an apr_off_t numeric value. + * @param offset The value of the parsed string. + * @param buf The string to parse. It may contain optional whitespace, + * followed by an optional '+' (positive, default) or '-' (negative) + * character, followed by an optional '0x' prefix if base is 0 or 16, + * followed by numeric digits appropriate for base. + * @param end A pointer to the end of the valid character in buf. If + * not NULL, it is set to the first invalid character in buf. + * @param base A numeric base in the range between 2 and 36 inclusive, + * or 0. If base is zero, buf will be treated as base ten unless its + * digits are prefixed with '0x', in which case it will be treated as + * base 16. + * @bug *end breaks type safety; where *buf is const, *end needs to be + * declared as const in APR 2.0 + */ +APR_DECLARE(apr_status_t) apr_strtoff(apr_off_t *offset, const char *buf, + char **end, int base); + +/** + * parse a numeric string into a 64-bit numeric value + * @param buf The string to parse. It may contain optional whitespace, + * followed by an optional '+' (positive, default) or '-' (negative) + * character, followed by an optional '0x' prefix if base is 0 or 16, + * followed by numeric digits appropriate for base. + * @param end A pointer to the end of the valid character in buf. If + * not NULL, it is set to the first invalid character in buf. + * @param base A numeric base in the range between 2 and 36 inclusive, + * or 0. If base is zero, buf will be treated as base ten unless its + * digits are prefixed with '0x', in which case it will be treated as + * base 16. + * @return The numeric value of the string. On overflow, errno is set + * to ERANGE. On success, errno is set to 0. + */ +APR_DECLARE(apr_int64_t) apr_strtoi64(const char *buf, char **end, int base); + +/** + * parse a base-10 numeric string into a 64-bit numeric value. + * Equivalent to apr_strtoi64(buf, (char**)NULL, 10). + * @param buf The string to parse + * @return The numeric value of the string. On overflow, errno is set + * to ERANGE. On success, errno is set to 0. + */ +APR_DECLARE(apr_int64_t) apr_atoi64(const char *buf); + +/** + * Format a binary size (magnitiudes are 2^10 rather than 10^3) from an apr_off_t, + * as bytes, K, M, T, etc, to a four character compacted human readable string. + * @param size The size to format + * @param buf The 5 byte text buffer (counting the trailing null) + * @return The buf passed to apr_strfsize() + * @remark All negative sizes report ' - ', apr_strfsize only formats positive values. + */ +APR_DECLARE(char *) apr_strfsize(apr_off_t size, char *buf); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_STRINGS_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_strmatch.h b/c/dependencies/windows/apr/x86/include/apr_strmatch.h new file mode 100644 index 00000000..53fadad5 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_strmatch.h @@ -0,0 +1,81 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_STRMATCH_H +#define APR_STRMATCH_H +/** + * @file apr_strmatch.h + * @brief APR-UTIL string matching routines + */ + +#include "apu.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_StrMatch String matching routines + * @ingroup APR_Util + * @{ + */ + +/** @see apr_strmatch_pattern */ +typedef struct apr_strmatch_pattern apr_strmatch_pattern; + +/** + * Precompiled search pattern + */ +struct apr_strmatch_pattern { + /** Function called to compare */ + const char *(*compare)(const apr_strmatch_pattern *this_pattern, + const char *s, apr_size_t slen); + const char *pattern; /**< Current pattern */ + apr_size_t length; /**< Current length */ + void *context; /**< hook to add precomputed metadata */ +}; + +#if defined(DOXYGEN) +/** + * Search for a precompiled pattern within a string + * @param pattern The pattern + * @param s The string in which to search for the pattern + * @param slen The length of s (excluding null terminator) + * @return A pointer to the first instance of the pattern in s, or + * NULL if not found + */ +APU_DECLARE(const char *) apr_strmatch(const apr_strmatch_pattern *pattern, + const char *s, apr_size_t slen); +#else +#define apr_strmatch(pattern, s, slen) (*((pattern)->compare))((pattern), (s), (slen)) +#endif + +/** + * Precompile a pattern for matching using the Boyer-Moore-Horspool algorithm + * @param p The pool from which to allocate the pattern + * @param s The pattern string + * @param case_sensitive Whether the matching should be case-sensitive + * @return a pointer to the compiled pattern, or NULL if compilation fails + */ +APU_DECLARE(const apr_strmatch_pattern *) apr_strmatch_precompile(apr_pool_t *p, const char *s, int case_sensitive); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_STRMATCH_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_support.h b/c/dependencies/windows/apr/x86/include/apr_support.h new file mode 100644 index 00000000..79c8cb47 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_support.h @@ -0,0 +1,57 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_SUPPORT_H +#define APR_SUPPORT_H + +/** + * @file apr_support.h + * @brief APR Support functions + */ + +#include "apr.h" +#include "apr_network_io.h" +#include "apr_file_io.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_support Internal APR support functions + * @ingroup APR + * @{ + */ + +/** + * Wait for IO to occur or timeout. + * + * @param f The file to wait on. + * @param s The socket to wait on if @a f is @c NULL. + * @param for_read If non-zero wait for data to be available to read, + * otherwise wait for data to be able to be written. + * @return APR_TIMEUP if we run out of time. + */ +apr_status_t apr_wait_for_io_or_timeout(apr_file_t *f, apr_socket_t *s, + int for_read); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_SUPPORT_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_tables.h b/c/dependencies/windows/apr/x86/include/apr_tables.h new file mode 100644 index 00000000..27974c0e --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_tables.h @@ -0,0 +1,507 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_TABLES_H +#define APR_TABLES_H + +/** + * @file apr_tables.h + * @brief APR Table library + */ + +#include "apr.h" +#include "apr_pools.h" + +#if APR_HAVE_STDARG_H +#include /* for va_list */ +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_tables Table and Array Functions + * @ingroup APR + * Arrays are used to store data which is referenced sequentially or + * as a stack. Functions are provided to push and pop individual + * elements as well as to operate on the entire array. + * + * Tables are used to store data which can be referenced by key. + * Limited capabilities are provided for tables with multiple elements + * which share a key; while key lookup will return only a single + * element, iteration is available. Additionally, a table can be + * compressed to resolve duplicates. + * + * Both arrays and tables may store string or binary data; some features, + * such as concatenation or merging of elements, work only for string + * data. + * @{ + */ + +/** the table abstract data type */ +typedef struct apr_table_t apr_table_t; + +/** @see apr_array_header_t */ +typedef struct apr_array_header_t apr_array_header_t; + +/** An opaque array type */ +struct apr_array_header_t { + /** The pool the array is allocated out of */ + apr_pool_t *pool; + /** The amount of memory allocated for each element of the array */ + int elt_size; + /** The number of active elements in the array */ + int nelts; + /** The number of elements allocated in the array */ + int nalloc; + /** The elements in the array */ + char *elts; +}; + +/** + * The (opaque) structure for string-content tables. + */ +typedef struct apr_table_entry_t apr_table_entry_t; + +/** The type for each entry in a string-content table */ +struct apr_table_entry_t { + /** The key for the current table entry */ + char *key; /* maybe NULL in future; + * check when iterating thru table_elts + */ + /** The value for the current table entry */ + char *val; + + /** A checksum for the key, for use by the apr_table internals */ + apr_uint32_t key_checksum; +}; + +/** + * Get the elements from a table. + * @param t The table + * @return An array containing the contents of the table + */ +APR_DECLARE(const apr_array_header_t *) apr_table_elts(const apr_table_t *t); + +/** + * Determine if the table is empty (either NULL or having no elements). + * @param t The table to check + * @return True if empty, False otherwise + */ +APR_DECLARE(int) apr_is_empty_table(const apr_table_t *t); + +/** + * Determine if the array is empty (either NULL or having no elements). + * @param a The array to check + * @return True if empty, False otherwise + */ +APR_DECLARE(int) apr_is_empty_array(const apr_array_header_t *a); + +/** + * Create an array. + * @param p The pool to allocate the memory out of + * @param nelts the number of elements in the initial array + * @param elt_size The size of each element in the array. + * @return The new array + */ +APR_DECLARE(apr_array_header_t *) apr_array_make(apr_pool_t *p, + int nelts, int elt_size); + +/** + * Add a new element to an array (as a first-in, last-out stack). + * @param arr The array to add an element to. + * @return Location for the new element in the array. + * @remark If there are no free spots in the array, then this function will + * allocate new space for the new element. + */ +APR_DECLARE(void *) apr_array_push(apr_array_header_t *arr); + +/** A helper macro for accessing a member of an APR array. + * + * @param ary the array + * @param i the index into the array to return + * @param type the type of the objects stored in the array + * + * @return the item at index i + */ +#define APR_ARRAY_IDX(ary,i,type) (((type *)(ary)->elts)[i]) + +/** A helper macro for pushing elements into an APR array. + * + * @param ary the array + * @param type the type of the objects stored in the array + * + * @return the location where the new object should be placed + */ +#define APR_ARRAY_PUSH(ary,type) (*((type *)apr_array_push(ary))) + +/** + * Remove an element from an array (as a first-in, last-out stack). + * @param arr The array to remove an element from. + * @return Location of the element in the array. + * @remark If there are no elements in the array, NULL is returned. + */ +APR_DECLARE(void *) apr_array_pop(apr_array_header_t *arr); + +/** + * Remove all elements from an array. + * @param arr The array to remove all elements from. + * @remark As the underlying storage is allocated from a pool, no + * memory is freed by this operation, but is available for reuse. + */ +APR_DECLARE(void) apr_array_clear(apr_array_header_t *arr); + +/** + * Concatenate two arrays together. + * @param dst The destination array, and the one to go first in the combined + * array + * @param src The source array to add to the destination array + */ +APR_DECLARE(void) apr_array_cat(apr_array_header_t *dst, + const apr_array_header_t *src); + +/** + * Copy the entire array. + * @param p The pool to allocate the copy of the array out of + * @param arr The array to copy + * @return An exact copy of the array passed in + * @remark The alternate apr_array_copy_hdr() copies only the header, and arranges + * for the elements to be copied if (and only if) the code subsequently + * does a push or arraycat. + */ +APR_DECLARE(apr_array_header_t *) apr_array_copy(apr_pool_t *p, + const apr_array_header_t *arr); +/** + * Copy the headers of the array, and arrange for the elements to be copied if + * and only if the code subsequently does a push or arraycat. + * @param p The pool to allocate the copy of the array out of + * @param arr The array to copy + * @return An exact copy of the array passed in + * @remark The alternate apr_array_copy() copies the *entire* array. + */ +APR_DECLARE(apr_array_header_t *) apr_array_copy_hdr(apr_pool_t *p, + const apr_array_header_t *arr); + +/** + * Append one array to the end of another, creating a new array in the process. + * @param p The pool to allocate the new array out of + * @param first The array to put first in the new array. + * @param second The array to put second in the new array. + * @return A new array containing the data from the two arrays passed in. +*/ +APR_DECLARE(apr_array_header_t *) apr_array_append(apr_pool_t *p, + const apr_array_header_t *first, + const apr_array_header_t *second); + +/** + * Generate a new string from the apr_pool_t containing the concatenated + * sequence of substrings referenced as elements within the array. The string + * will be empty if all substrings are empty or null, or if there are no + * elements in the array. If sep is non-NUL, it will be inserted between + * elements as a separator. + * @param p The pool to allocate the string out of + * @param arr The array to generate the string from + * @param sep The separator to use + * @return A string containing all of the data in the array. + */ +APR_DECLARE(char *) apr_array_pstrcat(apr_pool_t *p, + const apr_array_header_t *arr, + const char sep); + +/** + * Make a new table. + * @param p The pool to allocate the pool out of + * @param nelts The number of elements in the initial table. + * @return The new table. + * @warning This table can only store text data + */ +APR_DECLARE(apr_table_t *) apr_table_make(apr_pool_t *p, int nelts); + +/** + * Create a new table and copy another table into it. + * @param p The pool to allocate the new table out of + * @param t The table to copy + * @return A copy of the table passed in + * @warning The table keys and respective values are not copied + */ +APR_DECLARE(apr_table_t *) apr_table_copy(apr_pool_t *p, + const apr_table_t *t); + +/** + * Create a new table whose contents are deep copied from the given + * table. A deep copy operation copies all fields, and makes copies + * of dynamically allocated memory pointed to by the fields. + * @param p The pool to allocate the new table out of + * @param t The table to clone + * @return A deep copy of the table passed in + */ +APR_DECLARE(apr_table_t *) apr_table_clone(apr_pool_t *p, + const apr_table_t *t); + +/** + * Delete all of the elements from a table. + * @param t The table to clear + */ +APR_DECLARE(void) apr_table_clear(apr_table_t *t); + +/** + * Get the value associated with a given key from the table. After this call, + * the data is still in the table. + * @param t The table to search for the key + * @param key The key to search for (case does not matter) + * @return The value associated with the key, or NULL if the key does not exist. + */ +APR_DECLARE(const char *) apr_table_get(const apr_table_t *t, const char *key); + +/** + * Get values associated with a given key from the table. If more than one + * value exists, return a comma separated list of values. After this call, the + * data is still in the table. + * @param p The pool to allocate the combined value from, if necessary + * @param t The table to search for the key + * @param key The key to search for (case does not matter) + * @return The value associated with the key, or NULL if the key does not exist. + */ +APR_DECLARE(const char *) apr_table_getm(apr_pool_t *p, const apr_table_t *t, + const char *key); + +/** + * Add a key/value pair to a table. If another element already exists with the + * same key, this will overwrite the old data. + * @param t The table to add the data to. + * @param key The key to use (case does not matter) + * @param val The value to add + * @remark When adding data, this function makes a copy of both the key and the + * value. + */ +APR_DECLARE(void) apr_table_set(apr_table_t *t, const char *key, + const char *val); + +/** + * Add a key/value pair to a table. If another element already exists with the + * same key, this will overwrite the old data. + * @param t The table to add the data to. + * @param key The key to use (case does not matter) + * @param val The value to add + * @warning When adding data, this function does not make a copy of the key or + * the value, so care should be taken to ensure that the values will + * not change after they have been added.. + */ +APR_DECLARE(void) apr_table_setn(apr_table_t *t, const char *key, + const char *val); + +/** + * Remove data from the table. + * @param t The table to remove data from + * @param key The key of the data being removed (case does not matter) + */ +APR_DECLARE(void) apr_table_unset(apr_table_t *t, const char *key); + +/** + * Add data to a table by merging the value with data that has already been + * stored. The merging is done by concatenating the two values, separated + * by the string ", ". + * @param t The table to search for the data + * @param key The key to merge data for (case does not matter) + * @param val The data to add + * @remark If the key is not found, then this function acts like apr_table_add() + */ +APR_DECLARE(void) apr_table_merge(apr_table_t *t, const char *key, + const char *val); + +/** + * Add data to a table by merging the value with data that has already been + * stored. The merging is done by concatenating the two values, separated + * by the string ", ". + * @param t The table to search for the data + * @param key The key to merge data for (case does not matter) + * @param val The data to add + * @remark If the key is not found, then this function acts like apr_table_addn() + */ +APR_DECLARE(void) apr_table_mergen(apr_table_t *t, const char *key, + const char *val); + +/** + * Add data to a table, regardless of whether there is another element with the + * same key. + * @param t The table to add to + * @param key The key to use + * @param val The value to add. + * @remark When adding data, this function makes a copy of both the key and the + * value. + */ +APR_DECLARE(void) apr_table_add(apr_table_t *t, const char *key, + const char *val); + +/** + * Add data to a table, regardless of whether there is another element with the + * same key. + * @param t The table to add to + * @param key The key to use + * @param val The value to add. + * @remark When adding data, this function does not make a copy of the key or the + * value, so care should be taken to ensure that the values will not + * change after they have been added. + */ +APR_DECLARE(void) apr_table_addn(apr_table_t *t, const char *key, + const char *val); + +/** + * Merge two tables into one new table. + * @param p The pool to use for the new table + * @param overlay The first table to put in the new table + * @param base The table to add at the end of the new table + * @return A new table containing all of the data from the two passed in + */ +APR_DECLARE(apr_table_t *) apr_table_overlay(apr_pool_t *p, + const apr_table_t *overlay, + const apr_table_t *base); + +/** + * Declaration prototype for the iterator callback function of apr_table_do() + * and apr_table_vdo(). + * @param rec The data passed as the first argument to apr_table_[v]do() + * @param key The key from this iteration of the table + * @param value The value from this iteration of the table + * @remark Iteration continues while this callback function returns non-zero. + * To export the callback function for apr_table_[v]do() it must be declared + * in the _NONSTD convention. + * @see apr_table_do @see apr_table_vdo + */ +typedef int (apr_table_do_callback_fn_t)(void *rec, const char *key, + const char *value); + +/** + * Iterate over a table running the provided function once for every + * element in the table. The varargs array must be a list of zero or + * more (char *) keys followed by a NULL pointer. If zero keys are + * given, the @param comp function will be invoked for every element + * in the table. Otherwise, the function is invoked only for those + * elements matching the keys specified. + * + * If an invocation of the comp function returns zero, + * iteration will continue using the next specified key, if any. + * + * @param comp The function to run + * @param rec The data to pass as the first argument to the function + * @param t The table to iterate over + * @param ... A varargs array of zero or more (char *) keys followed by NULL + * @return FALSE if one of the comp() iterations returned zero; TRUE if all + * iterations returned non-zero + * @see apr_table_do_callback_fn_t @see apr_table_vdo + */ +APR_DECLARE_NONSTD(int) apr_table_do(apr_table_do_callback_fn_t *comp, + void *rec, const apr_table_t *t, ...) +#if defined(__GNUC__) && __GNUC__ >= 4 + __attribute__((sentinel)) +#endif + ; + +/** + * Iterate over a table running the provided function once for every + * element in the table. The vp varargs parameter must be a + * list of zero or more (char *) keys followed by a NULL pointer. If + * zero keys are given, the @param comp function will be invoked for + * every element in the table. Otherwise, the function is invoked + * only for those elements matching the keys specified. + * + * If an invocation of the comp function returns zero, + * iteration will continue using the next specified key, if any. + * + * @param comp The function to run + * @param rec The data to pass as the first argument to the function + * @param t The table to iterate over + * @param vp List of zero or more (char *) keys followed by NULL + * @return FALSE if one of the comp() iterations returned zero; TRUE if all + * iterations returned non-zero + * @see apr_table_do_callback_fn_t @see apr_table_do + */ +APR_DECLARE(int) apr_table_vdo(apr_table_do_callback_fn_t *comp, + void *rec, const apr_table_t *t, va_list vp); + +/** flag for overlap to use apr_table_setn */ +#define APR_OVERLAP_TABLES_SET (0) +/** flag for overlap to use apr_table_mergen */ +#define APR_OVERLAP_TABLES_MERGE (1) +/** flag for overlap to use apr_table_addn */ +#define APR_OVERLAP_TABLES_ADD (2) +/** + * For each element in table b, either use setn or mergen to add the data + * to table a. Which method is used is determined by the flags passed in. + * @param a The table to add the data to. + * @param b The table to iterate over, adding its data to table a + * @param flags How to add the table to table a. One of: + * APR_OVERLAP_TABLES_SET Use apr_table_setn + * APR_OVERLAP_TABLES_MERGE Use apr_table_mergen + * APR_OVERLAP_TABLES_ADD Use apr_table_addn + * @remark When merging duplicates, the two values are concatenated, + * separated by the string ", ". + * @remark This function is highly optimized, and uses less memory and CPU cycles + * than a function that just loops through table b calling other functions. + */ +/** + * Conceptually, apr_table_overlap does this: + * + *
+ *  apr_array_header_t *barr = apr_table_elts(b);
+ *  apr_table_entry_t *belt = (apr_table_entry_t *)barr->elts;
+ *  int i;
+ *
+ *  for (i = 0; i < barr->nelts; ++i) {
+ *      if (flags & APR_OVERLAP_TABLES_MERGE) {
+ *          apr_table_mergen(a, belt[i].key, belt[i].val);
+ *      }
+ *      else if (flags & APR_OVERLAP_TABLES_ADD) {
+ *          apr_table_addn(a, belt[i].key, belt[i].val);
+ *      }
+ *      else {
+ *          apr_table_setn(a, belt[i].key, belt[i].val);
+ *      }
+ *  }
+ * 
+ * + * Except that it is more efficient (less space and cpu-time) especially + * when b has many elements. + * + * Notice the assumptions on the keys and values in b -- they must be + * in an ancestor of a's pool. In practice b and a are usually from + * the same pool. + */ + +APR_DECLARE(void) apr_table_overlap(apr_table_t *a, const apr_table_t *b, + unsigned flags); + +/** + * Eliminate redundant entries in a table by either overwriting + * or merging duplicates. + * + * @param t Table. + * @param flags APR_OVERLAP_TABLES_MERGE to merge, or + * APR_OVERLAP_TABLES_SET to overwrite, or + * APR_OVERLAP_TABLES_ADD to add + * @remark When merging duplicates, the two values are concatenated, + * separated by the string ", ". + */ +APR_DECLARE(void) apr_table_compress(apr_table_t *t, unsigned flags); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_TABLES_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_thread_cond.h b/c/dependencies/windows/apr/x86/include/apr_thread_cond.h new file mode 100644 index 00000000..199f1ded --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_thread_cond.h @@ -0,0 +1,139 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_THREAD_COND_H +#define APR_THREAD_COND_H + +/** + * @file apr_thread_cond.h + * @brief APR Condition Variable Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_time.h" +#include "apr_thread_mutex.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#if APR_HAS_THREADS || defined(DOXYGEN) + +/** + * @defgroup apr_thread_cond Condition Variable Routines + * @ingroup APR + * @{ + */ + +/** Opaque structure for thread condition variables */ +typedef struct apr_thread_cond_t apr_thread_cond_t; + +/** + * Note: destroying a condition variable (or likewise, destroying or + * clearing the pool from which a condition variable was allocated) if + * any threads are blocked waiting on it gives undefined results. + */ + +/** + * Create and initialize a condition variable that can be used to signal + * and schedule threads in a single process. + * @param cond the memory address where the newly created condition variable + * will be stored. + * @param pool the pool from which to allocate the condition. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_create(apr_thread_cond_t **cond, + apr_pool_t *pool); + +/** + * Put the active calling thread to sleep until signaled to wake up. Each + * condition variable must be associated with a mutex, and that mutex must + * be locked before calling this function, or the behavior will be + * undefined. As the calling thread is put to sleep, the given mutex + * will be simultaneously released; and as this thread wakes up the lock + * is again simultaneously acquired. + * @param cond the condition variable on which to block. + * @param mutex the mutex that must be locked upon entering this function, + * is released while the thread is asleep, and is again acquired before + * returning from this function. + * @remark Spurious wakeups may occur. Before and after every call to wait on + * a condition variable, the caller should test whether the condition is already + * met. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_wait(apr_thread_cond_t *cond, + apr_thread_mutex_t *mutex); + +/** + * Put the active calling thread to sleep until signaled to wake up or + * the timeout is reached. Each condition variable must be associated + * with a mutex, and that mutex must be locked before calling this + * function, or the behavior will be undefined. As the calling thread + * is put to sleep, the given mutex will be simultaneously released; + * and as this thread wakes up the lock is again simultaneously acquired. + * @param cond the condition variable on which to block. + * @param mutex the mutex that must be locked upon entering this function, + * is released while the thread is asleep, and is again acquired before + * returning from this function. + * @param timeout The amount of time in microseconds to wait. This is + * a maximum, not a minimum. If the condition is signaled, we + * will wake up before this time, otherwise the error APR_TIMEUP + * is returned. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_timedwait(apr_thread_cond_t *cond, + apr_thread_mutex_t *mutex, + apr_interval_time_t timeout); + +/** + * Signals a single thread, if one exists, that is blocking on the given + * condition variable. That thread is then scheduled to wake up and acquire + * the associated mutex. Although it is not required, if predictable scheduling + * is desired, that mutex must be locked while calling this function. + * @param cond the condition variable on which to produce the signal. + * @remark If no threads are waiting on the condition variable, nothing happens. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_signal(apr_thread_cond_t *cond); + +/** + * Signals all threads blocking on the given condition variable. + * Each thread that was signaled is then scheduled to wake up and acquire + * the associated mutex. This will happen in a serialized manner. + * @param cond the condition variable on which to produce the broadcast. + * @remark If no threads are waiting on the condition variable, nothing happens. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_broadcast(apr_thread_cond_t *cond); + +/** + * Destroy the condition variable and free the associated memory. + * @param cond the condition variable to destroy. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_destroy(apr_thread_cond_t *cond); + +/** + * Get the pool used by this thread_cond. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(thread_cond); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_THREAD_COND_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_thread_mutex.h b/c/dependencies/windows/apr/x86/include/apr_thread_mutex.h new file mode 100644 index 00000000..8eb61729 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_thread_mutex.h @@ -0,0 +1,123 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_THREAD_MUTEX_H +#define APR_THREAD_MUTEX_H + +/** + * @file apr_thread_mutex.h + * @brief APR Thread Mutex Routines + */ + +#include "apr.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#if APR_HAS_THREADS || defined(DOXYGEN) + +/** + * @defgroup apr_thread_mutex Thread Mutex Routines + * @ingroup APR + * @{ + */ + +/** Opaque thread-local mutex structure */ +typedef struct apr_thread_mutex_t apr_thread_mutex_t; + +#define APR_THREAD_MUTEX_DEFAULT 0x0 /**< platform-optimal lock behavior */ +#define APR_THREAD_MUTEX_NESTED 0x1 /**< enable nested (recursive) locks */ +#define APR_THREAD_MUTEX_UNNESTED 0x2 /**< disable nested locks */ +#define APR_THREAD_MUTEX_TIMED 0x4 /**< enable timed locks */ + +/* Delayed the include to avoid a circular reference */ +#include "apr_pools.h" +#include "apr_time.h" + +/** + * Create and initialize a mutex that can be used to synchronize threads. + * @param mutex the memory address where the newly created mutex will be + * stored. + * @param flags Or'ed value of: + *
+ *           APR_THREAD_MUTEX_DEFAULT   platform-optimal lock behavior.
+ *           APR_THREAD_MUTEX_NESTED    enable nested (recursive) locks.
+ *           APR_THREAD_MUTEX_UNNESTED  disable nested locks (non-recursive).
+ * 
+ * @param pool the pool from which to allocate the mutex. + * @warning Be cautious in using APR_THREAD_MUTEX_DEFAULT. While this is the + * most optimal mutex based on a given platform's performance characteristics, + * it will behave as either a nested or an unnested lock. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_create(apr_thread_mutex_t **mutex, + unsigned int flags, + apr_pool_t *pool); +/** + * Acquire the lock for the given mutex. If the mutex is already locked, + * the current thread will be put to sleep until the lock becomes available. + * @param mutex the mutex on which to acquire the lock. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_lock(apr_thread_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex. If the mutex has already + * been acquired, the call returns immediately with APR_EBUSY. Note: it + * is important that the APR_STATUS_IS_EBUSY(s) macro be used to determine + * if the return value was APR_EBUSY, for portability reasons. + * @param mutex the mutex on which to attempt the lock acquiring. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_trylock(apr_thread_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex until timeout expires. + * If the acquisition time outs, the call returns with APR_TIMEUP. + * @param mutex the mutex on which to attempt the lock acquiring. + * @param timeout the relative timeout (microseconds). + * @note A timeout negative or nul means immediate attempt, returning + * APR_TIMEUP without blocking if it the lock is already acquired. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_timedlock(apr_thread_mutex_t *mutex, + apr_interval_time_t timeout); + +/** + * Release the lock for the given mutex. + * @param mutex the mutex from which to release the lock. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_unlock(apr_thread_mutex_t *mutex); + +/** + * Destroy the mutex and free the memory associated with the lock. + * @param mutex the mutex to destroy. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_destroy(apr_thread_mutex_t *mutex); + +/** + * Get the pool used by this thread_mutex. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(thread_mutex); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_THREAD_MUTEX_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_thread_pool.h b/c/dependencies/windows/apr/x86/include/apr_thread_pool.h new file mode 100644 index 00000000..cbf382b3 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_thread_pool.h @@ -0,0 +1,299 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +#ifndef APU_THREAD_POOL_H +#define APU_THREAD_POOL_H + +#include "apu.h" +#include "apr_thread_proc.h" + +/** + * @file apr_thread_pool.h + * @brief APR Thread Pool Library + + * @remarks This library implements a thread pool using apr_thread_t. A thread + * pool is a set of threads that can be created in advance or on demand until a + * maximum number. When a task is scheduled, the thread pool will find an idle + * thread to handle the task. In case all existing threads are busy and the + * number of tasks in the queue is higher than the adjustable threshold, the + * pool will try to create a new thread to serve the task if the maximum number + * has not been reached. Otherwise, the task will be put into a queue based on + * priority, which can be valued from 0 to 255, with higher values being served + * first. If there are tasks with the same priority, the new task might be put at + * the top or at the bottom - it depends on which function is used to put the task. + * + * @remarks There may be the case where the thread pool can use up to the maximum + * number of threads at peak load, but having those threads idle afterwards. A + * maximum number of idle threads can be set so that the extra idling threads will + * be terminated to save system resources. + */ +#if APR_HAS_THREADS + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_Util_TP Thread Pool routines + * @ingroup APR_Util + * @{ + */ + +/** Opaque Thread Pool structure. */ +typedef struct apr_thread_pool apr_thread_pool_t; + +#define APR_THREAD_TASK_PRIORITY_LOWEST 0 +#define APR_THREAD_TASK_PRIORITY_LOW 63 +#define APR_THREAD_TASK_PRIORITY_NORMAL 127 +#define APR_THREAD_TASK_PRIORITY_HIGH 191 +#define APR_THREAD_TASK_PRIORITY_HIGHEST 255 + +/** + * Create a thread pool + * @param me The pointer in which to return the newly created apr_thread_pool + * object, or NULL if thread pool creation fails. + * @param init_threads The number of threads to be created initially, this number + * will also be used as the initial value for the maximum number of idle threads. + * @param max_threads The maximum number of threads that can be created + * @param pool The pool to use + * @return APR_SUCCESS if the thread pool was created successfully. Otherwise, + * the error code. + */ +APU_DECLARE(apr_status_t) apr_thread_pool_create(apr_thread_pool_t **me, + apr_size_t init_threads, + apr_size_t max_threads, + apr_pool_t *pool); + +/** + * Destroy the thread pool and stop all the threads + * @return APR_SUCCESS if all threads are stopped. + */ +APU_DECLARE(apr_status_t) apr_thread_pool_destroy(apr_thread_pool_t *me); + +/** + * Schedule a task to the bottom of the tasks of same priority. + * @param me The thread pool + * @param func The task function + * @param param The parameter for the task function + * @param priority The priority of the task. + * @param owner Owner of this task. + * @return APR_SUCCESS if the task had been scheduled successfully + */ +APU_DECLARE(apr_status_t) apr_thread_pool_push(apr_thread_pool_t *me, + apr_thread_start_t func, + void *param, + apr_byte_t priority, + void *owner); +/** + * Schedule a task to be run after a delay + * @param me The thread pool + * @param func The task function + * @param param The parameter for the task function + * @param time Time in microseconds + * @param owner Owner of this task. + * @return APR_SUCCESS if the task had been scheduled successfully + */ +APU_DECLARE(apr_status_t) apr_thread_pool_schedule(apr_thread_pool_t *me, + apr_thread_start_t func, + void *param, + apr_interval_time_t time, + void *owner); + +/** + * Schedule a task to the top of the tasks of same priority. + * @param me The thread pool + * @param func The task function + * @param param The parameter for the task function + * @param priority The priority of the task. + * @param owner Owner of this task. + * @return APR_SUCCESS if the task had been scheduled successfully + */ +APU_DECLARE(apr_status_t) apr_thread_pool_top(apr_thread_pool_t *me, + apr_thread_start_t func, + void *param, + apr_byte_t priority, + void *owner); + +/** + * Cancel tasks submitted by the owner. If there is any task from the owner that + * is currently running, the function will spin until the task finished. + * @param me The thread pool + * @param owner Owner of the task + * @return APR_SUCCESS if the task has been cancelled successfully + * @note The task function should not be calling cancel, otherwise the function + * may get stuck forever. The function assert if it detect such a case. + */ +APU_DECLARE(apr_status_t) apr_thread_pool_tasks_cancel(apr_thread_pool_t *me, + void *owner); + +/** + * Get the current number of tasks waiting in the queue + * @param me The thread pool + * @return Number of tasks in the queue + */ +APU_DECLARE(apr_size_t) apr_thread_pool_tasks_count(apr_thread_pool_t *me); + +/** + * Get the current number of scheduled tasks waiting in the queue + * @param me The thread pool + * @return Number of scheduled tasks in the queue + */ +APU_DECLARE(apr_size_t) apr_thread_pool_scheduled_tasks_count(apr_thread_pool_t *me); + +/** + * Get the current number of threads + * @param me The thread pool + * @return Total number of threads + */ +APU_DECLARE(apr_size_t) apr_thread_pool_threads_count(apr_thread_pool_t *me); + +/** + * Get the current number of busy threads + * @param me The thread pool + * @return Number of busy threads + */ +APU_DECLARE(apr_size_t) apr_thread_pool_busy_count(apr_thread_pool_t *me); + +/** + * Get the current number of idle threads + * @param me The thread pool + * @return Number of idle threads + */ +APU_DECLARE(apr_size_t) apr_thread_pool_idle_count(apr_thread_pool_t *me); + +/** + * Access function for the maximum number of idle threads. Number of current + * idle threads will be reduced to the new limit. + * @param me The thread pool + * @param cnt The number + * @return The number of threads that were stopped. + */ +APU_DECLARE(apr_size_t) apr_thread_pool_idle_max_set(apr_thread_pool_t *me, + apr_size_t cnt); + +/** + * Get number of tasks that have run + * @param me The thread pool + * @return Number of tasks that have run + */ +APU_DECLARE(apr_size_t) + apr_thread_pool_tasks_run_count(apr_thread_pool_t * me); + +/** + * Get high water mark of the number of tasks waiting to run + * @param me The thread pool + * @return High water mark of tasks waiting to run + */ +APU_DECLARE(apr_size_t) + apr_thread_pool_tasks_high_count(apr_thread_pool_t * me); + +/** + * Get high water mark of the number of threads + * @param me The thread pool + * @return High water mark of threads in thread pool + */ +APU_DECLARE(apr_size_t) + apr_thread_pool_threads_high_count(apr_thread_pool_t * me); + +/** + * Get the number of idle threads that were destroyed after timing out + * @param me The thread pool + * @return Number of idle threads that timed out + */ +APU_DECLARE(apr_size_t) + apr_thread_pool_threads_idle_timeout_count(apr_thread_pool_t * me); + +/** + * Access function for the maximum number of idle threads + * @param me The thread pool + * @return The current maximum number + */ +APU_DECLARE(apr_size_t) apr_thread_pool_idle_max_get(apr_thread_pool_t *me); + +/** + * Access function for the maximum number of threads. + * @param me The thread pool + * @param cnt Number of threads + * @return The original maximum number of threads + */ +APU_DECLARE(apr_size_t) apr_thread_pool_thread_max_set(apr_thread_pool_t *me, + apr_size_t cnt); + +/** + * Access function for the maximum wait time (in microseconds) of an + * idling thread that exceeds the maximum number of idling threads. + * A non-zero value allows for the reaping of idling threads to shrink + * over time. Which helps reduce thrashing. + * @param me The thread pool + * @param timeout The number of microseconds an idle thread should wait + * till it reaps itself + * @return The original maximum wait time + */ +APU_DECLARE(apr_interval_time_t) + apr_thread_pool_idle_wait_set(apr_thread_pool_t * me, + apr_interval_time_t timeout); + +/** + * Access function for the maximum wait time (in microseconds) of an + * idling thread that exceeds the maximum number of idling threads + * @param me The thread pool + * @return The current maximum wait time + */ +APU_DECLARE(apr_interval_time_t) + apr_thread_pool_idle_wait_get(apr_thread_pool_t * me); + +/** + * Access function for the maximum number of threads + * @param me The thread pool + * @return The current maximum number + */ +APU_DECLARE(apr_size_t) apr_thread_pool_thread_max_get(apr_thread_pool_t *me); + +/** + * Access function for the threshold of tasks in queue to trigger a new thread. + * @param me The thread pool + * @param cnt The new threshold + * @return The original threshold + */ +APU_DECLARE(apr_size_t) apr_thread_pool_threshold_set(apr_thread_pool_t *me, + apr_size_t val); + +/** + * Access function for the threshold of tasks in queue to trigger a new thread. + * @param me The thread pool + * @return The current threshold + */ +APU_DECLARE(apr_size_t) apr_thread_pool_threshold_get(apr_thread_pool_t * me); + +/** + * Get owner of the task currently been executed by the thread. + * @param thd The thread is executing a task + * @param owner Pointer to receive owner of the task. + * @return APR_SUCCESS if the owner is retrieved successfully + */ +APU_DECLARE(apr_status_t) apr_thread_pool_task_owner_get(apr_thread_t *thd, + void **owner); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_HAS_THREADS */ +#endif /* !APR_THREAD_POOL_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_thread_proc.h b/c/dependencies/windows/apr/x86/include/apr_thread_proc.h new file mode 100644 index 00000000..ea3c43f9 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_thread_proc.h @@ -0,0 +1,846 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_THREAD_PROC_H +#define APR_THREAD_PROC_H + +/** + * @file apr_thread_proc.h + * @brief APR Thread and Process Library + */ + +#include "apr.h" +#include "apr_file_io.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_perms_set.h" + +#if APR_HAVE_STRUCT_RLIMIT +#include +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_thread_proc Threads and Process Functions + * @ingroup APR + * @{ + */ + +typedef enum { + APR_SHELLCMD, /**< use the shell to invoke the program */ + APR_PROGRAM, /**< invoke the program directly, no copied env */ + APR_PROGRAM_ENV, /**< invoke the program, replicating our environment */ + APR_PROGRAM_PATH, /**< find program on PATH, use our environment */ + APR_SHELLCMD_ENV /**< use the shell to invoke the program, + * replicating our environment + */ +} apr_cmdtype_e; + +typedef enum { + APR_WAIT, /**< wait for the specified process to finish */ + APR_NOWAIT /**< do not wait -- just see if it has finished */ +} apr_wait_how_e; + +/* I am specifically calling out the values so that the macros below make + * more sense. Yes, I know I don't need to, but I am hoping this makes what + * I am doing more clear. If you want to add more reasons to exit, continue + * to use bitmasks. + */ +typedef enum { + APR_PROC_EXIT = 1, /**< process exited normally */ + APR_PROC_SIGNAL = 2, /**< process exited due to a signal */ + APR_PROC_SIGNAL_CORE = 4 /**< process exited and dumped a core file */ +} apr_exit_why_e; + +/** did we exit the process */ +#define APR_PROC_CHECK_EXIT(x) (x & APR_PROC_EXIT) +/** did we get a signal */ +#define APR_PROC_CHECK_SIGNALED(x) (x & APR_PROC_SIGNAL) +/** did we get core */ +#define APR_PROC_CHECK_CORE_DUMP(x) (x & APR_PROC_SIGNAL_CORE) + +/** @see apr_procattr_io_set */ +#define APR_NO_PIPE 0 +/** @see apr_procattr_io_set and apr_file_pipe_create_ex */ +#define APR_FULL_BLOCK 1 +/** @see apr_procattr_io_set and apr_file_pipe_create_ex */ +#define APR_FULL_NONBLOCK 2 +/** @see apr_procattr_io_set */ +#define APR_PARENT_BLOCK 3 +/** @see apr_procattr_io_set */ +#define APR_CHILD_BLOCK 4 +/** @see apr_procattr_io_set */ +#define APR_NO_FILE 8 + +/** @see apr_file_pipe_create_ex */ +#define APR_READ_BLOCK 3 +/** @see apr_file_pipe_create_ex */ +#define APR_WRITE_BLOCK 4 + +/** @see apr_procattr_io_set + * @note Win32 only effective with version 1.2.12, portably introduced in 1.3.0 + */ +#define APR_NO_FILE 8 + +/** @see apr_procattr_limit_set */ +#define APR_LIMIT_CPU 0 +/** @see apr_procattr_limit_set */ +#define APR_LIMIT_MEM 1 +/** @see apr_procattr_limit_set */ +#define APR_LIMIT_NPROC 2 +/** @see apr_procattr_limit_set */ +#define APR_LIMIT_NOFILE 3 + +/** + * @defgroup APR_OC Other Child Flags + * @{ + */ +#define APR_OC_REASON_DEATH 0 /**< child has died, caller must call + * unregister still */ +#define APR_OC_REASON_UNWRITABLE 1 /**< write_fd is unwritable */ +#define APR_OC_REASON_RESTART 2 /**< a restart is occurring, perform + * any necessary cleanup (including + * sending a special signal to child) + */ +#define APR_OC_REASON_UNREGISTER 3 /**< unregister has been called, do + * whatever is necessary (including + * kill the child) */ +#define APR_OC_REASON_LOST 4 /**< somehow the child exited without + * us knowing ... buggy os? */ +#define APR_OC_REASON_RUNNING 5 /**< a health check is occurring, + * for most maintainence functions + * this is a no-op. + */ +/** @} */ + +/** The APR process type */ +typedef struct apr_proc_t { + /** The process ID */ + pid_t pid; + /** Parent's side of pipe to child's stdin */ + apr_file_t *in; + /** Parent's side of pipe to child's stdout */ + apr_file_t *out; + /** Parent's side of pipe to child's stdouterr */ + apr_file_t *err; +#if APR_HAS_PROC_INVOKED || defined(DOXYGEN) + /** Diagnositics/debugging string of the command invoked for + * this process [only present if APR_HAS_PROC_INVOKED is true] + * @remark Only enabled on Win32 by default. + * @bug This should either always or never be present in release + * builds - since it breaks binary compatibility. We may enable + * it always in APR 1.0 yet leave it undefined in most cases. + */ + char *invoked; +#endif +#if defined(WIN32) || defined(DOXYGEN) + /** (Win32 only) Creator's handle granting access to the process + * @remark This handle is closed and reset to NULL in every case + * corresponding to a waitpid() on Unix which returns the exit status. + * Therefore Win32 correspond's to Unix's zombie reaping characteristics + * and avoids potential handle leaks. + */ + HANDLE hproc; +#endif +} apr_proc_t; + +/** + * The prototype for APR child errfn functions. (See the description + * of apr_procattr_child_errfn_set() for more information.) + * It is passed the following parameters: + * @param pool Pool associated with the apr_proc_t. If your child + * error function needs user data, associate it with this + * pool. + * @param err APR error code describing the error + * @param description Text description of type of processing which failed + */ +typedef void (apr_child_errfn_t)(apr_pool_t *proc, apr_status_t err, + const char *description); + +/** Opaque Thread structure. */ +typedef struct apr_thread_t apr_thread_t; + +/** Opaque Thread attributes structure. */ +typedef struct apr_threadattr_t apr_threadattr_t; + +/** Opaque Process attributes structure. */ +typedef struct apr_procattr_t apr_procattr_t; + +/** Opaque control variable for one-time atomic variables. */ +typedef struct apr_thread_once_t apr_thread_once_t; + +/** Opaque thread private address space. */ +typedef struct apr_threadkey_t apr_threadkey_t; + +/** Opaque record of child process. */ +typedef struct apr_other_child_rec_t apr_other_child_rec_t; + +/** + * The prototype for any APR thread worker functions. + */ +typedef void *(APR_THREAD_FUNC *apr_thread_start_t)(apr_thread_t*, void*); + +typedef enum { + APR_KILL_NEVER, /**< process is never killed (i.e., never sent + * any signals), but it will be reaped if it exits + * before the pool is cleaned up */ + APR_KILL_ALWAYS, /**< process is sent SIGKILL on apr_pool_t cleanup */ + APR_KILL_AFTER_TIMEOUT, /**< SIGTERM, wait 3 seconds, SIGKILL */ + APR_JUST_WAIT, /**< wait forever for the process to complete */ + APR_KILL_ONLY_ONCE /**< send SIGTERM and then wait */ +} apr_kill_conditions_e; + +/* Thread Function definitions */ + +#if APR_HAS_THREADS + +/** + * Create and initialize a new threadattr variable + * @param new_attr The newly created threadattr. + * @param cont The pool to use + */ +APR_DECLARE(apr_status_t) apr_threadattr_create(apr_threadattr_t **new_attr, + apr_pool_t *cont); + +/** + * Set if newly created threads should be created in detached state. + * @param attr The threadattr to affect + * @param on Non-zero if detached threads should be created. + */ +APR_DECLARE(apr_status_t) apr_threadattr_detach_set(apr_threadattr_t *attr, + apr_int32_t on); + +/** + * Get the detach state for this threadattr. + * @param attr The threadattr to reference + * @return APR_DETACH if threads are to be detached, or APR_NOTDETACH + * if threads are to be joinable. + */ +APR_DECLARE(apr_status_t) apr_threadattr_detach_get(apr_threadattr_t *attr); + +/** + * Set the stack size of newly created threads. + * @param attr The threadattr to affect + * @param stacksize The stack size in bytes + */ +APR_DECLARE(apr_status_t) apr_threadattr_stacksize_set(apr_threadattr_t *attr, + apr_size_t stacksize); + +/** + * Set the stack guard area size of newly created threads. + * @param attr The threadattr to affect + * @param guardsize The stack guard area size in bytes + * @note Thread library implementations commonly use a "guard area" + * after each thread's stack which is not readable or writable such that + * stack overflows cause a segfault; this consumes e.g. 4K of memory + * and increases memory management overhead. Setting the guard area + * size to zero hence trades off reliable behaviour on stack overflow + * for performance. */ +APR_DECLARE(apr_status_t) apr_threadattr_guardsize_set(apr_threadattr_t *attr, + apr_size_t guardsize); + +/** + * Create a new thread of execution + * @param new_thread The newly created thread handle. + * @param attr The threadattr to use to determine how to create the thread + * @param func The function to start the new thread in + * @param data Any data to be passed to the starting function + * @param cont The pool to use + */ +APR_DECLARE(apr_status_t) apr_thread_create(apr_thread_t **new_thread, + apr_threadattr_t *attr, + apr_thread_start_t func, + void *data, apr_pool_t *cont); + +/** + * stop the current thread + * @param thd The thread to stop + * @param retval The return value to pass back to any thread that cares + */ +APR_DECLARE(apr_status_t) apr_thread_exit(apr_thread_t *thd, + apr_status_t retval); + +/** + * block until the desired thread stops executing. + * @param retval The return value from the dead thread. + * @param thd The thread to join + */ +APR_DECLARE(apr_status_t) apr_thread_join(apr_status_t *retval, + apr_thread_t *thd); + +/** + * force the current thread to yield the processor + */ +APR_DECLARE(void) apr_thread_yield(void); + +/** + * Initialize the control variable for apr_thread_once. If this isn't + * called, apr_initialize won't work. + * @param control The control variable to initialize + * @param p The pool to allocate data from. + */ +APR_DECLARE(apr_status_t) apr_thread_once_init(apr_thread_once_t **control, + apr_pool_t *p); + +/** + * Run the specified function one time, regardless of how many threads + * call it. + * @param control The control variable. The same variable should + * be passed in each time the function is tried to be + * called. This is how the underlying functions determine + * if the function has ever been called before. + * @param func The function to call. + */ +APR_DECLARE(apr_status_t) apr_thread_once(apr_thread_once_t *control, + void (*func)(void)); + +/** + * detach a thread + * @param thd The thread to detach + */ +APR_DECLARE(apr_status_t) apr_thread_detach(apr_thread_t *thd); + +/** + * Return user data associated with the current thread. + * @param data The user data associated with the thread. + * @param key The key to associate with the data + * @param thread The currently open thread. + */ +APR_DECLARE(apr_status_t) apr_thread_data_get(void **data, const char *key, + apr_thread_t *thread); + +/** + * Set user data associated with the current thread. + * @param data The user data to associate with the thread. + * @param key The key to use for associating the data with the thread + * @param cleanup The cleanup routine to use when the thread is destroyed. + * @param thread The currently open thread. + */ +APR_DECLARE(apr_status_t) apr_thread_data_set(void *data, const char *key, + apr_status_t (*cleanup) (void *), + apr_thread_t *thread); + +/** + * Create and initialize a new thread private address space + * @param key The thread private handle. + * @param dest The destructor to use when freeing the private memory. + * @param cont The pool to use + */ +APR_DECLARE(apr_status_t) apr_threadkey_private_create(apr_threadkey_t **key, + void (*dest)(void *), + apr_pool_t *cont); + +/** + * Get a pointer to the thread private memory + * @param new_mem The data stored in private memory + * @param key The handle for the desired thread private memory + */ +APR_DECLARE(apr_status_t) apr_threadkey_private_get(void **new_mem, + apr_threadkey_t *key); + +/** + * Set the data to be stored in thread private memory + * @param priv The data to be stored in private memory + * @param key The handle for the desired thread private memory + */ +APR_DECLARE(apr_status_t) apr_threadkey_private_set(void *priv, + apr_threadkey_t *key); + +/** + * Free the thread private memory + * @param key The handle for the desired thread private memory + */ +APR_DECLARE(apr_status_t) apr_threadkey_private_delete(apr_threadkey_t *key); + +/** + * Return the pool associated with the current threadkey. + * @param data The user data associated with the threadkey. + * @param key The key associated with the data + * @param threadkey The currently open threadkey. + */ +APR_DECLARE(apr_status_t) apr_threadkey_data_get(void **data, const char *key, + apr_threadkey_t *threadkey); + +/** + * Return the pool associated with the current threadkey. + * @param data The data to set. + * @param key The key to associate with the data. + * @param cleanup The cleanup routine to use when the file is destroyed. + * @param threadkey The currently open threadkey. + */ +APR_DECLARE(apr_status_t) apr_threadkey_data_set(void *data, const char *key, + apr_status_t (*cleanup) (void *), + apr_threadkey_t *threadkey); + +#endif + +/** + * Create and initialize a new procattr variable + * @param new_attr The newly created procattr. + * @param cont The pool to use + */ +APR_DECLARE(apr_status_t) apr_procattr_create(apr_procattr_t **new_attr, + apr_pool_t *cont); + +/** + * Determine if any of stdin, stdout, or stderr should be linked to pipes + * when starting a child process. + * @param attr The procattr we care about. + * @param in Should stdin be a pipe back to the parent? + * @param out Should stdout be a pipe back to the parent? + * @param err Should stderr be a pipe back to the parent? + * @note If APR_NO_PIPE, there will be no special channel, the child + * inherits the parent's corresponding stdio stream. If APR_NO_FILE is + * specified, that corresponding stream is closed in the child (and will + * be INVALID_HANDLE_VALUE when inspected on Win32). This can have ugly + * side effects, as the next file opened in the child on Unix will fall + * into the stdio stream fd slot! + */ +APR_DECLARE(apr_status_t) apr_procattr_io_set(apr_procattr_t *attr, + apr_int32_t in, apr_int32_t out, + apr_int32_t err); + +/** + * Set the child_in and/or parent_in values to existing apr_file_t values. + * @param attr The procattr we care about. + * @param child_in apr_file_t value to use as child_in. Must be a valid file. + * @param parent_in apr_file_t value to use as parent_in. Must be a valid file. + * @remark This is NOT a required initializer function. This is + * useful if you have already opened a pipe (or multiple files) + * that you wish to use, perhaps persistently across multiple + * process invocations - such as a log file. You can save some + * extra function calls by not creating your own pipe since this + * creates one in the process space for you. + * @bug Note that calling this function with two NULL files on some platforms + * creates an APR_FULL_BLOCK pipe, but this behavior is neither portable nor + * is it supported. @see apr_procattr_io_set instead for simple pipes. + */ +APR_DECLARE(apr_status_t) apr_procattr_child_in_set(struct apr_procattr_t *attr, + apr_file_t *child_in, + apr_file_t *parent_in); + +/** + * Set the child_out and parent_out values to existing apr_file_t values. + * @param attr The procattr we care about. + * @param child_out apr_file_t value to use as child_out. Must be a valid file. + * @param parent_out apr_file_t value to use as parent_out. Must be a valid file. + * @remark This is NOT a required initializer function. This is + * useful if you have already opened a pipe (or multiple files) + * that you wish to use, perhaps persistently across multiple + * process invocations - such as a log file. + * @bug Note that calling this function with two NULL files on some platforms + * creates an APR_FULL_BLOCK pipe, but this behavior is neither portable nor + * is it supported. @see apr_procattr_io_set instead for simple pipes. + */ +APR_DECLARE(apr_status_t) apr_procattr_child_out_set(struct apr_procattr_t *attr, + apr_file_t *child_out, + apr_file_t *parent_out); + +/** + * Set the child_err and parent_err values to existing apr_file_t values. + * @param attr The procattr we care about. + * @param child_err apr_file_t value to use as child_err. Must be a valid file. + * @param parent_err apr_file_t value to use as parent_err. Must be a valid file. + * @remark This is NOT a required initializer function. This is + * useful if you have already opened a pipe (or multiple files) + * that you wish to use, perhaps persistently across multiple + * process invocations - such as a log file. + * @bug Note that calling this function with two NULL files on some platforms + * creates an APR_FULL_BLOCK pipe, but this behavior is neither portable nor + * is it supported. @see apr_procattr_io_set instead for simple pipes. + */ +APR_DECLARE(apr_status_t) apr_procattr_child_err_set(struct apr_procattr_t *attr, + apr_file_t *child_err, + apr_file_t *parent_err); + +/** + * Set which directory the child process should start executing in. + * @param attr The procattr we care about. + * @param dir Which dir to start in. By default, this is the same dir as + * the parent currently resides in, when the createprocess call + * is made. + */ +APR_DECLARE(apr_status_t) apr_procattr_dir_set(apr_procattr_t *attr, + const char *dir); + +/** + * Set what type of command the child process will call. + * @param attr The procattr we care about. + * @param cmd The type of command. One of: + *
+ *            APR_SHELLCMD     --  Anything that the shell can handle
+ *            APR_PROGRAM      --  Executable program   (default) 
+ *            APR_PROGRAM_ENV  --  Executable program, copy environment
+ *            APR_PROGRAM_PATH --  Executable program on PATH, copy env
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_procattr_cmdtype_set(apr_procattr_t *attr, + apr_cmdtype_e cmd); + +/** + * Determine if the child should start in detached state. + * @param attr The procattr we care about. + * @param detach Should the child start in detached state? Default is no. + */ +APR_DECLARE(apr_status_t) apr_procattr_detach_set(apr_procattr_t *attr, + apr_int32_t detach); + +#if APR_HAVE_STRUCT_RLIMIT +/** + * Set the Resource Utilization limits when starting a new process. + * @param attr The procattr we care about. + * @param what Which limit to set, one of: + *
+ *                 APR_LIMIT_CPU
+ *                 APR_LIMIT_MEM
+ *                 APR_LIMIT_NPROC
+ *                 APR_LIMIT_NOFILE
+ * 
+ * @param limit Value to set the limit to. + */ +APR_DECLARE(apr_status_t) apr_procattr_limit_set(apr_procattr_t *attr, + apr_int32_t what, + struct rlimit *limit); +#endif + +/** + * Specify an error function to be called in the child process if APR + * encounters an error in the child prior to running the specified program. + * @param attr The procattr describing the child process to be created. + * @param errfn The function to call in the child process. + * @remark At the present time, it will only be called from apr_proc_create() + * on platforms where fork() is used. It will never be called on other + * platforms, on those platforms apr_proc_create() will return the error + * in the parent process rather than invoke the callback in the now-forked + * child process. + */ +APR_DECLARE(apr_status_t) apr_procattr_child_errfn_set(apr_procattr_t *attr, + apr_child_errfn_t *errfn); + +/** + * Specify that apr_proc_create() should do whatever it can to report + * failures to the caller of apr_proc_create(), rather than find out in + * the child. + * @param attr The procattr describing the child process to be created. + * @param chk Flag to indicate whether or not extra work should be done + * to try to report failures to the caller. + * @remark This flag only affects apr_proc_create() on platforms where + * fork() is used. This leads to extra overhead in the calling + * process, but that may help the application handle such + * errors more gracefully. + */ +APR_DECLARE(apr_status_t) apr_procattr_error_check_set(apr_procattr_t *attr, + apr_int32_t chk); + +/** + * Determine if the child should start in its own address space or using the + * current one from its parent + * @param attr The procattr we care about. + * @param addrspace Should the child start in its own address space? Default + * is no on NetWare and yes on other platforms. + */ +APR_DECLARE(apr_status_t) apr_procattr_addrspace_set(apr_procattr_t *attr, + apr_int32_t addrspace); + +/** + * Set the username used for running process + * @param attr The procattr we care about. + * @param username The username used + * @param password User password if needed. Password is needed on WIN32 + * or any other platform having + * APR_PROCATTR_USER_SET_REQUIRES_PASSWORD set. + */ +APR_DECLARE(apr_status_t) apr_procattr_user_set(apr_procattr_t *attr, + const char *username, + const char *password); + +/** + * Set the group used for running process + * @param attr The procattr we care about. + * @param groupname The group name used + */ +APR_DECLARE(apr_status_t) apr_procattr_group_set(apr_procattr_t *attr, + const char *groupname); + + +/** + * Register permission set function + * @param attr The procattr we care about. + * @param perms_set_fn Permission set callback + * @param data Data to pass to permission callback function + * @param perms Permissions to set + */ +APR_DECLARE(apr_status_t) apr_procattr_perms_set_register(apr_procattr_t *attr, + apr_perms_setfn_t *perms_set_fn, + void *data, + apr_fileperms_t perms); + +#if APR_HAS_FORK +/** + * This is currently the only non-portable call in APR. This executes + * a standard unix fork. + * @param proc The resulting process handle. + * @param cont The pool to use. + * @remark returns APR_INCHILD for the child, and APR_INPARENT for the parent + * or an error. + */ +APR_DECLARE(apr_status_t) apr_proc_fork(apr_proc_t *proc, apr_pool_t *cont); +#endif + +/** + * Create a new process and execute a new program within that process. + * @param new_proc The resulting process handle. + * @param progname The program to run + * @param args the arguments to pass to the new program. The first + * one should be the program name. + * @param env The new environment table for the new process. This + * should be a list of NULL-terminated strings. This argument + * is ignored for APR_PROGRAM_ENV, APR_PROGRAM_PATH, and + * APR_SHELLCMD_ENV types of commands. + * @param attr the procattr we should use to determine how to create the new + * process + * @param pool The pool to use. + * @note This function returns without waiting for the new process to terminate; + * use apr_proc_wait for that. + */ +APR_DECLARE(apr_status_t) apr_proc_create(apr_proc_t *new_proc, + const char *progname, + const char * const *args, + const char * const *env, + apr_procattr_t *attr, + apr_pool_t *pool); + +/** + * Wait for a child process to die + * @param proc The process handle that corresponds to the desired child process + * @param exitcode The returned exit status of the child, if a child process + * dies, or the signal that caused the child to die. + * On platforms that don't support obtaining this information, + * the status parameter will be returned as APR_ENOTIMPL. + * @param exitwhy Why the child died, the bitwise or of: + *
+ *            APR_PROC_EXIT         -- process terminated normally
+ *            APR_PROC_SIGNAL       -- process was killed by a signal
+ *            APR_PROC_SIGNAL_CORE  -- process was killed by a signal, and
+ *                                     generated a core dump.
+ * 
+ * @param waithow How should we wait. One of: + *
+ *            APR_WAIT   -- block until the child process dies.
+ *            APR_NOWAIT -- return immediately regardless of if the 
+ *                          child is dead or not.
+ * 
+ * @remark The child's status is in the return code to this process. It is one of: + *
+ *            APR_CHILD_DONE     -- child is no longer running.
+ *            APR_CHILD_NOTDONE  -- child is still running.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_proc_wait(apr_proc_t *proc, + int *exitcode, apr_exit_why_e *exitwhy, + apr_wait_how_e waithow); + +/** + * Wait for any current child process to die and return information + * about that child. + * @param proc Pointer to NULL on entry, will be filled out with child's + * information + * @param exitcode The returned exit status of the child, if a child process + * dies, or the signal that caused the child to die. + * On platforms that don't support obtaining this information, + * the status parameter will be returned as APR_ENOTIMPL. + * @param exitwhy Why the child died, the bitwise or of: + *
+ *            APR_PROC_EXIT         -- process terminated normally
+ *            APR_PROC_SIGNAL       -- process was killed by a signal
+ *            APR_PROC_SIGNAL_CORE  -- process was killed by a signal, and
+ *                                     generated a core dump.
+ * 
+ * @param waithow How should we wait. One of: + *
+ *            APR_WAIT   -- block until the child process dies.
+ *            APR_NOWAIT -- return immediately regardless of if the 
+ *                          child is dead or not.
+ * 
+ * @param p Pool to allocate child information out of. + * @bug Passing proc as a *proc rather than **proc was an odd choice + * for some platforms... this should be revisited in 1.0 + */ +APR_DECLARE(apr_status_t) apr_proc_wait_all_procs(apr_proc_t *proc, + int *exitcode, + apr_exit_why_e *exitwhy, + apr_wait_how_e waithow, + apr_pool_t *p); + +#define APR_PROC_DETACH_FOREGROUND 0 /**< Do not detach */ +#define APR_PROC_DETACH_DAEMONIZE 1 /**< Detach */ + +/** + * Detach the process from the controlling terminal. + * @param daemonize set to non-zero if the process should daemonize + * and become a background process, else it will + * stay in the foreground. + */ +APR_DECLARE(apr_status_t) apr_proc_detach(int daemonize); + +/** + * Register an other_child -- a child associated to its registered + * maintence callback. This callback is invoked when the process + * dies, is disconnected or disappears. + * @param proc The child process to register. + * @param maintenance maintenance is a function that is invoked with a + * reason and the data pointer passed here. + * @param data Opaque context data passed to the maintenance function. + * @param write_fd An fd that is probed for writing. If it is ever unwritable + * then the maintenance is invoked with reason + * OC_REASON_UNWRITABLE. + * @param p The pool to use for allocating memory. + * @bug write_fd duplicates the proc->out stream, it's really redundant + * and should be replaced in the APR 1.0 API with a bitflag of which + * proc->in/out/err handles should be health checked. + * @bug no platform currently tests the pipes health. + */ +APR_DECLARE(void) apr_proc_other_child_register(apr_proc_t *proc, + void (*maintenance) (int reason, + void *, + int status), + void *data, apr_file_t *write_fd, + apr_pool_t *p); + +/** + * Stop watching the specified other child. + * @param data The data to pass to the maintenance function. This is + * used to find the process to unregister. + * @warning Since this can be called by a maintenance function while we're + * scanning the other_children list, all scanners should protect + * themself by loading ocr->next before calling any maintenance + * function. + */ +APR_DECLARE(void) apr_proc_other_child_unregister(void *data); + +/** + * Notify the maintenance callback of a registered other child process + * that application has detected an event, such as death. + * @param proc The process to check + * @param reason The reason code to pass to the maintenance function + * @param status The status to pass to the maintenance function + * @remark An example of code using this behavior; + *
+ * rv = apr_proc_wait_all_procs(&proc, &exitcode, &status, APR_WAIT, p);
+ * if (APR_STATUS_IS_CHILD_DONE(rv)) {
+ * \#if APR_HAS_OTHER_CHILD
+ *     if (apr_proc_other_child_alert(&proc, APR_OC_REASON_DEATH, status)
+ *             == APR_SUCCESS) {
+ *         ;  (already handled)
+ *     }
+ *     else
+ * \#endif
+ *         [... handling non-otherchild processes death ...]
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_proc_other_child_alert(apr_proc_t *proc, + int reason, + int status); + +/** + * Test one specific other child processes and invoke the maintenance callback + * with the appropriate reason code, if still running, or the appropriate reason + * code if the process is no longer healthy. + * @param ocr The registered other child + * @param reason The reason code (e.g. APR_OC_REASON_RESTART) if still running + */ +APR_DECLARE(void) apr_proc_other_child_refresh(apr_other_child_rec_t *ocr, + int reason); + +/** + * Test all registered other child processes and invoke the maintenance callback + * with the appropriate reason code, if still running, or the appropriate reason + * code if the process is no longer healthy. + * @param reason The reason code (e.g. APR_OC_REASON_RESTART) to running processes + */ +APR_DECLARE(void) apr_proc_other_child_refresh_all(int reason); + +/** + * Terminate a process. + * @param proc The process to terminate. + * @param sig How to kill the process. + */ +APR_DECLARE(apr_status_t) apr_proc_kill(apr_proc_t *proc, int sig); + +/** + * Register a process to be killed when a pool dies. + * @param a The pool to use to define the processes lifetime + * @param proc The process to register + * @param how How to kill the process, one of: + *
+ *         APR_KILL_NEVER         -- process is never sent any signals
+ *         APR_KILL_ALWAYS        -- process is sent SIGKILL on apr_pool_t cleanup
+ *         APR_KILL_AFTER_TIMEOUT -- SIGTERM, wait 3 seconds, SIGKILL
+ *         APR_JUST_WAIT          -- wait forever for the process to complete
+ *         APR_KILL_ONLY_ONCE     -- send SIGTERM and then wait
+ * 
+ */ +APR_DECLARE(void) apr_pool_note_subprocess(apr_pool_t *a, apr_proc_t *proc, + apr_kill_conditions_e how); + +#if APR_HAS_THREADS + +#if (APR_HAVE_SIGWAIT || APR_HAVE_SIGSUSPEND) && !defined(OS2) + +/** + * Setup the process for a single thread to be used for all signal handling. + * @warning This must be called before any threads are created + */ +APR_DECLARE(apr_status_t) apr_setup_signal_thread(void); + +/** + * Make the current thread listen for signals. This thread will loop + * forever, calling a provided function whenever it receives a signal. That + * functions should return 1 if the signal has been handled, 0 otherwise. + * @param signal_handler The function to call when a signal is received + * apr_status_t apr_signal_thread((int)(*signal_handler)(int signum)) + * @note Synchronous signals like SIGABRT/SIGSEGV/SIGBUS/... are ignored by + * apr_signal_thread() and thus can't be waited by this function (they remain + * handled by the operating system or its native signals interface). + * @remark In APR version 1.6 and ealier, SIGUSR2 was part of these ignored + * signals and thus was never passed in to the signal_handler. From APR 1.7 + * this is no more the case so SIGUSR2 can be handled in signal_handler and + * acted upon like the other asynchronous signals. + */ +APR_DECLARE(apr_status_t) apr_signal_thread(int(*signal_handler)(int signum)); + +#endif /* (APR_HAVE_SIGWAIT || APR_HAVE_SIGSUSPEND) && !defined(OS2) */ + +/** + * Get the child-pool used by the thread from the thread info. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(thread); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_THREAD_PROC_H */ + diff --git a/c/dependencies/windows/apr/x86/include/apr_thread_rwlock.h b/c/dependencies/windows/apr/x86/include/apr_thread_rwlock.h new file mode 100644 index 00000000..0bd958fb --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_thread_rwlock.h @@ -0,0 +1,129 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_THREAD_RWLOCK_H +#define APR_THREAD_RWLOCK_H + +/** + * @file apr_thread_rwlock.h + * @brief APR Reader/Writer Lock Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#if APR_HAS_THREADS + +/** + * @defgroup apr_thread_rwlock Reader/Writer Lock Routines + * @ingroup APR + * @{ + */ + +/** Opaque read-write thread-safe lock. */ +typedef struct apr_thread_rwlock_t apr_thread_rwlock_t; + +/** + * Note: The following operations have undefined results: unlocking a + * read-write lock which is not locked in the calling thread; write + * locking a read-write lock which is already locked by the calling + * thread; destroying a read-write lock more than once; clearing or + * destroying the pool from which a locked read-write lock is + * allocated. + */ + +/** + * Create and initialize a read-write lock that can be used to synchronize + * threads. + * @param rwlock the memory address where the newly created readwrite lock + * will be stored. + * @param pool the pool from which to allocate the mutex. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_create(apr_thread_rwlock_t **rwlock, + apr_pool_t *pool); +/** + * Acquire a shared-read lock on the given read-write lock. This will allow + * multiple threads to enter the same critical section while they have acquired + * the read lock. + * @param rwlock the read-write lock on which to acquire the shared read. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_rdlock(apr_thread_rwlock_t *rwlock); + +/** + * Attempt to acquire the shared-read lock on the given read-write lock. This + * is the same as apr_thread_rwlock_rdlock(), only that the function fails + * if there is another thread holding the write lock, or if there are any + * write threads blocking on the lock. If the function fails for this case, + * APR_EBUSY will be returned. Note: it is important that the + * APR_STATUS_IS_EBUSY(s) macro be used to determine if the return value was + * APR_EBUSY, for portability reasons. + * @param rwlock the rwlock on which to attempt the shared read. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_tryrdlock(apr_thread_rwlock_t *rwlock); + +/** + * Acquire an exclusive-write lock on the given read-write lock. This will + * allow only one single thread to enter the critical sections. If there + * are any threads currently holding the read-lock, this thread is put to + * sleep until it can have exclusive access to the lock. + * @param rwlock the read-write lock on which to acquire the exclusive write. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_wrlock(apr_thread_rwlock_t *rwlock); + +/** + * Attempt to acquire the exclusive-write lock on the given read-write lock. + * This is the same as apr_thread_rwlock_wrlock(), only that the function fails + * if there is any other thread holding the lock (for reading or writing), + * in which case the function will return APR_EBUSY. Note: it is important + * that the APR_STATUS_IS_EBUSY(s) macro be used to determine if the return + * value was APR_EBUSY, for portability reasons. + * @param rwlock the rwlock on which to attempt the exclusive write. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_trywrlock(apr_thread_rwlock_t *rwlock); + +/** + * Release either the read or write lock currently held by the calling thread + * associated with the given read-write lock. + * @param rwlock the read-write lock to be released (unlocked). + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_unlock(apr_thread_rwlock_t *rwlock); + +/** + * Destroy the read-write lock and free the associated memory. + * @param rwlock the rwlock to destroy. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_destroy(apr_thread_rwlock_t *rwlock); + +/** + * Get the pool used by this thread_rwlock. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(thread_rwlock); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_THREAD_RWLOCK_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_time.h b/c/dependencies/windows/apr/x86/include/apr_time.h new file mode 100644 index 00000000..b0efd791 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_time.h @@ -0,0 +1,237 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_TIME_H +#define APR_TIME_H + +/** + * @file apr_time.h + * @brief APR Time Library + */ + +#include "apr.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_time Time Routines + * @ingroup APR + * @{ + */ + +/** month names */ +APR_DECLARE_DATA extern const char apr_month_snames[12][4]; +/** day names */ +APR_DECLARE_DATA extern const char apr_day_snames[7][4]; + + +/** number of microseconds since 00:00:00 January 1, 1970 UTC */ +typedef apr_int64_t apr_time_t; + + +/** mechanism to properly type apr_time_t literals */ +#define APR_TIME_C(val) APR_INT64_C(val) + +/** mechanism to properly print apr_time_t values */ +#define APR_TIME_T_FMT APR_INT64_T_FMT + +/** intervals for I/O timeouts, in microseconds */ +typedef apr_int64_t apr_interval_time_t; +/** short interval for I/O timeouts, in microseconds */ +typedef apr_int32_t apr_short_interval_time_t; + +/** number of microseconds per second */ +#define APR_USEC_PER_SEC APR_TIME_C(1000000) + +/** @return apr_time_t as a second */ +#define apr_time_sec(time) ((time) / APR_USEC_PER_SEC) + +/** @return apr_time_t as a usec */ +#define apr_time_usec(time) ((time) % APR_USEC_PER_SEC) + +/** @return apr_time_t as a msec */ +#define apr_time_msec(time) (((time) / 1000) % 1000) + +/** @return apr_time_t as a msec */ +#define apr_time_as_msec(time) ((time) / 1000) + +/** @return milliseconds as an apr_time_t */ +#define apr_time_from_msec(msec) ((apr_time_t)(msec) * 1000) + +/** @return seconds as an apr_time_t */ +#define apr_time_from_sec(sec) ((apr_time_t)(sec) * APR_USEC_PER_SEC) + +/** @return a second and usec combination as an apr_time_t */ +#define apr_time_make(sec, usec) ((apr_time_t)(sec) * APR_USEC_PER_SEC \ + + (apr_time_t)(usec)) + +/** + * @return the current time + */ +APR_DECLARE(apr_time_t) apr_time_now(void); + +/** @see apr_time_exp_t */ +typedef struct apr_time_exp_t apr_time_exp_t; + +/** + * a structure similar to ANSI struct tm with the following differences: + * - tm_usec isn't an ANSI field + * - tm_gmtoff isn't an ANSI field (it's a BSDism) + */ +struct apr_time_exp_t { + /** microseconds past tm_sec */ + apr_int32_t tm_usec; + /** (0-61) seconds past tm_min */ + apr_int32_t tm_sec; + /** (0-59) minutes past tm_hour */ + apr_int32_t tm_min; + /** (0-23) hours past midnight */ + apr_int32_t tm_hour; + /** (1-31) day of the month */ + apr_int32_t tm_mday; + /** (0-11) month of the year */ + apr_int32_t tm_mon; + /** year since 1900 */ + apr_int32_t tm_year; + /** (0-6) days since Sunday */ + apr_int32_t tm_wday; + /** (0-365) days since January 1 */ + apr_int32_t tm_yday; + /** daylight saving time */ + apr_int32_t tm_isdst; + /** seconds east of UTC */ + apr_int32_t tm_gmtoff; +}; + +/* Delayed the include to avoid a circular reference */ +#include "apr_pools.h" + +/** + * Convert an ansi time_t to an apr_time_t + * @param result the resulting apr_time_t + * @param input the time_t to convert + */ +APR_DECLARE(apr_status_t) apr_time_ansi_put(apr_time_t *result, + time_t input); + +/** + * Convert a time to its human readable components using an offset + * from GMT. + * @param result the exploded time + * @param input the time to explode + * @param offs the number of seconds offset to apply + */ +APR_DECLARE(apr_status_t) apr_time_exp_tz(apr_time_exp_t *result, + apr_time_t input, + apr_int32_t offs); + +/** + * Convert a time to its human readable components (GMT). + * @param result the exploded time + * @param input the time to explode + */ +APR_DECLARE(apr_status_t) apr_time_exp_gmt(apr_time_exp_t *result, + apr_time_t input); + +/** + * Convert a time to its human readable components in the local timezone. + * @param result the exploded time + * @param input the time to explode + */ +APR_DECLARE(apr_status_t) apr_time_exp_lt(apr_time_exp_t *result, + apr_time_t input); + +/** + * Convert time value from human readable format to a numeric apr_time_t + * (elapsed microseconds since the epoch). + * @param result the resulting imploded time + * @param input the input exploded time + */ +APR_DECLARE(apr_status_t) apr_time_exp_get(apr_time_t *result, + apr_time_exp_t *input); + +/** + * Convert time value from human readable format to a numeric apr_time_t that + * always represents GMT. + * @param result the resulting imploded time + * @param input the input exploded time + */ +APR_DECLARE(apr_status_t) apr_time_exp_gmt_get(apr_time_t *result, + apr_time_exp_t *input); + +/** + * Sleep for the specified number of micro-seconds. + * @param t desired amount of time to sleep. + * @warning May sleep for longer than the specified time. + */ +APR_DECLARE(void) apr_sleep(apr_interval_time_t t); + +/** length of a RFC822 Date */ +#define APR_RFC822_DATE_LEN (30) +/** + * apr_rfc822_date formats dates in the RFC822 + * format in an efficient manner. It is a fixed length + * format which requires APR_RFC822_DATA_LEN bytes of storage, + * including the trailing NUL terminator. + * @param date_str String to write to. + * @param t the time to convert + */ +APR_DECLARE(apr_status_t) apr_rfc822_date(char *date_str, apr_time_t t); + +/** length of a CTIME date */ +#define APR_CTIME_LEN (25) +/** + * apr_ctime formats dates in the ctime() format + * in an efficient manner. It is a fixed length format + * and requires APR_CTIME_LEN bytes of storage including + * the trailing NUL terminator. + * Unlike ANSI/ISO C ctime(), apr_ctime() does not include + * a \\n at the end of the string. + * @param date_str String to write to. + * @param t the time to convert + */ +APR_DECLARE(apr_status_t) apr_ctime(char *date_str, apr_time_t t); + +/** + * Formats the exploded time according to the format specified + * @param s string to write to + * @param retsize The length of the returned string + * @param max The maximum length of the string + * @param format The format for the time string + * @param tm The time to convert + */ +APR_DECLARE(apr_status_t) apr_strftime(char *s, apr_size_t *retsize, + apr_size_t max, const char *format, + apr_time_exp_t *tm); + +/** + * Improve the clock resolution for the lifetime of the given pool. + * Generally this is only desirable on benchmarking and other very + * time-sensitive applications, and has no impact on most platforms. + * @param p The pool to associate the finer clock resolution + */ +APR_DECLARE(void) apr_time_clock_hires(apr_pool_t *p); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_TIME_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_uri.h b/c/dependencies/windows/apr/x86/include/apr_uri.h new file mode 100644 index 00000000..02908a9d --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_uri.h @@ -0,0 +1,178 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_uri.h: External Interface of apr_uri.c + */ + +/** + * @file apr_uri.h + * @brief APR-UTIL URI Routines + */ + +#ifndef APR_URI_H +#define APR_URI_H + +#include "apu.h" + +#include "apr_network_io.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_URI URI + * @ingroup APR_Util + * @{ + */ + +#define APR_URI_FTP_DEFAULT_PORT 21 /**< default FTP port */ +#define APR_URI_SSH_DEFAULT_PORT 22 /**< default SSH port */ +#define APR_URI_TELNET_DEFAULT_PORT 23 /**< default telnet port */ +#define APR_URI_GOPHER_DEFAULT_PORT 70 /**< default Gopher port */ +#define APR_URI_HTTP_DEFAULT_PORT 80 /**< default HTTP port */ +#define APR_URI_POP_DEFAULT_PORT 110 /**< default POP port */ +#define APR_URI_NNTP_DEFAULT_PORT 119 /**< default NNTP port */ +#define APR_URI_IMAP_DEFAULT_PORT 143 /**< default IMAP port */ +#define APR_URI_PROSPERO_DEFAULT_PORT 191 /**< default Prospero port */ +#define APR_URI_WAIS_DEFAULT_PORT 210 /**< default WAIS port */ +#define APR_URI_LDAP_DEFAULT_PORT 389 /**< default LDAP port */ +#define APR_URI_HTTPS_DEFAULT_PORT 443 /**< default HTTPS port */ +#define APR_URI_RTSP_DEFAULT_PORT 554 /**< default RTSP port */ +#define APR_URI_SNEWS_DEFAULT_PORT 563 /**< default SNEWS port */ +#define APR_URI_ACAP_DEFAULT_PORT 674 /**< default ACAP port */ +#define APR_URI_NFS_DEFAULT_PORT 2049 /**< default NFS port */ +#define APR_URI_TIP_DEFAULT_PORT 3372 /**< default TIP port */ +#define APR_URI_SIP_DEFAULT_PORT 5060 /**< default SIP port */ + +/** Flags passed to unparse_uri_components(): */ +/** suppress "scheme://user\@site:port" */ +#define APR_URI_UNP_OMITSITEPART (1U<<0) +/** Just omit user */ +#define APR_URI_UNP_OMITUSER (1U<<1) +/** Just omit password */ +#define APR_URI_UNP_OMITPASSWORD (1U<<2) +/** omit "user:password\@" part */ +#define APR_URI_UNP_OMITUSERINFO (APR_URI_UNP_OMITUSER | \ + APR_URI_UNP_OMITPASSWORD) +/** Show plain text password (default: show XXXXXXXX) */ +#define APR_URI_UNP_REVEALPASSWORD (1U<<3) +/** Show "scheme://user\@site:port" only */ +#define APR_URI_UNP_OMITPATHINFO (1U<<4) +/** Omit the "?queryarg" from the path */ +#define APR_URI_UNP_OMITQUERY (1U<<5) + +/** @see apr_uri_t */ +typedef struct apr_uri_t apr_uri_t; + +/** + * A structure to encompass all of the fields in a uri + */ +struct apr_uri_t { + /** scheme ("http"/"ftp"/...) */ + char *scheme; + /** combined [user[:password]\@]host[:port] */ + char *hostinfo; + /** user name, as in http://user:passwd\@host:port/ */ + char *user; + /** password, as in http://user:passwd\@host:port/ */ + char *password; + /** hostname from URI (or from Host: header) */ + char *hostname; + /** port string (integer representation is in "port") */ + char *port_str; + /** the request path (or NULL if only scheme://host was given) */ + char *path; + /** Everything after a '?' in the path, if present */ + char *query; + /** Trailing "#fragment" string, if present */ + char *fragment; + + /** structure returned from gethostbyname() */ + struct hostent *hostent; + + /** The port number, numeric, valid only if port_str != NULL */ + apr_port_t port; + + /** has the structure been initialized */ + unsigned is_initialized:1; + + /** has the DNS been looked up yet */ + unsigned dns_looked_up:1; + /** has the dns been resolved yet */ + unsigned dns_resolved:1; +}; + +/* apr_uri.c */ +/** + * Return the default port for a given scheme. The schemes recognized are + * http, ftp, https, gopher, wais, nntp, snews, and prospero + * @param scheme_str The string that contains the current scheme + * @return The default port for this scheme + */ +APU_DECLARE(apr_port_t) apr_uri_port_of_scheme(const char *scheme_str); + +/** + * Unparse a apr_uri_t structure to an URI string. Optionally + * suppress the password for security reasons. + * @param p The pool to allocate out of + * @param uptr All of the parts of the uri + * @param flags How to unparse the uri. One of: + *
+ *    APR_URI_UNP_OMITSITEPART        Suppress "scheme://user\@site:port" 
+ *    APR_URI_UNP_OMITUSER            Just omit user 
+ *    APR_URI_UNP_OMITPASSWORD        Just omit password 
+ *    APR_URI_UNP_OMITUSERINFO        Omit "user:password\@" part
+ *    APR_URI_UNP_REVEALPASSWORD      Show plain text password (default: show XXXXXXXX)
+ *    APR_URI_UNP_OMITPATHINFO        Show "scheme://user\@site:port" only 
+ *    APR_URI_UNP_OMITQUERY           Omit "?queryarg" or "#fragment" 
+ * 
+ * @return The uri as a string + */ +APU_DECLARE(char *) apr_uri_unparse(apr_pool_t *p, + const apr_uri_t *uptr, + unsigned flags); + +/** + * Parse a given URI, fill in all supplied fields of a apr_uri_t + * structure. This eliminates the necessity of extracting host, port, + * path, query info repeatedly in the modules. + * @param p The pool to allocate out of + * @param uri The uri to parse + * @param uptr The apr_uri_t to fill out + * @return APR_SUCCESS for success or error code + */ +APU_DECLARE(apr_status_t) apr_uri_parse(apr_pool_t *p, const char *uri, + apr_uri_t *uptr); + +/** + * Special case for CONNECT parsing: it comes with the hostinfo part only + * @param p The pool to allocate out of + * @param hostinfo The hostinfo string to parse + * @param uptr The apr_uri_t to fill out + * @return APR_SUCCESS for success or error code + */ +APU_DECLARE(apr_status_t) apr_uri_parse_hostinfo(apr_pool_t *p, + const char *hostinfo, + apr_uri_t *uptr); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_URI_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_user.h b/c/dependencies/windows/apr/x86/include/apr_user.h new file mode 100644 index 00000000..0e0a3ac5 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_user.h @@ -0,0 +1,158 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_USER_H +#define APR_USER_H + +/** + * @file apr_user.h + * @brief APR User ID Services + */ + +#include "apr.h" +#include "apr_errno.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_user User and Group ID Services + * @ingroup APR + * @{ + */ + +/** + * Structure for determining user ownership. + */ +#ifdef WIN32 +typedef PSID apr_uid_t; +#else +typedef uid_t apr_uid_t; +#endif + +/** + * Structure for determining group ownership. + */ +#ifdef WIN32 +typedef PSID apr_gid_t; +#else +typedef gid_t apr_gid_t; +#endif + +#if APR_HAS_USER + +/** + * Get the userid (and groupid) of the calling process + * @param userid Returns the user id + * @param groupid Returns the user's group id + * @param p The pool from which to allocate working space + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_uid_current(apr_uid_t *userid, + apr_gid_t *groupid, + apr_pool_t *p); + +/** + * Get the user name for a specified userid + * @param username Pointer to new string containing user name (on output) + * @param userid The userid + * @param p The pool from which to allocate the string + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_uid_name_get(char **username, apr_uid_t userid, + apr_pool_t *p); + +/** + * Get the userid (and groupid) for the specified username + * @param userid Returns the user id + * @param groupid Returns the user's group id + * @param username The username to look up + * @param p The pool from which to allocate working space + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_uid_get(apr_uid_t *userid, apr_gid_t *groupid, + const char *username, apr_pool_t *p); + +/** + * Get the home directory for the named user + * @param dirname Pointer to new string containing directory name (on output) + * @param username The named user + * @param p The pool from which to allocate the string + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_uid_homepath_get(char **dirname, + const char *username, + apr_pool_t *p); + +/** + * Compare two user identifiers for equality. + * @param left One uid to test + * @param right Another uid to test + * @return APR_SUCCESS if the apr_uid_t structures identify the same user, + * APR_EMISMATCH if not, APR_BADARG if an apr_uid_t is invalid. + * @remark This function is available only if APR_HAS_USER is defined. + */ +#if defined(WIN32) +APR_DECLARE(apr_status_t) apr_uid_compare(apr_uid_t left, apr_uid_t right); +#else +#define apr_uid_compare(left,right) (((left) == (right)) ? APR_SUCCESS : APR_EMISMATCH) +#endif + +/** + * Get the group name for a specified groupid + * @param groupname Pointer to new string containing group name (on output) + * @param groupid The groupid + * @param p The pool from which to allocate the string + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_gid_name_get(char **groupname, + apr_gid_t groupid, apr_pool_t *p); + +/** + * Get the groupid for a specified group name + * @param groupid Pointer to the group id (on output) + * @param groupname The group name to look up + * @param p The pool from which to allocate the string + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_gid_get(apr_gid_t *groupid, + const char *groupname, apr_pool_t *p); + +/** + * Compare two group identifiers for equality. + * @param left One gid to test + * @param right Another gid to test + * @return APR_SUCCESS if the apr_gid_t structures identify the same group, + * APR_EMISMATCH if not, APR_BADARG if an apr_gid_t is invalid. + * @remark This function is available only if APR_HAS_USER is defined. + */ +#if defined(WIN32) +APR_DECLARE(apr_status_t) apr_gid_compare(apr_gid_t left, apr_gid_t right); +#else +#define apr_gid_compare(left,right) (((left) == (right)) ? APR_SUCCESS : APR_EMISMATCH) +#endif + +#endif /* ! APR_HAS_USER */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_USER_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_uuid.h b/c/dependencies/windows/apr/x86/include/apr_uuid.h new file mode 100644 index 00000000..5312a9f6 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_uuid.h @@ -0,0 +1,76 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_uuid.h + * @brief APR UUID library + */ +#ifndef APR_UUID_H +#define APR_UUID_H + +#include "apu.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_UUID UUID Handling + * @ingroup APR + * @{ + */ + +/** + * we represent a UUID as a block of 16 bytes. + */ + +typedef struct { + unsigned char data[16]; /**< the actual UUID */ +} apr_uuid_t; + +/** UUIDs are formatted as: 00112233-4455-6677-8899-AABBCCDDEEFF */ +#define APR_UUID_FORMATTED_LENGTH 36 + + +/** + * Generate and return a (new) UUID + * @param uuid The resulting UUID + */ +APU_DECLARE(void) apr_uuid_get(apr_uuid_t *uuid); + +/** + * Format a UUID into a string, following the standard format + * @param buffer The buffer to place the formatted UUID string into. It must + * be at least APR_UUID_FORMATTED_LENGTH + 1 bytes long to hold + * the formatted UUID and a null terminator + * @param uuid The UUID to format + */ +APU_DECLARE(void) apr_uuid_format(char *buffer, const apr_uuid_t *uuid); + +/** + * Parse a standard-format string into a UUID + * @param uuid The resulting UUID + * @param uuid_str The formatted UUID + */ +APU_DECLARE(apr_status_t) apr_uuid_parse(apr_uuid_t *uuid, const char *uuid_str); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_UUID_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_version.h b/c/dependencies/windows/apr/x86/include/apr_version.h new file mode 100644 index 00000000..e96de383 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_version.h @@ -0,0 +1,164 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_VERSION_H +#define APR_VERSION_H + +/** + * @file apr_version.h + * @brief APR Versioning Interface + * + * APR's Version + * + * There are several different mechanisms for accessing the version. There + * is a string form, and a set of numbers; in addition, there are constants + * which can be compiled into your application, and you can query the library + * being used for its actual version. + * + * Note that it is possible for an application to detect that it has been + * compiled against a different version of APR by use of the compile-time + * constants and the use of the run-time query function. + * + * APR version numbering follows the guidelines specified in: + * + * http://apr.apache.org/versioning.html + */ + + +#define APR_COPYRIGHT "Copyright (c) 2000-2019 The Apache Software " \ + "Foundation or its licensors, as applicable." + +/* The numeric compile-time version constants. These constants are the + * authoritative version numbers for APR. + */ + +/** major version + * Major API changes that could cause compatibility problems for older + * programs such as structure size changes. No binary compatibility is + * possible across a change in the major version. + */ +#define APR_MAJOR_VERSION 1 + +/** minor version + * Minor API changes that do not cause binary compatibility problems. + * Reset to 0 when upgrading APR_MAJOR_VERSION + */ +#define APR_MINOR_VERSION 7 + +/** patch level + * The Patch Level never includes API changes, simply bug fixes. + * Reset to 0 when upgrading APR_MINOR_VERSION + */ +#define APR_PATCH_VERSION 0 + +/** + * The symbol APR_IS_DEV_VERSION is only defined for internal, + * "development" copies of APR. It is undefined for released versions + * of APR. + */ +/* #undef APR_IS_DEV_VERSION */ + +/** + * Check at compile time if the APR version is at least a certain + * level. + * @param major The major version component of the version checked + * for (e.g., the "1" of "1.3.0"). + * @param minor The minor version component of the version checked + * for (e.g., the "3" of "1.3.0"). + * @param patch The patch level component of the version checked + * for (e.g., the "0" of "1.3.0"). + * @remark This macro is available with APR versions starting with + * 1.3.0. + */ +#define APR_VERSION_AT_LEAST(major,minor,patch) \ +(((major) < APR_MAJOR_VERSION) \ + || ((major) == APR_MAJOR_VERSION && (minor) < APR_MINOR_VERSION) \ + || ((major) == APR_MAJOR_VERSION && (minor) == APR_MINOR_VERSION && (patch) <= APR_PATCH_VERSION)) + +#if defined(APR_IS_DEV_VERSION) || defined(DOXYGEN) +/** Internal: string form of the "is dev" flag */ +#ifndef APR_IS_DEV_STRING +#define APR_IS_DEV_STRING "-dev" +#endif +#else +#define APR_IS_DEV_STRING "" +#endif + +/* APR_STRINGIFY is defined here, and also in apr_general.h, so wrap it */ +#ifndef APR_STRINGIFY +/** Properly quote a value as a string in the C preprocessor */ +#define APR_STRINGIFY(n) APR_STRINGIFY_HELPER(n) +/** Helper macro for APR_STRINGIFY */ +#define APR_STRINGIFY_HELPER(n) #n +#endif + +/** The formatted string of APR's version */ +#define APR_VERSION_STRING \ + APR_STRINGIFY(APR_MAJOR_VERSION) "." \ + APR_STRINGIFY(APR_MINOR_VERSION) "." \ + APR_STRINGIFY(APR_PATCH_VERSION) \ + APR_IS_DEV_STRING + +/** An alternative formatted string of APR's version */ +/* macro for Win32 .rc files using numeric csv representation */ +#define APR_VERSION_STRING_CSV APR_MAJOR_VERSION ##, \ + ##APR_MINOR_VERSION ##, \ + ##APR_PATCH_VERSION + + +#ifndef APR_VERSION_ONLY + +/* The C language API to access the version at run time, + * as opposed to compile time. APR_VERSION_ONLY may be defined + * externally when preprocessing apr_version.h to obtain strictly + * the C Preprocessor macro declarations. + */ + +#include "apr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The numeric version information is broken out into fields within this + * structure. + */ +typedef struct { + int major; /**< major number */ + int minor; /**< minor number */ + int patch; /**< patch number */ + int is_dev; /**< is development (1 or 0) */ +} apr_version_t; + +/** + * Return APR's version information information in a numeric form. + * + * @param pvsn Pointer to a version structure for returning the version + * information. + */ +APR_DECLARE(void) apr_version(apr_version_t *pvsn); + +/** Return APR's version information as a string. */ +APR_DECLARE(const char *) apr_version_string(void); + +#ifdef __cplusplus +} +#endif + +#endif /* ndef APR_VERSION_ONLY */ + +#endif /* ndef APR_VERSION_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_want.h b/c/dependencies/windows/apr/x86/include/apr_want.h new file mode 100644 index 00000000..2863b001 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_want.h @@ -0,0 +1,124 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr.h" /* configuration data */ +/** + * @file apr_want.h + * @brief APR Standard Headers Support + * + *
+ * Features:
+ *
+ *   APR_WANT_STRFUNC:  strcmp, strcat, strcpy, etc
+ *   APR_WANT_MEMFUNC:  memcmp, memcpy, etc
+ *   APR_WANT_STDIO:     and related bits
+ *   APR_WANT_IOVEC:    struct iovec
+ *   APR_WANT_BYTEFUNC: htons, htonl, ntohl, ntohs
+ *
+ * Typical usage:
+ *
+ *   \#define APR_WANT_STRFUNC
+ *   \#define APR_WANT_MEMFUNC
+ *   \#include "apr_want.h"
+ *
+ * The appropriate headers will be included.
+ *
+ * Note: it is safe to use this in a header (it won't interfere with other
+ *       headers' or source files' use of apr_want.h)
+ * 
+ */ + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_STRFUNC + +#if APR_HAVE_STRING_H +#include +#endif +#if APR_HAVE_STRINGS_H +#include +#endif + +#undef APR_WANT_STRFUNC +#endif + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_MEMFUNC + +#if APR_HAVE_STRING_H +#include +#endif + +#undef APR_WANT_MEMFUNC +#endif + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_STDIO + +#if APR_HAVE_STDIO_H +#include +#endif + +#undef APR_WANT_STDIO +#endif + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_IOVEC + +#if APR_HAVE_IOVEC + +#if APR_HAVE_SYS_UIO_H +#include +#endif + +#else + +#ifndef APR_IOVEC_DEFINED +#define APR_IOVEC_DEFINED +struct iovec +{ + void *iov_base; + size_t iov_len; +}; +#endif /* !APR_IOVEC_DEFINED */ + +#endif /* APR_HAVE_IOVEC */ + +#undef APR_WANT_IOVEC +#endif + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_BYTEFUNC + +/* Single Unix says they are in arpa/inet.h. Linux has them in + * netinet/in.h. FreeBSD has them in arpa/inet.h but requires that + * netinet/in.h be included first. + */ +#if APR_HAVE_NETINET_IN_H +#include +#endif +#if APR_HAVE_ARPA_INET_H +#include +#endif + +#undef APR_WANT_BYTEFUNC +#endif + +/* --------------------------------------------------------------------- */ diff --git a/c/dependencies/windows/apr/x86/include/apr_xlate.h b/c/dependencies/windows/apr/x86/include/apr_xlate.h new file mode 100644 index 00000000..32636685 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_xlate.h @@ -0,0 +1,163 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_XLATE_H +#define APR_XLATE_H + +#include "apu.h" +#include "apr_pools.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @file apr_xlate.h + * @brief APR I18N translation library + */ + +/** + * @defgroup APR_XLATE I18N translation library + * @ingroup APR + * @{ + */ +/** Opaque translation buffer */ +typedef struct apr_xlate_t apr_xlate_t; + +/** + * Set up for converting text from one charset to another. + * @param convset The handle to be filled in by this function + * @param topage The name of the target charset + * @param frompage The name of the source charset + * @param pool The pool to use + * @remark + * Specify APR_DEFAULT_CHARSET for one of the charset + * names to indicate the charset of the source code at + * compile time. This is useful if there are literal + * strings in the source code which must be translated + * according to the charset of the source code. + * APR_DEFAULT_CHARSET is not useful if the source code + * of the caller was not encoded in the same charset as + * APR at compile time. + * + * @remark + * Specify APR_LOCALE_CHARSET for one of the charset + * names to indicate the charset of the current locale. + * + * @remark + * Return APR_EINVAL if unable to procure a convset, or APR_ENOTIMPL + * if charset transcoding is not available in this instance of + * apr-util at all (i.e., APR_HAS_XLATE is undefined). + */ +APU_DECLARE(apr_status_t) apr_xlate_open(apr_xlate_t **convset, + const char *topage, + const char *frompage, + apr_pool_t *pool); + +/** + * This is to indicate the charset of the sourcecode at compile time + * names to indicate the charset of the source code at + * compile time. This is useful if there are literal + * strings in the source code which must be translated + * according to the charset of the source code. + */ +#define APR_DEFAULT_CHARSET (const char *)0 +/** + * To indicate charset names of the current locale + */ +#define APR_LOCALE_CHARSET (const char *)1 + +/** + * Find out whether or not the specified conversion is single-byte-only. + * @param convset The handle allocated by apr_xlate_open, specifying the + * parameters of conversion + * @param onoff Output: whether or not the conversion is single-byte-only + * @remark + * Return APR_ENOTIMPL if charset transcoding is not available + * in this instance of apr-util (i.e., APR_HAS_XLATE is undefined). + */ +APU_DECLARE(apr_status_t) apr_xlate_sb_get(apr_xlate_t *convset, int *onoff); + +/** + * Convert a buffer of text from one codepage to another. + * @param convset The handle allocated by apr_xlate_open, specifying + * the parameters of conversion + * @param inbuf The address of the source buffer + * @param inbytes_left Input: the amount of input data to be translated + * Output: the amount of input data not yet translated + * @param outbuf The address of the destination buffer + * @param outbytes_left Input: the size of the output buffer + * Output: the amount of the output buffer not yet used + * @remark + * Returns APR_ENOTIMPL if charset transcoding is not available + * in this instance of apr-util (i.e., APR_HAS_XLATE is undefined). + * Returns APR_INCOMPLETE if the input buffer ends in an incomplete + * multi-byte character. + * + * To correctly terminate the output buffer for some multi-byte + * character set encodings, a final call must be made to this function + * after the complete input string has been converted, passing + * the inbuf and inbytes_left parameters as NULL. (Note that this + * mode only works from version 1.1.0 onwards) + */ +APU_DECLARE(apr_status_t) apr_xlate_conv_buffer(apr_xlate_t *convset, + const char *inbuf, + apr_size_t *inbytes_left, + char *outbuf, + apr_size_t *outbytes_left); + +/* @see apr_file_io.h the comment in apr_file_io.h about this hack */ +#ifdef APR_NOT_DONE_YET +/** + * The purpose of apr_xlate_conv_char is to translate one character + * at a time. This needs to be written carefully so that it works + * with double-byte character sets. + * @param convset The handle allocated by apr_xlate_open, specifying the + * parameters of conversion + * @param inchar The character to convert + * @param outchar The converted character + */ +APU_DECLARE(apr_status_t) apr_xlate_conv_char(apr_xlate_t *convset, + char inchar, char outchar); +#endif + +/** + * Convert a single-byte character from one charset to another. + * @param convset The handle allocated by apr_xlate_open, specifying the + * parameters of conversion + * @param inchar The single-byte character to convert. + * @warning This only works when converting between single-byte character sets. + * -1 will be returned if the conversion can't be performed. + */ +APU_DECLARE(apr_int32_t) apr_xlate_conv_byte(apr_xlate_t *convset, + unsigned char inchar); + +/** + * Close a codepage translation handle. + * @param convset The codepage translation handle to close + * @remark + * Return APR_ENOTIMPL if charset transcoding is not available + * in this instance of apr-util (i.e., APR_HAS_XLATE is undefined). + */ +APU_DECLARE(apr_status_t) apr_xlate_close(apr_xlate_t *convset); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_XLATE_H */ diff --git a/c/dependencies/windows/apr/x86/include/apr_xml.h b/c/dependencies/windows/apr/x86/include/apr_xml.h new file mode 100644 index 00000000..87a696cc --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apr_xml.h @@ -0,0 +1,358 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file apr_xml.h + * @brief APR-UTIL XML Library + */ +#ifndef APR_XML_H +#define APR_XML_H + +/** + * @defgroup APR_Util_XML XML + * @ingroup APR_Util + * @{ + */ +#include "apr_pools.h" +#include "apr_tables.h" +#include "apr_file_io.h" + +#include "apu.h" +#if APR_CHARSET_EBCDIC +#include "apr_xlate.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @package Apache XML library + */ + +/* -------------------------------------------------------------------- */ + +/* ### these will need to move at some point to a more logical spot */ + +/** @see apr_text */ +typedef struct apr_text apr_text; + +/** Structure to keep a linked list of pieces of text */ +struct apr_text { + /** The current piece of text */ + const char *text; + /** a pointer to the next piece of text */ + struct apr_text *next; +}; + +/** @see apr_text_header */ +typedef struct apr_text_header apr_text_header; + +/** A list of pieces of text */ +struct apr_text_header { + /** The first piece of text in the list */ + apr_text *first; + /** The last piece of text in the list */ + apr_text *last; +}; + +/** + * Append a piece of text to the end of a list + * @param p The pool to allocate out of + * @param hdr The text header to append to + * @param text The new text to append + */ +APU_DECLARE(void) apr_text_append(apr_pool_t *p, apr_text_header *hdr, + const char *text); + + +/* -------------------------------------------------------------------- +** +** XML PARSING +*/ + +/* +** Qualified namespace values +** +** APR_XML_NS_DAV_ID +** We always insert the "DAV:" namespace URI at the head of the +** namespace array. This means that it will always be at ID==0, +** making it much easier to test for. +** +** APR_XML_NS_NONE +** This special ID is used for two situations: +** +** 1) The namespace prefix begins with "xml" (and we do not know +** what it means). Namespace prefixes with "xml" (any case) as +** their first three characters are reserved by the XML Namespaces +** specification for future use. mod_dav will pass these through +** unchanged. When this identifier is used, the prefix is LEFT in +** the element/attribute name. Downstream processing should not +** prepend another prefix. +** +** 2) The element/attribute does not have a namespace. +** +** a) No prefix was used, and a default namespace has not been +** defined. +** b) No prefix was used, and the default namespace was specified +** to mean "no namespace". This is done with a namespace +** declaration of: xmlns="" +** (this declaration is typically used to override a previous +** specification for the default namespace) +** +** In these cases, we need to record that the elem/attr has no +** namespace so that we will not attempt to prepend a prefix. +** All namespaces that are used will have a prefix assigned to +** them -- mod_dav will never set or use the default namespace +** when generating XML. This means that "no prefix" will always +** mean "no namespace". +** +** In both cases, the XML generation will avoid prepending a prefix. +** For the first case, this means the original prefix/name will be +** inserted into the output stream. For the latter case, it means +** the name will have no prefix, and since we never define a default +** namespace, this means it will have no namespace. +** +** Note: currently, mod_dav understands the "xmlns" prefix and the +** "xml:lang" attribute. These are handled specially (they aren't +** left within the XML tree), so the APR_XML_NS_NONE value won't ever +** really apply to these values. +*/ +#define APR_XML_NS_DAV_ID 0 /**< namespace ID for "DAV:" */ +#define APR_XML_NS_NONE -10 /**< no namespace for this elem/attr */ + +#define APR_XML_NS_ERROR_BASE -100 /**< used only during processing */ +/** Is this namespace an error? */ +#define APR_XML_NS_IS_ERROR(e) ((e) <= APR_XML_NS_ERROR_BASE) + +/** @see apr_xml_attr */ +typedef struct apr_xml_attr apr_xml_attr; +/** @see apr_xml_elem */ +typedef struct apr_xml_elem apr_xml_elem; +/** @see apr_xml_doc */ +typedef struct apr_xml_doc apr_xml_doc; + +/** apr_xml_attr: holds a parsed XML attribute */ +struct apr_xml_attr { + /** attribute name */ + const char *name; + /** index into namespace array */ + int ns; + + /** attribute value */ + const char *value; + + /** next attribute */ + struct apr_xml_attr *next; +}; + +/** apr_xml_elem: holds a parsed XML element */ +struct apr_xml_elem { + /** element name */ + const char *name; + /** index into namespace array */ + int ns; + /** xml:lang for attrs/contents */ + const char *lang; + + /** cdata right after start tag */ + apr_text_header first_cdata; + /** cdata after MY end tag */ + apr_text_header following_cdata; + + /** parent element */ + struct apr_xml_elem *parent; + /** next (sibling) element */ + struct apr_xml_elem *next; + /** first child element */ + struct apr_xml_elem *first_child; + /** first attribute */ + struct apr_xml_attr *attr; + + /* used only during parsing */ + /** last child element */ + struct apr_xml_elem *last_child; + /** namespaces scoped by this elem */ + struct apr_xml_ns_scope *ns_scope; + + /* used by modules during request processing */ + /** Place for modules to store private data */ + void *priv; +}; + +/** Is this XML element empty? */ +#define APR_XML_ELEM_IS_EMPTY(e) ((e)->first_child == NULL && \ + (e)->first_cdata.first == NULL) + +/** apr_xml_doc: holds a parsed XML document */ +struct apr_xml_doc { + /** root element */ + apr_xml_elem *root; + /** array of namespaces used */ + apr_array_header_t *namespaces; +}; + +/** Opaque XML parser structure */ +typedef struct apr_xml_parser apr_xml_parser; + +/** + * Create an XML parser + * @param pool The pool for allocating the parser and the parse results. + * @return The new parser. + */ +APU_DECLARE(apr_xml_parser *) apr_xml_parser_create(apr_pool_t *pool); + +/** + * Parse a File, producing a xml_doc + * @param p The pool for allocating the parse results. + * @param parser A pointer to *parser (needed so calling function can get + * errors), will be set to NULL on successful completion. + * @param ppdoc A pointer to *apr_xml_doc (which has the parsed results in it) + * @param xmlfd A file to read from. + * @param buffer_length Buffer length which would be suitable + * @return Any errors found during parsing. + */ +APU_DECLARE(apr_status_t) apr_xml_parse_file(apr_pool_t *p, + apr_xml_parser **parser, + apr_xml_doc **ppdoc, + apr_file_t *xmlfd, + apr_size_t buffer_length); + + +/** + * Feed input into the parser + * @param parser The XML parser for parsing this data. + * @param data The data to parse. + * @param len The length of the data. + * @return Any errors found during parsing. + * @remark Use apr_xml_parser_geterror() to get more error information. + */ +APU_DECLARE(apr_status_t) apr_xml_parser_feed(apr_xml_parser *parser, + const char *data, + apr_size_t len); + +/** + * Terminate the parsing and return the result + * @param parser The XML parser for parsing this data. + * @param pdoc The resulting parse information. May be NULL to simply + * terminate the parsing without fetching the info. + * @return Any errors found during the final stage of parsing. + * @remark Use apr_xml_parser_geterror() to get more error information. + */ +APU_DECLARE(apr_status_t) apr_xml_parser_done(apr_xml_parser *parser, + apr_xml_doc **pdoc); + +/** + * Fetch additional error information from the parser. + * @param parser The XML parser to query for errors. + * @param errbuf A buffer for storing error text. + * @param errbufsize The length of the error text buffer. + * @return The error buffer + */ +APU_DECLARE(char *) apr_xml_parser_geterror(apr_xml_parser *parser, + char *errbuf, + apr_size_t errbufsize); + + +/** + * Converts an XML element tree to flat text + * @param p The pool to allocate out of + * @param elem The XML element to convert + * @param style How to covert the XML. One of: + *
+ *     APR_XML_X2T_FULL                start tag, contents, end tag 
+ *     APR_XML_X2T_INNER               contents only 
+ *     APR_XML_X2T_LANG_INNER          xml:lang + inner contents 
+ *     APR_XML_X2T_FULL_NS_LANG        FULL + ns defns + xml:lang 
+ *     APR_XML_X2T_PARSED              original prefixes
+ * 
+ * @param namespaces The namespace of the current XML element + * @param ns_map Namespace mapping + * @param pbuf Buffer to put the converted text into + * @param psize Size of the converted text + */ +APU_DECLARE(void) apr_xml_to_text(apr_pool_t *p, const apr_xml_elem *elem, + int style, apr_array_header_t *namespaces, + int *ns_map, const char **pbuf, + apr_size_t *psize); + +/* style argument values: */ +#define APR_XML_X2T_FULL 0 /**< start tag, contents, end tag */ +#define APR_XML_X2T_INNER 1 /**< contents only */ +#define APR_XML_X2T_LANG_INNER 2 /**< xml:lang + inner contents */ +#define APR_XML_X2T_FULL_NS_LANG 3 /**< FULL + ns defns + xml:lang */ +#define APR_XML_X2T_PARSED 4 /**< original prefixes */ + +/** + * empty XML element + * @param p The pool to allocate out of + * @param elem The XML element to empty + * @return the string that was stored in the XML element + */ +APU_DECLARE(const char *) apr_xml_empty_elem(apr_pool_t *p, + const apr_xml_elem *elem); + +/** + * quote an XML string + * Replace '\<', '\>', and '\&' with '\<', '\>', and '\&'. + * @param p The pool to allocate out of + * @param s The string to quote + * @param quotes If quotes is true, then replace '"' with '\"'. + * @return The quoted string + * @note If the string does not contain special characters, it is not + * duplicated into the pool and the original string is returned. + */ +APU_DECLARE(const char *) apr_xml_quote_string(apr_pool_t *p, const char *s, + int quotes); + +/** + * Quote an XML element + * @param p The pool to allocate out of + * @param elem The element to quote + */ +APU_DECLARE(void) apr_xml_quote_elem(apr_pool_t *p, apr_xml_elem *elem); + +/* manage an array of unique URIs: apr_xml_insert_uri() and APR_XML_URI_ITEM() */ + +/** + * return the URI's (existing) index, or insert it and return a new index + * @param uri_array array to insert into + * @param uri The uri to insert + * @return int The uri's index + */ +APU_DECLARE(int) apr_xml_insert_uri(apr_array_header_t *uri_array, + const char *uri); + +/** Get the URI item for this XML element */ +#define APR_XML_GET_URI_ITEM(ary, i) (((const char * const *)(ary)->elts)[i]) + +#if APR_CHARSET_EBCDIC +/** + * Convert parsed tree in EBCDIC + * @param p The pool to allocate out of + * @param pdoc The apr_xml_doc to convert. + * @param xlate The translation handle to use. + * @return Any errors found during conversion. + */ +APU_DECLARE(apr_status_t) apr_xml_parser_convert_doc(apr_pool_t *p, + apr_xml_doc *pdoc, + apr_xlate_t *convset); +#endif + +#ifdef __cplusplus +} +#endif +/** @} */ +#endif /* APR_XML_H */ diff --git a/c/dependencies/windows/apr/x86/include/apu.h b/c/dependencies/windows/apr/x86/include/apu.h new file mode 100644 index 00000000..21fbedff --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apu.h @@ -0,0 +1,146 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apu.h is duplicated from apu.hw at build time -- do not edit apu.h + */ +/* @file apu.h + * @brief APR-Utility main file + */ +/** + * @defgroup APR_Util APR Utility Functions + * @{ + */ + + +#ifndef APU_H +#define APU_H + +/** + * APU_DECLARE_EXPORT is defined when building the APR-UTIL dynamic library, + * so that all public symbols are exported. + * + * APU_DECLARE_STATIC is defined when including the APR-UTIL public headers, + * to provide static linkage when the dynamic library may be unavailable. + * + * APU_DECLARE_STATIC and APU_DECLARE_EXPORT are left undefined when + * including the APR-UTIL public headers, to import and link the symbols from + * the dynamic APR-UTIL library and assure appropriate indirection and calling + * conventions at compile time. + */ + +/* Make sure we have our platform identifier macro defined we ask for later. + */ +#if defined(_WIN32) && !defined(WIN32) +#define WIN32 1 +#endif + +#if defined(DOXYGEN) || !defined(WIN32) +/** + * The public APR-UTIL functions are declared with APU_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APU_DECLARE_NONSTD(). + * + * @fn APU_DECLARE(rettype) apr_func(args); + */ +#define APU_DECLARE(type) type +/** + * The public APR-UTIL functions using variable arguments are declared with + * APU_DECLARE_NONSTD(), as they must use the C language calling convention. + * + * @fn APU_DECLARE_NONSTD(rettype) apr_func(args, ...); + */ +#define APU_DECLARE_NONSTD(type) type +/** + * The public APR-UTIL variables are declared with APU_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * + * @fn APU_DECLARE_DATA type apr_variable; + * @note extern APU_DECLARE_DATA type apr_variable; syntax is required for + * declarations within headers to properly import the variable. + */ +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_STATIC) +#define APU_DECLARE(type) type __stdcall +#define APU_DECLARE_NONSTD(type) type __cdecl +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_EXPORT) +#define APU_DECLARE(type) __declspec(dllexport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllexport) +#else +#define APU_DECLARE(type) __declspec(dllimport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllimport) +#endif + +#if !defined(WIN32) || defined(APU_MODULE_DECLARE_STATIC) +/** + * Declare a dso module's exported module structure as APU_MODULE_DECLARE_DATA. + * + * Unless APU_MODULE_DECLARE_STATIC is defined at compile time, symbols + * declared with APU_MODULE_DECLARE_DATA are always exported. + * @code + * module APU_MODULE_DECLARE_DATA mod_tag + * @endcode + */ +#define APU_MODULE_DECLARE_DATA +#else +#define APU_MODULE_DECLARE_DATA __declspec(dllexport) +#endif + +/* + * we always have SDBM (it's in our codebase) + */ +#define APU_HAVE_SDBM 1 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_GDBM 0 +#define APU_HAVE_NDBM 0 +#define APU_HAVE_DB 0 + +#if APU_HAVE_DB +#define APU_HAVE_DB_VERSION 0 +#endif +#endif + +/* + * we always enable dynamic driver loads within apr_dbd + * Win32 always has odbc (it's always installed) + */ +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_PGSQL 0 +#define APU_HAVE_MYSQL 0 +#define APU_HAVE_SQLITE3 0 +#define APU_HAVE_SQLITE2 0 +#define APU_HAVE_ORACLE 0 +#define APU_HAVE_ODBC 1 +#endif + +#define APU_HAVE_CRYPTO 0 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_OPENSSL 0 +#define APU_HAVE_NSS 0 +#define APU_HAVE_COMMONCRYPTO 0 +#endif + +#define APU_HAVE_APR_ICONV 1 +#define APU_HAVE_ICONV 0 +#define APR_HAS_XLATE (APU_HAVE_APR_ICONV || APU_HAVE_ICONV) + +#endif /* APU_H */ +/** @} */ diff --git a/c/dependencies/windows/apr/x86/include/apu.h.in b/c/dependencies/windows/apr/x86/include/apu.h.in new file mode 100644 index 00000000..0781a6a0 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apu.h.in @@ -0,0 +1,128 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apu.h is generated from apu.h.in by configure -- do not edit apu.h + */ +/* @file apu.h + * @brief APR-Utility main file + */ +/** + * @defgroup APR_Util APR Utility Functions + * @{ + */ + + +#ifndef APU_H +#define APU_H + +/** + * APU_DECLARE_EXPORT is defined when building the APR-UTIL dynamic library, + * so that all public symbols are exported. + * + * APU_DECLARE_STATIC is defined when including the APR-UTIL public headers, + * to provide static linkage when the dynamic library may be unavailable. + * + * APU_DECLARE_STATIC and APU_DECLARE_EXPORT are left undefined when + * including the APR-UTIL public headers, to import and link the symbols from + * the dynamic APR-UTIL library and assure appropriate indirection and calling + * conventions at compile time. + */ + +#if defined(DOXYGEN) || !defined(WIN32) +/** + * The public APR-UTIL functions are declared with APU_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APU_DECLARE_NONSTD(). + * + * @fn APU_DECLARE(rettype) apr_func(args); + */ +#define APU_DECLARE(type) type +/** + * The public APR-UTIL functions using variable arguments are declared with + * APU_DECLARE_NONSTD(), as they must use the C language calling convention. + * + * @fn APU_DECLARE_NONSTD(rettype) apr_func(args, ...); + */ +#define APU_DECLARE_NONSTD(type) type +/** + * The public APR-UTIL variables are declared with APU_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * + * @fn APU_DECLARE_DATA type apr_variable; + * @note APU_DECLARE_DATA extern type apr_variable; syntax is required for + * declarations within headers to properly import the variable. + */ +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_STATIC) +#define APU_DECLARE(type) type __stdcall +#define APU_DECLARE_NONSTD(type) type __cdecl +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_EXPORT) +#define APU_DECLARE(type) __declspec(dllexport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllexport) +#else +#define APU_DECLARE(type) __declspec(dllimport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllimport) +#endif + +#if !defined(WIN32) || defined(APU_MODULE_DECLARE_STATIC) +/** + * Declare a dso module's exported module structure as APU_MODULE_DECLARE_DATA. + * + * Unless APU_MODULE_DECLARE_STATIC is defined at compile time, symbols + * declared with APU_MODULE_DECLARE_DATA are always exported. + * @code + * module APU_MODULE_DECLARE_DATA mod_tag + * @endcode + */ +#define APU_MODULE_DECLARE_DATA +#else +#define APU_MODULE_DECLARE_DATA __declspec(dllexport) +#endif + +/* + * we always have SDBM (it's in our codebase) + */ +#define APU_HAVE_SDBM @apu_have_sdbm@ +#define APU_HAVE_GDBM @apu_have_gdbm@ +#define APU_HAVE_NDBM @apu_have_ndbm@ +#define APU_HAVE_DB @apu_have_db@ + +#if APU_HAVE_DB +#define APU_HAVE_DB_VERSION @apu_db_version@ +#endif + +#define APU_HAVE_PGSQL @apu_have_pgsql@ +#define APU_HAVE_MYSQL @apu_have_mysql@ +#define APU_HAVE_SQLITE3 @apu_have_sqlite3@ +#define APU_HAVE_SQLITE2 @apu_have_sqlite2@ +#define APU_HAVE_ORACLE @apu_have_oracle@ +#define APU_HAVE_ODBC @apu_have_odbc@ + +#define APU_HAVE_CRYPTO @apu_have_crypto@ +#define APU_HAVE_OPENSSL @apu_have_openssl@ +#define APU_HAVE_NSS @apu_have_nss@ +#define APU_HAVE_COMMONCRYPTO @apu_have_commoncrypto@ + +#define APU_HAVE_APR_ICONV @have_apr_iconv@ +#define APU_HAVE_ICONV @have_iconv@ +#define APR_HAS_XLATE (APU_HAVE_APR_ICONV || APU_HAVE_ICONV) + +#endif /* APU_H */ +/** @} */ diff --git a/c/dependencies/windows/apr/x86/include/apu.hnw b/c/dependencies/windows/apr/x86/include/apu.hnw new file mode 100644 index 00000000..12e73818 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apu.hnw @@ -0,0 +1,124 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Note: This is a NetWare specific version of apu.h. It is renamed to + * apu.h at the start of a NetWare build. + */ +/* @file apu.h + * @brief APR-Utility main file + */ + +#ifdef NETWARE +#ifndef APU_H +#define APU_H +/** + * @defgroup APR_Util APR Utility Functions + * @{ + */ + + +/** + * APU_DECLARE_EXPORT is defined when building the APR-UTIL dynamic library, + * so that all public symbols are exported. + * + * APU_DECLARE_STATIC is defined when including the APR-UTIL public headers, + * to provide static linkage when the dynamic library may be unavailable. + * + * APU_DECLARE_STATIC and APU_DECLARE_EXPORT are left undefined when + * including the APR-UTIL public headers, to import and link the symbols from + * the dynamic APR-UTIL library and assure appropriate indirection and calling + * conventions at compile time. + */ + +/** + * The public APR-UTIL functions are declared with APU_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APU_DECLARE_NONSTD(). + * + * @fn APU_DECLARE(rettype) apr_func(args); + */ +#define APU_DECLARE(type) type +/** + * The public APR-UTIL functions using variable arguments are declared with + * APU_DECLARE_NONSTD(), as they must use the C language calling convention. + * + * @fn APU_DECLARE_NONSTD(rettype) apr_func(args, ...); + */ +#define APU_DECLARE_NONSTD(type) type +/** + * The public APR-UTIL variables are declared with APU_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * + * @fn APU_DECLARE_DATA type apr_variable; + * @note APU_DECLARE_DATA extern type apr_variable; syntax is required for + * declarations within headers to properly import the variable. + */ +#define APU_DECLARE_DATA + +/** + * Declare a dso module's exported module structure as APU_MODULE_DECLARE_DATA. + * + * Unless APU_MODULE_DECLARE_STATIC is defined at compile time, symbols + * declared with APU_MODULE_DECLARE_DATA are always exported. + * @code + * module APU_MODULE_DECLARE_DATA mod_tag + * @endcode + */ +#define APU_MODULE_DECLARE_DATA + +/* + * we always have SDBM (it's in our codebase) + */ +#define APU_HAVE_SDBM 1 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_GDBM 0 +#define APU_HAVE_NDBM 0 +#define APU_HAVE_DB 0 + +#if APU_HAVE_DB +#define APU_HAVE_DB_VERSION 0 +#endif +#endif + +/* + * we always enable dynamic driver loads within apr_dbd + */ +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_PGSQL 0 +#define APU_HAVE_MYSQL 0 +#define APU_HAVE_SQLITE3 0 +#define APU_HAVE_SQLITE2 0 +#define APU_HAVE_ORACLE 0 +#define APU_HAVE_ODBC 0 +#endif + +#define APU_HAVE_CRYPTO 0 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_OPENSSL 0 +#define APU_HAVE_NSS 0 +#define APU_HAVE_COMMONCRYPTO 0 +#endif + +#define APU_HAVE_APR_ICONV 0 +#define APU_HAVE_ICONV 1 +#define APR_HAS_XLATE (APU_HAVE_APR_ICONV || APU_HAVE_ICONV) + +#endif /* APU_H */ +#endif /* NETWARE */ + diff --git a/c/dependencies/windows/apr/x86/include/apu.hw b/c/dependencies/windows/apr/x86/include/apu.hw new file mode 100644 index 00000000..a501d5d7 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apu.hw @@ -0,0 +1,146 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apu.h is duplicated from apu.hw at build time -- do not edit apu.h + */ +/* @file apu.h + * @brief APR-Utility main file + */ +/** + * @defgroup APR_Util APR Utility Functions + * @{ + */ + + +#ifndef APU_H +#define APU_H + +/** + * APU_DECLARE_EXPORT is defined when building the APR-UTIL dynamic library, + * so that all public symbols are exported. + * + * APU_DECLARE_STATIC is defined when including the APR-UTIL public headers, + * to provide static linkage when the dynamic library may be unavailable. + * + * APU_DECLARE_STATIC and APU_DECLARE_EXPORT are left undefined when + * including the APR-UTIL public headers, to import and link the symbols from + * the dynamic APR-UTIL library and assure appropriate indirection and calling + * conventions at compile time. + */ + +/* Make sure we have our platform identifier macro defined we ask for later. + */ +#if defined(_WIN32) && !defined(WIN32) +#define WIN32 1 +#endif + +#if defined(DOXYGEN) || !defined(WIN32) +/** + * The public APR-UTIL functions are declared with APU_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APU_DECLARE_NONSTD(). + * + * @fn APU_DECLARE(rettype) apr_func(args); + */ +#define APU_DECLARE(type) type +/** + * The public APR-UTIL functions using variable arguments are declared with + * APU_DECLARE_NONSTD(), as they must use the C language calling convention. + * + * @fn APU_DECLARE_NONSTD(rettype) apr_func(args, ...); + */ +#define APU_DECLARE_NONSTD(type) type +/** + * The public APR-UTIL variables are declared with APU_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * + * @fn APU_DECLARE_DATA type apr_variable; + * @note extern APU_DECLARE_DATA type apr_variable; syntax is required for + * declarations within headers to properly import the variable. + */ +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_STATIC) +#define APU_DECLARE(type) type __stdcall +#define APU_DECLARE_NONSTD(type) type __cdecl +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_EXPORT) +#define APU_DECLARE(type) __declspec(dllexport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllexport) +#else +#define APU_DECLARE(type) __declspec(dllimport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllimport) +#endif + +#if !defined(WIN32) || defined(APU_MODULE_DECLARE_STATIC) +/** + * Declare a dso module's exported module structure as APU_MODULE_DECLARE_DATA. + * + * Unless APU_MODULE_DECLARE_STATIC is defined at compile time, symbols + * declared with APU_MODULE_DECLARE_DATA are always exported. + * @code + * module APU_MODULE_DECLARE_DATA mod_tag + * @endcode + */ +#define APU_MODULE_DECLARE_DATA +#else +#define APU_MODULE_DECLARE_DATA __declspec(dllexport) +#endif + +/* + * we always have SDBM (it's in our codebase) + */ +#define APU_HAVE_SDBM 1 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_GDBM 0 +#define APU_HAVE_NDBM 0 +#define APU_HAVE_DB 0 + +#if APU_HAVE_DB +#define APU_HAVE_DB_VERSION 0 +#endif +#endif + +/* + * we always enable dynamic driver loads within apr_dbd + * Win32 always has odbc (it's always installed) + */ +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_PGSQL 0 +#define APU_HAVE_MYSQL 0 +#define APU_HAVE_SQLITE3 0 +#define APU_HAVE_SQLITE2 0 +#define APU_HAVE_ORACLE 0 +#define APU_HAVE_ODBC 1 +#endif + +#define APU_HAVE_CRYPTO 0 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_OPENSSL 0 +#define APU_HAVE_NSS 0 +#define APU_HAVE_COMMONCRYPTO 0 +#endif + +#define APU_HAVE_APR_ICONV 1 +#define APU_HAVE_ICONV 0 +#define APR_HAS_XLATE (APU_HAVE_APR_ICONV || APU_HAVE_ICONV) + +#endif /* APU_H */ +/** @} */ diff --git a/c/dependencies/windows/apr/x86/include/apu.hwc b/c/dependencies/windows/apr/x86/include/apu.hwc new file mode 100644 index 00000000..a663ec3e --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apu.hwc @@ -0,0 +1,145 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apu.h is duplicated from apu.hwc at build time -- do not edit apu.h + */ +/* @file apu.h + * @brief APR-Utility main file + */ +/** + * @defgroup APR_Util APR Utility Functions + * @{ + */ + + +#ifndef APU_H +#define APU_H + +/** + * APU_DECLARE_EXPORT is defined when building the APR-UTIL dynamic library, + * so that all public symbols are exported. + * + * APU_DECLARE_STATIC is defined when including the APR-UTIL public headers, + * to provide static linkage when the dynamic library may be unavailable. + * + * APU_DECLARE_STATIC and APU_DECLARE_EXPORT are left undefined when + * including the APR-UTIL public headers, to import and link the symbols from + * the dynamic APR-UTIL library and assure appropriate indirection and calling + * conventions at compile time. + */ + +/* Make sure we have our platform identifier macro defined we ask for later. + */ +#if defined(_WIN32) && !defined(WIN32) +#define WIN32 1 +#endif + +#if defined(DOXYGEN) || !defined(WIN32) +/** + * The public APR-UTIL functions are declared with APU_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APU_DECLARE_NONSTD(). + * + * @fn APU_DECLARE(rettype) apr_func(args); + */ +#define APU_DECLARE(type) type +/** + * The public APR-UTIL functions using variable arguments are declared with + * APU_DECLARE_NONSTD(), as they must use the C language calling convention. + * + * @fn APU_DECLARE_NONSTD(rettype) apr_func(args, ...); + */ +#define APU_DECLARE_NONSTD(type) type +/** + * The public APR-UTIL variables are declared with APU_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * + * @fn APU_DECLARE_DATA type apr_variable; + * @note extern APU_DECLARE_DATA type apr_variable; syntax is required for + * declarations within headers to properly import the variable. + */ +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_STATIC) +#define APU_DECLARE(type) type __stdcall +#define APU_DECLARE_NONSTD(type) type __cdecl +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_EXPORT) +#define APU_DECLARE(type) __declspec(dllexport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllexport) +#else +#define APU_DECLARE(type) __declspec(dllimport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllimport) +#endif + +#if !defined(WIN32) || defined(APU_MODULE_DECLARE_STATIC) +/** + * Declare a dso module's exported module structure as APU_MODULE_DECLARE_DATA. + * + * Unless APU_MODULE_DECLARE_STATIC is defined at compile time, symbols + * declared with APU_MODULE_DECLARE_DATA are always exported. + * @code + * module APU_MODULE_DECLARE_DATA mod_tag + * @endcode + */ +#define APU_MODULE_DECLARE_DATA +#else +#define APU_MODULE_DECLARE_DATA __declspec(dllexport) +#endif + +/* + * we always have SDBM (it's in our codebase) + */ +#define APU_HAVE_SDBM 1 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_GDBM 0 +#define APU_HAVE_NDBM 0 +#define APU_HAVE_DB 0 + +#if APU_HAVE_DB +#define APU_HAVE_DB_VERSION 0 +#endif +#endif + +/* + * we always enable dynamic driver loads within apr_dbd + * Win32 always has odbc (it's always installed) + */ +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_PGSQL 0 +#define APU_HAVE_MYSQL 0 +#define APU_HAVE_SQLITE3 0 +#define APU_HAVE_SQLITE2 0 +#define APU_HAVE_ORACLE 0 +#define APU_HAVE_ODBC 1 +#endif + +#define APU_HAVE_CRYPTO @apu_have_crypto_10@ + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_OPENSSL 0 +#define APU_HAVE_NSS 0 +#endif + +#define APU_HAVE_APR_ICONV @apu_have_apr_iconv_10@ +#define APU_HAVE_ICONV 0 +#define APR_HAS_XLATE (APU_HAVE_APR_ICONV || APU_HAVE_ICONV) + +#endif /* APU_H */ +/** @} */ diff --git a/c/dependencies/windows/apr/x86/include/apu_errno.h b/c/dependencies/windows/apr/x86/include/apu_errno.h new file mode 100644 index 00000000..c0a8ec7d --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apu_errno.h @@ -0,0 +1,173 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APU_ERRNO_H +#define APU_ERRNO_H + +/** + * @file apu_errno.h + * @brief APR-Util Error Codes + */ + +#include "apr.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apu_errno Error Codes + * @ingroup APR_Util + * @{ + */ + +/** + * @defgroup APR_Util_Error APR_Util Error Values + *
+ * APU ERROR VALUES
+ * APR_ENOKEY         The key provided was empty or NULL
+ * APR_ENOIV          The initialisation vector provided was NULL
+ * APR_EKEYTYPE       The key type was not recognised
+ * APR_ENOSPACE       The buffer supplied was not big enough
+ * APR_ECRYPT         An error occurred while encrypting or decrypting
+ * APR_EPADDING       Padding was not supported
+ * APR_EKEYLENGTH     The key length was incorrect
+ * APR_ENOCIPHER      The cipher provided was not recognised
+ * APR_ENODIGEST      The digest provided was not recognised
+ * APR_ENOENGINE      The engine provided was not recognised
+ * APR_EINITENGINE    The engine could not be initialised
+ * APR_EREINIT        Underlying crypto has already been initialised
+ * 
+ * + *
+ * APR STATUS VALUES
+ * APR_INCHILD        Program is currently executing in the child
+ * 
+ * @{ + */ +/** @see APR_STATUS_IS_ENOKEY */ +#define APR_ENOKEY (APR_UTIL_START_STATUS + 1) +/** @see APR_STATUS_IS_ENOIV */ +#define APR_ENOIV (APR_UTIL_START_STATUS + 2) +/** @see APR_STATUS_IS_EKEYTYPE */ +#define APR_EKEYTYPE (APR_UTIL_START_STATUS + 3) +/** @see APR_STATUS_IS_ENOSPACE */ +#define APR_ENOSPACE (APR_UTIL_START_STATUS + 4) +/** @see APR_STATUS_IS_ECRYPT */ +#define APR_ECRYPT (APR_UTIL_START_STATUS + 5) +/** @see APR_STATUS_IS_EPADDING */ +#define APR_EPADDING (APR_UTIL_START_STATUS + 6) +/** @see APR_STATUS_IS_EKEYLENGTH */ +#define APR_EKEYLENGTH (APR_UTIL_START_STATUS + 7) +/** @see APR_STATUS_IS_ENOCIPHER */ +#define APR_ENOCIPHER (APR_UTIL_START_STATUS + 8) +/** @see APR_STATUS_IS_ENODIGEST */ +#define APR_ENODIGEST (APR_UTIL_START_STATUS + 9) +/** @see APR_STATUS_IS_ENOENGINE */ +#define APR_ENOENGINE (APR_UTIL_START_STATUS + 10) +/** @see APR_STATUS_IS_EINITENGINE */ +#define APR_EINITENGINE (APR_UTIL_START_STATUS + 11) +/** @see APR_STATUS_IS_EREINIT */ +#define APR_EREINIT (APR_UTIL_START_STATUS + 12) +/** @} */ + +/** + * @defgroup APU_STATUS_IS Status Value Tests + * @warning For any particular error condition, more than one of these tests + * may match. This is because platform-specific error codes may not + * always match the semantics of the POSIX codes these tests (and the + * corresponding APR error codes) are named after. A notable example + * are the APR_STATUS_IS_ENOENT and APR_STATUS_IS_ENOTDIR tests on + * Win32 platforms. The programmer should always be aware of this and + * adjust the order of the tests accordingly. + * @{ + */ + +/** @} */ + +/** + * @addtogroup APR_Util_Error + * @{ + */ +/** + * The key was empty or not provided + */ +#define APR_STATUS_IS_ENOKEY(s) ((s) == APR_ENOKEY) +/** + * The initialisation vector was not provided + */ +#define APR_STATUS_IS_ENOIV(s) ((s) == APR_ENOIV) +/** + * The key type was not recognised + */ +#define APR_STATUS_IS_EKEYTYPE(s) ((s) == APR_EKEYTYPE) +/** + * The buffer provided was not big enough + */ +#define APR_STATUS_IS_ENOSPACE(s) ((s) == APR_ENOSPACE) +/** + * An error occurred while encrypting or decrypting + */ +#define APR_STATUS_IS_ECRYPT(s) ((s) == APR_ECRYPT) +/** + * An error occurred while padding + */ +#define APR_STATUS_IS_EPADDING(s) ((s) == APR_EPADDING) +/** + * An error occurred with the key length + */ +#define APR_STATUS_IS_EKEYLENGTH(s) ((s) == APR_EKEYLENGTH) +/** + * The cipher provided was not recognised + */ +#define APR_STATUS_IS_ENOCIPHER(s) ((s) == APR_ENOCIPHER) +/** + * The digest provided was not recognised + */ +#define APR_STATUS_IS_ENODIGEST(s) ((s) == APR_ENODIGEST) +/** + * The engine provided was not recognised + */ +#define APR_STATUS_IS_ENOENGINE(s) ((s) == APR_ENOENGINE) +/** + * The engine could not be initialised + */ +#define APR_STATUS_IS_EINITENGINE(s) ((s) == APR_EINITENGINE) +/** + * Crypto has already been initialised + */ +#define APR_STATUS_IS_EREINIT(s) ((s) == APR_EREINIT) +/** @} */ + +/** + * This structure allows the underlying API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apu_err_t { + const char *reason; + const char *msg; + int rc; +} apu_err_t; + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APU_ERRNO_H */ diff --git a/c/dependencies/windows/apr/x86/include/apu_version.h b/c/dependencies/windows/apr/x86/include/apu_version.h new file mode 100644 index 00000000..e4fb2e64 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apu_version.h @@ -0,0 +1,139 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APU_VERSION_H +#define APU_VERSION_H + +/** + * @file apu_version.h + * @brief APR-util Versioning Interface + * + * APR-util's Version + * + * There are several different mechanisms for accessing the version. There + * is a string form, and a set of numbers; in addition, there are constants + * which can be compiled into your application, and you can query the library + * being used for its actual version. + * + * Note that it is possible for an application to detect that it has been + * compiled against a different version of APU by use of the compile-time + * constants and the use of the run-time query function. + * + * APU version numbering follows the guidelines specified in: + * + * http://apr.apache.org/versioning.html + */ + + +#define APU_COPYRIGHT "Copyright (c) 2000-2016 The Apache Software " \ + "Foundation or its licensors, as applicable." + +/* The numeric compile-time version constants. These constants are the + * authoritative version numbers for APU. + */ + +/** major version + * Major API changes that could cause compatibility problems for older + * programs such as structure size changes. No binary compatibility is + * possible across a change in the major version. + */ +#define APU_MAJOR_VERSION 1 + +/** minor version + * Minor API changes that do not cause binary compatibility problems. + * Reset to 0 when upgrading APU_MAJOR_VERSION + */ +#define APU_MINOR_VERSION 6 + +/** patch level + * The Patch Level never includes API changes, simply bug fixes. + * Reset to 0 when upgrading APR_MINOR_VERSION + */ +#define APU_PATCH_VERSION 1 + +/** + * The symbol APU_IS_DEV_VERSION is only defined for internal, + * "development" copies of APU. It is undefined for released versions + * of APU. + */ +/* #undef APU_IS_DEV_VERSION */ + + +#if defined(APU_IS_DEV_VERSION) || defined(DOXYGEN) +/** Internal: string form of the "is dev" flag */ +#ifndef APU_IS_DEV_STRING +#define APU_IS_DEV_STRING "-dev" +#endif +#else +#define APU_IS_DEV_STRING "" +#endif + + +#ifndef APU_STRINGIFY +/** Properly quote a value as a string in the C preprocessor */ +#define APU_STRINGIFY(n) APU_STRINGIFY_HELPER(n) +/** Helper macro for APU_STRINGIFY */ +#define APU_STRINGIFY_HELPER(n) #n +#endif + +/** The formatted string of APU's version */ +#define APU_VERSION_STRING \ + APU_STRINGIFY(APU_MAJOR_VERSION) "." \ + APU_STRINGIFY(APU_MINOR_VERSION) "." \ + APU_STRINGIFY(APU_PATCH_VERSION) \ + APU_IS_DEV_STRING + +/** An alternative formatted string of APR's version */ +/* macro for Win32 .rc files using numeric csv representation */ +#define APU_VERSION_STRING_CSV APU_MAJOR_VERSION ##, \ + ##APU_MINOR_VERSION ##, \ + ##APU_PATCH_VERSION + + +#ifndef APU_VERSION_ONLY + +/* The C language API to access the version at run time, + * as opposed to compile time. APU_VERSION_ONLY may be defined + * externally when preprocessing apr_version.h to obtain strictly + * the C Preprocessor macro declarations. + */ + +#include "apr_version.h" + +#include "apu.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Return APR-util's version information information in a numeric form. + * + * @param pvsn Pointer to a version structure for returning the version + * information. + */ +APU_DECLARE(void) apu_version(apr_version_t *pvsn); + +/** Return APU's version information as a string. */ +APU_DECLARE(const char *) apu_version_string(void); + +#ifdef __cplusplus +} +#endif + +#endif /* ndef APU_VERSION_ONLY */ + +#endif /* ndef APU_VERSION_H */ diff --git a/c/dependencies/windows/apr/x86/include/apu_want.h b/c/dependencies/windows/apr/x86/include/apu_want.h new file mode 100644 index 00000000..8bb56ce7 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apu_want.h @@ -0,0 +1,52 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apu.h" /* configuration data */ + +/** + * @file apu_want.h + * @brief APR Standard Headers Support + * + *
+ * Features:
+ *
+ *   APU_WANT_DB:       
+ *
+ * Typical usage:
+ *
+ *   #define APU_WANT_DB
+ *   #include "apu_want.h"
+ *
+ * The appropriate headers will be included.
+ *
+ * Note: it is safe to use this in a header (it won't interfere with other
+ *       headers' or source files' use of apu_want.h)
+ * 
+ */ + +/* --------------------------------------------------------------------- */ + +#ifdef APU_WANT_DB + +#if APU_HAVE_DB +/* win32 note.. you will need to change this for db1 */ +#include +#endif + +#undef APU_WANT_DB +#endif + +/* --------------------------------------------------------------------- */ diff --git a/c/dependencies/windows/apr/x86/include/apu_want.h.in b/c/dependencies/windows/apr/x86/include/apu_want.h.in new file mode 100644 index 00000000..81297a75 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apu_want.h.in @@ -0,0 +1,51 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apu.h" /* configuration data */ + +/** + * @file apu_want.h + * @brief APR Standard Headers Support + * + *
+ * Features:
+ *
+ *   APU_WANT_DB:       <@apu_db_header@>
+ *
+ * Typical usage:
+ *
+ *   #define APU_WANT_DB
+ *   #include "apu_want.h"
+ *
+ * The appropriate headers will be included.
+ *
+ * Note: it is safe to use this in a header (it won't interfere with other
+ *       headers' or source files' use of apu_want.h)
+ * 
+ */ + +/* --------------------------------------------------------------------- */ + +#ifdef APU_WANT_DB + +#if APU_HAVE_DB +#include <@apu_db_header@> +#endif + +#undef APU_WANT_DB +#endif + +/* --------------------------------------------------------------------- */ diff --git a/c/dependencies/windows/apr/x86/include/apu_want.hnw b/c/dependencies/windows/apr/x86/include/apu_want.hnw new file mode 100644 index 00000000..5d6edd3c --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apu_want.hnw @@ -0,0 +1,52 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apu.h" /* configuration data */ + +/** + * @file apu_want.h + * @brief APR Standard Headers Support + * + *
+ * Features:
+ *
+ *   APU_WANT_DB:       <@apu_db_header>
+ *
+ * Typical usage:
+ *
+ *   #define APU_WANT_DB
+ *   #include "apu_want.h"
+ *
+ * The appropriate headers will be included.
+ *
+ * Note: it is safe to use this in a header (it won't interfere with other
+ *       headers' or source files' use of apu_want.h)
+ * 
+ */ + +/* --------------------------------------------------------------------- */ + +#ifdef APU_WANT_DB + +#if APU_HAVE_DB +/* win32 note.. you will need to change this for db1 */ +#include +#endif + +#undef APU_WANT_DB +#endif + +/* --------------------------------------------------------------------- */ diff --git a/c/dependencies/windows/apr/x86/include/apu_want.hw b/c/dependencies/windows/apr/x86/include/apu_want.hw new file mode 100644 index 00000000..03b6ea98 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/apu_want.hw @@ -0,0 +1,52 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apu.h" /* configuration data */ + +/** + * @file apu_want.h + * @brief APR Standard Headers Support + * + *
+ * Features:
+ *
+ *   APU_WANT_DB:       
+ *
+ * Typical usage:
+ *
+ *   #define APU_WANT_DB
+ *   #include "apu_want.h"
+ *
+ * The appropriate headers will be included.
+ *
+ * Note: it is safe to use this in a header (it won't interfere with other
+ *       headers' or source files' use of apu_want.h)
+ * 
+ */ + +/* --------------------------------------------------------------------- */ + +#ifdef APU_WANT_DB + +#if APU_HAVE_DB +/* win32 note.. you will need to change this for db1 */ +#include +#endif + +#undef APU_WANT_DB +#endif + +/* --------------------------------------------------------------------- */ diff --git a/c/dependencies/windows/apr/x86/include/arch/aix/apr_arch_dso.h b/c/dependencies/windows/apr/x86/include/arch/aix/apr_arch_dso.h new file mode 100644 index 00000000..d1cac684 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/aix/apr_arch_dso.h @@ -0,0 +1,41 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_dso.h" +#include "apr.h" + +#if APR_HAS_DSO + +void *dlopen(const char *path, int mode); +void *dlsym(void *handle, const char *symbol); +const char *dlerror(void); +int dlclose(void *handle); + +struct apr_dso_handle_t { + apr_pool_t *pool; + void *handle; + const char *errormsg; +}; + +#endif + +#endif diff --git a/c/dependencies/windows/apr/x86/include/arch/apr_private_common.h b/c/dependencies/windows/apr/x86/include/arch/apr_private_common.h new file mode 100644 index 00000000..ec850c65 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/apr_private_common.h @@ -0,0 +1,41 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * This file contains private declarations common to all architectures. + */ + +#ifndef APR_PRIVATE_COMMON_H +#define APR_PRIVATE_COMMON_H + +#include "apr_pools.h" +#include "apr_tables.h" + +apr_status_t apr_filepath_list_split_impl(apr_array_header_t **pathelts, + const char *liststr, + char separator, + apr_pool_t *p); + +apr_status_t apr_filepath_list_merge_impl(char **liststr, + apr_array_header_t *pathelts, + char separator, + apr_pool_t *p); + +/* temporary defines to handle 64bit compile mismatches */ +#define APR_INT_TRUNC_CAST int +#define APR_UINT32_TRUNC_CAST apr_uint32_t + +#endif /*APR_PRIVATE_COMMON_H*/ diff --git a/c/dependencies/windows/apr/x86/include/arch/beos/apr_arch_dso.h b/c/dependencies/windows/apr/x86/include/arch/beos/apr_arch_dso.h new file mode 100644 index 00000000..fbc5c2ff --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/beos/apr_arch_dso.h @@ -0,0 +1,41 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_dso.h" +#include "apr.h" +#include +#include + +#if APR_HAS_DSO + +struct apr_dso_handle_t { + image_id handle; /* Handle to the DSO loaded */ + apr_pool_t *pool; + const char *errormsg; /* if the load fails, we have an error + * message here :) + */ +}; + +#endif + +#endif diff --git a/c/dependencies/windows/apr/x86/include/arch/beos/apr_arch_proc_mutex.h b/c/dependencies/windows/apr/x86/include/arch/beos/apr_arch_proc_mutex.h new file mode 100644 index 00000000..c60d8c62 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/beos/apr_arch_proc_mutex.h @@ -0,0 +1,36 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PROC_MUTEX_H +#define PROC_MUTEX_H + +#include "apr_pools.h" +#include "apr_proc_mutex.h" +#include "apr_file_io.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_portable.h" + +struct apr_proc_mutex_t { + apr_pool_t *pool; + + /* Our lock :) */ + sem_id Lock; + int32 LockCount; +}; + +#endif /* PROC_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/beos/apr_arch_thread_cond.h b/c/dependencies/windows/apr/x86/include/arch/beos/apr_arch_thread_cond.h new file mode 100644 index 00000000..c9420b53 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/beos/apr_arch_thread_cond.h @@ -0,0 +1,46 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_COND_H +#define THREAD_COND_H + +#include +#include "apr_pools.h" +#include "apr_thread_cond.h" +#include "apr_file_io.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_portable.h" +#include "apr_ring.h" + +struct waiter_t { + APR_RING_ENTRY(waiter_t) link; + sem_id sem; +}; + +struct apr_thread_cond_t { + apr_pool_t *pool; + sem_id lock; + apr_thread_mutex_t *condlock; + thread_id owner; + /* active list */ + APR_RING_HEAD(active_list, waiter_t) alist; + /* free list */ + APR_RING_HEAD(free_list, waiter_t) flist; +}; + +#endif /* THREAD_COND_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/beos/apr_arch_thread_mutex.h b/c/dependencies/windows/apr/x86/include/arch/beos/apr_arch_thread_mutex.h new file mode 100644 index 00000000..bb7d4ae8 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/beos/apr_arch_thread_mutex.h @@ -0,0 +1,42 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_MUTEX_H +#define THREAD_MUTEX_H + +#include +#include "apr_pools.h" +#include "apr_thread_mutex.h" +#include "apr_file_io.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_portable.h" + +struct apr_thread_mutex_t { + apr_pool_t *pool; + + /* Our lock :) */ + sem_id Lock; + int32 LockCount; + + /* If we nest locks we need these... */ + int nested; + apr_os_thread_t owner; + int owner_ref; +}; + +#endif /* THREAD_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/beos/apr_arch_thread_rwlock.h b/c/dependencies/windows/apr/x86/include/arch/beos/apr_arch_thread_rwlock.h new file mode 100644 index 00000000..694b0d50 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/beos/apr_arch_thread_rwlock.h @@ -0,0 +1,45 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_RWLOCK_H +#define THREAD_RWLOCK_H + +#include +#include "apr_pools.h" +#include "apr_thread_rwlock.h" +#include "apr_file_io.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_portable.h" + +struct apr_thread_rwlock_t { + apr_pool_t *pool; + + /* Our lock :) */ + sem_id Lock; + int32 LockCount; + /* Read/Write lock stuff */ + sem_id Read; + int32 ReadCount; + sem_id Write; + int32 WriteCount; + int32 Nested; + + thread_id writer; +}; + +#endif /* THREAD_RWLOCK_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/beos/apr_arch_threadproc.h b/c/dependencies/windows/apr/x86/include/arch/beos/apr_arch_threadproc.h new file mode 100644 index 00000000..13de0536 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/beos/apr_arch_threadproc.h @@ -0,0 +1,95 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr_thread_proc.h" +#include "apr_arch_file_io.h" +#include "apr_file_io.h" +#include "apr_thread_proc.h" +#include "apr_general.h" +#include "apr_portable.h" +#include +#include +#include +#include +#include + +#ifndef THREAD_PROC_H +#define THREAD_PROC_H + +#define SHELL_PATH "/bin/sh" + +#define PTHREAD_CANCEL_AYNCHRONOUS CANCEL_ASYNCH; +#define PTHREAD_CANCEL_DEFERRED CANCEL_DEFER; + +#define PTHREAD_CANCEL_ENABLE CANCEL_ENABLE; +#define PTHREAD_CANCEL_DISABLE CANCEL_DISABLE; + +#define BEOS_MAX_DATAKEYS 128 + +struct apr_thread_t { + apr_pool_t *pool; + thread_id td; + void *data; + apr_thread_start_t func; + apr_status_t exitval; +}; + +struct apr_threadattr_t { + apr_pool_t *pool; + int32 attr; + int detached; + int joinable; +}; + +struct apr_threadkey_t { + apr_pool_t *pool; + int32 key; +}; + +struct beos_private_data { + const void ** data; + int count; + volatile thread_id td; +}; + +struct beos_key { + int assigned; + int count; + sem_id lock; + int32 ben_lock; + void (* destructor) (void *); +}; + +struct apr_procattr_t { + apr_pool_t *pool; + apr_file_t *parent_in; + apr_file_t *child_in; + apr_file_t *parent_out; + apr_file_t *child_out; + apr_file_t *parent_err; + apr_file_t *child_err; + char *currdir; + apr_int32_t cmdtype; + apr_int32_t detached; +}; + +struct apr_thread_once_t { + sem_id sem; + int hit; +}; + +#endif /* ! THREAD_PROC_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_dso.h b/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_dso.h new file mode 100644 index 00000000..ea0fe8c2 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_dso.h @@ -0,0 +1,43 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_dso.h" +#include "apr.h" + +#include + +typedef struct sym_list sym_list; + +struct sym_list { + sym_list *next; + char *symbol; +}; + +struct apr_dso_handle_t { + apr_pool_t *pool; + void *handle; + const char *errormsg; + sym_list *symbols; + char *path; +}; + +#endif diff --git a/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_file_io.h b/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_file_io.h new file mode 100644 index 00000000..8bd2a72c --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_file_io.h @@ -0,0 +1,176 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FILE_IO_H +#define FILE_IO_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_tables.h" +#include "apr_file_io.h" +#include "apr_file_info.h" +#include "apr_errno.h" +#include "apr_lib.h" +#include "apr_poll.h" + +/* System headers the file I/O library needs */ +#if APR_HAVE_FCNTL_H +#include +#endif +#if APR_HAVE_SYS_TYPES_H +#include +#endif +#if APR_HAVE_ERRNO_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#if APR_HAVE_STRINGS_H +#include +#endif +#if APR_HAVE_DIRENT_H +#include +#endif +#ifdef HAVE_SYS_STAT_H +#include +#endif +#if APR_HAVE_UNISTD_H +#include +#endif +#if APR_HAVE_STDIO_H +#include +#endif +#if APR_HAVE_STDLIB_H +#include +#endif +#if APR_HAVE_SYS_UIO_H +#include +#endif +#if APR_HAVE_SYS_TIME_H +#include +#endif + +#include + +/* End System headers */ + +#define APR_FILE_DEFAULT_BUFSIZE 4096 +/* For backwards compat */ +#define APR_FILE_BUFSIZE APR_FILE_DEFAULT_BUFSIZE + +#if APR_HAS_THREADS +#define file_lock(f) do { \ + if ((f)->thlock) \ + apr_thread_mutex_lock((f)->thlock); \ + } while (0) +#define file_unlock(f) do { \ + if ((f)->thlock) \ + apr_thread_mutex_unlock((f)->thlock); \ + } while (0) +#else +#define file_lock(f) do {} while (0) +#define file_unlock(f) do {} while (0) +#endif + +#if APR_HAS_LARGE_FILES +#define lseek(f,o,w) lseek64(f,o,w) +#define ftruncate(f,l) ftruncate64(f,l) +#endif + +typedef struct stat struct_stat; + +struct apr_file_t { + apr_pool_t *pool; + int filedes; + char *fname; + apr_int32_t flags; + int eof_hit; + int is_pipe; + apr_interval_time_t timeout; + int buffered; + enum {BLK_UNKNOWN, BLK_OFF, BLK_ON } blocking; + int ungetchar; /* Last char provided by an unget op. (-1 = no char)*/ + + /* if there is a timeout set, then this pollset is used */ + apr_pollset_t *pollset; + + /* Stuff for buffered mode */ + char *buffer; + apr_size_t bufpos; /* Read/Write position in buffer */ + apr_size_t bufsize; /* The buffer size */ + apr_off_t dataRead; /* amount of valid data read into buffer */ + int direction; /* buffer being used for 0 = read, 1 = write */ + apr_off_t filePtr; /* position in file of handle */ +#if APR_HAS_THREADS + struct apr_thread_mutex_t *thlock; +#endif +}; + +struct apr_dir_t { + apr_pool_t *pool; + char *dirname; + DIR *dirstruct; + struct dirent *entry; +}; + +typedef struct apr_stat_entry_t apr_stat_entry_t; + +struct apr_stat_entry_t { + struct stat info; + char *casedName; + apr_time_t expire; + NXPathCtx_t pathCtx; +}; + +#define MAX_SERVER_NAME 64 +#define MAX_VOLUME_NAME 64 +#define MAX_PATH_NAME 256 +#define MAX_FILE_NAME 256 + +#define DRIVE_ONLY 1 + +/* If the user passes d: vs. D: (or //mach/share vs. //MACH/SHARE), + * we need to fold the case to canonical form. This function is + * supposed to do so. + */ +apr_status_t filepath_root_case(char **rootpath, char *root, apr_pool_t *p); + +/* This function check to see of the given path includes a drive/volume + * specifier. If the _only_ parameter is set to DRIVE_ONLY then it + * check to see of the path only contains a drive/volume specifier and + * nothing else. + */ +apr_status_t filepath_has_drive(const char *rootpath, int only, apr_pool_t *p); + +/* This function compares the drive/volume specifiers for each given path. + * It returns zero if they match or non-zero if not. + */ +apr_status_t filepath_compare_drive(const char *path1, const char *path2, apr_pool_t *p); + +apr_status_t apr_unix_file_cleanup(void *); +apr_status_t apr_unix_child_file_cleanup(void *); + +mode_t apr_unix_perms2mode(apr_fileperms_t perms); +apr_fileperms_t apr_unix_mode2perms(mode_t mode); + +apr_status_t apr_file_flush_locked(apr_file_t *thefile); +apr_status_t apr_file_info_get_locked(apr_finfo_t *finfo, apr_int32_t wanted, + apr_file_t *thefile); + +#endif /* ! FILE_IO_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_global_mutex.h b/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_global_mutex.h new file mode 100644 index 00000000..4167d378 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_global_mutex.h @@ -0,0 +1,29 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GLOBAL_MUTEX_H +#define GLOBAL_MUTEX_H + +#include "apr_global_mutex.h" +#include "apr_thread_mutex.h" + +struct apr_global_mutex_t { + apr_pool_t *pool; + apr_thread_mutex_t *mutex; +}; + +#endif /* GLOBAL_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_internal_time.h b/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_internal_time.h new file mode 100644 index 00000000..59f10672 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_internal_time.h @@ -0,0 +1,26 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIME_INTERNAL_H +#define TIME_INTERNAL_H + +#include "apr.h" + +#define TZONE (*___timezone()) + +void apr_netware_setup_time(void); + +#endif /* TIME_INTERNAL_H */ diff --git a/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_networkio.h b/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_networkio.h new file mode 100644 index 00000000..63f17abe --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_networkio.h @@ -0,0 +1,31 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETWORK_IO_H + +#ifdef USE_WINSOCK +/* Making sure that we include the correct networkio.h since the + the project file is configured to first look for headers in + arch/netware and then arch/unix. But in this specific case we + want arch/win32. +*/ +#include <../win32/apr_arch_networkio.h> +#else +#include <../unix/apr_arch_networkio.h> +#endif + +#endif /* ! NETWORK_IO_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_pre_nw.h b/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_pre_nw.h new file mode 100644 index 00000000..7380e118 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_pre_nw.h @@ -0,0 +1,57 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef __pre_nw__ +#define __pre_nw__ + +#include + +#ifndef __GNUC__ +#pragma precompile_target "precomp.mch" +#endif + +#define NETWARE + +#define N_PLAT_NLM + +#define FAR +#define far + +/* no-op for Codewarrior C compiler; a functions are cdecl + by default */ +#define cdecl + +/* if we have wchar_t enabled in C++, predefine this type to avoid + a conflict in Novell's header files */ +#ifndef __GNUC__ +#ifndef DOXYGEN +#if (__option(cplusplus) && __option(wchar_type)) +#define _WCHAR_T +#endif +#endif +#endif + +/* C9X defintion used by MSL C++ library */ +#define DECIMAL_DIG 17 + +/* some code may want to use the MS convention for long long */ +#ifndef __int64 +#define __int64 long long +#endif + +#endif + + + diff --git a/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_proc_mutex.h b/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_proc_mutex.h new file mode 100644 index 00000000..7a634c2e --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_proc_mutex.h @@ -0,0 +1,29 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PROC_MUTEX_H +#define PROC_MUTEX_H + +#include "apr_proc_mutex.h" +#include "apr_thread_mutex.h" + +struct apr_proc_mutex_t { + apr_pool_t *pool; + apr_thread_mutex_t *mutex; +}; + +#endif /* PROC_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_thread_cond.h b/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_thread_cond.h new file mode 100644 index 00000000..b11a5f86 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_thread_cond.h @@ -0,0 +1,29 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_COND_H +#define THREAD_COND_H + +#include "apr_thread_cond.h" +#include + +struct apr_thread_cond_t { + apr_pool_t *pool; + NXCond_t *cond; +}; + +#endif /* THREAD_COND_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_thread_mutex.h b/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_thread_mutex.h new file mode 100644 index 00000000..18702fc7 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_thread_mutex.h @@ -0,0 +1,32 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_MUTEX_H +#define THREAD_MUTEX_H + +#include "apr_thread_mutex.h" +#include "apr_thread_cond.h" +#include + +struct apr_thread_mutex_t { + apr_pool_t *pool; + NXMutex_t *mutex; + apr_thread_cond_t *cond; + int locked, num_waiters; +}; + +#endif /* THREAD_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_thread_rwlock.h b/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_thread_rwlock.h new file mode 100644 index 00000000..d2dbd42f --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_thread_rwlock.h @@ -0,0 +1,29 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_RWLOCK_H +#define THREAD_RWLOCK_H + +#include "apr_thread_rwlock.h" +#include + +struct apr_thread_rwlock_t { + apr_pool_t *pool; + NXRwLock_t *rwlock; +}; + +#endif /* THREAD_RWLOCK_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_threadproc.h b/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_threadproc.h new file mode 100644 index 00000000..2fee2c00 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/netware/apr_arch_threadproc.h @@ -0,0 +1,80 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" + +#include + +#ifndef THREAD_PROC_H +#define THREAD_PROC_H + +#define SHELL_PATH "" +#define APR_DEFAULT_STACK_SIZE 65536 + +struct apr_thread_t { + apr_pool_t *pool; + NXContext_t ctx; + NXThreadId_t td; + char *thread_name; + apr_int32_t cancel; + apr_int32_t cancel_how; + void *data; + apr_thread_start_t func; + apr_status_t exitval; +}; + +struct apr_threadattr_t { + apr_pool_t *pool; + apr_size_t stack_size; + apr_int32_t detach; + char *thread_name; +}; + +struct apr_threadkey_t { + apr_pool_t *pool; + NXKey_t key; +}; + +struct apr_procattr_t { + apr_pool_t *pool; + apr_file_t *parent_in; + apr_file_t *child_in; + apr_file_t *parent_out; + apr_file_t *child_out; + apr_file_t *parent_err; + apr_file_t *child_err; + char *currdir; + apr_int32_t cmdtype; + apr_int32_t detached; + apr_int32_t addrspace; +}; + +struct apr_thread_once_t { + unsigned long value; +}; + +/* +struct apr_proc_t { + apr_pool_t *pool; + pid_t pid; + apr_procattr_t *attr; +}; +*/ + +#endif /* ! THREAD_PROC_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/netware/apr_private.h b/c/dependencies/windows/apr/x86/include/arch/netware/apr_private.h new file mode 100644 index 00000000..04f336de --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/netware/apr_private.h @@ -0,0 +1,205 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Note: + * This is the netware-specific autoconf-like config file + * which unix creates at ./configure time. + */ + +#ifdef NETWARE + +#ifndef APR_PRIVATE_H +#define APR_PRIVATE_H + +/* Pick up publicly advertised headers and symbols before the + * APR internal private headers and symbols + */ +#include + +/* Pick up privately consumed headers */ +#include + +/* Include alloca.h to get compiler-dependent defines */ +#include + +#include +#include +#include +#include +#include +#include +#include + +/* Use this section to define all of the HAVE_FOO_H + * that are required to build properly. + */ +#define HAVE_DLFCN_H 1 +#define HAVE_LIMITS_H 1 +#define HAVE_SIGNAL_H 1 +#define HAVE_STDDEF_H 1 +#define HAVE_STDLIB_H 1 +#ifndef USE_WINSOCK +#define HAVE_SYS_SELECT_H 1 +#define HAVE_WRITEV 1 +#endif +#define HAVE_SYS_STAT_H 1 +#define HAVE_SYS_MMAN_H 1 +#define HAVE_FCNTL_H 1 +#define HAVE_ICONV_H 1 +#define HAVE_UTIME_H 1 + +#define HAVE_STRICMP 1 +#define HAVE_STRNICMP 1 +#define HAVE_STRDUP 1 +#define HAVE_STRSTR 1 +#define HAVE_MEMCHR 1 +#define HAVE_CALLOC 1 +#define HAVE_UTIME 1 + +#define HAVE_GETENV 1 +#define HAVE_SETENV 1 +#define HAVE_UNSETENV 1 + +#define HAVE_WRITEV 1 + +#define HAVE_GETPASS_R 1 +/* + * Hack around older NDKs which have only the getpassword() function, + * a threadsafe, API-equivalent of getpass_r(). + */ +#if (CURRENT_NDK_THRESHOLD < 709060000) +#define getpass_r getpassword +#endif + +/*#define DSO_USE_DLFCN */ + +#ifdef NW_BUILD_IPV6 +#define HAVE_GETADDRINFO 1 +#define HAVE_GETNAMEINFO 1 +#endif + +/* 1 is used for SIGABRT on netware */ +/* 2 is used for SIGFPE on netware */ +/* 3 is used for SIGILL on netware */ +/* 4 is used for SIGINT on netware */ +/* 5 is used for SIGSEGV on netware */ +/* 6 is used for SIGTERM on netware */ +/* 7 is used for SIGPOLL on netware */ + +#if (CURRENT_NDK_THRESHOLD < 306030000) +#define SIGKILL 11 +#define SIGALRM 13 +#define SIGCHLD 14 +#define SIGCONT 15 +#define SIGHUP 16 +#define SIGPIPE 17 +#define SIGQUIT 18 +#define SIGSTOP 19 +#define SIGTSTP 20 +#define SIGTTIN 21 +#define SIGTTOU 22 +#define SIGUSR1 23 +#define SIGUSR2 24 +#endif + +#define SIGTRAP 25 +#define SIGIOT 26 +#define SIGSTKFLT 28 +#define SIGURG 29 +#define SIGXCPU 30 +#define SIGXFSZ 31 +#define SIGVTALRM 32 +#define SIGPROF 33 +#define SIGWINCH 34 +#define SIGIO 35 + +#if (CURRENT_NDK_THRESHOLD < 406230000) +#undef SA_NOCLDSTOP +#define SA_NOCLDSTOP 0x00000001 +#endif +#ifndef SIGBUS +#define SIGBUS SIGSEGV +#endif + +#define _getch getcharacter + +#define SIZEOF_SHORT 2 +#define SIZEOF_INT 4 +#define SIZEOF_LONGLONG 8 +#define SIZEOF_CHAR 1 +#define SIZEOF_SSIZE_T SIZEOF_INT + +void netware_pool_proc_cleanup(); + +/* NLM registration routines for managing which NLMs + are using the library. */ +int register_NLM(void *NLMHandle); +int unregister_NLM(void *NLMHandle); + +/* Application global data management */ +extern int gLibId; +extern void *gLibHandle; + +typedef struct app_data { + int initialized; + void* gPool; + void* gs_aHooksToSort; + void* gs_phOptionalHooks; + void* gs_phOptionalFunctions; + void* gs_nlmhandle; + rtag_t gs_startup_rtag; + rtag_t gs_socket_rtag; + rtag_t gs_lookup_rtag; + rtag_t gs_event_rtag; + rtag_t gs_pcp_rtag; + void* gs_ldap_xref_lock; + void* gs_xref_head; +} APP_DATA; + +int setGlobalPool(void *data); +void* getGlobalPool(); +int setStatCache(void *data); +void* getStatCache(); + +/* Redefine malloc to use the library malloc call so + that all of the memory resources will be owned + and can be shared by the library. */ +#undef malloc +#define malloc(x) library_malloc(gLibHandle,x) +#ifndef __MWERKS__ +#define _alloca alloca +#endif + +/* 64-bit integer conversion function */ +#define APR_INT64_STRFN strtoll + +#if APR_HAS_LARGE_FILES +#define APR_OFF_T_STRFN strtoll +#else +#define APR_OFF_T_STRFN strtol +#endif + +/* used to check DWORD overflow for 64bit compiles */ +#define APR_DWORD_MAX 0xFFFFFFFFUL + +/* + * Include common private declarations. + */ +#include "../apr_private_common.h" + +#endif /*APR_PRIVATE_H*/ +#endif /*NETWARE*/ diff --git a/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_dso.h b/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_dso.h new file mode 100644 index 00000000..2bda6b7c --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_dso.h @@ -0,0 +1,37 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_dso.h" +#include "apr.h" + +#if APR_HAS_DSO + +struct apr_dso_handle_t { + apr_pool_t *cont; /* Context for returning error strings */ + HMODULE handle; /* Handle to the DSO loaded */ + apr_status_t load_error; + char *failed_module; +}; + +#endif + +#endif diff --git a/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_file_io.h b/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_file_io.h new file mode 100644 index 00000000..79a57964 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_file_io.h @@ -0,0 +1,86 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FILE_IO_H +#define FILE_IO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_thread_mutex.h" +#include "apr_file_io.h" +#include "apr_file_info.h" +#include "apr_errno.h" +#include "apr_poll.h" + +/* We have an implementation of mkstemp but it's not very multi-threading + * friendly & is part of the POSIX emulation rather than native so don't + * use it. + */ +#undef HAVE_MKSTEMP + +#define APR_FILE_DEFAULT_BUFSIZE 4096 +#define APR_FILE_BUFSIZE APR_FILE_DEFAULT_BUFSIZE + +struct apr_file_t { + apr_pool_t *pool; + HFILE filedes; + char * fname; + int isopen; + int buffered; + int eof_hit; + apr_int32_t flags; + int timeout; + int pipe; + HEV pipeSem; + enum { BLK_UNKNOWN, BLK_OFF, BLK_ON } blocking; + + /* Stuff for buffered mode */ + char *buffer; + apr_size_t bufsize; /* Read/Write position in buffer */ + apr_size_t bufpos; /* Read/Write position in buffer */ + unsigned long dataRead; /* amount of valid data read into buffer */ + int direction; /* buffer being used for 0 = read, 1 = write */ + unsigned long filePtr; /* position in file of handle */ + apr_thread_mutex_t *mutex; /* mutex semaphore, must be owned to access + the above fields */ +}; + +struct apr_dir_t { + apr_pool_t *pool; + char *dirname; + ULONG handle; + FILEFINDBUF3 entry; + int validentry; +}; + +apr_status_t apr_file_cleanup(void *); +apr_status_t apr_os2_time_to_apr_time(apr_time_t *result, FDATE os2date, + FTIME os2time); +apr_status_t apr_apr_time_to_os2_time(FDATE *os2date, FTIME *os2time, + apr_time_t aprtime); + +/* see win32/fileio.h for description of these */ +extern const char c_is_fnchar[256]; + +#define IS_FNCHAR(c) c_is_fnchar[(unsigned char)c] + +apr_status_t filepath_root_test(char *path, apr_pool_t *p); +apr_status_t filepath_drive_get(char **rootpath, char drive, + apr_int32_t flags, apr_pool_t *p); +apr_status_t filepath_root_case(char **rootpath, char *root, apr_pool_t *p); + +#endif /* ! FILE_IO_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_inherit.h b/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_inherit.h new file mode 100644 index 00000000..494772ac --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_inherit.h @@ -0,0 +1,50 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INHERIT_H +#define INHERIT_H + +#include "apr_inherit.h" + +#define APR_INHERIT (1 << 24) /* Must not conflict with other bits */ + +#define APR_IMPLEMENT_INHERIT_SET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_set(apr_##name##_t *the##name) \ +{ \ + int rv; \ + ULONG state; \ + if (((rv = DosQueryFHState(attr->parent_err->filedes, &state)) \ + != 0) || \ + ((rv = DosSetFHState(attr->parent_err->filedes, \ + state & ~OPEN_FLAGS_NOINHERIT)) != 0)) \ + return APR_FROM_OS_ERROR(rv); \ + return APR_SUCCESS; \ +} + +#define APR_IMPLEMENT_INHERIT_UNSET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_unset(apr_##name##_t *the##name)\ +{ \ + int rv; \ + ULONG state; \ + if (((rv = DosQueryFHState(attr->parent_err->filedes, &state)) \ + != 0) || \ + ((rv = DosSetFHState(attr->parent_err->filedes, \ + state | OPEN_FLAGS_NOINHERIT)) != 0)) \ + return APR_FROM_OS_ERROR(rv); \ + return APR_SUCCESS; \ +} + +#endif /* ! INHERIT_H */ diff --git a/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_networkio.h b/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_networkio.h new file mode 100644 index 00000000..10c6de81 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_networkio.h @@ -0,0 +1,76 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETWORK_IO_H +#define NETWORK_IO_H + +#include "apr_private.h" +#include "apr_network_io.h" +#include "apr_general.h" +#include "apr_arch_os2calls.h" +#include "apr_poll.h" + +#if APR_HAVE_NETDB_H +#include +#endif + +typedef struct sock_userdata_t sock_userdata_t; +struct sock_userdata_t { + sock_userdata_t *next; + const char *key; + void *data; +}; + +struct apr_socket_t { + apr_pool_t *pool; + int socketdes; + int type; + int protocol; + apr_sockaddr_t *local_addr; + apr_sockaddr_t *remote_addr; + apr_interval_time_t timeout; + int nonblock; + int local_port_unknown; + int local_interface_unknown; + int remote_addr_unknown; + apr_int32_t options; + apr_int32_t inherit; + sock_userdata_t *userdata; + + /* if there is a timeout set, then this pollset is used */ + apr_pollset_t *pollset; +}; + +/* Error codes returned from sock_errno() */ +#define SOCBASEERR 10000 +#define SOCEPERM (SOCBASEERR+1) /* Not owner */ +#define SOCESRCH (SOCBASEERR+3) /* No such process */ +#define SOCEINTR (SOCBASEERR+4) /* Interrupted system call */ +#define SOCENXIO (SOCBASEERR+6) /* No such device or address */ +#define SOCEBADF (SOCBASEERR+9) /* Bad file number */ +#define SOCEACCES (SOCBASEERR+13) /* Permission denied */ +#define SOCEFAULT (SOCBASEERR+14) /* Bad address */ +#define SOCEINVAL (SOCBASEERR+22) /* Invalid argument */ +#define SOCEMFILE (SOCBASEERR+24) /* Too many open files */ +#define SOCEPIPE (SOCBASEERR+32) /* Broken pipe */ +#define SOCEOS2ERR (SOCBASEERR+100) /* OS/2 Error */ + +const char *apr_inet_ntop(int af, const void *src, char *dst, apr_size_t size); +int apr_inet_pton(int af, const char *src, void *dst); +void apr_sockaddr_vars_set(apr_sockaddr_t *, int, apr_port_t); + +#endif /* ! NETWORK_IO_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_os2calls.h b/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_os2calls.h new file mode 100644 index 00000000..3c739bfd --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_os2calls.h @@ -0,0 +1,59 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr_errno.h" +#include +#include + +extern int (*apr_os2_socket)(int, int, int); +extern int (*apr_os2_select)(int *, int, int, int, long); +extern int (*apr_os2_sock_errno)(); +extern int (*apr_os2_accept)(int, struct sockaddr *, int *); +extern int (*apr_os2_bind)(int, struct sockaddr *, int); +extern int (*apr_os2_connect)(int, struct sockaddr *, int); +extern int (*apr_os2_getpeername)(int, struct sockaddr *, int *); +extern int (*apr_os2_getsockname)(int, struct sockaddr *, int *); +extern int (*apr_os2_getsockopt)(int, int, int, char *, int *); +extern int (*apr_os2_ioctl)(int, int, caddr_t, int); +extern int (*apr_os2_listen)(int, int); +extern int (*apr_os2_recv)(int, char *, int, int); +extern int (*apr_os2_send)(int, const char *, int, int); +extern int (*apr_os2_setsockopt)(int, int, int, char *, int); +extern int (*apr_os2_shutdown)(int, int); +extern int (*apr_os2_soclose)(int); +extern int (*apr_os2_writev)(int, struct iovec *, int); +extern int (*apr_os2_sendto)(int, const char *, int, int, const struct sockaddr *, int); +extern int (*apr_os2_recvfrom)(int, char *, int, int, struct sockaddr *, int *); + +#define socket apr_os2_socket +#define select apr_os2_select +#define sock_errno apr_os2_sock_errno +#define accept apr_os2_accept +#define bind apr_os2_bind +#define connect apr_os2_connect +#define getpeername apr_os2_getpeername +#define getsockname apr_os2_getsockname +#define getsockopt apr_os2_getsockopt +#define ioctl apr_os2_ioctl +#define listen apr_os2_listen +#define recv apr_os2_recv +#define send apr_os2_send +#define setsockopt apr_os2_setsockopt +#define shutdown apr_os2_shutdown +#define soclose apr_os2_soclose +#define writev apr_os2_writev +#define sendto apr_os2_sendto +#define recvfrom apr_os2_recvfrom diff --git a/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_proc_mutex.h b/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_proc_mutex.h new file mode 100644 index 00000000..8caf3369 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_proc_mutex.h @@ -0,0 +1,31 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PROC_MUTEX_H +#define PROC_MUTEX_H + +#include "apr_proc_mutex.h" +#include "apr_file_io.h" + +struct apr_proc_mutex_t { + apr_pool_t *pool; + HMTX hMutex; + TID owner; + int lock_count; +}; + +#endif /* PROC_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_thread_cond.h b/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_thread_cond.h new file mode 100644 index 00000000..aa0a7ca6 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_thread_cond.h @@ -0,0 +1,33 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_COND_H +#define THREAD_COND_H + +#include "apr_thread_cond.h" +#include "apr_file_io.h" + +struct apr_thread_cond_t { + apr_pool_t *pool; + HEV semaphore; + HMTX mutex; + unsigned long num_waiting; + unsigned long num_wake; + unsigned long generation; +}; + +#endif /* THREAD_COND_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_thread_mutex.h b/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_thread_mutex.h new file mode 100644 index 00000000..3ae2a41d --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_thread_mutex.h @@ -0,0 +1,29 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_MUTEX_H +#define THREAD_MUTEX_H + +#include "apr_thread_mutex.h" +#include "apr_file_io.h" + +struct apr_thread_mutex_t { + apr_pool_t *pool; + HMTX hMutex; +}; + +#endif /* THREAD_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_thread_rwlock.h b/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_thread_rwlock.h new file mode 100644 index 00000000..7187d5cb --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_thread_rwlock.h @@ -0,0 +1,31 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_RWLOCK_H +#define THREAD_RWLOCK_H + +#include "apr_thread_rwlock.h" +#include "apr_file_io.h" + +struct apr_thread_rwlock_t { + apr_pool_t *pool; + int readers; + HMTX write_lock; + HEV read_done; +}; + +#endif /* THREAD_RWLOCK_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_threadproc.h b/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_threadproc.h new file mode 100644 index 00000000..c8017adb --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/os2/apr_arch_threadproc.h @@ -0,0 +1,67 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr_thread_proc.h" +#include "apr_file_io.h" + +#ifndef THREAD_PROC_H +#define THREAD_PROC_H + +#define APR_THREADATTR_DETACHED 1 + +#define SHELL_PATH "cmd.exe" +#define APR_THREAD_STACKSIZE 65536 + +struct apr_threadattr_t { + apr_pool_t *pool; + unsigned long attr; + apr_size_t stacksize; +}; + +struct apr_thread_t { + apr_pool_t *pool; + struct apr_threadattr_t *attr; + unsigned long tid; + apr_thread_start_t func; + void *data; + apr_status_t exitval; +}; + +struct apr_threadkey_t { + apr_pool_t *pool; + unsigned long *key; +}; + +struct apr_procattr_t { + apr_pool_t *pool; + apr_file_t *parent_in; + apr_file_t *child_in; + apr_file_t *parent_out; + apr_file_t *child_out; + apr_file_t *parent_err; + apr_file_t *child_err; + char *currdir; + apr_int32_t cmdtype; + apr_int32_t detached; +}; + +struct apr_thread_once_t { + unsigned long sem; + char hit; +}; + +#endif /* ! THREAD_PROC_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/os390/apr_arch_dso.h b/c/dependencies/windows/apr/x86/include/arch/os390/apr_arch_dso.h new file mode 100644 index 00000000..4263297b --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/os390/apr_arch_dso.h @@ -0,0 +1,39 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_dso.h" +#include "apr.h" + +#if APR_HAS_DSO + +#include + +struct apr_dso_handle_t { + dllhandle *handle; /* Handle to the DSO loaded */ + int failing_errno; /* Don't save the buffer returned by + strerror(); it gets reused */ + apr_pool_t *pool; +}; + +#endif + +#endif diff --git a/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_atomic.h b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_atomic.h new file mode 100644 index 00000000..559257de --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_atomic.h @@ -0,0 +1,53 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ATOMIC_H +#define ATOMIC_H + +#include "apr.h" +#include "apr_pools.h" +#include "apr_private.h" +#include "apr_atomic.h" + +#if defined(USE_ATOMICS_GENERIC) +/* noop */ +#elif HAVE_ATOMIC_BUILTINS +# define USE_ATOMICS_BUILTINS +#elif defined(SOLARIS2) && SOLARIS2 >= 10 +# define USE_ATOMICS_SOLARIS +# define NEED_ATOMICS_GENERIC64 +#elif defined(__GNUC__) && defined(__STRICT_ANSI__) +/* force use of generic atomics if building e.g. with -std=c89, which + * doesn't allow inline asm */ +# define USE_ATOMICS_GENERIC +#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) +# define USE_ATOMICS_IA32 +# define NEED_ATOMICS_GENERIC64 +#elif defined(__GNUC__) && (defined(__PPC__) || defined(__ppc__)) +# define USE_ATOMICS_PPC +# define NEED_ATOMICS_GENERIC64 +#elif defined(__GNUC__) && (defined(__s390__) || defined(__s390x__)) +# define USE_ATOMICS_S390 +# define NEED_ATOMICS_GENERIC64 +#else +# define USE_ATOMICS_GENERIC +#endif + +#if defined(USE_ATOMICS_GENERIC) || defined (NEED_ATOMICS_GENERIC64) +apr_status_t apr__atomic_generic64_init(apr_pool_t *p); +#endif + +#endif /* ATOMIC_H */ diff --git a/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_dso.h b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_dso.h new file mode 100644 index 00000000..d82182d4 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_dso.h @@ -0,0 +1,63 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_dso.h" +#include "apr.h" + +#if APR_HAS_DSO + +#ifdef HAVE_MACH_O_DYLD_H +#include +#endif + +#ifdef HAVE_DLFCN_H +#include +#endif + +#ifdef HAVE_DL_H +#include +#endif + +#ifndef RTLD_NOW +#define RTLD_NOW 1 +#endif + +#ifndef RTLD_GLOBAL +#define RTLD_GLOBAL 0 +#endif + +#if (defined(__DragonFly__) ||\ + defined(__FreeBSD__) ||\ + defined(__OpenBSD__) ||\ + defined(__NetBSD__) ) && !defined(__ELF__) +#define DLSYM_NEEDS_UNDERSCORE +#endif + +struct apr_dso_handle_t { + apr_pool_t *pool; + void *handle; + const char *errormsg; +}; + +#endif + +#endif diff --git a/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_file_io.h b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_file_io.h new file mode 100644 index 00000000..77a90917 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_file_io.h @@ -0,0 +1,174 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FILE_IO_H +#define FILE_IO_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_tables.h" +#include "apr_file_io.h" +#include "apr_file_info.h" +#include "apr_errno.h" +#include "apr_lib.h" +#include "apr_thread_mutex.h" +#ifndef WAITIO_USES_POLL +#include "apr_poll.h" +#endif + +/* System headers the file I/O library needs */ +#if APR_HAVE_FCNTL_H +#include +#endif +#if APR_HAVE_SYS_TYPES_H +#include +#endif +#if APR_HAVE_ERRNO_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#if APR_HAVE_STRINGS_H +#include +#endif +#if APR_HAVE_DIRENT_H +#include +#endif +#ifdef HAVE_SYS_STAT_H +#include +#endif +#if APR_HAVE_UNISTD_H +#include +#endif +#if APR_HAVE_STDIO_H +#include +#endif +#if APR_HAVE_STDLIB_H +#include +#endif +#if APR_HAVE_SYS_UIO_H +#include +#endif +#if APR_HAVE_SYS_TIME_H +#include +#endif +#ifdef BEOS +#include +#endif +/* Hunting down DEV_BSIZE if not from dirent.h, sys/stat.h etc */ +#ifdef HAVE_SYS_PARAM_H +#include +#endif + +#if BEOS_BONE +# ifndef BONE7 + /* prior to BONE/7 fd_set & select were defined in sys/socket.h */ +# include +# else + /* Be moved the fd_set stuff and also the FIONBIO definition... */ +# include +# endif +#endif +/* End System headers */ + +#define APR_FILE_DEFAULT_BUFSIZE 4096 +/* For backwards-compat */ +#define APR_FILE_BUFSIZE APR_FILE_DEFAULT_BUFSIZE + +struct apr_file_t { + apr_pool_t *pool; + int filedes; + char *fname; + apr_int32_t flags; + int eof_hit; + int is_pipe; + apr_interval_time_t timeout; + int buffered; + enum {BLK_UNKNOWN, BLK_OFF, BLK_ON } blocking; + int ungetchar; /* Last char provided by an unget op. (-1 = no char)*/ +#ifndef WAITIO_USES_POLL + /* if there is a timeout set, then this pollset is used */ + apr_pollset_t *pollset; +#endif + /* Stuff for buffered mode */ + char *buffer; + apr_size_t bufpos; /* Read/Write position in buffer */ + apr_size_t bufsize; /* The size of the buffer */ + unsigned long dataRead; /* amount of valid data read into buffer */ + int direction; /* buffer being used for 0 = read, 1 = write */ + apr_off_t filePtr; /* position in file of handle */ +#if APR_HAS_THREADS + struct apr_thread_mutex_t *thlock; +#endif +}; + +#if APR_HAS_THREADS +#define file_lock(f) do { \ + if ((f)->thlock) \ + apr_thread_mutex_lock((f)->thlock); \ + } while (0) +#define file_unlock(f) do { \ + if ((f)->thlock) \ + apr_thread_mutex_unlock((f)->thlock); \ + } while (0) +#else +#define file_lock(f) do {} while (0) +#define file_unlock(f) do {} while (0) +#endif + +#if APR_HAS_LARGE_FILES && defined(_LARGEFILE64_SOURCE) +#define stat(f,b) stat64(f,b) +#define lstat(f,b) lstat64(f,b) +#define fstat(f,b) fstat64(f,b) +#define lseek(f,o,w) lseek64(f,o,w) +#define ftruncate(f,l) ftruncate64(f,l) +typedef struct stat64 struct_stat; +#else +typedef struct stat struct_stat; +#endif + +/* readdir64_r is only used in specific cases: */ +#if APR_HAS_THREADS && defined(_POSIX_THREAD_SAFE_FUNCTIONS) \ + && !defined(READDIR_IS_THREAD_SAFE) && defined(HAVE_READDIR64_R) +#define APR_USE_READDIR64_R +#endif + +struct apr_dir_t { + apr_pool_t *pool; + char *dirname; + DIR *dirstruct; +#ifdef APR_USE_READDIR64_R + struct dirent64 *entry; +#else + struct dirent *entry; +#endif +}; + +apr_status_t apr_unix_file_cleanup(void *); +apr_status_t apr_unix_child_file_cleanup(void *); + +mode_t apr_unix_perms2mode(apr_fileperms_t perms); +apr_fileperms_t apr_unix_mode2perms(mode_t mode); + +apr_status_t apr_file_flush_locked(apr_file_t *thefile); +apr_status_t apr_file_info_get_locked(apr_finfo_t *finfo, apr_int32_t wanted, + apr_file_t *thefile); + + +#endif /* ! FILE_IO_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_global_mutex.h b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_global_mutex.h new file mode 100644 index 00000000..3add9ecf --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_global_mutex.h @@ -0,0 +1,37 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GLOBAL_MUTEX_H +#define GLOBAL_MUTEX_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_global_mutex.h" +#include "apr_arch_proc_mutex.h" +#include "apr_arch_thread_mutex.h" + +struct apr_global_mutex_t { + apr_pool_t *pool; + apr_proc_mutex_t *proc_mutex; +#if APR_HAS_THREADS + apr_thread_mutex_t *thread_mutex; +#endif /* APR_HAS_THREADS */ +}; + +#endif /* GLOBAL_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_inherit.h b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_inherit.h new file mode 100644 index 00000000..21543c1e --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_inherit.h @@ -0,0 +1,64 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INHERIT_H +#define INHERIT_H + +#include "apr_inherit.h" + +#define APR_INHERIT (1 << 24) /* Must not conflict with other bits */ + +#define APR_IMPLEMENT_INHERIT_SET(name, flag, pool, cleanup) \ +apr_status_t apr_##name##_inherit_set(apr_##name##_t *the##name) \ +{ \ + if (the##name->flag & APR_FOPEN_NOCLEANUP) \ + return APR_EINVAL; \ + if (!(the##name->flag & APR_INHERIT)) { \ + int flags = fcntl(the##name->name##des, F_GETFD); \ + if (flags == -1) \ + return errno; \ + flags &= ~(FD_CLOEXEC); \ + if (fcntl(the##name->name##des, F_SETFD, flags) == -1) \ + return errno; \ + the##name->flag |= APR_INHERIT; \ + apr_pool_child_cleanup_set(the##name->pool, \ + (void *)the##name, \ + cleanup, apr_pool_cleanup_null); \ + } \ + return APR_SUCCESS; \ +} + +#define APR_IMPLEMENT_INHERIT_UNSET(name, flag, pool, cleanup) \ +apr_status_t apr_##name##_inherit_unset(apr_##name##_t *the##name) \ +{ \ + if (the##name->flag & APR_FOPEN_NOCLEANUP) \ + return APR_EINVAL; \ + if (the##name->flag & APR_INHERIT) { \ + int flags; \ + if ((flags = fcntl(the##name->name##des, F_GETFD)) == -1) \ + return errno; \ + flags |= FD_CLOEXEC; \ + if (fcntl(the##name->name##des, F_SETFD, flags) == -1) \ + return errno; \ + the##name->flag &= ~APR_INHERIT; \ + apr_pool_child_cleanup_set(the##name->pool, \ + (void *)the##name, \ + cleanup, cleanup); \ + } \ + return APR_SUCCESS; \ +} + +#endif /* ! INHERIT_H */ diff --git a/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_internal_time.h b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_internal_time.h new file mode 100644 index 00000000..6e12c674 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_internal_time.h @@ -0,0 +1,24 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIME_INTERNAL_H +#define TIME_INTERNAL_H + +#include "apr.h" + +void apr_unix_setup_time(void); + +#endif /* TIME_INTERNAL_H */ diff --git a/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_misc.h b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_misc.h new file mode 100644 index 00000000..82351250 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_misc.h @@ -0,0 +1,67 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MISC_H +#define MISC_H + +#include "apr.h" +#include "apr_portable.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_getopt.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" +#include "apr_errno.h" +#include "apr_getopt.h" + +#if APR_HAVE_STDIO_H +#include +#endif +#if APR_HAVE_SIGNAL_H +#include +#endif +#if APR_HAVE_PTHREAD_H +#include +#endif + +#if APR_HAVE_STDLIB_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif + +#ifdef BEOS +#include +#endif + +struct apr_other_child_rec_t { + apr_pool_t *p; + struct apr_other_child_rec_t *next; + apr_proc_t *proc; + void (*maintenance) (int, void *, int); + void *data; + apr_os_file_t write_fd; +}; + +#if defined(WIN32) || defined(NETWARE) +#define WSAHighByte 2 +#define WSALowByte 0 +#endif + +#endif /* ! MISC_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_networkio.h b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_networkio.h new file mode 100644 index 00000000..5f3189d9 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_networkio.h @@ -0,0 +1,145 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETWORK_IO_H +#define NETWORK_IO_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_network_io.h" +#include "apr_errno.h" +#include "apr_general.h" +#include "apr_lib.h" +#ifndef WAITIO_USES_POLL +#include "apr_poll.h" +#endif + +/* System headers the network I/O library needs */ +#if APR_HAVE_SYS_TYPES_H +#include +#endif +#if APR_HAVE_SYS_UIO_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#endif +#if APR_HAVE_ERRNO_H +#include +#endif +#if APR_HAVE_SYS_TIME_H +#include +#endif +#if APR_HAVE_UNISTD_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#if APR_HAVE_NETINET_TCP_H +#include +#endif +#if APR_HAVE_NETINET_SCTP_UIO_H +#include +#endif +#if APR_HAVE_NETINET_SCTP_H +#include +#endif +#if APR_HAVE_NETINET_IN_H +#include +#endif +#if APR_HAVE_ARPA_INET_H +#include +#endif +#if APR_HAVE_SYS_SOCKET_H +#include +#endif +#if APR_HAVE_SYS_SOCKIO_H +#include +#endif +#if APR_HAVE_NETDB_H +#include +#endif +#if APR_HAVE_FCNTL_H +#include +#endif +#if APR_HAVE_SYS_SENDFILE_H +#include +#endif +#if APR_HAVE_SYS_IOCTL_H +#include +#endif +/* End System Headers */ + +#ifndef HAVE_POLLIN +#define POLLIN 1 +#define POLLPRI 2 +#define POLLOUT 4 +#define POLLERR 8 +#define POLLHUP 16 +#define POLLNVAL 32 +#endif + +typedef struct sock_userdata_t sock_userdata_t; +struct sock_userdata_t { + sock_userdata_t *next; + const char *key; + void *data; +}; + +struct apr_socket_t { + apr_pool_t *pool; + int socketdes; + int type; + int protocol; + apr_sockaddr_t *local_addr; + apr_sockaddr_t *remote_addr; + apr_interval_time_t timeout; +#ifndef HAVE_POLL + int connected; +#endif +#if APR_HAVE_SOCKADDR_UN + int bound; +#endif + int local_port_unknown; + int local_interface_unknown; + int remote_addr_unknown; + apr_int32_t options; + apr_int32_t inherit; + sock_userdata_t *userdata; +#ifndef WAITIO_USES_POLL + /* if there is a timeout set, then this pollset is used */ + apr_pollset_t *pollset; +#endif +}; + +const char *apr_inet_ntop(int af, const void *src, char *dst, apr_size_t size); +int apr_inet_pton(int af, const char *src, void *dst); +void apr_sockaddr_vars_set(apr_sockaddr_t *, int, apr_port_t); + +#define apr_is_option_set(skt, option) \ + (((skt)->options & (option)) == (option)) + +#define apr_set_option(skt, option, on) \ + do { \ + if (on) \ + (skt)->options |= (option); \ + else \ + (skt)->options &= ~(option); \ + } while (0) + +#endif /* ! NETWORK_IO_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_poll_private.h b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_poll_private.h new file mode 100644 index 00000000..ff813123 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_poll_private.h @@ -0,0 +1,189 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ARCH_POLL_PRIVATE_H +#define APR_ARCH_POLL_PRIVATE_H + +#if HAVE_POLL_H +#include +#endif + +#if HAVE_SYS_POLL_H +#include +#endif + +#ifdef HAVE_PORT_CREATE +#include +#include +#endif + +#ifdef HAVE_KQUEUE +#include +#include +#include +#endif + +#ifdef HAVE_EPOLL +#include +#endif + +#ifdef NETWARE +#define HAS_SOCKETS(dt) (dt == APR_POLL_SOCKET) ? 1 : 0 +#define HAS_PIPES(dt) (dt == APR_POLL_FILE) ? 1 : 0 +#endif + +#if defined(HAVE_AIO_H) && defined(HAVE_AIO_MSGQ) +#define _AIO_OS390 /* enable a bunch of z/OS aio.h definitions */ +#include /* aiocb */ +#endif + +/* Choose the best method platform specific to use in apr_pollset */ +#ifdef HAVE_KQUEUE +#define POLLSET_USES_KQUEUE +#define POLLSET_DEFAULT_METHOD APR_POLLSET_KQUEUE +#elif defined(HAVE_PORT_CREATE) +#define POLLSET_USES_PORT +#define POLLSET_DEFAULT_METHOD APR_POLLSET_PORT +#elif defined(HAVE_EPOLL) +#define POLLSET_USES_EPOLL +#define POLLSET_DEFAULT_METHOD APR_POLLSET_EPOLL +#elif defined(HAVE_AIO_MSGQ) +#define POLLSET_USES_AIO_MSGQ +#define POLLSET_DEFAULT_METHOD APR_POLLSET_AIO_MSGQ +#elif defined(HAVE_POLL) +#define POLLSET_USES_POLL +#define POLLSET_DEFAULT_METHOD APR_POLLSET_POLL +#else +#define POLLSET_USES_SELECT +#define POLLSET_DEFAULT_METHOD APR_POLLSET_SELECT +#endif + +#ifdef WIN32 +#define POLL_USES_SELECT +#undef POLLSET_DEFAULT_METHOD +#define POLLSET_DEFAULT_METHOD APR_POLLSET_SELECT +#else +#ifdef HAVE_POLL +#define POLL_USES_POLL +#else +#define POLL_USES_SELECT +#endif +#endif + +#if defined(POLLSET_USES_KQUEUE) || defined(POLLSET_USES_EPOLL) || defined(POLLSET_USES_PORT) || defined(POLLSET_USES_AIO_MSGQ) + +#include "apr_ring.h" + +#if APR_HAS_THREADS +#include "apr_thread_mutex.h" +#define pollset_lock_rings() \ + if (pollset->flags & APR_POLLSET_THREADSAFE) \ + apr_thread_mutex_lock(pollset->p->ring_lock); +#define pollset_unlock_rings() \ + if (pollset->flags & APR_POLLSET_THREADSAFE) \ + apr_thread_mutex_unlock(pollset->p->ring_lock); +#else +#define pollset_lock_rings() +#define pollset_unlock_rings() +#endif + +typedef struct pfd_elem_t pfd_elem_t; + +struct pfd_elem_t { + APR_RING_ENTRY(pfd_elem_t) link; + apr_pollfd_t pfd; +#ifdef HAVE_PORT_CREATE + int on_query_ring; +#endif +}; + +#endif + +typedef struct apr_pollset_private_t apr_pollset_private_t; +typedef struct apr_pollset_provider_t apr_pollset_provider_t; +typedef struct apr_pollcb_provider_t apr_pollcb_provider_t; + +struct apr_pollset_t +{ + apr_pool_t *pool; + apr_uint32_t nelts; + apr_uint32_t nalloc; + apr_uint32_t flags; + /* Pipe descriptors used for wakeup */ + apr_file_t *wakeup_pipe[2]; + apr_pollfd_t wakeup_pfd; + apr_pollset_private_t *p; + const apr_pollset_provider_t *provider; +}; + +typedef union { +#if defined(HAVE_EPOLL) + struct epoll_event *epoll; +#endif +#if defined(HAVE_PORT_CREATE) + port_event_t *port; +#endif +#if defined(HAVE_KQUEUE) + struct kevent *ke; +#endif +#if defined(HAVE_POLL) + struct pollfd *ps; +#endif + void *undef; +} apr_pollcb_pset; + +struct apr_pollcb_t { + apr_pool_t *pool; + apr_uint32_t nelts; + apr_uint32_t nalloc; + apr_uint32_t flags; + /* Pipe descriptors used for wakeup */ + apr_file_t *wakeup_pipe[2]; + apr_pollfd_t wakeup_pfd; + int fd; + apr_pollcb_pset pollset; + apr_pollfd_t **copyset; + const apr_pollcb_provider_t *provider; +}; + +struct apr_pollset_provider_t { + apr_status_t (*create)(apr_pollset_t *, apr_uint32_t, apr_pool_t *, apr_uint32_t); + apr_status_t (*add)(apr_pollset_t *, const apr_pollfd_t *); + apr_status_t (*remove)(apr_pollset_t *, const apr_pollfd_t *); + apr_status_t (*poll)(apr_pollset_t *, apr_interval_time_t, apr_int32_t *, const apr_pollfd_t **); + apr_status_t (*cleanup)(apr_pollset_t *); + const char *name; +}; + +struct apr_pollcb_provider_t { + apr_status_t (*create)(apr_pollcb_t *, apr_uint32_t, apr_pool_t *, apr_uint32_t); + apr_status_t (*add)(apr_pollcb_t *, apr_pollfd_t *); + apr_status_t (*remove)(apr_pollcb_t *, apr_pollfd_t *); + apr_status_t (*poll)(apr_pollcb_t *, apr_interval_time_t, apr_pollcb_cb_t, void *); + apr_status_t (*cleanup)(apr_pollcb_t *); + const char *name; +}; + +/* + * Private functions used for the implementation of both apr_pollcb_* and + * apr_pollset_* + */ +apr_status_t apr_poll_create_wakeup_pipe(apr_pool_t *pool, apr_pollfd_t *pfd, + apr_file_t **wakeup_pipe); +apr_status_t apr_poll_close_wakeup_pipe(apr_file_t **wakeup_pipe); +void apr_poll_drain_wakeup_pipe(apr_file_t **wakeup_pipe); + +#endif /* APR_ARCH_POLL_PRIVATE_H */ diff --git a/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_proc_mutex.h b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_proc_mutex.h new file mode 100644 index 00000000..cfa0049f --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_proc_mutex.h @@ -0,0 +1,121 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PROC_MUTEX_H +#define PROC_MUTEX_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_proc_mutex.h" +#include "apr_pools.h" +#include "apr_portable.h" +#include "apr_file_io.h" +#include "apr_arch_file_io.h" +#include "apr_time.h" + +/* System headers required by Locks library */ +#if APR_HAVE_SYS_TYPES_H +#include +#endif +#if APR_HAVE_STDIO_H +#include +#endif +#if APR_HAVE_FCNTL_H +#include +#endif + +#ifdef HAVE_SYS_IPC_H +#include +#endif +#ifdef HAVE_SYS_SEM_H +#include +#endif +#ifdef HAVE_SYS_FILE_H +#include +#endif +#if APR_HAVE_STDLIB_H +#include +#endif +#if APR_HAVE_UNISTD_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#ifdef HAVE_SYS_MMAN_H +#include +#endif +#if APR_HAVE_PTHREAD_H +#include +#endif +/* End System Headers */ + +struct apr_proc_mutex_unix_lock_methods_t { + unsigned int flags; + apr_status_t (*create)(apr_proc_mutex_t *, const char *); + apr_status_t (*acquire)(apr_proc_mutex_t *); + apr_status_t (*tryacquire)(apr_proc_mutex_t *); + apr_status_t (*timedacquire)(apr_proc_mutex_t *, apr_interval_time_t); + apr_status_t (*release)(apr_proc_mutex_t *); + apr_status_t (*cleanup)(void *); + apr_status_t (*child_init)(apr_proc_mutex_t **, apr_pool_t *, const char *); + apr_status_t (*perms_set)(apr_proc_mutex_t *, apr_fileperms_t, apr_uid_t, apr_gid_t); + apr_lockmech_e mech; + const char *name; +}; +typedef struct apr_proc_mutex_unix_lock_methods_t apr_proc_mutex_unix_lock_methods_t; + +/* bit values for flags field in apr_unix_lock_methods_t */ +#define APR_PROCESS_LOCK_MECH_IS_GLOBAL 1 + +#if !APR_HAVE_UNION_SEMUN && defined(APR_HAS_SYSVSEM_SERIALIZE) +union semun { + int val; + struct semid_ds *buf; + unsigned short *array; +}; +#endif + +struct apr_proc_mutex_t { + apr_pool_t *pool; + const apr_proc_mutex_unix_lock_methods_t *meth; + int curr_locked; + char *fname; + + apr_os_proc_mutex_t os; /* Native mutex holder. */ + +#if APR_HAS_FCNTL_SERIALIZE || APR_HAS_FLOCK_SERIALIZE + apr_file_t *interproc; /* For apr_file_ calls on native fd. */ + int interproc_closing; /* whether the native fd is opened/closed with + * 'interproc' or apr_os_file_put()ed (hence + * needing an an explicit close for consistency + * with other methods). + */ +#endif +#if APR_HAS_PROC_PTHREAD_SERIALIZE + int pthread_refcounting; /* Whether the native mutex is refcounted or + * apr_os_proc_mutex_put()ed, which makes + * refcounting impossible/undesirable. + */ +#endif +}; + +void apr_proc_mutex_unix_setup_lock(void); + +#endif /* PROC_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_shm.h b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_shm.h new file mode 100644 index 00000000..e9d25cad --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_shm.h @@ -0,0 +1,74 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SHM_H +#define SHM_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_shm.h" +#include "apr_pools.h" +#include "apr_file_io.h" +#include "apr_network_io.h" +#include "apr_portable.h" + +#if APR_HAVE_UNISTD_H +#include +#endif +#ifdef HAVE_SYS_MMAN_H +#include +#endif +#ifdef HAVE_SYS_IPC_H +#include +#endif +#ifdef HAVE_SYS_MUTEX_H +#include +#endif +#ifdef HAVE_SYS_SHM_H +#include +#endif +#if !defined(SHM_R) +#define SHM_R 0400 +#endif +#if !defined(SHM_W) +#define SHM_W 0200 +#endif +#ifdef HAVE_SYS_FILE_H +#include +#endif + +/* Not all systems seem to have MAP_FAILED defined, but it should always + * just be (void *)-1. */ +#ifndef MAP_FAILED +#define MAP_FAILED ((void *)-1) +#endif + +struct apr_shm_t { + apr_pool_t *pool; + void *base; /* base real address */ + void *usable; /* base usable address */ + apr_size_t reqsize; /* requested segment size */ + apr_size_t realsize; /* actual segment size */ + const char *filename; /* NULL if anonymous */ +#if APR_USE_SHMEM_SHMGET || APR_USE_SHMEM_SHMGET_ANON + int shmid; /* shmem ID returned from shmget() */ + key_t shmkey; /* shmem key IPC_ANON or returned from ftok() */ +#endif +}; + +#endif /* SHM_H */ diff --git a/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_thread_cond.h b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_thread_cond.h new file mode 100644 index 00000000..5c2b51d1 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_thread_cond.h @@ -0,0 +1,42 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_COND_H +#define THREAD_COND_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_thread_mutex.h" +#include "apr_thread_cond.h" +#include "apr_pools.h" + +#if APR_HAVE_PTHREAD_H +#include +#endif + +/* XXX: Should we have a better autoconf search, something like + * APR_HAS_PTHREAD_COND? -aaron */ +#if APR_HAS_THREADS +struct apr_thread_cond_t { + apr_pool_t *pool; + pthread_cond_t cond; +}; +#endif + +#endif /* THREAD_COND_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_thread_mutex.h b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_thread_mutex.h new file mode 100644 index 00000000..4fe46c3b --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_thread_mutex.h @@ -0,0 +1,42 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_MUTEX_H +#define THREAD_MUTEX_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_thread_mutex.h" +#include "apr_thread_cond.h" +#include "apr_portable.h" +#include "apr_atomic.h" + +#if APR_HAVE_PTHREAD_H +#include +#endif + +#if APR_HAS_THREADS +struct apr_thread_mutex_t { + apr_pool_t *pool; + pthread_mutex_t mutex; + apr_thread_cond_t *cond; + int locked, num_waiters; +}; +#endif + +#endif /* THREAD_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_thread_rwlock.h b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_thread_rwlock.h new file mode 100644 index 00000000..2cb43af6 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_thread_rwlock.h @@ -0,0 +1,49 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_RWLOCK_H +#define THREAD_RWLOCK_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_thread_rwlock.h" +#include "apr_pools.h" + +#if APR_HAVE_PTHREAD_H +/* this gives us pthread_rwlock_t */ +#include +#endif + +#if APR_HAS_THREADS +#ifdef HAVE_PTHREAD_RWLOCKS + +struct apr_thread_rwlock_t { + apr_pool_t *pool; + pthread_rwlock_t rwlock; +}; + +#else + +struct apr_thread_rwlock_t { + apr_pool_t *pool; +}; +#endif + +#endif + +#endif /* THREAD_RWLOCK_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_threadproc.h b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_threadproc.h new file mode 100644 index 00000000..7a3b3c09 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/unix/apr_arch_threadproc.h @@ -0,0 +1,119 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr.h" +#include "apr_private.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" +#include "apr_arch_file_io.h" +#include "apr_perms_set.h" + +/* System headers required for thread/process library */ +#if APR_HAVE_PTHREAD_H +#include +#endif +#ifdef HAVE_SYS_RESOURCE_H +#include +#endif +#if APR_HAVE_SIGNAL_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#if APR_HAVE_SYS_WAIT_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#ifdef HAVE_SCHED_H +#include +#endif +/* End System Headers */ + + +#ifndef THREAD_PROC_H +#define THREAD_PROC_H + +#define SHELL_PATH "/bin/sh" + +#if APR_HAS_THREADS + +struct apr_thread_t { + apr_pool_t *pool; + pthread_t *td; + void *data; + apr_thread_start_t func; + apr_status_t exitval; +}; + +struct apr_threadattr_t { + apr_pool_t *pool; + pthread_attr_t attr; +}; + +struct apr_threadkey_t { + apr_pool_t *pool; + pthread_key_t key; +}; + +struct apr_thread_once_t { + pthread_once_t once; +}; + +#endif + +typedef struct apr_procattr_pscb_t apr_procattr_pscb_t; +struct apr_procattr_pscb_t { + struct apr_procattr_pscb_t *next; + apr_perms_setfn_t *perms_set_fn; + apr_fileperms_t perms; + const void *data; +}; + +struct apr_procattr_t { + apr_pool_t *pool; + apr_file_t *parent_in; + apr_file_t *child_in; + apr_file_t *parent_out; + apr_file_t *child_out; + apr_file_t *parent_err; + apr_file_t *child_err; + char *currdir; + apr_int32_t cmdtype; + apr_int32_t detached; +#ifdef RLIMIT_CPU + struct rlimit *limit_cpu; +#endif +#if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS) + struct rlimit *limit_mem; +#endif +#ifdef RLIMIT_NPROC + struct rlimit *limit_nproc; +#endif +#ifdef RLIMIT_NOFILE + struct rlimit *limit_nofile; +#endif + apr_child_errfn_t *errfn; + apr_int32_t errchk; + apr_uid_t uid; + apr_gid_t gid; + apr_procattr_pscb_t *perms_set_callbacks; +}; + +#endif /* ! THREAD_PROC_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_atime.h b/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_atime.h new file mode 100644 index 00000000..35f2041a --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_atime.h @@ -0,0 +1,63 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ATIME_H +#define ATIME_H + +#include "apr_private.h" +#include "apr_time.h" +#if APR_HAVE_TIME_H +#include +#endif + +struct atime_t { + apr_pool_t *cntxt; + apr_time_t currtime; + SYSTEMTIME *explodedtime; +}; + + +/* Number of micro-seconds between the beginning of the Windows epoch + * (Jan. 1, 1601) and the Unix epoch (Jan. 1, 1970) + */ +#define APR_DELTA_EPOCH_IN_USEC APR_TIME_C(11644473600000000); + + +static APR_INLINE void FileTimeToAprTime(apr_time_t *result, FILETIME *input) +{ + /* Convert FILETIME one 64 bit number so we can work with it. */ + *result = input->dwHighDateTime; + *result = (*result) << 32; + *result |= input->dwLowDateTime; + *result /= 10; /* Convert from 100 nano-sec periods to micro-seconds. */ + *result -= APR_DELTA_EPOCH_IN_USEC; /* Convert from Windows epoch to Unix epoch */ + return; +} + + +static APR_INLINE void AprTimeToFileTime(LPFILETIME pft, apr_time_t t) +{ + LONGLONG ll; + t += APR_DELTA_EPOCH_IN_USEC; + ll = t * 10; + pft->dwLowDateTime = (DWORD)ll; + pft->dwHighDateTime = (DWORD) (ll >> 32); + return; +} + + +#endif /* ! ATIME_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_dso.h b/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_dso.h new file mode 100644 index 00000000..e2e4e40f --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_dso.h @@ -0,0 +1,36 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_dso.h" +#include "apr.h" + +#if APR_HAS_DSO + +struct apr_dso_handle_t { + apr_pool_t *cont; + void *handle; + apr_status_t load_error; +}; + +#endif + +#endif diff --git a/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_file_io.h b/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_file_io.h new file mode 100644 index 00000000..9fb8df19 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_file_io.h @@ -0,0 +1,266 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FILE_IO_H +#define FILE_IO_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_pools.h" +#include "apr_general.h" +#include "apr_tables.h" +#include "apr_thread_mutex.h" +#include "apr_file_io.h" +#include "apr_file_info.h" +#include "apr_errno.h" +#include "apr_arch_misc.h" +#include "apr_poll.h" + +#ifdef HAVE_SYS_STAT_H +#include +#endif +#if APR_HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_FCNTL_H +#include +#endif +#ifdef HAVE_TIME_H +#include +#endif +#if APR_HAVE_DIRENT_H +#include +#endif +#ifdef HAVE_MALLOC_H +#include +#endif + +#if APR_HAS_UNICODE_FS +#include "arch/win32/apr_arch_utf8.h" +#include + +/* Helper functions for the WinNT ApiW() functions. APR treats all + * resource identifiers (files, etc) by their UTF-8 name, to provide + * access to all named identifiers. [UTF-8 completely maps Unicode + * into char type strings.] + * + * The _path flavors below provide us fast mappings of the + * Unicode filename //?/D:/path and //?/UNC/mach/share/path mappings, + * which allow unlimited (well, 32000 wide character) length names. + * These prefixes may appear in Unicode, but must not appear in the + * Ascii API calls. So we tack them on in utf8_to_unicode_path, and + * strip them right back off in unicode_to_utf8_path. + */ +apr_status_t utf8_to_unicode_path(apr_wchar_t* dststr, apr_size_t dstchars, + const char* srcstr); +apr_status_t unicode_to_utf8_path(char* dststr, apr_size_t dstchars, + const apr_wchar_t* srcstr); + +#endif /* APR_HAS_UNICODE_FS */ + +/* Another Helper functions for the WinNT ApiW() functions. We need to + * derive some 'resource' names (max length 255 characters, prefixed with + * Global/ or Local/ on WinNT) from something that looks like a filename. + * Since 'resource' names never contain slashes, convert these to '_'s + * and return the appropriate char* or wchar* for ApiA or ApiW calls. + */ + +void *res_name_from_filename(const char *file, int global, apr_pool_t *pool); + +#define APR_FILE_MAX MAX_PATH + +#define APR_FILE_DEFAULT_BUFSIZE 4096 +/* For backwards-compat */ +#define APR_FILE_BUFSIZE APR_FILE_DEFAULT_BUFSIZE + +/* obscure ommissions from msvc's sys/stat.h */ +#ifdef _MSC_VER +#define S_IFIFO _S_IFIFO /* pipe */ +#define S_IFBLK 0060000 /* Block Special */ +#define S_IFLNK 0120000 /* Symbolic Link */ +#define S_IFSOCK 0140000 /* Socket */ +#define S_IFWHT 0160000 /* Whiteout */ +#endif + +/* Internal Flags for apr_file_open */ +#define APR_OPENINFO 0x00100000 /* Open without READ or WRITE access */ +#define APR_OPENLINK 0x00200000 /* Open a link itself, if supported */ +#define APR_READCONTROL 0x00400000 /* Read the file's owner/perms */ +#define APR_WRITECONTROL 0x00800000 /* Modify the file's owner/perms */ +/* #define APR_INHERIT 0x01000000 -- Defined in apr_arch_inherit.h! */ +#define APR_STDIN_FLAG 0x02000000 /* Obtained via apr_file_open_stdin() */ +#define APR_STDOUT_FLAG 0x04000000 /* Obtained via apr_file_open_stdout() */ +#define APR_STDERR_FLAG 0x06000000 /* Obtained via apr_file_open_stderr() */ +#define APR_STD_FLAGS (APR_STDIN_FLAG | APR_STDOUT_FLAG | APR_STDERR_FLAG) +#define APR_WRITEATTRS 0x08000000 /* Modify the file's attributes */ + +/* Entries missing from the MSVC 5.0 Win32 SDK: + */ +#ifndef FILE_ATTRIBUTE_DEVICE +#define FILE_ATTRIBUTE_DEVICE 0x00000040 +#endif +#ifndef FILE_ATTRIBUTE_REPARSE_POINT +#define FILE_ATTRIBUTE_REPARSE_POINT 0x00000400 +#endif +#ifndef FILE_FLAG_OPEN_NO_RECALL +#define FILE_FLAG_OPEN_NO_RECALL 0x00100000 +#endif +#ifndef FILE_FLAG_OPEN_REPARSE_POINT +#define FILE_FLAG_OPEN_REPARSE_POINT 0x00200000 +#endif +#ifndef TRUSTEE_IS_WELL_KNOWN_GROUP +#define TRUSTEE_IS_WELL_KNOWN_GROUP 5 +#endif + +/* Information bits available from the WIN32 FindFirstFile function */ +#define APR_FINFO_WIN32_DIR (APR_FINFO_NAME | APR_FINFO_TYPE \ + | APR_FINFO_CTIME | APR_FINFO_ATIME \ + | APR_FINFO_MTIME | APR_FINFO_SIZE) + +/* Sneak the Readonly bit through finfo->protection for internal use _only_ */ +#define APR_FREADONLY 0x10000000 + +/* Private function for apr_stat/lstat/getfileinfo/dir_read */ +int fillin_fileinfo(apr_finfo_t *finfo, WIN32_FILE_ATTRIBUTE_DATA *wininfo, + int byhandle, int finddata, const char *fname, + apr_int32_t wanted); + +/* Private function that extends apr_stat/lstat/getfileinfo/dir_read */ +apr_status_t more_finfo(apr_finfo_t *finfo, const void *ufile, + apr_int32_t wanted, int whatfile); + +/* whatfile types for the ufile arg */ +#define MORE_OF_HANDLE 0 +#define MORE_OF_FSPEC 1 +#define MORE_OF_WFSPEC 2 + +/* quick run-down of fields in windows' apr_file_t structure that may have + * obvious uses. + * fname -- the filename as passed to the open call. + * dwFileAttricutes -- Attributes used to open the file. + * append -- Windows doesn't support the append concept when opening files. + * APR needs to keep track of this, and always make sure we append + * correctly when writing to a file with this flag set TRUE. + */ + +/* for apr_poll.c */ +#define filedes filehand + +struct apr_file_t { + apr_pool_t *pool; + HANDLE filehand; + BOOLEAN pipe; /* Is this a pipe of a file? */ + OVERLAPPED *pOverlapped; + apr_interval_time_t timeout; + apr_int32_t flags; + + /* File specific info */ + apr_finfo_t *finfo; + char *fname; + DWORD dwFileAttributes; + int eof_hit; + BOOLEAN buffered; /* Use buffered I/O? */ + int ungetchar; /* Last char provided by an unget op. (-1 = no char) */ + int append; + + /* Stuff for buffered mode */ + char *buffer; + apr_size_t bufpos; /* Read/Write position in buffer */ + apr_size_t bufsize; /* The size of the buffer */ + apr_size_t dataRead; /* amount of valid data read into buffer */ + int direction; /* buffer being used for 0 = read, 1 = write */ + apr_off_t filePtr; /* position in file of handle */ + apr_thread_mutex_t *mutex; /* mutex semaphore, must be owned to access + * the above fields */ + +#if APR_FILES_AS_SOCKETS + /* if there is a timeout set, then this pollset is used */ + apr_pollset_t *pollset; +#endif + /* Pipe specific info */ +}; + +struct apr_dir_t { + apr_pool_t *pool; + HANDLE dirhand; + apr_size_t rootlen; + char *dirname; + char *name; + union { +#if APR_HAS_UNICODE_FS + struct { + WIN32_FIND_DATAW *entry; + } w; +#endif +#if APR_HAS_ANSI_FS + struct { + WIN32_FIND_DATAA *entry; + } n; +#endif + }; + int bof; +}; + +/* There are many goofy characters the filesystem can't accept + * or can confound the cmd.exe shell. Here's the list + * [declared in filesys.c] + */ +extern const char apr_c_is_fnchar[256]; + +#define IS_FNCHAR(c) (apr_c_is_fnchar[(unsigned char)(c)] & 1) +#define IS_SHCHAR(c) ((apr_c_is_fnchar[(unsigned char)(c)] & 2) == 2) + + +/* If the user passes APR_FILEPATH_TRUENAME to either + * apr_filepath_root or apr_filepath_merge, this fn determines + * that the root really exists. It's expensive, wouldn't want + * to do this too frequenly. + */ +apr_status_t filepath_root_test(char *path, apr_pool_t *p); + + +/* The apr_filepath_merge wants to canonicalize the cwd to the + * addpath if the user passes NULL as the old root path (this + * isn't true of an empty string "", which won't be concatenated. + * + * But we need to figure out what the cwd of a given volume is, + * when the user passes D:foo. This fn will determine D:'s cwd. + * + * If flags includes the bit APR_FILEPATH_NATIVE, the path returned + * is in the os-native format. + */ +apr_status_t filepath_drive_get(char **rootpath, char drive, + apr_int32_t flags, apr_pool_t *p); + + +/* If the user passes d: vs. D: (or //mach/share vs. //MACH/SHARE), + * we need to fold the case to canonical form. This function is + * supposed to do so. + */ +apr_status_t filepath_root_case(char **rootpath, char *root, apr_pool_t *p); + + +apr_status_t file_cleanup(void *); + +extern apr_status_t +apr_file_socket_pipe_create(apr_file_t **in, + apr_file_t **out, + apr_pool_t *p); + +extern apr_status_t +apr_file_socket_pipe_close(apr_file_t *file); + +#endif /* ! FILE_IO_H */ diff --git a/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_inherit.h b/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_inherit.h new file mode 100644 index 00000000..8969af66 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_inherit.h @@ -0,0 +1,123 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INHERIT_H +#define INHERIT_H + +#include "apr_inherit.h" + +#define APR_INHERIT (1 << 24) /* Must not conflict with other bits */ + +#if APR_HAS_UNICODE_FS && APR_HAS_ANSI_FS +/* !defined(_WIN32_WCE) is implicit here */ + +#define APR_IMPLEMENT_INHERIT_SET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_set(apr_##name##_t *the##name) \ +{ \ + IF_WIN_OS_IS_UNICODE \ + { \ +/* if (!SetHandleInformation(the##name->filehand, \ + * HANDLE_FLAG_INHERIT, \ + * HANDLE_FLAG_INHERIT)) \ + * return apr_get_os_error(); \ + */ } \ + ELSE_WIN_OS_IS_ANSI \ + { \ + HANDLE temp, hproc = GetCurrentProcess(); \ + if (!DuplicateHandle(hproc, the##name->filehand, \ + hproc, &temp, 0, TRUE, \ + DUPLICATE_SAME_ACCESS)) \ + return apr_get_os_error(); \ + CloseHandle(the##name->filehand); \ + the##name->filehand = temp; \ + } \ + return APR_SUCCESS; \ +} + +#define APR_IMPLEMENT_INHERIT_UNSET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_unset(apr_##name##_t *the##name)\ +{ \ + IF_WIN_OS_IS_UNICODE \ + { \ +/* if (!SetHandleInformation(the##name->filehand, \ + * HANDLE_FLAG_INHERIT, 0)) \ + * return apr_get_os_error(); \ + */ } \ + ELSE_WIN_OS_IS_ANSI \ + { \ + HANDLE temp, hproc = GetCurrentProcess(); \ + if (!DuplicateHandle(hproc, the##name->filehand, \ + hproc, &temp, 0, FALSE, \ + DUPLICATE_SAME_ACCESS)) \ + return apr_get_os_error(); \ + CloseHandle(the##name->filehand); \ + the##name->filehand = temp; \ + } \ + return APR_SUCCESS; \ +} + +#elif APR_HAS_ANSI_FS || defined(_WIN32_WCE) + +#define APR_IMPLEMENT_INHERIT_SET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_set(apr_##name##_t *the##name) \ +{ \ + HANDLE temp, hproc = GetCurrentProcess(); \ + if (!DuplicateHandle(hproc, the##name->filehand, \ + hproc, &temp, 0, TRUE, \ + DUPLICATE_SAME_ACCESS)) \ + return apr_get_os_error(); \ + CloseHandle(the##name->filehand); \ + the##name->filehand = temp; \ + return APR_SUCCESS; \ +} + +#define APR_IMPLEMENT_INHERIT_UNSET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_unset(apr_##name##_t *the##name)\ +{ \ + HANDLE temp, hproc = GetCurrentProcess(); \ + if (!DuplicateHandle(hproc, the##name->filehand, \ + hproc, &temp, 0, FALSE, \ + DUPLICATE_SAME_ACCESS)) \ + return apr_get_os_error(); \ + CloseHandle(the##name->filehand); \ + the##name->filehand = temp; \ + return APR_SUCCESS; \ +} + +#else /* APR_HAS_UNICODE_FS && !APR_HAS_ANSI_FS && !defined(_WIN32_WCE) */ + +#define APR_IMPLEMENT_INHERIT_SET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_set(apr_##name##_t *the##name) \ +{ \ +/* if (!SetHandleInformation(the##name->filehand, \ + * HANDLE_FLAG_INHERIT, \ + * HANDLE_FLAG_INHERIT)) \ + * return apr_get_os_error(); \ + */ return APR_SUCCESS; \ +} + +#define APR_IMPLEMENT_INHERIT_UNSET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_unset(apr_##name##_t *the##name)\ +{ \ +/* if (!SetHandleInformation(the##name->filehand, \ + * HANDLE_FLAG_INHERIT, 0)) \ + * return apr_get_os_error(); \ + */ return APR_SUCCESS; \ +} + +#endif /* defined(APR_HAS_UNICODE_FS) */ + +#endif /* ! INHERIT_H */ diff --git a/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_misc.h b/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_misc.h new file mode 100644 index 00000000..15312adf --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_misc.h @@ -0,0 +1,509 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MISC_H +#define MISC_H + +#include "apr.h" +#include "apr_portable.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_getopt.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" +#include "apr_errno.h" +#include "apr_getopt.h" + +#if APR_HAVE_STDIO_H +#include +#endif +#if APR_HAVE_SIGNAL_H +#include +#endif +#if APR_HAVE_PTHREAD_H +#include +#endif +#if APR_HAVE_STDLIB_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#ifndef _WIN32_WCE +#include +#endif + +#if defined(HAVE_IF_INDEXTONAME) && defined(_MSC_VER) +#include +#endif + +struct apr_other_child_rec_t { + apr_pool_t *p; + struct apr_other_child_rec_t *next; + apr_proc_t *proc; + void (*maintenance) (int, void *, int); + void *data; + apr_os_file_t write_fd; +}; + +#define WSAHighByte 2 +#define WSALowByte 0 + +/* start.c and apr_app.c helpers and communication within misc.c + * + * They are not for public consumption, although apr_app_init_complete + * must be an exported symbol to avoid reinitialization. + */ +extern int APR_DECLARE_DATA apr_app_init_complete; + +int apr_wastrtoastr(char const * const * *retarr, + wchar_t const * const *arr, int args); + +/* Platform specific designation of run time os version. + * Gaps allow for specific service pack levels that + * export new kernel or winsock functions or behavior. + */ +typedef enum { + APR_WIN_UNK = 0, + APR_WIN_UNSUP = 1, + APR_WIN_95 = 10, + APR_WIN_95_B = 11, + APR_WIN_95_OSR2 = 12, + APR_WIN_98 = 14, + APR_WIN_98_SE = 16, + APR_WIN_ME = 18, + + APR_WIN_UNICODE = 20, /* Prior versions support only narrow chars */ + + APR_WIN_CE_3 = 23, /* CE is an odd beast, not supporting */ + /* some pre-NT features, such as the */ + APR_WIN_NT = 30, /* narrow charset APIs (fooA fns), while */ + APR_WIN_NT_3_5 = 35, /* not supporting some NT-family features. */ + APR_WIN_NT_3_51 = 36, + + APR_WIN_NT_4 = 40, + APR_WIN_NT_4_SP2 = 42, + APR_WIN_NT_4_SP3 = 43, + APR_WIN_NT_4_SP4 = 44, + APR_WIN_NT_4_SP5 = 45, + APR_WIN_NT_4_SP6 = 46, + + APR_WIN_2000 = 50, + APR_WIN_2000_SP1 = 51, + APR_WIN_2000_SP2 = 52, + APR_WIN_XP = 60, + APR_WIN_XP_SP1 = 61, + APR_WIN_XP_SP2 = 62, + APR_WIN_2003 = 70, + APR_WIN_VISTA = 80, + APR_WIN_7 = 90 +} apr_oslevel_e; + +extern APR_DECLARE_DATA apr_oslevel_e apr_os_level; + +apr_status_t apr_get_oslevel(apr_oslevel_e *); + +/* The APR_HAS_ANSI_FS symbol is PRIVATE, and internal to APR. + * APR only supports char data for filenames. Like most applications, + * characters >127 are essentially undefined. APR_HAS_UNICODE_FS lets + * the application know that utf-8 is the encoding method of APR, and + * only incidently hints that we have Wide OS calls. + * + * APR_HAS_ANSI_FS is simply an OS flag to tell us all calls must be + * the unicode eqivilant. + */ + +#if defined(_WIN32_WCE) || defined(WINNT) +#define APR_HAS_ANSI_FS 0 +#else +#define APR_HAS_ANSI_FS 1 +#endif + +/* IF_WIN_OS_IS_UNICODE / ELSE_WIN_OS_IS_ANSI help us keep the code trivial + * where have runtime tests for unicode-ness, that aren't needed in any + * build which supports only WINNT or WCE. + */ +#if APR_HAS_ANSI_FS && APR_HAS_UNICODE_FS +#define IF_WIN_OS_IS_UNICODE if (apr_os_level >= APR_WIN_UNICODE) +#define ELSE_WIN_OS_IS_ANSI else +#else /* APR_HAS_UNICODE_FS */ +#define IF_WIN_OS_IS_UNICODE +#define ELSE_WIN_OS_IS_ANSI +#endif /* WINNT */ + +#if defined(_MSC_VER) && !defined(_WIN32_WCE) +#include "crtdbg.h" + +static APR_INLINE void* apr_malloc_dbg(size_t size, const char* filename, + int linenumber) +{ + return _malloc_dbg(size, _CRT_BLOCK, filename, linenumber); +} + +static APR_INLINE void* apr_realloc_dbg(void* userData, size_t newSize, + const char* filename, int linenumber) +{ + return _realloc_dbg(userData, newSize, _CRT_BLOCK, filename, linenumber); +} + +#else + +static APR_INLINE void* apr_malloc_dbg(size_t size, const char* filename, + int linenumber) +{ + return malloc(size); +} + +static APR_INLINE void* apr_realloc_dbg(void* userData, size_t newSize, + const char* filename, int linenumber) +{ + return realloc(userData, newSize); +} + +#endif /* ! _MSC_VER */ + +typedef enum { + DLL_WINBASEAPI = 0, /* kernel32 From WinBase.h */ + DLL_WINADVAPI = 1, /* advapi32 From WinBase.h */ + DLL_WINSOCKAPI = 2, /* mswsock From WinSock.h */ + DLL_WINSOCK2API = 3, /* ws2_32 From WinSock2.h */ + DLL_SHSTDAPI = 4, /* shell32 From ShellAPI.h */ + DLL_NTDLL = 5, /* ntdll From our real kernel */ + DLL_IPHLPAPI = 6, /* Iphlpapi From Iphlpapi.h */ + DLL_defined = 7 /* must define as last idx_ + 1 */ +} apr_dlltoken_e; + +FARPROC apr_load_dll_func(apr_dlltoken_e fnLib, char *fnName, int ordinal); + +/* The apr_load_dll_func call WILL return 0 set error to + * ERROR_INVALID_FUNCTION if the function cannot be loaded + */ +#define APR_DECLARE_LATE_DLL_FUNC(lib, rettype, calltype, fn, ord, args, names) \ + typedef rettype (calltype *apr_winapi_fpt_##fn) args; \ + static apr_winapi_fpt_##fn apr_winapi_pfn_##fn = NULL; \ + static int apr_winapi_chk_##fn = 0; \ + static APR_INLINE int apr_winapi_ld_##fn(void) \ + { if (apr_winapi_pfn_##fn) return 1; \ + if (apr_winapi_chk_##fn ++) return 0; \ + if (!apr_winapi_pfn_##fn) \ + apr_winapi_pfn_##fn = (apr_winapi_fpt_##fn) \ + apr_load_dll_func(lib, #fn, ord); \ + if (apr_winapi_pfn_##fn) return 1; else return 0; }; \ + static APR_INLINE rettype apr_winapi_##fn args \ + { if (apr_winapi_ld_##fn()) \ + return (*(apr_winapi_pfn_##fn)) names; \ + else { SetLastError(ERROR_INVALID_FUNCTION); return 0;} }; \ + +#define APR_HAVE_LATE_DLL_FUNC(fn) apr_winapi_ld_##fn() + +/* Provide late bound declarations of every API function missing from + * one or more supported releases of the Win32 API + * + * lib is the enumerated token from apr_dlltoken_e, and must correspond + * to the string table entry in start.c used by the apr_load_dll_func(). + * Token names (attempt to) follow Windows.h declarations prefixed by DLL_ + * in order to facilitate comparison. Use the exact declaration syntax + * and names from Windows.h to prevent ambigutity and bugs. + * + * rettype and calltype follow the original declaration in Windows.h + * fn is the true function name - beware Ansi/Unicode #defined macros + * ord is the ordinal within the library, use 0 if it varies between versions + * args is the parameter list following the original declaration, in parens + * names is the parameter list sans data types, enclosed in parens + * + * #undef/re#define the Ansi/Unicode generic name to abate confusion + * In the case of non-text functions, simply #define the original name + */ + +#if !defined(_WIN32_WCE) && !defined(WINNT) +/* This group is available to all versions of WINNT 4.0 SP6 and later */ + +#ifdef GetFileAttributesExA +#undef GetFileAttributesExA +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, GetFileAttributesExA, 0, ( + IN LPCSTR lpFileName, + IN GET_FILEEX_INFO_LEVELS fInfoLevelId, + OUT LPVOID lpFileInformation), + (lpFileName, fInfoLevelId, lpFileInformation)); +#define GetFileAttributesExA apr_winapi_GetFileAttributesExA +#undef GetFileAttributesEx +#define GetFileAttributesEx apr_winapi_GetFileAttributesExA + +#ifdef GetFileAttributesExW +#undef GetFileAttributesExW +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, GetFileAttributesExW, 0, ( + IN LPCWSTR lpFileName, + IN GET_FILEEX_INFO_LEVELS fInfoLevelId, + OUT LPVOID lpFileInformation), + (lpFileName, fInfoLevelId, lpFileInformation)); +#define GetFileAttributesExW apr_winapi_GetFileAttributesExW + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, CancelIo, 0, ( + IN HANDLE hFile), + (hFile)); +#define CancelIo apr_winapi_CancelIo + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, TryEnterCriticalSection, 0, ( + LPCRITICAL_SECTION lpCriticalSection), + (lpCriticalSection)); +#define TryEnterCriticalSection apr_winapi_TryEnterCriticalSection + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, SwitchToThread, 0, ( + void), + ()); +#define SwitchToThread apr_winapi_SwitchToThread + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINADVAPI, BOOL, WINAPI, GetEffectiveRightsFromAclW, 0, ( + IN PACL pacl, + IN PTRUSTEE_W pTrustee, + OUT PACCESS_MASK pAccessRights), + (pacl, pTrustee, pAccessRights)); +#define GetEffectiveRightsFromAclW apr_winapi_GetEffectiveRightsFromAclW + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINADVAPI, BOOL, WINAPI, GetNamedSecurityInfoW, 0, ( + IN LPWSTR pObjectName, + IN SE_OBJECT_TYPE ObjectType, + IN SECURITY_INFORMATION SecurityInfo, + OUT PSID *ppsidOwner, + OUT PSID *ppsidGroup, + OUT PACL *ppDacl, + OUT PACL *ppSacl, + OUT PSECURITY_DESCRIPTOR *ppSecurityDescriptor), + (pObjectName, ObjectType, SecurityInfo, ppsidOwner, ppsidGroup, + ppDacl, ppSacl, ppSecurityDescriptor)); +#define GetNamedSecurityInfoW apr_winapi_GetNamedSecurityInfoW + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINADVAPI, BOOL, WINAPI, GetNamedSecurityInfoA, 0, ( + IN LPSTR pObjectName, + IN SE_OBJECT_TYPE ObjectType, + IN SECURITY_INFORMATION SecurityInfo, + OUT PSID *ppsidOwner, + OUT PSID *ppsidGroup, + OUT PACL *ppDacl, + OUT PACL *ppSacl, + OUT PSECURITY_DESCRIPTOR *ppSecurityDescriptor), + (pObjectName, ObjectType, SecurityInfo, ppsidOwner, ppsidGroup, + ppDacl, ppSacl, ppSecurityDescriptor)); +#define GetNamedSecurityInfoA apr_winapi_GetNamedSecurityInfoA +#undef GetNamedSecurityInfo +#define GetNamedSecurityInfo apr_winapi_GetNamedSecurityInfoA + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINADVAPI, BOOL, WINAPI, GetSecurityInfo, 0, ( + IN HANDLE handle, + IN SE_OBJECT_TYPE ObjectType, + IN SECURITY_INFORMATION SecurityInfo, + OUT PSID *ppsidOwner, + OUT PSID *ppsidGroup, + OUT PACL *ppDacl, + OUT PACL *ppSacl, + OUT PSECURITY_DESCRIPTOR *ppSecurityDescriptor), + (handle, ObjectType, SecurityInfo, ppsidOwner, ppsidGroup, + ppDacl, ppSacl, ppSecurityDescriptor)); +#define GetSecurityInfo apr_winapi_GetSecurityInfo + +APR_DECLARE_LATE_DLL_FUNC(DLL_SHSTDAPI, LPWSTR *, WINAPI, CommandLineToArgvW, 0, ( + LPCWSTR lpCmdLine, + int *pNumArgs), + (lpCmdLine, pNumArgs)); +#define CommandLineToArgvW apr_winapi_CommandLineToArgvW + +#endif /* !defined(_WIN32_WCE) && !defined(WINNT) */ + +#if !defined(_WIN32_WCE) +/* This group is NOT available to all versions of WinNT, + * these we must always look up + */ + +#ifdef GetCompressedFileSizeA +#undef GetCompressedFileSizeA +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, DWORD, WINAPI, GetCompressedFileSizeA, 0, ( + IN LPCSTR lpFileName, + OUT LPDWORD lpFileSizeHigh), + (lpFileName, lpFileSizeHigh)); +#define GetCompressedFileSizeA apr_winapi_GetCompressedFileSizeA +#undef GetCompressedFileSize +#define GetCompressedFileSize apr_winapi_GetCompressedFileSizeA + +#ifdef GetCompressedFileSizeW +#undef GetCompressedFileSizeW +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, DWORD, WINAPI, GetCompressedFileSizeW, 0, ( + IN LPCWSTR lpFileName, + OUT LPDWORD lpFileSizeHigh), + (lpFileName, lpFileSizeHigh)); +#define GetCompressedFileSizeW apr_winapi_GetCompressedFileSizeW + + +APR_DECLARE_LATE_DLL_FUNC(DLL_NTDLL, LONG, WINAPI, NtQueryTimerResolution, 0, ( + ULONG *pMaxRes, /* Minimum NS Resolution */ + ULONG *pMinRes, /* Maximum NS Resolution */ + ULONG *pCurRes), /* Current NS Resolution */ + (pMaxRes, pMinRes, pCurRes)); +#define QueryTimerResolution apr_winapi_NtQueryTimerResolution + +APR_DECLARE_LATE_DLL_FUNC(DLL_NTDLL, LONG, WINAPI, NtSetTimerResolution, 0, ( + ULONG ReqRes, /* Requested NS Clock Resolution */ + BOOL Acquire, /* Aquire (1) or Release (0) our interest */ + ULONG *pNewRes), /* The NS Clock Resolution granted */ + (ReqRes, Acquire, pNewRes)); +#define SetTimerResolution apr_winapi_NtSetTimerResolution + +typedef struct PBI { + LONG ExitStatus; + PVOID PebBaseAddress; + apr_uintptr_t AffinityMask; + LONG BasePriority; + apr_uintptr_t UniqueProcessId; + apr_uintptr_t InheritedFromUniqueProcessId; +} PBI, *PPBI; + +APR_DECLARE_LATE_DLL_FUNC(DLL_NTDLL, LONG, WINAPI, NtQueryInformationProcess, 0, ( + HANDLE hProcess, /* Obvious */ + INT info, /* Use 0 for PBI documented above */ + PVOID pPI, /* The PIB buffer */ + ULONG LenPI, /* Use sizeof(PBI) */ + ULONG *pSizePI), /* returns pPI buffer used (may pass NULL) */ + (hProcess, info, pPI, LenPI, pSizePI)); +#define QueryInformationProcess apr_winapi_NtQueryInformationProcess + +APR_DECLARE_LATE_DLL_FUNC(DLL_NTDLL, LONG, WINAPI, NtQueryObject, 0, ( + HANDLE hObject, /* Obvious */ + INT info, /* Use 0 for PBI documented above */ + PVOID pOI, /* The PIB buffer */ + ULONG LenOI, /* Use sizeof(PBI) */ + ULONG *pSizeOI), /* returns pPI buffer used (may pass NULL) */ + (hObject, info, pOI, LenOI, pSizeOI)); +#define QueryObject apr_winapi_NtQueryObject + +typedef struct IOSB { + union { + UINT Status; + PVOID reserved; + }; + apr_uintptr_t Information; /* Varies by op, consumed buffer size for FSI below */ +} IOSB, *PIOSB; + +typedef struct FSI { + LONGLONG AllocationSize; + LONGLONG EndOfFile; + ULONG NumberOfLinks; + BOOL DeletePending; + BOOL Directory; +} FSI, *PFSI; + +APR_DECLARE_LATE_DLL_FUNC(DLL_NTDLL, LONG, WINAPI, ZwQueryInformationFile, 0, ( + HANDLE hObject, /* Obvious */ + PVOID pIOSB, /* Point to the IOSB buffer for detailed return results */ + PVOID pFI, /* The buffer, using FIB above */ + ULONG LenFI, /* Use sizeof(FI) */ + ULONG info), /* Use 5 for FSI documented above*/ + (hObject, pIOSB, pFI, LenFI, info)); +#define ZwQueryInformationFile apr_winapi_ZwQueryInformationFile + +#ifdef CreateToolhelp32Snapshot +#undef CreateToolhelp32Snapshot +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, HANDLE, WINAPI, CreateToolhelp32Snapshot, 0, ( + DWORD dwFlags, + DWORD th32ProcessID), + (dwFlags, th32ProcessID)); +#define CreateToolhelp32Snapshot apr_winapi_CreateToolhelp32Snapshot + +#ifdef Process32FirstW +#undef Process32FirstW +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, Process32FirstW, 0, ( + HANDLE hSnapshot, + LPPROCESSENTRY32W lppe), + (hSnapshot, lppe)); +#define Process32FirstW apr_winapi_Process32FirstW + +#ifdef Process32NextW +#undef Process32NextW +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, Process32NextW, 0, ( + HANDLE hSnapshot, + LPPROCESSENTRY32W lppe), + (hSnapshot, lppe)); +#define Process32NextW apr_winapi_Process32NextW + +#if !defined(POLLERR) +/* Event flag definitions for WSAPoll(). */ +#define POLLRDNORM 0x0100 +#define POLLRDBAND 0x0200 +#define POLLIN (POLLRDNORM | POLLRDBAND) +#define POLLPRI 0x0400 + +#define POLLWRNORM 0x0010 +#define POLLOUT (POLLWRNORM) +#define POLLWRBAND 0x0020 + +#define POLLERR 0x0001 +#define POLLHUP 0x0002 +#define POLLNVAL 0x0004 + +typedef struct pollfd { + SOCKET fd; + SHORT events; + SHORT revents; + +} WSAPOLLFD, *PWSAPOLLFD, FAR *LPWSAPOLLFD; + +#endif /* !defined(POLLERR) */ +#ifdef WSAPoll +#undef WSAPoll +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINSOCK2API, int, WSAAPI, WSAPoll, 0, ( + IN OUT LPWSAPOLLFD fdArray, + IN ULONG fds, + IN INT timeout), + (fdArray, fds, timeout)); +#define WSAPoll apr_winapi_WSAPoll +#define HAVE_POLL 1 + +#ifdef SetDllDirectoryW +#undef SetDllDirectoryW +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, SetDllDirectoryW, 0, ( + IN LPCWSTR lpPathName), + (lpPathName)); +#define SetDllDirectoryW apr_winapi_SetDllDirectoryW + +#ifdef if_nametoindex +#undef if_nametoindex +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_IPHLPAPI, NET_IFINDEX, WINAPI, if_nametoindex, 0, ( + IN PCSTR InterfaceName), + (InterfaceName)); +#define if_nametoindex apr_winapi_if_nametoindex + +#ifdef if_indextoname +#undef if_indextoname +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_IPHLPAPI, PCHAR, NETIOAPI_API_, if_indextoname, 0, ( + NET_IFINDEX InterfaceIndex, + PCHAR InterfaceName), + (InterfaceIndex, InterfaceName)); +#define if_indextoname apr_winapi_if_indextoname + +#endif /* !defined(_WIN32_WCE) */ + +#endif /* ! MISC_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_networkio.h b/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_networkio.h new file mode 100644 index 00000000..04be5559 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_networkio.h @@ -0,0 +1,90 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETWORK_IO_H +#define NETWORK_IO_H + +#include "apr_network_io.h" +#include "apr_general.h" +#include "apr_poll.h" + +typedef struct sock_userdata_t sock_userdata_t; +struct sock_userdata_t { + sock_userdata_t *next; + const char *key; + void *data; +}; + +struct apr_socket_t { + apr_pool_t *pool; + SOCKET socketdes; + int type; /* SOCK_STREAM, SOCK_DGRAM */ + int protocol; + apr_sockaddr_t *local_addr; + apr_sockaddr_t *remote_addr; + int timeout_ms; /* MUST MATCH if timeout > 0 */ + apr_interval_time_t timeout; + apr_int32_t disconnected; + int local_port_unknown; + int local_interface_unknown; + int remote_addr_unknown; + apr_int32_t options; + apr_int32_t inherit; +#if APR_HAS_SENDFILE + /* As of 07.20.04, the overlapped structure is only used by + * apr_socket_sendfile and that's where it will be allocated + * and initialized. + */ + OVERLAPPED *overlapped; +#endif + sock_userdata_t *userdata; + + /* if there is a timeout set, then this pollset is used */ + apr_pollset_t *pollset; +}; + +#ifdef _WIN32_WCE +#ifndef WSABUF +typedef struct _WSABUF { + u_long len; /* the length of the buffer */ + char FAR * buf; /* the pointer to the buffer */ +} WSABUF, FAR * LPWSABUF; +#endif +#else +#ifdef _MSC_VER +#define HAVE_STRUCT_IPMREQ +#endif +#endif + +apr_status_t status_from_res_error(int); + +const char *apr_inet_ntop(int af, const void *src, char *dst, apr_size_t size); +int apr_inet_pton(int af, const char *src, void *dst); +void apr_sockaddr_vars_set(apr_sockaddr_t *, int, apr_port_t); + +#define apr_is_option_set(skt, option) \ + (((skt)->options & (option)) == (option)) + +#define apr_set_option(skt, option, on) \ + do { \ + if (on) \ + (skt)->options |= (option); \ + else \ + (skt)->options &= ~(option); \ + } while (0) + +#endif /* ! NETWORK_IO_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_proc_mutex.h b/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_proc_mutex.h new file mode 100644 index 00000000..4e3e3993 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_proc_mutex.h @@ -0,0 +1,29 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PROC_MUTEX_H +#define PROC_MUTEX_H + +#include "apr_proc_mutex.h" + +struct apr_proc_mutex_t { + apr_pool_t *pool; + HANDLE handle; + const char *fname; +}; + +#endif /* PROC_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_thread_cond.h b/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_thread_cond.h new file mode 100644 index 00000000..c7f69f80 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_thread_cond.h @@ -0,0 +1,32 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_COND_H +#define THREAD_COND_H + +#include "apr_thread_cond.h" + +struct apr_thread_cond_t { + apr_pool_t *pool; + HANDLE semaphore; + CRITICAL_SECTION csection; + unsigned long num_waiting; + unsigned long num_wake; + unsigned long generation; +}; + +#endif /* THREAD_COND_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_thread_mutex.h b/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_thread_mutex.h new file mode 100644 index 00000000..13d3c1cb --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_thread_mutex.h @@ -0,0 +1,40 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_MUTEX_H +#define THREAD_MUTEX_H + +#include "apr_pools.h" + +typedef enum thread_mutex_type { + thread_mutex_critical_section, + thread_mutex_unnested_event, + thread_mutex_nested_mutex +} thread_mutex_type; + +/* handle applies only to unnested_event on all platforms + * and nested_mutex on Win9x only. Otherwise critical_section + * is used for NT nexted mutexes providing optimal performance. + */ +struct apr_thread_mutex_t { + apr_pool_t *pool; + thread_mutex_type type; + HANDLE handle; + CRITICAL_SECTION section; +}; + +#endif /* THREAD_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_thread_rwlock.h b/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_thread_rwlock.h new file mode 100644 index 00000000..1177e529 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_thread_rwlock.h @@ -0,0 +1,30 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_RWLOCK_H +#define THREAD_RWLOCK_H + +#include "apr_thread_rwlock.h" + +struct apr_thread_rwlock_t { + apr_pool_t *pool; + HANDLE write_mutex; + HANDLE read_event; + LONG readers; +}; + +#endif /* THREAD_RWLOCK_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_threadproc.h b/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_threadproc.h new file mode 100644 index 00000000..d3ce9c51 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_threadproc.h @@ -0,0 +1,74 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr_private.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" + +#ifndef THREAD_PROC_H +#define THREAD_PROC_H + +#define SHELL_PATH "cmd.exe" + +struct apr_thread_t { + apr_pool_t *pool; + HANDLE td; + apr_int32_t cancel; + apr_int32_t cancel_how; + void *data; + apr_thread_start_t func; + apr_status_t exitval; +}; + +struct apr_threadattr_t { + apr_pool_t *pool; + apr_int32_t detach; + apr_size_t stacksize; +}; + +struct apr_threadkey_t { + apr_pool_t *pool; + DWORD key; +}; + +struct apr_procattr_t { + apr_pool_t *pool; + apr_file_t *parent_in; + apr_file_t *child_in; + apr_file_t *parent_out; + apr_file_t *child_out; + apr_file_t *parent_err; + apr_file_t *child_err; + char *currdir; + apr_int32_t cmdtype; + apr_int32_t detached; + apr_child_errfn_t *errfn; + apr_int32_t errchk; +#ifndef _WIN32_WCE + HANDLE user_token; + LPSECURITY_ATTRIBUTES sa; + LPVOID sd; +#endif +}; + +struct apr_thread_once_t { + long value; +}; + +extern apr_status_t apr_threadproc_init(apr_pool_t *pool); + +#endif /* ! THREAD_PROC_H */ + diff --git a/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_utf8.h b/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_utf8.h new file mode 100644 index 00000000..84f8bf77 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/win32/apr_arch_utf8.h @@ -0,0 +1,56 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef UTF8_H +#define UTF8_H + +#include "apr.h" +#include "apr_lib.h" +#include "apr_errno.h" + +/* If we ever support anything more exciting than char... this could move. + */ +typedef apr_uint16_t apr_wchar_t; + +/** + * An APR internal function for fast utf-8 octet-encoded Unicode conversion + * to the ucs-2 wide Unicode format. This function is used for filename and + * other resource conversions for platforms providing native Unicode support. + * + * @tip Only the errors APR_EINVAL and APR_INCOMPLETE may occur, the former + * when the character code is invalid (in or out of context) and the later + * when more characters were expected, but insufficient characters remain. + */ +APR_DECLARE(apr_status_t) apr_conv_utf8_to_ucs2(const char *in, + apr_size_t *inbytes, + apr_wchar_t *out, + apr_size_t *outwords); + +/** + * An APR internal function for fast ucs-2 wide Unicode format conversion to + * the utf-8 octet-encoded Unicode. This function is used for filename and + * other resource conversions for platforms providing native Unicode support. + * + * @tip Only the errors APR_EINVAL and APR_INCOMPLETE may occur, the former + * when the character code is invalid (in or out of context) and the later + * when more words were expected, but insufficient words remain. + */ +APR_DECLARE(apr_status_t) apr_conv_ucs2_to_utf8(const apr_wchar_t *in, + apr_size_t *inwords, + char *out, + apr_size_t *outbytes); + +#endif /* def UTF8_H */ diff --git a/c/dependencies/windows/apr/x86/include/arch/win32/apr_dbg_win32_handles.h b/c/dependencies/windows/apr/x86/include/arch/win32/apr_dbg_win32_handles.h new file mode 100644 index 00000000..471cd66d --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/win32/apr_dbg_win32_handles.h @@ -0,0 +1,217 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_DBG_WIN32_HANDLES_H +#define APR_DBG_WIN32_HANDLES_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* USAGE: + * + * Add the following include to apr_private.h for internal debugging, + * or copy this header into apr/include add the include below to apr.h + * for really global debugging; + * + * #include "apr_dbg_win32_handles.h" + * + * apr_dbg_log is the crux of this function ... it uses Win32 API and + * no apr calls itself to log all activity to a file named for the + * executing application with a .pid suffix. Ergo several instances + * may be executing and logged at once. + * + * HANDLE apr_dbg_log(char* fn, HANDLE ha, char* fl, int ln, int nh + * [, HANDLE *hv, char *dsc...]) + * + * returns: the handle passed in ha, which is cast back to the real return type. + * + * formats one line into the debug log file if nh is zero; + * ha (hex) seq(hex) tid(hex) fn fl ln + * xxxxxxxx xxxxxxxx xxxxxxxx func() sourcefile:lineno + * The macro apr_dbg_rv makes this simple to implement for many APIs + * that simply take args that don't interest us, and return a handle. + * + * formats multiple lines (nh) into the debug log file for each hv/dsc pair + * (nh must correspond to the number of pairs); + * hv (hex) seq(hex) tid(hex) fn dsc fl ln + * xxxxxxxx xxxxxxxx xxxxxxxx func(arg) sourcefile:lineno + * In this later usage, hv is the still the return value but is not + * treated as a handle. + */ + +APR_DECLARE_NONSTD(HANDLE) apr_dbg_log(char* fn, HANDLE ha, char* fl, int ln, + int nh,/* HANDLE *hv, char *dsc */...); + +#define apr_dbg_rv(fn, args) (apr_dbg_log(#fn,(fn) args,__FILE__,__LINE__,0)) + +#define CloseHandle(h) \ + ((BOOL)apr_dbg_log("CloseHandle", \ + (HANDLE)(CloseHandle)(h), \ + __FILE__,__LINE__,1, \ + &(h),"")) + +#define CreateEventA(sd,b1,b2,nm) apr_dbg_rv(CreateEventA,(sd,b1,b2,nm)) +#define CreateEventW(sd,b1,b2,nm) apr_dbg_rv(CreateEventW,(sd,b1,b2,nm)) + +#define CreateFileA(nm,d1,d2,sd,d3,d4,h) apr_dbg_rv(CreateFileA,(nm,d1,d2,sd,d3,d4,h)) +#define CreateFileW(nm,d1,d2,sd,d3,d4,h) apr_dbg_rv(CreateFileW,(nm,d1,d2,sd,d3,d4,h)) + +#define CreateFileMappingA(fh,sd,d1,d2,d3,nm) apr_dbg_rv(CreateFileMappingA,(fh,sd,d1,d2,d3,nm)) +#define CreateFileMappingW(fh,sd,d1,d2,d3,nm) apr_dbg_rv(CreateFileMappingW,(fh,sd,d1,d2,d3,nm)) + +#define CreateMutexA(sd,b,nm) apr_dbg_rv(CreateMutexA,(sd,b,nm)) +#define CreateMutexW(sd,b,nm) apr_dbg_rv(CreateMutexW,(sd,b,nm)) + +#define CreateIoCompletionPort(h1,h2,pd1,d2) apr_dbg_rv(CreateIoCompletionPort,(h1,h2,pd1,d2)) + +#define CreateNamedPipeA(nm,d1,d2,d3,d4,d5,d6,sd) apr_dbg_rv(CreateNamedPipeA,(nm,d1,d2,d3,d4,d5,d6,sd)) +#define CreateNamedPipeW(nm,d1,d2,d3,d4,d5,d6,sd) apr_dbg_rv(CreateNamedPipeW,(nm,d1,d2,d3,d4,d5,d6,sd)) + +#define CreatePipe(ph1,ph2,sd,d) \ + ((BOOL)apr_dbg_log("CreatePipe", \ + (HANDLE)(CreatePipe)(ph1,ph2,sd,d), \ + __FILE__,__LINE__,2, \ + (ph1),"hRead", \ + (ph2),"hWrite")) + +#define CreateProcessA(s1,s2,sd1,sd2,b,d1,s3,s4,pd2,hr) \ + ((BOOL)apr_dbg_log("CreateProcessA", \ + (HANDLE)(CreateProcessA)(s1,s2,sd1,sd2,b,d1,s3,s4,pd2,hr), \ + __FILE__,__LINE__,2, \ + &((hr)->hProcess),"hProcess", \ + &((hr)->hThread),"hThread")) +#define CreateProcessW(s1,s2,sd1,sd2,b,d1,s3,s4,pd2,hr) \ + ((BOOL)apr_dbg_log("CreateProcessW", \ + (HANDLE)(CreateProcessW)(s1,s2,sd1,sd2,b,d1,s3,s4,pd2,hr), \ + __FILE__,__LINE__,2, \ + &((hr)->hProcess),"hProcess", \ + &((hr)->hThread),"hThread")) + +#define CreateSemaphoreA(sd,d1,d2,nm) apr_dbg_rv(CreateSemaphoreA,(sd,d1,d2,nm)) +#define CreateSemaphoreW(sd,d1,d2,nm) apr_dbg_rv(CreateSemaphoreW,(sd,d1,d2,nm)) + +#define CreateThread(sd,d1,fn,pv,d2,pd3) apr_dbg_rv(CreateThread,(sd,d1,fn,pv,d2,pd3)) + +#define DeregisterEventSource(h) \ + ((BOOL)apr_dbg_log("DeregisterEventSource", \ + (HANDLE)(DeregisterEventSource)(h), \ + __FILE__,__LINE__,1, \ + &(h),"")) + +#define DuplicateHandle(h1,h2,h3,ph4,d1,b,d2) \ + ((BOOL)apr_dbg_log("DuplicateHandle", \ + (HANDLE)(DuplicateHandle)(h1,h2,h3,ph4,d1,b,d2), \ + __FILE__,__LINE__,2, \ + (ph4),((h3)==GetCurrentProcess()) \ + ? "Target" : "EXTERN Target", \ + &(h2),((h1)==GetCurrentProcess()) \ + ? "Source" : "EXTERN Source")) + +#define GetCurrentProcess() \ + (apr_dbg_log("GetCurrentProcess", \ + (GetCurrentProcess)(),__FILE__,__LINE__,0)) + +#define GetCurrentThread() \ + (apr_dbg_log("GetCurrentThread", \ + (GetCurrentThread)(),__FILE__,__LINE__,0)) + +#define GetModuleHandleA(nm) apr_dbg_rv(GetModuleHandleA,(nm)) +#define GetModuleHandleW(nm) apr_dbg_rv(GetModuleHandleW,(nm)) + +#define GetStdHandle(d) apr_dbg_rv(GetStdHandle,(d)) + +#define LoadLibraryA(nm) apr_dbg_rv(LoadLibraryA,(nm)) +#define LoadLibraryW(nm) apr_dbg_rv(LoadLibraryW,(nm)) + +#define LoadLibraryExA(nm,h,d) apr_dbg_rv(LoadLibraryExA,(nm,h,d)) +#define LoadLibraryExW(nm,h,d) apr_dbg_rv(LoadLibraryExW,(nm,h,d)) + +#define OpenEventA(d,b,nm) apr_dbg_rv(OpenEventA,(d,b,nm)) +#define OpenEventW(d,b,nm) apr_dbg_rv(OpenEventW,(d,b,nm)) + +#define OpenFileMappingA(d,b,nm) apr_dbg_rv(OpenFileMappingA,(d,b,nm)) +#define OpenFileMappingW(d,b,nm) apr_dbg_rv(OpenFileMappingW,(d,b,nm)) + +#define RegisterEventSourceA(s1,s2) apr_dbg_rv(RegisterEventSourceA,(s1,s2)) +#define RegisterEventSourceW(s1,s2) apr_dbg_rv(RegisterEventSourceW,(s1,s2)) + +#define SetEvent(h) \ + ((BOOL)apr_dbg_log("SetEvent", \ + (HANDLE)(SetEvent)(h), \ + __FILE__,__LINE__,1, \ + &(h),"")) + +#define SetStdHandle(d,h) \ + ((BOOL)apr_dbg_log("SetStdHandle", \ + (HANDLE)(SetStdHandle)(d,h), \ + __FILE__,__LINE__,1,&(h),"")) + +#define socket(i1,i2,i3) \ + ((SOCKET)apr_dbg_log("socket", \ + (HANDLE)(socket)(i1,i2,i3), \ + __FILE__,__LINE__,0)) + +#define WaitForSingleObject(h,d) \ + ((DWORD)apr_dbg_log("WaitForSingleObject", \ + (HANDLE)(WaitForSingleObject)(h,d), \ + __FILE__,__LINE__,1,&(h),"Signaled")) + +#define WaitForSingleObjectEx(h,d,b) \ + ((DWORD)apr_dbg_log("WaitForSingleObjectEx", \ + (HANDLE)(WaitForSingleObjectEx)(h,d,b), \ + __FILE__,__LINE__,1,&(h),"Signaled")) + +#define WaitForMultipleObjects(d1,ah,b,d2) \ + ((DWORD)apr_dbg_log("WaitForMultipleObjects", \ + (HANDLE)(WaitForMultipleObjects)(d1,ah,b,d2), \ + __FILE__,__LINE__,1,ah,"Signaled")) + +#define WaitForMultipleObjectsEx(d1,ah,b1,d2,b2) \ + ((DWORD)apr_dbg_log("WaitForMultipleObjectsEx", \ + (HANDLE)(WaitForMultipleObjectsEx)(d1,ah,b1,d2,b2), \ + __FILE__,__LINE__,1,ah,"Signaled")) + +#define WSASocketA(i1,i2,i3,pi,g,dw) \ + ((SOCKET)apr_dbg_log("WSASocketA", \ + (HANDLE)(WSASocketA)(i1,i2,i3,pi,g,dw), \ + __FILE__,__LINE__,0)) + +#define WSASocketW(i1,i2,i3,pi,g,dw) \ + ((SOCKET)apr_dbg_log("WSASocketW", \ + (HANDLE)(WSASocketW)(i1,i2,i3,pi,g,dw), \ + __FILE__,__LINE__,0)) + +#define closesocket(sh) \ + ((int)apr_dbg_log("closesocket", \ + (HANDLE)(closesocket)(sh), \ + __FILE__,__LINE__,1,&(sh),"")) + +#define _beginthread(fn,d,pv) \ + ((unsigned long)apr_dbg_log("_beginthread", \ + (HANDLE)(_beginthread)(fn,d,pv), \ + __FILE__,__LINE__,0)) + +#define _beginthreadex(sd,d1,fn,pv,d2,pd3) \ + ((unsigned long)apr_dbg_log("_beginthreadex", \ + (HANDLE)(_beginthreadex)(sd,d1,fn,pv,d2,pd3), \ + __FILE__,__LINE__,0)) + +#ifdef __cplusplus +} +#endif + +#endif /* !defined(APR_DBG_WIN32_HANDLES_H) */ diff --git a/c/dependencies/windows/apr/x86/include/arch/win32/apr_private.h b/c/dependencies/windows/apr/x86/include/arch/win32/apr_private.h new file mode 100644 index 00000000..c631ad43 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/arch/win32/apr_private.h @@ -0,0 +1,175 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Note: + * This is the windows specific autoconf-like config file + * which unix would create at build time. + */ + +#ifdef WIN32 + +#ifndef APR_PRIVATE_H +#define APR_PRIVATE_H + +/* Include the public APR symbols, include our idea of the 'right' + * subset of the Windows.h header. This saves us repetition. + */ +#include "apr.h" + +/* + * Add a _very_few_ declarations missing from the restricted set of headers + * (If this list becomes extensive, re-enable the required headers above!) + * winsock headers were excluded by WIN32_LEAN_AND_MEAN, so include them now + */ +#ifndef SW_HIDE +#define SW_HIDE 0 +#endif + +/* For the misc.h late-loaded dynamic symbols, we need some obscure types + * Avoid dragging in wtypes.h unless it's absolutely necessary [generally + * not with APR itself, until some GUI-related security is introduced.] + */ +#ifndef _WIN32_WCE +#define HAVE_ACLAPI 1 +#ifdef __wtypes_h__ +#include +#else +#define __wtypes_h__ +#include +#undef __wtypes_h__ +#endif +#else +#define HAVE_ACLAPI 0 +#endif + +#if APR_HAVE_SYS_TYPES_H +#include +#endif +#if APR_HAVE_STDDEF_H +#include +#endif +#include +#if APR_HAVE_TIME_H +#include +#endif + +/* Use this section to define all of the HAVE_FOO_H + * that are required to build properly. + */ +#define HAVE_LIMITS_H 1 +#define HAVE_MALLOC_H 1 +#define HAVE_SIGNAL_H 1 +/* #define HAVE_STDDEF_H 1 why not? */ +#define HAVE_STDLIB_H 1 + +#define HAVE_STRICMP 1 +#define HAVE_STRNICMP 1 +#define HAVE_STRDUP 1 +#define HAVE_STRSTR 1 +#define HAVE_MEMCHR 1 + +#define SIGHUP 1 +/* 2 is used for SIGINT on windows */ +#define SIGQUIT 3 +/* 4 is used for SIGILL on windows */ +#define SIGTRAP 5 +#define SIGIOT 6 +#define SIGBUS 7 +/* 8 is used for SIGFPE on windows */ +#define SIGKILL 9 +#define SIGUSR1 10 +/* 11 is used for SIGSEGV on windows */ +#define SIGUSR2 12 +#define SIGPIPE 13 +#define SIGALRM 14 +/* 15 is used for SIGTERM on windows */ +#define SIGSTKFLT 16 +#define SIGCHLD 17 +#define SIGCONT 18 +#define SIGSTOP 19 +#define SIGTSTP 20 +/* 21 is used for SIGBREAK on windows */ +/* 22 is used for SIGABRT on windows */ +#define SIGTTIN 23 +#define SIGTTOU 24 +#define SIGURG 25 +#define SIGXCPU 26 +#define SIGXFSZ 27 +#define SIGVTALRM 28 +#define SIGPROF 29 +#define SIGWINCH 30 +#define SIGIO 31 + +/* APR COMPATABILITY FUNCTIONS + * This section should be used to define functions and + * macros which are need to make Windows features look + * like POSIX features. + */ +typedef void (Sigfunc)(int); + +#define sleep(t) Sleep((t) * 1000) + +#define SIZEOF_SHORT 2 +#define SIZEOF_INT 4 +#define SIZEOF_LONGLONG 8 +#define SIZEOF_CHAR 1 +#define SIZEOF_SSIZE_T SIZEOF_INT + +unsigned __stdcall SignalHandling(void *); +int thread_ready(void); + +#if !APR_HAVE_ERRNO_H +APR_DECLARE_DATA int errno; +#define ENOSPC 1 +#endif + +#if APR_HAVE_IPV6 +#define HAVE_GETADDRINFO 1 +#define HAVE_GETNAMEINFO 1 +#define HAVE_IF_INDEXTONAME 1 +#define HAVE_IF_NAMETOINDEX 1 +#endif + +/* MSVC 7.0 introduced _strtoi64 */ +#if _MSC_VER >= 1300 && _INTEGRAL_MAX_BITS >= 64 && !defined(_WIN32_WCE) +#define APR_INT64_STRFN _strtoi64 +#endif + +#if APR_HAS_LARGE_FILES +#ifdef APR_INT64_STRFN +#define APR_OFF_T_STRFN APR_INT64_STRFN +#else +#define APR_OFF_T_STRFN apr_strtoi64 +#endif +#else +#if defined(_WIN32_WCE) +#define APR_OFF_T_STRFN strtol +#else +#define APR_OFF_T_STRFN strtoi +#endif +#endif + +/* used to check for DWORD overflow in 64bit compiles */ +#define APR_DWORD_MAX 0xFFFFFFFFUL + +/* + * Include common private declarations. + */ +#include "../apr_private_common.h" + +#endif /*APR_PRIVATE_H*/ +#endif /*WIN32*/ diff --git a/c/dependencies/windows/apr/x86/include/private/apr_crypto_internal.h b/c/dependencies/windows/apr/x86/include/private/apr_crypto_internal.h new file mode 100644 index 00000000..1ea838bf --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/private/apr_crypto_internal.h @@ -0,0 +1,297 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_CRYPTO_INTERNAL_H +#define APR_CRYPTO_INTERNAL_H + +#include + +#include "apr_crypto.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if APU_HAVE_CRYPTO + +struct apr_crypto_driver_t { + + /** name */ + const char *name; + + /** + * @brief: allow driver to perform once-only initialisation. + * Called once only. + * @param pool The pool to register the cleanup in. + * @param params Optional init parameter string. + * @param rc Driver-specific additional error code + */ + apr_status_t (*init)(apr_pool_t *pool, const char *params, + const apu_err_t **result); + + /** + * @brief Create a context for supporting encryption. Keys, certificates, + * algorithms and other parameters will be set per context. More than + * one context can be created at one time. A cleanup will be automatically + * registered with the given pool to guarantee a graceful shutdown. + * @param f - context pointer will be written here + * @param provider - provider to use + * @param params - array of key parameters + * @param pool - process pool + * @return APR_ENOENGINE when the engine specified does not exist. APR_EINITENGINE + * if the engine cannot be initialised. + */ + apr_status_t (*make)(apr_crypto_t **f, const apr_crypto_driver_t *provider, + const char *params, apr_pool_t *pool); + + /** + * @brief Get a hash table of key types, keyed by the name of the type against + * a pointer to apr_crypto_block_key_type_t. + * + * @param types - hashtable of key types keyed to constants. + * @param f - encryption context + * @return APR_SUCCESS for success + */ + apr_status_t (*get_block_key_types)(apr_hash_t **types, + const apr_crypto_t *f); + + /** + * @brief Get a hash table of key modes, keyed by the name of the mode against + * a pointer to apr_crypto_block_key_mode_t. + * + * @param modes - hashtable of key modes keyed to constants. + * @param f - encryption context + * @return APR_SUCCESS for success + */ + apr_status_t (*get_block_key_modes)(apr_hash_t **modes, + const apr_crypto_t *f); + + /** + * @brief Create a key from the given passphrase. By default, the PBKDF2 + * algorithm is used to generate the key from the passphrase. It is expected + * that the same pass phrase will generate the same key, regardless of the + * backend crypto platform used. The key is cleaned up when the context + * is cleaned, and may be reused with multiple encryption or decryption + * operations. + * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If + * *key is not NULL, *key must point at a previously created structure. + * @param key The key returned, see note. + * @param ivSize The size of the initialisation vector will be returned, based + * on whether an IV is relevant for this type of crypto. + * @param pass The passphrase to use. + * @param passLen The passphrase length in bytes + * @param salt The salt to use. + * @param saltLen The salt length in bytes + * @param type 3DES_192, AES_128, AES_192, AES_256. + * @param mode Electronic Code Book / Cipher Block Chaining. + * @param doPad Pad if necessary. + * @param iterations Iteration count + * @param f The context to use. + * @param p The pool to use. + * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend + * error occurred while generating the key. APR_ENOCIPHER if the type or mode + * is not supported by the particular backend. APR_EKEYTYPE if the key type is + * not known. APR_EPADDING if padding was requested but is not supported. + * APR_ENOTIMPL if not implemented. + */ + apr_status_t (*passphrase)(apr_crypto_key_t **key, apr_size_t *ivSize, + const char *pass, apr_size_t passLen, const unsigned char * salt, + apr_size_t saltLen, const apr_crypto_block_key_type_e type, + const apr_crypto_block_key_mode_e mode, const int doPad, + const int iterations, const apr_crypto_t *f, apr_pool_t *p); + + /** + * @brief Initialise a context for encrypting arbitrary data using the given key. + * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If + * *ctx is not NULL, *ctx must point at a previously created structure. + * @param ctx The block context returned, see note. + * @param iv Optional initialisation vector. If the buffer pointed to is NULL, + * an IV will be created at random, in space allocated from the pool. + * If the buffer pointed to is not NULL, the IV in the buffer will be + * used. + * @param key The key structure. + * @param blockSize The block size of the cipher. + * @param p The pool to use. + * @return Returns APR_ENOIV if an initialisation vector is required but not specified. + * Returns APR_EINIT if the backend failed to initialise the context. Returns + * APR_ENOTIMPL if not implemented. + */ + apr_status_t (*block_encrypt_init)(apr_crypto_block_t **ctx, + const unsigned char **iv, const apr_crypto_key_t *key, + apr_size_t *blockSize, apr_pool_t *p); + + /** + * @brief Encrypt data provided by in, write it to out. + * @note The number of bytes written will be written to outlen. If + * out is NULL, outlen will contain the maximum size of the + * buffer needed to hold the data, including any data + * generated by apr_crypto_block_encrypt_finish below. If *out points + * to NULL, a buffer sufficiently large will be created from + * the pool provided. If *out points to a not-NULL value, this + * value will be used as a buffer instead. + * @param out Address of a buffer to which data will be written, + * see note. + * @param outlen Length of the output will be written here. + * @param in Address of the buffer to read. + * @param inlen Length of the buffer to read. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if + * not implemented. + */ + apr_status_t (*block_encrypt)(unsigned char **out, apr_size_t *outlen, + const unsigned char *in, apr_size_t inlen, apr_crypto_block_t *ctx); + + /** + * @brief Encrypt final data block, write it to out. + * @note If necessary the final block will be written out after being + * padded. Typically the final block will be written to the + * same buffer used by apr_crypto_block_encrypt, offset by the + * number of bytes returned as actually written by the + * apr_crypto_block_encrypt() call. After this call, the context + * is cleaned and can be reused by apr_crypto_block_encrypt_init(). + * @param out Address of a buffer to which data will be written. This + * buffer must already exist, and is usually the same + * buffer used by apr_evp_crypt(). See note. + * @param outlen Length of the output will be written here. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. + * @return APR_EPADDING if padding was enabled and the block was incorrectly + * formatted. + * @return APR_ENOTIMPL if not implemented. + */ + apr_status_t (*block_encrypt_finish)(unsigned char *out, + apr_size_t *outlen, apr_crypto_block_t *ctx); + + /** + * @brief Initialise a context for decrypting arbitrary data using the given key. + * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If + * *ctx is not NULL, *ctx must point at a previously created structure. + * @param ctx The block context returned, see note. + * @param blockSize The block size of the cipher. + * @param iv Optional initialisation vector. If the buffer pointed to is NULL, + * an IV will be created at random, in space allocated from the pool. + * If the buffer is not NULL, the IV in the buffer will be used. + * @param key The key structure. + * @param p The pool to use. + * @return Returns APR_ENOIV if an initialisation vector is required but not specified. + * Returns APR_EINIT if the backend failed to initialise the context. Returns + * APR_ENOTIMPL if not implemented. + */ + apr_status_t (*block_decrypt_init)(apr_crypto_block_t **ctx, + apr_size_t *blockSize, const unsigned char *iv, + const apr_crypto_key_t *key, apr_pool_t *p); + + /** + * @brief Decrypt data provided by in, write it to out. + * @note The number of bytes written will be written to outlen. If + * out is NULL, outlen will contain the maximum size of the + * buffer needed to hold the data, including any data + * generated by apr_crypto_block_decrypt_finish below. If *out points + * to NULL, a buffer sufficiently large will be created from + * the pool provided. If *out points to a not-NULL value, this + * value will be used as a buffer instead. + * @param out Address of a buffer to which data will be written, + * see note. + * @param outlen Length of the output will be written here. + * @param in Address of the buffer to read. + * @param inlen Length of the buffer to read. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if + * not implemented. + */ + apr_status_t (*block_decrypt)(unsigned char **out, apr_size_t *outlen, + const unsigned char *in, apr_size_t inlen, apr_crypto_block_t *ctx); + + /** + * @brief Decrypt final data block, write it to out. + * @note If necessary the final block will be written out after being + * padded. Typically the final block will be written to the + * same buffer used by apr_crypto_block_decrypt, offset by the + * number of bytes returned as actually written by the + * apr_crypto_block_decrypt() call. After this call, the context + * is cleaned and can be reused by apr_crypto_block_decrypt_init(). + * @param out Address of a buffer to which data will be written. This + * buffer must already exist, and is usually the same + * buffer used by apr_evp_crypt(). See note. + * @param outlen Length of the output will be written here. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. + * @return APR_EPADDING if padding was enabled and the block was incorrectly + * formatted. + * @return APR_ENOTIMPL if not implemented. + */ + apr_status_t (*block_decrypt_finish)(unsigned char *out, + apr_size_t *outlen, apr_crypto_block_t *ctx); + + /** + * @brief Clean encryption / decryption context. + * @note After cleanup, a context is free to be reused if necessary. + * @param ctx The block context to use. + * @return Returns APR_ENOTIMPL if not supported. + */ + apr_status_t (*block_cleanup)(apr_crypto_block_t *ctx); + + /** + * @brief Clean encryption / decryption context. + * @note After cleanup, a context is free to be reused if necessary. + * @param f The context to use. + * @return Returns APR_ENOTIMPL if not supported. + */ + apr_status_t (*cleanup)(apr_crypto_t *f); + + /** + * @brief Clean encryption / decryption context. + * @note After cleanup, a context is free to be reused if necessary. + * @return Returns APR_ENOTIMPL if not supported. + */ + apr_status_t (*shutdown)(void); + + /** + * @brief: fetch the most recent error from this driver. + * @param result - the result structure + * @param f - context pointer + * @return APR_SUCCESS for success. + */ + apr_status_t (*error)(const apu_err_t **result, const apr_crypto_t *f); + + /** + * @brief Create a key from the provided secret or passphrase. The key is cleaned + * up when the context is cleaned, and may be reused with multiple encryption + * or decryption operations. + * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If + * *key is not NULL, *key must point at a previously created structure. + * @param key The key returned, see note. + * @param rec The key record, from which the key will be derived. + * @param f The context to use. + * @param p The pool to use. + * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend + * error occurred while generating the key. APR_ENOCIPHER if the type or mode + * is not supported by the particular backend. APR_EKEYTYPE if the key type is + * not known. APR_EPADDING if padding was requested but is not supported. + * APR_ENOTIMPL if not implemented. + */ + apr_status_t (*key)(apr_crypto_key_t **key, const apr_crypto_key_rec_t *rec, + const apr_crypto_t *f, apr_pool_t *p); + +}; + +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/c/dependencies/windows/apr/x86/include/private/apr_dbd_internal.h b/c/dependencies/windows/apr/x86/include/private/apr_dbd_internal.h new file mode 100644 index 00000000..671ffb21 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/private/apr_dbd_internal.h @@ -0,0 +1,365 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* Overview of what this is and does: + * http://www.apache.org/~niq/dbd.html + */ + +#ifndef APR_DBD_INTERNAL_H +#define APR_DBD_INTERNAL_H + +#include + +#include "apr_dbd.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define TXN_IGNORE_ERRORS(t) \ + ((t) && ((t)->mode & APR_DBD_TRANSACTION_IGNORE_ERRORS)) +#define TXN_NOTICE_ERRORS(t) \ + ((t) && !((t)->mode & APR_DBD_TRANSACTION_IGNORE_ERRORS)) + +#define TXN_DO_COMMIT(t) (!((t)->mode & APR_DBD_TRANSACTION_ROLLBACK)) +#define TXN_DO_ROLLBACK(t) ((t)->mode & APR_DBD_TRANSACTION_ROLLBACK) + +#define TXN_MODE_BITS \ + (APR_DBD_TRANSACTION_ROLLBACK|APR_DBD_TRANSACTION_IGNORE_ERRORS) + +struct apr_dbd_driver_t { + /** name */ + const char *name; + + /** init: allow driver to perform once-only initialisation. + * Called once only. May be NULL + */ + void (*init)(apr_pool_t *pool); + + /** native_handle: return the native database handle of the underlying db + * + * @param handle - apr_dbd handle + * @return - native handle + */ + void *(*native_handle)(apr_dbd_t *handle); + + /** open: obtain a database connection from the server rec. + * Must be explicitly closed when you're finished with it. + * WARNING: only use this when you need a connection with + * a lifetime other than a request + * + * @param pool - a pool to use for error messages (if any). + * @param params - connection parameters. + * @param error - descriptive error. + * @return database handle, or NULL on error. + */ + apr_dbd_t *(*open)(apr_pool_t *pool, const char *params, + const char **error); + + /** check_conn: check status of a database connection + * + * @param pool - a pool to use for error messages (if any). + * @param handle - the connection to check + * @return APR_SUCCESS or error + */ + apr_status_t (*check_conn)(apr_pool_t *pool, apr_dbd_t *handle); + + /** close: close/release a connection obtained from open() + * + * @param handle - the connection to release + * @return APR_SUCCESS or error + */ + apr_status_t (*close)(apr_dbd_t *handle); + + /** set_dbname: select database name. May be a no-op if not supported. + * + * @param pool - working pool + * @param handle - the connection + * @param name - the database to select + * @return 0 for success or error code + */ + int (*set_dbname)(apr_pool_t* pool, apr_dbd_t *handle, const char *name); + + /** transaction: start a transaction. May be a no-op. + * + * @param pool - a pool to use for error messages (if any). + * @param handle - the connection + * @param trans - ptr to a transaction. May be null on entry + * @return 0 for success or error code + */ + int (*start_transaction)(apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_transaction_t **trans); + + /** end_transaction: end a transaction + * (commit on success, rollback on error). + * May be a no-op. + * + * @param trans - the transaction. + * @return 0 for success or error code + */ + int (*end_transaction)(apr_dbd_transaction_t *trans); + + /** query: execute an SQL query that doesn't return a result set + * + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the SQL statement to execute + * @return 0 for success or error code + */ + int (*query)(apr_dbd_t *handle, int *nrows, const char *statement); + + /** select: execute an SQL query that returns a result set + * + * @param pool - pool to allocate the result set + * @param handle - the connection + * @param res - pointer to result set pointer. May point to NULL on entry + * @param statement - the SQL statement to execute + * @param random - 1 to support random access to results (seek any row); + * 0 to support only looping through results in order + * (async access - faster) + * @return 0 for success or error code + */ + int (*select)(apr_pool_t *pool, apr_dbd_t *handle, apr_dbd_results_t **res, + const char *statement, int random); + + /** num_cols: get the number of columns in a results set + * + * @param res - result set. + * @return number of columns + */ + int (*num_cols)(apr_dbd_results_t *res); + + /** num_tuples: get the number of rows in a results set + * of a synchronous select + * + * @param res - result set. + * @return number of rows, or -1 if the results are asynchronous + */ + int (*num_tuples)(apr_dbd_results_t *res); + + /** get_row: get a row from a result set + * + * @param pool - pool to allocate the row + * @param res - result set pointer + * @param row - pointer to row pointer. May point to NULL on entry + * @param rownum - row number, or -1 for "next row". Ignored if random + * access is not supported. + * @return 0 for success, -1 for rownum out of range or data finished + */ + int (*get_row)(apr_pool_t *pool, apr_dbd_results_t *res, + apr_dbd_row_t **row, int rownum); + + /** get_entry: get an entry from a row + * + * @param row - row pointer + * @param col - entry number + * @param val - entry to fill + * @return 0 for success, -1 for no data, +1 for general error + */ + const char* (*get_entry)(const apr_dbd_row_t *row, int col); + + /** error: get current error message (if any) + * + * @param handle - the connection + * @param errnum - error code from operation that returned an error + * @return the database current error message, or message for errnum + * (implementation-dependent whether errnum is ignored) + */ + const char *(*error)(apr_dbd_t *handle, int errnum); + + /** escape: escape a string so it is safe for use in query/select + * + * @param pool - pool to alloc the result from + * @param string - the string to escape + * @param handle - the connection + * @return the escaped, safe string + */ + const char *(*escape)(apr_pool_t *pool, const char *string, + apr_dbd_t *handle); + + /** prepare: prepare a statement + * + * @param pool - pool to alloc the result from + * @param handle - the connection + * @param query - the SQL query + * @param label - A label for the prepared statement. + * use NULL for temporary prepared statements + * (eg within a Request in httpd) + * @param nargs - number of parameters in the query + * @param nvals - number of values passed in p[b]query/select + * @param types - pointer to an array with types of parameters + * @param statement - statement to prepare. May point to null on entry. + * @return 0 for success or error code + */ + int (*prepare)(apr_pool_t *pool, apr_dbd_t *handle, const char *query, + const char *label, int nargs, int nvals, + apr_dbd_type_e *types, apr_dbd_prepared_t **statement); + + /** pvquery: query using a prepared statement + args + * + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param args - args to prepared statement + * @return 0 for success or error code + */ + int (*pvquery)(apr_pool_t *pool, apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, va_list args); + + /** pvselect: select using a prepared statement + args + * + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param args - args to prepared statement + * @return 0 for success or error code + */ + int (*pvselect)(apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, int random, va_list args); + + /** pquery: query using a prepared statement + args + * + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param args - args to prepared statement + * @return 0 for success or error code + */ + int (*pquery)(apr_pool_t *pool, apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, const char **args); + + /** pselect: select using a prepared statement + args + * + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param args - args to prepared statement + * @return 0 for success or error code + */ + int (*pselect)(apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, apr_dbd_prepared_t *statement, + int random, const char **args); + + + /** get_name: get a column title from a result set + * + * @param res - result set pointer + * @param col - entry number + * @return param name, or NULL if col is out of bounds. + */ + const char* (*get_name)(const apr_dbd_results_t *res, int col); + + /** transaction_mode_get: get the mode of transaction + * + * @param trans - the transaction. + * @return mode of transaction + */ + int (*transaction_mode_get)(apr_dbd_transaction_t *trans); + + /** transaction_mode_set: get the mode of transaction + * + * @param trans - the transaction. + * @param mode - new mode of the transaction + * @return the mode of transaction in force after the call + */ + int (*transaction_mode_set)(apr_dbd_transaction_t *trans, int mode); + + /** format of prepared statement parameters */ + const char *pformat; + + /** pvbquery: query using a prepared statement + binary args + * + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ + int (*pvbquery)(apr_pool_t *pool, apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, va_list args); + + /** pvbselect: select using a prepared statement + binary args + * + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ + int (*pvbselect)(apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, int random, va_list args); + + /** pbquery: query using a prepared statement + binary args + * + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ + int (*pbquery)(apr_pool_t *pool, apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement,const void **args); + + /** pbselect: select using a prepared statement + binary args + * + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ + int (*pbselect)(apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, apr_dbd_prepared_t *statement, + int random, const void **args); + + /** datum_get: get a binary entry from a row + * + * @param row - row pointer + * @param col - entry number + * @param type - type of data to get + * @param data - pointer to data, allocated by the caller + * @return APR_SUCCESS, an error code on error or if col is out of bounds + */ + apr_status_t (*datum_get)(const apr_dbd_row_t *row, int col, + apr_dbd_type_e type, void *data); +}; + +/* Export mutex lock/unlock for drivers that need it + * deprecated; create a per-dbd mutex within the (*init) function + * to avoid blocking other providers running on other threads + */ +APU_DECLARE(apr_status_t) apr_dbd_mutex_lock(void); +APU_DECLARE(apr_status_t) apr_dbd_mutex_unlock(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/c/dependencies/windows/apr/x86/include/private/apr_dbd_odbc_v2.h b/c/dependencies/windows/apr/x86/include/private/apr_dbd_odbc_v2.h new file mode 100644 index 00000000..b8da7b18 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/private/apr_dbd_odbc_v2.h @@ -0,0 +1,119 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/* ONLY USED FOR ODBC Version 2 -DODBCV2 +* +* Re-define everything to work (more-or-less) in an ODBC V2 environment +* Random access to retrieved rows is not supported - i.e. calls to apr_dbd_select() cannot +* have a 'random' argument of 1. apr_dbd_get_row() must always pass rownum as 0 (get next row) +* +*/ + +#define SQLHANDLE SQLHENV /* Presumes that ENV, DBC, and STMT handles are all the same datatype */ +#define SQL_NULL_HANDLE 0 +#define SQL_HANDLE_STMT 1 +#define SQL_HANDLE_DBC 2 +#define SQL_HANDLE_ENV 3 +#define SQL_NO_DATA SQL_NO_DATA_FOUND + +#ifndef SQL_SUCCEEDED +#define SQL_SUCCEEDED(rc) (((rc)&(~1))==0) +#endif + +#undef SQLSetEnvAttr +#define SQLSetEnvAttr(henv, Attribute, Value, StringLength) (0) + +#undef SQLAllocHandle +#define SQLAllocHandle(type, parent, hndl) \ +( (type == SQL_HANDLE_STMT) ? SQLAllocStmt(parent, hndl) \ + : (type == SQL_HANDLE_ENV) ? SQLAllocEnv(hndl) \ + : SQLAllocConnect(parent, hndl) \ +) + +#undef SQLFreeHandle +#define SQLFreeHandle(type, hndl) \ +( (type == SQL_HANDLE_STMT) ? SQLFreeStmt(hndl, SQL_DROP) \ + : (type == SQL_HANDLE_ENV) ? SQLFreeEnv(hndl) \ + : SQLFreeConnect(hndl) \ +) + +#undef SQLGetDiagRec +#define SQLGetDiagRec(type, h, i, state, native, buffer, bufsize, reslen) \ + SQLError( (type == SQL_HANDLE_ENV) ? h : NULL, \ + (type == SQL_HANDLE_DBC) ? h : NULL, \ + (type == SQL_HANDLE_STMT) ? h : NULL, \ + state, native, buffer, bufsize, reslen) + +#undef SQLCloseCursor +#define SQLCloseCursor(stmt) SQLFreeStmt(stmt, SQL_CLOSE) + +#undef SQLGetConnectAttr +#define SQLGetConnectAttr(hdbc, fOption, ValuePtr, BufferLength, NULL) \ + SQLGetConnectOption(hdbc, fOption, ValuePtr) + +#undef SQLSetConnectAttr +#define SQLSetConnectAttr(hdbc, fOption, ValuePtr, BufferLength) \ + SQLSetConnectOption(hdbc, fOption, (SQLUINTEGER) ValuePtr) + +#undef SQLSetStmtAttr +#define SQLSetStmtAttr(hstmt, fOption, ValuePtr, BufferLength) (0); return APR_ENOTIMPL; + +#undef SQLEndTran +#define SQLEndTran(hType, hdbc,type) SQLTransact(henv, hdbc, type) + +#undef SQLFetchScroll +#define SQLFetchScroll(stmt, orient, rownum) (0); return APR_ENOTIMPL; + +#define SQL_DESC_TYPE SQL_COLUMN_TYPE +#define SQL_DESC_CONCISE_TYPE SQL_COLUMN_TYPE +#define SQL_DESC_DISPLAY_SIZE SQL_COLUMN_DISPLAY_SIZE +#define SQL_DESC_OCTET_LENGTH SQL_COLUMN_LENGTH +#define SQL_DESC_UNSIGNED SQL_COLUMN_UNSIGNED + +#undef SQLColAttribute +#define SQLColAttribute(s, c, f, a, l, m, n) SQLColAttributes(s, c, f, a, l, m, n) + +#define SQL_ATTR_ACCESS_MODE SQL_ACCESS_MODE +#define SQL_ATTR_AUTOCOMMIT SQL_AUTOCOMMIT +#define SQL_ATTR_CONNECTION_TIMEOUT 113 +#define SQL_ATTR_CURRENT_CATALOG SQL_CURRENT_QUALIFIER +#define SQL_ATTR_DISCONNECT_BEHAVIOR 114 +#define SQL_ATTR_ENLIST_IN_DTC 1207 +#define SQL_ATTR_ENLIST_IN_XA 1208 + +#define SQL_ATTR_CONNECTION_DEAD 1209 +#define SQL_CD_TRUE 1L /* Connection is closed/dead */ +#define SQL_CD_FALSE 0L /* Connection is open/available */ + +#define SQL_ATTR_LOGIN_TIMEOUT SQL_LOGIN_TIMEOUT +#define SQL_ATTR_ODBC_CURSORS SQL_ODBC_CURSORS +#define SQL_ATTR_PACKET_SIZE SQL_PACKET_SIZE +#define SQL_ATTR_QUIET_MODE SQL_QUIET_MODE +#define SQL_ATTR_TRACE SQL_OPT_TRACE +#define SQL_ATTR_TRACEFILE SQL_OPT_TRACEFILE +#define SQL_ATTR_TRANSLATE_LIB SQL_TRANSLATE_DLL +#define SQL_ATTR_TRANSLATE_OPTION SQL_TRANSLATE_OPTION +#define SQL_ATTR_TXN_ISOLATION SQL_TXN_ISOLATION + +#define SQL_ATTR_CURSOR_SCROLLABLE -1 + +#define SQL_C_SBIGINT (SQL_BIGINT+SQL_SIGNED_OFFSET) /* SIGNED BIGINT */ +#define SQL_C_UBIGINT (SQL_BIGINT+SQL_UNSIGNED_OFFSET) /* UNSIGNED BIGINT */ + +#define SQL_FALSE 0 +#define SQL_TRUE 1 + diff --git a/c/dependencies/windows/apr/x86/include/private/apr_dbm_private.h b/c/dependencies/windows/apr/x86/include/private/apr_dbm_private.h new file mode 100644 index 00000000..020d3a6b --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/private/apr_dbm_private.h @@ -0,0 +1,121 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_DBM_PRIVATE_H +#define APR_DBM_PRIVATE_H + +#include "apr.h" +#include "apr_errno.h" +#include "apr_pools.h" +#include "apr_dbm.h" +#include "apr_file_io.h" + +#include "apu.h" + +/* ### for now, include the DBM selection; this will go away once we start + ### building and linking all of the DBMs at once. */ +#include "apu_select_dbm.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** @internal */ + +/** + * Most DBM libraries take a POSIX mode for creating files. Don't trust + * the mode_t type, some platforms may not support it, int is safe. + */ +APU_DECLARE(int) apr_posix_perms2mode(apr_fileperms_t perm); + +/** + * Structure to describe the operations of the DBM + */ +typedef struct { + /** The name of the DBM Type */ + const char *name; + + /** Open the DBM */ + apr_status_t (*open)(apr_dbm_t **pdb, const char *pathname, + apr_int32_t mode, apr_fileperms_t perm, + apr_pool_t *pool); + + /** Close the DBM */ + void (*close)(apr_dbm_t *dbm); + + /** Fetch a dbm record value by key */ + apr_status_t (*fetch)(apr_dbm_t *dbm, apr_datum_t key, + apr_datum_t * pvalue); + + /** Store a dbm record value by key */ + apr_status_t (*store)(apr_dbm_t *dbm, apr_datum_t key, apr_datum_t value); + + /** Delete a dbm record value by key */ + apr_status_t (*del)(apr_dbm_t *dbm, apr_datum_t key); + + /** Search for a key within the dbm */ + int (*exists)(apr_dbm_t *dbm, apr_datum_t key); + + /** Retrieve the first record key from a dbm */ + apr_status_t (*firstkey)(apr_dbm_t *dbm, apr_datum_t * pkey); + + /** Retrieve the next record key from a dbm */ + apr_status_t (*nextkey)(apr_dbm_t *dbm, apr_datum_t * pkey); + + /** Proactively toss any memory associated with the apr_datum_t. */ + void (*freedatum)(apr_dbm_t *dbm, apr_datum_t data); + + /** Get the names that the DBM will use for a given pathname. */ + void (*getusednames)(apr_pool_t *pool, + const char *pathname, + const char **used1, + const char **used2); + +} apr_dbm_type_t; + + +/** + * The actual DBM + */ +struct apr_dbm_t +{ + /** Associated pool */ + apr_pool_t *pool; + + /** pointer to DB Implementation Specific data */ + void *file; + + /** Current integer error code */ + int errcode; + /** Current string error code */ + const char *errmsg; + + /** the type of DBM */ + const apr_dbm_type_t *type; +}; + + +/* Declare all of the DBM provider tables */ +APU_MODULE_DECLARE_DATA extern const apr_dbm_type_t apr_dbm_type_sdbm; +APU_MODULE_DECLARE_DATA extern const apr_dbm_type_t apr_dbm_type_gdbm; +APU_MODULE_DECLARE_DATA extern const apr_dbm_type_t apr_dbm_type_ndbm; +APU_MODULE_DECLARE_DATA extern const apr_dbm_type_t apr_dbm_type_db; + +#ifdef __cplusplus +} +#endif + +#endif /* APR_DBM_PRIVATE_H */ diff --git a/c/dependencies/windows/apr/x86/include/private/apr_encode_private.h b/c/dependencies/windows/apr/x86/include/private/apr_encode_private.h new file mode 100644 index 00000000..8db2e016 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/private/apr_encode_private.h @@ -0,0 +1,84 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_encode_private.h + * @brief APR-UTIL Encoding Private + */ +#ifndef APR_ENCODE_PRIVATE_H +#define APR_ENCODE_PRIVATE_H + +#include "apr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Encode_Private + * @ingroup APR_Util + * @{ + */ + +#if APR_CHARSET_EBCDIC + static int convert_a2e[256] = { + 0x00, 0x01, 0x02, 0x03, 0x37, 0x2D, 0x2E, 0x2F, 0x16, 0x05, 0x15, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, + 0x10, 0x11, 0x12, 0x13, 0x3C, 0x3D, 0x32, 0x26, 0x18, 0x19, 0x3F, 0x27, 0x1C, 0x1D, 0x1E, 0x1F, + 0x40, 0x5A, 0x7F, 0x7B, 0x5B, 0x6C, 0x50, 0x7D, 0x4D, 0x5D, 0x5C, 0x4E, 0x6B, 0x60, 0x4B, 0x61, + 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0x7A, 0x5E, 0x4C, 0x7E, 0x6E, 0x6F, + 0x7C, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, + 0xD7, 0xD8, 0xD9, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xAD, 0xE0, 0xBD, 0x5F, 0x6D, + 0x79, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, + 0x97, 0x98, 0x99, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xC0, 0x4F, 0xD0, 0xA1, 0x07, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x06, 0x17, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x09, 0x0A, 0x1B, + 0x30, 0x31, 0x1A, 0x33, 0x34, 0x35, 0x36, 0x08, 0x38, 0x39, 0x3A, 0x3B, 0x04, 0x14, 0x3E, 0xFF, + 0x41, 0xAA, 0x4A, 0xB1, 0x9F, 0xB2, 0x6A, 0xB5, 0xBB, 0xB4, 0x9A, 0x8A, 0xB0, 0xCA, 0xAF, 0xBC, + 0x90, 0x8F, 0xEA, 0xFA, 0xBE, 0xA0, 0xB6, 0xB3, 0x9D, 0xDA, 0x9B, 0x8B, 0xB7, 0xB8, 0xB9, 0xAB, + 0x64, 0x65, 0x62, 0x66, 0x63, 0x67, 0x9E, 0x68, 0x74, 0x71, 0x72, 0x73, 0x78, 0x75, 0x76, 0x77, + 0xAC, 0x69, 0xED, 0xEE, 0xEB, 0xEF, 0xEC, 0xBF, 0x80, 0xFD, 0xFE, 0xFB, 0xFC, 0xBA, 0xAE, 0x59, + 0x44, 0x45, 0x42, 0x46, 0x43, 0x47, 0x9C, 0x48, 0x54, 0x51, 0x52, 0x53, 0x58, 0x55, 0x56, 0x57, + 0x8C, 0x49, 0xCD, 0xCE, 0xCB, 0xCF, 0xCC, 0xE1, 0x70, 0xDD, 0xDE, 0xDB, 0xDC, 0x8D, 0x8E, 0xDF}; + + static int convert_e2a[256] = { + 0x00, 0x01, 0x02, 0x03, 0x9C, 0x09, 0x86, 0x7F, 0x97, 0x8D, 0x8E, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, + 0x10, 0x11, 0x12, 0x13, 0x9D, 0x0A, 0x08, 0x87, 0x18, 0x19, 0x92, 0x8F, 0x1C, 0x1D, 0x1E, 0x1F, + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x17, 0x1B, 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x05, 0x06, 0x07, + 0x90, 0x91, 0x16, 0x93, 0x94, 0x95, 0x96, 0x04, 0x98, 0x99, 0x9A, 0x9B, 0x14, 0x15, 0x9E, 0x1A, + 0x20, 0xA0, 0xE2, 0xE4, 0xE0, 0xE1, 0xE3, 0xE5, 0xE7, 0xF1, 0xA2, 0x2E, 0x3C, 0x28, 0x2B, 0x7C, + 0x26, 0xE9, 0xEA, 0xEB, 0xE8, 0xED, 0xEE, 0xEF, 0xEC, 0xDF, 0x21, 0x24, 0x2A, 0x29, 0x3B, 0x5E, + 0x2D, 0x2F, 0xC2, 0xC4, 0xC0, 0xC1, 0xC3, 0xC5, 0xC7, 0xD1, 0xA6, 0x2C, 0x25, 0x5F, 0x3E, 0x3F, + 0xF8, 0xC9, 0xCA, 0xCB, 0xC8, 0xCD, 0xCE, 0xCF, 0xCC, 0x60, 0x3A, 0x23, 0x40, 0x27, 0x3D, 0x22, + 0xD8, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xAB, 0xBB, 0xF0, 0xFD, 0xFE, 0xB1, + 0xB0, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0xAA, 0xBA, 0xE6, 0xB8, 0xC6, 0xA4, + 0xB5, 0x7E, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0xA1, 0xBF, 0xD0, 0x5B, 0xDE, 0xAE, + 0xAC, 0xA3, 0xA5, 0xB7, 0xA9, 0xA7, 0xB6, 0xBC, 0xBD, 0xBE, 0xDD, 0xA8, 0xAF, 0x5D, 0xB4, 0xD7, + 0x7B, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0xAD, 0xF4, 0xF6, 0xF2, 0xF3, 0xF5, + 0x7D, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0xB9, 0xFB, 0xFC, 0xF9, 0xFA, 0xFF, + 0x5C, 0xF7, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0xB2, 0xD4, 0xD6, 0xD2, 0xD3, 0xD5, + 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0xB3, 0xDB, 0xDC, 0xD9, 0xDA, 0x9F}; +#define decode ENCODE_TO_ASCII(ch) convert_e2a[(unsigned char)ch] +#define decode ENCODE_TO_NATIVE(ch) convert_a2e[(unsigned char)ch] +#else /* APR_CHARSET_EBCDIC */ +#define ENCODE_TO_ASCII(ch) (ch) +#define ENCODE_TO_NATIVE(ch) (ch) +#endif /* !APR_CHARSET_EBCDIC */ + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ENCODE_PRIVATE_H */ diff --git a/c/dependencies/windows/apr/x86/include/private/apu_config.h b/c/dependencies/windows/apr/x86/include/private/apu_config.h new file mode 100644 index 00000000..b0e20393 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/private/apu_config.h @@ -0,0 +1,52 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Note: This is a Windows specific version of apu_config.hw. It is copied + * as apu_config.h at the start of a Windows build. + */ + +#ifdef WIN32 + +#ifndef APU_CONFIG_H +#define APU_CONFIG_H + +/* Compile win32 with DSO support for .dll builds */ +#ifdef APU_DECLARE_STATIC +#define APU_DSO_BUILD 0 +#else +#define APU_DSO_BUILD 1 +#endif + +/* Presume a standard, modern (5.x) mysql sdk/ +#define HAVE_MY_GLOBAL_H 1 + +/* my_sys.h is broken on VC/Win32, and apparently not required */ +/* #undef HAVE_MY_SYS_H 0 */ + +/* + * Windows does not have GDBM, and we always use the bundled (new) Expat + */ + +/* Define if you have the gdbm library (-lgdbm). */ +/* #undef HAVE_LIBGDBM */ + +/* define if Expat 1.0 or 1.1 was found */ +/* #undef APR_HAVE_OLD_EXPAT */ + + +#endif /* APU_CONFIG_H */ +#endif /* WIN32 */ diff --git a/c/dependencies/windows/apr/x86/include/private/apu_config.hnw b/c/dependencies/windows/apr/x86/include/private/apu_config.hnw new file mode 100644 index 00000000..c7a6124b --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/private/apu_config.hnw @@ -0,0 +1,53 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Note: This is a NetWare specific version of apu_config.hnw. It is copied + * as apu_config.h at the start of a NetWare build. + */ + +#ifdef NETWARE + +#ifndef APU_CONFIG_H +#define APU_CONFIG_H + +/* Always compile Netware with DSO support for .nlm builds */ +#define APU_DSO_BUILD 0 + +/* + * NetWare does not have GDBM, and we always use the bundled (new) Expat + */ + +/* Define if you have the gdbm library (-lgdbm). */ +/* #undef HAVE_LIBGDBM */ + +/* define if Expat 1.0 or 1.1 was found */ +/* #undef APR_HAVE_OLD_EXPAT */ + +/* NetWare uses its own ICONV implementation. */ +#define HAVE_ICONV_H 1 + +/* + * check for newer NDKs which use now correctly 'const char*' with iconv. + */ +#include +#if (CURRENT_NDK_THRESHOLD >= 705110000) +#define APU_ICONV_INBUF_CONST +#endif + +#endif /* APU_CONFIG_H */ +#endif /* NETWARE */ + diff --git a/c/dependencies/windows/apr/x86/include/private/apu_config.hw b/c/dependencies/windows/apr/x86/include/private/apu_config.hw new file mode 100644 index 00000000..ac262fcb --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/private/apu_config.hw @@ -0,0 +1,52 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Note: This is a Windows specific version of apu_config.hw. It is copied + * as apu_config.h at the start of a Windows build. + */ + +#ifdef WIN32 + +#ifndef APU_CONFIG_H +#define APU_CONFIG_H + +/* Compile win32 with DSO support for .dll builds */ +#ifdef APU_DECLARE_STATIC +#define APU_DSO_BUILD 0 +#else +#define APU_DSO_BUILD 1 +#endif + +/* Presume a standard, modern (5.x) mysql sdk/ +#define HAVE_MY_GLOBAL_H 1 + +/* my_sys.h is broken on VC/Win32, and apparently not required */ +/* #undef HAVE_MY_SYS_H 0 */ + +/* + * Windows does not have GDBM, and we always use the bundled (new) Expat + */ + +/* Define if you have the gdbm library (-lgdbm). */ +/* #undef HAVE_LIBGDBM */ + +/* define if Expat 1.0 or 1.1 was found */ +/* #undef APR_HAVE_OLD_EXPAT */ + + +#endif /* APU_CONFIG_H */ +#endif /* WIN32 */ diff --git a/c/dependencies/windows/apr/x86/include/private/apu_internal.h b/c/dependencies/windows/apr/x86/include/private/apu_internal.h new file mode 100644 index 00000000..c95c9d50 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/private/apu_internal.h @@ -0,0 +1,73 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr.h" +#include "apr_dso.h" +#include "apu.h" + +#ifndef APU_INTERNAL_H +#define APU_INTERNAL_H + +#if APU_DSO_BUILD + +#ifdef __cplusplus +extern "C" { +#endif + +/* For modular dso loading, an internal interlock to allow us to + * continue to initialize modules by multiple threads, the caller + * of apu_dso_load must lock first, and not unlock until any init + * finalization is complete. + */ +apr_status_t apu_dso_init(apr_pool_t *pool); + +apr_status_t apu_dso_mutex_lock(void); +apr_status_t apu_dso_mutex_unlock(void); + +apr_status_t apu_dso_load(apr_dso_handle_t **dso, apr_dso_handle_sym_t *dsoptr, const char *module, + const char *modsym, apr_pool_t *pool); + +#if APR_HAS_LDAP + +/* For LDAP internal builds, wrap our LDAP namespace */ + +struct apr__ldap_dso_fntable { + int (*info)(apr_pool_t *pool, apr_ldap_err_t **result_err); + int (*init)(apr_pool_t *pool, LDAP **ldap, const char *hostname, + int portno, int secure, apr_ldap_err_t **result_err); + int (*ssl_init)(apr_pool_t *pool, const char *cert_auth_file, + int cert_file_type, apr_ldap_err_t **result_err); + int (*ssl_deinit)(void); + int (*get_option)(apr_pool_t *pool, LDAP *ldap, int option, + void *outvalue, apr_ldap_err_t **result_err); + int (*set_option)(apr_pool_t *pool, LDAP *ldap, int option, + const void *invalue, apr_ldap_err_t **result_err); + apr_status_t (*rebind_init)(apr_pool_t *pool); + apr_status_t (*rebind_add)(apr_pool_t *pool, LDAP *ld, + const char *bindDN, const char *bindPW); + apr_status_t (*rebind_remove)(LDAP *ld); +}; + +#endif /* APR_HAS_LDAP */ + +#ifdef __cplusplus +} +#endif + +#endif /* APU_DSO_BUILD */ + +#endif /* APU_INTERNAL_H */ + diff --git a/c/dependencies/windows/apr/x86/include/private/apu_select_dbm.h b/c/dependencies/windows/apr/x86/include/private/apu_select_dbm.h new file mode 100644 index 00000000..97c7b6c2 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/private/apu_select_dbm.h @@ -0,0 +1,28 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APU_SELECT_DBM_H +#define APU_SELECT_DBM_H + +/* +** The following macros control what features APRUTIL will use +*/ +#define APU_USE_SDBM 1 +#define APU_USE_GDBM 0 +#define APU_USE_NDBM 0 +#define APU_USE_DB 0 + +#endif /* !APU_SELECT_DBM_H */ diff --git a/c/dependencies/windows/apr/x86/include/private/apu_select_dbm.h.in b/c/dependencies/windows/apr/x86/include/private/apu_select_dbm.h.in new file mode 100644 index 00000000..d66be5fc --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/private/apu_select_dbm.h.in @@ -0,0 +1,28 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APU_SELECT_DBM_H +#define APU_SELECT_DBM_H + +/* +** The following macros control what features APRUTIL will use +*/ +#define APU_USE_SDBM @apu_use_sdbm@ +#define APU_USE_NDBM @apu_use_ndbm@ +#define APU_USE_GDBM @apu_use_gdbm@ +#define APU_USE_DB @apu_use_db@ + +#endif /* !APU_SELECT_DBM_H */ diff --git a/c/dependencies/windows/apr/x86/include/private/apu_select_dbm.hw b/c/dependencies/windows/apr/x86/include/private/apu_select_dbm.hw new file mode 100644 index 00000000..baa6c144 --- /dev/null +++ b/c/dependencies/windows/apr/x86/include/private/apu_select_dbm.hw @@ -0,0 +1,28 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APU_SELECT_DBM_H +#define APU_SELECT_DBM_H + +/* +** The following macros control what features APRUTIL will use +*/ +#define APU_USE_SDBM 1 +#define APU_USE_GDBM 0 +#define APU_USE_NDBM 0 +#define APU_USE_DB 0 + +#endif /* !APU_SELECT_DBM_H */ diff --git a/c/dependencies/windows/apr/x86/lib/apr.lib b/c/dependencies/windows/apr/x86/lib/apr.lib new file mode 100644 index 00000000..104aee51 Binary files /dev/null and b/c/dependencies/windows/apr/x86/lib/apr.lib differ diff --git a/c/dependencies/windows/apr/x86/lib/apr.pdb b/c/dependencies/windows/apr/x86/lib/apr.pdb new file mode 100644 index 00000000..e0936be5 Binary files /dev/null and b/c/dependencies/windows/apr/x86/lib/apr.pdb differ diff --git a/c/dependencies/windows/apr/x86/lib/aprapp.lib b/c/dependencies/windows/apr/x86/lib/aprapp.lib new file mode 100644 index 00000000..9c596142 Binary files /dev/null and b/c/dependencies/windows/apr/x86/lib/aprapp.lib differ diff --git a/c/dependencies/windows/apr/x86/lib/aprapp.pdb b/c/dependencies/windows/apr/x86/lib/aprapp.pdb new file mode 100644 index 00000000..1daab57c Binary files /dev/null and b/c/dependencies/windows/apr/x86/lib/aprapp.pdb differ diff --git a/c/dependencies/windows/apr/x86/lib/apriconv.lib b/c/dependencies/windows/apr/x86/lib/apriconv.lib new file mode 100644 index 00000000..63e4ccb1 Binary files /dev/null and b/c/dependencies/windows/apr/x86/lib/apriconv.lib differ diff --git a/c/dependencies/windows/apr/x86/lib/apriconv.pdb b/c/dependencies/windows/apr/x86/lib/apriconv.pdb new file mode 100644 index 00000000..0a8cf5fc Binary files /dev/null and b/c/dependencies/windows/apr/x86/lib/apriconv.pdb differ diff --git a/c/dependencies/windows/apr/x86/lib/aprutil.lib b/c/dependencies/windows/apr/x86/lib/aprutil.lib new file mode 100644 index 00000000..cfa21fd5 Binary files /dev/null and b/c/dependencies/windows/apr/x86/lib/aprutil.lib differ diff --git a/c/dependencies/windows/apr/x86/lib/aprutil.pdb b/c/dependencies/windows/apr/x86/lib/aprutil.pdb new file mode 100644 index 00000000..021a6d3f Binary files /dev/null and b/c/dependencies/windows/apr/x86/lib/aprutil.pdb differ diff --git a/c/dependencies/windows/apr/x86/lib/libapr.lib b/c/dependencies/windows/apr/x86/lib/libapr.lib new file mode 100644 index 00000000..e7e520f5 Binary files /dev/null and b/c/dependencies/windows/apr/x86/lib/libapr.lib differ diff --git a/c/dependencies/windows/apr/x86/lib/libapr.pdb b/c/dependencies/windows/apr/x86/lib/libapr.pdb new file mode 100644 index 00000000..18ccfe4e Binary files /dev/null and b/c/dependencies/windows/apr/x86/lib/libapr.pdb differ diff --git a/c/dependencies/windows/apr/x86/lib/libapr_src.pdb b/c/dependencies/windows/apr/x86/lib/libapr_src.pdb new file mode 100644 index 00000000..f8ec31d5 Binary files /dev/null and b/c/dependencies/windows/apr/x86/lib/libapr_src.pdb differ diff --git a/c/dependencies/windows/apr/x86/lib/libaprapp.lib b/c/dependencies/windows/apr/x86/lib/libaprapp.lib new file mode 100644 index 00000000..f0056e05 Binary files /dev/null and b/c/dependencies/windows/apr/x86/lib/libaprapp.lib differ diff --git a/c/dependencies/windows/apr/x86/lib/libaprapp.pdb b/c/dependencies/windows/apr/x86/lib/libaprapp.pdb new file mode 100644 index 00000000..61a9765c Binary files /dev/null and b/c/dependencies/windows/apr/x86/lib/libaprapp.pdb differ diff --git a/c/dependencies/windows/apr/x86/lib/libapriconv.lib b/c/dependencies/windows/apr/x86/lib/libapriconv.lib new file mode 100644 index 00000000..18512b3a Binary files /dev/null and b/c/dependencies/windows/apr/x86/lib/libapriconv.lib differ diff --git a/c/dependencies/windows/apr/x86/lib/libapriconv.pdb b/c/dependencies/windows/apr/x86/lib/libapriconv.pdb new file mode 100644 index 00000000..4669fc12 Binary files /dev/null and b/c/dependencies/windows/apr/x86/lib/libapriconv.pdb differ diff --git a/c/dependencies/windows/apr/x86/lib/libapriconv_src.pdb b/c/dependencies/windows/apr/x86/lib/libapriconv_src.pdb new file mode 100644 index 00000000..22154110 Binary files /dev/null and b/c/dependencies/windows/apr/x86/lib/libapriconv_src.pdb differ diff --git a/c/dependencies/windows/apr/x86/lib/libaprutil.lib b/c/dependencies/windows/apr/x86/lib/libaprutil.lib new file mode 100644 index 00000000..64b83fbf Binary files /dev/null and b/c/dependencies/windows/apr/x86/lib/libaprutil.lib differ diff --git a/c/dependencies/windows/apr/x86/lib/libaprutil.pdb b/c/dependencies/windows/apr/x86/lib/libaprutil.pdb new file mode 100644 index 00000000..0b69c244 Binary files /dev/null and b/c/dependencies/windows/apr/x86/lib/libaprutil.pdb differ diff --git a/c/dependencies/windows/apr/x86/lib/libaprutil_src.pdb b/c/dependencies/windows/apr/x86/lib/libaprutil_src.pdb new file mode 100644 index 00000000..801ae626 Binary files /dev/null and b/c/dependencies/windows/apr/x86/lib/libaprutil_src.pdb differ diff --git a/c/dependencies/windows/apr/x86_debug/include/api_version.h b/c/dependencies/windows/apr/x86_debug/include/api_version.h new file mode 100644 index 00000000..c2788959 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/api_version.h @@ -0,0 +1,132 @@ +/* Copyright 2000-2017 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef API_VERSION_H +#define API_VERSION_H + +/** + * @file api_version.h + * @brief APR-iconv Versioning Interface + * + * APR-iconv's Version + * + * There are several different mechanisms for accessing the version. There + * is a string form, and a set of numbers; in addition, there are constants + * which can be compiled into your application, and you can query the library + * being used for its actual version. + * + * Note that it is possible for an application to detect that it has been + * compiled against a different version of API by use of the compile-time + * constants and the use of the run-time query function. + * + * API version numbering follows the guidelines specified in: + * + * http://apr.apache.org/versioning.html + */ + + +/* The numeric compile-time version constants. These constants are the + * authoritative version numbers for API. + */ + +/** major version + * Major API changes that could cause compatibility problems for older + * programs such as structure size changes. No binary compatibility is + * possible across a change in the major version. + */ +#define API_MAJOR_VERSION 1 + +/** minor version + * Minor API changes that do not cause binary compatibility problems. + * Reset to 0 when upgrading API_MAJOR_VERSION + */ +#define API_MINOR_VERSION 2 + +/** patch level + * The Patch Level never includes API changes, simply bug fixes. + * Reset to 0 when upgrading API_MINOR_VERSION + */ +#define API_PATCH_VERSION 2 + +/** + * The symbol API_IS_DEV_VERSION is only defined for internal, + * "development" copies of API. It is undefined for released versions + * of API. + */ +/* #undef API_IS_DEV_VERSION */ + + +#if defined(API_IS_DEV_VERSION) || defined(DOXYGEN) +/** Internal: string form of the "is dev" flag */ +#define API_IS_DEV_STRING "-dev" +#else +#define API_IS_DEV_STRING "" +#endif + +#ifndef API_STRINGIFY +/** Properly quote a value as a string in the C preprocessor */ +#define API_STRINGIFY(n) API_STRINGIFY_HELPER(n) +/** Helper macro for API_STRINGIFY */ +#define API_STRINGIFY_HELPER(n) #n +#endif + +/** The formatted string of API's version */ +#define API_VERSION_STRING \ + API_STRINGIFY(API_MAJOR_VERSION) "." \ + API_STRINGIFY(API_MINOR_VERSION) "." \ + API_STRINGIFY(API_PATCH_VERSION) \ + API_IS_DEV_STRING + +/** An alternative formatted string of APR's version */ +/* macro for Win32 .rc files using numeric csv representation */ +#define API_VERSION_STRING_CSV API_MAJOR_VERSION ##, \ + ##API_MINOR_VERSION ##, \ + ##API_PATCH_VERSION + + +#ifndef API_VERSION_ONLY + +/* The C language API to access the version at run time, + * as opposed to compile time. API_VERSION_ONLY may be defined + * externally when preprocessing apr_version.h to obtain strictly + * the C Preprocessor macro declarations. + */ + +#include "apr_version.h" + +#include "apr_iconv.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Return APR-iconv's version information information in a numeric form. + * + * @param pvsn Pointer to a version structure for returning the version + * information. + */ +API_DECLARE(void) api_version(apr_version_t *pvsn); + +/** Return API's version information as a string. */ +API_DECLARE(const char *) api_version_string(void); + +#ifdef __cplusplus +} +#endif + +#endif /* ndef API_VERSION_ONLY */ + +#endif /* ndef API_VERSION_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr.h b/c/dependencies/windows/apr/x86_debug/include/apr.h new file mode 100644 index 00000000..3352fef3 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr.h @@ -0,0 +1,667 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef APR_H +#define APR_H + +/* GENERATED FILE WARNING! DO NOT EDIT apr.h + * + * You must modify apr.hw instead. + * + * And please, make an effort to stub apr.hnw and apr.h.in in the process. + * + * This is the Win32 specific version of apr.h. It is copied from + * apr.hw by the apr.dsp and libapr.dsp projects. + */ + +/** + * @file apr.h + * @brief APR Platform Definitions + * @remark This is a generated header generated from include/apr.h.in by + * ./configure, or copied from include/apr.hw or include/apr.hnw + * for Win32 or Netware by those build environments, respectively. + */ + +/* Make sure we have our platform identifier macro defined we ask for later. + */ +#if defined(_WIN32) && !defined(WIN32) +#define WIN32 1 +#endif + +#if defined(WIN32) || defined(DOXYGEN) + +/* Ignore most warnings (back down to /W3) for poorly constructed headers + */ +#if defined(_MSC_VER) && _MSC_VER >= 1200 +#pragma warning(push, 3) +#endif + +/* disable or reduce the frequency of... + * C4057: indirection to slightly different base types + * C4075: slight indirection changes (unsigned short* vs short[]) + * C4100: unreferenced formal parameter + * C4127: conditional expression is constant + * C4163: '_rotl64' : not available as an intrinsic function + * C4201: nonstandard extension nameless struct/unions + * C4244: int to char/short - precision loss + * C4514: unreferenced inline function removed + */ +#if defined(_MSC_VER) +#pragma warning(disable: 4100 4127 4163 4201 4514; once: 4057 4075 4244) +#endif + +/* Ignore Microsoft's interpretation of secure development + * and the POSIX string handling API + */ +#if defined(_MSC_VER) && _MSC_VER >= 1400 +#ifndef _CRT_SECURE_NO_DEPRECATE +#define _CRT_SECURE_NO_DEPRECATE +#endif +#pragma warning(disable: 4996) +#endif + +/* Has windows.h already been included? If so, our preferences don't matter, + * but we will still need the winsock things no matter what was included. + * If not, include a restricted set of windows headers to our tastes. + */ +#ifndef _WINDOWS_ +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef _WIN32_WINNT + +/* Restrict the server to a subset of Windows XP header files by default + */ +#define _WIN32_WINNT 0x0A00 +#endif +#ifndef NOUSER +#define NOUSER +#endif +#ifndef NOMCX +#define NOMCX +#endif +#ifndef NOIME +#define NOIME +#endif +#include +/* + * Add a _very_few_ declarations missing from the restricted set of headers + * (If this list becomes extensive, re-enable the required headers above!) + * winsock headers were excluded by WIN32_LEAN_AND_MEAN, so include them now + */ +#define SW_HIDE 0 +#ifndef _WIN32_WCE +#include +#include +#include +#else +#include +#endif +#endif /* !_WINDOWS_ */ + +/** + * @defgroup APR Apache Portability Runtime library + * @{ + */ +/** + * @defgroup apr_platform Platform Definitions + * @{ + * @warning + * The actual values of macros and typedefs on this page
+ * are platform specific and should NOT be relied upon!
+ */ + +#define APR_INLINE __inline +#define APR_HAS_INLINE 1 +#if !defined(__GNUC__) && !defined(__attribute__) +#define __attribute__(__x) +#endif + +#ifndef _WIN32_WCE +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_CONIO_H 1 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 1 +#define APR_HAVE_DIRENT_H 0 +#define APR_HAVE_ERRNO_H 1 +#define APR_HAVE_FCNTL_H 1 +#define APR_HAVE_IO_H 1 +#define APR_HAVE_LIMITS_H 1 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SEMAPHORE_H 0 +#define APR_HAVE_SIGNAL_H 1 +#define APR_HAVE_STDARG_H 1 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_SYS_IOCTL_H 0 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SIGNAL_H 0 +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#define APR_HAVE_SYS_TIME_H 0 +#define APR_HAVE_SYS_TYPES_H 1 +#define APR_HAVE_SYS_UIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#define APR_HAVE_SYS_WAIT_H 0 +#define APR_HAVE_TIME_H 1 +#define APR_HAVE_UNISTD_H 0 +#define APR_HAVE_STDDEF_H 1 +#define APR_HAVE_PROCESS_H 1 +#else +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_CONIO_H 0 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 0 +#define APR_HAVE_DIRENT_H 0 +#define APR_HAVE_ERRNO_H 0 +#define APR_HAVE_FCNTL_H 0 +#define APR_HAVE_IO_H 0 +#define APR_HAVE_LIMITS_H 0 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SEMAPHORE_H 0 +#define APR_HAVE_SIGNAL_H 0 +#define APR_HAVE_STDARG_H 0 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_SYS_IOCTL_H 0 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SIGNAL_H 0 +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#define APR_HAVE_SYS_TIME_H 0 +#define APR_HAVE_SYS_TYPES_H 0 +#define APR_HAVE_SYS_UIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#define APR_HAVE_SYS_WAIT_H 0 +#define APR_HAVE_TIME_H 0 +#define APR_HAVE_UNISTD_H 0 +#define APR_HAVE_STDDEF_H 0 +#define APR_HAVE_PROCESS_H 0 +#endif + +/** @} */ +/** @} */ + +/* We don't include our conditional headers within the doxyblocks + * or the extern "C" namespace + */ + +#if APR_HAVE_STDLIB_H +#include +#endif + +#if APR_HAVE_STDIO_H +#include +#endif + +#if APR_HAVE_SYS_TYPES_H +#include +#endif + +#if APR_HAVE_STDDEF_H +#include +#endif + +#if APR_HAVE_SYS_SOCKET_H +#include +#endif + +#if APR_HAVE_STDINT_H +#include +#endif + +#if APR_HAVE_SYS_WAIT_H +#include +#endif + +#if APR_HAVE_TIME_H +#include +#endif + +#if APR_HAVE_PROCESS_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @addtogroup apr_platform + * @ingroup APR + * @{ + */ + +#define APR_HAVE_SHMEM_MMAP_TMP 0 +#define APR_HAVE_SHMEM_MMAP_SHM 0 +#define APR_HAVE_SHMEM_MMAP_ZERO 0 +#define APR_HAVE_SHMEM_SHMGET_ANON 0 +#define APR_HAVE_SHMEM_SHMGET 0 +#define APR_HAVE_SHMEM_MMAP_ANON 0 +#define APR_HAVE_SHMEM_BEOS 0 + +#define APR_USE_SHMEM_MMAP_TMP 0 +#define APR_USE_SHMEM_MMAP_SHM 0 +#define APR_USE_SHMEM_MMAP_ZERO 0 +#define APR_USE_SHMEM_SHMGET_ANON 0 +#define APR_USE_SHMEM_SHMGET 0 +#define APR_USE_SHMEM_MMAP_ANON 0 +#define APR_USE_SHMEM_BEOS 0 + +#define APR_USE_FLOCK_SERIALIZE 0 +#define APR_USE_POSIXSEM_SERIALIZE 0 +#define APR_USE_SYSVSEM_SERIALIZE 0 +#define APR_USE_FCNTL_SERIALIZE 0 +#define APR_USE_PROC_PTHREAD_SERIALIZE 0 +#define APR_USE_PTHREAD_SERIALIZE 0 + +#define APR_HAS_FLOCK_SERIALIZE 0 +#define APR_HAS_SYSVSEM_SERIALIZE 0 +#define APR_HAS_POSIXSEM_SERIALIZE 0 +#define APR_HAS_FCNTL_SERIALIZE 0 +#define APR_HAS_PROC_PTHREAD_SERIALIZE 0 + +#define APR_PROCESS_LOCK_IS_GLOBAL 0 + +#define APR_HAVE_CORKABLE_TCP 0 +#define APR_HAVE_GETRLIMIT 0 +#define APR_HAVE_ICONV 0 +#define APR_HAVE_IN_ADDR 1 +#define APR_HAVE_INET_ADDR 1 +#define APR_HAVE_INET_NETWORK 0 +#define APR_HAVE_IPV6 1 +#define APR_HAVE_SOCKADDR_UN 0 +#define APR_HAVE_MEMMOVE 1 +#define APR_HAVE_SETRLIMIT 0 +#define APR_HAVE_SIGACTION 0 +#define APR_HAVE_SIGSUSPEND 0 +#define APR_HAVE_SIGWAIT 0 +#define APR_HAVE_SA_STORAGE 0 +#define APR_HAVE_STRCASECMP 0 +#define APR_HAVE_STRDUP 1 +#define APR_HAVE_STRNCASECMP 0 +#define APR_HAVE_STRSTR 1 +#define APR_HAVE_MEMCHR 1 +#define APR_HAVE_STRUCT_RLIMIT 0 +#define APR_HAVE_UNION_SEMUN 0 +#define APR_HAVE_SCTP 0 +#define APR_HAVE_IOVEC 0 + +#ifndef _WIN32_WCE +#define APR_HAVE_STRICMP 1 +#define APR_HAVE_STRNICMP 1 +#else +#define APR_HAVE_STRICMP 0 +#define APR_HAVE_STRNICMP 0 +#endif + +/* APR Feature Macros */ +#define APR_HAS_SHARED_MEMORY 1 +#define APR_HAS_THREADS 1 +#define APR_HAS_MMAP 1 +#define APR_HAS_FORK 0 +#define APR_HAS_RANDOM 1 +#define APR_HAS_OTHER_CHILD 1 +#define APR_HAS_DSO 1 +#define APR_HAS_SO_ACCEPTFILTER 0 +#define APR_HAS_UNICODE_FS 1 +#define APR_HAS_PROC_INVOKED 1 +#define APR_HAS_OS_UUID 1 +#define APR_HAS_TIMEDLOCKS 1 + +#ifndef _WIN32_WCE +#define APR_HAS_SENDFILE 1 +#define APR_HAS_USER 1 +#define APR_HAS_LARGE_FILES 1 +#define APR_HAS_XTHREAD_FILES 1 +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 1 +#else +#define APR_HAS_SENDFILE 0 +#define APR_HAS_USER 0 +#define APR_HAS_LARGE_FILES 0 +#define APR_HAS_XTHREAD_FILES 0 +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 0 +#endif + +/* APR sets APR_FILES_AS_SOCKETS to 1 on systems where it is possible + * to poll on files/pipes. + */ +#define APR_FILES_AS_SOCKETS 0 + +/* This macro indicates whether or not EBCDIC is the native character set. + */ +#define APR_CHARSET_EBCDIC 0 + +/* If we have a TCP implementation that can be "corked", what flag + * do we use? + */ +#define APR_TCP_NOPUSH_FLAG @apr_tcp_nopush_flag@ + +/* Is the TCP_NODELAY socket option inherited from listening sockets? + */ +#define APR_TCP_NODELAY_INHERITED 1 + +/* Is the O_NONBLOCK flag inherited from listening sockets? + */ +#define APR_O_NONBLOCK_INHERITED 1 + +/* Typedefs that APR needs. */ + +typedef unsigned char apr_byte_t; + +typedef short apr_int16_t; +typedef unsigned short apr_uint16_t; + +typedef int apr_int32_t; +typedef unsigned int apr_uint32_t; + +typedef __int64 apr_int64_t; +typedef unsigned __int64 apr_uint64_t; + +typedef size_t apr_size_t; +#if APR_HAVE_STDDEF_H +typedef ptrdiff_t apr_ssize_t; +#else +typedef int apr_ssize_t; +#endif +#if APR_HAS_LARGE_FILES +typedef __int64 apr_off_t; +#else +typedef int apr_off_t; +#endif +typedef int apr_socklen_t; +typedef apr_uint64_t apr_ino_t; + +#ifdef _WIN64 +#define APR_SIZEOF_VOIDP 8 +#else +#define APR_SIZEOF_VOIDP 4 +#endif + +#if APR_SIZEOF_VOIDP == 8 +typedef apr_uint64_t apr_uintptr_t; +#else +typedef apr_uint32_t apr_uintptr_t; +#endif + +/* Are we big endian? */ +/* XXX: Fatal assumption on Alpha platforms */ +#define APR_IS_BIGENDIAN 0 + +/* Mechanisms to properly type numeric literals */ + +#ifndef __GNUC__ +#define APR_INT64_C(val) (val##i64) +#define APR_UINT64_C(val) (val##Ui64) +#else +#define APR_INT64_C(val) (val##LL) +#define APR_UINT64_C(val) (val##ULL) +#endif + +#ifdef INT16_MIN +#define APR_INT16_MIN INT16_MIN +#else +#define APR_INT16_MIN (-0x7fff - 1) +#endif + +#ifdef INT16_MAX +#define APR_INT16_MAX INT16_MAX +#else +#define APR_INT16_MAX (0x7fff) +#endif + +#ifdef UINT16_MAX +#define APR_UINT16_MAX UINT16_MAX +#else +#define APR_UINT16_MAX (0xffff) +#endif + +#ifdef INT32_MIN +#define APR_INT32_MIN INT32_MIN +#else +#define APR_INT32_MIN (-0x7fffffff - 1) +#endif + +#ifdef INT32_MAX +#define APR_INT32_MAX INT32_MAX +#else +#define APR_INT32_MAX 0x7fffffff +#endif + +#ifdef UINT32_MAX +#define APR_UINT32_MAX UINT32_MAX +#else +#define APR_UINT32_MAX (0xffffffffU) +#endif + +#ifdef INT64_MIN +#define APR_INT64_MIN INT64_MIN +#else +#define APR_INT64_MIN (APR_INT64_C(-0x7fffffffffffffff) - 1) +#endif + +#ifdef INT64_MAX +#define APR_INT64_MAX INT64_MAX +#else +#define APR_INT64_MAX APR_INT64_C(0x7fffffffffffffff) +#endif + +#ifdef UINT64_MAX +#define APR_UINT64_MAX UINT64_MAX +#else +#define APR_UINT64_MAX APR_UINT64_C(0xffffffffffffffff) +#endif + +#define APR_SIZE_MAX (~((apr_size_t)0)) + +/* Definitions that APR programs need to work properly. */ + +/** + * APR public API wrap for C++ compilers. + */ +#ifdef __cplusplus +#define APR_BEGIN_DECLS extern "C" { +#define APR_END_DECLS } +#else +#define APR_BEGIN_DECLS +#define APR_END_DECLS +#endif + +/** + * Thread callbacks from APR functions must be declared with APR_THREAD_FUNC, + * so that they follow the platform's calling convention. + *
+ *
+ * void* APR_THREAD_FUNC my_thread_entry_fn(apr_thread_t *thd, void *data);
+ *
+ * 
+ */ +#define APR_THREAD_FUNC __stdcall + + +#if defined(DOXYGEN) || !defined(WIN32) + +/** + * The public APR functions are declared with APR_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APR_DECLARE_NONSTD(). + * + * @remark Both the declaration and implementations must use the same macro. + * + *
+ * APR_DECLARE(rettype) apr_func(args)
+ * 
+ * @see APR_DECLARE_NONSTD @see APR_DECLARE_DATA + * @remark Note that when APR compiles the library itself, it passes the + * symbol -DAPR_DECLARE_EXPORT to the compiler on some platforms (e.g. Win32) + * to export public symbols from the dynamic library build.\n + * The user must define the APR_DECLARE_STATIC when compiling to target + * the static APR library on some platforms (e.g. Win32.) The public symbols + * are neither exported nor imported when APR_DECLARE_STATIC is defined.\n + * By default, compiling an application and including the APR public + * headers, without defining APR_DECLARE_STATIC, will prepare the code to be + * linked to the dynamic library. + */ +#define APR_DECLARE(type) type + +/** + * The public APR functions using variable arguments are declared with + * APR_DECLARE_NONSTD(), as they must follow the C language calling convention. + * @see APR_DECLARE @see APR_DECLARE_DATA + * @remark Both the declaration and implementations must use the same macro. + *
+ *
+ * APR_DECLARE_NONSTD(rettype) apr_func(args, ...);
+ *
+ * 
+ */ +#define APR_DECLARE_NONSTD(type) type + +/** + * The public APR variables are declared with AP_MODULE_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * @see APR_DECLARE @see APR_DECLARE_NONSTD + * @remark Note that the declaration and implementations use different forms, + * but both must include the macro. + * + *
+ *
+ * extern APR_DECLARE_DATA type apr_variable;\n
+ * APR_DECLARE_DATA type apr_variable = value;
+ *
+ * 
+ */ +#define APR_DECLARE_DATA + +#elif defined(APR_DECLARE_STATIC) +#define APR_DECLARE(type) type __stdcall +#define APR_DECLARE_NONSTD(type) type __cdecl +#define APR_DECLARE_DATA +#elif defined(APR_DECLARE_EXPORT) +#define APR_DECLARE(type) __declspec(dllexport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllexport) +#else +#define APR_DECLARE(type) __declspec(dllimport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllimport) +#endif + +#ifdef _WIN64 +#define APR_SSIZE_T_FMT "I64d" +#define APR_SIZE_T_FMT "I64u" +#else +#define APR_SSIZE_T_FMT "d" +#define APR_SIZE_T_FMT "u" +#endif + +#if APR_HAS_LARGE_FILES +#define APR_OFF_T_FMT "I64d" +#else +#define APR_OFF_T_FMT "d" +#endif + +#define APR_PID_T_FMT "d" + +#define APR_INT64_T_FMT "I64d" +#define APR_UINT64_T_FMT "I64u" +#define APR_UINT64_T_HEX_FMT "I64x" + +/* No difference between PROC and GLOBAL mutex */ +#define APR_PROC_MUTEX_IS_GLOBAL 1 + +/* Local machine definition for console and log output. */ +#define APR_EOL_STR "\r\n" + +typedef int apr_wait_t; + +#if APR_HAS_UNICODE_FS +/* An arbitrary size that is digestable. True max is a bit less than 32000 */ +#define APR_PATH_MAX 8192 +#else /* !APR_HAS_UNICODE_FS */ +#define APR_PATH_MAX MAX_PATH +#endif + +#define APR_DSOPATH "PATH" + +/** @} */ + +/* Definitions that only Win32 programs need to compile properly. */ + +/* XXX These simply don't belong here, perhaps in apr_portable.h + * based on some APR_HAVE_PID/GID/UID? + */ +#ifndef __GNUC__ +typedef int pid_t; +#endif +typedef int uid_t; +typedef int gid_t; + +/* Win32 .h ommissions we really need */ +#define STDIN_FILENO 0 +#define STDOUT_FILENO 1 +#define STDERR_FILENO 2 + +#if APR_HAVE_IPV6 + +/* Appears in later flavors, not the originals. */ +#ifndef in_addr6 +#define in6_addr in_addr6 +#endif + +#ifndef WS2TCPIP_INLINE +#define IN6_IS_ADDR_V4MAPPED(a) \ + ( (*(const apr_uint64_t *)(const void *)(&(a)->s6_addr[0]) == 0) \ + && (*(const apr_uint32_t *)(const void *)(&(a)->s6_addr[8]) == ntohl(0x0000ffff))) +#endif + +#endif /* APR_HAVE_IPV6 */ + +#ifdef __cplusplus +} +#endif + +/* Done with badly written headers, leave 'deprecated CRT' undeprecated + */ +#if defined(_MSC_VER) && _MSC_VER >= 1200 +#pragma warning(pop) +#if _MSC_VER >= 1400 +#pragma warning(disable: 4996) +#endif +#endif + +#endif /* WIN32 */ + +#endif /* APR_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr.h.in b/c/dependencies/windows/apr/x86_debug/include/apr.h.in new file mode 100644 index 00000000..47d8b55a --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr.h.in @@ -0,0 +1,656 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef APR_H +#define APR_H + +/* GENERATED FILE WARNING! DO NOT EDIT apr.h + * + * You must modify apr.h.in instead. + * + * And please, make an effort to stub apr.hw and apr.hnw in the process. + */ + +/** + * @file apr.h + * @brief APR Platform Definitions + * @remark This is a generated header generated from include/apr.h.in by + * ./configure, or copied from include/apr.hw or include/apr.hnw + * for Win32 or Netware by those build environments, respectively. + */ + +/** + * @defgroup APR Apache Portability Runtime library + * @{ + */ +/** + * @defgroup apr_platform Platform Definitions + * @{ + * @warning + * The actual values of macros and typedefs on this page
+ * are platform specific and should NOT be relied upon!
+ */ + +/* So that we can use inline on some critical functions, and use + * GNUC attributes (such as to get -Wall warnings for printf-like + * functions). Only do this in gcc 2.7 or later ... it may work + * on earlier stuff, but why chance it. + * + * We've since discovered that the gcc shipped with NeXT systems + * as "cc" is completely broken. It claims to be __GNUC__ and so + * on, but it doesn't implement half of the things that __GNUC__ + * means. In particular it's missing inline and the __attribute__ + * stuff. So we hack around it. PR#1613. -djg + */ +#if !defined(__GNUC__) || __GNUC__ < 2 || \ + (__GNUC__ == 2 && __GNUC_MINOR__ < 7) ||\ + defined(NEXT) +#ifndef __attribute__ +#define __attribute__(__x) +#endif +#define APR_INLINE +#define APR_HAS_INLINE 0 +#else +#define APR_INLINE __inline__ +#define APR_HAS_INLINE 1 +#endif + +#define APR_HAVE_ARPA_INET_H @arpa_ineth@ +#define APR_HAVE_CONIO_H @conioh@ +#define APR_HAVE_CRYPT_H @crypth@ +#define APR_HAVE_CTYPE_H @ctypeh@ +#define APR_HAVE_DIRENT_H @direnth@ +#define APR_HAVE_ERRNO_H @errnoh@ +#define APR_HAVE_FCNTL_H @fcntlh@ +#define APR_HAVE_IO_H @ioh@ +#define APR_HAVE_LIMITS_H @limitsh@ +#define APR_HAVE_NETDB_H @netdbh@ +#define APR_HAVE_NETINET_IN_H @netinet_inh@ +#define APR_HAVE_NETINET_SCTP_H @netinet_sctph@ +#define APR_HAVE_NETINET_SCTP_UIO_H @netinet_sctp_uioh@ +#define APR_HAVE_NETINET_TCP_H @netinet_tcph@ +#define APR_HAVE_PROCESS_H @processh@ +#define APR_HAVE_PTHREAD_H @pthreadh@ +#define APR_HAVE_SEMAPHORE_H @semaphoreh@ +#define APR_HAVE_SIGNAL_H @signalh@ +#define APR_HAVE_STDARG_H @stdargh@ +#define APR_HAVE_STDINT_H @stdint@ +#define APR_HAVE_STDIO_H @stdioh@ +#define APR_HAVE_STDLIB_H @stdlibh@ +#define APR_HAVE_STRING_H @stringh@ +#define APR_HAVE_STRINGS_H @stringsh@ +#define APR_HAVE_INTTYPES_H @inttypesh@ +#define APR_HAVE_SYS_IOCTL_H @sys_ioctlh@ +#define APR_HAVE_SYS_SENDFILE_H @sys_sendfileh@ +#define APR_HAVE_SYS_SIGNAL_H @sys_signalh@ +#define APR_HAVE_SYS_SOCKET_H @sys_socketh@ +#define APR_HAVE_SYS_SOCKIO_H @sys_sockioh@ +#define APR_HAVE_SYS_SYSLIMITS_H @sys_syslimitsh@ +#define APR_HAVE_SYS_TIME_H @sys_timeh@ +#define APR_HAVE_SYS_TYPES_H @sys_typesh@ +#define APR_HAVE_SYS_UIO_H @sys_uioh@ +#define APR_HAVE_SYS_UN_H @sys_unh@ +#define APR_HAVE_SYS_WAIT_H @sys_waith@ +#define APR_HAVE_TIME_H @timeh@ +#define APR_HAVE_UNISTD_H @unistdh@ +#define APR_HAVE_WINDOWS_H @windowsh@ +#define APR_HAVE_WINSOCK2_H @winsock2h@ + +/** @} */ +/** @} */ + +/* We don't include our conditional headers within the doxyblocks + * or the extern "C" namespace + */ + +#if APR_HAVE_WINDOWS_H && defined(WIN32) +/* If windows.h was already included, our preferences don't matter. + * If not, include a restricted set of windows headers to our tastes. + */ +#ifndef _WINDOWS_ + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif + +#ifndef _WIN32_WINNT +/* Restrict the server to a subset of Windows XP header files by default + */ +#define _WIN32_WINNT 0x0501 +#endif + +#ifndef NOUSER +#define NOUSER +#endif +#ifndef NOMCX +#define NOMCX +#endif +#ifndef NOIME +#define NOIME +#endif + +#include +/* + * Add a _very_few_ declarations missing from the restricted set of headers + * (If this list becomes extensive, re-enable the required headers above!) + * winsock headers were excluded by WIN32_LEAN_AND_MEAN, so include them now + */ +#define SW_HIDE 0 +#ifndef _WIN32_WCE +#include +#include +#include +#else +#include +#endif + +#endif /* ndef _WINDOWS_ */ +#endif /* APR_HAVE_WINDOWS_H */ + +#if APR_HAVE_SYS_TYPES_H +#include +#endif + +#if APR_HAVE_SYS_SOCKET_H +#include +#endif + +#if APR_HAVE_STDINT_H +#ifdef __cplusplus +/* C99 7.18.4 requires that stdint.h only exposes INT64_C + * and UINT64_C for C++ implementations if this is defined: */ +#ifndef __STDC_CONSTANT_MACROS +#define __STDC_CONSTANT_MACROS +#endif +/* C++ needs this too for PRI*NN formats: */ +#ifndef __STDC_FORMAT_MACROS +#define __STDC_FORMAT_MACROS +#endif +#endif /* __cplusplus */ +#include +#endif + +#if APR_HAVE_INTTYPES_H +#include +#endif + +#if APR_HAVE_SYS_WAIT_H +#include +#endif + +#ifdef OS2 +#define INCL_DOS +#define INCL_DOSERRORS +#include +#endif + +/* header files for PATH_MAX, _POSIX_PATH_MAX */ +#if APR_HAVE_LIMITS_H +#include +#else +#if APR_HAVE_SYS_SYSLIMITS_H +#include +#endif +#endif + +/* __APPLE__ is now the official pre-defined macro for macOS */ +#ifdef __APPLE__ +#undef DARWIN +#undef DARWIN_10 +#define DARWIN +#define DARWIN_10 +#endif /* __APPLE__ */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @addtogroup apr_platform + * @ingroup APR + * @{ + */ + +#define APR_HAVE_SHMEM_MMAP_TMP @havemmaptmp@ +#define APR_HAVE_SHMEM_MMAP_SHM @havemmapshm@ +#define APR_HAVE_SHMEM_MMAP_ZERO @havemmapzero@ +#define APR_HAVE_SHMEM_SHMGET_ANON @haveshmgetanon@ +#define APR_HAVE_SHMEM_SHMGET @haveshmget@ +#define APR_HAVE_SHMEM_MMAP_ANON @havemmapanon@ +#define APR_HAVE_SHMEM_BEOS @havebeosarea@ + +#define APR_USE_SHMEM_MMAP_TMP @usemmaptmp@ +#define APR_USE_SHMEM_MMAP_SHM @usemmapshm@ +#define APR_USE_SHMEM_MMAP_ZERO @usemmapzero@ +#define APR_USE_SHMEM_SHMGET_ANON @useshmgetanon@ +#define APR_USE_SHMEM_SHMGET @useshmget@ +#define APR_USE_SHMEM_MMAP_ANON @usemmapanon@ +#define APR_USE_SHMEM_BEOS @usebeosarea@ + +#define APR_USE_FLOCK_SERIALIZE @flockser@ +#define APR_USE_SYSVSEM_SERIALIZE @sysvser@ +#define APR_USE_POSIXSEM_SERIALIZE @posixser@ +#define APR_USE_FCNTL_SERIALIZE @fcntlser@ +#define APR_USE_PROC_PTHREAD_SERIALIZE @procpthreadser@ +#define APR_USE_PTHREAD_SERIALIZE @pthreadser@ + +#define APR_HAS_FLOCK_SERIALIZE @hasflockser@ +#define APR_HAS_SYSVSEM_SERIALIZE @hassysvser@ +#define APR_HAS_POSIXSEM_SERIALIZE @hasposixser@ +#define APR_HAS_FCNTL_SERIALIZE @hasfcntlser@ +#define APR_HAS_PROC_PTHREAD_SERIALIZE @hasprocpthreadser@ + +#define APR_PROCESS_LOCK_IS_GLOBAL @proclockglobal@ + +#define APR_HAVE_CORKABLE_TCP @have_corkable_tcp@ +#define APR_HAVE_GETRLIMIT @have_getrlimit@ +#define APR_HAVE_IN_ADDR @have_in_addr@ +#define APR_HAVE_INET_ADDR @have_inet_addr@ +#define APR_HAVE_INET_NETWORK @have_inet_network@ +#define APR_HAVE_IPV6 @have_ipv6@ +#define APR_HAVE_SOCKADDR_UN @have_sockaddr_un@ +#define APR_HAVE_MEMMOVE @have_memmove@ +#define APR_HAVE_SETRLIMIT @have_setrlimit@ +#define APR_HAVE_SIGACTION @have_sigaction@ +#define APR_HAVE_SIGSUSPEND @have_sigsuspend@ +#define APR_HAVE_SIGWAIT @have_sigwait@ +#define APR_HAVE_SA_STORAGE @have_sa_storage@ +#define APR_HAVE_STRCASECMP @have_strcasecmp@ +#define APR_HAVE_STRDUP @have_strdup@ +#define APR_HAVE_STRICMP @have_stricmp@ +#define APR_HAVE_STRNCASECMP @have_strncasecmp@ +#define APR_HAVE_STRNICMP @have_strnicmp@ +#define APR_HAVE_STRSTR @have_strstr@ +#define APR_HAVE_MEMCHR @have_memchr@ +#define APR_HAVE_STRUCT_RLIMIT @struct_rlimit@ +#define APR_HAVE_UNION_SEMUN @have_union_semun@ +#define APR_HAVE_SCTP @have_sctp@ +#define APR_HAVE_IOVEC @have_iovec@ + +/* APR Feature Macros */ +#define APR_HAS_SHARED_MEMORY @sharedmem@ +#define APR_HAS_THREADS @threads@ +#define APR_HAS_SENDFILE @sendfile@ +#define APR_HAS_MMAP @mmap@ +#define APR_HAS_FORK @fork@ +#define APR_HAS_RANDOM @rand@ +#define APR_HAS_OTHER_CHILD @oc@ +#define APR_HAS_DSO @aprdso@ +#define APR_HAS_SO_ACCEPTFILTER @acceptfilter@ +#define APR_HAS_UNICODE_FS @have_unicode_fs@ +#define APR_HAS_PROC_INVOKED @have_proc_invoked@ +#define APR_HAS_USER @apr_has_user@ +#define APR_HAS_LARGE_FILES @aprlfs@ +#define APR_HAS_XTHREAD_FILES @apr_has_xthread_files@ +#define APR_HAS_OS_UUID @osuuid@ +#define APR_HAS_TIMEDLOCKS @apr_has_timedlocks@ + +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD @apr_procattr_user_set_requires_password@ + +/* APR sets APR_FILES_AS_SOCKETS to 1 on systems where it is possible + * to poll on files/pipes. + */ +#define APR_FILES_AS_SOCKETS @file_as_socket@ + +/* This macro indicates whether or not EBCDIC is the native character set. + */ +#define APR_CHARSET_EBCDIC @apr_charset_ebcdic@ + +/* If we have a TCP implementation that can be "corked", what flag + * do we use? + */ +#define APR_TCP_NOPUSH_FLAG @apr_tcp_nopush_flag@ + +/* Is the TCP_NODELAY socket option inherited from listening sockets? +*/ +#define APR_TCP_NODELAY_INHERITED @tcp_nodelay_inherited@ + +/* Is the O_NONBLOCK flag inherited from listening sockets? +*/ +#define APR_O_NONBLOCK_INHERITED @o_nonblock_inherited@ + +/* Typedefs that APR needs. */ + +typedef unsigned char apr_byte_t; + +typedef @short_value@ apr_int16_t; +typedef unsigned @short_value@ apr_uint16_t; + +typedef @int_value@ apr_int32_t; +typedef unsigned @int_value@ apr_uint32_t; + +#define APR_SIZEOF_VOIDP @voidp_size@ + +/* + * Darwin 10's default compiler (gcc42) builds for both 64 and + * 32 bit architectures unless specifically told not to. + * In those cases, we need to override types depending on how + * we're being built at compile time. + * NOTE: This is an ugly work-around for Darwin's + * concept of universal binaries, a single package + * (executable, lib, etc...) which contains both 32 + * and 64 bit versions. The issue is that if APR is + * built universally, if something else is compiled + * against it, some bit sizes will depend on whether + * it is 32 or 64 bit. This is determined by the __LP64__ + * flag. Since we need to support both, we have to + * handle OS X unqiuely. + */ +#ifdef DARWIN_10 +#undef APR_SIZEOF_VOIDP +#undef APR_INT64_C +#undef APR_UINT64_C +#ifdef __LP64__ + typedef long apr_int64_t; + typedef unsigned long apr_uint64_t; + #define APR_SIZEOF_VOIDP 8 + #define APR_INT64_C(v) (v ## L) + #define APR_UINT64_C(v) (v ## UL) +#else + typedef long long apr_int64_t; + typedef unsigned long long apr_uint64_t; + #define APR_SIZEOF_VOIDP 4 + #define APR_INT64_C(v) (v ## LL) + #define APR_UINT64_C(v) (v ## ULL) +#endif +#else + typedef @int64_value@ apr_int64_t; + typedef @uint64_value@ apr_uint64_t; + + /* Mechanisms to properly type numeric literals */ + @int64_literal@ + @uint64_literal@ +#endif + +typedef @size_t_value@ apr_size_t; +typedef @ssize_t_value@ apr_ssize_t; +typedef @off_t_value@ apr_off_t; +typedef @socklen_t_value@ apr_socklen_t; +typedef @ino_t_value@ apr_ino_t; + +#if APR_SIZEOF_VOIDP == 8 +typedef apr_uint64_t apr_uintptr_t; +#else +typedef apr_uint32_t apr_uintptr_t; +#endif + +/* Are we big endian? */ +#define APR_IS_BIGENDIAN @bigendian@ + +#ifdef INT16_MIN +#define APR_INT16_MIN INT16_MIN +#else +#define APR_INT16_MIN (-0x7fff - 1) +#endif + +#ifdef INT16_MAX +#define APR_INT16_MAX INT16_MAX +#else +#define APR_INT16_MAX (0x7fff) +#endif + +#ifdef UINT16_MAX +#define APR_UINT16_MAX UINT16_MAX +#else +#define APR_UINT16_MAX (0xffff) +#endif + +#ifdef INT32_MIN +#define APR_INT32_MIN INT32_MIN +#else +#define APR_INT32_MIN (-0x7fffffff - 1) +#endif + +#ifdef INT32_MAX +#define APR_INT32_MAX INT32_MAX +#else +#define APR_INT32_MAX 0x7fffffff +#endif + +#ifdef UINT32_MAX +#define APR_UINT32_MAX UINT32_MAX +#else +#define APR_UINT32_MAX (0xffffffffU) +#endif + +#ifdef INT64_MIN +#define APR_INT64_MIN INT64_MIN +#else +#define APR_INT64_MIN (APR_INT64_C(-0x7fffffffffffffff) - 1) +#endif + +#ifdef INT64_MAX +#define APR_INT64_MAX INT64_MAX +#else +#define APR_INT64_MAX APR_INT64_C(0x7fffffffffffffff) +#endif + +#ifdef UINT64_MAX +#define APR_UINT64_MAX UINT64_MAX +#else +#define APR_UINT64_MAX APR_UINT64_C(0xffffffffffffffff) +#endif + +#define APR_SIZE_MAX (~((apr_size_t)0)) + + +/* Definitions that APR programs need to work properly. */ + +/** + * APR public API wrap for C++ compilers. + */ +#ifdef __cplusplus +#define APR_BEGIN_DECLS extern "C" { +#define APR_END_DECLS } +#else +#define APR_BEGIN_DECLS +#define APR_END_DECLS +#endif + +/** + * Thread callbacks from APR functions must be declared with APR_THREAD_FUNC, + * so that they follow the platform's calling convention. + *
+ *
+ * void* APR_THREAD_FUNC my_thread_entry_fn(apr_thread_t *thd, void *data);
+ *
+ * 
+ */ +#define APR_THREAD_FUNC @apr_thread_func@ + +#if defined(DOXYGEN) || !defined(WIN32) + +/** + * The public APR functions are declared with APR_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APR_DECLARE_NONSTD(). + * + * @remark Both the declaration and implementations must use the same macro. + * + *
+ * APR_DECLARE(rettype) apr_func(args)
+ * 
+ * @see APR_DECLARE_NONSTD @see APR_DECLARE_DATA + * @remark Note that when APR compiles the library itself, it passes the + * symbol -DAPR_DECLARE_EXPORT to the compiler on some platforms (e.g. Win32) + * to export public symbols from the dynamic library build.\n + * The user must define the APR_DECLARE_STATIC when compiling to target + * the static APR library on some platforms (e.g. Win32.) The public symbols + * are neither exported nor imported when APR_DECLARE_STATIC is defined.\n + * By default, compiling an application and including the APR public + * headers, without defining APR_DECLARE_STATIC, will prepare the code to be + * linked to the dynamic library. + */ +#define APR_DECLARE(type) type + +/** + * The public APR functions using variable arguments are declared with + * APR_DECLARE_NONSTD(), as they must follow the C language calling convention. + * @see APR_DECLARE @see APR_DECLARE_DATA + * @remark Both the declaration and implementations must use the same macro. + *
+ *
+ * APR_DECLARE_NONSTD(rettype) apr_func(args, ...);
+ *
+ * 
+ */ +#define APR_DECLARE_NONSTD(type) type + +/** + * The public APR variables are declared with AP_MODULE_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * @see APR_DECLARE @see APR_DECLARE_NONSTD + * @remark Note that the declaration and implementations use different forms, + * but both must include the macro. + * + *
+ *
+ * extern APR_DECLARE_DATA type apr_variable;\n
+ * APR_DECLARE_DATA type apr_variable = value;
+ *
+ * 
+ */ +#define APR_DECLARE_DATA + +#elif defined(APR_DECLARE_STATIC) +#define APR_DECLARE(type) type __stdcall +#define APR_DECLARE_NONSTD(type) type __cdecl +#define APR_DECLARE_DATA +#elif defined(APR_DECLARE_EXPORT) +#define APR_DECLARE(type) __declspec(dllexport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllexport) +#else +#define APR_DECLARE(type) __declspec(dllimport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllimport) +#endif + +/* Define APR_SSIZE_T_FMT. + * If ssize_t is an integer we define it to be "d", + * if ssize_t is a long int we define it to be "ld", + * if ssize_t is neither we declare an error here. + * I looked for a better way to define this here, but couldn't find one, so + * to find the logic for this definition search for "ssize_t_fmt" in + * configure.in. + */ + +@ssize_t_fmt@ + +/* And APR_SIZE_T_FMT */ +@size_t_fmt@ + +/* And APR_OFF_T_FMT */ +@off_t_fmt@ + +/* And APR_PID_T_FMT */ +@pid_t_fmt@ + +/* And APR_INT64_T_FMT */ +@int64_t_fmt@ + +/* And APR_UINT64_T_FMT */ +@uint64_t_fmt@ + +/* And APR_UINT64_T_HEX_FMT */ +@uint64_t_hex_fmt@ + +/* + * Ensure we work with universal binaries on Darwin + */ +#ifdef DARWIN_10 + +#undef APR_HAS_LARGE_FILES +#undef APR_SIZEOF_VOIDP +#undef APR_INT64_T_FMT +#undef APR_UINT64_T_FMT +#undef APR_UINT64_T_HEX_FMT + +#ifdef __LP64__ + #define APR_HAS_LARGE_FILES 0 + #define APR_SIZEOF_VOIDP 8 + #define APR_INT64_T_FMT "ld" + #define APR_UINT64_T_FMT "lu" + #define APR_UINT64_T_HEX_FMT "lx" +#else + #define APR_HAS_LARGE_FILES 1 + #define APR_SIZEOF_VOIDP 4 + #define APR_INT64_T_FMT "lld" + #define APR_UINT64_T_FMT "llu" + #define APR_UINT64_T_HEX_FMT "llx" +#endif + +#undef APR_IS_BIGENDIAN +#ifdef __BIG_ENDIAN__ + #define APR_IS_BIGENDIAN 1 +#else + #define APR_IS_BIGENDIAN 0 +#endif + +#undef APR_OFF_T_FMT +#define APR_OFF_T_FMT "lld" + +#endif /* DARWIN_10 */ + +/* Does the proc mutex lock threads too */ +#define APR_PROC_MUTEX_IS_GLOBAL @proc_mutex_is_global@ + +/* Local machine definition for console and log output. */ +#define APR_EOL_STR "@eolstr@" + +#if APR_HAVE_SYS_WAIT_H +#ifdef WEXITSTATUS +#define apr_wait_t int +#else +#define apr_wait_t union wait +#define WEXITSTATUS(status) (int)((status).w_retcode) +#define WTERMSIG(status) (int)((status).w_termsig) +#endif /* !WEXITSTATUS */ +#elif defined(__MINGW32__) +typedef int apr_wait_t; +#endif /* HAVE_SYS_WAIT_H */ + +#if defined(PATH_MAX) +#define APR_PATH_MAX PATH_MAX +#elif defined(_POSIX_PATH_MAX) +#define APR_PATH_MAX _POSIX_PATH_MAX +#else +#error no decision has been made on APR_PATH_MAX for your platform +#endif + +#define APR_DSOPATH "@shlibpath_var@" + +/** @} */ + +/* Definitions that only Win32 programs need to compile properly. */ + +/* XXX These simply don't belong here, perhaps in apr_portable.h + * based on some APR_HAVE_PID/GID/UID? + */ +#ifdef __MINGW32__ +#ifndef __GNUC__ +typedef int pid_t; +#endif +typedef int uid_t; +typedef int gid_t; +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* APR_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr.hnw b/c/dependencies/windows/apr/x86_debug/include/apr.hnw new file mode 100644 index 00000000..21c8a98e --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr.hnw @@ -0,0 +1,445 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef APR_H +#define APR_H + +/* GENERATED FILE WARNING! DO NOT EDIT apr.h + * + * You must modify apr.hnw instead. + * + * And please, make an effort to stub apr.hw and apr.h.in in the process. + * + * This is the NetWare specific version of apr.h. It is copied from + * apr.hnw at the start of a NetWare build by the ./build/NWGNmakefile. + */ + +/** + * @file apr.h + * @brief APR Platform Definitions + * @remark This is a generated header generated from include/apr.h.in by + * ./configure, or copied from include/apr.hw or include/apr.hnw + * for Win32 or Netware by those build environments, respectively. + */ + +#if defined(NETWARE) || defined(DOXYGEN) + +#undef FD_SETSIZE +#define FD_SETSIZE 1024 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef USE_WINSOCK +#include +#ifdef NW_BUILD_IPV6 +#include +#endif +#else +#include +#include +#endif +#include + +#define _POSIX_THREAD_SAFE_FUNCTIONS 1 +#define READDIR_IS_THREAD_SAFE 1 + +/* Keep #include'd headers from within the __cplusplus or doxyblocks */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_platform Platform Definitions + * @ingroup APR + * @{ + */ + +#define APR_INLINE +#define APR_HAS_INLINE 0 +#ifndef __attribute__ +#define __attribute__(__x) +#endif +#define ENUM_BITFIELD(e,n,w) signed int n : w + +#define APR_HAVE_CONIO_H 0 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 1 +#define APR_HAVE_DIRENT_H 1 +#define APR_HAVE_ERRNO_H 1 +#define APR_HAVE_FCNTL_H 1 +#define APR_HAVE_IO_H 0 +#define APR_HAVE_LIMITS_H 1 +#ifdef USE_WINSOCK +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#else +#define APR_HAVE_ARPA_INET_H 1 +#define APR_HAVE_NETDB_H 1 +#define APR_HAVE_NETINET_IN_H 1 +#endif +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SIGNAL_H 1 +#define APR_HAVE_STDARG_H 1 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_STRTOLL 1 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#ifdef USE_WINSOCK +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#else +#define APR_HAVE_SYS_SOCKET_H 1 +#define APR_HAVE_SYS_SOCKIO_H 1 +#define APR_HAVE_SYS_UN_H 1 +#endif +#define APR_HAVE_SYS_SIGNAL_H 1 +#define APR_HAVE_SYS_TIME_H 1 +#define APR_HAVE_SYS_TYPES_H 1 +#define APR_HAVE_SYS_UIO_H 1 +#define APR_HAVE_SYS_WAIT_H 1 +#define APR_HAVE_TIME_H 1 +#define APR_HAVE_UNISTD_H 1 + +#define APR_HAVE_SHMEM_MMAP_TMP 0 +#define APR_HAVE_SHMEM_MMAP_SHM 0 +#define APR_HAVE_SHMEM_MMAP_ZERO 0 +#define APR_HAVE_SHMEM_SHMGET_ANON 0 +#define APR_HAVE_SHMEM_SHMGET 0 +#define APR_HAVE_SHMEM_MMAP_ANON 0 +#define APR_HAVE_SHMEM_BEOS 0 + +#define APR_USE_SHMEM_MMAP_TMP 0 +#define APR_USE_SHMEM_MMAP_SHM 0 +#define APR_USE_SHMEM_MMAP_ZERO 0 +#define APR_USE_SHMEM_SHMGET_ANON 0 +#define APR_USE_SHMEM_SHMGET 0 +#define APR_USE_SHMEM_MMAP_ANON 0 +#define APR_USE_SHMEM_BEOS 0 + +#define APR_USE_FLOCK_SERIALIZE 0 +#define APR_USE_SYSVSEM_SERIALIZE 0 +#define APR_USE_FCNTL_SERIALIZE 0 +#define APR_USE_PROC_PTHREAD_SERIALIZE 0 +#define APR_USE_PTHREAD_SERIALIZE 0 + +#define APR_HAS_FLOCK_SERIALIZE 0 +#define APR_HAS_SYSVSEM_SERIALIZE 0 +#define APR_HAS_FCNTL_SERIALIZE 0 +#define APR_HAS_PROC_PTHREAD_SERIALIZE 0 +#define APR_HAS_RWLOCK_SERIALIZE 0 + +#define APR_HAS_LOCK_CREATE_NP 0 + +#define APR_PROCESS_LOCK_IS_GLOBAL 1 + +#define APR_FILE_BASED_SHM 0 + +#define APR_HAVE_CORKABLE_TCP 0 +#define APR_HAVE_GETRLIMIT 0 +#define APR_HAVE_ICONV 0 +#define APR_HAVE_IN_ADDR 1 +#define APR_HAVE_INET_ADDR 1 +#define APR_HAVE_INET_NETWORK 0 +#ifdef NW_BUILD_IPV6 +#define APR_HAVE_IPV6 1 +#else +#define APR_HAVE_IPV6 0 +#endif +#define APR_HAVE_SOCKADDR_UN 0 +#define APR_HAVE_MEMCHR 1 +#define APR_HAVE_MEMMOVE 1 +#define APR_HAVE_SETRLIMIT 0 +#define APR_HAVE_SIGACTION 0 +#define APR_HAVE_SIGSUSPEND 0 +#define APR_HAVE_SIGWAIT 0 +#define APR_HAVE_STRCASECMP 1 +#define APR_HAVE_STRDUP 1 +#define APR_HAVE_STRICMP 1 +#define APR_HAVE_STRNCASECMP 1 +#define APR_HAVE_STRNICMP 1 +#define APR_HAVE_STRSTR 1 +#define APR_HAVE_STRUCT_RLIMIT 0 +#define APR_HAVE_UNION_SEMUN 0 +#define APR_HAVE_SCTP 0 +#define APR_HAVE_IOVEC 1 + +/* APR Feature Macros */ +#define APR_HAS_SHARED_MEMORY 0 +#define APR_HAS_THREADS 1 +#define APR_HAS_SENDFILE 0 +#define APR_HAS_MMAP 0 +#define APR_HAS_FORK 0 +#define APR_HAS_RANDOM 1 +#define APR_HAS_OTHER_CHILD 0 +#define APR_HAS_DSO 1 +#define APR_HAS_SO_ACCEPTFILTER 0 +#define APR_HAS_UNICODE_FS 0 +#define APR_HAS_PROC_INVOKED 0 +#define APR_HAS_USER 1 +#define APR_HAS_LARGE_FILES 1 +#define APR_HAS_XTHREAD_FILES 0 +#define APR_HAS_OS_UUID 0 +#define APR_HAS_TIMEDLOCKS 1 + +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 0 + +/* Netware can poll on files/pipes. + */ +#define APR_FILES_AS_SOCKETS 1 + +/* This macro indicates whether or not EBCDIC is the native character set. + */ +#define APR_CHARSET_EBCDIC 0 + +/* Is the TCP_NODELAY socket option inherited from listening sockets? +*/ +#define APR_TCP_NODELAY_INHERITED 1 + +/* Is the O_NONBLOCK flag inherited from listening sockets? +*/ +#define APR_O_NONBLOCK_INHERITED 1 + +/* Typedefs that APR needs. */ + +typedef unsigned char apr_byte_t; + +typedef short apr_int16_t; +typedef unsigned short apr_uint16_t; + +typedef int apr_int32_t; +typedef unsigned int apr_uint32_t; + +typedef long long apr_int64_t; +typedef unsigned long long apr_uint64_t; + +typedef size_t apr_size_t; +typedef ssize_t apr_ssize_t; +#if APR_HAS_LARGE_FILES +typedef off64_t apr_off_t; +#else +typedef off_t apr_off_t; +#endif +#ifdef USE_WINSOCK +typedef int apr_socklen_t; +#else +typedef size_t apr_socklen_t; +#endif +typedef apr_uint64_t apr_ino_t; + +/* Are we big endian? */ +/* XXX: Fatal assumption on Alpha platforms */ +#define APR_IS_BIGENDIAN 0 + +#ifdef UNKNOWN_NETWARE_64BIT_FLAG_NEEDED +#define APR_SIZEOF_VOIDP 8 +#else +#define APR_SIZEOF_VOIDP 4 +#endif + +#if APR_SIZEOF_VOIDP == 8 +typedef apr_uint64_t apr_uintptr_t; +#else +typedef apr_uint32_t apr_uintptr_t; +#endif + +/* Mechanisms to properly type numeric literals */ +#define APR_INT64_C(val) (val##LL) +#define APR_UINT64_C(val) (val##ULL) + +#ifdef INT16_MIN +#define APR_INT16_MIN INT16_MIN +#else +#define APR_INT16_MIN (-0x7fff - 1) +#endif + +#ifdef INT16_MAX +#define APR_INT16_MAX INT16_MAX +#else +#define APR_INT16_MAX (0x7fff) +#endif + +#ifdef UINT16_MAX +#define APR_UINT16_MAX UINT16_MAX +#else +#define APR_UINT16_MAX (0xffff) +#endif + +#ifdef INT32_MIN +#define APR_INT32_MIN INT32_MIN +#else +#define APR_INT32_MIN (-0x7fffffff - 1) +#endif + +#ifdef INT32_MAX +#define APR_INT32_MAX INT32_MAX +#else +#define APR_INT32_MAX 0x7fffffff +#endif + +#ifdef UINT32_MAX +#define APR_UINT32_MAX UINT32_MAX +#else +#define APR_UINT32_MAX (0xffffffffU) +#endif + +#ifdef INT64_MIN +#define APR_INT64_MIN INT64_MIN +#else +#define APR_INT64_MIN (APR_INT64_C(-0x7fffffffffffffff) - 1) +#endif + +#ifdef INT64_MAX +#define APR_INT64_MAX INT64_MAX +#else +#define APR_INT64_MAX APR_INT64_C(0x7fffffffffffffff) +#endif + +#ifdef UINT64_MAX +#define APR_UINT64_MAX UINT64_MAX +#else +#define APR_UINT64_MAX APR_UINT64_C(0xffffffffffffffff) +#endif + +#define APR_SIZE_MAX (~((apr_size_t)0)) + +/* PROC mutex is a GLOBAL mutex on Netware */ +#define APR_PROC_MUTEX_IS_GLOBAL 1 + +/* Definitions that APR programs need to work properly. */ + +/** + * APR public API wrap for C++ compilers. + */ +#ifdef __cplusplus +#define APR_BEGIN_DECLS extern "C" { +#define APR_END_DECLS } +#else +#define APR_BEGIN_DECLS +#define APR_END_DECLS +#endif + +/** + * Thread callbacks from APR functions must be declared with APR_THREAD_FUNC, + * so that they follow the platform's calling convention. + * @example + */ +/** void* APR_THREAD_FUNC my_thread_entry_fn(apr_thread_t *thd, void *data); + */ +#define APR_THREAD_FUNC + +/** + * The public APR functions are declared with APR_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APR_DECLARE_NONSTD(). + * + * @remark Both the declaration and implementations must use the same macro. + * @example + */ +/** APR_DECLARE(rettype) apr_func(args) + * @see APR_DECLARE_NONSTD @see APR_DECLARE_DATA + * @remark Note that when APR compiles the library itself, it passes the + * symbol -DAPR_DECLARE_EXPORT to the compiler on some platforms (e.g. Win32) + * to export public symbols from the dynamic library build.\n + * The user must define the APR_DECLARE_STATIC when compiling to target + * the static APR library on some platforms (e.g. Win32.) The public symbols + * are neither exported nor imported when APR_DECLARE_STATIC is defined.\n + * By default, compiling an application and including the APR public + * headers, without defining APR_DECLARE_STATIC, will prepare the code to be + * linked to the dynamic library. + */ +#define APR_DECLARE(type) type + +/** + * The public APR functions using variable arguments are declared with + * APR_DECLARE_NONSTD(), as they must follow the C language calling convention. + * @see APR_DECLARE @see APR_DECLARE_DATA + * @remark Both the declaration and implementations must use the same macro. + * @example + */ +/** APR_DECLARE_NONSTD(rettype) apr_func(args, ...); + */ +#define APR_DECLARE_NONSTD(type) type + +/** + * The public APR variables are declared with APR_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * @see APR_DECLARE @see APR_DECLARE_NONSTD + * @remark Note that the declaration and implementations use different forms, + * but both must include the macro. + * @example + */ +/** extern APR_DECLARE_DATA type apr_variable;\n + * APR_DECLARE_DATA type apr_variable = value; + */ +#define APR_DECLARE_DATA + +#define APR_SSIZE_T_FMT "d" + +#define APR_SIZE_T_FMT "d" + +#if APR_HAS_LARGE_FILES +#define APR_OFF_T_FMT "lld" +#else +#define APR_OFF_T_FMT "ld" +#endif + +#define APR_PID_T_FMT "d" + +/* Local machine definition for console and log output. */ +#define APR_EOL_STR "\r\n" + +typedef int apr_wait_t; + +#define APR_PATH_MAX PATH_MAX + +#define APR_DSOPATH "PATH" + +#define APR_INT64_T_FMT "lld" +#define APR_UINT64_T_FMT "llu" +#define APR_UINT64_T_HEX_FMT "llx" +#define APR_TIME_T_FMT APR_INT64_T_FMT + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* NETWARE */ + +#endif /* APR_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr.hw b/c/dependencies/windows/apr/x86_debug/include/apr.hw new file mode 100644 index 00000000..b8d97495 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr.hw @@ -0,0 +1,667 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef APR_H +#define APR_H + +/* GENERATED FILE WARNING! DO NOT EDIT apr.h + * + * You must modify apr.hw instead. + * + * And please, make an effort to stub apr.hnw and apr.h.in in the process. + * + * This is the Win32 specific version of apr.h. It is copied from + * apr.hw by the apr.dsp and libapr.dsp projects. + */ + +/** + * @file apr.h + * @brief APR Platform Definitions + * @remark This is a generated header generated from include/apr.h.in by + * ./configure, or copied from include/apr.hw or include/apr.hnw + * for Win32 or Netware by those build environments, respectively. + */ + +/* Make sure we have our platform identifier macro defined we ask for later. + */ +#if defined(_WIN32) && !defined(WIN32) +#define WIN32 1 +#endif + +#if defined(WIN32) || defined(DOXYGEN) + +/* Ignore most warnings (back down to /W3) for poorly constructed headers + */ +#if defined(_MSC_VER) && _MSC_VER >= 1200 +#pragma warning(push, 3) +#endif + +/* disable or reduce the frequency of... + * C4057: indirection to slightly different base types + * C4075: slight indirection changes (unsigned short* vs short[]) + * C4100: unreferenced formal parameter + * C4127: conditional expression is constant + * C4163: '_rotl64' : not available as an intrinsic function + * C4201: nonstandard extension nameless struct/unions + * C4244: int to char/short - precision loss + * C4514: unreferenced inline function removed + */ +#if defined(_MSC_VER) +#pragma warning(disable: 4100 4127 4163 4201 4514; once: 4057 4075 4244) +#endif + +/* Ignore Microsoft's interpretation of secure development + * and the POSIX string handling API + */ +#if defined(_MSC_VER) && _MSC_VER >= 1400 +#ifndef _CRT_SECURE_NO_DEPRECATE +#define _CRT_SECURE_NO_DEPRECATE +#endif +#pragma warning(disable: 4996) +#endif + +/* Has windows.h already been included? If so, our preferences don't matter, + * but we will still need the winsock things no matter what was included. + * If not, include a restricted set of windows headers to our tastes. + */ +#ifndef _WINDOWS_ +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef _WIN32_WINNT + +/* Restrict the server to a subset of Windows XP header files by default + */ +#define _WIN32_WINNT 0x0A00 +#endif +#ifndef NOUSER +#define NOUSER +#endif +#ifndef NOMCX +#define NOMCX +#endif +#ifndef NOIME +#define NOIME +#endif +#include +/* + * Add a _very_few_ declarations missing from the restricted set of headers + * (If this list becomes extensive, re-enable the required headers above!) + * winsock headers were excluded by WIN32_LEAN_AND_MEAN, so include them now + */ +#define SW_HIDE 0 +#ifndef _WIN32_WCE +#include +#include +#include +#else +#include +#endif +#endif /* !_WINDOWS_ */ + +/** + * @defgroup APR Apache Portability Runtime library + * @{ + */ +/** + * @defgroup apr_platform Platform Definitions + * @{ + * @warning + * The actual values of macros and typedefs on this page
+ * are platform specific and should NOT be relied upon!
+ */ + +#define APR_INLINE __inline +#define APR_HAS_INLINE 1 +#if !defined(__GNUC__) && !defined(__attribute__) +#define __attribute__(__x) +#endif + +#ifndef _WIN32_WCE +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_CONIO_H 1 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 1 +#define APR_HAVE_DIRENT_H 0 +#define APR_HAVE_ERRNO_H 1 +#define APR_HAVE_FCNTL_H 1 +#define APR_HAVE_IO_H 1 +#define APR_HAVE_LIMITS_H 1 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SEMAPHORE_H 0 +#define APR_HAVE_SIGNAL_H 1 +#define APR_HAVE_STDARG_H 1 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_SYS_IOCTL_H 0 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SIGNAL_H 0 +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#define APR_HAVE_SYS_TIME_H 0 +#define APR_HAVE_SYS_TYPES_H 1 +#define APR_HAVE_SYS_UIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#define APR_HAVE_SYS_WAIT_H 0 +#define APR_HAVE_TIME_H 1 +#define APR_HAVE_UNISTD_H 0 +#define APR_HAVE_STDDEF_H 1 +#define APR_HAVE_PROCESS_H 1 +#else +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_CONIO_H 0 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 0 +#define APR_HAVE_DIRENT_H 0 +#define APR_HAVE_ERRNO_H 0 +#define APR_HAVE_FCNTL_H 0 +#define APR_HAVE_IO_H 0 +#define APR_HAVE_LIMITS_H 0 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SEMAPHORE_H 0 +#define APR_HAVE_SIGNAL_H 0 +#define APR_HAVE_STDARG_H 0 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_SYS_IOCTL_H 0 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SIGNAL_H 0 +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#define APR_HAVE_SYS_TIME_H 0 +#define APR_HAVE_SYS_TYPES_H 0 +#define APR_HAVE_SYS_UIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#define APR_HAVE_SYS_WAIT_H 0 +#define APR_HAVE_TIME_H 0 +#define APR_HAVE_UNISTD_H 0 +#define APR_HAVE_STDDEF_H 0 +#define APR_HAVE_PROCESS_H 0 +#endif + +/** @} */ +/** @} */ + +/* We don't include our conditional headers within the doxyblocks + * or the extern "C" namespace + */ + +#if APR_HAVE_STDLIB_H +#include +#endif + +#if APR_HAVE_STDIO_H +#include +#endif + +#if APR_HAVE_SYS_TYPES_H +#include +#endif + +#if APR_HAVE_STDDEF_H +#include +#endif + +#if APR_HAVE_SYS_SOCKET_H +#include +#endif + +#if APR_HAVE_STDINT_H +#include +#endif + +#if APR_HAVE_SYS_WAIT_H +#include +#endif + +#if APR_HAVE_TIME_H +#include +#endif + +#if APR_HAVE_PROCESS_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @addtogroup apr_platform + * @ingroup APR + * @{ + */ + +#define APR_HAVE_SHMEM_MMAP_TMP 0 +#define APR_HAVE_SHMEM_MMAP_SHM 0 +#define APR_HAVE_SHMEM_MMAP_ZERO 0 +#define APR_HAVE_SHMEM_SHMGET_ANON 0 +#define APR_HAVE_SHMEM_SHMGET 0 +#define APR_HAVE_SHMEM_MMAP_ANON 0 +#define APR_HAVE_SHMEM_BEOS 0 + +#define APR_USE_SHMEM_MMAP_TMP 0 +#define APR_USE_SHMEM_MMAP_SHM 0 +#define APR_USE_SHMEM_MMAP_ZERO 0 +#define APR_USE_SHMEM_SHMGET_ANON 0 +#define APR_USE_SHMEM_SHMGET 0 +#define APR_USE_SHMEM_MMAP_ANON 0 +#define APR_USE_SHMEM_BEOS 0 + +#define APR_USE_FLOCK_SERIALIZE 0 +#define APR_USE_POSIXSEM_SERIALIZE 0 +#define APR_USE_SYSVSEM_SERIALIZE 0 +#define APR_USE_FCNTL_SERIALIZE 0 +#define APR_USE_PROC_PTHREAD_SERIALIZE 0 +#define APR_USE_PTHREAD_SERIALIZE 0 + +#define APR_HAS_FLOCK_SERIALIZE 0 +#define APR_HAS_SYSVSEM_SERIALIZE 0 +#define APR_HAS_POSIXSEM_SERIALIZE 0 +#define APR_HAS_FCNTL_SERIALIZE 0 +#define APR_HAS_PROC_PTHREAD_SERIALIZE 0 + +#define APR_PROCESS_LOCK_IS_GLOBAL 0 + +#define APR_HAVE_CORKABLE_TCP 0 +#define APR_HAVE_GETRLIMIT 0 +#define APR_HAVE_ICONV 0 +#define APR_HAVE_IN_ADDR 1 +#define APR_HAVE_INET_ADDR 1 +#define APR_HAVE_INET_NETWORK 0 +#define APR_HAVE_IPV6 1 +#define APR_HAVE_SOCKADDR_UN 0 +#define APR_HAVE_MEMMOVE 1 +#define APR_HAVE_SETRLIMIT 0 +#define APR_HAVE_SIGACTION 0 +#define APR_HAVE_SIGSUSPEND 0 +#define APR_HAVE_SIGWAIT 0 +#define APR_HAVE_SA_STORAGE 0 +#define APR_HAVE_STRCASECMP 0 +#define APR_HAVE_STRDUP 1 +#define APR_HAVE_STRNCASECMP 0 +#define APR_HAVE_STRSTR 1 +#define APR_HAVE_MEMCHR 1 +#define APR_HAVE_STRUCT_RLIMIT 0 +#define APR_HAVE_UNION_SEMUN 0 +#define APR_HAVE_SCTP 0 +#define APR_HAVE_IOVEC 0 + +#ifndef _WIN32_WCE +#define APR_HAVE_STRICMP 1 +#define APR_HAVE_STRNICMP 1 +#else +#define APR_HAVE_STRICMP 0 +#define APR_HAVE_STRNICMP 0 +#endif + +/* APR Feature Macros */ +#define APR_HAS_SHARED_MEMORY 1 +#define APR_HAS_THREADS 1 +#define APR_HAS_MMAP 1 +#define APR_HAS_FORK 0 +#define APR_HAS_RANDOM 1 +#define APR_HAS_OTHER_CHILD 1 +#define APR_HAS_DSO 1 +#define APR_HAS_SO_ACCEPTFILTER 0 +#define APR_HAS_UNICODE_FS 1 +#define APR_HAS_PROC_INVOKED 1 +#define APR_HAS_OS_UUID 1 +#define APR_HAS_TIMEDLOCKS 1 + +#ifndef _WIN32_WCE +#define APR_HAS_SENDFILE 1 +#define APR_HAS_USER 1 +#define APR_HAS_LARGE_FILES 1 +#define APR_HAS_XTHREAD_FILES 1 +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 1 +#else +#define APR_HAS_SENDFILE 0 +#define APR_HAS_USER 0 +#define APR_HAS_LARGE_FILES 0 +#define APR_HAS_XTHREAD_FILES 0 +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 0 +#endif + +/* APR sets APR_FILES_AS_SOCKETS to 1 on systems where it is possible + * to poll on files/pipes. + */ +#define APR_FILES_AS_SOCKETS 0 + +/* This macro indicates whether or not EBCDIC is the native character set. + */ +#define APR_CHARSET_EBCDIC 0 + +/* If we have a TCP implementation that can be "corked", what flag + * do we use? + */ +#define APR_TCP_NOPUSH_FLAG @apr_tcp_nopush_flag@ + +/* Is the TCP_NODELAY socket option inherited from listening sockets? + */ +#define APR_TCP_NODELAY_INHERITED 1 + +/* Is the O_NONBLOCK flag inherited from listening sockets? + */ +#define APR_O_NONBLOCK_INHERITED 1 + +/* Typedefs that APR needs. */ + +typedef unsigned char apr_byte_t; + +typedef short apr_int16_t; +typedef unsigned short apr_uint16_t; + +typedef int apr_int32_t; +typedef unsigned int apr_uint32_t; + +typedef __int64 apr_int64_t; +typedef unsigned __int64 apr_uint64_t; + +typedef size_t apr_size_t; +#if APR_HAVE_STDDEF_H +typedef ptrdiff_t apr_ssize_t; +#else +typedef int apr_ssize_t; +#endif +#if APR_HAS_LARGE_FILES +typedef __int64 apr_off_t; +#else +typedef int apr_off_t; +#endif +typedef int apr_socklen_t; +typedef apr_uint64_t apr_ino_t; + +#ifdef _WIN64 +#define APR_SIZEOF_VOIDP 8 +#else +#define APR_SIZEOF_VOIDP 4 +#endif + +#if APR_SIZEOF_VOIDP == 8 +typedef apr_uint64_t apr_uintptr_t; +#else +typedef apr_uint32_t apr_uintptr_t; +#endif + +/* Are we big endian? */ +/* XXX: Fatal assumption on Alpha platforms */ +#define APR_IS_BIGENDIAN 0 + +/* Mechanisms to properly type numeric literals */ + +#ifndef __GNUC__ +#define APR_INT64_C(val) (val##i64) +#define APR_UINT64_C(val) (val##Ui64) +#else +#define APR_INT64_C(val) (val##LL) +#define APR_UINT64_C(val) (val##ULL) +#endif + +#ifdef INT16_MIN +#define APR_INT16_MIN INT16_MIN +#else +#define APR_INT16_MIN (-0x7fff - 1) +#endif + +#ifdef INT16_MAX +#define APR_INT16_MAX INT16_MAX +#else +#define APR_INT16_MAX (0x7fff) +#endif + +#ifdef UINT16_MAX +#define APR_UINT16_MAX UINT16_MAX +#else +#define APR_UINT16_MAX (0xffff) +#endif + +#ifdef INT32_MIN +#define APR_INT32_MIN INT32_MIN +#else +#define APR_INT32_MIN (-0x7fffffff - 1) +#endif + +#ifdef INT32_MAX +#define APR_INT32_MAX INT32_MAX +#else +#define APR_INT32_MAX 0x7fffffff +#endif + +#ifdef UINT32_MAX +#define APR_UINT32_MAX UINT32_MAX +#else +#define APR_UINT32_MAX (0xffffffffU) +#endif + +#ifdef INT64_MIN +#define APR_INT64_MIN INT64_MIN +#else +#define APR_INT64_MIN (APR_INT64_C(-0x7fffffffffffffff) - 1) +#endif + +#ifdef INT64_MAX +#define APR_INT64_MAX INT64_MAX +#else +#define APR_INT64_MAX APR_INT64_C(0x7fffffffffffffff) +#endif + +#ifdef UINT64_MAX +#define APR_UINT64_MAX UINT64_MAX +#else +#define APR_UINT64_MAX APR_UINT64_C(0xffffffffffffffff) +#endif + +#define APR_SIZE_MAX (~((apr_size_t)0)) + +/* Definitions that APR programs need to work properly. */ + +/** + * APR public API wrap for C++ compilers. + */ +#ifdef __cplusplus +#define APR_BEGIN_DECLS extern "C" { +#define APR_END_DECLS } +#else +#define APR_BEGIN_DECLS +#define APR_END_DECLS +#endif + +/** + * Thread callbacks from APR functions must be declared with APR_THREAD_FUNC, + * so that they follow the platform's calling convention. + *
+ *
+ * void* APR_THREAD_FUNC my_thread_entry_fn(apr_thread_t *thd, void *data);
+ *
+ * 
+ */ +#define APR_THREAD_FUNC __stdcall + + +#if defined(DOXYGEN) || !defined(WIN32) + +/** + * The public APR functions are declared with APR_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APR_DECLARE_NONSTD(). + * + * @remark Both the declaration and implementations must use the same macro. + * + *
+ * APR_DECLARE(rettype) apr_func(args)
+ * 
+ * @see APR_DECLARE_NONSTD @see APR_DECLARE_DATA + * @remark Note that when APR compiles the library itself, it passes the + * symbol -DAPR_DECLARE_EXPORT to the compiler on some platforms (e.g. Win32) + * to export public symbols from the dynamic library build.\n + * The user must define the APR_DECLARE_STATIC when compiling to target + * the static APR library on some platforms (e.g. Win32.) The public symbols + * are neither exported nor imported when APR_DECLARE_STATIC is defined.\n + * By default, compiling an application and including the APR public + * headers, without defining APR_DECLARE_STATIC, will prepare the code to be + * linked to the dynamic library. + */ +#define APR_DECLARE(type) type + +/** + * The public APR functions using variable arguments are declared with + * APR_DECLARE_NONSTD(), as they must follow the C language calling convention. + * @see APR_DECLARE @see APR_DECLARE_DATA + * @remark Both the declaration and implementations must use the same macro. + *
+ *
+ * APR_DECLARE_NONSTD(rettype) apr_func(args, ...);
+ *
+ * 
+ */ +#define APR_DECLARE_NONSTD(type) type + +/** + * The public APR variables are declared with AP_MODULE_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * @see APR_DECLARE @see APR_DECLARE_NONSTD + * @remark Note that the declaration and implementations use different forms, + * but both must include the macro. + * + *
+ *
+ * extern APR_DECLARE_DATA type apr_variable;\n
+ * APR_DECLARE_DATA type apr_variable = value;
+ *
+ * 
+ */ +#define APR_DECLARE_DATA + +#elif defined(APR_DECLARE_STATIC) +#define APR_DECLARE(type) type __stdcall +#define APR_DECLARE_NONSTD(type) type __cdecl +#define APR_DECLARE_DATA +#elif defined(APR_DECLARE_EXPORT) +#define APR_DECLARE(type) __declspec(dllexport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllexport) +#else +#define APR_DECLARE(type) __declspec(dllimport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllimport) +#endif + +#ifdef _WIN64 +#define APR_SSIZE_T_FMT "I64d" +#define APR_SIZE_T_FMT "I64u" +#else +#define APR_SSIZE_T_FMT "d" +#define APR_SIZE_T_FMT "u" +#endif + +#if APR_HAS_LARGE_FILES +#define APR_OFF_T_FMT "I64d" +#else +#define APR_OFF_T_FMT "d" +#endif + +#define APR_PID_T_FMT "d" + +#define APR_INT64_T_FMT "I64d" +#define APR_UINT64_T_FMT "I64u" +#define APR_UINT64_T_HEX_FMT "I64x" + +/* No difference between PROC and GLOBAL mutex */ +#define APR_PROC_MUTEX_IS_GLOBAL 1 + +/* Local machine definition for console and log output. */ +#define APR_EOL_STR "\r\n" + +typedef int apr_wait_t; + +#if APR_HAS_UNICODE_FS +/* An arbitrary size that is digestable. True max is a bit less than 32000 */ +#define APR_PATH_MAX 8192 +#else /* !APR_HAS_UNICODE_FS */ +#define APR_PATH_MAX MAX_PATH +#endif + +#define APR_DSOPATH "PATH" + +/** @} */ + +/* Definitions that only Win32 programs need to compile properly. */ + +/* XXX These simply don't belong here, perhaps in apr_portable.h + * based on some APR_HAVE_PID/GID/UID? + */ +#ifndef __GNUC__ +typedef int pid_t; +#endif +typedef int uid_t; +typedef int gid_t; + +/* Win32 .h ommissions we really need */ +#define STDIN_FILENO 0 +#define STDOUT_FILENO 1 +#define STDERR_FILENO 2 + +#if APR_HAVE_IPV6 + +/* Appears in later flavors, not the originals. */ +#ifndef in_addr6 +#define in6_addr in_addr6 +#endif + +#ifndef WS2TCPIP_INLINE +#define IN6_IS_ADDR_V4MAPPED(a) \ + ( (*(const apr_uint64_t *)(const void *)(&(a)->s6_addr[0]) == 0) \ + && (*(const apr_uint32_t *)(const void *)(&(a)->s6_addr[8]) == ntohl(0x0000ffff))) +#endif + +#endif /* APR_HAVE_IPV6 */ + +#ifdef __cplusplus +} +#endif + +/* Done with badly written headers, leave 'deprecated CRT' undeprecated + */ +#if defined(_MSC_VER) && _MSC_VER >= 1200 +#pragma warning(pop) +#if _MSC_VER >= 1400 +#pragma warning(disable: 4996) +#endif +#endif + +#endif /* WIN32 */ + +#endif /* APR_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr.hwc b/c/dependencies/windows/apr/x86_debug/include/apr.hwc new file mode 100644 index 00000000..ffb8368b --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr.hwc @@ -0,0 +1,664 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef APR_H +#define APR_H + +/* GENERATED FILE WARNING! DO NOT EDIT apr.h + * + * You must modify apr.hwc instead. + * + * And please, make an effort to stub apr.hnw and apr.h.in in the process. + * + * This is the Win32 specific version of apr.h. It is copied from + * apr.hw by the apr.dsp and libapr.dsp projects. + */ + +/** + * @file apr.h + * @brief APR Platform Definitions + * @remark This is a generated header generated from include/apr.h.in by + * ./configure, or copied from include/apr.hw or include/apr.hnw + * for Win32 or Netware by those build environments, respectively. + */ + +/* Make sure we have our platform identifier macro defined we ask for later. + */ +#if defined(_WIN32) && !defined(WIN32) +#define WIN32 1 +#endif + +#if defined(WIN32) || defined(DOXYGEN) + +/* Ignore most warnings (back down to /W3) for poorly constructed headers + */ +#if defined(_MSC_VER) && _MSC_VER >= 1200 +#pragma warning(push, 3) +#endif + +/* disable or reduce the frequency of... + * C4057: indirection to slightly different base types + * C4075: slight indirection changes (unsigned short* vs short[]) + * C4100: unreferenced formal parameter + * C4127: conditional expression is constant + * C4163: '_rotl64' : not available as an intrinsic function + * C4201: nonstandard extension nameless struct/unions + * C4244: int to char/short - precision loss + * C4514: unreferenced inline function removed + */ +#if defined(_MSC_VER) +#pragma warning(disable: 4100 4127 4163 4201 4514; once: 4057 4075 4244) +#endif + +/* Ignore Microsoft's interpretation of secure development + * and the POSIX string handling API + */ +#if defined(_MSC_VER) && _MSC_VER >= 1400 +#ifndef _CRT_SECURE_NO_DEPRECATE +#define _CRT_SECURE_NO_DEPRECATE +#endif +#pragma warning(disable: 4996) +#endif + +/* Has windows.h already been included? If so, our preferences don't matter, + * but we will still need the winsock things no matter what was included. + * If not, include a restricted set of windows headers to our tastes. + */ +#ifndef _WINDOWS_ +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef _WIN32_WINNT +#define _WIN32_WINNT @win32_winnt_str@ +#endif +#ifndef NOUSER +#define NOUSER +#endif +#ifndef NOMCX +#define NOMCX +#endif +#ifndef NOIME +#define NOIME +#endif +#include +/* + * Add a _very_few_ declarations missing from the restricted set of headers + * (If this list becomes extensive, re-enable the required headers above!) + * winsock headers were excluded by WIN32_LEAN_AND_MEAN, so include them now + */ +#define SW_HIDE 0 +#ifndef _WIN32_WCE +#include +#include +#include +#else +#include +#endif +#endif /* !_WINDOWS_ */ + +/** + * @defgroup APR Apache Portability Runtime library + * @{ + */ +/** + * @defgroup apr_platform Platform Definitions + * @{ + * @warning + * The actual values of macros and typedefs on this page
+ * are platform specific and should NOT be relied upon!
+ */ + +#define APR_INLINE __inline +#define APR_HAS_INLINE 1 +#if !defined(__GNUC__) && !defined(__attribute__) +#define __attribute__(__x) +#endif + +#ifndef _WIN32_WCE +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_CONIO_H 1 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 1 +#define APR_HAVE_DIRENT_H 0 +#define APR_HAVE_ERRNO_H 1 +#define APR_HAVE_FCNTL_H 1 +#define APR_HAVE_IO_H 1 +#define APR_HAVE_LIMITS_H 1 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SEMAPHORE_H 0 +#define APR_HAVE_SIGNAL_H 1 +#define APR_HAVE_STDARG_H 1 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_SYS_IOCTL_H 0 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SIGNAL_H 0 +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#define APR_HAVE_SYS_TIME_H 0 +#define APR_HAVE_SYS_TYPES_H 1 +#define APR_HAVE_SYS_UIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#define APR_HAVE_SYS_WAIT_H 0 +#define APR_HAVE_TIME_H 1 +#define APR_HAVE_UNISTD_H 0 +#define APR_HAVE_STDDEF_H 1 +#define APR_HAVE_PROCESS_H 1 +#else +#define APR_HAVE_ARPA_INET_H 0 +#define APR_HAVE_CONIO_H 0 +#define APR_HAVE_CRYPT_H 0 +#define APR_HAVE_CTYPE_H 0 +#define APR_HAVE_DIRENT_H 0 +#define APR_HAVE_ERRNO_H 0 +#define APR_HAVE_FCNTL_H 0 +#define APR_HAVE_IO_H 0 +#define APR_HAVE_LIMITS_H 0 +#define APR_HAVE_NETDB_H 0 +#define APR_HAVE_NETINET_IN_H 0 +#define APR_HAVE_NETINET_SCTP_H 0 +#define APR_HAVE_NETINET_SCTP_UIO_H 0 +#define APR_HAVE_NETINET_TCP_H 0 +#define APR_HAVE_PTHREAD_H 0 +#define APR_HAVE_SEMAPHORE_H 0 +#define APR_HAVE_SIGNAL_H 0 +#define APR_HAVE_STDARG_H 0 +#define APR_HAVE_STDINT_H 0 +#define APR_HAVE_STDIO_H 1 +#define APR_HAVE_STDLIB_H 1 +#define APR_HAVE_STRING_H 1 +#define APR_HAVE_STRINGS_H 0 +#define APR_HAVE_SYS_IOCTL_H 0 +#define APR_HAVE_SYS_SENDFILE_H 0 +#define APR_HAVE_SYS_SIGNAL_H 0 +#define APR_HAVE_SYS_SOCKET_H 0 +#define APR_HAVE_SYS_SOCKIO_H 0 +#define APR_HAVE_SYS_SYSLIMITS_H 0 +#define APR_HAVE_SYS_TIME_H 0 +#define APR_HAVE_SYS_TYPES_H 0 +#define APR_HAVE_SYS_UIO_H 0 +#define APR_HAVE_SYS_UN_H 0 +#define APR_HAVE_SYS_WAIT_H 0 +#define APR_HAVE_TIME_H 0 +#define APR_HAVE_UNISTD_H 0 +#define APR_HAVE_STDDEF_H 0 +#define APR_HAVE_PROCESS_H 0 +#endif + +/** @} */ +/** @} */ + +/* We don't include our conditional headers within the doxyblocks + * or the extern "C" namespace + */ + +#if APR_HAVE_STDLIB_H +#include +#endif + +#if APR_HAVE_STDIO_H +#include +#endif + +#if APR_HAVE_SYS_TYPES_H +#include +#endif + +#if APR_HAVE_STDDEF_H +#include +#endif + +#if APR_HAVE_SYS_SOCKET_H +#include +#endif + +#if APR_HAVE_STDINT_H +#include +#endif + +#if APR_HAVE_SYS_WAIT_H +#include +#endif + +#if APR_HAVE_TIME_H +#include +#endif + +#if APR_HAVE_PROCESS_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @addtogroup apr_platform + * @ingroup APR + * @{ + */ + +#define APR_HAVE_SHMEM_MMAP_TMP 0 +#define APR_HAVE_SHMEM_MMAP_SHM 0 +#define APR_HAVE_SHMEM_MMAP_ZERO 0 +#define APR_HAVE_SHMEM_SHMGET_ANON 0 +#define APR_HAVE_SHMEM_SHMGET 0 +#define APR_HAVE_SHMEM_MMAP_ANON 0 +#define APR_HAVE_SHMEM_BEOS 0 + +#define APR_USE_SHMEM_MMAP_TMP 0 +#define APR_USE_SHMEM_MMAP_SHM 0 +#define APR_USE_SHMEM_MMAP_ZERO 0 +#define APR_USE_SHMEM_SHMGET_ANON 0 +#define APR_USE_SHMEM_SHMGET 0 +#define APR_USE_SHMEM_MMAP_ANON 0 +#define APR_USE_SHMEM_BEOS 0 + +#define APR_USE_FLOCK_SERIALIZE 0 +#define APR_USE_POSIXSEM_SERIALIZE 0 +#define APR_USE_SYSVSEM_SERIALIZE 0 +#define APR_USE_FCNTL_SERIALIZE 0 +#define APR_USE_PROC_PTHREAD_SERIALIZE 0 +#define APR_USE_PTHREAD_SERIALIZE 0 + +#define APR_HAS_FLOCK_SERIALIZE 0 +#define APR_HAS_SYSVSEM_SERIALIZE 0 +#define APR_HAS_POSIXSEM_SERIALIZE 0 +#define APR_HAS_FCNTL_SERIALIZE 0 +#define APR_HAS_PROC_PTHREAD_SERIALIZE 0 + +#define APR_PROCESS_LOCK_IS_GLOBAL 0 + +#define APR_HAVE_CORKABLE_TCP 0 +#define APR_HAVE_GETRLIMIT 0 +#define APR_HAVE_ICONV 0 +#define APR_HAVE_IN_ADDR 1 +#define APR_HAVE_INET_ADDR 1 +#define APR_HAVE_INET_NETWORK 0 +#define APR_HAVE_IPV6 @apr_have_ipv6_10@ +#define APR_HAVE_SOCKADDR_UN 0 +#define APR_HAVE_MEMMOVE 1 +#define APR_HAVE_SETRLIMIT 0 +#define APR_HAVE_SIGACTION 0 +#define APR_HAVE_SIGSUSPEND 0 +#define APR_HAVE_SIGWAIT 0 +#define APR_HAVE_SA_STORAGE 0 +#define APR_HAVE_STRCASECMP 0 +#define APR_HAVE_STRDUP 1 +#define APR_HAVE_STRNCASECMP 0 +#define APR_HAVE_STRSTR 1 +#define APR_HAVE_MEMCHR 1 +#define APR_HAVE_STRUCT_RLIMIT 0 +#define APR_HAVE_UNION_SEMUN 0 +#define APR_HAVE_SCTP 0 +#define APR_HAVE_IOVEC 0 + +#ifndef _WIN32_WCE +#define APR_HAVE_STRICMP 1 +#define APR_HAVE_STRNICMP 1 +#else +#define APR_HAVE_STRICMP 0 +#define APR_HAVE_STRNICMP 0 +#endif + +/* APR Feature Macros */ +#define APR_HAS_SHARED_MEMORY 1 +#define APR_HAS_THREADS 1 +#define APR_HAS_MMAP 1 +#define APR_HAS_FORK 0 +#define APR_HAS_RANDOM 1 +#define APR_HAS_OTHER_CHILD 1 +#define APR_HAS_DSO 1 +#define APR_HAS_SO_ACCEPTFILTER 0 +#define APR_HAS_UNICODE_FS 1 +#define APR_HAS_PROC_INVOKED 1 +#define APR_HAS_OS_UUID 1 +#define APR_HAS_TIMEDLOCKS 1 + +#ifndef _WIN32_WCE +#define APR_HAS_SENDFILE 1 +#define APR_HAS_USER 1 +#define APR_HAS_LARGE_FILES 1 +#define APR_HAS_XTHREAD_FILES 1 +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 1 +#else +#define APR_HAS_SENDFILE 0 +#define APR_HAS_USER 0 +#define APR_HAS_LARGE_FILES 0 +#define APR_HAS_XTHREAD_FILES 0 +#define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 0 +#endif + +/* APR sets APR_FILES_AS_SOCKETS to 1 on systems where it is possible + * to poll on files/pipes. + */ +#define APR_FILES_AS_SOCKETS 0 + +/* This macro indicates whether or not EBCDIC is the native character set. + */ +#define APR_CHARSET_EBCDIC 0 + +/* If we have a TCP implementation that can be "corked", what flag + * do we use? + */ +#define APR_TCP_NOPUSH_FLAG @apr_tcp_nopush_flag@ + +/* Is the TCP_NODELAY socket option inherited from listening sockets? + */ +#define APR_TCP_NODELAY_INHERITED 1 + +/* Is the O_NONBLOCK flag inherited from listening sockets? + */ +#define APR_O_NONBLOCK_INHERITED 1 + +/* Typedefs that APR needs. */ + +typedef unsigned char apr_byte_t; + +typedef short apr_int16_t; +typedef unsigned short apr_uint16_t; + +typedef int apr_int32_t; +typedef unsigned int apr_uint32_t; + +typedef __int64 apr_int64_t; +typedef unsigned __int64 apr_uint64_t; + +typedef size_t apr_size_t; +#if APR_HAVE_STDDEF_H +typedef ptrdiff_t apr_ssize_t; +#else +typedef int apr_ssize_t; +#endif +#if APR_HAS_LARGE_FILES +typedef __int64 apr_off_t; +#else +typedef int apr_off_t; +#endif +typedef int apr_socklen_t; +typedef apr_uint64_t apr_ino_t; + +#ifdef _WIN64 +#define APR_SIZEOF_VOIDP 8 +#else +#define APR_SIZEOF_VOIDP 4 +#endif + +#if APR_SIZEOF_VOIDP == 8 +typedef apr_uint64_t apr_uintptr_t; +#else +typedef apr_uint32_t apr_uintptr_t; +#endif + +/* Are we big endian? */ +/* XXX: Fatal assumption on Alpha platforms */ +#define APR_IS_BIGENDIAN 0 + +/* Mechanisms to properly type numeric literals */ + +#ifndef __GNUC__ +#define APR_INT64_C(val) (val##i64) +#define APR_UINT64_C(val) (val##Ui64) +#else +#define APR_INT64_C(val) (val##LL) +#define APR_UINT64_C(val) (val##ULL) +#endif + +#ifdef INT16_MIN +#define APR_INT16_MIN INT16_MIN +#else +#define APR_INT16_MIN (-0x7fff - 1) +#endif + +#ifdef INT16_MAX +#define APR_INT16_MAX INT16_MAX +#else +#define APR_INT16_MAX (0x7fff) +#endif + +#ifdef UINT16_MAX +#define APR_UINT16_MAX UINT16_MAX +#else +#define APR_UINT16_MAX (0xffff) +#endif + +#ifdef INT32_MIN +#define APR_INT32_MIN INT32_MIN +#else +#define APR_INT32_MIN (-0x7fffffff - 1) +#endif + +#ifdef INT32_MAX +#define APR_INT32_MAX INT32_MAX +#else +#define APR_INT32_MAX 0x7fffffff +#endif + +#ifdef UINT32_MAX +#define APR_UINT32_MAX UINT32_MAX +#else +#define APR_UINT32_MAX (0xffffffffU) +#endif + +#ifdef INT64_MIN +#define APR_INT64_MIN INT64_MIN +#else +#define APR_INT64_MIN (APR_INT64_C(-0x7fffffffffffffff) - 1) +#endif + +#ifdef INT64_MAX +#define APR_INT64_MAX INT64_MAX +#else +#define APR_INT64_MAX APR_INT64_C(0x7fffffffffffffff) +#endif + +#ifdef UINT64_MAX +#define APR_UINT64_MAX UINT64_MAX +#else +#define APR_UINT64_MAX APR_UINT64_C(0xffffffffffffffff) +#endif + +#define APR_SIZE_MAX (~((apr_size_t)0)) + +/* Definitions that APR programs need to work properly. */ + +/** + * APR public API wrap for C++ compilers. + */ +#ifdef __cplusplus +#define APR_BEGIN_DECLS extern "C" { +#define APR_END_DECLS } +#else +#define APR_BEGIN_DECLS +#define APR_END_DECLS +#endif + +/** + * Thread callbacks from APR functions must be declared with APR_THREAD_FUNC, + * so that they follow the platform's calling convention. + *
+ *
+ * void* APR_THREAD_FUNC my_thread_entry_fn(apr_thread_t *thd, void *data);
+ *
+ * 
+ */ +#define APR_THREAD_FUNC __stdcall + + +#if defined(DOXYGEN) || !defined(WIN32) + +/** + * The public APR functions are declared with APR_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APR_DECLARE_NONSTD(). + * + * @remark Both the declaration and implementations must use the same macro. + * + *
+ * APR_DECLARE(rettype) apr_func(args)
+ * 
+ * @see APR_DECLARE_NONSTD @see APR_DECLARE_DATA + * @remark Note that when APR compiles the library itself, it passes the + * symbol -DAPR_DECLARE_EXPORT to the compiler on some platforms (e.g. Win32) + * to export public symbols from the dynamic library build.\n + * The user must define the APR_DECLARE_STATIC when compiling to target + * the static APR library on some platforms (e.g. Win32.) The public symbols + * are neither exported nor imported when APR_DECLARE_STATIC is defined.\n + * By default, compiling an application and including the APR public + * headers, without defining APR_DECLARE_STATIC, will prepare the code to be + * linked to the dynamic library. + */ +#define APR_DECLARE(type) type + +/** + * The public APR functions using variable arguments are declared with + * APR_DECLARE_NONSTD(), as they must follow the C language calling convention. + * @see APR_DECLARE @see APR_DECLARE_DATA + * @remark Both the declaration and implementations must use the same macro. + *
+ *
+ * APR_DECLARE_NONSTD(rettype) apr_func(args, ...);
+ *
+ * 
+ */ +#define APR_DECLARE_NONSTD(type) type + +/** + * The public APR variables are declared with AP_MODULE_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * @see APR_DECLARE @see APR_DECLARE_NONSTD + * @remark Note that the declaration and implementations use different forms, + * but both must include the macro. + * + *
+ *
+ * extern APR_DECLARE_DATA type apr_variable;\n
+ * APR_DECLARE_DATA type apr_variable = value;
+ *
+ * 
+ */ +#define APR_DECLARE_DATA + +#elif defined(APR_DECLARE_STATIC) +#define APR_DECLARE(type) type __stdcall +#define APR_DECLARE_NONSTD(type) type __cdecl +#define APR_DECLARE_DATA +#elif defined(APR_DECLARE_EXPORT) +#define APR_DECLARE(type) __declspec(dllexport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllexport) +#else +#define APR_DECLARE(type) __declspec(dllimport) type __stdcall +#define APR_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APR_DECLARE_DATA __declspec(dllimport) +#endif + +#ifdef _WIN64 +#define APR_SSIZE_T_FMT "I64d" +#define APR_SIZE_T_FMT "I64u" +#else +#define APR_SSIZE_T_FMT "d" +#define APR_SIZE_T_FMT "u" +#endif + +#if APR_HAS_LARGE_FILES +#define APR_OFF_T_FMT "I64d" +#else +#define APR_OFF_T_FMT "d" +#endif + +#define APR_PID_T_FMT "d" + +#define APR_INT64_T_FMT "I64d" +#define APR_UINT64_T_FMT "I64u" +#define APR_UINT64_T_HEX_FMT "I64x" + +/* No difference between PROC and GLOBAL mutex */ +#define APR_PROC_MUTEX_IS_GLOBAL 1 + +/* Local machine definition for console and log output. */ +#define APR_EOL_STR "\r\n" + +typedef int apr_wait_t; + +#if APR_HAS_UNICODE_FS +/* An arbitrary size that is digestable. True max is a bit less than 32000 */ +#define APR_PATH_MAX 8192 +#else /* !APR_HAS_UNICODE_FS */ +#define APR_PATH_MAX MAX_PATH +#endif + +#define APR_DSOPATH "PATH" + +/** @} */ + +/* Definitions that only Win32 programs need to compile properly. */ + +/* XXX These simply don't belong here, perhaps in apr_portable.h + * based on some APR_HAVE_PID/GID/UID? + */ +#ifndef __GNUC__ +typedef int pid_t; +#endif +typedef int uid_t; +typedef int gid_t; + +/* Win32 .h ommissions we really need */ +#define STDIN_FILENO 0 +#define STDOUT_FILENO 1 +#define STDERR_FILENO 2 + +#if APR_HAVE_IPV6 + +/* Appears in later flavors, not the originals. */ +#ifndef in_addr6 +#define in6_addr in_addr6 +#endif + +#ifndef WS2TCPIP_INLINE +#define IN6_IS_ADDR_V4MAPPED(a) \ + ( (*(const apr_uint64_t *)(const void *)(&(a)->s6_addr[0]) == 0) \ + && (*(const apr_uint32_t *)(const void *)(&(a)->s6_addr[8]) == ntohl(0x0000ffff))) +#endif + +#endif /* APR_HAVE_IPV6 */ + +#ifdef __cplusplus +} +#endif + +/* Done with badly written headers, leave 'deprecated CRT' undeprecated + */ +#if defined(_MSC_VER) && _MSC_VER >= 1200 +#pragma warning(pop) +#if _MSC_VER >= 1400 +#pragma warning(disable: 4996) +#endif +#endif + +#endif /* WIN32 */ + +#endif /* APR_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_allocator.h b/c/dependencies/windows/apr/x86_debug/include/apr_allocator.h new file mode 100644 index 00000000..be05d0e4 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_allocator.h @@ -0,0 +1,179 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ALLOCATOR_H +#define APR_ALLOCATOR_H + +/** + * @file apr_allocator.h + * @brief APR Internal Memory Allocation + */ + +#include "apr.h" +#include "apr_errno.h" +#define APR_WANT_MEMFUNC /**< For no good reason? */ +#include "apr_want.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_allocator Internal Memory Allocation + * @ingroup APR + * @{ + */ + +/** the allocator structure */ +typedef struct apr_allocator_t apr_allocator_t; +/** the structure which holds information about the allocation */ +typedef struct apr_memnode_t apr_memnode_t; + +/** basic memory node structure + * @note The next, ref and first_avail fields are available for use by the + * caller of apr_allocator_alloc(), the remaining fields are read-only. + * The next field has to be used with caution and sensibly set when the + * memnode is passed back to apr_allocator_free(). See apr_allocator_free() + * for details. + * The ref and first_avail fields will be properly restored by + * apr_allocator_free(). + */ +struct apr_memnode_t { + apr_memnode_t *next; /**< next memnode */ + apr_memnode_t **ref; /**< reference to self */ + apr_uint32_t index; /**< size */ + apr_uint32_t free_index; /**< how much free */ + char *first_avail; /**< pointer to first free memory */ + char *endp; /**< pointer to end of free memory */ +}; + +/** The base size of a memory node - aligned. */ +#define APR_MEMNODE_T_SIZE APR_ALIGN_DEFAULT(sizeof(apr_memnode_t)) + +/** Symbolic constants */ +#define APR_ALLOCATOR_MAX_FREE_UNLIMITED 0 + +/** + * Create a new allocator + * @param allocator The allocator we have just created. + * + */ +APR_DECLARE(apr_status_t) apr_allocator_create(apr_allocator_t **allocator) + __attribute__((nonnull(1))); + +/** + * Destroy an allocator + * @param allocator The allocator to be destroyed + * @remark Any memnodes not given back to the allocator prior to destroying + * will _not_ be free()d. + */ +APR_DECLARE(void) apr_allocator_destroy(apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +/** + * Allocate a block of mem from the allocator + * @param allocator The allocator to allocate from + * @param size The size of the mem to allocate (excluding the + * memnode structure) + */ +APR_DECLARE(apr_memnode_t *) apr_allocator_alloc(apr_allocator_t *allocator, + apr_size_t size) + __attribute__((nonnull(1))); + +/** + * Free a list of blocks of mem, giving them back to the allocator. + * The list is typically terminated by a memnode with its next field + * set to NULL. + * @param allocator The allocator to give the mem back to + * @param memnode The memory node to return + */ +APR_DECLARE(void) apr_allocator_free(apr_allocator_t *allocator, + apr_memnode_t *memnode) + __attribute__((nonnull(1,2))); + +/** + * Get the true size that would be allocated for the given size (including + * the header and alignment). + * @param allocator The allocator from which to the memory would be allocated + * @param size The size to align + * @return The aligned size (or zero on apr_size_t overflow) + */ +APR_DECLARE(apr_size_t) apr_allocator_align(apr_allocator_t *allocator, + apr_size_t size); + +#include "apr_pools.h" + +/** + * Set the owner of the allocator + * @param allocator The allocator to set the owner for + * @param pool The pool that is to own the allocator + * @remark Typically pool is the highest level pool using the allocator + */ +/* + * XXX: see if we can come up with something a bit better. Currently + * you can make a pool an owner, but if the pool doesn't use the allocator + * the allocator will never be destroyed. + */ +APR_DECLARE(void) apr_allocator_owner_set(apr_allocator_t *allocator, + apr_pool_t *pool) + __attribute__((nonnull(1))); + +/** + * Get the current owner of the allocator + * @param allocator The allocator to get the owner from + */ +APR_DECLARE(apr_pool_t *) apr_allocator_owner_get(apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +/** + * Set the current threshold at which the allocator should start + * giving blocks back to the system. + * @param allocator The allocator to set the threshold on + * @param size The threshold. 0 == unlimited. + */ +APR_DECLARE(void) apr_allocator_max_free_set(apr_allocator_t *allocator, + apr_size_t size) + __attribute__((nonnull(1))); + +#include "apr_thread_mutex.h" + +#if APR_HAS_THREADS +/** + * Set a mutex for the allocator to use + * @param allocator The allocator to set the mutex for + * @param mutex The mutex + */ +APR_DECLARE(void) apr_allocator_mutex_set(apr_allocator_t *allocator, + apr_thread_mutex_t *mutex) + __attribute__((nonnull(1))); + +/** + * Get the mutex currently set for the allocator + * @param allocator The allocator + */ +APR_DECLARE(apr_thread_mutex_t *) apr_allocator_mutex_get( + apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ALLOCATOR_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_anylock.h b/c/dependencies/windows/apr/x86_debug/include/apr_anylock.h new file mode 100644 index 00000000..51e97ff3 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_anylock.h @@ -0,0 +1,128 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_anylock.h + * @brief APR-Util transparent any lock flavor wrapper + */ +#ifndef APR_ANYLOCK_H +#define APR_ANYLOCK_H + +#include "apr_proc_mutex.h" +#include "apr_thread_mutex.h" +#include "apr_thread_rwlock.h" + +/** Structure that may contain any APR lock type */ +typedef struct apr_anylock_t { + /** Indicates what type of lock is in lock */ + enum tm_lock { + apr_anylock_none, /**< None */ + apr_anylock_procmutex, /**< Process-based */ + apr_anylock_threadmutex, /**< Thread-based */ + apr_anylock_readlock, /**< Read lock */ + apr_anylock_writelock /**< Write lock */ + } type; + /** Union of all possible APR locks */ + union apr_anylock_u_t { + apr_proc_mutex_t *pm; /**< Process mutex */ +#if APR_HAS_THREADS + apr_thread_mutex_t *tm; /**< Thread mutex */ + apr_thread_rwlock_t *rw; /**< Read-write lock */ +#endif + } lock; +} apr_anylock_t; + +#if APR_HAS_THREADS + +/** Lock an apr_anylock_t structure */ +#define APR_ANYLOCK_LOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_threadmutex) \ + ? apr_thread_mutex_lock((lck)->lock.tm) \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_lock((lck)->lock.pm) \ + : (((lck)->type == apr_anylock_readlock) \ + ? apr_thread_rwlock_rdlock((lck)->lock.rw) \ + : (((lck)->type == apr_anylock_writelock) \ + ? apr_thread_rwlock_wrlock((lck)->lock.rw) \ + : APR_EINVAL))))) + +#else /* APR_HAS_THREADS */ + +#define APR_ANYLOCK_LOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_lock((lck)->lock.pm) \ + : APR_EINVAL)) + +#endif /* APR_HAS_THREADS */ + +#if APR_HAS_THREADS + +/** Try to lock an apr_anylock_t structure */ +#define APR_ANYLOCK_TRYLOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_threadmutex) \ + ? apr_thread_mutex_trylock((lck)->lock.tm) \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_trylock((lck)->lock.pm) \ + : (((lck)->type == apr_anylock_readlock) \ + ? apr_thread_rwlock_tryrdlock((lck)->lock.rw) \ + : (((lck)->type == apr_anylock_writelock) \ + ? apr_thread_rwlock_trywrlock((lck)->lock.rw) \ + : APR_EINVAL))))) + +#else /* APR_HAS_THREADS */ + +#define APR_ANYLOCK_TRYLOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_trylock((lck)->lock.pm) \ + : APR_EINVAL)) + +#endif /* APR_HAS_THREADS */ + +#if APR_HAS_THREADS + +/** Unlock an apr_anylock_t structure */ +#define APR_ANYLOCK_UNLOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_threadmutex) \ + ? apr_thread_mutex_unlock((lck)->lock.tm) \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_unlock((lck)->lock.pm) \ + : ((((lck)->type == apr_anylock_readlock) || \ + ((lck)->type == apr_anylock_writelock)) \ + ? apr_thread_rwlock_unlock((lck)->lock.rw) \ + : APR_EINVAL)))) + +#else /* APR_HAS_THREADS */ + +#define APR_ANYLOCK_UNLOCK(lck) \ + (((lck)->type == apr_anylock_none) \ + ? APR_SUCCESS \ + : (((lck)->type == apr_anylock_procmutex) \ + ? apr_proc_mutex_unlock((lck)->lock.pm) \ + : APR_EINVAL)) + +#endif /* APR_HAS_THREADS */ + +#endif /* !APR_ANYLOCK_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_atomic.h b/c/dependencies/windows/apr/x86_debug/include/apr_atomic.h new file mode 100644 index 00000000..3d203edc --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_atomic.h @@ -0,0 +1,207 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ATOMIC_H +#define APR_ATOMIC_H + +/** + * @file apr_atomic.h + * @brief APR Atomic Operations + */ + +#include "apr.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_atomic Atomic Operations + * @ingroup APR + * @{ + */ + +/** + * this function is required on some platforms to initialize the + * atomic operation's internal structures + * @param p pool + * @return APR_SUCCESS on successful completion + * @remark Programs do NOT need to call this directly. APR will call this + * automatically from apr_initialize(). + * @internal + */ +APR_DECLARE(apr_status_t) apr_atomic_init(apr_pool_t *p); + +/* + * Atomic operations on 32-bit values + * Note: Each of these functions internally implements a memory barrier + * on platforms that require it + */ + +/** + * atomically read an apr_uint32_t from memory + * @param mem the pointer + */ +APR_DECLARE(apr_uint32_t) apr_atomic_read32(volatile apr_uint32_t *mem); + +/** + * atomically set an apr_uint32_t in memory + * @param mem pointer to the object + * @param val value that the object will assume + */ +APR_DECLARE(void) apr_atomic_set32(volatile apr_uint32_t *mem, apr_uint32_t val); + +/** + * atomically add 'val' to an apr_uint32_t + * @param mem pointer to the object + * @param val amount to add + * @return old value pointed to by mem + */ +APR_DECLARE(apr_uint32_t) apr_atomic_add32(volatile apr_uint32_t *mem, apr_uint32_t val); + +/** + * atomically subtract 'val' from an apr_uint32_t + * @param mem pointer to the object + * @param val amount to subtract + */ +APR_DECLARE(void) apr_atomic_sub32(volatile apr_uint32_t *mem, apr_uint32_t val); + +/** + * atomically increment an apr_uint32_t by 1 + * @param mem pointer to the object + * @return old value pointed to by mem + */ +APR_DECLARE(apr_uint32_t) apr_atomic_inc32(volatile apr_uint32_t *mem); + +/** + * atomically decrement an apr_uint32_t by 1 + * @param mem pointer to the atomic value + * @return zero if the value becomes zero on decrement, otherwise non-zero + */ +APR_DECLARE(int) apr_atomic_dec32(volatile apr_uint32_t *mem); + +/** + * compare an apr_uint32_t's value with 'cmp'. + * If they are the same swap the value with 'with' + * @param mem pointer to the value + * @param with what to swap it with + * @param cmp the value to compare it to + * @return the old value of *mem + */ +APR_DECLARE(apr_uint32_t) apr_atomic_cas32(volatile apr_uint32_t *mem, apr_uint32_t with, + apr_uint32_t cmp); + +/** + * exchange an apr_uint32_t's value with 'val'. + * @param mem pointer to the value + * @param val what to swap it with + * @return the old value of *mem + */ +APR_DECLARE(apr_uint32_t) apr_atomic_xchg32(volatile apr_uint32_t *mem, apr_uint32_t val); + +/* + * Atomic operations on 64-bit values + * Note: Each of these functions internally implements a memory barrier + * on platforms that require it + */ + +/** + * atomically read an apr_uint64_t from memory + * @param mem the pointer + */ +APR_DECLARE(apr_uint64_t) apr_atomic_read64(volatile apr_uint64_t *mem); + +/** + * atomically set an apr_uint64_t in memory + * @param mem pointer to the object + * @param val value that the object will assume + */ +APR_DECLARE(void) apr_atomic_set64(volatile apr_uint64_t *mem, apr_uint64_t val); + +/** + * atomically add 'val' to an apr_uint64_t + * @param mem pointer to the object + * @param val amount to add + * @return old value pointed to by mem + */ +APR_DECLARE(apr_uint64_t) apr_atomic_add64(volatile apr_uint64_t *mem, apr_uint64_t val); + +/** + * atomically subtract 'val' from an apr_uint64_t + * @param mem pointer to the object + * @param val amount to subtract + */ +APR_DECLARE(void) apr_atomic_sub64(volatile apr_uint64_t *mem, apr_uint64_t val); + +/** + * atomically increment an apr_uint64_t by 1 + * @param mem pointer to the object + * @return old value pointed to by mem + */ +APR_DECLARE(apr_uint64_t) apr_atomic_inc64(volatile apr_uint64_t *mem); + +/** + * atomically decrement an apr_uint64_t by 1 + * @param mem pointer to the atomic value + * @return zero if the value becomes zero on decrement, otherwise non-zero + */ +APR_DECLARE(int) apr_atomic_dec64(volatile apr_uint64_t *mem); + +/** + * compare an apr_uint64_t's value with 'cmp'. + * If they are the same swap the value with 'with' + * @param mem pointer to the value + * @param with what to swap it with + * @param cmp the value to compare it to + * @return the old value of *mem + */ +APR_DECLARE(apr_uint64_t) apr_atomic_cas64(volatile apr_uint64_t *mem, apr_uint64_t with, + apr_uint64_t cmp); + +/** + * exchange an apr_uint64_t's value with 'val'. + * @param mem pointer to the value + * @param val what to swap it with + * @return the old value of *mem + */ +APR_DECLARE(apr_uint64_t) apr_atomic_xchg64(volatile apr_uint64_t *mem, apr_uint64_t val); + +/** + * compare the pointer's value with cmp. + * If they are the same swap the value with 'with' + * @param mem pointer to the pointer + * @param with what to swap it with + * @param cmp the value to compare it to + * @return the old value of the pointer + */ +APR_DECLARE(void*) apr_atomic_casptr(volatile void **mem, void *with, const void *cmp); + +/** + * exchange a pair of pointer values + * @param mem pointer to the pointer + * @param with what to swap it with + * @return the old value of the pointer + */ +APR_DECLARE(void*) apr_atomic_xchgptr(volatile void **mem, void *with); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ATOMIC_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_base64.h b/c/dependencies/windows/apr/x86_debug/include/apr_base64.h new file mode 100644 index 00000000..17de1c58 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_base64.h @@ -0,0 +1,113 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * The apr_vsnprintf/apr_snprintf functions are based on, and used with the + * permission of, the SIO stdio-replacement strx_* functions by Panos + * Tsirigotis for xinetd. + */ + +/** + * @file apr_base64.h + * @brief APR-UTIL Base64 Encoding + */ +#ifndef APR_BASE64_H +#define APR_BASE64_H + +#include "apu.h" +#include "apr_general.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Base64 Base64 Encoding + * @ingroup APR_Util + * @{ + */ + +/* Simple BASE64 encode/decode functions. + * + * As we might encode binary strings, hence we require the length of + * the incoming plain source. And return the length of what we decoded. + * + * The decoding function takes any non valid char (i.e. whitespace, \0 + * or anything non A-Z,0-9 etc as terminal. + * + * plain strings/binary sequences are not assumed '\0' terminated. Encoded + * strings are neither. But probably should. + * + */ + +/** + * Given the length of an un-encoded string, get the length of the + * encoded string. + * @param len the length of an unencoded string. + * @return the length of the string after it is encoded, including the + * trailing \0 + */ +APU_DECLARE(int) apr_base64_encode_len(int len); + +/** + * Encode a text string using base64encoding. + * @param coded_dst The destination string for the encoded string. + * @param plain_src The original string in plain text + * @param len_plain_src The length of the plain text string + * @return the length of the encoded string + */ +APU_DECLARE(int) apr_base64_encode(char * coded_dst, const char *plain_src, + int len_plain_src); + +/** + * Encode an EBCDIC string using base64encoding. + * @param coded_dst The destination string for the encoded string. + * @param plain_src The original string in plain text + * @param len_plain_src The length of the plain text string + * @return the length of the encoded string + */ +APU_DECLARE(int) apr_base64_encode_binary(char * coded_dst, + const unsigned char *plain_src, + int len_plain_src); + +/** + * Determine the maximum buffer length required to decode the plain text + * string given the encoded string. + * @param coded_src The encoded string + * @return the maximum required buffer length for the plain text string + */ +APU_DECLARE(int) apr_base64_decode_len(const char * coded_src); + +/** + * Decode a string to plain text + * @param plain_dst The destination string for the plain text + * @param coded_src The encoded string + * @return the length of the plain text string + */ +APU_DECLARE(int) apr_base64_decode(char * plain_dst, const char *coded_src); + +/** + * Decode an EBCDIC string to plain text + * @param plain_dst The destination string for the plain text + * @param coded_src The encoded string + * @return the length of the plain text string + */ +APU_DECLARE(int) apr_base64_decode_binary(unsigned char * plain_dst, + const char *coded_src); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_BASE64_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_buckets.h b/c/dependencies/windows/apr/x86_debug/include/apr_buckets.h new file mode 100644 index 00000000..ce64b78d --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_buckets.h @@ -0,0 +1,1598 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file apr_buckets.h + * @brief APR-UTIL Buckets/Bucket Brigades + */ + +#ifndef APR_BUCKETS_H +#define APR_BUCKETS_H + +#if defined(APR_BUCKET_DEBUG) && !defined(APR_RING_DEBUG) +#define APR_RING_DEBUG +#endif + +#include "apu.h" +#include "apr_network_io.h" +#include "apr_file_io.h" +#include "apr_general.h" +#include "apr_mmap.h" +#include "apr_errno.h" +#include "apr_ring.h" +#include "apr.h" +#if APR_HAVE_SYS_UIO_H +#include /* for struct iovec */ +#endif +#if APR_HAVE_STDARG_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Bucket_Brigades Bucket Brigades + * @ingroup APR_Util + * @{ + */ + +/** default bucket buffer size - 8KB minus room for memory allocator headers */ +#define APR_BUCKET_BUFF_SIZE 8000 + +/** Determines how a bucket or brigade should be read */ +typedef enum { + APR_BLOCK_READ, /**< block until data becomes available */ + APR_NONBLOCK_READ /**< return immediately if no data is available */ +} apr_read_type_e; + +/** + * The one-sentence buzzword-laden overview: Bucket brigades represent + * a complex data stream that can be passed through a layered IO + * system without unnecessary copying. A longer overview follows... + * + * A bucket brigade is a doubly linked list (ring) of buckets, so we + * aren't limited to inserting at the front and removing at the end. + * Buckets are only passed around as members of a brigade, although + * singleton buckets can occur for short periods of time. + * + * Buckets are data stores of various types. They can refer to data in + * memory, or part of a file or mmap area, or the output of a process, + * etc. Buckets also have some type-dependent accessor functions: + * read, split, copy, setaside, and destroy. + * + * read returns the address and size of the data in the bucket. If the + * data isn't in memory then it is read in and the bucket changes type + * so that it can refer to the new location of the data. If all the + * data doesn't fit in the bucket then a new bucket is inserted into + * the brigade to hold the rest of it. + * + * split divides the data in a bucket into two regions. After a split + * the original bucket refers to the first part of the data and a new + * bucket inserted into the brigade after the original bucket refers + * to the second part of the data. Reference counts are maintained as + * necessary. + * + * setaside ensures that the data in the bucket has a long enough + * lifetime. Sometimes it is convenient to create a bucket referring + * to data on the stack in the expectation that it will be consumed + * (output to the network) before the stack is unwound. If that + * expectation turns out not to be valid, the setaside function is + * called to move the data somewhere safer. + * + * copy makes a duplicate of the bucket structure as long as it's + * possible to have multiple references to a single copy of the + * data itself. Not all bucket types can be copied. + * + * destroy maintains the reference counts on the resources used by a + * bucket and frees them if necessary. + * + * Note: all of the above functions have wrapper macros (apr_bucket_read(), + * apr_bucket_destroy(), etc), and those macros should be used rather + * than using the function pointers directly. + * + * To write a bucket brigade, they are first made into an iovec, so that we + * don't write too little data at one time. Currently we ignore compacting the + * buckets into as few buckets as possible, but if we really want good + * performance, then we need to compact the buckets before we convert to an + * iovec, or possibly while we are converting to an iovec. + */ + +/* + * Forward declaration of the main types. + */ + +/** @see apr_bucket_brigade */ +typedef struct apr_bucket_brigade apr_bucket_brigade; +/** @see apr_bucket */ +typedef struct apr_bucket apr_bucket; +/** @see apr_bucket_alloc_t */ +typedef struct apr_bucket_alloc_t apr_bucket_alloc_t; + +/** @see apr_bucket_type_t */ +typedef struct apr_bucket_type_t apr_bucket_type_t; + +/** + * Basic bucket type + */ +struct apr_bucket_type_t { + /** + * The name of the bucket type + */ + const char *name; + /** + * The number of functions this bucket understands. Can not be less than + * five. + */ + int num_func; + /** + * Whether the bucket contains metadata (ie, information that + * describes the regular contents of the brigade). The metadata + * is not returned by apr_bucket_read() and is not indicated by + * the ->length of the apr_bucket itself. In other words, an + * empty bucket is safe to arbitrarily remove if and only if it + * contains no metadata. In this sense, "data" is just raw bytes + * that are the "content" of the brigade and "metadata" describes + * that data but is not a proper part of it. + */ + enum { + /** This bucket type represents actual data to send to the client. */ + APR_BUCKET_DATA = 0, + /** This bucket type represents metadata. */ + APR_BUCKET_METADATA = 1 + } is_metadata; + /** + * Free the private data and any resources used by the bucket (if they + * aren't shared with another bucket). This function is required to be + * implemented for all bucket types, though it might be a no-op on some + * of them (namely ones that never allocate any private data structures). + * @param data The private data pointer from the bucket to be destroyed + */ + void (*destroy)(void *data); + + /** + * Read the data from the bucket. This is required to be implemented + * for all bucket types. + * @param b The bucket to read from + * @param str A place to store the data read. Allocation should only be + * done if absolutely necessary. + * @param len The amount of data read. + * @param block Should this read function block if there is more data that + * cannot be read immediately. + */ + apr_status_t (*read)(apr_bucket *b, const char **str, apr_size_t *len, + apr_read_type_e block); + + /** + * Make it possible to set aside the data for at least as long as the + * given pool. Buckets containing data that could potentially die before + * this pool (e.g. the data resides on the stack, in a child pool of + * the given pool, or in a disjoint pool) must somehow copy, shift, or + * transform the data to have the proper lifetime. + * @param e The bucket to convert + * @remark Some bucket types contain data that will always outlive the + * bucket itself. For example no data (EOS and FLUSH), or the data + * resides in global, constant memory (IMMORTAL), or the data is on + * the heap (HEAP). For these buckets, apr_bucket_setaside_noop can + * be used. + */ + apr_status_t (*setaside)(apr_bucket *e, apr_pool_t *pool); + + /** + * Split one bucket in two at the specified position by duplicating + * the bucket structure (not the data) and modifying any necessary + * start/end/offset information. If it's not possible to do this + * for the bucket type (perhaps the length of the data is indeterminate, + * as with pipe and socket buckets), then APR_ENOTIMPL is returned. + * @param e The bucket to split + * @param point The offset of the first byte in the new bucket + */ + apr_status_t (*split)(apr_bucket *e, apr_size_t point); + + /** + * Copy the bucket structure (not the data), assuming that this is + * possible for the bucket type. If it's not, APR_ENOTIMPL is returned. + * @param e The bucket to copy + * @param c Returns a pointer to the new bucket + */ + apr_status_t (*copy)(apr_bucket *e, apr_bucket **c); + +}; + +/** + * apr_bucket structures are allocated on the malloc() heap and + * their lifetime is controlled by the parent apr_bucket_brigade + * structure. Buckets can move from one brigade to another e.g. by + * calling APR_BRIGADE_CONCAT(). In general the data in a bucket has + * the same lifetime as the bucket and is freed when the bucket is + * destroyed; if the data is shared by more than one bucket (e.g. + * after a split) the data is freed when the last bucket goes away. + */ +struct apr_bucket { + /** Links to the rest of the brigade */ + APR_RING_ENTRY(apr_bucket) link; + /** The type of bucket. */ + const apr_bucket_type_t *type; + /** The length of the data in the bucket. This could have been implemented + * with a function, but this is an optimization, because the most + * common thing to do will be to get the length. If the length is unknown, + * the value of this field will be (apr_size_t)(-1). + */ + apr_size_t length; + /** The start of the data in the bucket relative to the private base + * pointer. The vast majority of bucket types allow a fixed block of + * data to be referenced by multiple buckets, each bucket pointing to + * a different segment of the data. That segment starts at base+start + * and ends at base+start+length. + * If the length == (apr_size_t)(-1), then start == -1. + */ + apr_off_t start; + /** type-dependent data hangs off this pointer */ + void *data; + /** + * Pointer to function used to free the bucket. This function should + * always be defined and it should be consistent with the memory + * function used to allocate the bucket. For example, if malloc() is + * used to allocate the bucket, this pointer should point to free(). + * @param e Pointer to the bucket being freed + */ + void (*free)(void *e); + /** The freelist from which this bucket was allocated */ + apr_bucket_alloc_t *list; +}; + +/** A list of buckets */ +struct apr_bucket_brigade { + /** The pool to associate the brigade with. The data is not allocated out + * of the pool, but a cleanup is registered with this pool. If the + * brigade is destroyed by some mechanism other than pool destruction, + * the destroying function is responsible for killing the cleanup. + */ + apr_pool_t *p; + /** The buckets in the brigade are on this list. */ + /* + * The apr_bucket_list structure doesn't actually need a name tag + * because it has no existence independent of struct apr_bucket_brigade; + * the ring macros are designed so that you can leave the name tag + * argument empty in this situation but apparently the Windows compiler + * doesn't like that. + */ + APR_RING_HEAD(apr_bucket_list, apr_bucket) list; + /** The freelist from which this bucket was allocated */ + apr_bucket_alloc_t *bucket_alloc; +}; + + +/** + * Function called when a brigade should be flushed + */ +typedef apr_status_t (*apr_brigade_flush)(apr_bucket_brigade *bb, void *ctx); + +/* + * define APR_BUCKET_DEBUG if you want your brigades to be checked for + * validity at every possible instant. this will slow your code down + * substantially but is a very useful debugging tool. + */ +#ifdef APR_BUCKET_DEBUG + +#define APR_BRIGADE_CHECK_CONSISTENCY(b) \ + APR_RING_CHECK_CONSISTENCY(&(b)->list, apr_bucket, link) + +#define APR_BUCKET_CHECK_CONSISTENCY(e) \ + APR_RING_CHECK_ELEM_CONSISTENCY((e), apr_bucket, link) + +#else +/** + * checks the ring pointers in a bucket brigade for consistency. an + * abort() will be triggered if any inconsistencies are found. + * note: this is a no-op unless APR_BUCKET_DEBUG is defined. + * @param b The brigade + */ +#define APR_BRIGADE_CHECK_CONSISTENCY(b) +/** + * checks the brigade a bucket is in for ring consistency. an + * abort() will be triggered if any inconsistencies are found. + * note: this is a no-op unless APR_BUCKET_DEBUG is defined. + * @param e The bucket + */ +#define APR_BUCKET_CHECK_CONSISTENCY(e) +#endif + + +/** + * Wrappers around the RING macros to reduce the verbosity of the code + * that handles bucket brigades. + */ +/** + * The magic pointer value that indicates the head of the brigade + * @remark This is used to find the beginning and end of the brigade, eg: + *
+ *      while (e != APR_BRIGADE_SENTINEL(b)) {
+ *          ...
+ *          e = APR_BUCKET_NEXT(e);
+ *      }
+ * 
+ * @param b The brigade + * @return The magic pointer value + */ +#define APR_BRIGADE_SENTINEL(b) APR_RING_SENTINEL(&(b)->list, apr_bucket, link) + +/** + * Determine if the bucket brigade is empty + * @param b The brigade to check + * @return true or false + */ +#define APR_BRIGADE_EMPTY(b) APR_RING_EMPTY(&(b)->list, apr_bucket, link) + +/** + * Return the first bucket in a brigade + * @param b The brigade to query + * @return The first bucket in the brigade + */ +#define APR_BRIGADE_FIRST(b) APR_RING_FIRST(&(b)->list) +/** + * Return the last bucket in a brigade + * @param b The brigade to query + * @return The last bucket in the brigade + */ +#define APR_BRIGADE_LAST(b) APR_RING_LAST(&(b)->list) + +/** + * Insert a single bucket at the front of a brigade + * @param b The brigade to add to + * @param e The bucket to insert + */ +#define APR_BRIGADE_INSERT_HEAD(b, e) do { \ + apr_bucket *ap__b = (e); \ + APR_RING_INSERT_HEAD(&(b)->list, ap__b, apr_bucket, link); \ + APR_BRIGADE_CHECK_CONSISTENCY((b)); \ + } while (0) + +/** + * Insert a single bucket at the end of a brigade + * @param b The brigade to add to + * @param e The bucket to insert + */ +#define APR_BRIGADE_INSERT_TAIL(b, e) do { \ + apr_bucket *ap__b = (e); \ + APR_RING_INSERT_TAIL(&(b)->list, ap__b, apr_bucket, link); \ + APR_BRIGADE_CHECK_CONSISTENCY((b)); \ + } while (0) + +/** + * Concatenate brigade b onto the end of brigade a, leaving brigade b empty + * @param a The first brigade + * @param b The second brigade + */ +#define APR_BRIGADE_CONCAT(a, b) do { \ + APR_RING_CONCAT(&(a)->list, &(b)->list, apr_bucket, link); \ + APR_BRIGADE_CHECK_CONSISTENCY((a)); \ + } while (0) + +/** + * Prepend brigade b onto the beginning of brigade a, leaving brigade b empty + * @param a The first brigade + * @param b The second brigade + */ +#define APR_BRIGADE_PREPEND(a, b) do { \ + APR_RING_PREPEND(&(a)->list, &(b)->list, apr_bucket, link); \ + APR_BRIGADE_CHECK_CONSISTENCY((a)); \ + } while (0) + +/** + * Insert a single bucket before a specified bucket + * @param a The bucket to insert before + * @param b The bucket to insert + */ +#define APR_BUCKET_INSERT_BEFORE(a, b) do { \ + apr_bucket *ap__a = (a), *ap__b = (b); \ + APR_RING_INSERT_BEFORE(ap__a, ap__b, link); \ + APR_BUCKET_CHECK_CONSISTENCY(ap__a); \ + } while (0) + +/** + * Insert a single bucket after a specified bucket + * @param a The bucket to insert after + * @param b The bucket to insert + */ +#define APR_BUCKET_INSERT_AFTER(a, b) do { \ + apr_bucket *ap__a = (a), *ap__b = (b); \ + APR_RING_INSERT_AFTER(ap__a, ap__b, link); \ + APR_BUCKET_CHECK_CONSISTENCY(ap__a); \ + } while (0) + +/** + * Get the next bucket in the list + * @param e The current bucket + * @return The next bucket + */ +#define APR_BUCKET_NEXT(e) APR_RING_NEXT((e), link) +/** + * Get the previous bucket in the list + * @param e The current bucket + * @return The previous bucket + */ +#define APR_BUCKET_PREV(e) APR_RING_PREV((e), link) + +/** + * Remove a bucket from its bucket brigade + * @param e The bucket to remove + */ +#define APR_BUCKET_REMOVE(e) APR_RING_REMOVE((e), link) + +/** + * Initialize a new bucket's prev/next pointers + * @param e The bucket to initialize + */ +#define APR_BUCKET_INIT(e) APR_RING_ELEM_INIT((e), link) + +/** + * Determine if a bucket contains metadata. An empty bucket is + * safe to arbitrarily remove if and only if this is false. + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_METADATA(e) ((e)->type->is_metadata) + +/** + * Determine if a bucket is a FLUSH bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_FLUSH(e) ((e)->type == &apr_bucket_type_flush) +/** + * Determine if a bucket is an EOS bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_EOS(e) ((e)->type == &apr_bucket_type_eos) +/** + * Determine if a bucket is a FILE bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_FILE(e) ((e)->type == &apr_bucket_type_file) +/** + * Determine if a bucket is a PIPE bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_PIPE(e) ((e)->type == &apr_bucket_type_pipe) +/** + * Determine if a bucket is a SOCKET bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_SOCKET(e) ((e)->type == &apr_bucket_type_socket) +/** + * Determine if a bucket is a HEAP bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_HEAP(e) ((e)->type == &apr_bucket_type_heap) +/** + * Determine if a bucket is a TRANSIENT bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_TRANSIENT(e) ((e)->type == &apr_bucket_type_transient) +/** + * Determine if a bucket is a IMMORTAL bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_IMMORTAL(e) ((e)->type == &apr_bucket_type_immortal) +#if APR_HAS_MMAP +/** + * Determine if a bucket is a MMAP bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_MMAP(e) ((e)->type == &apr_bucket_type_mmap) +#endif +/** + * Determine if a bucket is a POOL bucket + * @param e The bucket to inspect + * @return true or false + */ +#define APR_BUCKET_IS_POOL(e) ((e)->type == &apr_bucket_type_pool) + +/* + * General-purpose reference counting for the various bucket types. + * + * Any bucket type that keeps track of the resources it uses (i.e. + * most of them except for IMMORTAL, TRANSIENT, and EOS) needs to + * attach a reference count to the resource so that it can be freed + * when the last bucket that uses it goes away. Resource-sharing may + * occur because of bucket splits or buckets that refer to globally + * cached data. */ + +/** @see apr_bucket_refcount */ +typedef struct apr_bucket_refcount apr_bucket_refcount; +/** + * The structure used to manage the shared resource must start with an + * apr_bucket_refcount which is updated by the general-purpose refcount + * code. A pointer to the bucket-type-dependent private data structure + * can be cast to a pointer to an apr_bucket_refcount and vice versa. + */ +struct apr_bucket_refcount { + /** The number of references to this bucket */ + int refcount; +}; + +/* ***** Reference-counted bucket types ***** */ + +/** @see apr_bucket_heap */ +typedef struct apr_bucket_heap apr_bucket_heap; +/** + * A bucket referring to data allocated off the heap. + */ +struct apr_bucket_heap { + /** Number of buckets using this memory */ + apr_bucket_refcount refcount; + /** The start of the data actually allocated. This should never be + * modified, it is only used to free the bucket. + */ + char *base; + /** how much memory was allocated */ + apr_size_t alloc_len; + /** function to use to delete the data */ + void (*free_func)(void *data); +}; + +/** @see apr_bucket_pool */ +typedef struct apr_bucket_pool apr_bucket_pool; +/** + * A bucket referring to data allocated from a pool + */ +struct apr_bucket_pool { + /** The pool bucket must be able to be easily morphed to a heap + * bucket if the pool gets cleaned up before all references are + * destroyed. This apr_bucket_heap structure is populated automatically + * when the pool gets cleaned up, and subsequent calls to pool_read() + * will result in the apr_bucket in question being morphed into a + * regular heap bucket. (To avoid having to do many extra refcount + * manipulations and b->data manipulations, the apr_bucket_pool + * struct actually *contains* the apr_bucket_heap struct that it + * will become as its first element; the two share their + * apr_bucket_refcount members.) + */ + apr_bucket_heap heap; + /** The block of data actually allocated from the pool. + * Segments of this block are referenced by adjusting + * the start and length of the apr_bucket accordingly. + * This will be NULL after the pool gets cleaned up. + */ + const char *base; + /** The pool the data was allocated from. When the pool + * is cleaned up, this gets set to NULL as an indicator + * to pool_read() that the data is now on the heap and + * so it should morph the bucket into a regular heap + * bucket before continuing. + */ + apr_pool_t *pool; + /** The freelist this structure was allocated from, which is + * needed in the cleanup phase in order to allocate space on the heap + */ + apr_bucket_alloc_t *list; +}; + +#if APR_HAS_MMAP +/** @see apr_bucket_mmap */ +typedef struct apr_bucket_mmap apr_bucket_mmap; +/** + * A bucket referring to an mmap()ed file + */ +struct apr_bucket_mmap { + /** Number of buckets using this memory */ + apr_bucket_refcount refcount; + /** The mmap this sub_bucket refers to */ + apr_mmap_t *mmap; +}; +#endif + +/** @see apr_bucket_file */ +typedef struct apr_bucket_file apr_bucket_file; +/** + * A bucket referring to an file + */ +struct apr_bucket_file { + /** Number of buckets using this memory */ + apr_bucket_refcount refcount; + /** The file this bucket refers to */ + apr_file_t *fd; + /** The pool into which any needed structures should + * be created while reading from this file bucket */ + apr_pool_t *readpool; +#if APR_HAS_MMAP + /** Whether this bucket should be memory-mapped if + * a caller tries to read from it */ + int can_mmap; +#endif /* APR_HAS_MMAP */ + /** File read block size */ + apr_size_t read_size; +}; + +/** @see apr_bucket_structs */ +typedef union apr_bucket_structs apr_bucket_structs; +/** + * A union of all bucket structures so we know what + * the max size is. + */ +union apr_bucket_structs { + apr_bucket b; /**< Bucket */ + apr_bucket_heap heap; /**< Heap */ + apr_bucket_pool pool; /**< Pool */ +#if APR_HAS_MMAP + apr_bucket_mmap mmap; /**< MMap */ +#endif + apr_bucket_file file; /**< File */ +}; + +/** + * The amount that apr_bucket_alloc() should allocate in the common case. + * Note: this is twice as big as apr_bucket_structs to allow breathing + * room for third-party bucket types. + */ +#define APR_BUCKET_ALLOC_SIZE APR_ALIGN_DEFAULT(2*sizeof(apr_bucket_structs)) + +/* ***** Bucket Brigade Functions ***** */ +/** + * Create a new bucket brigade. The bucket brigade is originally empty. + * @param p The pool to associate with the brigade. Data is not allocated out + * of the pool, but a cleanup is registered. + * @param list The bucket allocator to use + * @return The empty bucket brigade + */ +APU_DECLARE(apr_bucket_brigade *) apr_brigade_create(apr_pool_t *p, + apr_bucket_alloc_t *list); + +/** + * destroy an entire bucket brigade. This includes destroying all of the + * buckets within the bucket brigade's bucket list. + * @param b The bucket brigade to destroy + */ +APU_DECLARE(apr_status_t) apr_brigade_destroy(apr_bucket_brigade *b); + +/** + * empty out an entire bucket brigade. This includes destroying all of the + * buckets within the bucket brigade's bucket list. This is similar to + * apr_brigade_destroy(), except that it does not deregister the brigade's + * pool cleanup function. + * @param data The bucket brigade to clean up + * @remark Generally, you should use apr_brigade_destroy(). This function + * can be useful in situations where you have a single brigade that + * you wish to reuse many times by destroying all of the buckets in + * the brigade and putting new buckets into it later. + */ +APU_DECLARE(apr_status_t) apr_brigade_cleanup(void *data); + +/** + * Move the buckets from the tail end of the existing brigade @a b into + * the brigade @a a. If @a a is NULL a new brigade is created. Buckets + * from @a e to the last bucket (inclusively) of brigade @a b are moved + * from @a b to the returned brigade @a a. + * + * @param b The brigade to split + * @param e The first bucket to move + * @param a The brigade which should be used for the result or NULL if + * a new brigade should be created. The brigade @a a will be + * cleared if it is not empty. + * @return The brigade supplied in @a a or a new one if @a a was NULL. + * @warning Note that this function allocates a new brigade if @a a is + * NULL so memory consumption should be carefully considered. + */ +APU_DECLARE(apr_bucket_brigade *) apr_brigade_split_ex(apr_bucket_brigade *b, + apr_bucket *e, + apr_bucket_brigade *a); + +/** + * Create a new bucket brigade and move the buckets from the tail end + * of an existing brigade into the new brigade. Buckets from + * @a e to the last bucket (inclusively) of brigade @a b + * are moved from @a b to the returned brigade. + * @param b The brigade to split + * @param e The first bucket to move + * @return The new brigade + * @warning Note that this function always allocates a new brigade + * so memory consumption should be carefully considered. + */ +APU_DECLARE(apr_bucket_brigade *) apr_brigade_split(apr_bucket_brigade *b, + apr_bucket *e); + +/** + * Partition a bucket brigade at a given offset (in bytes from the start of + * the brigade). This is useful whenever a filter wants to use known ranges + * of bytes from the brigade; the ranges can even overlap. + * @param b The brigade to partition + * @param point The offset at which to partition the brigade + * @param after_point Returns a pointer to the first bucket after the partition + * @return APR_SUCCESS on success, APR_INCOMPLETE if the contents of the + * brigade were shorter than @a point, or an error code. + * @remark if APR_INCOMPLETE is returned, @a after_point will be set to + * the brigade sentinel. + */ +APU_DECLARE(apr_status_t) apr_brigade_partition(apr_bucket_brigade *b, + apr_off_t point, + apr_bucket **after_point); + +/** + * Return the total length of the brigade. + * @param bb The brigade to compute the length of + * @param read_all Read unknown-length buckets to force a size + * @param length Returns the length of the brigade (up to the end, or up + * to a bucket read error), or -1 if the brigade has buckets + * of indeterminate length and read_all is 0. + */ +APU_DECLARE(apr_status_t) apr_brigade_length(apr_bucket_brigade *bb, + int read_all, + apr_off_t *length); + +/** + * Take a bucket brigade and store the data in a flat char* + * @param bb The bucket brigade to create the char* from + * @param c The char* to write into + * @param len The maximum length of the char array. On return, it is the + * actual length of the char array. + */ +APU_DECLARE(apr_status_t) apr_brigade_flatten(apr_bucket_brigade *bb, + char *c, + apr_size_t *len); + +/** + * Creates a pool-allocated string representing a flat bucket brigade + * @param bb The bucket brigade to create the char array from + * @param c On return, the allocated char array + * @param len On return, the length of the char array. + * @param pool The pool to allocate the string from. + */ +APU_DECLARE(apr_status_t) apr_brigade_pflatten(apr_bucket_brigade *bb, + char **c, + apr_size_t *len, + apr_pool_t *pool); + +/** + * Split a brigade to represent one LF line. + * @param bbOut The bucket brigade that will have the LF line appended to. + * @param bbIn The input bucket brigade to search for a LF-line. + * @param block The blocking mode to be used to split the line. + * @param maxbytes The maximum bytes to read. If this many bytes are seen + * without a LF, the brigade will contain a partial line. + */ +APU_DECLARE(apr_status_t) apr_brigade_split_line(apr_bucket_brigade *bbOut, + apr_bucket_brigade *bbIn, + apr_read_type_e block, + apr_off_t maxbytes); + +/** + * Create an iovec of the elements in a bucket_brigade... return number + * of elements used. This is useful for writing to a file or to the + * network efficiently. + * @param b The bucket brigade to create the iovec from + * @param vec The iovec to create + * @param nvec The number of elements in the iovec. On return, it is the + * number of iovec elements actually filled out. + */ +APU_DECLARE(apr_status_t) apr_brigade_to_iovec(apr_bucket_brigade *b, + struct iovec *vec, int *nvec); + +/** + * This function writes a list of strings into a bucket brigade. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param va A list of strings to add + * @return APR_SUCCESS or error code. + */ +APU_DECLARE(apr_status_t) apr_brigade_vputstrs(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, + va_list va); + +/** + * This function writes a string into a bucket brigade. + * + * The apr_brigade_write function attempts to be efficient with the + * handling of heap buckets. Regardless of the amount of data stored + * inside a heap bucket, heap buckets are a fixed size to promote their + * reuse. + * + * If an attempt is made to write a string to a brigade that already + * ends with a heap bucket, this function will attempt to pack the + * string into the remaining space in the previous heap bucket, before + * allocating a new heap bucket. + * + * This function always returns APR_SUCCESS, unless a flush function is + * passed, in which case the return value of the flush function will be + * returned if used. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param str The string to add + * @param nbyte The number of bytes to write + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_write(apr_bucket_brigade *b, + apr_brigade_flush flush, void *ctx, + const char *str, apr_size_t nbyte); + +/** + * This function writes multiple strings into a bucket brigade. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param vec The strings to add (address plus length for each) + * @param nvec The number of entries in iovec + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_writev(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, + const struct iovec *vec, + apr_size_t nvec); + +/** + * This function writes a string into a bucket brigade. + * @param bb The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param str The string to add + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_puts(apr_bucket_brigade *bb, + apr_brigade_flush flush, void *ctx, + const char *str); + +/** + * This function writes a character into a bucket brigade. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param c The character to add + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_putc(apr_bucket_brigade *b, + apr_brigade_flush flush, void *ctx, + const char c); + +/** + * This function writes an unspecified number of strings into a bucket brigade. + * @param b The bucket brigade to add to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param ... The strings to add + * @return APR_SUCCESS or error code + */ +APU_DECLARE_NONSTD(apr_status_t) apr_brigade_putstrs(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, ...); + +/** + * Evaluate a printf and put the resulting string at the end + * of the bucket brigade. + * @param b The brigade to write to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param fmt The format of the string to write + * @param ... The arguments to fill out the format + * @return APR_SUCCESS or error code + */ +APU_DECLARE_NONSTD(apr_status_t) apr_brigade_printf(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, + const char *fmt, ...) + __attribute__((format(printf,4,5))); + +/** + * Evaluate a printf and put the resulting string at the end + * of the bucket brigade. + * @param b The brigade to write to + * @param flush The flush function to use if the brigade is full + * @param ctx The structure to pass to the flush function + * @param fmt The format of the string to write + * @param va The arguments to fill out the format + * @return APR_SUCCESS or error code + */ +APU_DECLARE(apr_status_t) apr_brigade_vprintf(apr_bucket_brigade *b, + apr_brigade_flush flush, + void *ctx, + const char *fmt, va_list va); + +/** + * Utility function to insert a file (or a segment of a file) onto the + * end of the brigade. The file is split into multiple buckets if it + * is larger than the maximum size which can be represented by a + * single bucket. + * @param bb the brigade to insert into + * @param f the file to insert + * @param start the offset of the start of the segment + * @param len the length of the segment of the file to insert + * @param p pool from which file buckets are allocated + * @return the last bucket inserted + */ +APU_DECLARE(apr_bucket *) apr_brigade_insert_file(apr_bucket_brigade *bb, + apr_file_t *f, + apr_off_t start, + apr_off_t len, + apr_pool_t *p); + + + +/* ***** Bucket freelist functions ***** */ +/** + * Create a bucket allocator. + * @param p This pool's underlying apr_allocator_t is used to allocate memory + * for the bucket allocator. When the pool is destroyed, the bucket + * allocator's cleanup routine will free all memory that has been + * allocated from it. + * @remark The reason the allocator gets its memory from the pool's + * apr_allocator_t rather than from the pool itself is because + * the bucket allocator will free large memory blocks back to the + * allocator when it's done with them, thereby preventing memory + * footprint growth that would occur if we allocated from the pool. + * @warning The allocator must never be used by more than one thread at a time. + */ +APU_DECLARE_NONSTD(apr_bucket_alloc_t *) apr_bucket_alloc_create(apr_pool_t *p); + +/** + * Create a bucket allocator. + * @param allocator This apr_allocator_t is used to allocate both the bucket + * allocator and all memory handed out by the bucket allocator. The + * caller is responsible for destroying the bucket allocator and the + * apr_allocator_t -- no automatic cleanups will happen. + * @warning The allocator must never be used by more than one thread at a time. + */ +APU_DECLARE_NONSTD(apr_bucket_alloc_t *) apr_bucket_alloc_create_ex(apr_allocator_t *allocator); + +/** + * Destroy a bucket allocator. + * @param list The allocator to be destroyed + */ +APU_DECLARE_NONSTD(void) apr_bucket_alloc_destroy(apr_bucket_alloc_t *list); + +/** + * Get the aligned size corresponding to the requested size, but minus the + * allocator(s) overhead such that the allocation would remain in the + * same boundary. + * @param list The allocator from which to the memory would be allocated. + * @param size The requested size. + * @return The corresponding aligned/floored size. + */ +APU_DECLARE_NONSTD(apr_size_t) apr_bucket_alloc_aligned_floor(apr_bucket_alloc_t *list, + apr_size_t size) + __attribute__((nonnull(1))); + +/** + * Allocate memory for use by the buckets. + * @param size The amount to allocate. + * @param list The allocator from which to allocate the memory. + */ +APU_DECLARE_NONSTD(void *) apr_bucket_alloc(apr_size_t size, apr_bucket_alloc_t *list); + +/** + * Free memory previously allocated with apr_bucket_alloc(). + * @param block The block of memory to be freed. + */ +APU_DECLARE_NONSTD(void) apr_bucket_free(void *block); + + +/* ***** Bucket Functions ***** */ +/** + * Free the resources used by a bucket. If multiple buckets refer to + * the same resource it is freed when the last one goes away. + * @see apr_bucket_delete() + * @param e The bucket to destroy + */ +#define apr_bucket_destroy(e) do { \ + (e)->type->destroy((e)->data); \ + (e)->free(e); \ + } while (0) + +/** + * Delete a bucket by removing it from its brigade (if any) and then + * destroying it. + * @remark This mainly acts as an aid in avoiding code verbosity. It is + * the preferred exact equivalent to: + *
+ *      APR_BUCKET_REMOVE(e);
+ *      apr_bucket_destroy(e);
+ * 
+ * @param e The bucket to delete + */ +#define apr_bucket_delete(e) do { \ + APR_BUCKET_REMOVE(e); \ + apr_bucket_destroy(e); \ + } while (0) + +/** + * Read some data from the bucket. + * + * The apr_bucket_read function returns a convenient amount of data + * from the bucket provided, writing the address and length of the + * data to the pointers provided by the caller. The function tries + * as hard as possible to avoid a memory copy. + * + * Buckets are expected to be a member of a brigade at the time they + * are read. + * + * In typical application code, buckets are read in a loop, and after + * each bucket is read and processed, it is moved or deleted from the + * brigade and the next bucket read. + * + * The definition of "convenient" depends on the type of bucket that + * is being read, and is decided by APR. In the case of memory based + * buckets such as heap and immortal buckets, a pointer will be + * returned to the location of the buffer containing the complete + * contents of the bucket. + * + * Some buckets, such as the socket bucket, might have no concept + * of length. If an attempt is made to read such a bucket, the + * apr_bucket_read function will read a convenient amount of data + * from the socket. The socket bucket is magically morphed into a + * heap bucket containing the just-read data, and a new socket bucket + * is inserted just after this heap bucket. + * + * To understand why apr_bucket_read might do this, consider the loop + * described above to read and process buckets. The current bucket + * is magically morphed into a heap bucket and returned to the caller. + * The caller processes the data, and deletes the heap bucket, moving + * onto the next bucket, the new socket bucket. This process repeats, + * giving the illusion of a bucket brigade that contains potentially + * infinite amounts of data. It is up to the caller to decide at what + * point to stop reading buckets. + * + * Some buckets, such as the file bucket, might have a fixed size, + * but be significantly larger than is practical to store in RAM in + * one go. As with the socket bucket, if an attempt is made to read + * from a file bucket, the file bucket is magically morphed into a + * heap bucket containing a convenient amount of data read from the + * current offset in the file. During the read, the offset will be + * moved forward on the file, and a new file bucket will be inserted + * directly after the current bucket representing the remainder of the + * file. If the heap bucket was large enough to store the whole + * remainder of the file, no more file buckets are inserted, and the + * file bucket will disappear completely. + * + * The pattern for reading buckets described above does create the + * illusion that the code is willing to swallow buckets that might be + * too large for the system to handle in one go. This however is just + * an illusion: APR will always ensure that large (file) or infinite + * (socket) buckets are broken into convenient bite sized heap buckets + * before data is returned to the caller. + * + * There is a potential gotcha to watch for: if buckets are read in a + * loop, and aren't deleted after being processed, the potentially large + * bucket will slowly be converted into RAM resident heap buckets. If + * the file is larger than available RAM, an out of memory condition + * could be caused if the application is not careful to manage this. + * + * @param e The bucket to read from + * @param str The location to store a pointer to the data in + * @param len The location to store the amount of data read + * @param block Whether the read function blocks + */ +#define apr_bucket_read(e,str,len,block) (e)->type->read(e, str, len, block) + +/** + * Setaside data so that stack data is not destroyed on returning from + * the function + * @param e The bucket to setaside + * @param p The pool to setaside into + */ +#define apr_bucket_setaside(e,p) (e)->type->setaside(e,p) + +/** + * Split one bucket in two at the point provided. + * + * Once split, the original bucket becomes the first of the two new buckets. + * + * (It is assumed that the bucket is a member of a brigade when this + * function is called). + * @param e The bucket to split + * @param point The offset to split the bucket at + */ +#define apr_bucket_split(e,point) (e)->type->split(e, point) + +/** + * Copy a bucket. + * @param e The bucket to copy + * @param c Returns a pointer to the new bucket + */ +#define apr_bucket_copy(e,c) (e)->type->copy(e, c) + +/* Bucket type handling */ + +/** + * This function simply returns APR_SUCCESS to denote that the bucket does + * not require anything to happen for its setaside() function. This is + * appropriate for buckets that have "immortal" data -- the data will live + * at least as long as the bucket. + * @param data The bucket to setaside + * @param pool The pool defining the desired lifetime of the bucket data + * @return APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_setaside_noop(apr_bucket *data, + apr_pool_t *pool); + +/** + * A place holder function that signifies that the setaside function was not + * implemented for this bucket + * @param data The bucket to setaside + * @param pool The pool defining the desired lifetime of the bucket data + * @return APR_ENOTIMPL + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_setaside_notimpl(apr_bucket *data, + apr_pool_t *pool); + +/** + * A place holder function that signifies that the split function was not + * implemented for this bucket + * @param data The bucket to split + * @param point The location to split the bucket + * @return APR_ENOTIMPL + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_split_notimpl(apr_bucket *data, + apr_size_t point); + +/** + * A place holder function that signifies that the copy function was not + * implemented for this bucket + * @param e The bucket to copy + * @param c Returns a pointer to the new bucket + * @return APR_ENOTIMPL + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_copy_notimpl(apr_bucket *e, + apr_bucket **c); + +/** + * A place holder function that signifies that this bucket does not need + * to do anything special to be destroyed. That's only the case for buckets + * that either have no data (metadata buckets) or buckets whose data pointer + * points to something that's not a bucket-type-specific structure, as with + * simple buckets where data points to a string and pipe buckets where data + * points directly to the apr_file_t. + * @param data The bucket data to destroy + */ +APU_DECLARE_NONSTD(void) apr_bucket_destroy_noop(void *data); + +/** + * There is no apr_bucket_destroy_notimpl, because destruction is required + * to be implemented (it could be a noop, but only if that makes sense for + * the bucket type) + */ + +/* There is no apr_bucket_read_notimpl, because it is a required function + */ + + +/* All of the bucket types implemented by the core */ +/** + * The flush bucket type. This signifies that all data should be flushed to + * the next filter. The flush bucket should be sent with the other buckets. + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_flush; +/** + * The EOS bucket type. This signifies that there will be no more data, ever. + * All filters MUST send all data to the next filter when they receive a + * bucket of this type + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_eos; +/** + * The FILE bucket type. This bucket represents a file on disk + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_file; +/** + * The HEAP bucket type. This bucket represents a data allocated from the + * heap. + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_heap; +#if APR_HAS_MMAP +/** + * The MMAP bucket type. This bucket represents an MMAP'ed file + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_mmap; +#endif +/** + * The POOL bucket type. This bucket represents a data that was allocated + * from a pool. IF this bucket is still available when the pool is cleared, + * the data is copied on to the heap. + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_pool; +/** + * The PIPE bucket type. This bucket represents a pipe to another program. + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_pipe; +/** + * The IMMORTAL bucket type. This bucket represents a segment of data that + * the creator is willing to take responsibility for. The core will do + * nothing with the data in an immortal bucket + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_immortal; +/** + * The TRANSIENT bucket type. This bucket represents a data allocated off + * the stack. When the setaside function is called, this data is copied on + * to the heap + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_transient; +/** + * The SOCKET bucket type. This bucket represents a socket to another machine + */ +APU_DECLARE_DATA extern const apr_bucket_type_t apr_bucket_type_socket; + + +/* ***** Simple buckets ***** */ + +/** + * Split a simple bucket into two at the given point. Most non-reference + * counting buckets that allow multiple references to the same block of + * data (eg transient and immortal) will use this as their split function + * without any additional type-specific handling. + * @param b The bucket to be split + * @param point The offset of the first byte in the new bucket + * @return APR_EINVAL if the point is not within the bucket; + * APR_ENOMEM if allocation failed; + * or APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_simple_split(apr_bucket *b, + apr_size_t point); + +/** + * Copy a simple bucket. Most non-reference-counting buckets that allow + * multiple references to the same block of data (eg transient and immortal) + * will use this as their copy function without any additional type-specific + * handling. + * @param a The bucket to copy + * @param b Returns a pointer to the new bucket + * @return APR_ENOMEM if allocation failed; + * or APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_simple_copy(apr_bucket *a, + apr_bucket **b); + + +/* ***** Shared, reference-counted buckets ***** */ + +/** + * Initialize a bucket containing reference-counted data that may be + * shared. The caller must allocate the bucket if necessary and + * initialize its type-dependent fields, and allocate and initialize + * its own private data structure. This function should only be called + * by type-specific bucket creation functions. + * @param b The bucket to initialize + * @param data A pointer to the private data structure + * with the reference count at the start + * @param start The start of the data in the bucket + * relative to the private base pointer + * @param length The length of the data in the bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_shared_make(apr_bucket *b, void *data, + apr_off_t start, + apr_size_t length); + +/** + * Decrement the refcount of the data in the bucket. This function + * should only be called by type-specific bucket destruction functions. + * @param data The private data pointer from the bucket to be destroyed + * @return TRUE or FALSE; TRUE if the reference count is now + * zero, indicating that the shared resource itself can + * be destroyed by the caller. + */ +APU_DECLARE(int) apr_bucket_shared_destroy(void *data); + +/** + * Split a bucket into two at the given point, and adjust the refcount + * to the underlying data. Most reference-counting bucket types will + * be able to use this function as their split function without any + * additional type-specific handling. + * @param b The bucket to be split + * @param point The offset of the first byte in the new bucket + * @return APR_EINVAL if the point is not within the bucket; + * APR_ENOMEM if allocation failed; + * or APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_shared_split(apr_bucket *b, + apr_size_t point); + +/** + * Copy a refcounted bucket, incrementing the reference count. Most + * reference-counting bucket types will be able to use this function + * as their copy function without any additional type-specific handling. + * @param a The bucket to copy + * @param b Returns a pointer to the new bucket + * @return APR_ENOMEM if allocation failed; + or APR_SUCCESS + */ +APU_DECLARE_NONSTD(apr_status_t) apr_bucket_shared_copy(apr_bucket *a, + apr_bucket **b); + + +/* ***** Functions to Create Buckets of varying types ***** */ +/* + * Each bucket type foo has two initialization functions: + * apr_bucket_foo_make which sets up some already-allocated memory as a + * bucket of type foo; and apr_bucket_foo_create which allocates memory + * for the bucket, calls apr_bucket_make_foo, and initializes the + * bucket's list pointers. The apr_bucket_foo_make functions are used + * inside the bucket code to change the type of buckets in place; + * other code should call apr_bucket_foo_create. All the initialization + * functions change nothing if they fail. + */ + +/** + * Create an End of Stream bucket. This indicates that there is no more data + * coming from down the filter stack. All filters should flush at this point. + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_eos_create(apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in an EOS bucket. This indicates that there is no + * more data coming from down the filter stack. All filters should flush at + * this point. + * @param b The bucket to make into an EOS bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_eos_make(apr_bucket *b); + +/** + * Create a flush bucket. This indicates that filters should flush their + * data. There is no guarantee that they will flush it, but this is the + * best we can do. + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_flush_create(apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a FLUSH bucket. This indicates that filters + * should flush their data. There is no guarantee that they will flush it, + * but this is the best we can do. + * @param b The bucket to make into a FLUSH bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_flush_make(apr_bucket *b); + +/** + * Create a bucket referring to long-lived data. + * @param buf The data to insert into the bucket + * @param nbyte The size of the data to insert. + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_immortal_create(const char *buf, + apr_size_t nbyte, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to long-lived data + * @param b The bucket to make into a IMMORTAL bucket + * @param buf The data to insert into the bucket + * @param nbyte The size of the data to insert. + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_immortal_make(apr_bucket *b, + const char *buf, + apr_size_t nbyte); + +/** + * Create a bucket referring to data on the stack. + * @param buf The data to insert into the bucket + * @param nbyte The size of the data to insert. + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_transient_create(const char *buf, + apr_size_t nbyte, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to stack data + * @param b The bucket to make into a TRANSIENT bucket + * @param buf The data to insert into the bucket + * @param nbyte The size of the data to insert. + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_transient_make(apr_bucket *b, + const char *buf, + apr_size_t nbyte); + +/** + * Create a bucket referring to memory on the heap. If the caller asks + * for the data to be copied, this function always allocates 4K of + * memory so that more data can be added to the bucket without + * requiring another allocation. Therefore not all the data may be put + * into the bucket. If copying is not requested then the bucket takes + * over responsibility for free()ing the memory. + * @param buf The buffer to insert into the bucket + * @param nbyte The size of the buffer to insert. + * @param free_func Function to use to free the data; NULL indicates that the + * bucket should make a copy of the data + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_heap_create(const char *buf, + apr_size_t nbyte, + void (*free_func)(void *data), + apr_bucket_alloc_t *list); +/** + * Make the bucket passed in a bucket refer to heap data + * @param b The bucket to make into a HEAP bucket + * @param buf The buffer to insert into the bucket + * @param nbyte The size of the buffer to insert. + * @param free_func Function to use to free the data; NULL indicates that the + * bucket should make a copy of the data + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_heap_make(apr_bucket *b, const char *buf, + apr_size_t nbyte, + void (*free_func)(void *data)); + +/** + * Create a bucket referring to memory allocated from a pool. + * + * @param buf The buffer to insert into the bucket + * @param length The number of bytes referred to by this bucket + * @param pool The pool the memory was allocated from + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_pool_create(const char *buf, + apr_size_t length, + apr_pool_t *pool, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to pool data + * @param b The bucket to make into a pool bucket + * @param buf The buffer to insert into the bucket + * @param length The number of bytes referred to by this bucket + * @param pool The pool the memory was allocated from + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_pool_make(apr_bucket *b, const char *buf, + apr_size_t length, + apr_pool_t *pool); + +#if APR_HAS_MMAP +/** + * Create a bucket referring to mmap()ed memory. + * @param mm The mmap to insert into the bucket + * @param start The offset of the first byte in the mmap + * that this bucket refers to + * @param length The number of bytes referred to by this bucket + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_mmap_create(apr_mmap_t *mm, + apr_off_t start, + apr_size_t length, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to an MMAP'ed file + * @param b The bucket to make into a MMAP bucket + * @param mm The mmap to insert into the bucket + * @param start The offset of the first byte in the mmap + * that this bucket refers to + * @param length The number of bytes referred to by this bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_mmap_make(apr_bucket *b, apr_mmap_t *mm, + apr_off_t start, + apr_size_t length); +#endif + +/** + * Create a bucket referring to a socket. + * @param thissock The socket to put in the bucket + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_socket_create(apr_socket_t *thissock, + apr_bucket_alloc_t *list); +/** + * Make the bucket passed in a bucket refer to a socket + * @param b The bucket to make into a SOCKET bucket + * @param thissock The socket to put in the bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_socket_make(apr_bucket *b, + apr_socket_t *thissock); + +/** + * Create a bucket referring to a pipe. + * @param thispipe The pipe to put in the bucket + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_pipe_create(apr_file_t *thispipe, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to a pipe + * @param b The bucket to make into a PIPE bucket + * @param thispipe The pipe to put in the bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_pipe_make(apr_bucket *b, + apr_file_t *thispipe); + +/** + * Create a bucket referring to a file. + * @param fd The file to put in the bucket + * @param offset The offset where the data of interest begins in the file + * @param len The amount of data in the file we are interested in + * @param p The pool into which any needed structures should be created + * while reading from this file bucket + * @param list The freelist from which this bucket should be allocated + * @return The new bucket, or NULL if allocation failed + * @remark If the file is truncated such that the segment of the file + * referenced by the bucket no longer exists, an attempt to read + * from the bucket will fail with APR_EOF. + * @remark apr_brigade_insert_file() should generally be used to + * insert files into brigades, since that function can correctly + * handle large file issues. + */ +APU_DECLARE(apr_bucket *) apr_bucket_file_create(apr_file_t *fd, + apr_off_t offset, + apr_size_t len, + apr_pool_t *p, + apr_bucket_alloc_t *list); + +/** + * Make the bucket passed in a bucket refer to a file + * @param b The bucket to make into a FILE bucket + * @param fd The file to put in the bucket + * @param offset The offset where the data of interest begins in the file + * @param len The amount of data in the file we are interested in + * @param p The pool into which any needed structures should be created + * while reading from this file bucket + * @return The new bucket, or NULL if allocation failed + */ +APU_DECLARE(apr_bucket *) apr_bucket_file_make(apr_bucket *b, apr_file_t *fd, + apr_off_t offset, + apr_size_t len, apr_pool_t *p); + +/** + * Enable or disable memory-mapping for a FILE bucket (default is enabled) + * @param b The bucket + * @param enabled Whether memory-mapping should be enabled + * @return APR_SUCCESS normally, or an error code if the operation fails + */ +APU_DECLARE(apr_status_t) apr_bucket_file_enable_mmap(apr_bucket *b, + int enabled); + +/** + * Set the size of the read buffer allocated by a FILE bucket (default + * is @a APR_BUCKET_BUFF_SIZE) + * memory-mapping is disabled only) + * @param b The bucket + * @param size Size of the allocated buffers + * @return APR_SUCCESS normally, or an error code if the operation fails + * @remark Relevant/used only when memory-mapping is disabled (@see + * apr_bucket_file_enable_mmap) + */ +APU_DECLARE(apr_status_t) apr_bucket_file_set_buf_size(apr_bucket *e, + apr_size_t size); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_BUCKETS_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_crypto.h b/c/dependencies/windows/apr/x86_debug/include/apr_crypto.h new file mode 100644 index 00000000..b90f3fec --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_crypto.h @@ -0,0 +1,507 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_CRYPTO_H +#define APR_CRYPTO_H + +#include "apu.h" +#include "apr_pools.h" +#include "apr_tables.h" +#include "apr_hash.h" +#include "apu_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_crypto.h + * @brief APR-UTIL Crypto library + */ +/** + * @defgroup APR_Util_Crypto Crypto routines + * @ingroup APR_Util + * @{ + */ + +#if APU_HAVE_CRYPTO + +#ifndef APU_CRYPTO_RECOMMENDED_DRIVER +#if APU_HAVE_COMMONCRYPTO +#define APU_CRYPTO_RECOMMENDED_DRIVER "commoncrypto" +#else +#if APU_HAVE_OPENSSL +#define APU_CRYPTO_RECOMMENDED_DRIVER "openssl" +#else +#if APU_HAVE_NSS +#define APU_CRYPTO_RECOMMENDED_DRIVER "nss" +#else +#if APU_HAVE_MSCNG +#define APU_CRYPTO_RECOMMENDED_DRIVER "mscng" +#else +#if APU_HAVE_MSCAPI +#define APU_CRYPTO_RECOMMENDED_DRIVER "mscapi" +#else +#endif +#endif +#endif +#endif +#endif +#endif + +/** + * Symmetric Key types understood by the library. + * + * NOTE: It is expected that this list will grow over time. + * + * Interoperability Matrix: + * + * The matrix is based on the testcrypto.c unit test, which attempts to + * test whether a simple encrypt/decrypt will succeed, as well as testing + * whether an encrypted string by one library can be decrypted by the + * others. + * + * Some libraries will successfully encrypt and decrypt their own data, + * but won't decrypt data from another library. It is hoped that over + * time these anomalies will be found and fixed, but until then it is + * recommended that ciphers are chosen that interoperate across platform. + * + * An X below means the test passes, it does not necessarily mean that + * encryption performed is correct or secure. Applications should stick + * to ciphers that pass the interoperablity tests on the right hand side + * of the table. + * + * Aligned data is data whose length is a multiple of the block size for + * the chosen cipher. Padded data is data that is not aligned by block + * size and must be padded by the crypto library. + * + * OpenSSL CommonCrypto NSS Interop + * Align Pad Align Pad Align Pad Align Pad + * 3DES_192/CBC X X X X X X X X + * 3DES_192/ECB X X X X + * AES_256/CBC X X X X X X X X + * AES_256/ECB X X X X X X + * AES_192/CBC X X X X X X + * AES_192/ECB X X X X X + * AES_128/CBC X X X X X X + * AES_128/ECB X X X X X + * + * Conclusion: for padded data, use 3DES_192/CBC or AES_256/CBC. For + * aligned data, use 3DES_192/CBC, AES_256/CBC or AES_256/ECB. + */ + +typedef enum +{ + APR_KEY_NONE, APR_KEY_3DES_192, /** 192 bit (3-Key) 3DES */ + APR_KEY_AES_128, /** 128 bit AES */ + APR_KEY_AES_192, /** 192 bit AES */ + APR_KEY_AES_256 +/** 256 bit AES */ +} apr_crypto_block_key_type_e; + +typedef enum +{ + APR_MODE_NONE, /** An error condition */ + APR_MODE_ECB, /** Electronic Code Book */ + APR_MODE_CBC +/** Cipher Block Chaining */ +} apr_crypto_block_key_mode_e; + +/* These are opaque structs. Instantiation is up to each backend */ +typedef struct apr_crypto_driver_t apr_crypto_driver_t; +typedef struct apr_crypto_t apr_crypto_t; +typedef struct apr_crypto_config_t apr_crypto_config_t; +typedef struct apr_crypto_key_t apr_crypto_key_t; +typedef struct apr_crypto_block_t apr_crypto_block_t; + +typedef struct apr_crypto_block_key_type_t { + apr_crypto_block_key_type_e type; + int keysize; + int blocksize; + int ivsize; +} apr_crypto_block_key_type_t; + +typedef struct apr_crypto_block_key_mode_t { + apr_crypto_block_key_mode_e mode; +} apr_crypto_block_key_mode_t; + +typedef struct apr_crypto_passphrase_t { + const char *pass; + apr_size_t passLen; + const unsigned char * salt; + apr_size_t saltLen; + int iterations; +} apr_crypto_passphrase_t; + +typedef struct apr_crypto_secret_t { + const unsigned char *secret; + apr_size_t secretLen; +} apr_crypto_secret_t; + +typedef enum { + /** Key is derived from a passphrase */ + APR_CRYPTO_KTYPE_PASSPHRASE = 1, + /** Key is derived from a raw key */ + APR_CRYPTO_KTYPE_SECRET = 2, +} apr_crypto_key_type; + +typedef struct apr_crypto_key_rec_t { + apr_crypto_key_type ktype; + apr_crypto_block_key_type_e type; + apr_crypto_block_key_mode_e mode; + int pad; + union { + apr_crypto_passphrase_t passphrase; + apr_crypto_secret_t secret; + } k; +} apr_crypto_key_rec_t; + +/** + * @brief Perform once-only initialisation. Call once only. + * + * @param pool - pool to register any shutdown cleanups, etc + * @return APR_NOTIMPL in case of no crypto support. + */ +APU_DECLARE(apr_status_t) apr_crypto_init(apr_pool_t *pool); + +/** + * @brief Zero out the buffer provided when the pool is cleaned up. + * + * @param pool - pool to register the cleanup + * @param buffer - buffer to zero out + * @param size - size of the buffer to zero out + */ +APU_DECLARE(apr_status_t) apr_crypto_clear(apr_pool_t *pool, void *buffer, + apr_size_t size); + +/** + * @brief Always zero out the buffer provided, without being optimized out by + * the compiler. + * + * @param buffer - buffer to zero out + * @param size - size of the buffer to zero out + */ +APU_DECLARE(apr_status_t) apr_crypto_memzero(void *buffer, apr_size_t size); + +/** + * @brief Timing attacks safe buffers comparison, where the executing time does + * not depend on the bytes compared but solely on the number of bytes. + * + * @param buf1 - first buffer to compare + * @param buf2 - second buffer to compare + * @param size - size of the buffers to compare + * @return 1 if the buffers are equals, 0 otherwise. + */ +APU_DECLARE(int) apr_crypto_equals(const void *buf1, const void *buf2, + apr_size_t size); + +/** + * @brief Get the driver struct for a name + * + * @param driver - pointer to driver struct. + * @param name - driver name + * @param params - array of initialisation parameters + * @param result - result and error message on failure + * @param pool - (process) pool to register cleanup + * @return APR_SUCCESS for success + * @return APR_ENOTIMPL for no driver (when DSO not enabled) + * @return APR_EDSOOPEN if DSO driver file can't be opened + * @return APR_ESYMNOTFOUND if the driver file doesn't contain a driver + * @remarks NSS: the params can have "dir", "key3", "cert7" and "secmod" + * keys, each followed by an equal sign and a value. Such key/value pairs can + * be delimited by space or tab. If the value contains a space, surround the + * whole key value pair in quotes: "dir=My Directory". + * @remarks OpenSSL: currently no params are supported. + */ +APU_DECLARE(apr_status_t) apr_crypto_get_driver( + const apr_crypto_driver_t **driver, + const char *name, const char *params, const apu_err_t **result, + apr_pool_t *pool); + +/** + * @brief Return the name of the driver. + * + * @param driver - The driver in use. + * @return The name of the driver. + */ +APU_DECLARE(const char *) apr_crypto_driver_name( + const apr_crypto_driver_t *driver); + +/** + * @brief Get the result of the last operation on a context. If the result + * is NULL, the operation was successful. + * @param result - the result structure + * @param f - context pointer + * @return APR_SUCCESS for success + */ +APU_DECLARE(apr_status_t) apr_crypto_error(const apu_err_t **result, + const apr_crypto_t *f); + +/** + * @brief Create a context for supporting encryption. Keys, certificates, + * algorithms and other parameters will be set per context. More than + * one context can be created at one time. A cleanup will be automatically + * registered with the given pool to guarantee a graceful shutdown. + * @param f - context pointer will be written here + * @param driver - driver to use + * @param params - array of key parameters + * @param pool - process pool + * @return APR_ENOENGINE when the engine specified does not exist. APR_EINITENGINE + * if the engine cannot be initialised. + * @remarks NSS: currently no params are supported. + * @remarks OpenSSL: the params can have "engine" as a key, followed by an equal + * sign and a value. + */ +APU_DECLARE(apr_status_t) apr_crypto_make(apr_crypto_t **f, + const apr_crypto_driver_t *driver, const char *params, + apr_pool_t *pool); + +/** + * @brief Get a hash table of key types, keyed by the name of the type against + * a pointer to apr_crypto_block_key_type_t, which in turn begins with an + * integer. + * + * @param types - hashtable of key types keyed to constants. + * @param f - encryption context + * @return APR_SUCCESS for success + */ +APU_DECLARE(apr_status_t) apr_crypto_get_block_key_types(apr_hash_t **types, + const apr_crypto_t *f); + +/** + * @brief Get a hash table of key modes, keyed by the name of the mode against + * a pointer to apr_crypto_block_key_mode_t, which in turn begins with an + * integer. + * + * @param modes - hashtable of key modes keyed to constants. + * @param f - encryption context + * @return APR_SUCCESS for success + */ +APU_DECLARE(apr_status_t) apr_crypto_get_block_key_modes(apr_hash_t **modes, + const apr_crypto_t *f); + +/** + * @brief Create a key from the provided secret or passphrase. The key is cleaned + * up when the context is cleaned, and may be reused with multiple encryption + * or decryption operations. + * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If + * *key is not NULL, *key must point at a previously created structure. + * @param key The key returned, see note. + * @param rec The key record, from which the key will be derived. + * @param f The context to use. + * @param p The pool to use. + * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend + * error occurred while generating the key. APR_ENOCIPHER if the type or mode + * is not supported by the particular backend. APR_EKEYTYPE if the key type is + * not known. APR_EPADDING if padding was requested but is not supported. + * APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_key(apr_crypto_key_t **key, + const apr_crypto_key_rec_t *rec, const apr_crypto_t *f, apr_pool_t *p); + +/** + * @brief Create a key from the given passphrase. By default, the PBKDF2 + * algorithm is used to generate the key from the passphrase. It is expected + * that the same pass phrase will generate the same key, regardless of the + * backend crypto platform used. The key is cleaned up when the context + * is cleaned, and may be reused with multiple encryption or decryption + * operations. + * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If + * *key is not NULL, *key must point at a previously created structure. + * @param key The key returned, see note. + * @param ivSize The size of the initialisation vector will be returned, based + * on whether an IV is relevant for this type of crypto. + * @param pass The passphrase to use. + * @param passLen The passphrase length in bytes + * @param salt The salt to use. + * @param saltLen The salt length in bytes + * @param type 3DES_192, AES_128, AES_192, AES_256. + * @param mode Electronic Code Book / Cipher Block Chaining. + * @param doPad Pad if necessary. + * @param iterations Number of iterations to use in algorithm + * @param f The context to use. + * @param p The pool to use. + * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend + * error occurred while generating the key. APR_ENOCIPHER if the type or mode + * is not supported by the particular backend. APR_EKEYTYPE if the key type is + * not known. APR_EPADDING if padding was requested but is not supported. + * APR_ENOTIMPL if not implemented. + * @deprecated Replaced by apr_crypto_key(). + */ +APU_DECLARE(apr_status_t) apr_crypto_passphrase(apr_crypto_key_t **key, + apr_size_t *ivSize, const char *pass, apr_size_t passLen, + const unsigned char * salt, apr_size_t saltLen, + const apr_crypto_block_key_type_e type, + const apr_crypto_block_key_mode_e mode, const int doPad, + const int iterations, const apr_crypto_t *f, apr_pool_t *p); + +/** + * @brief Initialise a context for encrypting arbitrary data using the given key. + * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If + * *ctx is not NULL, *ctx must point at a previously created structure. + * @param ctx The block context returned, see note. + * @param iv Optional initialisation vector. If the buffer pointed to is NULL, + * an IV will be created at random, in space allocated from the pool. + * If the buffer pointed to is not NULL, the IV in the buffer will be + * used. + * @param key The key structure to use. + * @param blockSize The block size of the cipher. + * @param p The pool to use. + * @return Returns APR_ENOIV if an initialisation vector is required but not specified. + * Returns APR_EINIT if the backend failed to initialise the context. Returns + * APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_encrypt_init( + apr_crypto_block_t **ctx, const unsigned char **iv, + const apr_crypto_key_t *key, apr_size_t *blockSize, apr_pool_t *p); + +/** + * @brief Encrypt data provided by in, write it to out. + * @note The number of bytes written will be written to outlen. If + * out is NULL, outlen will contain the maximum size of the + * buffer needed to hold the data, including any data + * generated by apr_crypto_block_encrypt_finish below. If *out points + * to NULL, a buffer sufficiently large will be created from + * the pool provided. If *out points to a not-NULL value, this + * value will be used as a buffer instead. + * @param out Address of a buffer to which data will be written, + * see note. + * @param outlen Length of the output will be written here. + * @param in Address of the buffer to read. + * @param inlen Length of the buffer to read. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if + * not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_encrypt(unsigned char **out, + apr_size_t *outlen, const unsigned char *in, apr_size_t inlen, + apr_crypto_block_t *ctx); + +/** + * @brief Encrypt final data block, write it to out. + * @note If necessary the final block will be written out after being + * padded. Typically the final block will be written to the + * same buffer used by apr_crypto_block_encrypt, offset by the + * number of bytes returned as actually written by the + * apr_crypto_block_encrypt() call. After this call, the context + * is cleaned and can be reused by apr_crypto_block_encrypt_init(). + * @param out Address of a buffer to which data will be written. This + * buffer must already exist, and is usually the same + * buffer used by apr_evp_crypt(). See note. + * @param outlen Length of the output will be written here. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. + * @return APR_EPADDING if padding was enabled and the block was incorrectly + * formatted. + * @return APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_encrypt_finish(unsigned char *out, + apr_size_t *outlen, apr_crypto_block_t *ctx); + +/** + * @brief Initialise a context for decrypting arbitrary data using the given key. + * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If + * *ctx is not NULL, *ctx must point at a previously created structure. + * @param ctx The block context returned, see note. + * @param blockSize The block size of the cipher. + * @param iv Optional initialisation vector. + * @param key The key structure to use. + * @param p The pool to use. + * @return Returns APR_ENOIV if an initialisation vector is required but not specified. + * Returns APR_EINIT if the backend failed to initialise the context. Returns + * APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_decrypt_init( + apr_crypto_block_t **ctx, apr_size_t *blockSize, + const unsigned char *iv, const apr_crypto_key_t *key, apr_pool_t *p); + +/** + * @brief Decrypt data provided by in, write it to out. + * @note The number of bytes written will be written to outlen. If + * out is NULL, outlen will contain the maximum size of the + * buffer needed to hold the data, including any data + * generated by apr_crypto_block_decrypt_finish below. If *out points + * to NULL, a buffer sufficiently large will be created from + * the pool provided. If *out points to a not-NULL value, this + * value will be used as a buffer instead. + * @param out Address of a buffer to which data will be written, + * see note. + * @param outlen Length of the output will be written here. + * @param in Address of the buffer to read. + * @param inlen Length of the buffer to read. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if + * not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_decrypt(unsigned char **out, + apr_size_t *outlen, const unsigned char *in, apr_size_t inlen, + apr_crypto_block_t *ctx); + +/** + * @brief Decrypt final data block, write it to out. + * @note If necessary the final block will be written out after being + * padded. Typically the final block will be written to the + * same buffer used by apr_crypto_block_decrypt, offset by the + * number of bytes returned as actually written by the + * apr_crypto_block_decrypt() call. After this call, the context + * is cleaned and can be reused by apr_crypto_block_decrypt_init(). + * @param out Address of a buffer to which data will be written. This + * buffer must already exist, and is usually the same + * buffer used by apr_evp_crypt(). See note. + * @param outlen Length of the output will be written here. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. + * @return APR_EPADDING if padding was enabled and the block was incorrectly + * formatted. + * @return APR_ENOTIMPL if not implemented. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_decrypt_finish(unsigned char *out, + apr_size_t *outlen, apr_crypto_block_t *ctx); + +/** + * @brief Clean encryption / decryption context. + * @note After cleanup, a context is free to be reused if necessary. + * @param ctx The block context to use. + * @return Returns APR_ENOTIMPL if not supported. + */ +APU_DECLARE(apr_status_t) apr_crypto_block_cleanup(apr_crypto_block_t *ctx); + +/** + * @brief Clean encryption / decryption context. + * @note After cleanup, a context is free to be reused if necessary. + * @param f The context to use. + * @return Returns APR_ENOTIMPL if not supported. + */ +APU_DECLARE(apr_status_t) apr_crypto_cleanup(apr_crypto_t *f); + +/** + * @brief Shutdown the crypto library. + * @note After shutdown, it is expected that the init function can be called again. + * @param driver - driver to use + * @return Returns APR_ENOTIMPL if not supported. + */ +APU_DECLARE(apr_status_t) apr_crypto_shutdown( + const apr_crypto_driver_t *driver); + +#endif /* APU_HAVE_CRYPTO */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_cstr.h b/c/dependencies/windows/apr/x86_debug/include/apr_cstr.h new file mode 100644 index 00000000..3f1b1a09 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_cstr.h @@ -0,0 +1,292 @@ +/* ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * ==================================================================== + */ + +/** + * @file apr_cstr.h + * @brief C string goodies. + */ + +#ifndef APR_CSTR_H +#define APR_CSTR_H + +#include /* for apr_size_t */ +#include /* for apr_pool_t */ +#include /* for apr_array_header_t */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_cstr C (POSIX) locale string functions + * @ingroup apr_strings + * + * The apr_cstr_* functions provide traditional C char * string text handling, + * and notabilty they treat all text in the C (a.k.a. POSIX) locale using the + * minimal POSIX character set, represented in either ASCII or a corresponding + * EBCDIC subset. + * + * Character values outside of that set are treated as opaque bytes, and all + * multi-byte character sequences are handled as individual distinct octets. + * + * Multi-byte characters sequences whose octets fall in the ASCII range cause + * unexpected results, such as in the ISO-2022-JP code page where ASCII octets + * occur within both shift-state and multibyte sequences. + * + * In the case of the UTF-8 encoding, all multibyte characters all fall outside + * of the C/POSIX range of characters, so these functions are generally safe + * to use on UTF-8 strings. The programmer must be aware that each octet may + * not represent a distinct printable character in such encodings. + * + * The standard C99/POSIX string functions, rather than apr_cstr, should be + * used in all cases where the current locale and encoding of the text is + * significant. + * @{ + */ + + +/** Divide @a input into substrings, interpreting any char from @a sep + * as a token separator. + * + * Return an array of copies of those substrings (plain const char*), + * allocating both the array and the copies in @a pool. + * + * None of the elements added to the array contain any of the + * characters in @a sep_chars, and none of the new elements are empty + * (thus, it is possible that the returned array will have length + * zero). + * + * If @a chop_whitespace is TRUE, then remove leading and trailing + * whitespace from the returned strings. + * + * @since New in 1.6 + */ +APR_DECLARE(apr_array_header_t *) apr_cstr_split(const char *input, + const char *sep_chars, + int chop_whitespace, + apr_pool_t *pool); + +/** Like apr_cstr_split(), but append to existing @a array instead of + * creating a new one. Allocate the copied substrings in @a pool + * (i.e., caller decides whether or not to pass @a array->pool as @a pool). + * + * @since New in 1.6 + */ +APR_DECLARE(void) apr_cstr_split_append(apr_array_header_t *array, + const char *input, + const char *sep_chars, + int chop_whitespace, + apr_pool_t *pool); + + +/** Return @c TRUE iff @a str matches any of the elements of @a list, a list + * of zero or more glob patterns. + * + * @since New in 1.6 + */ +APR_DECLARE(int) apr_cstr_match_glob_list(const char *str, + const apr_array_header_t *list); + +/** Return @c TRUE iff @a str exactly matches any of the elements of @a list. + * + * @since New in 1.6 + */ +APR_DECLARE(int) apr_cstr_match_list(const char *str, + const apr_array_header_t *list); + +/** + * Get the next token from @a *str interpreting any char from @a sep as a + * token separator. Separators at the beginning of @a str will be skipped. + * Returns a pointer to the beginning of the first token in @a *str or NULL + * if no token is left. Modifies @a str such that the next call will return + * the next token. + * + * @note The content of @a *str may be modified by this function. + * + * @since New in 1.6. + */ +APR_DECLARE(char *) apr_cstr_tokenize(const char *sep, char **str); + +/** + * Return the number of line breaks in @a msg, allowing any kind of newline + * termination (CR, LF, CRLF, or LFCR), even inconsistent. + * + * @since New in 1.6. + */ +APR_DECLARE(int) apr_cstr_count_newlines(const char *msg); + +#if 0 /* XXX: stringbuf logic is not present in APR */ +/** + * Return a cstring which is the concatenation of @a strings (an array + * of char *) each followed by @a separator (that is, @a separator + * will also end the resulting string). Allocate the result in @a pool. + * If @a strings is empty, then return the empty string. + * + * @since New in 1.6. + */ +APR_DECLARE(char *) apr_cstr_join(const apr_array_header_t *strings, + const char *separator, + apr_pool_t *pool); +#endif + +/** + * Perform a case-insensitive comparison of two strings @a atr1 and @a atr2, + * treating upper and lower case values of the 26 standard C/POSIX alphabetic + * characters as equivalent. Extended latin characters outside of this set + * are treated as unique octets, irrespective of the current locale. + * + * Returns in integer greater than, equal to, or less than 0, + * according to whether @a str1 is considered greater than, equal to, + * or less than @a str2. + * + * @since New in 1.6. + */ +APR_DECLARE(int) apr_cstr_casecmp(const char *str1, const char *str2); + +/** + * Perform a case-insensitive comparison of two strings @a atr1 and @a atr2, + * treating upper and lower case values of the 26 standard C/POSIX alphabetic + * characters as equivalent. Extended latin characters outside of this set + * are treated as unique octets, irrespective of the current locale. + * + * Returns in integer greater than, equal to, or less than 0, + * according to whether @a str1 is considered greater than, equal to, + * or less than @a str2. + * + * @since New in 1.6. + */ +APR_DECLARE(int) apr_cstr_casecmpn(const char *str1, + const char *str2, + apr_size_t n); + +/** + * Parse the C string @a str into a 64 bit number, and return it in @a *n. + * Assume that the number is represented in base @a base. + * Raise an error if conversion fails (e.g. due to overflow), or if the + * converted number is smaller than @a minval or larger than @a maxval. + * + * Leading whitespace in @a str is skipped in a locale-dependent way. + * After that, the string may contain an optional '+' (positive, default) + * or '-' (negative) character, followed by an optional '0x' prefix if + * @a base is 0 or 16, followed by numeric digits appropriate for the base. + * If there are any more characters after the numeric digits, an error is + * returned. + * + * If @a base is zero, then a leading '0x' or '0X' prefix means hexadecimal, + * else a leading '0' means octal (implemented, though not documented, in + * apr_strtoi64() in APR 0.9.0 through 1.5.0), else use base ten. + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_strtoi64(apr_int64_t *n, const char *str, + apr_int64_t minval, + apr_int64_t maxval, + int base); + +/** + * Parse the C string @a str into a 64 bit number, and return it in @a *n. + * Assume that the number is represented in base 10. + * Raise an error if conversion fails (e.g. due to overflow). + * + * The behaviour otherwise is as described for apr_cstr_strtoi64(). + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_atoi64(apr_int64_t *n, const char *str); + +/** + * Parse the C string @a str into a 32 bit number, and return it in @a *n. + * Assume that the number is represented in base 10. + * Raise an error if conversion fails (e.g. due to overflow). + * + * The behaviour otherwise is as described for apr_cstr_strtoi64(). + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_atoi(int *n, const char *str); + +/** + * Parse the C string @a str into an unsigned 64 bit number, and return + * it in @a *n. Assume that the number is represented in base @a base. + * Raise an error if conversion fails (e.g. due to overflow), or if the + * converted number is smaller than @a minval or larger than @a maxval. + * + * Leading whitespace in @a str is skipped in a locale-dependent way. + * After that, the string may contain an optional '+' (positive, default) + * or '-' (negative) character, followed by an optional '0x' prefix if + * @a base is 0 or 16, followed by numeric digits appropriate for the base. + * If there are any more characters after the numeric digits, an error is + * returned. + * + * If @a base is zero, then a leading '0x' or '0X' prefix means hexadecimal, + * else a leading '0' means octal (as implemented, though not documented, in + * apr_strtoi64(), else use base ten. + * + * @warning The implementation returns APR_ERANGE if the parsed number + * is greater than APR_INT64_MAX, even if it is not greater than @a maxval. + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_strtoui64(apr_uint64_t *n, const char *str, + apr_uint64_t minval, + apr_uint64_t maxval, + int base); + +/** + * Parse the C string @a str into an unsigned 64 bit number, and return + * it in @a *n. Assume that the number is represented in base 10. + * Raise an error if conversion fails (e.g. due to overflow). + * + * The behaviour otherwise is as described for apr_cstr_strtoui64(), + * including the upper limit of APR_INT64_MAX. + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_atoui64(apr_uint64_t *n, const char *str); + +/** + * Parse the C string @a str into an unsigned 32 bit number, and return + * it in @a *n. Assume that the number is represented in base 10. + * Raise an error if conversion fails (e.g. due to overflow). + * + * The behaviour otherwise is as described for apr_cstr_strtoui64(), + * including the upper limit of APR_INT64_MAX. + * + * @since New in 1.6. + */ +APR_DECLARE(apr_status_t) apr_cstr_atoui(unsigned int *n, const char *str); + +/** + * Skip the common prefix @a prefix from the C string @a str, and return + * a pointer to the next character after the prefix. + * Return @c NULL if @a str does not start with @a prefix. + * + * @since New in 1.6. + */ +APR_DECLARE(const char *) apr_cstr_skip_prefix(const char *str, + const char *prefix); + +/** @} */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* SVN_STRING_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_date.h b/c/dependencies/windows/apr/x86_debug/include/apr_date.h new file mode 100644 index 00000000..b098b542 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_date.h @@ -0,0 +1,106 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_DATE_H +#define APR_DATE_H + +/** + * @file apr_date.h + * @brief APR-UTIL date routines + */ + +/** + * @defgroup APR_Util_Date Date routines + * @ingroup APR_Util + * @{ + */ + +/* + * apr_date.h: prototypes for date parsing utility routines + */ + +#include "apu.h" +#include "apr_time.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** A bad date. */ +#define APR_DATE_BAD ((apr_time_t)0) + +/** + * Compare a string to a mask + * @param data The string to compare + * @param mask Mask characters (arbitrary maximum is 256 characters): + *
+ *   '\@' - uppercase letter
+ *   '\$' - lowercase letter
+ *   '\&' - hex digit
+ *   '#' - digit
+ *   '~' - digit or space
+ *   '*' - swallow remaining characters
+ * 
+ * @remark The mask tests for an exact match for any other character + * @return 1 if the string matches, 0 otherwise + */ +APU_DECLARE(int) apr_date_checkmask(const char *data, const char *mask); + +/** + * Parses an HTTP date in one of three standard forms: + *
+ *     Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
+ *     Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
+ *     Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format
+ * 
+ * @param date The date in one of the three formats above + * @return the apr_time_t number of microseconds since 1 Jan 1970 GMT, or + * 0 if this would be out of range or if the date is invalid. + */ +APU_DECLARE(apr_time_t) apr_date_parse_http(const char *date); + +/** + * Parses a string resembling an RFC 822 date. This is meant to be + * leinent in its parsing of dates. Hence, this will parse a wider + * range of dates than apr_date_parse_http. + * + * The prominent mailer (or poster, if mailer is unknown) that has + * been seen in the wild is included for the unknown formats. + *
+ *     Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
+ *     Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
+ *     Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format
+ *     Sun, 6 Nov 1994 08:49:37 GMT   ; RFC 822, updated by RFC 1123
+ *     Sun, 06 Nov 94 08:49:37 GMT    ; RFC 822
+ *     Sun, 6 Nov 94 08:49:37 GMT     ; RFC 822
+ *     Sun, 06 Nov 94 08:49 GMT       ; Unknown [drtr\@ast.cam.ac.uk] 
+ *     Sun, 6 Nov 94 08:49 GMT        ; Unknown [drtr\@ast.cam.ac.uk]
+ *     Sun, 06 Nov 94 8:49:37 GMT     ; Unknown [Elm 70.85]
+ *     Sun, 6 Nov 94 8:49:37 GMT      ; Unknown [Elm 70.85] 
+ * 
+ * + * @param date The date in one of the formats above + * @return the apr_time_t number of microseconds since 1 Jan 1970 GMT, or + * 0 if this would be out of range or if the date is invalid. + */ +APU_DECLARE(apr_time_t) apr_date_parse_rfc(const char *date); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_DATE_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_dbd.h b/c/dependencies/windows/apr/x86_debug/include/apr_dbd.h new file mode 100644 index 00000000..9912612b --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_dbd.h @@ -0,0 +1,549 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* Overview of what this is and does: + * http://www.apache.org/~niq/dbd.html + */ + +#ifndef APR_DBD_H +#define APR_DBD_H + +#include "apu.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_dbd.h + * @brief APR-UTIL DBD library + */ +/** + * @defgroup APR_Util_DBD DBD routines + * @ingroup APR_Util + * @{ + */ + +/** + * Mapping of C to SQL types, used for prepared statements. + * @remarks + * For apr_dbd_p[v]query/select functions, in and out parameters are always + * const char * (i.e. regular nul terminated strings). LOB types are passed + * with four (4) arguments: payload, length, table and column, all as const + * char *, where table and column are reserved for future use by Oracle. + * @remarks + * For apr_dbd_p[v]bquery/select functions, in and out parameters are + * described next to each enumeration constant and are generally native binary + * types or some APR data type. LOB types are passed with four (4) arguments: + * payload (char*), length (apr_size_t*), table (char*) and column (char*). + * Table and column are reserved for future use by Oracle. + */ +typedef enum { + APR_DBD_TYPE_NONE, + APR_DBD_TYPE_TINY, /**< \%hhd : in, out: char* */ + APR_DBD_TYPE_UTINY, /**< \%hhu : in, out: unsigned char* */ + APR_DBD_TYPE_SHORT, /**< \%hd : in, out: short* */ + APR_DBD_TYPE_USHORT, /**< \%hu : in, out: unsigned short* */ + APR_DBD_TYPE_INT, /**< \%d : in, out: int* */ + APR_DBD_TYPE_UINT, /**< \%u : in, out: unsigned int* */ + APR_DBD_TYPE_LONG, /**< \%ld : in, out: long* */ + APR_DBD_TYPE_ULONG, /**< \%lu : in, out: unsigned long* */ + APR_DBD_TYPE_LONGLONG, /**< \%lld : in, out: apr_int64_t* */ + APR_DBD_TYPE_ULONGLONG, /**< \%llu : in, out: apr_uint64_t* */ + APR_DBD_TYPE_FLOAT, /**< \%f : in, out: float* */ + APR_DBD_TYPE_DOUBLE, /**< \%lf : in, out: double* */ + APR_DBD_TYPE_STRING, /**< \%s : in: char*, out: char** */ + APR_DBD_TYPE_TEXT, /**< \%pDt : in: char*, out: char** */ + APR_DBD_TYPE_TIME, /**< \%pDi : in: char*, out: char** */ + APR_DBD_TYPE_DATE, /**< \%pDd : in: char*, out: char** */ + APR_DBD_TYPE_DATETIME, /**< \%pDa : in: char*, out: char** */ + APR_DBD_TYPE_TIMESTAMP, /**< \%pDs : in: char*, out: char** */ + APR_DBD_TYPE_ZTIMESTAMP, /**< \%pDz : in: char*, out: char** */ + APR_DBD_TYPE_BLOB, /**< \%pDb : in: char* apr_size_t* char* char*, out: apr_bucket_brigade* */ + APR_DBD_TYPE_CLOB, /**< \%pDc : in: char* apr_size_t* char* char*, out: apr_bucket_brigade* */ + APR_DBD_TYPE_NULL /**< \%pDn : in: void*, out: void** */ +} apr_dbd_type_e; + +/* These are opaque structs. Instantiation is up to each backend */ +typedef struct apr_dbd_driver_t apr_dbd_driver_t; +typedef struct apr_dbd_t apr_dbd_t; +typedef struct apr_dbd_transaction_t apr_dbd_transaction_t; +typedef struct apr_dbd_results_t apr_dbd_results_t; +typedef struct apr_dbd_row_t apr_dbd_row_t; +typedef struct apr_dbd_prepared_t apr_dbd_prepared_t; + +/** apr_dbd_init: perform once-only initialisation. Call once only. + * + * @param pool - pool to register any shutdown cleanups, etc + */ +APU_DECLARE(apr_status_t) apr_dbd_init(apr_pool_t *pool); + +/** apr_dbd_get_driver: get the driver struct for a name + * + * @param pool - (process) pool to register cleanup + * @param name - driver name + * @param driver - pointer to driver struct. + * @return APR_SUCCESS for success + * @return APR_ENOTIMPL for no driver (when DSO not enabled) + * @return APR_EDSOOPEN if DSO driver file can't be opened + * @return APR_ESYMNOTFOUND if the driver file doesn't contain a driver + */ +APU_DECLARE(apr_status_t) apr_dbd_get_driver(apr_pool_t *pool, const char *name, + const apr_dbd_driver_t **driver); + +/** apr_dbd_open_ex: open a connection to a backend + * + * @param driver - driver struct. + * @param pool - working pool + * @param params - arguments to driver (implementation-dependent) + * @param handle - pointer to handle to return + * @param error - descriptive error. + * @return APR_SUCCESS for success + * @return APR_EGENERAL if driver exists but connection failed + * @remarks PostgreSQL: the params is passed directly to the PQconnectdb() + * function (check PostgreSQL documentation for more details on the syntax). + * @remarks SQLite2: the params is split on a colon, with the first part used + * as the filename and second part converted to an integer and used as file + * mode. + * @remarks SQLite3: the params is passed directly to the sqlite3_open() + * function as a filename to be opened (check SQLite3 documentation for more + * details). + * @remarks Oracle: the params can have "user", "pass", "dbname" and "server" + * keys, each followed by an equal sign and a value. Such key/value pairs can + * be delimited by space, CR, LF, tab, semicolon, vertical bar or comma. + * @remarks MySQL: the params can have "host", "port", "user", "pass", + * "dbname", "sock", "flags" "fldsz", "group" and "reconnect" keys, each + * followed by an equal sign and a value. Such key/value pairs can be + * delimited by space, CR, LF, tab, semicolon, vertical bar or comma. For + * now, "flags" can only recognise CLIENT_FOUND_ROWS (check MySQL manual for + * details). The value associated with "fldsz" determines maximum amount of + * memory (in bytes) for each of the fields in the result set of prepared + * statements. By default, this value is 1 MB. The value associated with + * "group" determines which group from configuration file to use (see + * MYSQL_READ_DEFAULT_GROUP option of mysql_options() in MySQL manual). + * Reconnect is set to 1 by default (i.e. true). + */ +APU_DECLARE(apr_status_t) apr_dbd_open_ex(const apr_dbd_driver_t *driver, + apr_pool_t *pool, const char *params, + apr_dbd_t **handle, + const char **error); + +/** apr_dbd_open: open a connection to a backend + * + * @param driver - driver struct. + * @param pool - working pool + * @param params - arguments to driver (implementation-dependent) + * @param handle - pointer to handle to return + * @return APR_SUCCESS for success + * @return APR_EGENERAL if driver exists but connection failed + * @see apr_dbd_open_ex + */ +APU_DECLARE(apr_status_t) apr_dbd_open(const apr_dbd_driver_t *driver, + apr_pool_t *pool, const char *params, + apr_dbd_t **handle); + +/** apr_dbd_close: close a connection to a backend + * + * @param driver - driver struct. + * @param handle - handle to close + * @return APR_SUCCESS for success or error status + */ +APU_DECLARE(apr_status_t) apr_dbd_close(const apr_dbd_driver_t *driver, + apr_dbd_t *handle); + +/* apr-function-shaped versions of things */ + +/** apr_dbd_name: get the name of the driver + * + * @param driver - the driver + * @return - name + */ +APU_DECLARE(const char*) apr_dbd_name(const apr_dbd_driver_t *driver); + +/** apr_dbd_native_handle: get native database handle of the underlying db + * + * @param driver - the driver + * @param handle - apr_dbd handle + * @return - native handle + */ +APU_DECLARE(void*) apr_dbd_native_handle(const apr_dbd_driver_t *driver, + apr_dbd_t *handle); + +/** check_conn: check status of a database connection + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection to check + * @return APR_SUCCESS or error + */ +APU_DECLARE(int) apr_dbd_check_conn(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle); + +/** apr_dbd_set_dbname: select database name. May be a no-op if not supported. + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param name - the database to select + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_set_dbname(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, const char *name); + +/** apr_dbd_transaction_start: start a transaction. May be a no-op. + * + * @param driver - the driver + * @param pool - a pool to use for error messages (if any). + * @param handle - the db connection + * @param trans - ptr to a transaction. May be null on entry + * @return 0 for success or error code + * @remarks Note that transaction modes, set by calling + * apr_dbd_transaction_mode_set(), will affect all query/select calls within + * a transaction. By default, any error in query/select during a transaction + * will cause the transaction to inherit the error code and any further + * query/select calls will fail immediately. Put transaction in "ignore + * errors" mode to avoid that. Use "rollback" mode to do explicit rollback. + */ +APU_DECLARE(int) apr_dbd_transaction_start(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_t *handle, + apr_dbd_transaction_t **trans); + +/** apr_dbd_transaction_end: end a transaction + * (commit on success, rollback on error). + * May be a no-op. + * + * @param driver - the driver + * @param handle - the db connection + * @param trans - the transaction. + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_transaction_end(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_transaction_t *trans); + +#define APR_DBD_TRANSACTION_COMMIT 0x00 /**< commit the transaction */ +#define APR_DBD_TRANSACTION_ROLLBACK 0x01 /**< rollback the transaction */ +#define APR_DBD_TRANSACTION_IGNORE_ERRORS 0x02 /**< ignore transaction errors */ + +/** apr_dbd_transaction_mode_get: get the mode of transaction + * + * @param driver - the driver + * @param trans - the transaction + * @return mode of transaction + */ +APU_DECLARE(int) apr_dbd_transaction_mode_get(const apr_dbd_driver_t *driver, + apr_dbd_transaction_t *trans); + +/** apr_dbd_transaction_mode_set: set the mode of transaction + * + * @param driver - the driver + * @param trans - the transaction + * @param mode - new mode of the transaction + * @return the mode of transaction in force after the call + */ +APU_DECLARE(int) apr_dbd_transaction_mode_set(const apr_dbd_driver_t *driver, + apr_dbd_transaction_t *trans, + int mode); + +/** apr_dbd_query: execute an SQL query that doesn't return a result set + * + * @param driver - the driver + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the SQL statement to execute + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_query(const apr_dbd_driver_t *driver, apr_dbd_t *handle, + int *nrows, const char *statement); + +/** apr_dbd_select: execute an SQL query that returns a result set + * + * @param driver - the driver + * @param pool - pool to allocate the result set + * @param handle - the connection + * @param res - pointer to result set pointer. May point to NULL on entry + * @param statement - the SQL statement to execute + * @param random - 1 to support random access to results (seek any row); + * 0 to support only looping through results in order + * (async access - faster) + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_select(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, apr_dbd_results_t **res, + const char *statement, int random); + +/** apr_dbd_num_cols: get the number of columns in a results set + * + * @param driver - the driver + * @param res - result set. + * @return number of columns + */ +APU_DECLARE(int) apr_dbd_num_cols(const apr_dbd_driver_t *driver, + apr_dbd_results_t *res); + +/** apr_dbd_num_tuples: get the number of rows in a results set + * of a synchronous select + * + * @param driver - the driver + * @param res - result set. + * @return number of rows, or -1 if the results are asynchronous + */ +APU_DECLARE(int) apr_dbd_num_tuples(const apr_dbd_driver_t *driver, + apr_dbd_results_t *res); + +/** apr_dbd_get_row: get a row from a result set + * + * @param driver - the driver + * @param pool - pool to allocate the row + * @param res - result set pointer + * @param row - pointer to row pointer. May point to NULL on entry + * @param rownum - row number (counting from 1), or -1 for "next row". + * Ignored if random access is not supported. + * @return 0 for success, -1 for rownum out of range or data finished + */ +APU_DECLARE(int) apr_dbd_get_row(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_results_t *res, apr_dbd_row_t **row, + int rownum); + +/** apr_dbd_get_entry: get an entry from a row + * + * @param driver - the driver + * @param row - row pointer + * @param col - entry number + * @return value from the row, or NULL if col is out of bounds. + */ +APU_DECLARE(const char*) apr_dbd_get_entry(const apr_dbd_driver_t *driver, + apr_dbd_row_t *row, int col); + +/** apr_dbd_get_name: get an entry name from a result set + * + * @param driver - the driver + * @param res - result set pointer + * @param col - entry number + * @return name of the entry, or NULL if col is out of bounds. + */ +APU_DECLARE(const char*) apr_dbd_get_name(const apr_dbd_driver_t *driver, + apr_dbd_results_t *res, int col); + + +/** apr_dbd_error: get current error message (if any) + * + * @param driver - the driver + * @param handle - the connection + * @param errnum - error code from operation that returned an error + * @return the database current error message, or message for errnum + * (implementation-dependent whether errnum is ignored) + */ +APU_DECLARE(const char*) apr_dbd_error(const apr_dbd_driver_t *driver, + apr_dbd_t *handle, int errnum); + +/** apr_dbd_escape: escape a string so it is safe for use in query/select + * + * @param driver - the driver + * @param pool - pool to alloc the result from + * @param string - the string to escape + * @param handle - the connection + * @return the escaped, safe string + */ +APU_DECLARE(const char*) apr_dbd_escape(const apr_dbd_driver_t *driver, + apr_pool_t *pool, const char *string, + apr_dbd_t *handle); + +/** apr_dbd_prepare: prepare a statement + * + * @param driver - the driver + * @param pool - pool to alloc the result from + * @param handle - the connection + * @param query - the SQL query + * @param label - A label for the prepared statement. + * use NULL for temporary prepared statements + * (eg within a Request in httpd) + * @param statement - statement to prepare. May point to null on entry. + * @return 0 for success or error code + * @remarks To specify parameters of the prepared query, use \%s, \%d etc. + * (see below for full list) in place of database specific parameter syntax + * (e.g. for PostgreSQL, this would be $1, $2, for SQLite3 this would be ? + * etc.). For instance: "SELECT name FROM customers WHERE name=%s" would be + * a query that this function understands. + * @remarks Here is the full list of format specifiers that this function + * understands and what they map to in SQL: \%hhd (TINY INT), \%hhu (UNSIGNED + * TINY INT), \%hd (SHORT), \%hu (UNSIGNED SHORT), \%d (INT), \%u (UNSIGNED + * INT), \%ld (LONG), \%lu (UNSIGNED LONG), \%lld (LONG LONG), \%llu + * (UNSIGNED LONG LONG), \%f (FLOAT, REAL), \%lf (DOUBLE PRECISION), \%s + * (VARCHAR), \%pDt (TEXT), \%pDi (TIME), \%pDd (DATE), \%pDa (DATETIME), + * \%pDs (TIMESTAMP), \%pDz (TIMESTAMP WITH TIME ZONE), \%pDb (BLOB), \%pDc + * (CLOB) and \%pDn (NULL). Not all databases have support for all these + * types, so the underlying driver will attempt the "best match" where + * possible. A \% followed by any letter not in the above list will be + * interpreted as VARCHAR (i.e. \%s). + */ +APU_DECLARE(int) apr_dbd_prepare(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, const char *query, + const char *label, + apr_dbd_prepared_t **statement); + + +/** apr_dbd_pquery: query using a prepared statement + args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param nargs - ignored (for backward compatibility only) + * @param args - args to prepared statement + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_pquery(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, int nargs, + const char **args); + +/** apr_dbd_pselect: select using a prepared statement + args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param nargs - ignored (for backward compatibility only) + * @param args - args to prepared statement + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_pselect(const apr_dbd_driver_t *driver, apr_pool_t *pool, + apr_dbd_t *handle, apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, int random, + int nargs, const char **args); + +/** apr_dbd_pvquery: query using a prepared statement + args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param ... - varargs list + * @return 0 for success or error code + */ +APU_DECLARE_NONSTD(int) apr_dbd_pvquery(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, ...); + +/** apr_dbd_pvselect: select using a prepared statement + args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param ... - varargs list + * @return 0 for success or error code + */ +APU_DECLARE_NONSTD(int) apr_dbd_pvselect(const apr_dbd_driver_t *driver, + apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, + int random, ...); + +/** apr_dbd_pbquery: query using a prepared statement + binary args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_pbquery(const apr_dbd_driver_t *driver, + apr_pool_t *pool, apr_dbd_t *handle, + int *nrows, apr_dbd_prepared_t *statement, + const void **args); + +/** apr_dbd_pbselect: select using a prepared statement + binary args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ +APU_DECLARE(int) apr_dbd_pbselect(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_t *handle, apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, int random, + const void **args); + +/** apr_dbd_pvbquery: query using a prepared statement + binary args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param ... - varargs list of binary args + * @return 0 for success or error code + */ +APU_DECLARE_NONSTD(int) apr_dbd_pvbquery(const apr_dbd_driver_t *driver, + apr_pool_t *pool, + apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, ...); + +/** apr_dbd_pvbselect: select using a prepared statement + binary args + * + * @param driver - the driver + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param ... - varargs list of binary args + * @return 0 for success or error code + */ +APU_DECLARE_NONSTD(int) apr_dbd_pvbselect(const apr_dbd_driver_t *driver, + apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, + int random, ...); + +/** apr_dbd_datum_get: get a binary entry from a row + * + * @param driver - the driver + * @param row - row pointer + * @param col - entry number + * @param type - type of data to get + * @param data - pointer to data, allocated by the caller + * @return APR_SUCCESS on success, APR_ENOENT if data is NULL or APR_EGENERAL + */ +APU_DECLARE(apr_status_t) apr_dbd_datum_get(const apr_dbd_driver_t *driver, + apr_dbd_row_t *row, int col, + apr_dbd_type_e type, void *data); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_dbm.h b/c/dependencies/windows/apr/x86_debug/include/apr_dbm.h new file mode 100644 index 00000000..ad1b4f39 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_dbm.h @@ -0,0 +1,227 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_DBM_H +#define APR_DBM_H + +#include "apu.h" +#include "apr.h" +#include "apr_errno.h" +#include "apr_pools.h" +#include "apr_file_info.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_dbm.h + * @brief APR-UTIL DBM library + */ +/** + * @defgroup APR_Util_DBM DBM routines + * @ingroup APR_Util + * @{ + */ +/** + * Structure for referencing a dbm + */ +typedef struct apr_dbm_t apr_dbm_t; + +/** + * Structure for referencing the datum record within a dbm + */ +typedef struct +{ + /** pointer to the 'data' to retrieve/store in the DBM */ + char *dptr; + /** size of the 'data' to retrieve/store in the DBM */ + apr_size_t dsize; +} apr_datum_t; + +/* modes to open the DB */ +#define APR_DBM_READONLY 1 /**< open for read-only access */ +#define APR_DBM_READWRITE 2 /**< open for read-write access */ +#define APR_DBM_RWCREATE 3 /**< open for r/w, create if needed */ +#define APR_DBM_RWTRUNC 4 /**< open for r/w, truncating an existing + DB if present */ +/** + * Open a dbm file by file name and type of DBM + * @param dbm The newly opened database + * @param type The type of the DBM (not all may be available at run time) + *
+ *  db   for Berkeley DB files
+ *  gdbm for GDBM files
+ *  ndbm for NDBM files
+ *  sdbm for SDBM files (always available)
+ *  default for the default DBM type
+ *  
+ * @param name The dbm file name to open + * @param mode The flag value + *
+ *           APR_DBM_READONLY   open for read-only access
+ *           APR_DBM_READWRITE  open for read-write access
+ *           APR_DBM_RWCREATE   open for r/w, create if needed
+ *           APR_DBM_RWTRUNC    open for r/w, truncate if already there
+ * 
+ * @param perm Permissions to apply to if created + * @param cntxt The pool to use when creating the dbm + * @remark The dbm name may not be a true file name, as many dbm packages + * append suffixes for seperate data and index files. + * @bug In apr-util 0.9 and 1.x, the type arg was case insensitive. This + * was highly inefficient, and as of 2.x the dbm name must be provided in + * the correct case (lower case for all bundled providers) + */ + +APU_DECLARE(apr_status_t) apr_dbm_open_ex(apr_dbm_t **dbm, const char* type, + const char *name, + apr_int32_t mode, apr_fileperms_t perm, + apr_pool_t *cntxt); + + +/** + * Open a dbm file by file name + * @param dbm The newly opened database + * @param name The dbm file name to open + * @param mode The flag value + *
+ *           APR_DBM_READONLY   open for read-only access
+ *           APR_DBM_READWRITE  open for read-write access
+ *           APR_DBM_RWCREATE   open for r/w, create if needed
+ *           APR_DBM_RWTRUNC    open for r/w, truncate if already there
+ * 
+ * @param perm Permissions to apply to if created + * @param cntxt The pool to use when creating the dbm + * @remark The dbm name may not be a true file name, as many dbm packages + * append suffixes for seperate data and index files. + */ +APU_DECLARE(apr_status_t) apr_dbm_open(apr_dbm_t **dbm, const char *name, + apr_int32_t mode, apr_fileperms_t perm, + apr_pool_t *cntxt); + +/** + * Close a dbm file previously opened by apr_dbm_open + * @param dbm The database to close + */ +APU_DECLARE(void) apr_dbm_close(apr_dbm_t *dbm); + +/** + * Fetch a dbm record value by key + * @param dbm The database + * @param key The key datum to find this record + * @param pvalue The value datum retrieved for this record + */ +APU_DECLARE(apr_status_t) apr_dbm_fetch(apr_dbm_t *dbm, apr_datum_t key, + apr_datum_t *pvalue); +/** + * Store a dbm record value by key + * @param dbm The database + * @param key The key datum to store this record by + * @param value The value datum to store in this record + */ +APU_DECLARE(apr_status_t) apr_dbm_store(apr_dbm_t *dbm, apr_datum_t key, + apr_datum_t value); + +/** + * Delete a dbm record value by key + * @param dbm The database + * @param key The key datum of the record to delete + * @remark It is not an error to delete a non-existent record. + */ +APU_DECLARE(apr_status_t) apr_dbm_delete(apr_dbm_t *dbm, apr_datum_t key); + +/** + * Search for a key within the dbm + * @param dbm The database + * @param key The datum describing a key to test + */ +APU_DECLARE(int) apr_dbm_exists(apr_dbm_t *dbm, apr_datum_t key); + +/** + * Retrieve the first record key from a dbm + * @param dbm The database + * @param pkey The key datum of the first record + */ +APU_DECLARE(apr_status_t) apr_dbm_firstkey(apr_dbm_t *dbm, apr_datum_t *pkey); + +/** + * Retrieve the next record key from a dbm + * @param dbm The database + * @param pkey The key datum of the next record + */ +APU_DECLARE(apr_status_t) apr_dbm_nextkey(apr_dbm_t *dbm, apr_datum_t *pkey); + +/** + * Proactively toss any memory associated with the apr_datum_t. + * @param dbm The database + * @param data The datum to free. + */ +APU_DECLARE(void) apr_dbm_freedatum(apr_dbm_t *dbm, apr_datum_t data); + +/** + * Report more information when an apr_dbm function fails. + * @param dbm The database + * @param errcode A DBM-specific value for the error (for logging). If this + * isn't needed, it may be NULL. + * @param errbuf Location to store the error text + * @param errbufsize The size of the provided buffer + * @return The errbuf parameter, for convenience. + */ +APU_DECLARE(char *) apr_dbm_geterror(apr_dbm_t *dbm, int *errcode, + char *errbuf, apr_size_t errbufsize); +/** + * If the specified file/path were passed to apr_dbm_open(), return the + * actual file/path names which would be (created and) used. At most, two + * files may be used; used2 may be NULL if only one file is used. + * @param pool The pool for allocating used1 and used2. + * @param type The type of DBM you require info on @see apr_dbm_open_ex + * @param pathname The path name to generate used-names from. + * @param used1 The first pathname used by the apr_dbm implementation. + * @param used2 The second pathname used by apr_dbm. If only one file is + * used by the specific implementation, this will be set to NULL. + * @return An error if the specified type is invalid. + * @remark The dbm file(s) don't need to exist. This function only manipulates + * the pathnames. + */ +APU_DECLARE(apr_status_t) apr_dbm_get_usednames_ex(apr_pool_t *pool, + const char *type, + const char *pathname, + const char **used1, + const char **used2); + +/** + * If the specified file/path were passed to apr_dbm_open(), return the + * actual file/path names which would be (created and) used. At most, two + * files may be used; used2 may be NULL if only one file is used. + * @param pool The pool for allocating used1 and used2. + * @param pathname The path name to generate used-names from. + * @param used1 The first pathname used by the apr_dbm implementation. + * @param used2 The second pathname used by apr_dbm. If only one file is + * used by the specific implementation, this will be set to NULL. + * @remark The dbm file(s) don't need to exist. This function only manipulates + * the pathnames. + */ +APU_DECLARE(void) apr_dbm_get_usednames(apr_pool_t *pool, + const char *pathname, + const char **used1, + const char **used2); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_DBM_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_dso.h b/c/dependencies/windows/apr/x86_debug/include/apr_dso.h new file mode 100644 index 00000000..ac701cfd --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_dso.h @@ -0,0 +1,94 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_DSO_DOT_H +#define APR_DSO_DOT_H + +/** + * @file apr_dso.h + * @brief APR Dynamic Object Handling Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_dso Dynamic Object Handling + * @ingroup APR + * @{ + */ + +#if APR_HAS_DSO || defined(DOXYGEN) + +/** + * Structure for referencing dynamic objects + */ +typedef struct apr_dso_handle_t apr_dso_handle_t; + +/** + * Structure for referencing symbols from dynamic objects + */ +typedef void * apr_dso_handle_sym_t; + +/** + * Load a DSO library. + * @param res_handle Location to store new handle for the DSO. + * @param path Path to the DSO library + * @param ctx Pool to use. + * @bug We aught to provide an alternative to RTLD_GLOBAL, which + * is the only supported method of loading DSOs today. + */ +APR_DECLARE(apr_status_t) apr_dso_load(apr_dso_handle_t **res_handle, + const char *path, apr_pool_t *ctx); + +/** + * Close a DSO library. + * @param handle handle to close. + */ +APR_DECLARE(apr_status_t) apr_dso_unload(apr_dso_handle_t *handle); + +/** + * Load a symbol from a DSO handle. + * @param ressym Location to store the loaded symbol + * @param handle handle to load the symbol from. + * @param symname Name of the symbol to load. + */ +APR_DECLARE(apr_status_t) apr_dso_sym(apr_dso_handle_sym_t *ressym, + apr_dso_handle_t *handle, + const char *symname); + +/** + * Report more information when a DSO function fails. + * @param dso The dso handle that has been opened + * @param buf Location to store the dso error + * @param bufsize The size of the provided buffer + */ +APR_DECLARE(const char *) apr_dso_error(apr_dso_handle_t *dso, char *buf, apr_size_t bufsize); + +#endif /* APR_HAS_DSO */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_encode.h b/c/dependencies/windows/apr/x86_debug/include/apr_encode.h new file mode 100644 index 00000000..20fc932f --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_encode.h @@ -0,0 +1,569 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_encode.h + * @brief APR-UTIL Encoding + */ +#ifndef APR_ENCODE_H +#define APR_ENCODE_H + +#include "apr.h" +#include "apr_general.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Encode Base64/Base64Url/Base32/Base32Hex/Base16 Encoding + * @ingroup APR_Util + * @{ + */ + +/** + * RFC4648 and RFC7515 compliant BASE64, BASE64URL, BASE32, BASE32HEX + * and BASE16 encode/decode functions. + * + * The following encodings are supported: + * + * - Base 64 Encoding + * + * o Use flag APR_ENCODE_NONE + * o https://tools.ietf.org/html/rfc4648#section-4 + * + * - Base 64 Encoding with URL and Filename Safe Alphabet + * + * o Use flag APR_ENCODE_URL + * o https://tools.ietf.org/html/rfc4648#section-5 + * + * - Base 64 URL Encoding without Padding + * + * o Use flag APR_ENCODE_BASE64URL + * o https://tools.ietf.org/html/rfc7515#appendix-C + * + * - Base 32 Encoding + * + * o Use flag APR_ENCODE_NONE + * o https://tools.ietf.org/html/rfc4648#section-6 + * + * - Base 32 Encoding with Extended Hex Alphabet + * + * o Use flag APR_ENCODE_BASE32HEX + * o https://tools.ietf.org/html/rfc4648#section-7 + * + * - Base 16 Encoding + * + * o Use flags APR_ENCODE_NONE/APR_ENCODE_COLON + * o https://tools.ietf.org/html/rfc4648#section-8 + * + * If a non valid character of any kind including whitespace is passed to any + * of the decoder functions, APR_BADCH will be returned. In this case decoding + * will still take place, but the results can not be trusted. + * + * If APR_ENCODE_RELAXED is passed to the decoder functions, decoding will be + * attempted up until the first non valid character. If this results in an + * invalid state in the decoder, such as but not limited to an odd number of + * base16 characters, APR_BADCH will still be returned. + * + * If APR_ENCODE_RELAXED is not passed to a decoder function, the decoding will + * be done in constant time regardless of whether the result returns APR_SUCCESS + * or APR_BADCH. + * + * If the dest parameter is NULL, the maximum theoretical buffer size is + * returned in the len field, including space for a terminating zero character + * if the destination is a string. This value can be used to allocate buffers + * of a suitable safe size. + * + * If the dest parameter is provided, the encoding or decoding will take place, + * and the actual number of characters written is returned in the len field, + * ignoring any terminating zero. + * + * Plain strings are not assumed '\0' terminated unless APR_ENCODE_STRING is + * provided. + * + */ + +/** + * When passing a string to one of the encode functions, this value can be + * passed to indicate a string-valued key, and have the length computed + * automatically. + */ +#define APR_ENCODE_STRING (-1) + +/** + * Generate RFC4648 base16/base32/base64. + */ +#define APR_ENCODE_NONE 0 + +/** + * If relaxed, decode up until the first non base16/base32/base64 character. + */ +#define APR_ENCODE_RELAXED 1 + +/** + * Omit the padding character (=) while encoding. + */ +#define APR_ENCODE_NOPADDING 2 + +/** + * Generate RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet + */ +#define APR_ENCODE_URL 4 + +/** + * Generate RFC7515 BASE64URL + */ +#define APR_ENCODE_BASE64URL (APR_ENCODE_NOPADDING | APR_ENCODE_URL) + +/** + * Generate base32hex encoding instead of base32 encoding + */ +#define APR_ENCODE_BASE32HEX 8 + +/** + * Generate base16 with colons between each token. + */ +#define APR_ENCODE_COLON 16 + +/** + * Generate base16 with lower case characters. + */ +#define APR_ENCODE_LOWER 32 + +/** + * Convert text data to base64. + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 64 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_URL, + * use RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet. + * If APR_ENCODE_BASE64URL, use RFC7515 base64url Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination string, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base64(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert binary data to base64. + * @param dest The destination string, can be NULL. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 64 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_URL, + * use RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet. + * If APR_ENCODE_BASE64URL, use RFC7515 base64url Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination string, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base64_binary(char *dest, const unsigned char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert text data to base64, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 64 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_URL, + * use RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet. + * If APR_ENCODE_BASE64URL, use RFC7515 base64url Encoding. + * @param len If present, returns the number of characters written excluding + * the zero pad. + * @return A zero padded string allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *)apr_pencode_base64(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len)__attribute__((nonnull(1))); + +/** + * Convert binary data to base64, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 64 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_URL, + * use RFC4648 Base 64 Encoding with URL and Filename Safe Alphabet. + * If APR_ENCODE_BASE64URL, use RFC7515 base64url Encoding. + * @param len If present, returns the number of characters written excluding + * the zero pad. + * @return A zero padded string allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *)apr_pencode_base64_binary(apr_pool_t * p, const unsigned char *src, + apr_ssize_t slen, int flags, apr_size_t * len)__attribute__((nonnull(1))); + +/** + * Convert base64 or base64url with or without padding to text data. + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, attempt to decode the full original buffer, + * and return NULL if any bad character is detected. If APR_ENCODE_RELAXED, + * decode until the first non base64/base64url character. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination string, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL, or APR_BADCH + * if a non hex character is present. + */ +APR_DECLARE(apr_status_t) apr_decode_base64(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base64 or base64url with or without padding to binary data. + * @param dest The destination buffer, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, attempt to decode the full original buffer, + * and return NULL if any bad character is detected. If APR_ENCODE_RELAXED, + * decode until the first non base64/base64url character. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the src was NULL, or APR_BADCH + * if a non base64 character is present. + */ +APR_DECLARE(apr_status_t) apr_decode_base64_binary(unsigned char *dest, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base64 or base64url with or without padding to text data, and + * return the results from a pool. + * @param p Pool to allocate from. + * @param src The base64 string to decode. + * @param slen The length of the base64 string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, attempt to decode the full original buffer, + * and return NULL if any bad character is detected. If APR_ENCODE_RELAXED, + * decode until the first non base64/base64url character. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A string allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const char *)apr_pdecode_base64(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert base64 or base64url with or without padding to binary data, and + * return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, attempt to decode the full original buffer, + * and return NULL if any bad character is detected. If APR_ENCODE_RELAXED, + * decode until the first non base64/base64url character. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A buffer allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const unsigned char *)apr_pdecode_base64_binary(apr_pool_t * p, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert text data to base32. + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 32 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_BASE32HEX, + * use RFC4648 base32hex Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination string, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base32(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert binary data to base32. + * @param dest The destination string, can be NULL. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 32 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_BASE32HEX, + * use RFC4648 base32hex Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination string, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base32_binary(char *dest, const unsigned char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert text data to base32, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 32 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_BASE32HEX, + * use RFC4648 base32hex Encoding. + * @param len If present, returns the number of characters written excluding + * the zero pad. + * @return A zero padded string allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *)apr_pencode_base32(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert binary data to base32, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 32 Encoding. If + * APR_ENCODE_NOPADDING, omit the = padding character. If APR_ENCODE_BASE32HEX, + * use RFC7515 base32hex Encoding. + * @param len If present, returns the number of characters written excluding + * the zero pad. + * @return A zero padded string allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *)apr_pencode_base32_binary(apr_pool_t * p, const unsigned char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert base32 or base32hex with or without padding to text data. + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 32 Encoding. If + * APR_ENCODE_BASE32HEX, use RFC4648 base32hex Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL, or APR_BADCH + * if a non base32 character is present. + */ +APR_DECLARE(apr_status_t) apr_decode_base32(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base32 or base32hex with or without padding to binary data. + * @param dest The destination buffer, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 32 Encoding. If + * APR_ENCODE_BASE32HEX, use RFC4648 base32hex Encoding. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the src was NULL, or APR_BADCH + * if a non base32 character is present. + */ +APR_DECLARE(apr_status_t) apr_decode_base32_binary(unsigned char *dest, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base32 or base32hex with or without padding to text data, and + * return the results from a pool. + * @param p Pool to allocate from. + * @param src The base32 string to decode. + * @param slen The length of the base32 string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 32 Encoding. If + * APR_ENCODE_BASE32HEX, use RFC4648 base32hex Encoding. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A string allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const char *)apr_pdecode_base32(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert base32 or base32hex with or without padding to binary data, and + * return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 32 Encoding. If + * APR_ENCODE_BASE32HEX, use RFC4648 base32hex Encoding. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A buffer allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const unsigned char *)apr_pdecode_base32_binary(apr_pool_t * p, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert text data to base16 (hex). + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, separate each token with a colon. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base16(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert binary data to base16 (hex). + * @param dest The destination string, can be NULL. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, separate each token with a colon. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL. + */ +APR_DECLARE(apr_status_t) apr_encode_base16_binary(char *dest, + const unsigned char *src, apr_ssize_t slen, int flags, + apr_size_t * len); + +/** + * Convert text data to base16 (hex), and return the results from a + * pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, separate each token with a colon. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A string allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const char *)apr_pencode_base16(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert binary data to base16 (hex), and return the results from a + * pool. + * @param p Pool to allocate from. + * @param src The original buffer. + * @param slen The length of the original buffer. + * @param flags If APR_ENCODE_NONE, emit RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, separate each token with a colon. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A string allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const char *)apr_pencode_base16_binary(apr_pool_t * p, + const unsigned char *src, apr_ssize_t slen, + int flags, apr_size_t * len)__attribute__((nonnull(1))); + +/** + * Convert base16 (hex) to text data. + * @param dest The destination string, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, allow tokens to be separated with a colon. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL, or APR_BADCH + * if a non hex character is present. A zero pad is appended to the buffer. + */ +APR_DECLARE(apr_status_t) apr_decode_base16(char *dest, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base16 (hex) to binary data. + * @param dest The destination buffer, can be NULL. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, allow tokens to be separated with a colon. + * @param len If present and src is NULL, returns the maximum possible length + * of the destination buffer, including a zero pad. If present and src is + * not NULL, returns the number of characters actually written. + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL, or APR_BADCH + * if a non hex character is present. No zero pad is written to the buffer. + */ +APR_DECLARE(apr_status_t) apr_decode_base16_binary(unsigned char *dest, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len); + +/** + * Convert base16 (hex) and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, allow tokens to be separated with a colon. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A buffer allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const char *)apr_pdecode_base16(apr_pool_t * p, const char *src, + apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** + * Convert base16 (hex) to binary data, and return the results from a pool. + * @param p Pool to allocate from. + * @param src The original string. + * @param slen The length of the original string, or APR_ENCODE_STRING if + * NUL terminated. + * @param flags If APR_ENCODE_NONE, parse RFC4648 Base 16 Encoding. If + * APR_ENCODE_COLON, allow tokens to be separated with a colon. + * @param len If present, returns the number of characters written, excluding + * the zero padding. + * @return A buffer allocated from the pool containing the result with a zero + * pad. If src was NULL, or an error occurred, NULL is returned. + */ +APR_DECLARE(const unsigned char *)apr_pdecode_base16_binary(apr_pool_t * p, + const char *src, apr_ssize_t slen, int flags, apr_size_t * len) + __attribute__((nonnull(1))); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ENCODE_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_env.h b/c/dependencies/windows/apr/x86_debug/include/apr_env.h new file mode 100644 index 00000000..85ab6704 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_env.h @@ -0,0 +1,67 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ENV_H +#define APR_ENV_H +/** + * @file apr_env.h + * @brief APR Environment functions + */ +#include "apr_errno.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_env Functions for manipulating the environment + * @ingroup APR + * @{ + */ + +/** + * Get the value of an environment variable + * @param value the returned value, allocated from @a pool + * @param envvar the name of the environment variable + * @param pool where to allocate @a value and any temporary storage from + */ +APR_DECLARE(apr_status_t) apr_env_get(char **value, const char *envvar, + apr_pool_t *pool); + +/** + * Set the value of an environment variable + * @param envvar the name of the environment variable + * @param value the value to set + * @param pool where to allocate temporary storage from + */ +APR_DECLARE(apr_status_t) apr_env_set(const char *envvar, const char *value, + apr_pool_t *pool); + +/** + * Delete a variable from the environment + * @param envvar the name of the environment variable + * @param pool where to allocate temporary storage from + */ +APR_DECLARE(apr_status_t) apr_env_delete(const char *envvar, apr_pool_t *pool); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_ENV_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_errno.h b/c/dependencies/windows/apr/x86_debug/include/apr_errno.h new file mode 100644 index 00000000..8fa6628b --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_errno.h @@ -0,0 +1,1342 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ERRNO_H +#define APR_ERRNO_H + +/** + * @file apr_errno.h + * @brief APR Error Codes + */ + +#include "apr.h" + +#if APR_HAVE_ERRNO_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_errno Error Codes + * @ingroup APR + * @{ + */ + +/** + * Type for specifying an error or status code. + */ +typedef int apr_status_t; + +/** + * Return a human readable string describing the specified error. + * @param statcode The error code to get a string for. + * @param buf A buffer to hold the error string. + * @param bufsize Size of the buffer to hold the string. + */ +APR_DECLARE(char *) apr_strerror(apr_status_t statcode, char *buf, + apr_size_t bufsize); + +#if defined(DOXYGEN) +/** + * @def APR_FROM_OS_ERROR(os_err_type syserr) + * Fold a platform specific error into an apr_status_t code. + * @return apr_status_t + * @param e The platform os error code. + * @warning macro implementation; the syserr argument may be evaluated + * multiple times. + */ +#define APR_FROM_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e + APR_OS_START_SYSERR) + +/** + * @def APR_TO_OS_ERROR(apr_status_t statcode) + * @return os_err_type + * Fold an apr_status_t code back to the native platform defined error. + * @param e The apr_status_t folded platform os error code. + * @warning macro implementation; the statcode argument may be evaluated + * multiple times. If the statcode was not created by apr_get_os_error + * or APR_FROM_OS_ERROR, the results are undefined. + */ +#define APR_TO_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e - APR_OS_START_SYSERR) + +/** @def apr_get_os_error() + * @return apr_status_t the last platform error, folded into apr_status_t, on most platforms + * @remark This retrieves errno, or calls a GetLastError() style function, and + * folds it with APR_FROM_OS_ERROR. Some platforms (such as OS2) have no + * such mechanism, so this call may be unsupported. Do NOT use this + * call for socket errors from socket, send, recv etc! + */ + +/** @def apr_set_os_error(e) + * Reset the last platform error, unfolded from an apr_status_t, on some platforms + * @param e The OS error folded in a prior call to APR_FROM_OS_ERROR() + * @warning This is a macro implementation; the statcode argument may be evaluated + * multiple times. If the statcode was not created by apr_get_os_error + * or APR_FROM_OS_ERROR, the results are undefined. This macro sets + * errno, or calls a SetLastError() style function, unfolding statcode + * with APR_TO_OS_ERROR. Some platforms (such as OS2) have no such + * mechanism, so this call may be unsupported. + */ + +/** @def apr_get_netos_error() + * Return the last socket error, folded into apr_status_t, on all platforms + * @remark This retrieves errno or calls a GetLastSocketError() style function, + * and folds it with APR_FROM_OS_ERROR. + */ + +/** @def apr_set_netos_error(e) + * Reset the last socket error, unfolded from an apr_status_t + * @param e The socket error folded in a prior call to APR_FROM_OS_ERROR() + * @warning This is a macro implementation; the statcode argument may be evaluated + * multiple times. If the statcode was not created by apr_get_os_error + * or APR_FROM_OS_ERROR, the results are undefined. This macro sets + * errno, or calls a WSASetLastError() style function, unfolding + * socketcode with APR_TO_OS_ERROR. + */ + +#endif /* defined(DOXYGEN) */ + +/** + * APR_OS_START_ERROR is where the APR specific error values start. + */ +#define APR_OS_START_ERROR 20000 +/** + * APR_OS_ERRSPACE_SIZE is the maximum number of errors you can fit + * into one of the error/status ranges below -- except for + * APR_OS_START_USERERR, which see. + */ +#define APR_OS_ERRSPACE_SIZE 50000 +/** + * APR_UTIL_ERRSPACE_SIZE is the size of the space that is reserved for + * use within apr-util. This space is reserved above that used by APR + * internally. + * @note This number MUST be smaller than APR_OS_ERRSPACE_SIZE by a + * large enough amount that APR has sufficient room for its + * codes. + */ +#define APR_UTIL_ERRSPACE_SIZE 20000 +/** + * APR_OS_START_STATUS is where the APR specific status codes start. + */ +#define APR_OS_START_STATUS (APR_OS_START_ERROR + APR_OS_ERRSPACE_SIZE) +/** + * APR_UTIL_START_STATUS is where APR-Util starts defining its + * status codes. + */ +#define APR_UTIL_START_STATUS (APR_OS_START_STATUS + \ + (APR_OS_ERRSPACE_SIZE - APR_UTIL_ERRSPACE_SIZE)) +/** + * APR_OS_START_USERERR are reserved for applications that use APR that + * layer their own error codes along with APR's. Note that the + * error immediately following this one is set ten times farther + * away than usual, so that users of apr have a lot of room in + * which to declare custom error codes. + * + * In general applications should try and create unique error codes. To try + * and assist in finding suitable ranges of numbers to use, the following + * ranges are known to be used by the listed applications. If your + * application defines error codes please advise the range of numbers it + * uses to dev@apr.apache.org for inclusion in this list. + * + * Ranges shown are in relation to APR_OS_START_USERERR + * + * Subversion - Defined ranges, of less than 100, at intervals of 5000 + * starting at an offset of 5000, e.g. + * +5000 to 5100, +10000 to 10100 + * + * Apache HTTPD - +2000 to 2999 + */ +#define APR_OS_START_USERERR (APR_OS_START_STATUS + APR_OS_ERRSPACE_SIZE) +/** + * APR_OS_START_USEERR is obsolete, defined for compatibility only. + * Use APR_OS_START_USERERR instead. + */ +#define APR_OS_START_USEERR APR_OS_START_USERERR +/** + * APR_OS_START_CANONERR is where APR versions of errno values are defined + * on systems which don't have the corresponding errno. + */ +#define APR_OS_START_CANONERR (APR_OS_START_USERERR \ + + (APR_OS_ERRSPACE_SIZE * 10)) +/** + * APR_OS_START_EAIERR folds EAI_ error codes from getaddrinfo() into + * apr_status_t values. + */ +#define APR_OS_START_EAIERR (APR_OS_START_CANONERR + APR_OS_ERRSPACE_SIZE) +/** + * APR_OS_START_SYSERR folds platform-specific system error values into + * apr_status_t values. + */ +#define APR_OS_START_SYSERR (APR_OS_START_EAIERR + APR_OS_ERRSPACE_SIZE) + +/** + * @defgroup APR_ERROR_map APR Error Space + *
+ * The following attempts to show the relation of the various constants
+ * used for mapping APR Status codes.
+ *
+ *       0
+ *
+ *  20,000     APR_OS_START_ERROR
+ *
+ *         + APR_OS_ERRSPACE_SIZE (50,000)
+ *
+ *  70,000      APR_OS_START_STATUS
+ *
+ *         + APR_OS_ERRSPACE_SIZE - APR_UTIL_ERRSPACE_SIZE (30,000)
+ *
+ * 100,000      APR_UTIL_START_STATUS
+ *
+ *         + APR_UTIL_ERRSPACE_SIZE (20,000)
+ *
+ * 120,000      APR_OS_START_USERERR
+ *
+ *         + 10 x APR_OS_ERRSPACE_SIZE (50,000 * 10)
+ *
+ * 620,000      APR_OS_START_CANONERR
+ *
+ *         + APR_OS_ERRSPACE_SIZE (50,000)
+ *
+ * 670,000      APR_OS_START_EAIERR
+ *
+ *         + APR_OS_ERRSPACE_SIZE (50,000)
+ *
+ * 720,000      APR_OS_START_SYSERR
+ *
+ * 
+ */ + +/** no error. */ +#define APR_SUCCESS 0 + +/** + * @defgroup APR_Error APR Error Values + *
+ * APR ERROR VALUES
+ * APR_ENOSTAT      APR was unable to perform a stat on the file
+ * APR_ENOPOOL      APR was not provided a pool with which to allocate memory
+ * APR_EBADDATE     APR was given an invalid date
+ * APR_EINVALSOCK   APR was given an invalid socket
+ * APR_ENOPROC      APR was not given a process structure
+ * APR_ENOTIME      APR was not given a time structure
+ * APR_ENODIR       APR was not given a directory structure
+ * APR_ENOLOCK      APR was not given a lock structure
+ * APR_ENOPOLL      APR was not given a poll structure
+ * APR_ENOSOCKET    APR was not given a socket
+ * APR_ENOTHREAD    APR was not given a thread structure
+ * APR_ENOTHDKEY    APR was not given a thread key structure
+ * APR_ENOSHMAVAIL  There is no more shared memory available
+ * APR_EDSOOPEN     APR was unable to open the dso object.  For more
+ *                  information call apr_dso_error().
+ * APR_EGENERAL     General failure (specific information not available)
+ * APR_EBADIP       The specified IP address is invalid
+ * APR_EBADMASK     The specified netmask is invalid
+ * APR_ESYMNOTFOUND Could not find the requested symbol
+ * APR_ENOTENOUGHENTROPY Not enough entropy to continue
+ * 
+ * + *
+ * APR STATUS VALUES
+ * APR_INCHILD        Program is currently executing in the child
+ * APR_INPARENT       Program is currently executing in the parent
+ * APR_DETACH         The thread is detached
+ * APR_NOTDETACH      The thread is not detached
+ * APR_CHILD_DONE     The child has finished executing
+ * APR_CHILD_NOTDONE  The child has not finished executing
+ * APR_TIMEUP         The operation did not finish before the timeout
+ * APR_INCOMPLETE     The operation was incomplete although some processing
+ *                    was performed and the results are partially valid
+ * APR_BADCH          Getopt found an option not in the option string
+ * APR_BADARG         Getopt found an option that is missing an argument
+ *                    and an argument was specified in the option string
+ * APR_EOF            APR has encountered the end of the file
+ * APR_NOTFOUND       APR was unable to find the socket in the poll structure
+ * APR_ANONYMOUS      APR is using anonymous shared memory
+ * APR_FILEBASED      APR is using a file name as the key to the shared memory
+ * APR_KEYBASED       APR is using a shared key as the key to the shared memory
+ * APR_EINIT          Ininitalizer value.  If no option has been found, but
+ *                    the status variable requires a value, this should be used
+ * APR_ENOTIMPL       The APR function has not been implemented on this
+ *                    platform, either because nobody has gotten to it yet,
+ *                    or the function is impossible on this platform.
+ * APR_EMISMATCH      Two passwords do not match.
+ * APR_EABSOLUTE      The given path was absolute.
+ * APR_ERELATIVE      The given path was relative.
+ * APR_EINCOMPLETE    The given path was neither relative nor absolute.
+ * APR_EABOVEROOT     The given path was above the root path.
+ * APR_EBUSY          The given lock was busy.
+ * APR_EPROC_UNKNOWN  The given process wasn't recognized by APR
+ * 
+ * @{ + */ +/** @see APR_STATUS_IS_ENOSTAT */ +#define APR_ENOSTAT (APR_OS_START_ERROR + 1) +/** @see APR_STATUS_IS_ENOPOOL */ +#define APR_ENOPOOL (APR_OS_START_ERROR + 2) +/* empty slot: +3 */ +/** @see APR_STATUS_IS_EBADDATE */ +#define APR_EBADDATE (APR_OS_START_ERROR + 4) +/** @see APR_STATUS_IS_EINVALSOCK */ +#define APR_EINVALSOCK (APR_OS_START_ERROR + 5) +/** @see APR_STATUS_IS_ENOPROC */ +#define APR_ENOPROC (APR_OS_START_ERROR + 6) +/** @see APR_STATUS_IS_ENOTIME */ +#define APR_ENOTIME (APR_OS_START_ERROR + 7) +/** @see APR_STATUS_IS_ENODIR */ +#define APR_ENODIR (APR_OS_START_ERROR + 8) +/** @see APR_STATUS_IS_ENOLOCK */ +#define APR_ENOLOCK (APR_OS_START_ERROR + 9) +/** @see APR_STATUS_IS_ENOPOLL */ +#define APR_ENOPOLL (APR_OS_START_ERROR + 10) +/** @see APR_STATUS_IS_ENOSOCKET */ +#define APR_ENOSOCKET (APR_OS_START_ERROR + 11) +/** @see APR_STATUS_IS_ENOTHREAD */ +#define APR_ENOTHREAD (APR_OS_START_ERROR + 12) +/** @see APR_STATUS_IS_ENOTHDKEY */ +#define APR_ENOTHDKEY (APR_OS_START_ERROR + 13) +/** @see APR_STATUS_IS_EGENERAL */ +#define APR_EGENERAL (APR_OS_START_ERROR + 14) +/** @see APR_STATUS_IS_ENOSHMAVAIL */ +#define APR_ENOSHMAVAIL (APR_OS_START_ERROR + 15) +/** @see APR_STATUS_IS_EBADIP */ +#define APR_EBADIP (APR_OS_START_ERROR + 16) +/** @see APR_STATUS_IS_EBADMASK */ +#define APR_EBADMASK (APR_OS_START_ERROR + 17) +/* empty slot: +18 */ +/** @see APR_STATUS_IS_EDSOPEN */ +#define APR_EDSOOPEN (APR_OS_START_ERROR + 19) +/** @see APR_STATUS_IS_EABSOLUTE */ +#define APR_EABSOLUTE (APR_OS_START_ERROR + 20) +/** @see APR_STATUS_IS_ERELATIVE */ +#define APR_ERELATIVE (APR_OS_START_ERROR + 21) +/** @see APR_STATUS_IS_EINCOMPLETE */ +#define APR_EINCOMPLETE (APR_OS_START_ERROR + 22) +/** @see APR_STATUS_IS_EABOVEROOT */ +#define APR_EABOVEROOT (APR_OS_START_ERROR + 23) +/** @see APR_STATUS_IS_EBADPATH */ +#define APR_EBADPATH (APR_OS_START_ERROR + 24) +/** @see APR_STATUS_IS_EPATHWILD */ +#define APR_EPATHWILD (APR_OS_START_ERROR + 25) +/** @see APR_STATUS_IS_ESYMNOTFOUND */ +#define APR_ESYMNOTFOUND (APR_OS_START_ERROR + 26) +/** @see APR_STATUS_IS_EPROC_UNKNOWN */ +#define APR_EPROC_UNKNOWN (APR_OS_START_ERROR + 27) +/** @see APR_STATUS_IS_ENOTENOUGHENTROPY */ +#define APR_ENOTENOUGHENTROPY (APR_OS_START_ERROR + 28) +/** @} */ + +/** + * @defgroup APR_STATUS_IS Status Value Tests + * @warning For any particular error condition, more than one of these tests + * may match. This is because platform-specific error codes may not + * always match the semantics of the POSIX codes these tests (and the + * corresponding APR error codes) are named after. A notable example + * are the APR_STATUS_IS_ENOENT and APR_STATUS_IS_ENOTDIR tests on + * Win32 platforms. The programmer should always be aware of this and + * adjust the order of the tests accordingly. + * @{ + */ +/** + * APR was unable to perform a stat on the file + * @warning always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_ENOSTAT(s) ((s) == APR_ENOSTAT) +/** + * APR was not provided a pool with which to allocate memory + * @warning always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_ENOPOOL(s) ((s) == APR_ENOPOOL) +/** APR was given an invalid date */ +#define APR_STATUS_IS_EBADDATE(s) ((s) == APR_EBADDATE) +/** APR was given an invalid socket */ +#define APR_STATUS_IS_EINVALSOCK(s) ((s) == APR_EINVALSOCK) +/** APR was not given a process structure */ +#define APR_STATUS_IS_ENOPROC(s) ((s) == APR_ENOPROC) +/** APR was not given a time structure */ +#define APR_STATUS_IS_ENOTIME(s) ((s) == APR_ENOTIME) +/** APR was not given a directory structure */ +#define APR_STATUS_IS_ENODIR(s) ((s) == APR_ENODIR) +/** APR was not given a lock structure */ +#define APR_STATUS_IS_ENOLOCK(s) ((s) == APR_ENOLOCK) +/** APR was not given a poll structure */ +#define APR_STATUS_IS_ENOPOLL(s) ((s) == APR_ENOPOLL) +/** APR was not given a socket */ +#define APR_STATUS_IS_ENOSOCKET(s) ((s) == APR_ENOSOCKET) +/** APR was not given a thread structure */ +#define APR_STATUS_IS_ENOTHREAD(s) ((s) == APR_ENOTHREAD) +/** APR was not given a thread key structure */ +#define APR_STATUS_IS_ENOTHDKEY(s) ((s) == APR_ENOTHDKEY) +/** Generic Error which can not be put into another spot */ +#define APR_STATUS_IS_EGENERAL(s) ((s) == APR_EGENERAL) +/** There is no more shared memory available */ +#define APR_STATUS_IS_ENOSHMAVAIL(s) ((s) == APR_ENOSHMAVAIL) +/** The specified IP address is invalid */ +#define APR_STATUS_IS_EBADIP(s) ((s) == APR_EBADIP) +/** The specified netmask is invalid */ +#define APR_STATUS_IS_EBADMASK(s) ((s) == APR_EBADMASK) +/* empty slot: +18 */ +/** + * APR was unable to open the dso object. + * For more information call apr_dso_error(). + */ +#if defined(WIN32) +#define APR_STATUS_IS_EDSOOPEN(s) ((s) == APR_EDSOOPEN \ + || APR_TO_OS_ERROR(s) == ERROR_MOD_NOT_FOUND) +#else +#define APR_STATUS_IS_EDSOOPEN(s) ((s) == APR_EDSOOPEN) +#endif +/** The given path was absolute. */ +#define APR_STATUS_IS_EABSOLUTE(s) ((s) == APR_EABSOLUTE) +/** The given path was relative. */ +#define APR_STATUS_IS_ERELATIVE(s) ((s) == APR_ERELATIVE) +/** The given path was neither relative nor absolute. */ +#define APR_STATUS_IS_EINCOMPLETE(s) ((s) == APR_EINCOMPLETE) +/** The given path was above the root path. */ +#define APR_STATUS_IS_EABOVEROOT(s) ((s) == APR_EABOVEROOT) +/** The given path was bad. */ +#define APR_STATUS_IS_EBADPATH(s) ((s) == APR_EBADPATH) +/** The given path contained wildcards. */ +#define APR_STATUS_IS_EPATHWILD(s) ((s) == APR_EPATHWILD) +/** Could not find the requested symbol. + * For more information call apr_dso_error(). + */ +#if defined(WIN32) +#define APR_STATUS_IS_ESYMNOTFOUND(s) ((s) == APR_ESYMNOTFOUND \ + || APR_TO_OS_ERROR(s) == ERROR_PROC_NOT_FOUND) +#else +#define APR_STATUS_IS_ESYMNOTFOUND(s) ((s) == APR_ESYMNOTFOUND) +#endif +/** The given process was not recognized by APR. */ +#define APR_STATUS_IS_EPROC_UNKNOWN(s) ((s) == APR_EPROC_UNKNOWN) +/** APR could not gather enough entropy to continue. */ +#define APR_STATUS_IS_ENOTENOUGHENTROPY(s) ((s) == APR_ENOTENOUGHENTROPY) + +/** @} */ + +/** + * @addtogroup APR_Error + * @{ + */ +/** @see APR_STATUS_IS_INCHILD */ +#define APR_INCHILD (APR_OS_START_STATUS + 1) +/** @see APR_STATUS_IS_INPARENT */ +#define APR_INPARENT (APR_OS_START_STATUS + 2) +/** @see APR_STATUS_IS_DETACH */ +#define APR_DETACH (APR_OS_START_STATUS + 3) +/** @see APR_STATUS_IS_NOTDETACH */ +#define APR_NOTDETACH (APR_OS_START_STATUS + 4) +/** @see APR_STATUS_IS_CHILD_DONE */ +#define APR_CHILD_DONE (APR_OS_START_STATUS + 5) +/** @see APR_STATUS_IS_CHILD_NOTDONE */ +#define APR_CHILD_NOTDONE (APR_OS_START_STATUS + 6) +/** @see APR_STATUS_IS_TIMEUP */ +#define APR_TIMEUP (APR_OS_START_STATUS + 7) +/** @see APR_STATUS_IS_INCOMPLETE */ +#define APR_INCOMPLETE (APR_OS_START_STATUS + 8) +/* empty slot: +9 */ +/* empty slot: +10 */ +/* empty slot: +11 */ +/** @see APR_STATUS_IS_BADCH */ +#define APR_BADCH (APR_OS_START_STATUS + 12) +/** @see APR_STATUS_IS_BADARG */ +#define APR_BADARG (APR_OS_START_STATUS + 13) +/** @see APR_STATUS_IS_EOF */ +#define APR_EOF (APR_OS_START_STATUS + 14) +/** @see APR_STATUS_IS_NOTFOUND */ +#define APR_NOTFOUND (APR_OS_START_STATUS + 15) +/* empty slot: +16 */ +/* empty slot: +17 */ +/* empty slot: +18 */ +/** @see APR_STATUS_IS_ANONYMOUS */ +#define APR_ANONYMOUS (APR_OS_START_STATUS + 19) +/** @see APR_STATUS_IS_FILEBASED */ +#define APR_FILEBASED (APR_OS_START_STATUS + 20) +/** @see APR_STATUS_IS_KEYBASED */ +#define APR_KEYBASED (APR_OS_START_STATUS + 21) +/** @see APR_STATUS_IS_EINIT */ +#define APR_EINIT (APR_OS_START_STATUS + 22) +/** @see APR_STATUS_IS_ENOTIMPL */ +#define APR_ENOTIMPL (APR_OS_START_STATUS + 23) +/** @see APR_STATUS_IS_EMISMATCH */ +#define APR_EMISMATCH (APR_OS_START_STATUS + 24) +/** @see APR_STATUS_IS_EBUSY */ +#define APR_EBUSY (APR_OS_START_STATUS + 25) +/** @} */ + +/** + * @addtogroup APR_STATUS_IS + * @{ + */ +/** + * Program is currently executing in the child + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code */ +#define APR_STATUS_IS_INCHILD(s) ((s) == APR_INCHILD) +/** + * Program is currently executing in the parent + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_INPARENT(s) ((s) == APR_INPARENT) +/** + * The thread is detached + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_DETACH(s) ((s) == APR_DETACH) +/** + * The thread is not detached + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_NOTDETACH(s) ((s) == APR_NOTDETACH) +/** + * The child has finished executing + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_CHILD_DONE(s) ((s) == APR_CHILD_DONE) +/** + * The child has not finished executing + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_CHILD_NOTDONE(s) ((s) == APR_CHILD_NOTDONE) +/** + * The operation did not finish before the timeout + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_TIMEUP(s) ((s) == APR_TIMEUP) +/** + * The operation was incomplete although some processing was performed + * and the results are partially valid. + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_INCOMPLETE(s) ((s) == APR_INCOMPLETE) +/* empty slot: +9 */ +/* empty slot: +10 */ +/* empty slot: +11 */ +/** + * Getopt found an option not in the option string + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_BADCH(s) ((s) == APR_BADCH) +/** + * Getopt found an option not in the option string and an argument was + * specified in the option string + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_BADARG(s) ((s) == APR_BADARG) +/** + * APR has encountered the end of the file + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_EOF(s) ((s) == APR_EOF) +/** + * APR was unable to find the socket in the poll structure + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_NOTFOUND(s) ((s) == APR_NOTFOUND) +/* empty slot: +16 */ +/* empty slot: +17 */ +/* empty slot: +18 */ +/** + * APR is using anonymous shared memory + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_ANONYMOUS(s) ((s) == APR_ANONYMOUS) +/** + * APR is using a file name as the key to the shared memory + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_FILEBASED(s) ((s) == APR_FILEBASED) +/** + * APR is using a shared key as the key to the shared memory + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_KEYBASED(s) ((s) == APR_KEYBASED) +/** + * Ininitalizer value. If no option has been found, but + * the status variable requires a value, this should be used + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_EINIT(s) ((s) == APR_EINIT) +/** + * The APR function has not been implemented on this + * platform, either because nobody has gotten to it yet, + * or the function is impossible on this platform. + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_ENOTIMPL(s) ((s) == APR_ENOTIMPL) +/** + * Two passwords do not match. + * @warning + * always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_EMISMATCH(s) ((s) == APR_EMISMATCH) +/** + * The given lock was busy + * @warning always use this test, as platform-specific variances may meet this + * more than one error code + */ +#define APR_STATUS_IS_EBUSY(s) ((s) == APR_EBUSY) + +/** @} */ + +/** + * @addtogroup APR_Error APR Error Values + * @{ + */ +/* APR CANONICAL ERROR VALUES */ +/** @see APR_STATUS_IS_EACCES */ +#ifdef EACCES +#define APR_EACCES EACCES +#else +#define APR_EACCES (APR_OS_START_CANONERR + 1) +#endif + +/** @see APR_STATUS_IS_EEXIST */ +#ifdef EEXIST +#define APR_EEXIST EEXIST +#else +#define APR_EEXIST (APR_OS_START_CANONERR + 2) +#endif + +/** @see APR_STATUS_IS_ENAMETOOLONG */ +#ifdef ENAMETOOLONG +#define APR_ENAMETOOLONG ENAMETOOLONG +#else +#define APR_ENAMETOOLONG (APR_OS_START_CANONERR + 3) +#endif + +/** @see APR_STATUS_IS_ENOENT */ +#ifdef ENOENT +#define APR_ENOENT ENOENT +#else +#define APR_ENOENT (APR_OS_START_CANONERR + 4) +#endif + +/** @see APR_STATUS_IS_ENOTDIR */ +#ifdef ENOTDIR +#define APR_ENOTDIR ENOTDIR +#else +#define APR_ENOTDIR (APR_OS_START_CANONERR + 5) +#endif + +/** @see APR_STATUS_IS_ENOSPC */ +#ifdef ENOSPC +#define APR_ENOSPC ENOSPC +#else +#define APR_ENOSPC (APR_OS_START_CANONERR + 6) +#endif + +/** @see APR_STATUS_IS_ENOMEM */ +#ifdef ENOMEM +#define APR_ENOMEM ENOMEM +#else +#define APR_ENOMEM (APR_OS_START_CANONERR + 7) +#endif + +/** @see APR_STATUS_IS_EMFILE */ +#ifdef EMFILE +#define APR_EMFILE EMFILE +#else +#define APR_EMFILE (APR_OS_START_CANONERR + 8) +#endif + +/** @see APR_STATUS_IS_ENFILE */ +#ifdef ENFILE +#define APR_ENFILE ENFILE +#else +#define APR_ENFILE (APR_OS_START_CANONERR + 9) +#endif + +/** @see APR_STATUS_IS_EBADF */ +#ifdef EBADF +#define APR_EBADF EBADF +#else +#define APR_EBADF (APR_OS_START_CANONERR + 10) +#endif + +/** @see APR_STATUS_IS_EINVAL */ +#ifdef EINVAL +#define APR_EINVAL EINVAL +#else +#define APR_EINVAL (APR_OS_START_CANONERR + 11) +#endif + +/** @see APR_STATUS_IS_ESPIPE */ +#ifdef ESPIPE +#define APR_ESPIPE ESPIPE +#else +#define APR_ESPIPE (APR_OS_START_CANONERR + 12) +#endif + +/** + * @see APR_STATUS_IS_EAGAIN + * @warning use APR_STATUS_IS_EAGAIN instead of just testing this value + */ +#ifdef EAGAIN +#define APR_EAGAIN EAGAIN +#elif defined(EWOULDBLOCK) +#define APR_EAGAIN EWOULDBLOCK +#else +#define APR_EAGAIN (APR_OS_START_CANONERR + 13) +#endif + +/** @see APR_STATUS_IS_EINTR */ +#ifdef EINTR +#define APR_EINTR EINTR +#else +#define APR_EINTR (APR_OS_START_CANONERR + 14) +#endif + +/** @see APR_STATUS_IS_ENOTSOCK */ +#ifdef ENOTSOCK +#define APR_ENOTSOCK ENOTSOCK +#else +#define APR_ENOTSOCK (APR_OS_START_CANONERR + 15) +#endif + +/** @see APR_STATUS_IS_ECONNREFUSED */ +#ifdef ECONNREFUSED +#define APR_ECONNREFUSED ECONNREFUSED +#else +#define APR_ECONNREFUSED (APR_OS_START_CANONERR + 16) +#endif + +/** @see APR_STATUS_IS_EINPROGRESS */ +#ifdef EINPROGRESS +#define APR_EINPROGRESS EINPROGRESS +#else +#define APR_EINPROGRESS (APR_OS_START_CANONERR + 17) +#endif + +/** + * @see APR_STATUS_IS_ECONNABORTED + * @warning use APR_STATUS_IS_ECONNABORTED instead of just testing this value + */ + +#ifdef ECONNABORTED +#define APR_ECONNABORTED ECONNABORTED +#else +#define APR_ECONNABORTED (APR_OS_START_CANONERR + 18) +#endif + +/** @see APR_STATUS_IS_ECONNRESET */ +#ifdef ECONNRESET +#define APR_ECONNRESET ECONNRESET +#else +#define APR_ECONNRESET (APR_OS_START_CANONERR + 19) +#endif + +/** @see APR_STATUS_IS_ETIMEDOUT + * @deprecated */ +#ifdef ETIMEDOUT +#define APR_ETIMEDOUT ETIMEDOUT +#else +#define APR_ETIMEDOUT (APR_OS_START_CANONERR + 20) +#endif + +/** @see APR_STATUS_IS_EHOSTUNREACH */ +#ifdef EHOSTUNREACH +#define APR_EHOSTUNREACH EHOSTUNREACH +#else +#define APR_EHOSTUNREACH (APR_OS_START_CANONERR + 21) +#endif + +/** @see APR_STATUS_IS_ENETUNREACH */ +#ifdef ENETUNREACH +#define APR_ENETUNREACH ENETUNREACH +#else +#define APR_ENETUNREACH (APR_OS_START_CANONERR + 22) +#endif + +/** @see APR_STATUS_IS_EFTYPE */ +#ifdef EFTYPE +#define APR_EFTYPE EFTYPE +#else +#define APR_EFTYPE (APR_OS_START_CANONERR + 23) +#endif + +/** @see APR_STATUS_IS_EPIPE */ +#ifdef EPIPE +#define APR_EPIPE EPIPE +#else +#define APR_EPIPE (APR_OS_START_CANONERR + 24) +#endif + +/** @see APR_STATUS_IS_EXDEV */ +#ifdef EXDEV +#define APR_EXDEV EXDEV +#else +#define APR_EXDEV (APR_OS_START_CANONERR + 25) +#endif + +/** @see APR_STATUS_IS_ENOTEMPTY */ +#ifdef ENOTEMPTY +#define APR_ENOTEMPTY ENOTEMPTY +#else +#define APR_ENOTEMPTY (APR_OS_START_CANONERR + 26) +#endif + +/** @see APR_STATUS_IS_EAFNOSUPPORT */ +#ifdef EAFNOSUPPORT +#define APR_EAFNOSUPPORT EAFNOSUPPORT +#else +#define APR_EAFNOSUPPORT (APR_OS_START_CANONERR + 27) +#endif + +/** @see APR_STATUS_IS_EOPNOTSUPP */ +#ifdef EOPNOTSUPP +#define APR_EOPNOTSUPP EOPNOTSUPP +#else +#define APR_EOPNOTSUPP (APR_OS_START_CANONERR + 28) +#endif + +/** @see APR_STATUS_IS_ERANGE */ +#ifdef ERANGE +#define APR_ERANGE ERANGE +#else +#define APR_ERANGE (APR_OS_START_CANONERR + 29) +#endif + +/** @} */ + +#if defined(OS2) && !defined(DOXYGEN) + +#define APR_FROM_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e + APR_OS_START_SYSERR) +#define APR_TO_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e - APR_OS_START_SYSERR) + +#define INCL_DOSERRORS +#define INCL_DOS + +/* Leave these undefined. + * OS2 doesn't rely on the errno concept. + * The API calls always return a result codes which + * should be filtered through APR_FROM_OS_ERROR(). + * + * #define apr_get_os_error() (APR_FROM_OS_ERROR(GetLastError())) + * #define apr_set_os_error(e) (SetLastError(APR_TO_OS_ERROR(e))) + */ + +/* A special case, only socket calls require this; + */ +#define apr_get_netos_error() (APR_FROM_OS_ERROR(errno)) +#define apr_set_netos_error(e) (errno = APR_TO_OS_ERROR(e)) + +/* And this needs to be greped away for good: + */ +#define APR_OS2_STATUS(e) (APR_FROM_OS_ERROR(e)) + +/* These can't sit in a private header, so in spite of the extra size, + * they need to be made available here. + */ +#define SOCBASEERR 10000 +#define SOCEPERM (SOCBASEERR+1) /* Not owner */ +#define SOCESRCH (SOCBASEERR+3) /* No such process */ +#define SOCEINTR (SOCBASEERR+4) /* Interrupted system call */ +#define SOCENXIO (SOCBASEERR+6) /* No such device or address */ +#define SOCEBADF (SOCBASEERR+9) /* Bad file number */ +#define SOCEACCES (SOCBASEERR+13) /* Permission denied */ +#define SOCEFAULT (SOCBASEERR+14) /* Bad address */ +#define SOCEINVAL (SOCBASEERR+22) /* Invalid argument */ +#define SOCEMFILE (SOCBASEERR+24) /* Too many open files */ +#define SOCEPIPE (SOCBASEERR+32) /* Broken pipe */ +#define SOCEOS2ERR (SOCBASEERR+100) /* OS/2 Error */ +#define SOCEWOULDBLOCK (SOCBASEERR+35) /* Operation would block */ +#define SOCEINPROGRESS (SOCBASEERR+36) /* Operation now in progress */ +#define SOCEALREADY (SOCBASEERR+37) /* Operation already in progress */ +#define SOCENOTSOCK (SOCBASEERR+38) /* Socket operation on non-socket */ +#define SOCEDESTADDRREQ (SOCBASEERR+39) /* Destination address required */ +#define SOCEMSGSIZE (SOCBASEERR+40) /* Message too long */ +#define SOCEPROTOTYPE (SOCBASEERR+41) /* Protocol wrong type for socket */ +#define SOCENOPROTOOPT (SOCBASEERR+42) /* Protocol not available */ +#define SOCEPROTONOSUPPORT (SOCBASEERR+43) /* Protocol not supported */ +#define SOCESOCKTNOSUPPORT (SOCBASEERR+44) /* Socket type not supported */ +#define SOCEOPNOTSUPP (SOCBASEERR+45) /* Operation not supported on socket */ +#define SOCEPFNOSUPPORT (SOCBASEERR+46) /* Protocol family not supported */ +#define SOCEAFNOSUPPORT (SOCBASEERR+47) /* Address family not supported by protocol family */ +#define SOCEADDRINUSE (SOCBASEERR+48) /* Address already in use */ +#define SOCEADDRNOTAVAIL (SOCBASEERR+49) /* Can't assign requested address */ +#define SOCENETDOWN (SOCBASEERR+50) /* Network is down */ +#define SOCENETUNREACH (SOCBASEERR+51) /* Network is unreachable */ +#define SOCENETRESET (SOCBASEERR+52) /* Network dropped connection on reset */ +#define SOCECONNABORTED (SOCBASEERR+53) /* Software caused connection abort */ +#define SOCECONNRESET (SOCBASEERR+54) /* Connection reset by peer */ +#define SOCENOBUFS (SOCBASEERR+55) /* No buffer space available */ +#define SOCEISCONN (SOCBASEERR+56) /* Socket is already connected */ +#define SOCENOTCONN (SOCBASEERR+57) /* Socket is not connected */ +#define SOCESHUTDOWN (SOCBASEERR+58) /* Can't send after socket shutdown */ +#define SOCETOOMANYREFS (SOCBASEERR+59) /* Too many references: can't splice */ +#define SOCETIMEDOUT (SOCBASEERR+60) /* Connection timed out */ +#define SOCECONNREFUSED (SOCBASEERR+61) /* Connection refused */ +#define SOCELOOP (SOCBASEERR+62) /* Too many levels of symbolic links */ +#define SOCENAMETOOLONG (SOCBASEERR+63) /* File name too long */ +#define SOCEHOSTDOWN (SOCBASEERR+64) /* Host is down */ +#define SOCEHOSTUNREACH (SOCBASEERR+65) /* No route to host */ +#define SOCENOTEMPTY (SOCBASEERR+66) /* Directory not empty */ + +/* APR CANONICAL ERROR TESTS */ +#define APR_STATUS_IS_EACCES(s) ((s) == APR_EACCES \ + || (s) == APR_OS_START_SYSERR + ERROR_ACCESS_DENIED \ + || (s) == APR_OS_START_SYSERR + ERROR_SHARING_VIOLATION) +#define APR_STATUS_IS_EEXIST(s) ((s) == APR_EEXIST \ + || (s) == APR_OS_START_SYSERR + ERROR_OPEN_FAILED \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_EXISTS \ + || (s) == APR_OS_START_SYSERR + ERROR_ALREADY_EXISTS \ + || (s) == APR_OS_START_SYSERR + ERROR_ACCESS_DENIED) +#define APR_STATUS_IS_ENAMETOOLONG(s) ((s) == APR_ENAMETOOLONG \ + || (s) == APR_OS_START_SYSERR + ERROR_FILENAME_EXCED_RANGE \ + || (s) == APR_OS_START_SYSERR + SOCENAMETOOLONG) +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_PATH_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_MORE_FILES \ + || (s) == APR_OS_START_SYSERR + ERROR_OPEN_FAILED) +#define APR_STATUS_IS_ENOTDIR(s) ((s) == APR_ENOTDIR) +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC \ + || (s) == APR_OS_START_SYSERR + ERROR_DISK_FULL) +#define APR_STATUS_IS_ENOMEM(s) ((s) == APR_ENOMEM) +#define APR_STATUS_IS_EMFILE(s) ((s) == APR_EMFILE \ + || (s) == APR_OS_START_SYSERR + ERROR_TOO_MANY_OPEN_FILES) +#define APR_STATUS_IS_ENFILE(s) ((s) == APR_ENFILE) +#define APR_STATUS_IS_EBADF(s) ((s) == APR_EBADF \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_HANDLE) +#define APR_STATUS_IS_EINVAL(s) ((s) == APR_EINVAL \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_PARAMETER \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_FUNCTION) +#define APR_STATUS_IS_ESPIPE(s) ((s) == APR_ESPIPE \ + || (s) == APR_OS_START_SYSERR + ERROR_NEGATIVE_SEEK) +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_DATA \ + || (s) == APR_OS_START_SYSERR + SOCEWOULDBLOCK \ + || (s) == APR_OS_START_SYSERR + ERROR_LOCK_VIOLATION) +#define APR_STATUS_IS_EINTR(s) ((s) == APR_EINTR \ + || (s) == APR_OS_START_SYSERR + SOCEINTR) +#define APR_STATUS_IS_ENOTSOCK(s) ((s) == APR_ENOTSOCK \ + || (s) == APR_OS_START_SYSERR + SOCENOTSOCK) +#define APR_STATUS_IS_ECONNREFUSED(s) ((s) == APR_ECONNREFUSED \ + || (s) == APR_OS_START_SYSERR + SOCECONNREFUSED) +#define APR_STATUS_IS_EINPROGRESS(s) ((s) == APR_EINPROGRESS \ + || (s) == APR_OS_START_SYSERR + SOCEINPROGRESS) +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED \ + || (s) == APR_OS_START_SYSERR + SOCECONNABORTED) +#define APR_STATUS_IS_ECONNRESET(s) ((s) == APR_ECONNRESET \ + || (s) == APR_OS_START_SYSERR + SOCECONNRESET) +/* XXX deprecated */ +#define APR_STATUS_IS_ETIMEDOUT(s) ((s) == APR_ETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + SOCETIMEDOUT) +#undef APR_STATUS_IS_TIMEUP +#define APR_STATUS_IS_TIMEUP(s) ((s) == APR_TIMEUP \ + || (s) == APR_OS_START_SYSERR + SOCETIMEDOUT) +#define APR_STATUS_IS_EHOSTUNREACH(s) ((s) == APR_EHOSTUNREACH \ + || (s) == APR_OS_START_SYSERR + SOCEHOSTUNREACH) +#define APR_STATUS_IS_ENETUNREACH(s) ((s) == APR_ENETUNREACH \ + || (s) == APR_OS_START_SYSERR + SOCENETUNREACH) +#define APR_STATUS_IS_EFTYPE(s) ((s) == APR_EFTYPE) +#define APR_STATUS_IS_EPIPE(s) ((s) == APR_EPIPE \ + || (s) == APR_OS_START_SYSERR + ERROR_BROKEN_PIPE \ + || (s) == APR_OS_START_SYSERR + SOCEPIPE) +#define APR_STATUS_IS_EXDEV(s) ((s) == APR_EXDEV \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_SAME_DEVICE) +#define APR_STATUS_IS_ENOTEMPTY(s) ((s) == APR_ENOTEMPTY \ + || (s) == APR_OS_START_SYSERR + ERROR_DIR_NOT_EMPTY \ + || (s) == APR_OS_START_SYSERR + ERROR_ACCESS_DENIED) +#define APR_STATUS_IS_EAFNOSUPPORT(s) ((s) == APR_AFNOSUPPORT \ + || (s) == APR_OS_START_SYSERR + SOCEAFNOSUPPORT) +#define APR_STATUS_IS_EOPNOTSUPP(s) ((s) == APR_EOPNOTSUPP \ + || (s) == APR_OS_START_SYSERR + SOCEOPNOTSUPP) +#define APR_STATUS_IS_ERANGE(s) ((s) == APR_ERANGE) + +/* + Sorry, too tired to wrap this up for OS2... feel free to + fit the following into their best matches. + + { ERROR_NO_SIGNAL_SENT, ESRCH }, + { SOCEALREADY, EALREADY }, + { SOCEDESTADDRREQ, EDESTADDRREQ }, + { SOCEMSGSIZE, EMSGSIZE }, + { SOCEPROTOTYPE, EPROTOTYPE }, + { SOCENOPROTOOPT, ENOPROTOOPT }, + { SOCEPROTONOSUPPORT, EPROTONOSUPPORT }, + { SOCESOCKTNOSUPPORT, ESOCKTNOSUPPORT }, + { SOCEPFNOSUPPORT, EPFNOSUPPORT }, + { SOCEADDRINUSE, EADDRINUSE }, + { SOCEADDRNOTAVAIL, EADDRNOTAVAIL }, + { SOCENETDOWN, ENETDOWN }, + { SOCENETRESET, ENETRESET }, + { SOCENOBUFS, ENOBUFS }, + { SOCEISCONN, EISCONN }, + { SOCENOTCONN, ENOTCONN }, + { SOCESHUTDOWN, ESHUTDOWN }, + { SOCETOOMANYREFS, ETOOMANYREFS }, + { SOCELOOP, ELOOP }, + { SOCEHOSTDOWN, EHOSTDOWN }, + { SOCENOTEMPTY, ENOTEMPTY }, + { SOCEPIPE, EPIPE } +*/ + +#elif defined(WIN32) && !defined(DOXYGEN) /* !defined(OS2) */ + +#define APR_FROM_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e + APR_OS_START_SYSERR) +#define APR_TO_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e - APR_OS_START_SYSERR) + +#define apr_get_os_error() (APR_FROM_OS_ERROR(GetLastError())) +#define apr_set_os_error(e) (SetLastError(APR_TO_OS_ERROR(e))) + +/* A special case, only socket calls require this: + */ +#define apr_get_netos_error() (APR_FROM_OS_ERROR(WSAGetLastError())) +#define apr_set_netos_error(e) (WSASetLastError(APR_TO_OS_ERROR(e))) + +/* APR CANONICAL ERROR TESTS */ +#define APR_STATUS_IS_EACCES(s) ((s) == APR_EACCES \ + || (s) == APR_OS_START_SYSERR + ERROR_ACCESS_DENIED \ + || (s) == APR_OS_START_SYSERR + ERROR_CANNOT_MAKE \ + || (s) == APR_OS_START_SYSERR + ERROR_CURRENT_DIRECTORY \ + || (s) == APR_OS_START_SYSERR + ERROR_DRIVE_LOCKED \ + || (s) == APR_OS_START_SYSERR + ERROR_FAIL_I24 \ + || (s) == APR_OS_START_SYSERR + ERROR_LOCK_VIOLATION \ + || (s) == APR_OS_START_SYSERR + ERROR_LOCK_FAILED \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_LOCKED \ + || (s) == APR_OS_START_SYSERR + ERROR_NETWORK_ACCESS_DENIED \ + || (s) == APR_OS_START_SYSERR + ERROR_SHARING_VIOLATION) +#define APR_STATUS_IS_EEXIST(s) ((s) == APR_EEXIST \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_EXISTS \ + || (s) == APR_OS_START_SYSERR + ERROR_ALREADY_EXISTS) +#define APR_STATUS_IS_ENAMETOOLONG(s) ((s) == APR_ENAMETOOLONG \ + || (s) == APR_OS_START_SYSERR + ERROR_FILENAME_EXCED_RANGE \ + || (s) == APR_OS_START_SYSERR + WSAENAMETOOLONG) +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_PATH_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_OPEN_FAILED \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_MORE_FILES) +#define APR_STATUS_IS_ENOTDIR(s) ((s) == APR_ENOTDIR \ + || (s) == APR_OS_START_SYSERR + ERROR_PATH_NOT_FOUND \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_NETPATH \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_NET_NAME \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_PATHNAME \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_DRIVE \ + || (s) == APR_OS_START_SYSERR + ERROR_DIRECTORY) +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC \ + || (s) == APR_OS_START_SYSERR + ERROR_DISK_FULL) +#define APR_STATUS_IS_ENOMEM(s) ((s) == APR_ENOMEM \ + || (s) == APR_OS_START_SYSERR + ERROR_ARENA_TRASHED \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_ENOUGH_MEMORY \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_BLOCK \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_ENOUGH_QUOTA \ + || (s) == APR_OS_START_SYSERR + ERROR_OUTOFMEMORY) +#define APR_STATUS_IS_EMFILE(s) ((s) == APR_EMFILE \ + || (s) == APR_OS_START_SYSERR + ERROR_TOO_MANY_OPEN_FILES) +#define APR_STATUS_IS_ENFILE(s) ((s) == APR_ENFILE) +#define APR_STATUS_IS_EBADF(s) ((s) == APR_EBADF \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_HANDLE \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_TARGET_HANDLE) +#define APR_STATUS_IS_EINVAL(s) ((s) == APR_EINVAL \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_ACCESS \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_DATA \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_FUNCTION \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_HANDLE \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_PARAMETER \ + || (s) == APR_OS_START_SYSERR + ERROR_NEGATIVE_SEEK) +#define APR_STATUS_IS_ESPIPE(s) ((s) == APR_ESPIPE \ + || (s) == APR_OS_START_SYSERR + ERROR_SEEK_ON_DEVICE \ + || (s) == APR_OS_START_SYSERR + ERROR_NEGATIVE_SEEK) +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_DATA \ + || (s) == APR_OS_START_SYSERR + ERROR_NO_PROC_SLOTS \ + || (s) == APR_OS_START_SYSERR + ERROR_NESTING_NOT_ALLOWED \ + || (s) == APR_OS_START_SYSERR + ERROR_MAX_THRDS_REACHED \ + || (s) == APR_OS_START_SYSERR + ERROR_LOCK_VIOLATION \ + || (s) == APR_OS_START_SYSERR + WSAEWOULDBLOCK) +#define APR_STATUS_IS_EINTR(s) ((s) == APR_EINTR \ + || (s) == APR_OS_START_SYSERR + WSAEINTR) +#define APR_STATUS_IS_ENOTSOCK(s) ((s) == APR_ENOTSOCK \ + || (s) == APR_OS_START_SYSERR + WSAENOTSOCK) +#define APR_STATUS_IS_ECONNREFUSED(s) ((s) == APR_ECONNREFUSED \ + || (s) == APR_OS_START_SYSERR + WSAECONNREFUSED) +#define APR_STATUS_IS_EINPROGRESS(s) ((s) == APR_EINPROGRESS \ + || (s) == APR_OS_START_SYSERR + WSAEINPROGRESS) +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED \ + || (s) == APR_OS_START_SYSERR + WSAECONNABORTED) +#define APR_STATUS_IS_ECONNRESET(s) ((s) == APR_ECONNRESET \ + || (s) == APR_OS_START_SYSERR + ERROR_NETNAME_DELETED \ + || (s) == APR_OS_START_SYSERR + WSAECONNRESET) +/* XXX deprecated */ +#define APR_STATUS_IS_ETIMEDOUT(s) ((s) == APR_ETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WSAETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WAIT_TIMEOUT) +#undef APR_STATUS_IS_TIMEUP +#define APR_STATUS_IS_TIMEUP(s) ((s) == APR_TIMEUP \ + || (s) == APR_OS_START_SYSERR + WSAETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WAIT_TIMEOUT) +#define APR_STATUS_IS_EHOSTUNREACH(s) ((s) == APR_EHOSTUNREACH \ + || (s) == APR_OS_START_SYSERR + WSAEHOSTUNREACH) +#define APR_STATUS_IS_ENETUNREACH(s) ((s) == APR_ENETUNREACH \ + || (s) == APR_OS_START_SYSERR + WSAENETUNREACH) +#define APR_STATUS_IS_EFTYPE(s) ((s) == APR_EFTYPE \ + || (s) == APR_OS_START_SYSERR + ERROR_EXE_MACHINE_TYPE_MISMATCH \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_DLL \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_MODULETYPE \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_EXE_FORMAT \ + || (s) == APR_OS_START_SYSERR + ERROR_INVALID_EXE_SIGNATURE \ + || (s) == APR_OS_START_SYSERR + ERROR_FILE_CORRUPT \ + || (s) == APR_OS_START_SYSERR + ERROR_BAD_FORMAT) +#define APR_STATUS_IS_EPIPE(s) ((s) == APR_EPIPE \ + || (s) == APR_OS_START_SYSERR + ERROR_BROKEN_PIPE) +#define APR_STATUS_IS_EXDEV(s) ((s) == APR_EXDEV \ + || (s) == APR_OS_START_SYSERR + ERROR_NOT_SAME_DEVICE) +#define APR_STATUS_IS_ENOTEMPTY(s) ((s) == APR_ENOTEMPTY \ + || (s) == APR_OS_START_SYSERR + ERROR_DIR_NOT_EMPTY) +#define APR_STATUS_IS_EAFNOSUPPORT(s) ((s) == APR_EAFNOSUPPORT \ + || (s) == APR_OS_START_SYSERR + WSAEAFNOSUPPORT) +#define APR_STATUS_IS_EOPNOTSUPP(s) ((s) == APR_EOPNOTSUPP \ + || (s) == APR_OS_START_SYSERR + WSAEOPNOTSUPP) +#define APR_STATUS_IS_ERANGE(s) ((s) == APR_ERANGE) + +#elif defined(NETWARE) && defined(USE_WINSOCK) && !defined(DOXYGEN) /* !defined(OS2) && !defined(WIN32) */ + +#define APR_FROM_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e + APR_OS_START_SYSERR) +#define APR_TO_OS_ERROR(e) (e == 0 ? APR_SUCCESS : e - APR_OS_START_SYSERR) + +#define apr_get_os_error() (errno) +#define apr_set_os_error(e) (errno = (e)) + +/* A special case, only socket calls require this: */ +#define apr_get_netos_error() (APR_FROM_OS_ERROR(WSAGetLastError())) +#define apr_set_netos_error(e) (WSASetLastError(APR_TO_OS_ERROR(e))) + +/* APR CANONICAL ERROR TESTS */ +#define APR_STATUS_IS_EACCES(s) ((s) == APR_EACCES) +#define APR_STATUS_IS_EEXIST(s) ((s) == APR_EEXIST) +#define APR_STATUS_IS_ENAMETOOLONG(s) ((s) == APR_ENAMETOOLONG) +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT) +#define APR_STATUS_IS_ENOTDIR(s) ((s) == APR_ENOTDIR) +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC) +#define APR_STATUS_IS_ENOMEM(s) ((s) == APR_ENOMEM) +#define APR_STATUS_IS_EMFILE(s) ((s) == APR_EMFILE) +#define APR_STATUS_IS_ENFILE(s) ((s) == APR_ENFILE) +#define APR_STATUS_IS_EBADF(s) ((s) == APR_EBADF) +#define APR_STATUS_IS_EINVAL(s) ((s) == APR_EINVAL) +#define APR_STATUS_IS_ESPIPE(s) ((s) == APR_ESPIPE) + +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN \ + || (s) == EWOULDBLOCK \ + || (s) == APR_OS_START_SYSERR + WSAEWOULDBLOCK) +#define APR_STATUS_IS_EINTR(s) ((s) == APR_EINTR \ + || (s) == APR_OS_START_SYSERR + WSAEINTR) +#define APR_STATUS_IS_ENOTSOCK(s) ((s) == APR_ENOTSOCK \ + || (s) == APR_OS_START_SYSERR + WSAENOTSOCK) +#define APR_STATUS_IS_ECONNREFUSED(s) ((s) == APR_ECONNREFUSED \ + || (s) == APR_OS_START_SYSERR + WSAECONNREFUSED) +#define APR_STATUS_IS_EINPROGRESS(s) ((s) == APR_EINPROGRESS \ + || (s) == APR_OS_START_SYSERR + WSAEINPROGRESS) +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED \ + || (s) == APR_OS_START_SYSERR + WSAECONNABORTED) +#define APR_STATUS_IS_ECONNRESET(s) ((s) == APR_ECONNRESET \ + || (s) == APR_OS_START_SYSERR + WSAECONNRESET) +/* XXX deprecated */ +#define APR_STATUS_IS_ETIMEDOUT(s) ((s) == APR_ETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WSAETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WAIT_TIMEOUT) +#undef APR_STATUS_IS_TIMEUP +#define APR_STATUS_IS_TIMEUP(s) ((s) == APR_TIMEUP \ + || (s) == APR_OS_START_SYSERR + WSAETIMEDOUT \ + || (s) == APR_OS_START_SYSERR + WAIT_TIMEOUT) +#define APR_STATUS_IS_EHOSTUNREACH(s) ((s) == APR_EHOSTUNREACH \ + || (s) == APR_OS_START_SYSERR + WSAEHOSTUNREACH) +#define APR_STATUS_IS_ENETUNREACH(s) ((s) == APR_ENETUNREACH \ + || (s) == APR_OS_START_SYSERR + WSAENETUNREACH) +#define APR_STATUS_IS_ENETDOWN(s) ((s) == APR_OS_START_SYSERR + WSAENETDOWN) +#define APR_STATUS_IS_EFTYPE(s) ((s) == APR_EFTYPE) +#define APR_STATUS_IS_EPIPE(s) ((s) == APR_EPIPE) +#define APR_STATUS_IS_EXDEV(s) ((s) == APR_EXDEV) +#define APR_STATUS_IS_ENOTEMPTY(s) ((s) == APR_ENOTEMPTY) +#define APR_STATUS_IS_EAFNOSUPPORT(s) ((s) == APR_EAFNOSUPPORT \ + || (s) == APR_OS_START_SYSERR + WSAEAFNOSUPPORT) +#define APR_STATUS_IS_EOPNOTSUPP(s) ((s) == APR_EOPNOTSUPP \ + || (s) == APR_OS_START_SYSERR + WSAEOPNOTSUPP) +#define APR_STATUS_IS_ERANGE(s) ((s) == APR_ERANGE) + +#else /* !defined(NETWARE) && !defined(OS2) && !defined(WIN32) */ + +/* + * os error codes are clib error codes + */ +#define APR_FROM_OS_ERROR(e) (e) +#define APR_TO_OS_ERROR(e) (e) + +#define apr_get_os_error() (errno) +#define apr_set_os_error(e) (errno = (e)) + +/* A special case, only socket calls require this: + */ +#define apr_get_netos_error() (errno) +#define apr_set_netos_error(e) (errno = (e)) + +/** + * @addtogroup APR_STATUS_IS + * @{ + */ + +/** permission denied */ +#define APR_STATUS_IS_EACCES(s) ((s) == APR_EACCES) +/** file exists */ +#define APR_STATUS_IS_EEXIST(s) ((s) == APR_EEXIST) +/** path name is too long */ +#define APR_STATUS_IS_ENAMETOOLONG(s) ((s) == APR_ENAMETOOLONG) +/** + * no such file or directory + * @remark + * EMVSCATLG can be returned by the automounter on z/OS for + * paths which do not exist. + */ +#ifdef EMVSCATLG +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT \ + || (s) == EMVSCATLG) +#else +#define APR_STATUS_IS_ENOENT(s) ((s) == APR_ENOENT) +#endif +/** not a directory */ +#define APR_STATUS_IS_ENOTDIR(s) ((s) == APR_ENOTDIR) +/** no space left on device */ +#ifdef EDQUOT +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC \ + || (s) == EDQUOT) +#else +#define APR_STATUS_IS_ENOSPC(s) ((s) == APR_ENOSPC) +#endif +/** not enough memory */ +#define APR_STATUS_IS_ENOMEM(s) ((s) == APR_ENOMEM) +/** too many open files */ +#define APR_STATUS_IS_EMFILE(s) ((s) == APR_EMFILE) +/** file table overflow */ +#define APR_STATUS_IS_ENFILE(s) ((s) == APR_ENFILE) +/** bad file # */ +#define APR_STATUS_IS_EBADF(s) ((s) == APR_EBADF) +/** invalid argument */ +#define APR_STATUS_IS_EINVAL(s) ((s) == APR_EINVAL) +/** illegal seek */ +#define APR_STATUS_IS_ESPIPE(s) ((s) == APR_ESPIPE) + +/** operation would block */ +#if !defined(EWOULDBLOCK) || !defined(EAGAIN) +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN) +#elif (EWOULDBLOCK == EAGAIN) +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN) +#else +#define APR_STATUS_IS_EAGAIN(s) ((s) == APR_EAGAIN \ + || (s) == EWOULDBLOCK) +#endif + +/** interrupted system call */ +#define APR_STATUS_IS_EINTR(s) ((s) == APR_EINTR) +/** socket operation on a non-socket */ +#define APR_STATUS_IS_ENOTSOCK(s) ((s) == APR_ENOTSOCK) +/** Connection Refused */ +#define APR_STATUS_IS_ECONNREFUSED(s) ((s) == APR_ECONNREFUSED) +/** operation now in progress */ +#define APR_STATUS_IS_EINPROGRESS(s) ((s) == APR_EINPROGRESS) + +/** + * Software caused connection abort + * @remark + * EPROTO on certain older kernels really means ECONNABORTED, so we need to + * ignore it for them. See discussion in new-httpd archives nh.9701 & nh.9603 + * + * There is potentially a bug in Solaris 2.x x<6, and other boxes that + * implement tcp sockets in userland (i.e. on top of STREAMS). On these + * systems, EPROTO can actually result in a fatal loop. See PR#981 for + * example. It's hard to handle both uses of EPROTO. + */ +#ifdef EPROTO +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED \ + || (s) == EPROTO) +#else +#define APR_STATUS_IS_ECONNABORTED(s) ((s) == APR_ECONNABORTED) +#endif + +/** Connection Reset by peer */ +#define APR_STATUS_IS_ECONNRESET(s) ((s) == APR_ECONNRESET) +/** Operation timed out + * @deprecated */ +#define APR_STATUS_IS_ETIMEDOUT(s) ((s) == APR_ETIMEDOUT) +/** no route to host */ +#define APR_STATUS_IS_EHOSTUNREACH(s) ((s) == APR_EHOSTUNREACH) +/** network is unreachable */ +#define APR_STATUS_IS_ENETUNREACH(s) ((s) == APR_ENETUNREACH) +/** inappropriate file type or format */ +#define APR_STATUS_IS_EFTYPE(s) ((s) == APR_EFTYPE) +/** broken pipe */ +#define APR_STATUS_IS_EPIPE(s) ((s) == APR_EPIPE) +/** cross device link */ +#define APR_STATUS_IS_EXDEV(s) ((s) == APR_EXDEV) +/** Directory Not Empty */ +#define APR_STATUS_IS_ENOTEMPTY(s) ((s) == APR_ENOTEMPTY || \ + (s) == APR_EEXIST) +/** Address Family not supported */ +#define APR_STATUS_IS_EAFNOSUPPORT(s) ((s) == APR_EAFNOSUPPORT) +/** Socket operation not supported */ +#define APR_STATUS_IS_EOPNOTSUPP(s) ((s) == APR_EOPNOTSUPP) + +/** Numeric value not representable */ +#define APR_STATUS_IS_ERANGE(s) ((s) == APR_ERANGE) +/** @} */ + +#endif /* !defined(NETWARE) && !defined(OS2) && !defined(WIN32) */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_ERRNO_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_escape.h b/c/dependencies/windows/apr/x86_debug/include/apr_escape.h new file mode 100644 index 00000000..ed048c95 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_escape.h @@ -0,0 +1,431 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file apr_escape.h + * @brief APR-UTIL Escaping + */ +#ifndef APR_ESCAPE_H +#define APR_ESCAPE_H +#include "apr.h" +#include "apr_general.h" +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Escaping Escape functions + * @ingroup APR + * @{ + */ + +/* Simple escape/unescape functions. + * + * The design goal of these functions are: + * + * - Avoid unnecessary work. + * + * In most cases the strings passed in do not need to be escaped at all. In + * these cases the original string will be returned. + * + * - Lowest possible memory footprint. + * + * The amount of memory allocated for a given encoding is calculated based + * on the exact amount of memory needed, and not the theoretical worst case + * scenario. + * + */ + +/** + * When passing a string to one of the escape functions, this value can be + * passed to indicate a string-valued key, and have the length computed + * automatically. + */ +#define APR_ESCAPE_STRING (-1) + +/** + * Apply LDAP distinguished name escaping as per RFC4514. + */ +#define APR_ESCAPE_LDAP_DN (0x01) + +/** + * Apply LDAP filter escaping as per RFC4515. + */ +#define APR_ESCAPE_LDAP_FILTER (0x02) + +/** + * Apply both RFC4514 and RFC4515 LDAP escaping. + */ +#define APR_ESCAPE_LDAP_ALL (0x03) + +/** + * Perform shell escaping on the provided string. + * + * Shell escaping causes characters to be prefixed with a '\' character. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_shell(char *escaped, const char *str, + apr_ssize_t slen, apr_size_t *len); + +/** + * Perform shell escaping on the provided string, returning the result + * from the pool. + * + * Shell escaping causes characters to be prefixed with a '\' character. + * + * If no characters were escaped, the original string is returned. + * @param p Pool to allocate from + * @param str The original string + * @return the encoded string, allocated from the pool, or the original + * string if no escaping took place or the string was NULL. + */ +APR_DECLARE(const char *) apr_pescape_shell(apr_pool_t *p, const char *str) + __attribute__((nonnull(1))); + +/** + * Unescapes a URL, leaving reserved characters intact. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param url String to be unescaped + * @param slen The length of the original url, or APR_ESCAPE_STRING + * @param forbid Optional list of forbidden characters, in addition to + * 0x00 + * @param reserved Optional list of reserved characters that will be + * left unescaped + * @param plus If non zero, '+' is converted to ' ' as per + * application/x-www-form-urlencoded encoding + * @param len If set, the length of the escaped string will be returned + * @return APR_SUCCESS on success, APR_NOTFOUND if no characters are + * decoded or the string is NULL, APR_EINVAL if a bad escape sequence is + * found, APR_BADCH if a character on the forbid list is found. + */ +APR_DECLARE(apr_status_t) apr_unescape_url(char *escaped, const char *url, + apr_ssize_t slen, const char *forbid, const char *reserved, int plus, + apr_size_t *len); + +/** + * Unescapes a URL, leaving reserved characters intact, returning the + * result from a pool. + * @param p Pool to allocate from + * @param url String to be unescaped in place + * @param forbid Optional list of forbidden characters, in addition to + * 0x00 + * @param reserved Optional list of reserved characters that will be + * left unescaped + * @param plus If non zero, '+' is converted to ' ' as per + * application/x-www-form-urlencoded encoding + * @return A string allocated from the pool on success, the original string + * if no characters are decoded, or NULL if a bad escape sequence is found + * or if a character on the forbid list is found, or if the original string + * was NULL. + */ +APR_DECLARE(const char *) apr_punescape_url(apr_pool_t *p, const char *url, + const char *forbid, const char *reserved, int plus) + __attribute__((nonnull(1))); + +/** + * Escape a path segment, as defined in RFC1808. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_path_segment(char *escaped, + const char *str, apr_ssize_t slen, apr_size_t *len); + +/** + * Escape a path segment, as defined in RFC1808, returning the result from a + * pool. + * @param p Pool to allocate from + * @param str String to be escaped + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or the string is NULL. + */ +APR_DECLARE(const char *) apr_pescape_path_segment(apr_pool_t *p, + const char *str) __attribute__((nonnull(1))); + +/** + * Converts an OS path to a URL, in an OS dependent way, as defined in RFC1808. + * In all cases if a ':' occurs before the first '/' in the URL, the URL should + * be prefixed with "./" (or the ':' escaped). In the case of Unix, this means + * leaving '/' alone, but otherwise doing what escape_path_segment() does. For + * efficiency reasons, we don't use escape_path_segment(), which is provided for + * reference. Again, RFC 1808 is where this stuff is defined. + * + * If partial is set, os_escape_path() assumes that the path will be appended to + * something with a '/' in it (and thus does not prefix "./"). + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param path The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param partial If non zero, suppresses the prepending of "./" + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or if the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_path(char *escaped, const char *path, + apr_ssize_t slen, int partial, apr_size_t *len); + +/** + * Converts an OS path to a URL, in an OS dependent way, as defined in RFC1808, + * returning the result from a pool. + * + * In all cases if a ':' occurs before the first '/' in the URL, the URL should + * be prefixed with "./" (or the ':' escaped). In the case of Unix, this means + * leaving '/' alone, but otherwise doing what escape_path_segment() does. For + * efficiency reasons, we don't use escape_path_segment(), which is provided for + * reference. Again, RFC 1808 is where this stuff is defined. + * + * If partial is set, os_escape_path() assumes that the path will be appended to + * something with a '/' in it (and thus does not prefix "./"). + * @param p Pool to allocate from + * @param str The original string + * @param partial If non zero, suppresses the prepending of "./" + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or if the string was NULL. + */ +APR_DECLARE(const char *) apr_pescape_path(apr_pool_t *p, const char *str, + int partial) __attribute__((nonnull(1))); + +/** + * Urlencode a string, as defined in + * http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or if the stirng was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_urlencoded(char *escaped, const char *str, + apr_ssize_t slen, apr_size_t *len); + +/** + * Urlencode a string, as defined in + * http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1, returning + * the result from a pool. + * @param p Pool to allocate from + * @param str String to be escaped + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or if the string was NULL. + */ +APR_DECLARE(const char *) apr_pescape_urlencoded(apr_pool_t *p, + const char *str) __attribute__((nonnull(1))); + +/** + * Apply entity encoding to a string. Characters are replaced as follows: + * '<' becomes '\<', '>' becomes '\>', '&' becomes '\&', the + * double quote becomes '\"" and the single quote becomes '\''. + * + * If toasc is not zero, any non ascii character will be encoded as + * '%\#ddd;', where ddd is the decimal code of the character. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param toasc If non zero, encode non ascii characters + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_entity(char *escaped, const char *str, + apr_ssize_t slen, int toasc, apr_size_t *len); + +/** + * Apply entity encoding to a string, returning the result from a pool. + * Characters are replaced as follows: '<' becomes '\<', '>' becomes + * '\>', '&' becomes '\&', the double quote becomes '\"" and the + * single quote becomes '\''. + * @param p Pool to allocate from + * @param str The original string + * @param toasc If non zero, encode non ascii characters + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or the string is NULL. + */ +APR_DECLARE(const char *) apr_pescape_entity(apr_pool_t *p, const char *str, + int toasc) __attribute__((nonnull(1))); + +/** + * Decodes html entities or numeric character references in a string. If + * the string to be unescaped is syntactically incorrect, then the + * following fixups will be made: + * unknown entities will be left undecoded; + * references to unused numeric characters will be deleted. + * In particular, � will not be decoded, but will be deleted. + * @param unescaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_unescape_entity(char *unescaped, const char *str, + apr_ssize_t slen, apr_size_t *len); + +/** + * Decodes html entities or numeric character references in a string. If + * the string to be unescaped is syntactically incorrect, then the + * following fixups will be made: + * unknown entities will be left undecoded; + * references to unused numeric characters will be deleted. + * In particular, � will not be decoded, but will be deleted. + * @param p Pool to allocate from + * @param str The original string + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or the string is NULL. + */ +APR_DECLARE(const char *) apr_punescape_entity(apr_pool_t *p, const char *str) + __attribute__((nonnull(1))); + +/** + * Escape control characters in a string, as performed by the shell's + * 'echo' command. Characters are replaced as follows: + * \\a alert (bell), \\b backspace, \\f form feed, \\n new line, \\r carriage + * return, \\t horizontal tab, \\v vertical tab, \\ backslash. + * + * Any non ascii character will be encoded as '\\xHH', where HH is the hex + * code of the character. + * + * If quote is not zero, the double quote character will also be escaped. + * @param escaped Optional buffer to write the encoded string, can be + * NULL + * @param str The original string + * @param slen The length of the original string, or APR_ESCAPE_STRING + * @param quote If non zero, encode double quotes + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if no changes to the string were + * detected or the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_echo(char *escaped, const char *str, + apr_ssize_t slen, int quote, apr_size_t *len); + +/** + * Escape control characters in a string, as performed by the shell's + * 'echo' command, and return the results from a pool. Characters are + * replaced as follows: \\a alert (bell), \\b backspace, \\f form feed, + * \\n new line, \\r carriage return, \\t horizontal tab, \\v vertical tab, + * \\ backslash. + * + * Any non ascii character will be encoded as '\\xHH', where HH is the hex + * code of the character. + * + * If quote is not zero, the double quote character will also be escaped. + * @param p Pool to allocate from + * @param str The original string + * @param quote If non zero, encode double quotes + * @return A string allocated from the pool on success, the original string + * if no characters are encoded or the string is NULL. + */ +APR_DECLARE(const char *) apr_pescape_echo(apr_pool_t *p, const char *str, + int quote); + +/** + * Convert binary data to a hex encoding. + * @param dest The destination buffer, can be NULL + * @param src The original buffer + * @param srclen The length of the original buffer + * @param colon If not zero, insert colon characters between hex digits. + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_hex(char *dest, const void *src, + apr_size_t srclen, int colon, apr_size_t *len); + +/** + * Convert binary data to a hex encoding, and return the results from a + * pool. + * @param p Pool to allocate from + * @param src The original buffer + * @param slen The length of the original buffer + * @param colon If not zero, insert colon characters between hex digits. + * @return A zero padded buffer allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *) apr_pescape_hex(apr_pool_t *p, const void *src, + apr_size_t slen, int colon) __attribute__((nonnull(1))); + +/** + * Convert hex encoded string to binary data. + * @param dest The destination buffer, can be NULL + * @param str The original buffer + * @param slen The length of the original buffer + * @param colon If not zero, ignore colon characters between hex digits. + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL, or APR_BADCH + * if a non hex character is present. + */ +APR_DECLARE(apr_status_t) apr_unescape_hex(void *dest, const char *str, + apr_ssize_t slen, int colon, apr_size_t *len); + +/** + * Convert hex encoding to binary data, and return the results from a pool. + * If the colon character appears between pairs of hex digits, it will be + * ignored. + * @param p Pool to allocate from + * @param str The original string + * @param colon If not zero, ignore colon characters between hex digits. + * @param len If present, returns the length of the final buffer + * @return A buffer allocated from the pool on success, or NULL if src was + * NULL, or a bad character was present. + */ +APR_DECLARE(const void *) apr_punescape_hex(apr_pool_t *p, const char *str, + int colon, apr_size_t *len); + +/** + * Apply LDAP escaping to binary data. Characters from RFC4514 and RFC4515 + * are escaped with their hex equivalents. + * @param dest The destination buffer, can be NULL + * @param src The original buffer + * @param srclen The length of the original buffer + * @param flags APR_ESCAPE_LDAP_DN for RFC4514, APR_ESCAPE_LDAP_FILTER for + * RFC4515, APR_ESCAPE_LDAP_ALL for both + * @param len If present, returns the length of the string + * @return APR_SUCCESS, or APR_NOTFOUND if the string was NULL + */ +APR_DECLARE(apr_status_t) apr_escape_ldap(char *dest, const void *src, + apr_ssize_t srclen, int flags, apr_size_t *len); + +/** + * Apply LDAP escaping to binary data, and return the results from a + * pool. Characters from RFC4514 and RFC4515 are escaped with their hex + * equivalents. + * @param p Pool to allocate from + * @param src The original buffer + * @param slen The length of the original buffer + * @param flags APR_ESCAPE_LDAP_DN for RFC4514, APR_ESCAPE_LDAP_FILTER for + * RFC4515, APR_ESCAPE_LDAP_ALL for both + * @return A zero padded buffer allocated from the pool on success, or + * NULL if src was NULL. + */ +APR_DECLARE(const char *) apr_pescape_ldap(apr_pool_t *p, const void *src, + apr_ssize_t slen, int flags) __attribute__((nonnull(1))); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ESCAPE_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_escape_test_char.h b/c/dependencies/windows/apr/x86_debug/include/apr_escape_test_char.h new file mode 100644 index 00000000..ad36c615 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_escape_test_char.h @@ -0,0 +1,25 @@ +/* this file is automatically generated by gen_test_char, do not edit. "make include/private/apr_escape_test_char.h" to regenerate. */ +#define T_ESCAPE_SHELL_CMD (1) +#define T_ESCAPE_PATH_SEGMENT (2) +#define T_OS_ESCAPE_PATH (4) +#define T_ESCAPE_ECHO (8) +#define T_ESCAPE_URLENCODED (16) +#define T_ESCAPE_XML (32) +#define T_ESCAPE_LDAP_DN (64) +#define T_ESCAPE_LDAP_FILTER (128) + +static const unsigned char test_char_table[256] = { + 224,222,222,222,222,222,222,222,222,222,223,222,222,223,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,6,16,127,22,17,23,49,17, + 145,145,129,80,80,0,0,18,0,0,0,0,0,0,0,0,0,0,16,87, + 119,16,119,23,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,23,223,23,23,0,23,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,23,23,23,17,222,222,222,222,222,222,222,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222, + 222,222,222,222,222,222,222,222,222,222,222,222,222,222,222,222 +}; diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_file_info.h b/c/dependencies/windows/apr/x86_debug/include/apr_file_info.h new file mode 100644 index 00000000..cfddc68d --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_file_info.h @@ -0,0 +1,428 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_FILE_INFO_H +#define APR_FILE_INFO_H + +/** + * @file apr_file_info.h + * @brief APR File Information + */ + +#include "apr.h" +#include "apr_user.h" +#include "apr_pools.h" +#include "apr_tables.h" +#include "apr_time.h" +#include "apr_errno.h" + +#if APR_HAVE_SYS_UIO_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_file_info File Information + * @ingroup APR + * @{ + */ + +/* Many applications use the type member to determine the + * existance of a file or initialization of the file info, + * so the APR_NOFILE value must be distinct from APR_UNKFILE. + */ + +/** apr_filetype_e values for the filetype member of the + * apr_file_info_t structure + * @warning Not all of the filetypes below can be determined. + * For example, a given platform might not correctly report + * a socket descriptor as APR_SOCK if that type isn't + * well-identified on that platform. In such cases where + * a filetype exists but cannot be described by the recognized + * flags below, the filetype will be APR_UNKFILE. If the + * filetype member is not determined, the type will be APR_NOFILE. + */ + +typedef enum { + APR_NOFILE = 0, /**< no file type determined */ + APR_REG, /**< a regular file */ + APR_DIR, /**< a directory */ + APR_CHR, /**< a character device */ + APR_BLK, /**< a block device */ + APR_PIPE, /**< a FIFO / pipe */ + APR_LNK, /**< a symbolic link */ + APR_SOCK, /**< a [unix domain] socket */ + APR_UNKFILE = 127 /**< a file of some other unknown type */ +} apr_filetype_e; + +/** + * @defgroup apr_file_permissions File Permissions flags + * @{ + */ + +#define APR_FPROT_USETID 0x8000 /**< Set user id */ +#define APR_FPROT_UREAD 0x0400 /**< Read by user */ +#define APR_FPROT_UWRITE 0x0200 /**< Write by user */ +#define APR_FPROT_UEXECUTE 0x0100 /**< Execute by user */ + +#define APR_FPROT_GSETID 0x4000 /**< Set group id */ +#define APR_FPROT_GREAD 0x0040 /**< Read by group */ +#define APR_FPROT_GWRITE 0x0020 /**< Write by group */ +#define APR_FPROT_GEXECUTE 0x0010 /**< Execute by group */ + +#define APR_FPROT_WSTICKY 0x2000 /**< Sticky bit */ +#define APR_FPROT_WREAD 0x0004 /**< Read by others */ +#define APR_FPROT_WWRITE 0x0002 /**< Write by others */ +#define APR_FPROT_WEXECUTE 0x0001 /**< Execute by others */ + +#define APR_FPROT_OS_DEFAULT 0x0FFF /**< use OS's default permissions */ + +/* additional permission flags for apr_file_copy and apr_file_append */ +#define APR_FPROT_FILE_SOURCE_PERMS 0x1000 /**< Copy source file's permissions */ + +/* backcompat */ +#define APR_USETID APR_FPROT_USETID /**< @deprecated @see APR_FPROT_USETID */ +#define APR_UREAD APR_FPROT_UREAD /**< @deprecated @see APR_FPROT_UREAD */ +#define APR_UWRITE APR_FPROT_UWRITE /**< @deprecated @see APR_FPROT_UWRITE */ +#define APR_UEXECUTE APR_FPROT_UEXECUTE /**< @deprecated @see APR_FPROT_UEXECUTE */ +#define APR_GSETID APR_FPROT_GSETID /**< @deprecated @see APR_FPROT_GSETID */ +#define APR_GREAD APR_FPROT_GREAD /**< @deprecated @see APR_FPROT_GREAD */ +#define APR_GWRITE APR_FPROT_GWRITE /**< @deprecated @see APR_FPROT_GWRITE */ +#define APR_GEXECUTE APR_FPROT_GEXECUTE /**< @deprecated @see APR_FPROT_GEXECUTE */ +#define APR_WSTICKY APR_FPROT_WSTICKY /**< @deprecated @see APR_FPROT_WSTICKY */ +#define APR_WREAD APR_FPROT_WREAD /**< @deprecated @see APR_FPROT_WREAD */ +#define APR_WWRITE APR_FPROT_WWRITE /**< @deprecated @see APR_FPROT_WWRITE */ +#define APR_WEXECUTE APR_FPROT_WEXECUTE /**< @deprecated @see APR_FPROT_WEXECUTE */ +#define APR_OS_DEFAULT APR_FPROT_OS_DEFAULT /**< @deprecated @see APR_FPROT_OS_DEFAULT */ +#define APR_FILE_SOURCE_PERMS APR_FPROT_FILE_SOURCE_PERMS /**< @deprecated @see APR_FPROT_FILE_SOURCE_PERMS */ + +/** @} */ + + +/** + * Structure for referencing directories. + */ +typedef struct apr_dir_t apr_dir_t; +/** + * Structure for determining file permissions. + */ +typedef apr_int32_t apr_fileperms_t; +#if (defined WIN32) || (defined NETWARE) +/** + * Structure for determining the device the file is on. + */ +typedef apr_uint32_t apr_dev_t; +#else +/** + * Structure for determining the device the file is on. + */ +typedef dev_t apr_dev_t; +#endif + +/** + * @defgroup apr_file_stat Stat Functions + * @{ + */ +/** file info structure */ +typedef struct apr_finfo_t apr_finfo_t; + +#define APR_FINFO_LINK 0x00000001 /**< Stat the link not the file itself if it is a link */ +#define APR_FINFO_MTIME 0x00000010 /**< Modification Time */ +#define APR_FINFO_CTIME 0x00000020 /**< Creation or inode-changed time */ +#define APR_FINFO_ATIME 0x00000040 /**< Access Time */ +#define APR_FINFO_SIZE 0x00000100 /**< Size of the file */ +#define APR_FINFO_CSIZE 0x00000200 /**< Storage size consumed by the file */ +#define APR_FINFO_DEV 0x00001000 /**< Device */ +#define APR_FINFO_INODE 0x00002000 /**< Inode */ +#define APR_FINFO_NLINK 0x00004000 /**< Number of links */ +#define APR_FINFO_TYPE 0x00008000 /**< Type */ +#define APR_FINFO_USER 0x00010000 /**< User */ +#define APR_FINFO_GROUP 0x00020000 /**< Group */ +#define APR_FINFO_UPROT 0x00100000 /**< User protection bits */ +#define APR_FINFO_GPROT 0x00200000 /**< Group protection bits */ +#define APR_FINFO_WPROT 0x00400000 /**< World protection bits */ +#define APR_FINFO_ICASE 0x01000000 /**< if dev is case insensitive */ +#define APR_FINFO_NAME 0x02000000 /**< ->name in proper case */ + +#define APR_FINFO_MIN 0x00008170 /**< type, mtime, ctime, atime, size */ +#define APR_FINFO_IDENT 0x00003000 /**< dev and inode */ +#define APR_FINFO_OWNER 0x00030000 /**< user and group */ +#define APR_FINFO_PROT 0x00700000 /**< all protections */ +#define APR_FINFO_NORM 0x0073b170 /**< an atomic unix apr_stat() */ +#define APR_FINFO_DIRENT 0x02000000 /**< an atomic unix apr_dir_read() */ + +/** + * The file information structure. This is analogous to the POSIX + * stat structure. + */ +struct apr_finfo_t { + /** Allocates memory and closes lingering handles in the specified pool */ + apr_pool_t *pool; + /** The bitmask describing valid fields of this apr_finfo_t structure + * including all available 'wanted' fields and potentially more */ + apr_int32_t valid; + /** The access permissions of the file. Mimics Unix access rights. */ + apr_fileperms_t protection; + /** The type of file. One of APR_REG, APR_DIR, APR_CHR, APR_BLK, APR_PIPE, + * APR_LNK or APR_SOCK. If the type is undetermined, the value is APR_NOFILE. + * If the type cannot be determined, the value is APR_UNKFILE. + */ + apr_filetype_e filetype; + /** The user id that owns the file */ + apr_uid_t user; + /** The group id that owns the file */ + apr_gid_t group; + /** The inode of the file. */ + apr_ino_t inode; + /** The id of the device the file is on. */ + apr_dev_t device; + /** The number of hard links to the file. */ + apr_int32_t nlink; + /** The size of the file */ + apr_off_t size; + /** The storage size consumed by the file */ + apr_off_t csize; + /** The time the file was last accessed */ + apr_time_t atime; + /** The time the file was last modified */ + apr_time_t mtime; + /** The time the file was created, or the inode was last changed */ + apr_time_t ctime; + /** The pathname of the file (possibly unrooted) */ + const char *fname; + /** The file's name (no path) in filesystem case */ + const char *name; + /** Unused */ + struct apr_file_t *filehand; +}; + +/** + * get the specified file's stats. The file is specified by filename, + * instead of using a pre-opened file. + * @param finfo Where to store the information about the file, which is + * never touched if the call fails. + * @param fname The name of the file to stat. + * @param wanted The desired apr_finfo_t fields, as a bit flag of APR_FINFO_ + values + * @param pool the pool to use to allocate the new file. + * + * @note If @c APR_INCOMPLETE is returned all the fields in @a finfo may + * not be filled in, and you need to check the @c finfo->valid bitmask + * to verify that what you're looking for is there. + */ +APR_DECLARE(apr_status_t) apr_stat(apr_finfo_t *finfo, const char *fname, + apr_int32_t wanted, apr_pool_t *pool); + +/** @} */ +/** + * @defgroup apr_dir Directory Manipulation Functions + * @{ + */ + +/** + * Open the specified directory. + * @param new_dir The opened directory descriptor. + * @param dirname The full path to the directory (use / on all systems) + * @param pool The pool to use. + */ +APR_DECLARE(apr_status_t) apr_dir_open(apr_dir_t **new_dir, + const char *dirname, + apr_pool_t *pool); + +/** + * close the specified directory. + * @param thedir the directory descriptor to close. + */ +APR_DECLARE(apr_status_t) apr_dir_close(apr_dir_t *thedir); + +/** + * Read the next entry from the specified directory. + * @param finfo the file info structure and filled in by apr_dir_read + * @param wanted The desired apr_finfo_t fields, as a bit flag of APR_FINFO_ + values + * @param thedir the directory descriptor returned from apr_dir_open + * @remark No ordering is guaranteed for the entries read. + * + * @note If @c APR_INCOMPLETE is returned all the fields in @a finfo may + * not be filled in, and you need to check the @c finfo->valid bitmask + * to verify that what you're looking for is there. When no more + * entries are available, APR_ENOENT is returned. + */ +APR_DECLARE(apr_status_t) apr_dir_read(apr_finfo_t *finfo, apr_int32_t wanted, + apr_dir_t *thedir); + +/** + * Rewind the directory to the first entry. + * @param thedir the directory descriptor to rewind. + */ +APR_DECLARE(apr_status_t) apr_dir_rewind(apr_dir_t *thedir); +/** @} */ + +/** + * @defgroup apr_filepath Filepath Manipulation Functions + * @{ + */ + +/** Cause apr_filepath_merge to fail if addpath is above rootpath + * @bug in APR 0.9 and 1.x, this flag's behavior is undefined + * if the rootpath is NULL or empty. In APR 2.0 this should be + * changed to imply NOTABSOLUTE if the rootpath is NULL or empty. + */ +#define APR_FILEPATH_NOTABOVEROOT 0x01 + +/** internal: Only meaningful with APR_FILEPATH_NOTABOVEROOT */ +#define APR_FILEPATH_SECUREROOTTEST 0x02 + +/** Cause apr_filepath_merge to fail if addpath is above rootpath, + * even given a rootpath /foo/bar and an addpath ../bar/bash + */ +#define APR_FILEPATH_SECUREROOT 0x03 + +/** Fail apr_filepath_merge if the merged path is relative */ +#define APR_FILEPATH_NOTRELATIVE 0x04 + +/** Fail apr_filepath_merge if the merged path is absolute */ +#define APR_FILEPATH_NOTABSOLUTE 0x08 + +/** Return the file system's native path format (e.g. path delimiters + * of ':' on MacOS9, '\' on Win32, etc.) */ +#define APR_FILEPATH_NATIVE 0x10 + +/** Resolve the true case of existing directories and file elements + * of addpath, (resolving any aliases on Win32) and append a proper + * trailing slash if a directory + */ +#define APR_FILEPATH_TRUENAME 0x20 + +/** + * Extract the rootpath from the given filepath + * @param rootpath the root file path returned with APR_SUCCESS or APR_EINCOMPLETE + * @param filepath the pathname to parse for its root component + * @param flags the desired rules to apply, from + *
+ *      APR_FILEPATH_NATIVE    Use native path separators (e.g. '\' on Win32)
+ *      APR_FILEPATH_TRUENAME  Tests that the root exists, and makes it proper
+ * 
+ * @param p the pool to allocate the new path string from + * @remark on return, filepath points to the first non-root character in the + * given filepath. In the simplest example, given a filepath of "/foo", + * returns the rootpath of "/" and filepath points at "foo". This is far + * more complex on other platforms, which will canonicalize the root form + * to a consistant format, given the APR_FILEPATH_TRUENAME flag, and also + * test for the validity of that root (e.g., that a drive d:/ or network + * share //machine/foovol/). + * The function returns APR_ERELATIVE if filepath isn't rooted (an + * error), APR_EINCOMPLETE if the root path is ambiguous (but potentially + * legitimate, e.g. "/" on Windows is incomplete because it doesn't specify + * the drive letter), or APR_EBADPATH if the root is simply invalid. + * APR_SUCCESS is returned if filepath is an absolute path. + */ +APR_DECLARE(apr_status_t) apr_filepath_root(const char **rootpath, + const char **filepath, + apr_int32_t flags, + apr_pool_t *p); + +/** + * Merge additional file path onto the previously processed rootpath + * @param newpath the merged paths returned + * @param rootpath the root file path (NULL uses the current working path) + * @param addpath the path to add to the root path + * @param flags the desired APR_FILEPATH_ rules to apply when merging + * @param p the pool to allocate the new path string from + * @remark if the flag APR_FILEPATH_TRUENAME is given, and the addpath + * contains wildcard characters ('*', '?') on platforms that don't support + * such characters within filenames, the paths will be merged, but the + * result code will be APR_EPATHWILD, and all further segments will not + * reflect the true filenames including the wildcard and following segments. + */ +APR_DECLARE(apr_status_t) apr_filepath_merge(char **newpath, + const char *rootpath, + const char *addpath, + apr_int32_t flags, + apr_pool_t *p); + +/** + * Split a search path into separate components + * @param pathelts the returned components of the search path + * @param liststr the search path (e.g., getenv("PATH")) + * @param p the pool to allocate the array and path components from + * @remark empty path components do not become part of @a pathelts. + * @remark the path separator in @a liststr is system specific; + * e.g., ':' on Unix, ';' on Windows, etc. + */ +APR_DECLARE(apr_status_t) apr_filepath_list_split(apr_array_header_t **pathelts, + const char *liststr, + apr_pool_t *p); + +/** + * Merge a list of search path components into a single search path + * @param liststr the returned search path; may be NULL if @a pathelts is empty + * @param pathelts the components of the search path + * @param p the pool to allocate the search path from + * @remark emtpy strings in the source array are ignored. + * @remark the path separator in @a liststr is system specific; + * e.g., ':' on Unix, ';' on Windows, etc. + */ +APR_DECLARE(apr_status_t) apr_filepath_list_merge(char **liststr, + apr_array_header_t *pathelts, + apr_pool_t *p); + +/** + * Return the default file path (for relative file names) + * @param path the default path string returned + * @param flags optional flag APR_FILEPATH_NATIVE to retrieve the + * default file path in os-native format. + * @param p the pool to allocate the default path string from + */ +APR_DECLARE(apr_status_t) apr_filepath_get(char **path, apr_int32_t flags, + apr_pool_t *p); + +/** + * Set the default file path (for relative file names) + * @param path the default path returned + * @param p the pool to allocate any working storage + */ +APR_DECLARE(apr_status_t) apr_filepath_set(const char *path, apr_pool_t *p); + +/** The FilePath character encoding is unknown */ +#define APR_FILEPATH_ENCODING_UNKNOWN 0 + +/** The FilePath character encoding is locale-dependent */ +#define APR_FILEPATH_ENCODING_LOCALE 1 + +/** The FilePath character encoding is UTF-8 */ +#define APR_FILEPATH_ENCODING_UTF8 2 + +/** + * Determine the encoding used internally by the FilePath functions + * @param style points to a variable which receives the encoding style flag + * @param p the pool to allocate any working storage + * @remark Use apr_os_locale_encoding() and/or apr_os_default_encoding() + * to get the name of the path encoding if it's not UTF-8. + */ +APR_DECLARE(apr_status_t) apr_filepath_encoding(int *style, apr_pool_t *p); +/** @} */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_FILE_INFO_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_file_io.h b/c/dependencies/windows/apr/x86_debug/include/apr_file_io.h new file mode 100644 index 00000000..af931939 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_file_io.h @@ -0,0 +1,1005 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_FILE_IO_H +#define APR_FILE_IO_H + +/** + * @file apr_file_io.h + * @brief APR File I/O Handling + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_time.h" +#include "apr_errno.h" +#include "apr_file_info.h" +#include "apr_inherit.h" + +#define APR_WANT_STDIO /**< for SEEK_* */ +#define APR_WANT_IOVEC /**< for apr_file_writev */ +#include "apr_want.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_file_io File I/O Handling Functions + * @ingroup APR + * @{ + */ + +/** + * @defgroup apr_file_open_flags File Open Flags/Routines + * @{ + */ + +/* Note to implementors: Values in the range 0x00100000--0x80000000 + are reserved for platform-specific values. */ + +#define APR_FOPEN_READ 0x00001 /**< Open the file for reading */ +#define APR_FOPEN_WRITE 0x00002 /**< Open the file for writing */ +#define APR_FOPEN_CREATE 0x00004 /**< Create the file if not there */ +#define APR_FOPEN_APPEND 0x00008 /**< Append to the end of the file */ +#define APR_FOPEN_TRUNCATE 0x00010 /**< Open the file and truncate + to 0 length */ +#define APR_FOPEN_BINARY 0x00020 /**< Open the file in binary mode + (This flag is ignored on UNIX + because it has no meaning)*/ +#define APR_FOPEN_EXCL 0x00040 /**< Open should fail if #APR_FOPEN_CREATE + and file exists. */ +#define APR_FOPEN_BUFFERED 0x00080 /**< Open the file for buffered I/O */ +#define APR_FOPEN_DELONCLOSE 0x00100 /**< Delete the file after close */ +#define APR_FOPEN_XTHREAD 0x00200 /**< Platform dependent tag to open + the file for use across multiple + threads */ +#define APR_FOPEN_SHARELOCK 0x00400 /**< Platform dependent support for + higher level locked read/write + access to support writes across + process/machines */ +#define APR_FOPEN_NOCLEANUP 0x00800 /**< Do not register a cleanup + when the file is opened. The + apr_os_file_t handle in apr_file_t + will not be closed when the pool + is destroyed. */ +#define APR_FOPEN_SENDFILE_ENABLED 0x01000 /**< Advisory flag that this + file should support + apr_socket_sendfile operation */ +#define APR_FOPEN_LARGEFILE 0x04000 /**< Platform dependent flag to enable + * large file support, see WARNING below + */ +#define APR_FOPEN_SPARSE 0x08000 /**< Platform dependent flag to enable + * sparse file support, see WARNING below + */ +#define APR_FOPEN_NONBLOCK 0x40000 /**< Platform dependent flag to enable + * non blocking file io */ + + +/* backcompat */ +#define APR_READ APR_FOPEN_READ /**< @deprecated @see APR_FOPEN_READ */ +#define APR_WRITE APR_FOPEN_WRITE /**< @deprecated @see APR_FOPEN_WRITE */ +#define APR_CREATE APR_FOPEN_CREATE /**< @deprecated @see APR_FOPEN_CREATE */ +#define APR_APPEND APR_FOPEN_APPEND /**< @deprecated @see APR_FOPEN_APPEND */ +#define APR_TRUNCATE APR_FOPEN_TRUNCATE /**< @deprecated @see APR_FOPEN_TRUNCATE */ +#define APR_BINARY APR_FOPEN_BINARY /**< @deprecated @see APR_FOPEN_BINARY */ +#define APR_EXCL APR_FOPEN_EXCL /**< @deprecated @see APR_FOPEN_EXCL */ +#define APR_BUFFERED APR_FOPEN_BUFFERED /**< @deprecated @see APR_FOPEN_BUFFERED */ +#define APR_DELONCLOSE APR_FOPEN_DELONCLOSE /**< @deprecated @see APR_FOPEN_DELONCLOSE */ +#define APR_XTHREAD APR_FOPEN_XTHREAD /**< @deprecated @see APR_FOPEN_XTHREAD */ +#define APR_SHARELOCK APR_FOPEN_SHARELOCK /**< @deprecated @see APR_FOPEN_SHARELOCK */ +#define APR_FILE_NOCLEANUP APR_FOPEN_NOCLEANUP /**< @deprecated @see APR_FOPEN_NOCLEANUP */ +#define APR_SENDFILE_ENABLED APR_FOPEN_SENDFILE_ENABLED /**< @deprecated @see APR_FOPEN_SENDFILE_ENABLED */ +#define APR_LARGEFILE APR_FOPEN_LARGEFILE /**< @deprecated @see APR_FOPEN_LARGEFILE */ + +/** @def APR_FOPEN_LARGEFILE + * @warning APR_FOPEN_LARGEFILE flag only has effect on some + * platforms where sizeof(apr_off_t) == 4. Where implemented, it + * allows opening and writing to a file which exceeds the size which + * can be represented by apr_off_t (2 gigabytes). When a file's size + * does exceed 2Gb, apr_file_info_get() will fail with an error on the + * descriptor, likewise apr_stat()/apr_lstat() will fail on the + * filename. apr_dir_read() will fail with #APR_INCOMPLETE on a + * directory entry for a large file depending on the particular + * APR_FINFO_* flags. Generally, it is not recommended to use this + * flag. + * + * @def APR_FOPEN_SPARSE + * @warning APR_FOPEN_SPARSE may, depending on platform, convert a + * normal file to a sparse file. Some applications may be unable + * to decipher a sparse file, so it's critical that the sparse file + * flag should only be used for files accessed only by APR or other + * applications known to be able to decipher them. APR does not + * guarantee that it will compress the file into sparse segments + * if it was previously created and written without the sparse flag. + * On platforms which do not understand, or on file systems which + * cannot handle sparse files, the flag is ignored by apr_file_open(). + * + * @def APR_FOPEN_NONBLOCK + * @warning APR_FOPEN_NONBLOCK is not implemented on all platforms. + * Callers should be prepared for it to fail with #APR_ENOTIMPL. + */ + +/** @} */ + +/** + * @defgroup apr_file_seek_flags File Seek Flags + * @{ + */ + +/* flags for apr_file_seek */ +/** Set the file position */ +#define APR_SET SEEK_SET +/** Current */ +#define APR_CUR SEEK_CUR +/** Go to end of file */ +#define APR_END SEEK_END +/** @} */ + +/** + * @defgroup apr_file_attrs_set_flags File Attribute Flags + * @{ + */ + +/* flags for apr_file_attrs_set */ +#define APR_FILE_ATTR_READONLY 0x01 /**< File is read-only */ +#define APR_FILE_ATTR_EXECUTABLE 0x02 /**< File is executable */ +#define APR_FILE_ATTR_HIDDEN 0x04 /**< File is hidden */ +/** @} */ + +/** + * @defgroup apr_file_writev{_full} max iovec size + * @{ + */ +#if defined(DOXYGEN) +#define APR_MAX_IOVEC_SIZE 1024 /**< System dependent maximum + size of an iovec array */ +#elif defined(IOV_MAX) +#define APR_MAX_IOVEC_SIZE IOV_MAX +#elif defined(MAX_IOVEC) +#define APR_MAX_IOVEC_SIZE MAX_IOVEC +#else +#define APR_MAX_IOVEC_SIZE 1024 +#endif +/** @} */ + +/** File attributes */ +typedef apr_uint32_t apr_fileattrs_t; + +/** Type to pass as whence argument to apr_file_seek. */ +typedef int apr_seek_where_t; + +/** + * Structure for referencing files. + */ +typedef struct apr_file_t apr_file_t; + +/* File lock types/flags */ +/** + * @defgroup apr_file_lock_types File Lock Types + * @{ + */ + +#define APR_FLOCK_SHARED 1 /**< Shared lock. More than one process + or thread can hold a shared lock + at any given time. Essentially, + this is a "read lock", preventing + writers from establishing an + exclusive lock. */ +#define APR_FLOCK_EXCLUSIVE 2 /**< Exclusive lock. Only one process + may hold an exclusive lock at any + given time. This is analogous to + a "write lock". */ + +#define APR_FLOCK_TYPEMASK 0x000F /**< mask to extract lock type */ +#define APR_FLOCK_NONBLOCK 0x0010 /**< do not block while acquiring the + file lock */ +/** @} */ + +/** + * Open the specified file. + * @param newf The opened file descriptor. + * @param fname The full path to the file (using / on all systems) + * @param flag Or'ed value of: + * @li #APR_FOPEN_READ open for reading + * @li #APR_FOPEN_WRITE open for writing + * @li #APR_FOPEN_CREATE create the file if not there + * @li #APR_FOPEN_APPEND file ptr is set to end prior to all writes + * @li #APR_FOPEN_TRUNCATE set length to zero if file exists + * @li #APR_FOPEN_BINARY not a text file + * @li #APR_FOPEN_BUFFERED buffer the data. Default is non-buffered + * @li #APR_FOPEN_EXCL return error if #APR_FOPEN_CREATE and file exists + * @li #APR_FOPEN_DELONCLOSE delete the file after closing + * @li #APR_FOPEN_XTHREAD Platform dependent tag to open the file + * for use across multiple threads + * @li #APR_FOPEN_SHARELOCK Platform dependent support for higher + * level locked read/write access to support + * writes across process/machines + * @li #APR_FOPEN_NOCLEANUP Do not register a cleanup with the pool + * passed in on the @a pool argument (see below) + * @li #APR_FOPEN_SENDFILE_ENABLED Open with appropriate platform semantics + * for sendfile operations. Advisory only, + * apr_socket_sendfile does not check this flag + * @li #APR_FOPEN_LARGEFILE Platform dependent flag to enable large file + * support, see WARNING below + * @li #APR_FOPEN_SPARSE Platform dependent flag to enable sparse file + * support, see WARNING below + * @li #APR_FOPEN_NONBLOCK Platform dependent flag to enable + * non blocking file io + * @param perm Access permissions for file. + * @param pool The pool to use. + * @remark If perm is #APR_FPROT_OS_DEFAULT and the file is being created, + * appropriate default permissions will be used. + * @remark By default, the returned file descriptor will not be + * inherited by child processes created by apr_proc_create(). This + * can be changed using apr_file_inherit_set(). + */ +APR_DECLARE(apr_status_t) apr_file_open(apr_file_t **newf, const char *fname, + apr_int32_t flag, apr_fileperms_t perm, + apr_pool_t *pool); + +/** + * Close the specified file. + * @param file The file descriptor to close. + */ +APR_DECLARE(apr_status_t) apr_file_close(apr_file_t *file); + +/** + * Delete the specified file. + * @param path The full path to the file (using / on all systems) + * @param pool The pool to use. + * @remark If the file is open, it won't be removed until all + * instances are closed. + */ +APR_DECLARE(apr_status_t) apr_file_remove(const char *path, apr_pool_t *pool); + +/** + * Rename the specified file. + * @param from_path The full path to the original file (using / on all systems) + * @param to_path The full path to the new file (using / on all systems) + * @param pool The pool to use. + * @warning If a file exists at the new location, then it will be + * overwritten. Moving files or directories across devices may not be + * possible. + */ +APR_DECLARE(apr_status_t) apr_file_rename(const char *from_path, + const char *to_path, + apr_pool_t *pool); + +/** + * Create a hard link to the specified file. + * @param from_path The full path to the original file (using / on all systems) + * @param to_path The full path to the new file (using / on all systems) + * @remark Both files must reside on the same device. + */ +APR_DECLARE(apr_status_t) apr_file_link(const char *from_path, + const char *to_path); + +/** + * Copy the specified file to another file. + * @param from_path The full path to the original file (using / on all systems) + * @param to_path The full path to the new file (using / on all systems) + * @param perms Access permissions for the new file if it is created. + * In place of the usual or'd combination of file permissions, the + * value #APR_FPROT_FILE_SOURCE_PERMS may be given, in which case the source + * file's permissions are copied. + * @param pool The pool to use. + * @remark The new file does not need to exist, it will be created if required. + * @warning If the new file already exists, its contents will be overwritten. + */ +APR_DECLARE(apr_status_t) apr_file_copy(const char *from_path, + const char *to_path, + apr_fileperms_t perms, + apr_pool_t *pool); + +/** + * Append the specified file to another file. + * @param from_path The full path to the source file (use / on all systems) + * @param to_path The full path to the destination file (use / on all systems) + * @param perms Access permissions for the destination file if it is created. + * In place of the usual or'd combination of file permissions, the + * value #APR_FPROT_FILE_SOURCE_PERMS may be given, in which case the source + * file's permissions are copied. + * @param pool The pool to use. + * @remark The new file does not need to exist, it will be created if required. + * @remark Note that advanced filesystem permissions such as ACLs are not + * duplicated by this API. The target permissions (including duplicating the + * source file permissions) are assigned only when the target file does not yet + * exist. + */ +APR_DECLARE(apr_status_t) apr_file_append(const char *from_path, + const char *to_path, + apr_fileperms_t perms, + apr_pool_t *pool); + +/** + * Are we at the end of the file + * @param fptr The apr file we are testing. + * @remark Returns #APR_EOF if we are at the end of file, #APR_SUCCESS otherwise. + */ +APR_DECLARE(apr_status_t) apr_file_eof(apr_file_t *fptr); + +/** + * Open standard error as an apr file pointer. + * @param thefile The apr file to use as stderr. + * @param pool The pool to allocate the file out of. + * + * @remark The only reason that the apr_file_open_std* functions exist + * is that you may not always have a stderr/out/in on Windows. This + * is generally a problem with newer versions of Windows and services. + * + * @remark The other problem is that the C library functions generally work + * differently on Windows and Unix. So, by using apr_file_open_std* + * functions, you can get a handle to an APR struct that works with + * the APR functions which are supposed to work identically on all + * platforms. + */ +APR_DECLARE(apr_status_t) apr_file_open_stderr(apr_file_t **thefile, + apr_pool_t *pool); + +/** + * open standard output as an apr file pointer. + * @param thefile The apr file to use as stdout. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_stdout(apr_file_t **thefile, + apr_pool_t *pool); + +/** + * open standard input as an apr file pointer. + * @param thefile The apr file to use as stdin. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_stdin(apr_file_t **thefile, + apr_pool_t *pool); + +/** + * open standard error as an apr file pointer, with flags. + * @param thefile The apr file to use as stderr. + * @param flags The flags to open the file with. Only the + * @li #APR_FOPEN_EXCL + * @li #APR_FOPEN_BUFFERED + * @li #APR_FOPEN_XTHREAD + * @li #APR_FOPEN_SHARELOCK + * @li #APR_FOPEN_SENDFILE_ENABLED + * @li #APR_FOPEN_LARGEFILE + * + * flags should be used. The #APR_FOPEN_WRITE flag will + * be set unconditionally. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_flags_stderr(apr_file_t **thefile, + apr_int32_t flags, + apr_pool_t *pool); + +/** + * open standard output as an apr file pointer, with flags. + * @param thefile The apr file to use as stdout. + * @param flags The flags to open the file with. Only the + * @li #APR_FOPEN_EXCL + * @li #APR_FOPEN_BUFFERED + * @li #APR_FOPEN_XTHREAD + * @li #APR_FOPEN_SHARELOCK + * @li #APR_FOPEN_SENDFILE_ENABLED + * @li #APR_FOPEN_LARGEFILE + * + * flags should be used. The #APR_FOPEN_WRITE flag will + * be set unconditionally. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_flags_stdout(apr_file_t **thefile, + apr_int32_t flags, + apr_pool_t *pool); + +/** + * open standard input as an apr file pointer, with flags. + * @param thefile The apr file to use as stdin. + * @param flags The flags to open the file with. Only the + * @li #APR_FOPEN_EXCL + * @li #APR_FOPEN_BUFFERED + * @li #APR_FOPEN_XTHREAD + * @li #APR_FOPEN_SHARELOCK + * @li #APR_FOPEN_SENDFILE_ENABLED + * @li #APR_FOPEN_LARGEFILE + * + * flags should be used. The #APR_FOPEN_WRITE flag will + * be set unconditionally. + * @param pool The pool to allocate the file out of. + * + * @remark See remarks for apr_file_open_stderr(). + */ +APR_DECLARE(apr_status_t) apr_file_open_flags_stdin(apr_file_t **thefile, + apr_int32_t flags, + apr_pool_t *pool); + +/** + * Read data from the specified file. + * @param thefile The file descriptor to read from. + * @param buf The buffer to store the data to. + * @param nbytes On entry, the number of bytes to read; on exit, the number + * of bytes read. + * + * @remark apr_file_read() will read up to the specified number of + * bytes, but never more. If there isn't enough data to fill that + * number of bytes, all of the available data is read. The third + * argument is modified to reflect the number of bytes read. If a + * char was put back into the stream via ungetc, it will be the first + * character returned. + * + * @remark It is not possible for both bytes to be read and an #APR_EOF + * or other error to be returned. #APR_EINTR is never returned. + */ +APR_DECLARE(apr_status_t) apr_file_read(apr_file_t *thefile, void *buf, + apr_size_t *nbytes); + +/** + * Write data to the specified file. + * @param thefile The file descriptor to write to. + * @param buf The buffer which contains the data. + * @param nbytes On entry, the number of bytes to write; on exit, the number + * of bytes written. + * + * @remark apr_file_write() will write up to the specified number of + * bytes, but never more. If the OS cannot write that many bytes, it + * will write as many as it can. The third argument is modified to + * reflect the * number of bytes written. + * + * @remark It is possible for both bytes to be written and an error to + * be returned. #APR_EINTR is never returned. + */ +APR_DECLARE(apr_status_t) apr_file_write(apr_file_t *thefile, const void *buf, + apr_size_t *nbytes); + +/** + * Write data from iovec array to the specified file. + * @param thefile The file descriptor to write to. + * @param vec The array from which to get the data to write to the file. + * @param nvec The number of elements in the struct iovec array. This must + * be smaller than #APR_MAX_IOVEC_SIZE. If it isn't, the function + * will fail with #APR_EINVAL. + * @param nbytes The number of bytes written. + * + * @remark It is possible for both bytes to be written and an error to + * be returned. #APR_EINTR is never returned. + * + * @remark apr_file_writev() is available even if the underlying + * operating system doesn't provide writev(). + */ +APR_DECLARE(apr_status_t) apr_file_writev(apr_file_t *thefile, + const struct iovec *vec, + apr_size_t nvec, apr_size_t *nbytes); + +/** + * Read data from the specified file, ensuring that the buffer is filled + * before returning. + * @param thefile The file descriptor to read from. + * @param buf The buffer to store the data to. + * @param nbytes The number of bytes to read. + * @param bytes_read If non-NULL, this will contain the number of bytes read. + * + * @remark apr_file_read_full() will read up to the specified number of + * bytes, but never more. If there isn't enough data to fill that + * number of bytes, then the process/thread will block until it is + * available or EOF is reached. If a char was put back into the + * stream via ungetc, it will be the first character returned. + * + * @remark It is possible for both bytes to be read and an error to be + * returned. And if *bytes_read is less than nbytes, an accompanying + * error is _always_ returned. + * + * @remark #APR_EINTR is never returned. + */ +APR_DECLARE(apr_status_t) apr_file_read_full(apr_file_t *thefile, void *buf, + apr_size_t nbytes, + apr_size_t *bytes_read); + +/** + * Write data to the specified file, ensuring that all of the data is + * written before returning. + * @param thefile The file descriptor to write to. + * @param buf The buffer which contains the data. + * @param nbytes The number of bytes to write. + * @param bytes_written If non-NULL, set to the number of bytes written. + * + * @remark apr_file_write_full() will write up to the specified number of + * bytes, but never more. If the OS cannot write that many bytes, the + * process/thread will block until they can be written. Exceptional + * error such as "out of space" or "pipe closed" will terminate with + * an error. + * + * @remark It is possible for both bytes to be written and an error to + * be returned. And if *bytes_written is less than nbytes, an + * accompanying error is _always_ returned. + * + * @remark #APR_EINTR is never returned. + */ +APR_DECLARE(apr_status_t) apr_file_write_full(apr_file_t *thefile, + const void *buf, + apr_size_t nbytes, + apr_size_t *bytes_written); + + +/** + * Write data from iovec array to the specified file, ensuring that all of the + * data is written before returning. + * @param thefile The file descriptor to write to. + * @param vec The array from which to get the data to write to the file. + * @param nvec The number of elements in the struct iovec array. This must + * be smaller than #APR_MAX_IOVEC_SIZE. If it isn't, the function + * will fail with #APR_EINVAL. + * @param nbytes The number of bytes written. + * + * @remark apr_file_writev_full() is available even if the underlying + * operating system doesn't provide writev(). + */ +APR_DECLARE(apr_status_t) apr_file_writev_full(apr_file_t *thefile, + const struct iovec *vec, + apr_size_t nvec, + apr_size_t *nbytes); +/** + * Write a character into the specified file. + * @param ch The character to write. + * @param thefile The file descriptor to write to + */ +APR_DECLARE(apr_status_t) apr_file_putc(char ch, apr_file_t *thefile); + +/** + * Read a character from the specified file. + * @param ch The character to read into + * @param thefile The file descriptor to read from + */ +APR_DECLARE(apr_status_t) apr_file_getc(char *ch, apr_file_t *thefile); + +/** + * Put a character back onto a specified stream. + * @param ch The character to write. + * @param thefile The file descriptor to write to + */ +APR_DECLARE(apr_status_t) apr_file_ungetc(char ch, apr_file_t *thefile); + +/** + * Read a line from the specified file + * @param str The buffer to store the string in. + * @param len The length of the string + * @param thefile The file descriptor to read from + * @remark The buffer will be NUL-terminated if any characters are stored. + * The newline at the end of the line will not be stripped. + */ +APR_DECLARE(apr_status_t) apr_file_gets(char *str, int len, + apr_file_t *thefile); + +/** + * Write the string into the specified file. + * @param str The string to write. + * @param thefile The file descriptor to write to + */ +APR_DECLARE(apr_status_t) apr_file_puts(const char *str, apr_file_t *thefile); + +/** + * Flush the file's buffer. + * @param thefile The file descriptor to flush + */ +APR_DECLARE(apr_status_t) apr_file_flush(apr_file_t *thefile); + +/** + * Transfer all file modified data and metadata to disk. + * @param thefile The file descriptor to sync + */ +APR_DECLARE(apr_status_t) apr_file_sync(apr_file_t *thefile); + +/** + * Transfer all file modified data to disk. + * @param thefile The file descriptor to sync + */ +APR_DECLARE(apr_status_t) apr_file_datasync(apr_file_t *thefile); + +/** + * Duplicate the specified file descriptor. + * @param new_file The structure to duplicate into. + * @param old_file The file to duplicate. + * @param p The pool to use for the new file. + * @remark *new_file must point to a valid apr_file_t, or point to NULL. + */ +APR_DECLARE(apr_status_t) apr_file_dup(apr_file_t **new_file, + apr_file_t *old_file, + apr_pool_t *p); + +/** + * Duplicate the specified file descriptor and close the original + * @param new_file The old file that is to be closed and reused + * @param old_file The file to duplicate + * @param p The pool to use for the new file + * + * @remark new_file MUST point at a valid apr_file_t. It cannot be NULL. + */ +APR_DECLARE(apr_status_t) apr_file_dup2(apr_file_t *new_file, + apr_file_t *old_file, + apr_pool_t *p); + +/** + * Move the specified file descriptor to a new pool + * @param new_file Pointer in which to return the new apr_file_t + * @param old_file The file to move + * @param p The pool to which the descriptor is to be moved + * @remark Unlike apr_file_dup2(), this function doesn't do an + * OS dup() operation on the underlying descriptor; it just + * moves the descriptor's apr_file_t wrapper to a new pool. + * @remark The new pool need not be an ancestor of old_file's pool. + * @remark After calling this function, old_file may not be used + */ +APR_DECLARE(apr_status_t) apr_file_setaside(apr_file_t **new_file, + apr_file_t *old_file, + apr_pool_t *p); + +/** + * Give the specified apr file handle a new buffer + * @param thefile The file handle that is to be modified + * @param buffer The buffer + * @param bufsize The size of the buffer + * @remark It is possible to add a buffer to previously unbuffered + * file handles, the #APR_FOPEN_BUFFERED flag will be added to + * the file handle's flags. Likewise, with buffer=NULL and + * bufsize=0 arguments it is possible to make a previously + * buffered file handle unbuffered. + */ +APR_DECLARE(apr_status_t) apr_file_buffer_set(apr_file_t *thefile, + char * buffer, + apr_size_t bufsize); + +/** + * Get the size of any buffer for the specified apr file handle + * @param thefile The file handle + */ +APR_DECLARE(apr_size_t) apr_file_buffer_size_get(apr_file_t *thefile); + +/** + * Move the read/write file offset to a specified byte within a file. + * @param thefile The file descriptor + * @param where How to move the pointer, one of: + * @li #APR_SET -- set the offset to offset + * @li #APR_CUR -- add the offset to the current position + * @li #APR_END -- add the offset to the current file size + * @param offset The offset to move the pointer to. + * @remark The third argument is modified to be the offset the pointer + was actually moved to. + */ +APR_DECLARE(apr_status_t) apr_file_seek(apr_file_t *thefile, + apr_seek_where_t where, + apr_off_t *offset); + +/** + * Create an anonymous pipe. + * @param in The newly created pipe's file for reading. + * @param out The newly created pipe's file for writing. + * @param pool The pool to operate on. + * @remark By default, the returned file descriptors will be inherited + * by child processes created using apr_proc_create(). This can be + * changed using apr_file_inherit_unset(). + * @bug Some platforms cannot toggle between blocking and nonblocking, + * and when passing a pipe as a standard handle to an application which + * does not expect it, a non-blocking stream will fluxor the client app. + * @deprecated @see apr_file_pipe_create_pools() + */ +APR_DECLARE(apr_status_t) apr_file_pipe_create(apr_file_t **in, + apr_file_t **out, + apr_pool_t *pool); + +/** + * Create an anonymous pipe which portably supports async timeout options. + * @param in The newly created pipe's file for reading. + * @param out The newly created pipe's file for writing. + * @param blocking one of these values defined in apr_thread_proc.h; + * @li #APR_FULL_BLOCK + * @li #APR_READ_BLOCK + * @li #APR_WRITE_BLOCK + * @li #APR_FULL_NONBLOCK + * @param pool The pool to operate on. + * @remark By default, the returned file descriptors will be inherited + * by child processes created using apr_proc_create(). This can be + * changed using apr_file_inherit_unset(). + * @remark Some platforms cannot toggle between blocking and nonblocking, + * and when passing a pipe as a standard handle to an application which + * does not expect it, a non-blocking stream will fluxor the client app. + * Use this function rather than apr_file_pipe_create() to create pipes + * where one or both ends require non-blocking semantics. + * @deprecated @see apr_file_pipe_create_pools() + */ +APR_DECLARE(apr_status_t) apr_file_pipe_create_ex(apr_file_t **in, + apr_file_t **out, + apr_int32_t blocking, + apr_pool_t *pool); + +/** + * Create an anonymous pipe which portably supports async timeout options, + * placing each side of the pipe in a different pool. + * @param in The newly created pipe's file for reading. + * @param out The newly created pipe's file for writing. + * @param blocking one of these values defined in apr_thread_proc.h; + * @li #APR_FULL_BLOCK + * @li #APR_READ_BLOCK + * @li #APR_WRITE_BLOCK + * @li #APR_FULL_NONBLOCK + * @param pool_in The pool for the reading pipe. + * @param pool_out The pool for the writing pipe. + * @remark By default, the returned file descriptors will be inherited + * by child processes created using apr_proc_create(). This can be + * changed using apr_file_inherit_unset(). + * @remark Some platforms cannot toggle between blocking and nonblocking, + * and when passing a pipe as a standard handle to an application which + * does not expect it, a non-blocking stream will fluxor the client app. + * Use this function rather than apr_file_pipe_create() to create pipes + * where one or both ends require non-blocking semantics. + */ +APR_DECLARE(apr_status_t) apr_file_pipe_create_pools(apr_file_t **in, + apr_file_t **out, + apr_int32_t blocking, + apr_pool_t *pool_in, + apr_pool_t *pool_out); + +/** + * Create a named pipe. + * @param filename The filename of the named pipe + * @param perm The permissions for the newly created pipe. + * @param pool The pool to operate on. + */ +APR_DECLARE(apr_status_t) apr_file_namedpipe_create(const char *filename, + apr_fileperms_t perm, + apr_pool_t *pool); + +/** + * Get the timeout value for a pipe or manipulate the blocking state. + * @param thepipe The pipe we are getting a timeout for. + * @param timeout The current timeout value in microseconds. + */ +APR_DECLARE(apr_status_t) apr_file_pipe_timeout_get(apr_file_t *thepipe, + apr_interval_time_t *timeout); + +/** + * Set the timeout value for a pipe or manipulate the blocking state. + * @param thepipe The pipe we are setting a timeout on. + * @param timeout The timeout value in microseconds. Values < 0 mean wait + * forever, 0 means do not wait at all. + */ +APR_DECLARE(apr_status_t) apr_file_pipe_timeout_set(apr_file_t *thepipe, + apr_interval_time_t timeout); + +/** file (un)locking functions. */ + +/** + * Establish a lock on the specified, open file. The lock may be advisory + * or mandatory, at the discretion of the platform. The lock applies to + * the file as a whole, rather than a specific range. Locks are established + * on a per-thread/process basis; a second lock by the same thread will not + * block. + * @param thefile The file to lock. + * @param type The type of lock to establish on the file. + */ +APR_DECLARE(apr_status_t) apr_file_lock(apr_file_t *thefile, int type); + +/** + * Remove any outstanding locks on the file. + * @param thefile The file to unlock. + */ +APR_DECLARE(apr_status_t) apr_file_unlock(apr_file_t *thefile); + +/**accessor and general file_io functions. */ + +/** + * return the file name of the current file. + * @param new_path The path of the file. + * @param thefile The currently open file. + */ +APR_DECLARE(apr_status_t) apr_file_name_get(const char **new_path, + apr_file_t *thefile); + +/** + * Return the data associated with the current file. + * @param data The user data associated with the file. + * @param key The key to use for retrieving data associated with this file. + * @param file The currently open file. + */ +APR_DECLARE(apr_status_t) apr_file_data_get(void **data, const char *key, + apr_file_t *file); + +/** + * Set the data associated with the current file. + * @param file The currently open file. + * @param data The user data to associate with the file. + * @param key The key to use for associating data with the file. + * @param cleanup The cleanup routine to use when the file is destroyed. + */ +APR_DECLARE(apr_status_t) apr_file_data_set(apr_file_t *file, void *data, + const char *key, + apr_status_t (*cleanup)(void *)); + +/** + * Write a string to a file using a printf format. + * @param fptr The file to write to. + * @param format The format string + * @param ... The values to substitute in the format string + * @return The number of bytes written + */ +APR_DECLARE_NONSTD(int) apr_file_printf(apr_file_t *fptr, + const char *format, ...) + __attribute__((format(printf,2,3))); + +/** + * set the specified file's permission bits. + * @param fname The file (name) to apply the permissions to. + * @param perms The permission bits to apply to the file. + * + * @warning Some platforms may not be able to apply all of the + * available permission bits; #APR_INCOMPLETE will be returned if some + * permissions are specified which could not be set. + * + * @warning Platforms which do not implement this feature will return + * #APR_ENOTIMPL. + */ +APR_DECLARE(apr_status_t) apr_file_perms_set(const char *fname, + apr_fileperms_t perms); + +/** + * Set attributes of the specified file. + * @param fname The full path to the file (using / on all systems) + * @param attributes Or'd combination of + * @li #APR_FILE_ATTR_READONLY - make the file readonly + * @li #APR_FILE_ATTR_EXECUTABLE - make the file executable + * @li #APR_FILE_ATTR_HIDDEN - make the file hidden + * @param attr_mask Mask of valid bits in attributes. + * @param pool the pool to use. + * @remark This function should be used in preference to explicit manipulation + * of the file permissions, because the operations to provide these + * attributes are platform specific and may involve more than simply + * setting permission bits. + * @warning Platforms which do not implement this feature will return + * #APR_ENOTIMPL. + */ +APR_DECLARE(apr_status_t) apr_file_attrs_set(const char *fname, + apr_fileattrs_t attributes, + apr_fileattrs_t attr_mask, + apr_pool_t *pool); + +/** + * Set the mtime of the specified file. + * @param fname The full path to the file (using / on all systems) + * @param mtime The mtime to apply to the file. + * @param pool The pool to use. + * @warning Platforms which do not implement this feature will return + * #APR_ENOTIMPL. + */ +APR_DECLARE(apr_status_t) apr_file_mtime_set(const char *fname, + apr_time_t mtime, + apr_pool_t *pool); + +/** + * Create a new directory on the file system. + * @param path the path for the directory to be created. (use / on all systems) + * @param perm Permissions for the new directory. + * @param pool the pool to use. + */ +APR_DECLARE(apr_status_t) apr_dir_make(const char *path, apr_fileperms_t perm, + apr_pool_t *pool); + +/** Creates a new directory on the file system, but behaves like + * 'mkdir -p'. Creates intermediate directories as required. No error + * will be reported if PATH already exists. + * @param path the path for the directory to be created. (use / on all systems) + * @param perm Permissions for the new directory. + * @param pool the pool to use. + */ +APR_DECLARE(apr_status_t) apr_dir_make_recursive(const char *path, + apr_fileperms_t perm, + apr_pool_t *pool); + +/** + * Remove directory from the file system. + * @param path the path for the directory to be removed. (use / on all systems) + * @param pool the pool to use. + * @remark Removing a directory which is in-use (e.g., the current working + * directory, or during apr_dir_read, or with an open file) is not portable. + */ +APR_DECLARE(apr_status_t) apr_dir_remove(const char *path, apr_pool_t *pool); + +/** + * get the specified file's stats. + * @param finfo Where to store the information about the file. + * @param wanted The desired apr_finfo_t fields, as a bit flag of APR_FINFO_* values + * @param thefile The file to get information about. + */ +APR_DECLARE(apr_status_t) apr_file_info_get(apr_finfo_t *finfo, + apr_int32_t wanted, + apr_file_t *thefile); + + +/** + * Truncate the file's length to the specified offset + * @param fp The file to truncate + * @param offset The offset to truncate to. + * @remark The read/write file offset is repositioned to offset. + */ +APR_DECLARE(apr_status_t) apr_file_trunc(apr_file_t *fp, apr_off_t offset); + +/** + * Retrieve the flags that were passed into apr_file_open() + * when the file was opened. + * @return apr_int32_t the flags + */ +APR_DECLARE(apr_int32_t) apr_file_flags_get(apr_file_t *f); + +/** + * Get the pool used by the file. + */ +APR_POOL_DECLARE_ACCESSOR(file); + +/** + * Set a file to be inherited by child processes. + * + */ +APR_DECLARE_INHERIT_SET(file); + +/** + * Unset a file from being inherited by child processes. + */ +APR_DECLARE_INHERIT_UNSET(file); + +/** + * Open a temporary file + * @param fp The apr file to use as a temporary file. + * @param templ The template to use when creating a temp file. + * @param flags The flags to open the file with. If this is zero, + * the file is opened with + * #APR_FOPEN_CREATE | #APR_FOPEN_READ | #APR_FOPEN_WRITE | + * #APR_FOPEN_EXCL | #APR_FOPEN_DELONCLOSE + * @param p The pool to allocate the file out of. + * @remark + * This function generates a unique temporary file name from template. + * The last six characters of template must be XXXXXX and these are replaced + * with a string that makes the filename unique. Since it will be modified, + * template must not be a string constant, but should be declared as a character + * array. + * + */ +APR_DECLARE(apr_status_t) apr_file_mktemp(apr_file_t **fp, char *templ, + apr_int32_t flags, apr_pool_t *p); + + +/** + * Find an existing directory suitable as a temporary storage location. + * @param temp_dir The temp directory. + * @param p The pool to use for any necessary allocations. + * @remark + * This function uses an algorithm to search for a directory that an + * an application can use for temporary storage. + * + */ +APR_DECLARE(apr_status_t) apr_temp_dir_get(const char **temp_dir, + apr_pool_t *p); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_FILE_IO_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_fnmatch.h b/c/dependencies/windows/apr/x86_debug/include/apr_fnmatch.h new file mode 100644 index 00000000..e8f6b03c --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_fnmatch.h @@ -0,0 +1,153 @@ +/* + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)fnmatch.h 8.1 (Berkeley) 6/2/93 + */ + +/* This file has been modified by the Apache Software Foundation. */ +#ifndef _APR_FNMATCH_H_ +#define _APR_FNMATCH_H_ + +/** + * @file apr_fnmatch.h + * @brief APR FNMatch Functions + */ + +#include "apr_errno.h" +#include "apr_tables.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_fnmatch Filename Matching Functions + * @ingroup APR + * @{ + */ + +#define APR_FNM_NOMATCH 1 /**< Match failed. */ + +#define APR_FNM_NOESCAPE 0x01 /**< Disable backslash escaping. */ +#define APR_FNM_PATHNAME 0x02 /**< Slash must be matched by slash. */ +#define APR_FNM_PERIOD 0x04 /**< Period must be matched by period. */ +#define APR_FNM_CASE_BLIND 0x08 /**< Compare characters case-insensitively. */ + +/** + * Try to match the string to the given pattern, return APR_SUCCESS if + * match, else return APR_FNM_NOMATCH. Note that there is no such thing as + * an illegal pattern. + * + * With all flags unset, a pattern is interpreted as such: + * + * PATTERN: Backslash followed by any character, including another + * backslash.
+ * MATCHES: That character exactly. + * + *

+ * PATTERN: ?
+ * MATCHES: Any single character. + *

+ * + *

+ * PATTERN: *
+ * MATCHES: Any sequence of zero or more characters. (Note that multiple + * *s in a row are equivalent to one.) + * + * PATTERN: Any character other than \?*[ or a \ at the end of the pattern
+ * MATCHES: That character exactly. (Case sensitive.) + * + * PATTERN: [ followed by a class description followed by ]
+ * MATCHES: A single character described by the class description. + * (Never matches, if the class description reaches until the + * end of the string without a ].) If the first character of + * the class description is ^ or !, the sense of the description + * is reversed. The rest of the class description is a list of + * single characters or pairs of characters separated by -. Any + * of those characters can have a backslash in front of them, + * which is ignored; this lets you use the characters ] and - + * in the character class, as well as ^ and ! at the + * beginning. The pattern matches a single character if it + * is one of the listed characters or falls into one of the + * listed ranges (inclusive, case sensitive). Ranges with + * the first character larger than the second are legal but + * never match. Edge cases: [] never matches, and [^] and [!] + * always match without consuming a character. + * + * Note that these patterns attempt to match the entire string, not + * just find a substring matching the pattern. + * + * @param pattern The pattern to match to + * @param strings The string we are trying to match + * @param flags flags to use in the match. Bitwise OR of: + *

+ *              APR_FNM_NOESCAPE       Disable backslash escaping
+ *              APR_FNM_PATHNAME       Slash must be matched by slash
+ *              APR_FNM_PERIOD         Period must be matched by period
+ *              APR_FNM_CASE_BLIND     Compare characters case-insensitively.
+ * 
+ */ + +APR_DECLARE(apr_status_t) apr_fnmatch(const char *pattern, + const char *strings, int flags); + +/** + * Determine if the given pattern is a regular expression. + * @param pattern The pattern to search for glob characters. + * @return non-zero if pattern has any glob characters in it + */ +APR_DECLARE(int) apr_fnmatch_test(const char *pattern); + +/** + * Find all files that match a specified pattern in a directory. + * @param dir_pattern The pattern to use for finding files, appended + * to the search directory. The pattern is anything following the + * final forward or backward slash in the parameter. If no slash + * is found, the current directory is searched. + * @param result Array to use when storing the results + * @param p The pool to use. + * @return APR_SUCCESS if no processing errors occurred, APR error + * code otherwise + * @remark The returned array may be empty even if APR_SUCCESS was + * returned. + */ +APR_DECLARE(apr_status_t) apr_match_glob(const char *dir_pattern, + apr_array_header_t **result, + apr_pool_t *p); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !_APR_FNMATCH_H_ */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_general.h b/c/dependencies/windows/apr/x86_debug/include/apr_general.h new file mode 100644 index 00000000..fa073c85 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_general.h @@ -0,0 +1,244 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_GENERAL_H +#define APR_GENERAL_H + +/** + * @file apr_general.h + * This is collection of oddballs that didn't fit anywhere else, + * and might move to more appropriate headers with the release + * of APR 1.0. + * @brief APR Miscellaneous library routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" + +#if APR_HAVE_SIGNAL_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_general Miscellaneous library routines + * @ingroup APR + * This is collection of oddballs that didn't fit anywhere else, + * and might move to more appropriate headers with the release + * of APR 1.0. + * @{ + */ + +/** FALSE */ +#ifndef FALSE +#define FALSE 0 +#endif +/** TRUE */ +#ifndef TRUE +#define TRUE (!FALSE) +#endif + +/** a space */ +#define APR_ASCII_BLANK '\040' +/** a carrige return */ +#define APR_ASCII_CR '\015' +/** a line feed */ +#define APR_ASCII_LF '\012' +/** a tab */ +#define APR_ASCII_TAB '\011' + +/** signal numbers typedef */ +typedef int apr_signum_t; + +/** + * Finding offsets of elements within structures. + * Taken from the X code... they've sweated portability of this stuff + * so we don't have to. Sigh... + * @param p_type pointer type name + * @param field data field within the structure pointed to + * @return offset + */ + +#if defined(CRAY) || (defined(__arm) && !(defined(LINUX) || defined(__FreeBSD__))) +#ifdef __STDC__ +#define APR_OFFSET(p_type,field) _Offsetof(p_type,field) +#else +#ifdef CRAY2 +#define APR_OFFSET(p_type,field) \ + (sizeof(int)*((unsigned int)&(((p_type)NULL)->field))) + +#else /* !CRAY2 */ + +#define APR_OFFSET(p_type,field) ((unsigned int)&(((p_type)NULL)->field)) + +#endif /* !CRAY2 */ +#endif /* __STDC__ */ +#else /* ! (CRAY || __arm) */ + +#define APR_OFFSET(p_type,field) \ + ((long) (((char *) (&(((p_type)NULL)->field))) - ((char *) NULL))) + +#endif /* !CRAY */ + +/** + * Finding offsets of elements within structures. + * @param s_type structure type name + * @param field data field within the structure + * @return offset + */ +#if defined(offsetof) && !defined(__cplusplus) +#define APR_OFFSETOF(s_type,field) offsetof(s_type,field) +#else +#define APR_OFFSETOF(s_type,field) APR_OFFSET(s_type*,field) +#endif + +#ifndef DOXYGEN + +/* A couple of prototypes for functions in case some platform doesn't + * have it + */ +#if (!APR_HAVE_STRCASECMP) && (APR_HAVE_STRICMP) +#define strcasecmp(s1, s2) stricmp(s1, s2) +#elif (!APR_HAVE_STRCASECMP) +int strcasecmp(const char *a, const char *b); +#endif + +#if (!APR_HAVE_STRNCASECMP) && (APR_HAVE_STRNICMP) +#define strncasecmp(s1, s2, n) strnicmp(s1, s2, n) +#elif (!APR_HAVE_STRNCASECMP) +int strncasecmp(const char *a, const char *b, size_t n); +#endif + +#endif + +/** + * Alignment macros + */ + +/* APR_ALIGN() is only to be used to align on a power of 2 boundary */ +#define APR_ALIGN(size, boundary) \ + (((size) + ((boundary) - 1)) & ~((boundary) - 1)) + +/** Default alignment */ +#define APR_ALIGN_DEFAULT(size) APR_ALIGN(size, 8) + + +/** + * String and memory functions + */ + +/* APR_STRINGIFY is defined here, and also in apr_release.h, so wrap it */ +#ifndef APR_STRINGIFY +/** Properly quote a value as a string in the C preprocessor */ +#define APR_STRINGIFY(n) APR_STRINGIFY_HELPER(n) +/** Helper macro for APR_STRINGIFY */ +#define APR_STRINGIFY_HELPER(n) #n +#endif + +#if (!APR_HAVE_MEMMOVE) +#define memmove(a,b,c) bcopy(b,a,c) +#endif + +#if (!APR_HAVE_MEMCHR) +void *memchr(const void *s, int c, size_t n); +#endif + +/** @} */ + +/** + * @defgroup apr_library Library initialization and termination + * @{ + */ + +/** + * Setup any APR internal data structures. This MUST be the first function + * called for any APR library. It is safe to call apr_initialize several + * times as long as apr_terminate() is called the same number of times. + * @remark See apr_app_initialize() if this is an application, rather than + * a library consumer of apr. + */ +APR_DECLARE(apr_status_t) apr_initialize(void); + +/** + * Set up an application with normalized argc, argv (and optionally env) in + * order to deal with platform-specific oddities, such as Win32 services, + * code pages and signals. This must be the first function called for any + * APR program. + * @param argc Pointer to the argc that may be corrected + * @param argv Pointer to the argv that may be corrected + * @param env Pointer to the env that may be corrected, may be NULL + * @remark See apr_initialize() if this is a library consumer of apr. + * Otherwise, this call is identical to apr_initialize(), and must be closed + * with a call to apr_terminate() at the end of program execution. + */ +APR_DECLARE(apr_status_t) apr_app_initialize(int *argc, + char const * const * *argv, + char const * const * *env); + +/** + * Tear down any APR internal data structures which aren't torn down + * automatically. apr_terminate must be called once for every call to + * apr_initialize() or apr_app_initialize(). + * @remark An APR program must call this function at termination once it + * has stopped using APR services. The APR developers suggest using + * @c atexit(apr_terminate) to ensure this is called. When using APR + * from a language other than C that has problems with the calling + * convention, use apr_terminate2() instead. + * @see apr_terminate2 + */ +APR_DECLARE_NONSTD(void) apr_terminate(void); + +/** + * Tear down any APR internal data structures which aren't torn down + * automatically, same as apr_terminate() + * @remark An APR program must call either the apr_terminate() or apr_terminate2 + * function once it it has finished using APR services. The APR + * developers suggest using @c atexit(apr_terminate) to ensure this is done. + * apr_terminate2 exists to allow non-c language apps to tear down apr, + * while apr_terminate() is recommended from c language applications. + */ +APR_DECLARE(void) apr_terminate2(void); + +/** @} */ + +/** + * @defgroup apr_random Random Functions + * @{ + */ + +#if APR_HAS_RANDOM || defined(DOXYGEN) + +/* TODO: I'm not sure this is the best place to put this prototype...*/ +/** + * Generate random bytes. + * @param buf Buffer to fill with random bytes + * @param length Length of buffer in bytes + */ +APR_DECLARE(apr_status_t) apr_generate_random_bytes(unsigned char * buf, + apr_size_t length); + +#endif +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_GENERAL_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_getopt.h b/c/dependencies/windows/apr/x86_debug/include/apr_getopt.h new file mode 100644 index 00000000..75ad5663 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_getopt.h @@ -0,0 +1,160 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_GETOPT_H +#define APR_GETOPT_H + +/** + * @file apr_getopt.h + * @brief APR Command Arguments (getopt) + */ + +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_getopt Command Argument Parsing + * @ingroup APR + * @{ + */ + +/** + * An @c apr_getopt_t error callback function. + * + * @a arg is this @c apr_getopt_t's @c errarg member. + */ +typedef void (apr_getopt_err_fn_t)(void *arg, const char *err, ...); + +/** @see apr_getopt_t */ +typedef struct apr_getopt_t apr_getopt_t; + +/** + * Structure to store command line argument information. + */ +struct apr_getopt_t { + /** context for processing */ + apr_pool_t *cont; + /** function to print error message (NULL == no messages) */ + apr_getopt_err_fn_t *errfn; + /** user defined first arg to pass to error message */ + void *errarg; + /** index into parent argv vector */ + int ind; + /** character checked for validity */ + int opt; + /** reset getopt */ + int reset; + /** count of arguments */ + int argc; + /** array of pointers to arguments */ + const char **argv; + /** argument associated with option */ + char const* place; + /** set to nonzero to support interleaving options with regular args */ + int interleave; + /** start of non-option arguments skipped for interleaving */ + int skip_start; + /** end of non-option arguments skipped for interleaving */ + int skip_end; +}; + +/** @see apr_getopt_option_t */ +typedef struct apr_getopt_option_t apr_getopt_option_t; + +/** + * Structure used to describe options that getopt should search for. + */ +struct apr_getopt_option_t { + /** long option name, or NULL if option has no long name */ + const char *name; + /** option letter, or a value greater than 255 if option has no letter */ + int optch; + /** nonzero if option takes an argument */ + int has_arg; + /** a description of the option */ + const char *description; +}; + +/** + * Initialize the arguments for parsing by apr_getopt(). + * @param os The options structure created for apr_getopt() + * @param cont The pool to operate on + * @param argc The number of arguments to parse + * @param argv The array of arguments to parse + * @remark Arguments 3 and 4 are most commonly argc and argv from main(argc, argv) + * The (*os)->errfn is initialized to fprintf(stderr... but may be overridden. + */ +APR_DECLARE(apr_status_t) apr_getopt_init(apr_getopt_t **os, apr_pool_t *cont, + int argc, const char * const *argv); + +/** + * Parse the options initialized by apr_getopt_init(). + * @param os The apr_opt_t structure returned by apr_getopt_init() + * @param opts A string of characters that are acceptable options to the + * program. Characters followed by ":" are required to have an + * option associated + * @param option_ch The next option character parsed + * @param option_arg The argument following the option character: + * @return There are four potential status values on exit. They are: + *
+ *             APR_EOF      --  No more options to parse
+ *             APR_BADCH    --  Found a bad option character
+ *             APR_BADARG   --  No argument followed the option flag
+ *             APR_SUCCESS  --  The next option was found.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_getopt(apr_getopt_t *os, const char *opts, + char *option_ch, const char **option_arg); + +/** + * Parse the options initialized by apr_getopt_init(), accepting long + * options beginning with "--" in addition to single-character + * options beginning with "-". + * @param os The apr_getopt_t structure created by apr_getopt_init() + * @param opts A pointer to a list of apr_getopt_option_t structures, which + * can be initialized with { "name", optch, has_args }. has_args + * is nonzero if the option requires an argument. A structure + * with an optch value of 0 terminates the list. + * @param option_ch Receives the value of "optch" from the apr_getopt_option_t + * structure corresponding to the next option matched. + * @param option_arg Receives the argument following the option, if any. + * @return There are four potential status values on exit. They are: + *
+ *             APR_EOF      --  No more options to parse
+ *             APR_BADCH    --  Found a bad option character
+ *             APR_BADARG   --  No argument followed the option flag
+ *             APR_SUCCESS  --  The next option was found.
+ * 
+ * When APR_SUCCESS is returned, os->ind gives the index of the first + * non-option argument. On error, a message will be printed to stdout unless + * os->err is set to 0. If os->interleave is set to nonzero, options can come + * after arguments, and os->argv will be permuted to leave non-option arguments + * at the end (the original argv is unaffected). + */ +APR_DECLARE(apr_status_t) apr_getopt_long(apr_getopt_t *os, + const apr_getopt_option_t *opts, + int *option_ch, + const char **option_arg); +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_GETOPT_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_global_mutex.h b/c/dependencies/windows/apr/x86_debug/include/apr_global_mutex.h new file mode 100644 index 00000000..e3cba23f --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_global_mutex.h @@ -0,0 +1,195 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_GLOBAL_MUTEX_H +#define APR_GLOBAL_MUTEX_H + +/** + * @file apr_global_mutex.h + * @brief APR Global Locking Routines + */ + +#include "apr.h" +#include "apr_proc_mutex.h" /* only for apr_lockmech_e */ +#include "apr_pools.h" +#include "apr_errno.h" +#if APR_PROC_MUTEX_IS_GLOBAL +#include "apr_proc_mutex.h" +#endif +#include "apr_time.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_GlobalMutex Global Locking Routines + * @ingroup APR + * @{ + */ + +#if !APR_PROC_MUTEX_IS_GLOBAL || defined(DOXYGEN) + +/** Opaque global mutex structure. */ +typedef struct apr_global_mutex_t apr_global_mutex_t; + +/* Function definitions */ + +/** + * Create and initialize a mutex that can be used to synchronize both + * processes and threads. Note: There is considerable overhead in using + * this API if only cross-process or cross-thread mutual exclusion is + * required. See apr_proc_mutex.h and apr_thread_mutex.h for more + * specialized lock routines. + * @param mutex the memory address where the newly created mutex will be + * stored. + * @param fname A file name to use if the lock mechanism requires one. This + * argument should always be provided. The lock code itself will + * determine if it should be used. + * @param mech The mechanism to use for the interprocess lock, if any; one of + *
+ *            APR_LOCK_FCNTL
+ *            APR_LOCK_FLOCK
+ *            APR_LOCK_SYSVSEM
+ *            APR_LOCK_POSIXSEM
+ *            APR_LOCK_PROC_PTHREAD
+ *            APR_LOCK_DEFAULT     pick the default mechanism for the platform
+ *            APR_LOCK_DEFAULT_TIMED pick the default timed mechanism
+ * 
+ * @param pool the pool from which to allocate the mutex. + * @warning Check APR_HAS_foo_SERIALIZE defines to see if the platform supports + * APR_LOCK_foo. Only APR_LOCK_DEFAULT is portable. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_create(apr_global_mutex_t **mutex, + const char *fname, + apr_lockmech_e mech, + apr_pool_t *pool); + +/** + * Re-open a mutex in a child process. + * @param mutex The newly re-opened mutex structure. + * @param fname A file name to use if the mutex mechanism requires one. This + * argument should always be provided. The mutex code itself will + * determine if it should be used. This filename should be the + * same one that was passed to apr_global_mutex_create(). + * @param pool The pool to operate on. + * @remark This function must be called to maintain portability, even + * if the underlying lock mechanism does not require it. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_child_init( + apr_global_mutex_t **mutex, + const char *fname, + apr_pool_t *pool); + +/** + * Acquire the lock for the given mutex. If the mutex is already locked, + * the current thread will be put to sleep until the lock becomes available. + * @param mutex the mutex on which to acquire the lock. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_lock(apr_global_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex. If the mutex has already + * been acquired, the call returns immediately with APR_EBUSY. Note: it + * is important that the APR_STATUS_IS_EBUSY(s) macro be used to determine + * if the return value was APR_EBUSY, for portability reasons. + * @param mutex the mutex on which to attempt the lock acquiring. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_trylock(apr_global_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex until timeout expires. + * If the acquisition time outs, the call returns with APR_TIMEUP. + * @param mutex the mutex on which to attempt the lock acquiring. + * @param timeout the relative timeout (microseconds). + * @note A negative or nul timeout means immediate attempt, returning + * APR_TIMEUP without blocking if it the lock is already acquired. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_timedlock(apr_global_mutex_t *mutex, + apr_interval_time_t timeout); + +/** + * Release the lock for the given mutex. + * @param mutex the mutex from which to release the lock. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_unlock(apr_global_mutex_t *mutex); + +/** + * Destroy the mutex and free the memory associated with the lock. + * @param mutex the mutex to destroy. + */ +APR_DECLARE(apr_status_t) apr_global_mutex_destroy(apr_global_mutex_t *mutex); + +/** + * Return the name of the lockfile for the mutex, or NULL + * if the mutex doesn't use a lock file + */ +APR_DECLARE(const char *) apr_global_mutex_lockfile(apr_global_mutex_t *mutex); + +/** + * Get the mechanism of the mutex, as it relates to the actual method + * used for the underlying apr_proc_mutex_t. + * @param mutex the mutex to get the mechanism from. + */ +APR_DECLARE(apr_lockmech_e) apr_global_mutex_mech(apr_global_mutex_t *mutex); + +/** + * Get the mechanism's name of the mutex, as it relates to the actual method + * used for the underlying apr_proc_mutex_t. + * @param mutex the mutex to get the mechanism's name from. + */ +APR_DECLARE(const char *) apr_global_mutex_name(apr_global_mutex_t *mutex); + +/** + * Set mutex permissions. + */ +APR_PERMS_SET_IMPLEMENT(global_mutex); + +/** + * Get the pool used by this global_mutex. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(global_mutex); + +#else /* APR_PROC_MUTEX_IS_GLOBAL */ + +/* Some platforms [e.g. Win32] have cross process locks that are truly + * global locks, since there isn't the concept of cross-process locks. + * Define these platforms in terms of an apr_proc_mutex_t. + */ + +#define apr_global_mutex_t apr_proc_mutex_t +#define apr_global_mutex_create apr_proc_mutex_create +#define apr_global_mutex_child_init apr_proc_mutex_child_init +#define apr_global_mutex_lock apr_proc_mutex_lock +#define apr_global_mutex_trylock apr_proc_mutex_trylock +#define apr_global_mutex_unlock apr_proc_mutex_unlock +#define apr_global_mutex_destroy apr_proc_mutex_destroy +#define apr_global_mutex_lockfile apr_proc_mutex_lockfile +#define apr_global_mutex_mech apr_proc_mutex_mech +#define apr_global_mutex_name apr_proc_mutex_name +#define apr_global_mutex_perms_set apr_proc_mutex_perms_set +#define apr_global_mutex_pool_get apr_proc_mutex_pool_get + +#endif + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ndef APR_GLOBAL_MUTEX_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_hash.h b/c/dependencies/windows/apr/x86_debug/include/apr_hash.h new file mode 100644 index 00000000..2276f84c --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_hash.h @@ -0,0 +1,283 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_HASH_H +#define APR_HASH_H + +/** + * @file apr_hash.h + * @brief APR Hash Tables + */ + +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_hash Hash Tables + * @ingroup APR + * @{ + */ + +/** + * When passing a key to apr_hash_set or apr_hash_get, this value can be + * passed to indicate a string-valued key, and have apr_hash compute the + * length automatically. + * + * @remark apr_hash will use strlen(key) for the length. The NUL terminator + * is not included in the hash value (why throw a constant in?). + * Since the hash table merely references the provided key (rather + * than copying it), apr_hash_this() will return the NUL-term'd key. + */ +#define APR_HASH_KEY_STRING (-1) + +/** + * Abstract type for hash tables. + */ +typedef struct apr_hash_t apr_hash_t; + +/** + * Abstract type for scanning hash tables. + */ +typedef struct apr_hash_index_t apr_hash_index_t; + +/** + * Callback functions for calculating hash values. + * @param key The key. + * @param klen The length of the key, or APR_HASH_KEY_STRING to use the string + * length. If APR_HASH_KEY_STRING then returns the actual key length. + */ +typedef unsigned int (*apr_hashfunc_t)(const char *key, apr_ssize_t *klen); + +/** + * The default hash function. + */ +APR_DECLARE_NONSTD(unsigned int) apr_hashfunc_default(const char *key, + apr_ssize_t *klen); + +/** + * Create a hash table. + * @param pool The pool to allocate the hash table out of + * @return The hash table just created + */ +APR_DECLARE(apr_hash_t *) apr_hash_make(apr_pool_t *pool); + +/** + * Create a hash table with a custom hash function + * @param pool The pool to allocate the hash table out of + * @param hash_func A custom hash function. + * @return The hash table just created + */ +APR_DECLARE(apr_hash_t *) apr_hash_make_custom(apr_pool_t *pool, + apr_hashfunc_t hash_func); + +/** + * Make a copy of a hash table + * @param pool The pool from which to allocate the new hash table + * @param h The hash table to clone + * @return The hash table just created + * @remark Makes a shallow copy + */ +APR_DECLARE(apr_hash_t *) apr_hash_copy(apr_pool_t *pool, + const apr_hash_t *h); + +/** + * Associate a value with a key in a hash table. + * @param ht The hash table + * @param key Pointer to the key + * @param klen Length of the key. Can be APR_HASH_KEY_STRING to use the string length. + * @param val Value to associate with the key + * @remark If the value is NULL the hash entry is deleted. The key is stored as is, + * and so must have a lifetime at least as long as the hash table's pool. + */ +APR_DECLARE(void) apr_hash_set(apr_hash_t *ht, const void *key, + apr_ssize_t klen, const void *val); + +/** + * Look up the value associated with a key in a hash table. + * @param ht The hash table + * @param key Pointer to the key + * @param klen Length of the key. Can be APR_HASH_KEY_STRING to use the string length. + * @return Returns NULL if the key is not present. + */ +APR_DECLARE(void *) apr_hash_get(apr_hash_t *ht, const void *key, + apr_ssize_t klen); + +/** + * Start iterating over the entries in a hash table. + * @param p The pool to allocate the apr_hash_index_t iterator. If this + * pool is NULL, then an internal, non-thread-safe iterator is used. + * @param ht The hash table + * @return The iteration state + * @remark There is no restriction on adding or deleting hash entries during + * an iteration (although the results may be unpredictable unless all you do + * is delete the current entry) and multiple iterations can be in + * progress at the same time. + * + * @par Example: + * + * @code + * int sum_values(apr_pool_t *p, apr_hash_t *ht) + * { + * apr_hash_index_t *hi; + * void *val; + * int sum = 0; + * for (hi = apr_hash_first(p, ht); hi; hi = apr_hash_next(hi)) { + * apr_hash_this(hi, NULL, NULL, &val); + * sum += *(int *)val; + * } + * return sum; + * } + * @endcode + */ +APR_DECLARE(apr_hash_index_t *) apr_hash_first(apr_pool_t *p, apr_hash_t *ht); + +/** + * Continue iterating over the entries in a hash table. + * @param hi The iteration state + * @return a pointer to the updated iteration state. NULL if there are no more + * entries. + */ +APR_DECLARE(apr_hash_index_t *) apr_hash_next(apr_hash_index_t *hi); + +/** + * Get the current entry's details from the iteration state. + * @param hi The iteration state + * @param key Return pointer for the pointer to the key. + * @param klen Return pointer for the key length. + * @param val Return pointer for the associated value. + * @remark The return pointers should point to a variable that will be set to the + * corresponding data, or they may be NULL if the data isn't interesting. + */ +APR_DECLARE(void) apr_hash_this(apr_hash_index_t *hi, const void **key, + apr_ssize_t *klen, void **val); + +/** + * Get the current entry's key from the iteration state. + * @param hi The iteration state + * @return The pointer to the key + */ +APR_DECLARE(const void*) apr_hash_this_key(apr_hash_index_t *hi); + +/** + * Get the current entry's key length from the iteration state. + * @param hi The iteration state + * @return The key length + */ +APR_DECLARE(apr_ssize_t) apr_hash_this_key_len(apr_hash_index_t *hi); + +/** + * Get the current entry's value from the iteration state. + * @param hi The iteration state + * @return The pointer to the value + */ +APR_DECLARE(void*) apr_hash_this_val(apr_hash_index_t *hi); + +/** + * Get the number of key/value pairs in the hash table. + * @param ht The hash table + * @return The number of key/value pairs in the hash table. + */ +APR_DECLARE(unsigned int) apr_hash_count(apr_hash_t *ht); + +/** + * Clear any key/value pairs in the hash table. + * @param ht The hash table + */ +APR_DECLARE(void) apr_hash_clear(apr_hash_t *ht); + +/** + * Merge two hash tables into one new hash table. The values of the overlay + * hash override the values of the base if both have the same key. Both + * hash tables must use the same hash function. + * @param p The pool to use for the new hash table + * @param overlay The table to add to the initial table + * @param base The table that represents the initial values of the new table + * @return A new hash table containing all of the data from the two passed in + */ +APR_DECLARE(apr_hash_t *) apr_hash_overlay(apr_pool_t *p, + const apr_hash_t *overlay, + const apr_hash_t *base); + +/** + * Merge two hash tables into one new hash table. If the same key + * is present in both tables, call the supplied merge function to + * produce a merged value for the key in the new table. Both + * hash tables must use the same hash function. + * @param p The pool to use for the new hash table + * @param h1 The first of the tables to merge + * @param h2 The second of the tables to merge + * @param merger A callback function to merge values, or NULL to + * make values from h1 override values from h2 (same semantics as + * apr_hash_overlay()) + * @param data Client data to pass to the merger function + * @return A new hash table containing all of the data from the two passed in + */ +APR_DECLARE(apr_hash_t *) apr_hash_merge(apr_pool_t *p, + const apr_hash_t *h1, + const apr_hash_t *h2, + void * (*merger)(apr_pool_t *p, + const void *key, + apr_ssize_t klen, + const void *h1_val, + const void *h2_val, + const void *data), + const void *data); + +/** + * Declaration prototype for the iterator callback function of apr_hash_do(). + * + * @param rec The data passed as the first argument to apr_hash_[v]do() + * @param key The key from this iteration of the hash table + * @param klen The key length from this iteration of the hash table + * @param value The value from this iteration of the hash table + * @remark Iteration continues while this callback function returns non-zero. + * To export the callback function for apr_hash_do() it must be declared + * in the _NONSTD convention. + */ +typedef int (apr_hash_do_callback_fn_t)(void *rec, const void *key, + apr_ssize_t klen, + const void *value); + +/** + * Iterate over a hash table running the provided function once for every + * element in the hash table. The @param comp function will be invoked for + * every element in the hash table. + * + * @param comp The function to run + * @param rec The data to pass as the first argument to the function + * @param ht The hash table to iterate over + * @return FALSE if one of the comp() iterations returned zero; TRUE if all + * iterations returned non-zero + * @see apr_hash_do_callback_fn_t + */ +APR_DECLARE(int) apr_hash_do(apr_hash_do_callback_fn_t *comp, + void *rec, const apr_hash_t *ht); + +/** + * Get a pointer to the pool which the hash table was created in + */ +APR_POOL_DECLARE_ACCESSOR(hash); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_HASH_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_hooks.h b/c/dependencies/windows/apr/x86_debug/include/apr_hooks.h new file mode 100644 index 00000000..eee16e3c --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_hooks.h @@ -0,0 +1,358 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_HOOKS_H +#define APR_HOOKS_H + +#include "apu.h" +/* For apr_array_header_t */ +#include "apr_tables.h" + +/** + * @file apr_hooks.h + * @brief Apache hook functions + */ + +#ifdef __cplusplus +extern "C" { +#endif +/** + * @defgroup APR_Util_Hook Hook Functions + * @ingroup APR_Util + * @{ + */ + +/** + * @defgroup apr_hook_probes Hook probe capability + * APR hooks provide a trace probe capability for capturing + * the flow of control and return values with hooks. + * + * In order to use this facility, the application must define + * the symbol APR_HOOK_PROBES_ENABLED and the four APR_HOOK_PROBE_ + * macros described below before including apr_hooks.h in files + * that use the APR_IMPLEMENT_EXTERNAL_HOOK_* macros. + * + * This probe facility is not provided for APR optional hooks. + * @{ + */ + +#ifdef APR_HOOK_PROBES_ENABLED +#define APR_HOOK_INT_DCL_UD void *ud = NULL +#else +/** internal implementation detail to avoid the ud declaration when + * hook probes are not used + */ +#define APR_HOOK_INT_DCL_UD +/** + * User-defined hook probe macro that is invoked when the hook + * is run, before calling any hook functions. + * @param ud A void * user data field that should be filled in by + * this macro, and will be provided to the other hook probe macros. + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param args The argument list to the hook functions, with enclosing + * parens. + */ +#define APR_HOOK_PROBE_ENTRY(ud,ns,name,args) +/** + * User-defined hook probe macro that is invoked after the hook + * has run. + * @param ud A void * user data field that was filled in by the user- + * provided APR_HOOK_PROBE_ENTRY(). + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param rv The return value of the hook, or 0 if the hook is void. + * @param args The argument list to the hook functions, with enclosing + * parens. + */ +#define APR_HOOK_PROBE_RETURN(ud,ns,name,rv,args) +/** + * User-defined hook probe macro that is invoked before calling a + * hook function. + * @param ud A void * user data field that was filled in by the user- + * provided APR_HOOK_PROBE_ENTRY(). + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param src The value of apr_hook_debug_current at the time the function + * was hooked (usually the source file implementing the hook function). + * @param args The argument list to the hook functions, with enclosing + * parens. + */ +#define APR_HOOK_PROBE_INVOKE(ud,ns,name,src,args) +/** + * User-defined hook probe macro that is invoked after calling a + * hook function. + * @param ud A void * user data field that was filled in by the user- + * provided APR_HOOK_PROBE_ENTRY(). + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param src The value of apr_hook_debug_current at the time the function + * was hooked (usually the source file implementing the hook function). + * @param rv The return value of the hook function, or 0 if the hook is void. + * @param args The argument list to the hook functions, with enclosing + * parens. + */ +#define APR_HOOK_PROBE_COMPLETE(ud,ns,name,src,rv,args) +#endif + +/** @} */ + +/** macro to return the prototype of the hook function */ +#define APR_IMPLEMENT_HOOK_GET_PROTO(ns,link,name) \ +link##_DECLARE(apr_array_header_t *) ns##_hook_get_##name(void) + +/** macro to declare the hook correctly */ +#define APR_DECLARE_EXTERNAL_HOOK(ns,link,ret,name,args) \ +typedef ret ns##_HOOK_##name##_t args; \ +link##_DECLARE(void) ns##_hook_##name(ns##_HOOK_##name##_t *pf, \ + const char * const *aszPre, \ + const char * const *aszSucc, int nOrder); \ +link##_DECLARE(ret) ns##_run_##name args; \ +APR_IMPLEMENT_HOOK_GET_PROTO(ns,link,name); \ +typedef struct ns##_LINK_##name##_t \ + { \ + ns##_HOOK_##name##_t *pFunc; \ + const char *szName; \ + const char * const *aszPredecessors; \ + const char * const *aszSuccessors; \ + int nOrder; \ + } ns##_LINK_##name##_t; + +/** macro to declare the hook structure */ +#define APR_HOOK_STRUCT(members) \ +static struct { members } _hooks; + +/** macro to link the hook structure */ +#define APR_HOOK_LINK(name) \ + apr_array_header_t *link_##name; + +/** macro to implement the hook */ +#define APR_IMPLEMENT_EXTERNAL_HOOK_BASE(ns,link,name) \ +link##_DECLARE(void) ns##_hook_##name(ns##_HOOK_##name##_t *pf,const char * const *aszPre, \ + const char * const *aszSucc,int nOrder) \ + { \ + ns##_LINK_##name##_t *pHook; \ + if(!_hooks.link_##name) \ + { \ + _hooks.link_##name=apr_array_make(apr_hook_global_pool,1,sizeof(ns##_LINK_##name##_t)); \ + apr_hook_sort_register(#name,&_hooks.link_##name); \ + } \ + pHook=apr_array_push(_hooks.link_##name); \ + pHook->pFunc=pf; \ + pHook->aszPredecessors=aszPre; \ + pHook->aszSuccessors=aszSucc; \ + pHook->nOrder=nOrder; \ + pHook->szName=apr_hook_debug_current; \ + if(apr_hook_debug_enabled) \ + apr_hook_debug_show(#name,aszPre,aszSucc); \ + } \ + APR_IMPLEMENT_HOOK_GET_PROTO(ns,link,name) \ + { \ + return _hooks.link_##name; \ + } + +/** + * Implement a hook that has no return code, and therefore runs all of the + * registered functions + * @param ns The namespace prefix of the hook functions + * @param link The linkage declaration prefix of the hook + * @param name The name of the hook + * @param args_decl The declaration of the arguments for the hook + * @param args_use The names for the arguments for the hook + * @note The link prefix FOO corresponds to FOO_DECLARE() macros, which + * provide export linkage from the module that IMPLEMENTs the hook, and + * import linkage from external modules that link to the hook's module. + */ +#define APR_IMPLEMENT_EXTERNAL_HOOK_VOID(ns,link,name,args_decl,args_use) \ +APR_IMPLEMENT_EXTERNAL_HOOK_BASE(ns,link,name) \ +link##_DECLARE(void) ns##_run_##name args_decl \ + { \ + ns##_LINK_##name##_t *pHook; \ + int n; \ + APR_HOOK_INT_DCL_UD; \ +\ + APR_HOOK_PROBE_ENTRY(ud, ns, name, args_use); \ +\ + if(_hooks.link_##name) \ + { \ + pHook=(ns##_LINK_##name##_t *)_hooks.link_##name->elts; \ + for(n=0 ; n < _hooks.link_##name->nelts ; ++n) \ + { \ + APR_HOOK_PROBE_INVOKE(ud, ns, name, (char *)pHook[n].szName, args_use); \ + pHook[n].pFunc args_use; \ + APR_HOOK_PROBE_COMPLETE(ud, ns, name, (char *)pHook[n].szName, 0, args_use); \ + } \ + } \ +\ + APR_HOOK_PROBE_RETURN(ud, ns, name, 0, args_use); \ +\ + } + +/* FIXME: note that this returns ok when nothing is run. I suspect it should + really return decline, but that breaks Apache currently - Ben +*/ +/** + * Implement a hook that runs until one of the functions returns something + * other than OK or DECLINE + * @param ns The namespace prefix of the hook functions + * @param link The linkage declaration prefix of the hook + * @param ret Type to return + * @param name The name of the hook + * @param args_decl The declaration of the arguments for the hook + * @param args_use The names for the arguments for the hook + * @param ok Success value + * @param decline Decline value + * @note The link prefix FOO corresponds to FOO_DECLARE() macros, which + * provide export linkage from the module that IMPLEMENTs the hook, and + * import linkage from external modules that link to the hook's module. + */ +#define APR_IMPLEMENT_EXTERNAL_HOOK_RUN_ALL(ns,link,ret,name,args_decl,args_use,ok,decline) \ +APR_IMPLEMENT_EXTERNAL_HOOK_BASE(ns,link,name) \ +link##_DECLARE(ret) ns##_run_##name args_decl \ + { \ + ns##_LINK_##name##_t *pHook; \ + int n; \ + ret rv = ok; \ + APR_HOOK_INT_DCL_UD; \ +\ + APR_HOOK_PROBE_ENTRY(ud, ns, name, args_use); \ +\ + if(_hooks.link_##name) \ + { \ + pHook=(ns##_LINK_##name##_t *)_hooks.link_##name->elts; \ + for(n=0 ; n < _hooks.link_##name->nelts ; ++n) \ + { \ + APR_HOOK_PROBE_INVOKE(ud, ns, name, (char *)pHook[n].szName, args_use); \ + rv=pHook[n].pFunc args_use; \ + APR_HOOK_PROBE_COMPLETE(ud, ns, name, (char *)pHook[n].szName, rv, args_use); \ + if(rv != ok && rv != decline) \ + break; \ + rv = ok; \ + } \ + } \ +\ + APR_HOOK_PROBE_RETURN(ud, ns, name, rv, args_use); \ +\ + return rv; \ + } + + +/** + * Implement a hook that runs until the first function returns something + * other than the value of decline + * @param ns The namespace prefix of the hook functions + * @param link The linkage declaration prefix of the hook + * @param name The name of the hook + * @param ret Type to return + * @param args_decl The declaration of the arguments for the hook + * @param args_use The names for the arguments for the hook + * @param decline Decline value + * @note The link prefix FOO corresponds to FOO_DECLARE() macros, which + * provide export linkage from the module that IMPLEMENTs the hook, and + * import linkage from external modules that link to the hook's module. + */ +#define APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(ns,link,ret,name,args_decl,args_use,decline) \ +APR_IMPLEMENT_EXTERNAL_HOOK_BASE(ns,link,name) \ +link##_DECLARE(ret) ns##_run_##name args_decl \ + { \ + ns##_LINK_##name##_t *pHook; \ + int n; \ + ret rv = decline; \ + APR_HOOK_INT_DCL_UD; \ +\ + APR_HOOK_PROBE_ENTRY(ud, ns, name, args_use); \ +\ + if(_hooks.link_##name) \ + { \ + pHook=(ns##_LINK_##name##_t *)_hooks.link_##name->elts; \ + for(n=0 ; n < _hooks.link_##name->nelts ; ++n) \ + { \ + APR_HOOK_PROBE_INVOKE(ud, ns, name, (char *)pHook[n].szName, args_use); \ + rv=pHook[n].pFunc args_use; \ + APR_HOOK_PROBE_COMPLETE(ud, ns, name, (char *)pHook[n].szName, rv, args_use); \ +\ + if(rv != decline) \ + break; \ + } \ + } \ +\ + APR_HOOK_PROBE_RETURN(ud, ns, name, rv, args_use); \ +\ + return rv; \ + } + + /* Hook orderings */ +/** run this hook first, before ANYTHING */ +#define APR_HOOK_REALLY_FIRST (-10) +/** run this hook first */ +#define APR_HOOK_FIRST 0 +/** run this hook somewhere */ +#define APR_HOOK_MIDDLE 10 +/** run this hook after every other hook which is defined*/ +#define APR_HOOK_LAST 20 +/** run this hook last, after EVERYTHING */ +#define APR_HOOK_REALLY_LAST 30 + +/** + * The global pool used to allocate any memory needed by the hooks. + */ +APU_DECLARE_DATA extern apr_pool_t *apr_hook_global_pool; + +/** + * A global variable to determine if debugging information about the + * hooks functions should be printed. + */ +APU_DECLARE_DATA extern int apr_hook_debug_enabled; + +/** + * The name of the module that is currently registering a function. + */ +APU_DECLARE_DATA extern const char *apr_hook_debug_current; + +/** + * Register a hook function to be sorted. + * @param szHookName The name of the Hook the function is registered for + * @param aHooks The array which stores all of the functions for this hook + */ +APU_DECLARE(void) apr_hook_sort_register(const char *szHookName, + apr_array_header_t **aHooks); +/** + * Sort all of the registered functions for a given hook. + */ +APU_DECLARE(void) apr_hook_sort_all(void); + +/** + * Print all of the information about the current hook. This is used for + * debugging purposes. + * @param szName The name of the hook + * @param aszPre All of the functions in the predecessor array + * @param aszSucc All of the functions in the successor array + */ +APU_DECLARE(void) apr_hook_debug_show(const char *szName, + const char * const *aszPre, + const char * const *aszSucc); + +/** + * Remove all currently registered functions. + */ +APU_DECLARE(void) apr_hook_deregister_all(void); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_HOOKS_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_iconv.h b/c/dependencies/windows/apr/x86_debug/include/apr_iconv.h new file mode 100644 index 00000000..81a0d315 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_iconv.h @@ -0,0 +1,150 @@ +/*- + * Copyright (c) 1999,2000 + * Konstantin Chuguev. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Konstantin Chuguev + * and its contributors. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + */ + +#ifndef APR_ICONV_H +#define APR_ICONV_H + +/** + * @file apr_iconv.h + * @brief APR-iconv substitute iconv library implementation + */ + +#include "apr.h" +#include "apr_pools.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_iconv substitute iconv implementation + * @ingroup APR-iconv + * @{ + */ + +/** + * API_DECLARE_EXPORT is defined when building the libapriconv dynamic + * library, so that all public symbols are exported. + * + * API_DECLARE_STATIC is defined when including the apriconv public headers, + * to provide static linkage when the dynamic library may be unavailable. + * + * API_DECLARE_STATIC and API_DECLARE_EXPORT are left undefined when + * including the apr-iconv public headers, to import and link the symbols + * from the dynamic libapriconv library and assure appropriate indirection + * and calling conventions at compile time. + */ + +#if defined(DOXYGEN) || !defined(WIN32) +/** + * The public apr-iconv functions are declared with API_DECLARE(), so they + * use the most portable calling convention. Public apr-iconv functions + * with variable arguments must use API_DECLARE_NONSTD(). + * + * @deffunc API_DECLARE(rettype) apr_func(args); + */ +#define API_DECLARE(type) type +/** + * The private apr-iconv functions are declared with API_DECLARE_NONSTD(), + * so they use the most optimal C language calling conventions. + * + * @deffunc API_DECLARE(rettype) apr_func(args); + */ +#define API_DECLARE_NONSTD(type) type +/** + * All exported apr-iconv variables are declared with API_DECLARE_DATA + * This assures the appropriate indirection is invoked at compile time. + * + * @deffunc API_DECLARE_DATA type apr_variable; + * @tip extern API_DECLARE_DATA type apr_variable; syntax is required for + * declarations within headers to properly import the variable. + */ +#define API_DECLARE_DATA +#elif defined(API_DECLARE_STATIC) +#define API_DECLARE(type) type __stdcall +#define API_DECLARE_NONSTD(type) type __cdecl +#define API_DECLARE_DATA +#elif defined(API_DECLARE_EXPORT) +#define API_DECLARE(type) __declspec(dllexport) type __stdcall +#define API_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define API_DECLARE_DATA __declspec(dllexport) +#else +#define API_DECLARE(type) __declspec(dllimport) type __stdcall +#define API_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define API_DECLARE_DATA __declspec(dllimport) +#endif + +/* + * apr_iconv_t: charset conversion descriptor type + */ +typedef void *apr_iconv_t; + +/* __BEGIN_DECLS */ + +/** + * Create a conversion descriptor. + * @param to name of charset to convert to. + * @param from name of charset of the input bytes. + * @param pool pool to alloc memory. + * @param cd conversion descriptor created in pool. + */ +API_DECLARE(apr_status_t) apr_iconv_open(const char *to, const char *from, + apr_pool_t *pool, apr_iconv_t *cd); +/** + * Perform character set conversion. + * @param cd conversion descriptor created by apr_iconv_open(). + * @param inbuf input buffer. + * @param inbytesleft bytes to convert. + * @param outbuf output buffer. + * @param outbytesleft space (in bytes) available in outbuf. + * @param translated number of input bytes converted. + */ +API_DECLARE(apr_status_t) apr_iconv(apr_iconv_t cd, + const char **inbuf, apr_size_t *inbytesleft, + char **outbuf, apr_size_t *outbytesleft, + apr_size_t *translated); +/** + * Deallocate descriptor for character set conversion. + * @param cd conversion descriptor. + * @param pool pool used in the apr_iconv_open(). + */ +API_DECLARE(apr_status_t) apr_iconv_close(apr_iconv_t cd, apr_pool_t *pool); + +/* __END_DECLS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_ICONV_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_inherit.h b/c/dependencies/windows/apr/x86_debug/include/apr_inherit.h new file mode 100644 index 00000000..b9fe56fe --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_inherit.h @@ -0,0 +1,51 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_INHERIT_H +#define APR_INHERIT_H + +/** + * @file apr_inherit.h + * @brief APR File Handle Inheritance Helpers + * @remark This internal header includes internal declaration helpers + * for other headers to declare apr_foo_inherit_[un]set functions. + */ + +/** + * Prototype for type-specific declarations of apr_foo_inherit_set + * functions. + * @remark Doxygen unwraps this macro (via doxygen.conf) to provide + * actual help for each specific occurrence of apr_foo_inherit_set. + * @remark the linkage is specified for APR. It would be possible to expand + * the macros to support other linkages. + */ +#define APR_DECLARE_INHERIT_SET(type) \ + APR_DECLARE(apr_status_t) apr_##type##_inherit_set( \ + apr_##type##_t *the##type) + +/** + * Prototype for type-specific declarations of apr_foo_inherit_unset + * functions. + * @remark Doxygen unwraps this macro (via doxygen.conf) to provide + * actual help for each specific occurrence of apr_foo_inherit_unset. + * @remark the linkage is specified for APR. It would be possible to expand + * the macros to support other linkages. + */ +#define APR_DECLARE_INHERIT_UNSET(type) \ + APR_DECLARE(apr_status_t) apr_##type##_inherit_unset( \ + apr_##type##_t *the##type) + +#endif /* ! APR_INHERIT_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_ldap.h b/c/dependencies/windows/apr/x86_debug/include/apr_ldap.h new file mode 100644 index 00000000..c1bd0d4b --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_ldap.h @@ -0,0 +1,197 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_ldap.h is generated from apr_ldap.h.in by configure -- do not edit apr_ldap.h + */ +/** + * @file apr_ldap.h + * @brief APR-UTIL LDAP + */ +#ifndef APU_LDAP_H +#define APU_LDAP_H + +/** + * @defgroup APR_Util_LDAP LDAP + * @ingroup APR_Util + * @{ + */ + +/* this will be defined if LDAP support was compiled into apr-util */ +#define APR_HAS_LDAP 1 + +/* identify the LDAP toolkit used */ +#define APR_HAS_NETSCAPE_LDAPSDK 0 +#define APR_HAS_SOLARIS_LDAPSDK 0 +#define APR_HAS_NOVELL_LDAPSDK 0 +#define APR_HAS_MOZILLA_LDAPSDK 0 +#define APR_HAS_OPENLDAP_LDAPSDK 0 +#define APR_HAS_MICROSOFT_LDAPSDK 1 +#define APR_HAS_TIVOLI_LDAPSDK 0 +#define APR_HAS_ZOS_LDAPSDK 0 +#define APR_HAS_OTHER_LDAPSDK 0 + + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/* + * The following #defines are DEPRECATED and should not be used for + * anything. They remain to maintain binary compatibility. + * The original code defined the OPENLDAP SDK as present regardless + * of what really was there, which was way bogus. In addition, the + * apr_ldap_url_parse*() functions have been rewritten specifically for + * APR, so the APR_HAS_LDAP_URL_PARSE macro is forced to zero. + */ +#if APR_HAS_TIVOLI_LDAPSDK +#define APR_HAS_LDAP_SSL 0 +#else +#define APR_HAS_LDAP_SSL 1 +#endif +#define APR_HAS_LDAP_URL_PARSE 0 + +#if APR_HAS_OPENLDAP_LDAPSDK && !defined(LDAP_DEPRECATED) +/* Ensure that the "deprecated" interfaces are still exposed + * with OpenLDAP >= 2.3; these were exposed by default in earlier + * releases. */ +#define LDAP_DEPRECATED 1 +#endif + +/* + * Include the standard LDAP header files. + */ + +#include + + +/* + * Detected standard functions + */ +#define APR_HAS_LDAPSSL_CLIENT_INIT 0 +#define APR_HAS_LDAPSSL_CLIENT_DEINIT 0 +#define APR_HAS_LDAPSSL_ADD_TRUSTED_CERT 0 +#define APR_HAS_LDAP_START_TLS_S 0 +#define APR_HAS_LDAP_SSLINIT 1 +#define APR_HAS_LDAPSSL_INIT 0 +#define APR_HAS_LDAPSSL_INSTALL_ROUTINES 0 + + +/* + * Make sure the secure LDAP port is defined + */ +#ifndef LDAPS_PORT +#define LDAPS_PORT 636 /* ldaps:/// default LDAP over TLS port */ +#endif + + +/* + * For ldap function calls that input a size limit on the number of returned elements + * Some SDKs do not have the define for LDAP_DEFAULT_LIMIT (-1) or LDAP_NO_LIMIT (0) + * LDAP_DEFAULT_LIMIT is preferred as it allows inheritance from whatever the SDK + * or process is configured for. + */ +#ifdef LDAP_DEFAULT_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_DEFAULT_LIMIT +#else +#ifdef LDAP_NO_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_NO_LIMIT +#endif +#endif + +#ifndef APR_LDAP_SIZELIMIT +#define APR_LDAP_SIZELIMIT 0 /* equivalent to LDAP_NO_LIMIT, and what goes on the wire */ +#endif + +/* + * z/OS is missing some defines + */ +#ifndef LDAP_VERSION_MAX +#define LDAP_VERSION_MAX LDAP_VERSION +#endif +#if APR_HAS_ZOS_LDAPSDK +#define LDAP_VENDOR_NAME "IBM z/OS" +#endif + +/* Note: Macros defining const casting has been removed in APR v1.0, + * pending real support for LDAP v2.0 toolkits. + * + * In the mean time, please use an LDAP v3.0 toolkit. + */ +#if LDAP_VERSION_MAX <= 2 +#error Support for LDAP v2.0 toolkits has been removed from apr-util. Please use an LDAP v3.0 toolkit. +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * This structure allows the C LDAP API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apr_ldap_err_t { + const char *reason; + const char *msg; + int rc; +} apr_ldap_err_t; + +#ifdef __cplusplus +} +#endif + +/* The MS SDK returns LDAP_UNAVAILABLE when the backend has closed the connection + * between LDAP calls. Protect with APR_HAS_MICROSOFT_LDAPSDK in case someone + * manually chooses another SDK on Windows + */ +#if APR_HAS_MICROSOFT_LDAPSDK +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN \ + || (s) == LDAP_UNAVAILABLE) +#else +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN) +#endif + +/* These symbols are not actually exported in a DSO build, but mapped into + * a private exported function array for apr_ldap_stub to bind dynamically. + * Rename them appropriately to protect the global namespace. + */ +#ifdef APU_DSO_LDAP_BUILD + +#define apr_ldap_info apr__ldap_info +#define apr_ldap_init apr__ldap_init +#define apr_ldap_ssl_init apr__ldap_ssl_init +#define apr_ldap_ssl_deinit apr__ldap_ssl_deinit +#define apr_ldap_get_option apr__ldap_get_option +#define apr_ldap_set_option apr__ldap_set_option +#define apr_ldap_rebind_init apr__ldap_rebind_init +#define apr_ldap_rebind_add apr__ldap_rebind_add +#define apr_ldap_rebind_remove apr__ldap_rebind_remove + +#define APU_DECLARE_LDAP(type) type +#else +#define APU_DECLARE_LDAP(type) APU_DECLARE(type) +#endif + +#include "apr_ldap_url.h" +#include "apr_ldap_init.h" +#include "apr_ldap_option.h" +#include "apr_ldap_rebind.h" + +/** @} */ +#endif /* APR_HAS_LDAP */ +#endif /* APU_LDAP_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_ldap.h.in b/c/dependencies/windows/apr/x86_debug/include/apr_ldap.h.in new file mode 100644 index 00000000..6c62d601 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_ldap.h.in @@ -0,0 +1,197 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_ldap.h is generated from apr_ldap.h.in by configure -- do not edit apr_ldap.h + */ +/** + * @file apr_ldap.h + * @brief APR-UTIL LDAP + */ +#ifndef APU_LDAP_H +#define APU_LDAP_H + +/** + * @defgroup APR_Util_LDAP LDAP + * @ingroup APR_Util + * @{ + */ + +/* this will be defined if LDAP support was compiled into apr-util */ +#define APR_HAS_LDAP @apu_has_ldap@ + +/* identify the LDAP toolkit used */ +#define APR_HAS_NETSCAPE_LDAPSDK @apu_has_ldap_netscape@ +#define APR_HAS_SOLARIS_LDAPSDK @apu_has_ldap_solaris@ +#define APR_HAS_NOVELL_LDAPSDK @apu_has_ldap_novell@ +#define APR_HAS_MOZILLA_LDAPSDK @apu_has_ldap_mozilla@ +#define APR_HAS_OPENLDAP_LDAPSDK @apu_has_ldap_openldap@ +#define APR_HAS_MICROSOFT_LDAPSDK @apu_has_ldap_microsoft@ +#define APR_HAS_TIVOLI_LDAPSDK @apu_has_ldap_tivoli@ +#define APR_HAS_ZOS_LDAPSDK @apu_has_ldap_zos@ +#define APR_HAS_OTHER_LDAPSDK @apu_has_ldap_other@ + + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/* + * The following #defines are DEPRECATED and should not be used for + * anything. They remain to maintain binary compatibility. + * The original code defined the OPENLDAP SDK as present regardless + * of what really was there, which was way bogus. In addition, the + * apr_ldap_url_parse*() functions have been rewritten specifically for + * APR, so the APR_HAS_LDAP_URL_PARSE macro is forced to zero. + */ +#if APR_HAS_TIVOLI_LDAPSDK +#define APR_HAS_LDAP_SSL 0 +#else +#define APR_HAS_LDAP_SSL 1 +#endif +#define APR_HAS_LDAP_URL_PARSE 0 + +#if APR_HAS_OPENLDAP_LDAPSDK && !defined(LDAP_DEPRECATED) +/* Ensure that the "deprecated" interfaces are still exposed + * with OpenLDAP >= 2.3; these were exposed by default in earlier + * releases. */ +#define LDAP_DEPRECATED 1 +#endif + +/* + * Include the standard LDAP header files. + */ + +@lber_h@ +@ldap_h@ +@ldap_ssl_h@ + + +/* + * Detected standard functions + */ +#define APR_HAS_LDAPSSL_CLIENT_INIT @apu_has_ldapssl_client_init@ +#define APR_HAS_LDAPSSL_CLIENT_DEINIT @apu_has_ldapssl_client_deinit@ +#define APR_HAS_LDAPSSL_ADD_TRUSTED_CERT @apu_has_ldapssl_add_trusted_cert@ +#define APR_HAS_LDAP_START_TLS_S @apu_has_ldap_start_tls_s@ +#define APR_HAS_LDAP_SSLINIT @apu_has_ldap_sslinit@ +#define APR_HAS_LDAPSSL_INIT @apu_has_ldapssl_init@ +#define APR_HAS_LDAPSSL_INSTALL_ROUTINES @apu_has_ldapssl_install_routines@ + +/* + * Make sure the secure LDAP port is defined + */ +#ifndef LDAPS_PORT +#define LDAPS_PORT 636 /* ldaps:/// default LDAP over TLS port */ +#endif + +/* + * For ldap function calls that input a size limit on the number of returned elements + * Some SDKs do not have the define for LDAP_DEFAULT_LIMIT (-1) or LDAP_NO_LIMIT (0) + * LDAP_DEFAULT_LIMIT is preferred as it allows inheritance from whatever the SDK + * or process is configured for. + */ +#ifdef LDAP_DEFAULT_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_DEFAULT_LIMIT +#else +#ifdef LDAP_NO_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_NO_LIMIT +#endif +#endif + +#ifndef APR_LDAP_SIZELIMIT +#define APR_LDAP_SIZELIMIT 0 /* equivalent to LDAP_NO_LIMIT, and what goes on the wire */ +#endif + +/* + * z/OS is missing some defines + */ +#ifndef LDAP_VERSION_MAX +#define LDAP_VERSION_MAX LDAP_VERSION +#endif +#if APR_HAS_ZOS_LDAPSDK +#define LDAP_VENDOR_NAME "IBM z/OS" +#endif + +/* Note: Macros defining const casting has been removed in APR v1.0, + * pending real support for LDAP v2.0 toolkits. + * + * In the mean time, please use an LDAP v3.0 toolkit. + */ +#if LDAP_VERSION_MAX <= 2 +#error Support for LDAP v2.0 toolkits has been removed from apr-util. Please use an LDAP v3.0 toolkit. +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * This structure allows the C LDAP API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apr_ldap_err_t { + const char *reason; + const char *msg; + int rc; +} apr_ldap_err_t; + +#ifdef __cplusplus +} +#endif + +/* The MS SDK returns LDAP_UNAVAILABLE when the backend has closed the connection + * between LDAP calls. Protect with APR_HAS_MICROSOFT_LDAPSDK in case someone + * manually chooses another SDK on Windows + */ +#if APR_HAS_MICROSOFT_LDAPSDK +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN \ + || (s) == LDAP_UNAVAILABLE) +#else +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN) +#endif + +/* These symbols are not actually exported in a DSO build, but mapped into + * a private exported function array for apr_ldap_stub to bind dynamically. + * Rename them appropriately to protect the global namespace. + */ +#ifdef APU_DSO_LDAP_BUILD + +#define apr_ldap_info apr__ldap_info +#define apr_ldap_init apr__ldap_init +#define apr_ldap_ssl_init apr__ldap_ssl_init +#define apr_ldap_ssl_deinit apr__ldap_ssl_deinit +#define apr_ldap_get_option apr__ldap_get_option +#define apr_ldap_set_option apr__ldap_set_option +#define apr_ldap_rebind_init apr__ldap_rebind_init +#define apr_ldap_rebind_add apr__ldap_rebind_add +#define apr_ldap_rebind_remove apr__ldap_rebind_remove + +#define APU_DECLARE_LDAP(type) type +#else +#define APU_DECLARE_LDAP(type) APU_DECLARE(type) +#endif + +#include "apr_ldap_url.h" +#include "apr_ldap_init.h" +#include "apr_ldap_option.h" +#include "apr_ldap_rebind.h" + +#endif /* APR_HAS_LDAP */ +/** @} */ +#endif /* APU_LDAP_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_ldap.hnw b/c/dependencies/windows/apr/x86_debug/include/apr_ldap.hnw new file mode 100644 index 00000000..2148c90f --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_ldap.hnw @@ -0,0 +1,158 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_ldap.h is generated from apr_ldap.h.in by configure -- do not edit apr_ldap.h + */ +/** + * @file apr_ldap.h + * @brief APR-UTIL LDAP + */ +#ifndef APU_LDAP_H +#define APU_LDAP_H + +/** + * @defgroup APR_Util_LDAP LDAP + * @ingroup APR_Util + * @{ + */ + +/* this will be defined if LDAP support was compiled into apr-util */ +#define APR_HAS_LDAP 1 + +/* identify the LDAP toolkit used */ +#define APR_HAS_NETSCAPE_LDAPSDK 0 +#define APR_HAS_SOLARIS_LDAPSDK 0 +#define APR_HAS_NOVELL_LDAPSDK 1 +#define APR_HAS_MOZILLA_LDAPSDK 0 +#define APR_HAS_OPENLDAP_LDAPSDK 0 +#define APR_HAS_MICROSOFT_LDAPSDK 0 +#define APR_HAS_OTHER_LDAPSDK 0 + + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/* + * The following #defines are DEPRECATED and should not be used for + * anything. They remain to maintain binary compatibility. + * The original code defined the OPENLDAP SDK as present regardless + * of what really was there, which was way bogus. In addition, the + * apr_ldap_url_parse*() functions have been rewritten specifically for + * APR, so the APR_HAS_LDAP_URL_PARSE macro is forced to zero. + */ +#define APR_HAS_LDAP_SSL 1 +#define APR_HAS_LDAP_URL_PARSE 0 + + +/* + * Include the standard LDAP header files. + */ + +#ifdef GENEXPORTS +#define LDAP_VERSION_MAX 3 +#define LDAP_INSUFFICIENT_ACCESS +#else +#include +#include +#if APR_HAS_LDAP_SSL +#include +#endif +#endif + + +/* + * Detected standard functions + */ +#define APR_HAS_LDAPSSL_CLIENT_INIT 1 +#define APR_HAS_LDAPSSL_CLIENT_DEINIT 1 +#define APR_HAS_LDAPSSL_ADD_TRUSTED_CERT 1 +#define APR_HAS_LDAP_START_TLS_S 0 +#define APR_HAS_LDAP_SSLINIT 0 +#define APR_HAS_LDAPSSL_INIT 1 +#define APR_HAS_LDAPSSL_INSTALL_ROUTINES 0 + + +/* + * Make sure the secure LDAP port is defined + */ +#ifndef LDAPS_PORT +#define LDAPS_PORT 636 /* ldaps:/// default LDAP over TLS port */ +#endif + + +/* Note: Macros defining const casting has been removed in APR v1.0, + * pending real support for LDAP v2.0 toolkits. + * + * In the mean time, please use an LDAP v3.0 toolkit. + */ +#if LDAP_VERSION_MAX <= 2 +#error Support for LDAP v2.0 toolkits has been removed from apr-util. Please use an LDAP v3.0 toolkit. +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * This structure allows the C LDAP API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apr_ldap_err_t { + const char *reason; + const char *msg; + int rc; +} apr_ldap_err_t; + +#ifdef __cplusplus +} +#endif + +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN) + +/* These symbols are not actually exported in a DSO build, but mapped into + * a private exported function array for apr_ldap_stub to bind dynamically. + * Rename them appropriately to protect the global namespace. + */ +#ifdef APU_DSO_LDAP_BUILD + +#define apr_ldap_info apr__ldap_info +#define apr_ldap_init apr__ldap_init +#define apr_ldap_ssl_init apr__ldap_ssl_init +#define apr_ldap_ssl_deinit apr__ldap_ssl_deinit +#define apr_ldap_get_option apr__ldap_get_option +#define apr_ldap_set_option apr__ldap_set_option +#define apr_ldap_rebind_init apr__ldap_rebind_init +#define apr_ldap_rebind_add apr__ldap_rebind_add +#define apr_ldap_rebind_remove apr__ldap_rebind_remove + +#define APU_DECLARE_LDAP(type) type +#else +#define APU_DECLARE_LDAP(type) APU_DECLARE(type) +#endif + +#include "apr_ldap_url.h" +#include "apr_ldap_init.h" +#include "apr_ldap_option.h" +#include "apr_ldap_rebind.h" + +/** @} */ +#endif /* APR_HAS_LDAP */ +#endif /* APU_LDAP_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_ldap.hw b/c/dependencies/windows/apr/x86_debug/include/apr_ldap.hw new file mode 100644 index 00000000..fcef8b17 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_ldap.hw @@ -0,0 +1,197 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_ldap.h is generated from apr_ldap.h.in by configure -- do not edit apr_ldap.h + */ +/** + * @file apr_ldap.h + * @brief APR-UTIL LDAP + */ +#ifndef APU_LDAP_H +#define APU_LDAP_H + +/** + * @defgroup APR_Util_LDAP LDAP + * @ingroup APR_Util + * @{ + */ + +/* this will be defined if LDAP support was compiled into apr-util */ +#define APR_HAS_LDAP 1 + +/* identify the LDAP toolkit used */ +#define APR_HAS_NETSCAPE_LDAPSDK 0 +#define APR_HAS_SOLARIS_LDAPSDK 0 +#define APR_HAS_NOVELL_LDAPSDK 0 +#define APR_HAS_MOZILLA_LDAPSDK 0 +#define APR_HAS_OPENLDAP_LDAPSDK 0 +#define APR_HAS_MICROSOFT_LDAPSDK 1 +#define APR_HAS_TIVOLI_LDAPSDK 0 +#define APR_HAS_ZOS_LDAPSDK 0 +#define APR_HAS_OTHER_LDAPSDK 0 + + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/* + * The following #defines are DEPRECATED and should not be used for + * anything. They remain to maintain binary compatibility. + * The original code defined the OPENLDAP SDK as present regardless + * of what really was there, which was way bogus. In addition, the + * apr_ldap_url_parse*() functions have been rewritten specifically for + * APR, so the APR_HAS_LDAP_URL_PARSE macro is forced to zero. + */ +#if APR_HAS_TIVOLI_LDAPSDK +#define APR_HAS_LDAP_SSL 0 +#else +#define APR_HAS_LDAP_SSL 1 +#endif +#define APR_HAS_LDAP_URL_PARSE 0 + +#if APR_HAS_OPENLDAP_LDAPSDK && !defined(LDAP_DEPRECATED) +/* Ensure that the "deprecated" interfaces are still exposed + * with OpenLDAP >= 2.3; these were exposed by default in earlier + * releases. */ +#define LDAP_DEPRECATED 1 +#endif + +/* + * Include the standard LDAP header files. + */ + +#include + + +/* + * Detected standard functions + */ +#define APR_HAS_LDAPSSL_CLIENT_INIT 0 +#define APR_HAS_LDAPSSL_CLIENT_DEINIT 0 +#define APR_HAS_LDAPSSL_ADD_TRUSTED_CERT 0 +#define APR_HAS_LDAP_START_TLS_S 0 +#define APR_HAS_LDAP_SSLINIT 1 +#define APR_HAS_LDAPSSL_INIT 0 +#define APR_HAS_LDAPSSL_INSTALL_ROUTINES 0 + + +/* + * Make sure the secure LDAP port is defined + */ +#ifndef LDAPS_PORT +#define LDAPS_PORT 636 /* ldaps:/// default LDAP over TLS port */ +#endif + + +/* + * For ldap function calls that input a size limit on the number of returned elements + * Some SDKs do not have the define for LDAP_DEFAULT_LIMIT (-1) or LDAP_NO_LIMIT (0) + * LDAP_DEFAULT_LIMIT is preferred as it allows inheritance from whatever the SDK + * or process is configured for. + */ +#ifdef LDAP_DEFAULT_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_DEFAULT_LIMIT +#else +#ifdef LDAP_NO_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_NO_LIMIT +#endif +#endif + +#ifndef APR_LDAP_SIZELIMIT +#define APR_LDAP_SIZELIMIT 0 /* equivalent to LDAP_NO_LIMIT, and what goes on the wire */ +#endif + +/* + * z/OS is missing some defines + */ +#ifndef LDAP_VERSION_MAX +#define LDAP_VERSION_MAX LDAP_VERSION +#endif +#if APR_HAS_ZOS_LDAPSDK +#define LDAP_VENDOR_NAME "IBM z/OS" +#endif + +/* Note: Macros defining const casting has been removed in APR v1.0, + * pending real support for LDAP v2.0 toolkits. + * + * In the mean time, please use an LDAP v3.0 toolkit. + */ +#if LDAP_VERSION_MAX <= 2 +#error Support for LDAP v2.0 toolkits has been removed from apr-util. Please use an LDAP v3.0 toolkit. +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * This structure allows the C LDAP API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apr_ldap_err_t { + const char *reason; + const char *msg; + int rc; +} apr_ldap_err_t; + +#ifdef __cplusplus +} +#endif + +/* The MS SDK returns LDAP_UNAVAILABLE when the backend has closed the connection + * between LDAP calls. Protect with APR_HAS_MICROSOFT_LDAPSDK in case someone + * manually chooses another SDK on Windows + */ +#if APR_HAS_MICROSOFT_LDAPSDK +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN \ + || (s) == LDAP_UNAVAILABLE) +#else +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN) +#endif + +/* These symbols are not actually exported in a DSO build, but mapped into + * a private exported function array for apr_ldap_stub to bind dynamically. + * Rename them appropriately to protect the global namespace. + */ +#ifdef APU_DSO_LDAP_BUILD + +#define apr_ldap_info apr__ldap_info +#define apr_ldap_init apr__ldap_init +#define apr_ldap_ssl_init apr__ldap_ssl_init +#define apr_ldap_ssl_deinit apr__ldap_ssl_deinit +#define apr_ldap_get_option apr__ldap_get_option +#define apr_ldap_set_option apr__ldap_set_option +#define apr_ldap_rebind_init apr__ldap_rebind_init +#define apr_ldap_rebind_add apr__ldap_rebind_add +#define apr_ldap_rebind_remove apr__ldap_rebind_remove + +#define APU_DECLARE_LDAP(type) type +#else +#define APU_DECLARE_LDAP(type) APU_DECLARE(type) +#endif + +#include "apr_ldap_url.h" +#include "apr_ldap_init.h" +#include "apr_ldap_option.h" +#include "apr_ldap_rebind.h" + +/** @} */ +#endif /* APR_HAS_LDAP */ +#endif /* APU_LDAP_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_ldap.hwc b/c/dependencies/windows/apr/x86_debug/include/apr_ldap.hwc new file mode 100644 index 00000000..4d07b296 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_ldap.hwc @@ -0,0 +1,197 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_ldap.h is generated from apr_ldap.h.in by configure -- do not edit apr_ldap.h + */ +/** + * @file apr_ldap.h + * @brief APR-UTIL LDAP + */ +#ifndef APU_LDAP_H +#define APU_LDAP_H + +/** + * @defgroup APR_Util_LDAP LDAP + * @ingroup APR_Util + * @{ + */ + +/* this will be defined if LDAP support was compiled into apr-util */ +#define APR_HAS_LDAP @apr_has_ldap_10@ + +/* identify the LDAP toolkit used */ +#define APR_HAS_NETSCAPE_LDAPSDK 0 +#define APR_HAS_SOLARIS_LDAPSDK 0 +#define APR_HAS_NOVELL_LDAPSDK 0 +#define APR_HAS_MOZILLA_LDAPSDK 0 +#define APR_HAS_OPENLDAP_LDAPSDK 0 +#define APR_HAS_MICROSOFT_LDAPSDK 1 +#define APR_HAS_TIVOLI_LDAPSDK 0 +#define APR_HAS_ZOS_LDAPSDK 0 +#define APR_HAS_OTHER_LDAPSDK 0 + + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/* + * The following #defines are DEPRECATED and should not be used for + * anything. They remain to maintain binary compatibility. + * The original code defined the OPENLDAP SDK as present regardless + * of what really was there, which was way bogus. In addition, the + * apr_ldap_url_parse*() functions have been rewritten specifically for + * APR, so the APR_HAS_LDAP_URL_PARSE macro is forced to zero. + */ +#if APR_HAS_TIVOLI_LDAPSDK +#define APR_HAS_LDAP_SSL 0 +#else +#define APR_HAS_LDAP_SSL 1 +#endif +#define APR_HAS_LDAP_URL_PARSE 0 + +#if APR_HAS_OPENLDAP_LDAPSDK && !defined(LDAP_DEPRECATED) +/* Ensure that the "deprecated" interfaces are still exposed + * with OpenLDAP >= 2.3; these were exposed by default in earlier + * releases. */ +#define LDAP_DEPRECATED 1 +#endif + +/* + * Include the standard LDAP header files. + */ + +#include + + +/* + * Detected standard functions + */ +#define APR_HAS_LDAPSSL_CLIENT_INIT 0 +#define APR_HAS_LDAPSSL_CLIENT_DEINIT 0 +#define APR_HAS_LDAPSSL_ADD_TRUSTED_CERT 0 +#define APR_HAS_LDAP_START_TLS_S 0 +#define APR_HAS_LDAP_SSLINIT 1 +#define APR_HAS_LDAPSSL_INIT 0 +#define APR_HAS_LDAPSSL_INSTALL_ROUTINES 0 + + +/* + * Make sure the secure LDAP port is defined + */ +#ifndef LDAPS_PORT +#define LDAPS_PORT 636 /* ldaps:/// default LDAP over TLS port */ +#endif + + +/* + * For ldap function calls that input a size limit on the number of returned elements + * Some SDKs do not have the define for LDAP_DEFAULT_LIMIT (-1) or LDAP_NO_LIMIT (0) + * LDAP_DEFAULT_LIMIT is preferred as it allows inheritance from whatever the SDK + * or process is configured for. + */ +#ifdef LDAP_DEFAULT_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_DEFAULT_LIMIT +#else +#ifdef LDAP_NO_LIMIT +#define APR_LDAP_SIZELIMIT LDAP_NO_LIMIT +#endif +#endif + +#ifndef APR_LDAP_SIZELIMIT +#define APR_LDAP_SIZELIMIT 0 /* equivalent to LDAP_NO_LIMIT, and what goes on the wire */ +#endif + +/* + * z/OS is missing some defines + */ +#ifndef LDAP_VERSION_MAX +#define LDAP_VERSION_MAX LDAP_VERSION +#endif +#if APR_HAS_ZOS_LDAPSDK +#define LDAP_VENDOR_NAME "IBM z/OS" +#endif + +/* Note: Macros defining const casting has been removed in APR v1.0, + * pending real support for LDAP v2.0 toolkits. + * + * In the mean time, please use an LDAP v3.0 toolkit. + */ +#if LDAP_VERSION_MAX <= 2 +#error Support for LDAP v2.0 toolkits has been removed from apr-util. Please use an LDAP v3.0 toolkit. +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * This structure allows the C LDAP API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apr_ldap_err_t { + const char *reason; + const char *msg; + int rc; +} apr_ldap_err_t; + +#ifdef __cplusplus +} +#endif + +/* The MS SDK returns LDAP_UNAVAILABLE when the backend has closed the connection + * between LDAP calls. Protect with APR_HAS_MICROSOFT_LDAPSDK in case someone + * manually chooses another SDK on Windows + */ +#if APR_HAS_MICROSOFT_LDAPSDK +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN \ + || (s) == LDAP_UNAVAILABLE) +#else +#define APR_LDAP_IS_SERVER_DOWN(s) ((s) == LDAP_SERVER_DOWN) +#endif + +/* These symbols are not actually exported in a DSO build, but mapped into + * a private exported function array for apr_ldap_stub to bind dynamically. + * Rename them appropriately to protect the global namespace. + */ +#ifdef APU_DSO_LDAP_BUILD + +#define apr_ldap_info apr__ldap_info +#define apr_ldap_init apr__ldap_init +#define apr_ldap_ssl_init apr__ldap_ssl_init +#define apr_ldap_ssl_deinit apr__ldap_ssl_deinit +#define apr_ldap_get_option apr__ldap_get_option +#define apr_ldap_set_option apr__ldap_set_option +#define apr_ldap_rebind_init apr__ldap_rebind_init +#define apr_ldap_rebind_add apr__ldap_rebind_add +#define apr_ldap_rebind_remove apr__ldap_rebind_remove + +#define APU_DECLARE_LDAP(type) type +#else +#define APU_DECLARE_LDAP(type) APU_DECLARE(type) +#endif + +#include "apr_ldap_url.h" +#include "apr_ldap_init.h" +#include "apr_ldap_option.h" +#include "apr_ldap_rebind.h" + +/** @} */ +#endif /* APR_HAS_LDAP */ +#endif /* APU_LDAP_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_ldap_init.h b/c/dependencies/windows/apr/x86_debug/include/apr_ldap_init.h new file mode 100644 index 00000000..aeb6d9bb --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_ldap_init.h @@ -0,0 +1,165 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_ldap_init.h + * @brief APR-UTIL LDAP ldap_init() functions + */ +#ifndef APR_LDAP_INIT_H +#define APR_LDAP_INIT_H + +/** + * @addtogroup APR_Util_LDAP + * @{ + */ + +#include "apr_ldap.h" + +#if APR_HAS_LDAP + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + + +/** + * Macro to detect security related return values. + */ +#if defined(LDAP_INSUFFICIENT_ACCESS) +#define APU_LDAP_INSUFFICIENT_ACCESS LDAP_INSUFFICIENT_ACCESS +#elif defined(LDAP_INSUFFICIENT_RIGHTS) +#define APU_LDAP_INSUFFICIENT_ACCESS LDAP_INSUFFICIENT_RIGHTS +#elif defined(APR_HAS_MICROSOFT_LDAPSDK) +/* The macros above fail to contemplate that LDAP_RETCODE values + * may be represented by an enum. autoconf tests would be much + * more robust. + */ +#define APU_LDAP_INSUFFICIENT_ACCESS LDAP_INSUFFICIENT_RIGHTS +#else +#error The security return codes must be added to support this LDAP toolkit. +#endif + +#if defined(LDAP_SECURITY_ERROR) +#define APU_LDAP_SECURITY_ERROR LDAP_SECURITY_ERROR +#else +#define APU_LDAP_SECURITY_ERROR(n) \ + (LDAP_INAPPROPRIATE_AUTH == n) ? 1 \ + : (LDAP_INVALID_CREDENTIALS == n) ? 1 \ + : (APU_LDAP_INSUFFICIENT_ACCESS == n) ? 1 \ + : 0 +#endif + + +/** + * APR LDAP SSL Initialise function + * + * This function initialises SSL on the underlying LDAP toolkit + * if this is necessary. + * + * If a CA certificate is provided, this is set, however the setting + * of certificates via this method has been deprecated and will be removed in + * APR v2.0. + * + * The apr_ldap_set_option() function with the APR_LDAP_OPT_TLS_CERT option + * should be used instead to set certificates. + * + * If SSL support is not available on this platform, or a problem + * was encountered while trying to set the certificate, the function + * will return APR_EGENERAL. Further LDAP specific error information + * can be found in result_err. + * @param pool The pool to use + * @param cert_auth_file The name of the certificate to use, can be NULL + * @param cert_file_type The type of certificate specified. See the + * apr_ldap_set_option() APR_LDAP_OPT_TLS_CERT option for details. + * @param result_err The returned result + */ +APU_DECLARE_LDAP(int) apr_ldap_ssl_init(apr_pool_t *pool, + const char *cert_auth_file, + int cert_file_type, + apr_ldap_err_t **result_err); + +/** + * APR LDAP SSL De-Initialise function + * + * This function tears down any SSL certificate setup previously + * set using apr_ldap_ssl_init(). It should be called to clean + * up if a graceful restart of a service is attempted. + * @todo currently we do not check whether apr_ldap_ssl_init() + * has been called first - we probably should. + */ +APU_DECLARE_LDAP(int) apr_ldap_ssl_deinit(void); + +/** + * APR LDAP initialise function + * + * This function is responsible for initialising an LDAP + * connection in a toolkit independant way. It does the + * job of ldap_init() from the C api. + * + * It handles both the SSL and non-SSL case, and attempts + * to hide the complexity setup from the user. This function + * assumes that any certificate setup necessary has already + * been done. + * + * If SSL or STARTTLS needs to be enabled, and the underlying + * toolkit supports it, the following values are accepted for + * secure: + * + * APR_LDAP_NONE: No encryption + * APR_LDAP_SSL: SSL encryption (ldaps://) + * APR_LDAP_STARTTLS: Force STARTTLS on ldap:// + * @remark The Novell toolkit is only able to set the SSL mode via this + * function. To work around this limitation, set the SSL mode here if no + * per connection client certificates are present, otherwise set secure + * APR_LDAP_NONE here, then set the per connection client certificates, + * followed by setting the SSL mode via apr_ldap_set_option(). As Novell + * does not support per connection client certificates, this problem is + * worked around while still being compatible with other LDAP toolkits. + * @param pool The pool to use + * @param ldap The LDAP handle + * @param hostname The name of the host to connect to. This can be either a + * DNS name, or an IP address. + * @param portno The port to connect to + * @param secure The security mode to set + * @param result_err The returned result + */ +APU_DECLARE_LDAP(int) apr_ldap_init(apr_pool_t *pool, + LDAP **ldap, + const char *hostname, + int portno, + int secure, + apr_ldap_err_t **result_err); + +/** + * APR LDAP info function + * + * This function returns a string describing the LDAP toolkit + * currently in use. The string is placed inside result_err->reason. + * @param pool The pool to use + * @param result_err The returned result + */ +APU_DECLARE_LDAP(int) apr_ldap_info(apr_pool_t *pool, + apr_ldap_err_t **result_err); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_HAS_LDAP */ + +/** @} */ + +#endif /* APR_LDAP_URL_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_ldap_option.h b/c/dependencies/windows/apr/x86_debug/include/apr_ldap_option.h new file mode 100644 index 00000000..0ff8a862 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_ldap_option.h @@ -0,0 +1,254 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_ldap_option.h + * @brief APR-UTIL LDAP ldap_*_option() functions + */ +#ifndef APR_LDAP_OPTION_H +#define APR_LDAP_OPTION_H + +/** + * @addtogroup APR_Util_LDAP + * @{ + */ + +#include "apr_ldap.h" + +#if APR_HAS_LDAP + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* + * The following defines handle the different TLS certificate + * options available. If these options are missing, APR will try and + * emulate support for this using the deprecated ldap_start_tls_s() + * function. + */ +/** + * Set SSL mode to one of APR_LDAP_NONE, APR_LDAP_SSL, APR_LDAP_STARTTLS + * or APR_LDAP_STOPTLS. + */ +#define APR_LDAP_OPT_TLS 0x6fff +/** + * Set zero or more CA certificates, client certificates or private + * keys globally, or per connection (where supported). + */ +#define APR_LDAP_OPT_TLS_CERT 0x6ffe +/** + * Set the LDAP library to no verify the server certificate. This means + * all servers are considered trusted. + */ +#define APR_LDAP_OPT_VERIFY_CERT 0x6ffd +/** + * Set the LDAP library to indicate if referrals should be chased during + * LDAP searches. + */ +#define APR_LDAP_OPT_REFERRALS 0x6ffc +/** + * Set the LDAP library to indicate a maximum number of referral hops to + * chase before giving up on the search. + */ +#define APR_LDAP_OPT_REFHOPLIMIT 0x6ffb + +/** + * Structures for the apr_set_option() cases + */ + +/** + * APR_LDAP_OPT_TLS_CERT + * + * This structure includes possible options to set certificates on + * system initialisation. Different SDKs have different certificate + * requirements, and to achieve this multiple certificates must be + * specified at once passed as an (apr_array_header_t *). + * + * Netscape: + * Needs the CA cert database (cert7.db), the client cert database (key3.db) + * and the security module file (secmod.db) set at the system initialisation + * time. Three types are supported: APR_LDAP_CERT7_DB, APR_LDAP_KEY3_DB and + * APR_LDAP_SECMOD. + * + * To specify a client cert connection, a certificate nickname needs to be + * provided with a type of APR_LDAP_CERT. + * int ldapssl_enable_clientauth( LDAP *ld, char *keynickname, + * char *keypasswd, char *certnickname ); + * keynickname is currently not used, and should be set to "" + * + * Novell: + * Needs CA certificates and client certificates set at system initialisation + * time. Three types are supported: APR_LDAP_CA*, APR_LDAP_CERT* and + * APR_LDAP_KEY*. + * + * Certificates cannot be specified per connection. + * + * The functions used are: + * ldapssl_add_trusted_cert(serverTrustedRoot, serverTrustedRootEncoding); + * Clients certs and keys are set at system initialisation time with + * int ldapssl_set_client_cert ( + * void *cert, + * int type + * void *password); + * type can be LDAPSSL_CERT_FILETYPE_B64 or LDAPSSL_CERT_FILETYPE_DER + * ldapssl_set_client_private_key(clientPrivateKey, + * clientPrivateKeyEncoding, + * clientPrivateKeyPassword); + * + * OpenSSL: + * Needs one or more CA certificates to be set at system initialisation time + * with a type of APR_LDAP_CA*. + * + * May have one or more client certificates set per connection with a type of + * APR_LDAP_CERT*, and keys with APR_LDAP_KEY*. + */ +/** CA certificate type unknown */ +#define APR_LDAP_CA_TYPE_UNKNOWN 0 +/** binary DER encoded CA certificate */ +#define APR_LDAP_CA_TYPE_DER 1 +/** PEM encoded CA certificate */ +#define APR_LDAP_CA_TYPE_BASE64 2 +/** Netscape/Mozilla cert7.db CA certificate database */ +#define APR_LDAP_CA_TYPE_CERT7_DB 3 +/** Netscape/Mozilla secmod file */ +#define APR_LDAP_CA_TYPE_SECMOD 4 +/** Client certificate type unknown */ +#define APR_LDAP_CERT_TYPE_UNKNOWN 5 +/** binary DER encoded client certificate */ +#define APR_LDAP_CERT_TYPE_DER 6 +/** PEM encoded client certificate */ +#define APR_LDAP_CERT_TYPE_BASE64 7 +/** Netscape/Mozilla key3.db client certificate database */ +#define APR_LDAP_CERT_TYPE_KEY3_DB 8 +/** Netscape/Mozilla client certificate nickname */ +#define APR_LDAP_CERT_TYPE_NICKNAME 9 +/** Private key type unknown */ +#define APR_LDAP_KEY_TYPE_UNKNOWN 10 +/** binary DER encoded private key */ +#define APR_LDAP_KEY_TYPE_DER 11 +/** PEM encoded private key */ +#define APR_LDAP_KEY_TYPE_BASE64 12 +/** PKCS#12 encoded client certificate */ +#define APR_LDAP_CERT_TYPE_PFX 13 +/** PKCS#12 encoded private key */ +#define APR_LDAP_KEY_TYPE_PFX 14 +/** Openldap directory full of base64-encoded cert + * authorities with hashes in corresponding .0 directory + */ +#define APR_LDAP_CA_TYPE_CACERTDIR_BASE64 15 + + +/** + * Certificate structure. + * + * This structure is used to store certificate details. An array of + * these structures is passed to apr_ldap_set_option() to set CA + * and client certificates. + * @param type Type of certificate APR_LDAP_*_TYPE_* + * @param path Path, file or nickname of the certificate + * @param password Optional password, can be NULL + */ +typedef struct apr_ldap_opt_tls_cert_t apr_ldap_opt_tls_cert_t; +struct apr_ldap_opt_tls_cert_t { + int type; + const char *path; + const char *password; +}; + +/** + * APR_LDAP_OPT_TLS + * + * This sets the SSL level on the LDAP handle. + * + * Netscape/Mozilla: + * Supports SSL, but not STARTTLS + * SSL is enabled by calling ldapssl_install_routines(). + * + * Novell: + * Supports SSL and STARTTLS. + * SSL is enabled by calling ldapssl_install_routines(). Note that calling + * other ldap functions before ldapssl_install_routines() may cause this + * function to fail. + * STARTTLS is enabled by calling ldapssl_start_tls_s() after calling + * ldapssl_install_routines() (check this). + * + * OpenLDAP: + * Supports SSL and supports STARTTLS, but none of this is documented: + * http://www.openldap.org/lists/openldap-software/200409/msg00618.html + * Documentation for both SSL support and STARTTLS has been deleted from + * the OpenLDAP documentation and website. + */ + +/** No encryption */ +#define APR_LDAP_NONE 0 +/** SSL encryption (ldaps://) */ +#define APR_LDAP_SSL 1 +/** TLS encryption (STARTTLS) */ +#define APR_LDAP_STARTTLS 2 +/** end TLS encryption (STOPTLS) */ +#define APR_LDAP_STOPTLS 3 + +/** + * APR LDAP get option function + * + * This function gets option values from a given LDAP session if + * one was specified. It maps to the native ldap_get_option() function. + * @param pool The pool to use + * @param ldap The LDAP handle + * @param option The LDAP_OPT_* option to return + * @param outvalue The value returned (if any) + * @param result_err The apr_ldap_err_t structure contained detailed results + * of the operation. + */ +APU_DECLARE_LDAP(int) apr_ldap_get_option(apr_pool_t *pool, + LDAP *ldap, + int option, + void *outvalue, + apr_ldap_err_t **result_err); + +/** + * APR LDAP set option function + * + * This function sets option values to a given LDAP session if + * one was specified. It maps to the native ldap_set_option() function. + * + * Where an option is not supported by an LDAP toolkit, this function + * will try and apply legacy functions to achieve the same effect, + * depending on the platform. + * @param pool The pool to use + * @param ldap The LDAP handle + * @param option The LDAP_OPT_* option to set + * @param invalue The value to set + * @param result_err The apr_ldap_err_t structure contained detailed results + * of the operation. + */ +APU_DECLARE_LDAP(int) apr_ldap_set_option(apr_pool_t *pool, + LDAP *ldap, + int option, + const void *invalue, + apr_ldap_err_t **result_err); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_HAS_LDAP */ + +/** @} */ + +#endif /* APR_LDAP_OPTION_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_ldap_rebind.h b/c/dependencies/windows/apr/x86_debug/include/apr_ldap_rebind.h new file mode 100644 index 00000000..342a17c3 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_ldap_rebind.h @@ -0,0 +1,98 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The APR LDAP rebind functions provide an implementation of + * a rebind procedure that can be used to allow clients to chase referrals, + * using the same credentials used to log in originally. + * + * Use of this implementation is optional. + * + * @file apr_ldap_rebind.h + * @brief Apache LDAP library + */ + +#ifndef APU_LDAP_REBIND_H +#define APU_LDAP_REBIND_H + +/** + * @addtogroup APR_Util_LDAP + * @{ + **/ + +#if defined(DOXYGEN) +#include "apr_ldap.h" +#endif + +/* + * Handle the case when LDAP is enabled + */ +#if APR_HAS_LDAP + +/** + * APR LDAP initialize rebind lock + * + * This function creates the lock for controlling access to the xref list.. + * @param pool Pool to use when creating the xref_lock. + */ +APU_DECLARE_LDAP(apr_status_t) apr_ldap_rebind_init(apr_pool_t *pool); + + +/** + * APR LDAP rebind_add function + * + * This function creates a cross reference entry for the specified ldap + * connection. The rebind callback function will look up this ldap + * connection so it can retrieve the bindDN and bindPW for use in any + * binds while referrals are being chased. + * + * This function will add the callback to the LDAP handle passed in. + * + * A cleanup is registered within the pool provided to remove this + * entry when the pool is removed. Alternatively apr_ldap_rebind_remove() + * can be called to explicitly remove the entry at will. + * + * @param pool The pool to use + * @param ld The LDAP connectionhandle + * @param bindDN The bind DN to be used for any binds while chasing + * referrals on this ldap connection. + * @param bindPW The bind Password to be used for any binds while + * chasing referrals on this ldap connection. + */ +APU_DECLARE_LDAP(apr_status_t) apr_ldap_rebind_add(apr_pool_t *pool, + LDAP *ld, + const char *bindDN, + const char *bindPW); + +/** + * APR LDAP rebind_remove function + * + * This function removes the rebind cross reference entry for the + * specified ldap connection. + * + * If not explicitly removed, this function will be called automatically + * when the pool is cleaned up. + * + * @param ld The LDAP connectionhandle + */ +APU_DECLARE_LDAP(apr_status_t) apr_ldap_rebind_remove(LDAP *ld); + +#endif /* APR_HAS_LDAP */ + +/** @} */ + +#endif /* APU_LDAP_REBIND_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_ldap_url.h b/c/dependencies/windows/apr/x86_debug/include/apr_ldap_url.h new file mode 100644 index 00000000..a71f5b3c --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_ldap_url.h @@ -0,0 +1,120 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_ldap_url.h + * @brief APR-UTIL LDAP ldap_init() functions + */ +#ifndef APR_LDAP_URL_H +#define APR_LDAP_URL_H + +/** + * @addtogroup APR_Util_LDAP + * @{ + */ + +#if defined(DOXYGEN) +#include "apr_ldap.h" +#endif + +#if APR_HAS_LDAP + +#include "apu.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** Structure to access an exploded LDAP URL */ +typedef struct apr_ldap_url_desc_t { + struct apr_ldap_url_desc_t *lud_next; + char *lud_scheme; + char *lud_host; + int lud_port; + char *lud_dn; + char **lud_attrs; + int lud_scope; + char *lud_filter; + char **lud_exts; + int lud_crit_exts; +} apr_ldap_url_desc_t; + +#ifndef APR_LDAP_URL_SUCCESS +#define APR_LDAP_URL_SUCCESS 0x00 /* Success */ +#define APR_LDAP_URL_ERR_MEM 0x01 /* can't allocate memory space */ +#define APR_LDAP_URL_ERR_PARAM 0x02 /* parameter is bad */ +#define APR_LDAP_URL_ERR_BADSCHEME 0x03 /* URL doesn't begin with "ldap[si]://" */ +#define APR_LDAP_URL_ERR_BADENCLOSURE 0x04 /* URL is missing trailing ">" */ +#define APR_LDAP_URL_ERR_BADURL 0x05 /* URL is bad */ +#define APR_LDAP_URL_ERR_BADHOST 0x06 /* host port is bad */ +#define APR_LDAP_URL_ERR_BADATTRS 0x07 /* bad (or missing) attributes */ +#define APR_LDAP_URL_ERR_BADSCOPE 0x08 /* scope string is invalid (or missing) */ +#define APR_LDAP_URL_ERR_BADFILTER 0x09 /* bad or missing filter */ +#define APR_LDAP_URL_ERR_BADEXTS 0x0a /* bad or missing extensions */ +#endif + +/** + * Is this URL an ldap url? ldap:// + * @param url The url to test + */ +APU_DECLARE(int) apr_ldap_is_ldap_url(const char *url); + +/** + * Is this URL an SSL ldap url? ldaps:// + * @param url The url to test + */ +APU_DECLARE(int) apr_ldap_is_ldaps_url(const char *url); + +/** + * Is this URL an ldap socket url? ldapi:// + * @param url The url to test + */ +APU_DECLARE(int) apr_ldap_is_ldapi_url(const char *url); + +/** + * Parse an LDAP URL. + * @param pool The pool to use + * @param url_in The URL to parse + * @param ludpp The structure to return the exploded URL + * @param result_err The result structure of the operation + */ +APU_DECLARE(int) apr_ldap_url_parse_ext(apr_pool_t *pool, + const char *url_in, + apr_ldap_url_desc_t **ludpp, + apr_ldap_err_t **result_err); + +/** + * Parse an LDAP URL. + * @param pool The pool to use + * @param url_in The URL to parse + * @param ludpp The structure to return the exploded URL + * @param result_err The result structure of the operation + */ +APU_DECLARE(int) apr_ldap_url_parse(apr_pool_t *pool, + const char *url_in, + apr_ldap_url_desc_t **ludpp, + apr_ldap_err_t **result_err); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_HAS_LDAP */ + +/** @} */ + +#endif /* APR_LDAP_URL_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_lib.h b/c/dependencies/windows/apr/x86_debug/include/apr_lib.h new file mode 100644 index 00000000..466e8185 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_lib.h @@ -0,0 +1,241 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_LIB_H +#define APR_LIB_H + +/** + * @file apr_lib.h + * This is collection of oddballs that didn't fit anywhere else, + * and might move to more appropriate headers with the release + * of APR 1.0. + * @brief APR general purpose library routines + */ + +#include "apr.h" +#include "apr_errno.h" + +#if APR_HAVE_CTYPE_H +#include +#endif +#if APR_HAVE_STDARG_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_lib General Purpose Library Routines + * @ingroup APR + * This is collection of oddballs that didn't fit anywhere else, + * and might move to more appropriate headers with the release + * of APR 1.0. + * @{ + */ + +/** A constant representing a 'large' string. */ +#define HUGE_STRING_LEN 8192 + +/* + * Define the structures used by the APR general-purpose library. + */ + +/** @see apr_vformatter_buff_t */ +typedef struct apr_vformatter_buff_t apr_vformatter_buff_t; + +/** + * Structure used by the variable-formatter routines. + */ +struct apr_vformatter_buff_t { + /** The current position */ + char *curpos; + /** The end position of the format string */ + char *endpos; +}; + +/** + * return the final element of the pathname + * @param pathname The path to get the final element of + * @return the final element of the path + * @remark + *
+ * For example:
+ *                 "/foo/bar/gum"    -> "gum"
+ *                 "/foo/bar/gum/"   -> ""
+ *                 "gum"             -> "gum"
+ *                 "bs\\path\\stuff" -> "stuff"
+ * 
+ */ +APR_DECLARE(const char *) apr_filepath_name_get(const char *pathname); + +/** + * apr_killpg + * Small utility macros to make things easier to read. Not usually a + * goal, to be sure.. + */ + +#ifdef WIN32 +#define apr_killpg(x, y) +#else /* WIN32 */ +#ifdef NO_KILLPG +#define apr_killpg(x, y) (kill (-(x), (y))) +#else /* NO_KILLPG */ +#define apr_killpg(x, y) (killpg ((x), (y))) +#endif /* NO_KILLPG */ +#endif /* WIN32 */ + +/** + * apr_vformatter() is a generic printf-style formatting routine + * with some extensions. + * @param flush_func The function to call when the buffer is full + * @param c The buffer to write to + * @param fmt The format string + * @param ap The arguments to use to fill out the format string. + * + * @remark + *
+ * The extensions are:
+ *
+ * - %%pA takes a struct in_addr *, and prints it as a.b.c.d
+ * - %%pI takes an apr_sockaddr_t * and prints it as a.b.c.d:port or
+ * \[ipv6-address\]:port
+ * - %%pT takes an apr_os_thread_t * and prints it in decimal
+ * ('0' is printed if !APR_HAS_THREADS)
+ * - %%pt takes an apr_os_thread_t * and prints it in hexadecimal
+ * ('0' is printed if !APR_HAS_THREADS)
+ * - %%pm takes an apr_status_t * and prints the appropriate error
+ * string (from apr_strerror) corresponding to that error code.
+ * - %%pp takes a void * and outputs it in hex
+ * - %%pB takes a apr_uint32_t * as bytes and outputs it's apr_strfsize
+ * - %%pF same as above, but takes a apr_off_t *
+ * - %%pS same as above, but takes a apr_size_t *
+ *
+ * %%pA, %%pI, %%pT, %%pp are available from APR 1.0.0 onwards (and in 0.9.x).
+ * %%pt is only available from APR 1.2.0 onwards.
+ * %%pm, %%pB, %%pF and %%pS are only available from APR 1.3.0 onwards.
+ *
+ * The %%p hacks are to force gcc's printf warning code to skip
+ * over a pointer argument without complaining.  This does
+ * mean that the ANSI-style %%p (output a void * in hex format) won't
+ * work as expected at all, but that seems to be a fair trade-off
+ * for the increased robustness of having printf-warnings work.
+ *
+ * Additionally, apr_vformatter allows for arbitrary output methods
+ * using the apr_vformatter_buff and flush_func.
+ *
+ * The apr_vformatter_buff has two elements curpos and endpos.
+ * curpos is where apr_vformatter will write the next byte of output.
+ * It proceeds writing output to curpos, and updating curpos, until
+ * either the end of output is reached, or curpos == endpos (i.e. the
+ * buffer is full).
+ *
+ * If the end of output is reached, apr_vformatter returns the
+ * number of bytes written.
+ *
+ * When the buffer is full, the flush_func is called.  The flush_func
+ * can return -1 to indicate that no further output should be attempted,
+ * and apr_vformatter will return immediately with -1.  Otherwise
+ * the flush_func should flush the buffer in whatever manner is
+ * appropriate, re apr_pool_t nitialize curpos and endpos, and return 0.
+ *
+ * Note that flush_func is only invoked as a result of attempting to
+ * write another byte at curpos when curpos >= endpos.  So for
+ * example, it's possible when the output exactly matches the buffer
+ * space available that curpos == endpos will be true when
+ * apr_vformatter returns.
+ *
+ * apr_vformatter does not call out to any other code, it is entirely
+ * self-contained.  This allows the callers to do things which are
+ * otherwise "unsafe".  For example, apr_psprintf uses the "scratch"
+ * space at the unallocated end of a block, and doesn't actually
+ * complete the allocation until apr_vformatter returns.  apr_psprintf
+ * would be completely broken if apr_vformatter were to call anything
+ * that used this same pool.  Similarly http_bprintf() uses the "scratch"
+ * space at the end of its output buffer, and doesn't actually note
+ * that the space is in use until it either has to flush the buffer
+ * or until apr_vformatter returns.
+ * 
+ */ +APR_DECLARE(int) apr_vformatter(int (*flush_func)(apr_vformatter_buff_t *b), + apr_vformatter_buff_t *c, const char *fmt, + va_list ap); + +/** + * Display a prompt and read in the password from stdin. + * @param prompt The prompt to display + * @param pwbuf Buffer to store the password + * @param bufsize The length of the password buffer. + * @remark If the password entered must be truncated to fit in + * the provided buffer, APR_ENAMETOOLONG will be returned. + * Note that the bufsize paramater is passed by reference for no + * reason; its value will never be modified by the apr_password_get() + * function. + */ +APR_DECLARE(apr_status_t) apr_password_get(const char *prompt, char *pwbuf, + apr_size_t *bufsize); + +/** @} */ + +/** + * @defgroup apr_ctype ctype functions + * These macros allow correct support of 8-bit characters on systems which + * support 8-bit characters. Pretty dumb how the cast is required, but + * that's legacy libc for ya. These new macros do not support EOF like + * the standard macros do. Tough. + * @{ + */ +/** @see isalnum */ +#define apr_isalnum(c) (isalnum(((unsigned char)(c)))) +/** @see isalpha */ +#define apr_isalpha(c) (isalpha(((unsigned char)(c)))) +/** @see iscntrl */ +#define apr_iscntrl(c) (iscntrl(((unsigned char)(c)))) +/** @see isdigit */ +#define apr_isdigit(c) (isdigit(((unsigned char)(c)))) +/** @see isgraph */ +#define apr_isgraph(c) (isgraph(((unsigned char)(c)))) +/** @see islower*/ +#define apr_islower(c) (islower(((unsigned char)(c)))) +/** @see isascii */ +#ifdef isascii +#define apr_isascii(c) (isascii(((unsigned char)(c)))) +#else +#define apr_isascii(c) (((c) & ~0x7f)==0) +#endif +/** @see isprint */ +#define apr_isprint(c) (isprint(((unsigned char)(c)))) +/** @see ispunct */ +#define apr_ispunct(c) (ispunct(((unsigned char)(c)))) +/** @see isspace */ +#define apr_isspace(c) (isspace(((unsigned char)(c)))) +/** @see isupper */ +#define apr_isupper(c) (isupper(((unsigned char)(c)))) +/** @see isxdigit */ +#define apr_isxdigit(c) (isxdigit(((unsigned char)(c)))) +/** @see tolower */ +#define apr_tolower(c) (tolower(((unsigned char)(c)))) +/** @see toupper */ +#define apr_toupper(c) (toupper(((unsigned char)(c)))) + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_LIB_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_md4.h b/c/dependencies/windows/apr/x86_debug/include/apr_md4.h new file mode 100644 index 00000000..43fb33e3 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_md4.h @@ -0,0 +1,135 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* This is derived from material copyright RSA Data Security, Inc. + * Their notice is reproduced below in its entirety. + * + * Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All + * rights reserved. + * + * License to copy and use this software is granted provided that it + * is identified as the "RSA Data Security, Inc. MD4 Message-Digest + * Algorithm" in all material mentioning or referencing this software + * or this function. + * + * License is also granted to make and use derivative works provided + * that such works are identified as "derived from the RSA Data + * Security, Inc. MD4 Message-Digest Algorithm" in all material + * mentioning or referencing the derived work. + * + * RSA Data Security, Inc. makes no representations concerning either + * the merchantability of this software or the suitability of this + * software for any particular purpose. It is provided "as is" + * without express or implied warranty of any kind. + * + * These notices must be retained in any copies of any part of this + * documentation and/or software. + */ + +#ifndef APR_MD4_H +#define APR_MD4_H + +#include "apu.h" +#include "apr_xlate.h" +/** + * @file apr_md4.h + * @brief APR-UTIL MD4 Library + */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_MD4 MD4 Library + * @ingroup APR_Util + * @{ + */ + +/** The digestsize for MD4 */ +#define APR_MD4_DIGESTSIZE 16 + +/** @see apr_md4_ctx_t */ +typedef struct apr_md4_ctx_t apr_md4_ctx_t; + +/** MD4 context. */ +struct apr_md4_ctx_t { + /** state (ABCD) */ + apr_uint32_t state[4]; + /** number of bits, modulo 2^64 (lsb first) */ + apr_uint32_t count[2]; + /** input buffer */ + unsigned char buffer[64]; +#if APR_HAS_XLATE + /** translation handle */ + apr_xlate_t *xlate; +#endif +}; + +/** + * MD4 Initialize. Begins an MD4 operation, writing a new context. + * @param context The MD4 context to initialize. + */ +APU_DECLARE(apr_status_t) apr_md4_init(apr_md4_ctx_t *context); + +#if APR_HAS_XLATE +/** + * MDr4 translation setup. Provides the APR translation handle to be used + * for translating the content before calculating the digest. + * @param context The MD4 content to set the translation for. + * @param xlate The translation handle to use for this MD4 context + */ +APU_DECLARE(apr_status_t) apr_md4_set_xlate(apr_md4_ctx_t *context, + apr_xlate_t *xlate); +#else +#define apr_md4_set_xlate(context, xlate) APR_ENOTIMPL +#endif + +/** + * MD4 block update operation. Continue an MD4 message-digest operation, + * processing another message block, and updating the context. + * @param context The MD4 content to update. + * @param input next message block to update + * @param inputLen The length of the next message block + */ +APU_DECLARE(apr_status_t) apr_md4_update(apr_md4_ctx_t *context, + const unsigned char *input, + apr_size_t inputLen); + +/** + * MD4 finalization. Ends an MD4 message-digest operation, writing the + * message digest and zeroing the context + * @param digest The final MD4 digest + * @param context The MD4 content we are finalizing. + */ +APU_DECLARE(apr_status_t) apr_md4_final( + unsigned char digest[APR_MD4_DIGESTSIZE], + apr_md4_ctx_t *context); + +/** + * MD4 digest computation + * @param digest The MD4 digest + * @param input message block to use + * @param inputLen The length of the message block + */ +APU_DECLARE(apr_status_t) apr_md4(unsigned char digest[APR_MD4_DIGESTSIZE], + const unsigned char *input, + apr_size_t inputLen); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_MD4_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_md5.h b/c/dependencies/windows/apr/x86_debug/include/apr_md5.h new file mode 100644 index 00000000..e0202dfd --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_md5.h @@ -0,0 +1,176 @@ +/* + * This is work is derived from material Copyright RSA Data Security, Inc. + * + * The RSA copyright statement and Licence for that original material is + * included below. This is followed by the Apache copyright statement and + * licence for the modifications made to that material. + */ + +/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All + rights reserved. + + License to copy and use this software is granted provided that it + is identified as the "RSA Data Security, Inc. MD5 Message-Digest + Algorithm" in all material mentioning or referencing this software + or this function. + + License is also granted to make and use derivative works provided + that such works are identified as "derived from the RSA Data + Security, Inc. MD5 Message-Digest Algorithm" in all material + mentioning or referencing the derived work. + + RSA Data Security, Inc. makes no representations concerning either + the merchantability of this software or the suitability of this + software for any particular purpose. It is provided "as is" + without express or implied warranty of any kind. + + These notices must be retained in any copies of any part of this + documentation and/or software. + */ + +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_MD5_H +#define APR_MD5_H + +#include "apu.h" +#include "apr_xlate.h" + +#ifdef __cplusplus +extern "C" { +#endif +/** + * @file apr_md5.h + * @brief APR MD5 Routines + */ + +/** + * @defgroup APR_MD5 MD5 Routines + * @ingroup APR + * @{ + */ + +/** The MD5 digest size */ +#define APR_MD5_DIGESTSIZE 16 + +/** @see apr_md5_ctx_t */ +typedef struct apr_md5_ctx_t apr_md5_ctx_t; + +/** MD5 context. */ +struct apr_md5_ctx_t { + /** state (ABCD) */ + apr_uint32_t state[4]; + /** number of bits, modulo 2^64 (lsb first) */ + apr_uint32_t count[2]; + /** input buffer */ + unsigned char buffer[64]; + /** translation handle + * ignored if xlate is unsupported + */ + apr_xlate_t *xlate; +}; + +/** + * MD5 Initialize. Begins an MD5 operation, writing a new context. + * @param context The MD5 context to initialize. + */ +APU_DECLARE(apr_status_t) apr_md5_init(apr_md5_ctx_t *context); + +/** + * MD5 translation setup. Provides the APR translation handle to be used + * for translating the content before calculating the digest. + * @param context The MD5 content to set the translation for. + * @param xlate The translation handle to use for this MD5 context + */ +APU_DECLARE(apr_status_t) apr_md5_set_xlate(apr_md5_ctx_t *context, + apr_xlate_t *xlate); + +/** + * MD5 block update operation. Continue an MD5 message-digest operation, + * processing another message block, and updating the context. + * @param context The MD5 content to update. + * @param input next message block to update + * @param inputLen The length of the next message block + */ +APU_DECLARE(apr_status_t) apr_md5_update(apr_md5_ctx_t *context, + const void *input, + apr_size_t inputLen); + +/** + * MD5 finalization. Ends an MD5 message-digest operation, writing the + * message digest and zeroing the context + * @param digest The final MD5 digest + * @param context The MD5 content we are finalizing. + */ +APU_DECLARE(apr_status_t) apr_md5_final(unsigned char digest[APR_MD5_DIGESTSIZE], + apr_md5_ctx_t *context); + +/** + * MD5 in one step + * @param digest The final MD5 digest + * @param input The message block to use + * @param inputLen The length of the message block + */ +APU_DECLARE(apr_status_t) apr_md5(unsigned char digest[APR_MD5_DIGESTSIZE], + const void *input, + apr_size_t inputLen); + +/** + * Encode a password using an MD5 algorithm + * @param password The password to encode + * @param salt The salt string to use for the encoding + * @param result The string to store the encoded password in + * @param nbytes The size of the result buffer + */ +APU_DECLARE(apr_status_t) apr_md5_encode(const char *password, const char *salt, + char *result, apr_size_t nbytes); + +/** + * Encode a password using the bcrypt algorithm + * @param password The password to encode + * @param count The cost of the encoding, possible values are 4 to 31 + * @param salt Pointer to binary data to be used as salt for the encoding + * @param salt_len The size of the salt data (must be >= 16) + * @param out The string to store the encoded password in + * @param out_len The size of the result buffer (must be >= 61) + */ +APU_DECLARE(apr_status_t) apr_bcrypt_encode(const char *pw, + unsigned int count, + const unsigned char *salt, + apr_size_t salt_len, + char *out, apr_size_t out_len); + +/** + * Validate hashes created by APR-supported algorithms: md5, bcrypt, and sha1. + * hashes created by crypt are supported only on platforms that provide + * crypt(3), so don't rely on that function unless you know that your + * application will be run only on platforms that support it. On platforms + * that don't support crypt(3), this falls back to a clear text string + * comparison. + * @param passwd The password to validate + * @param hash The password to validate against + */ +APU_DECLARE(apr_status_t) apr_password_validate(const char *passwd, + const char *hash); + + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_MD5_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_memcache.h b/c/dependencies/windows/apr/x86_debug/include/apr_memcache.h new file mode 100644 index 00000000..82878825 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_memcache.h @@ -0,0 +1,444 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_MEMCACHE_H +#define APR_MEMCACHE_H + +/** + * @file apr_memcache.h + * @brief Client interface for memcached + * @remark To use this interface you must have a separate memcached + * server running. See the memcached website at http://www.danga.com/memcached/ + * for more information. + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_time.h" +#include "apr_strings.h" +#include "apr_network_io.h" +#include "apr_ring.h" +#include "apr_buckets.h" +#include "apr_reslist.h" +#include "apr_hash.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_Util_MC Memcached Client Routines + * @ingroup APR_Util + * @{ + */ + +/** Specifies the status of a memcached server */ +typedef enum +{ + APR_MC_SERVER_LIVE, /**< Server is alive and responding to requests */ + APR_MC_SERVER_DEAD /**< Server is not responding to requests */ +} apr_memcache_server_status_t; + +/** Opaque memcache client connection object */ +typedef struct apr_memcache_conn_t apr_memcache_conn_t; + +/** Memcache Server Info Object */ +typedef struct apr_memcache_server_t apr_memcache_server_t; +struct apr_memcache_server_t +{ + const char *host; /**< Hostname of this Server */ + apr_port_t port; /**< Port of this Server */ + apr_memcache_server_status_t status; /**< @see apr_memcache_server_status_t */ +#if APR_HAS_THREADS || defined(DOXYGEN) + apr_reslist_t *conns; /**< Resource list of actual client connections */ +#else + apr_memcache_conn_t *conn; +#endif + apr_pool_t *p; /** Pool to use for private allocations */ +#if APR_HAS_THREADS + apr_thread_mutex_t *lock; +#endif + apr_time_t btime; +}; + +/* Custom hash callback function prototype, user for server selection. +* @param baton user selected baton +* @param data data to hash +* @param data_len length of data +*/ +typedef apr_uint32_t (*apr_memcache_hash_func)(void *baton, + const char *data, + const apr_size_t data_len); + +typedef struct apr_memcache_t apr_memcache_t; + +/* Custom Server Select callback function prototype. +* @param baton user selected baton +* @param mc memcache instance, use mc->live_servers to select a node +* @param hash hash of the selected key. +*/ +typedef apr_memcache_server_t* (*apr_memcache_server_func)(void *baton, + apr_memcache_t *mc, + const apr_uint32_t hash); + +/** Container for a set of memcached servers */ +struct apr_memcache_t +{ + apr_uint32_t flags; /**< Flags, Not currently used */ + apr_uint16_t nalloc; /**< Number of Servers Allocated */ + apr_uint16_t ntotal; /**< Number of Servers Added */ + apr_memcache_server_t **live_servers; /**< Array of Servers */ + apr_pool_t *p; /** Pool to use for allocations */ + void *hash_baton; + apr_memcache_hash_func hash_func; + void *server_baton; + apr_memcache_server_func server_func; +}; + +/** Returned Data from a multiple get */ +typedef struct +{ + apr_status_t status; + const char* key; + apr_size_t len; + char *data; + apr_uint16_t flags; +} apr_memcache_value_t; + +/** + * Creates a crc32 hash used to split keys between servers + * @param mc The memcache client object to use + * @param data Data to be hashed + * @param data_len Length of the data to use + * @return crc32 hash of data + * @remark The crc32 hash is not compatible with old memcached clients. + */ +APU_DECLARE(apr_uint32_t) apr_memcache_hash(apr_memcache_t *mc, + const char *data, + const apr_size_t data_len); + +/** + * Pure CRC32 Hash. Used by some clients. + */ +APU_DECLARE(apr_uint32_t) apr_memcache_hash_crc32(void *baton, + const char *data, + const apr_size_t data_len); + +/** + * hash compatible with the standard Perl Client. + */ +APU_DECLARE(apr_uint32_t) apr_memcache_hash_default(void *baton, + const char *data, + const apr_size_t data_len); + +/** + * Picks a server based on a hash + * @param mc The memcache client object to use + * @param hash Hashed value of a Key + * @return server that controls specified hash + * @see apr_memcache_hash + */ +APU_DECLARE(apr_memcache_server_t *) apr_memcache_find_server_hash(apr_memcache_t *mc, + const apr_uint32_t hash); + +/** + * server selection compatible with the standard Perl Client. + */ +APU_DECLARE(apr_memcache_server_t *) apr_memcache_find_server_hash_default(void *baton, + apr_memcache_t *mc, + const apr_uint32_t hash); + +/** + * Adds a server to a client object + * @param mc The memcache client object to use + * @param server Server to add + * @remark Adding servers is not thread safe, and should be done once at startup. + * @warning Changing servers after startup may cause keys to go to + * different servers. + */ +APU_DECLARE(apr_status_t) apr_memcache_add_server(apr_memcache_t *mc, + apr_memcache_server_t *server); + + +/** + * Finds a Server object based on a hostname/port pair + * @param mc The memcache client object to use + * @param host Hostname of the server + * @param port Port of the server + * @return Server with matching Hostname and Port, or NULL if none was found. + */ +APU_DECLARE(apr_memcache_server_t *) apr_memcache_find_server(apr_memcache_t *mc, + const char *host, + apr_port_t port); + +/** + * Enables a Server for use again + * @param mc The memcache client object to use + * @param ms Server to Activate + */ +APU_DECLARE(apr_status_t) apr_memcache_enable_server(apr_memcache_t *mc, + apr_memcache_server_t *ms); + + +/** + * Disable a Server + * @param mc The memcache client object to use + * @param ms Server to Disable + */ +APU_DECLARE(apr_status_t) apr_memcache_disable_server(apr_memcache_t *mc, + apr_memcache_server_t *ms); + +/** + * Creates a new Server Object + * @param p Pool to use + * @param host hostname of the server + * @param port port of the server + * @param min minimum number of client sockets to open + * @param smax soft maximum number of client connections to open + * @param max hard maximum number of client connections + * @param ttl time to live in microseconds of a client connection + * @param ns location of the new server object + * @see apr_reslist_create + * @remark min, smax, and max are only used when APR_HAS_THREADS + */ +APU_DECLARE(apr_status_t) apr_memcache_server_create(apr_pool_t *p, + const char *host, + apr_port_t port, + apr_uint32_t min, + apr_uint32_t smax, + apr_uint32_t max, + apr_uint32_t ttl, + apr_memcache_server_t **ns); +/** + * Creates a new memcached client object + * @param p Pool to use + * @param max_servers maximum number of servers + * @param flags Not currently used + * @param mc location of the new memcache client object + */ +APU_DECLARE(apr_status_t) apr_memcache_create(apr_pool_t *p, + apr_uint16_t max_servers, + apr_uint32_t flags, + apr_memcache_t **mc); + +/** + * Gets a value from the server, allocating the value out of p + * @param mc client to use + * @param p Pool to use + * @param key null terminated string containing the key + * @param baton location of the allocated value + * @param len length of data at baton + * @param flags any flags set by the client for this key + * @return + */ +APU_DECLARE(apr_status_t) apr_memcache_getp(apr_memcache_t *mc, + apr_pool_t *p, + const char* key, + char **baton, + apr_size_t *len, + apr_uint16_t *flags); + + +/** + * Add a key to a hash for a multiget query + * if the hash (*value) is NULL it will be created + * @param data_pool pool from where the hash and their items are created from + * @param key null terminated string containing the key + * @param values hash of keys and values that this key will be added to + * @return + */ +APU_DECLARE(void) apr_memcache_add_multget_key(apr_pool_t *data_pool, + const char* key, + apr_hash_t **values); + +/** + * Gets multiple values from the server, allocating the values out of p + * @param mc client to use + * @param temp_pool Pool used for temporary allocations. May be cleared inside this + * call. + * @param data_pool Pool used to allocate data for the returned values. + * @param values hash of apr_memcache_value_t keyed by strings, contains the + * result of the multiget call. + * @return + */ +APU_DECLARE(apr_status_t) apr_memcache_multgetp(apr_memcache_t *mc, + apr_pool_t *temp_pool, + apr_pool_t *data_pool, + apr_hash_t *values); + +/** + * Sets a value by key on the server + * @param mc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param timeout time in seconds for the data to live on the server + * @param flags any flags set by the client for this key + */ +APU_DECLARE(apr_status_t) apr_memcache_set(apr_memcache_t *mc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint32_t timeout, + apr_uint16_t flags); + +/** + * Adds value by key on the server + * @param mc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param timeout time for the data to live on the server + * @param flags any flags set by the client for this key + * @return APR_SUCCESS if the key was added, APR_EEXIST if the key + * already exists on the server. + */ +APU_DECLARE(apr_status_t) apr_memcache_add(apr_memcache_t *mc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint32_t timeout, + apr_uint16_t flags); + +/** + * Replaces value by key on the server + * @param mc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param timeout time for the data to live on the server + * @param flags any flags set by the client for this key + * @return APR_SUCCESS if the key was added, APR_EEXIST if the key + * did not exist on the server. + */ +APU_DECLARE(apr_status_t) apr_memcache_replace(apr_memcache_t *mc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint32_t timeout, + apr_uint16_t flags); +/** + * Deletes a key from a server + * @param mc client to use + * @param key null terminated string containing the key + * @param timeout time for the delete to stop other clients from adding + */ +APU_DECLARE(apr_status_t) apr_memcache_delete(apr_memcache_t *mc, + const char *key, + apr_uint32_t timeout); + +/** + * Increments a value + * @param mc client to use + * @param key null terminated string containing the key + * @param n number to increment by + * @param nv new value after incrementing + */ +APU_DECLARE(apr_status_t) apr_memcache_incr(apr_memcache_t *mc, + const char *key, + apr_int32_t n, + apr_uint32_t *nv); + +/** + * Decrements a value + * @param mc client to use + * @param key null terminated string containing the key + * @param n number to decrement by + * @param new_value new value after decrementing + */ +APU_DECLARE(apr_status_t) apr_memcache_decr(apr_memcache_t *mc, + const char *key, + apr_int32_t n, + apr_uint32_t *new_value); + +/** + * Query a server's version + * @param ms server to query + * @param p Pool to allocate answer from + * @param baton location to store server version string + * @param len length of the server version string + */ +APU_DECLARE(apr_status_t) apr_memcache_version(apr_memcache_server_t *ms, + apr_pool_t *p, + char **baton); + +typedef struct +{ + /** Version string of this server */ + const char *version; + /** Process id of this server process */ + apr_uint32_t pid; + /** Number of seconds this server has been running */ + apr_uint32_t uptime; + /** current UNIX time according to the server */ + apr_time_t time; + /** The size of a pointer on the current machine */ + apr_uint32_t pointer_size; + /** Accumulated user time for this process */ + apr_time_t rusage_user; + /** Accumulated system time for this process */ + apr_time_t rusage_system; + /** Current number of items stored by the server */ + apr_uint32_t curr_items; + /** Total number of items stored by this server */ + apr_uint32_t total_items; + /** Current number of bytes used by this server to store items */ + apr_uint64_t bytes; + /** Number of open connections */ + apr_uint32_t curr_connections; + /** Total number of connections opened since the server started running */ + apr_uint32_t total_connections; + /** Number of connection structures allocated by the server */ + apr_uint32_t connection_structures; + /** Cumulative number of retrieval requests */ + apr_uint32_t cmd_get; + /** Cumulative number of storage requests */ + apr_uint32_t cmd_set; + /** Number of keys that have been requested and found present */ + apr_uint32_t get_hits; + /** Number of items that have been requested and not found */ + apr_uint32_t get_misses; + /** Number of items removed from cache because they passed their + expiration time */ + apr_uint64_t evictions; + /** Total number of bytes read by this server */ + apr_uint64_t bytes_read; + /** Total number of bytes sent by this server */ + apr_uint64_t bytes_written; + /** Number of bytes this server is allowed to use for storage. */ + apr_uint32_t limit_maxbytes; + /** Number of threads the server is running (if built with threading) */ + apr_uint32_t threads; +} apr_memcache_stats_t; + +/** + * Query a server for statistics + * @param ms server to query + * @param p Pool to allocate answer from + * @param stats location of the new statistics structure + */ +APU_DECLARE(apr_status_t) apr_memcache_stats(apr_memcache_server_t *ms, + apr_pool_t *p, + apr_memcache_stats_t **stats); + + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_MEMCACHE_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_mmap.h b/c/dependencies/windows/apr/x86_debug/include/apr_mmap.h new file mode 100644 index 00000000..c14de192 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_mmap.h @@ -0,0 +1,171 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_MMAP_H +#define APR_MMAP_H + +/** + * @file apr_mmap.h + * @brief APR MMAP routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_ring.h" +#include "apr_file_io.h" /* for apr_file_t */ + +#ifdef BEOS +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_mmap MMAP (Memory Map) Routines + * @ingroup APR + * @{ + */ + +/** MMap opened for reading */ +#define APR_MMAP_READ 1 +/** MMap opened for writing */ +#define APR_MMAP_WRITE 2 + +/** @see apr_mmap_t */ +typedef struct apr_mmap_t apr_mmap_t; + +/** + * @remark + * As far as I can tell the only really sane way to store an MMAP is as a + * void * and a length. BeOS requires this area_id, but that's just a little + * something extra. I am exposing this type, because it doesn't make much + * sense to keep it private, and opening it up makes some stuff easier in + * Apache. + */ +/** The MMAP structure */ +struct apr_mmap_t { + /** The pool the mmap structure was allocated out of. */ + apr_pool_t *cntxt; +#ifdef BEOS + /** An area ID. Only valid on BeOS */ + area_id area; +#endif +#ifdef WIN32 + /** The handle of the file mapping */ + HANDLE mhandle; + /** The start of the real memory page area (mapped view) */ + void *mv; + /** The physical start, size and offset */ + apr_off_t pstart; + apr_size_t psize; + apr_off_t poffset; +#endif + /** The start of the memory mapped area */ + void *mm; + /** The amount of data in the mmap */ + apr_size_t size; + /** ring of apr_mmap_t's that reference the same + * mmap'ed region; acts in place of a reference count */ + APR_RING_ENTRY(apr_mmap_t) link; +}; + +#if APR_HAS_MMAP || defined(DOXYGEN) + +/** @def APR_MMAP_THRESHOLD + * Files have to be at least this big before they're mmap()d. This is to deal + * with systems where the expense of doing an mmap() and an munmap() outweighs + * the benefit for small files. It shouldn't be set lower than 1. + */ +#ifdef MMAP_THRESHOLD +# define APR_MMAP_THRESHOLD MMAP_THRESHOLD +#else +# ifdef SUNOS4 +# define APR_MMAP_THRESHOLD (8*1024) +# else +# define APR_MMAP_THRESHOLD 1 +# endif /* SUNOS4 */ +#endif /* MMAP_THRESHOLD */ + +/** @def APR_MMAP_LIMIT + * Maximum size of MMap region + */ +#ifdef MMAP_LIMIT +# define APR_MMAP_LIMIT MMAP_LIMIT +#else +# define APR_MMAP_LIMIT (4*1024*1024) +#endif /* MMAP_LIMIT */ + +/** Can this file be MMaped */ +#define APR_MMAP_CANDIDATE(filelength) \ + ((filelength >= APR_MMAP_THRESHOLD) && (filelength < APR_MMAP_LIMIT)) + +/* Function definitions */ + +/** + * Create a new mmap'ed file out of an existing APR file. + * @param newmmap The newly created mmap'ed file. + * @param file The file to turn into an mmap. + * @param offset The offset into the file to start the data pointer at. + * @param size The size of the file + * @param flag bit-wise or of: + *
+ *          APR_MMAP_READ       MMap opened for reading
+ *          APR_MMAP_WRITE      MMap opened for writing
+ * 
+ * @param cntxt The pool to use when creating the mmap. + */ +APR_DECLARE(apr_status_t) apr_mmap_create(apr_mmap_t **newmmap, + apr_file_t *file, apr_off_t offset, + apr_size_t size, apr_int32_t flag, + apr_pool_t *cntxt); + +/** + * Duplicate the specified MMAP. + * @param new_mmap The structure to duplicate into. + * @param old_mmap The mmap to duplicate. + * @param p The pool to use for new_mmap. + */ +APR_DECLARE(apr_status_t) apr_mmap_dup(apr_mmap_t **new_mmap, + apr_mmap_t *old_mmap, + apr_pool_t *p); + +/** + * Remove a mmap'ed. + * @param mm The mmap'ed file. + */ +APR_DECLARE(apr_status_t) apr_mmap_delete(apr_mmap_t *mm); + +/** + * Move the pointer into the mmap'ed file to the specified offset. + * @param addr The pointer to the offset specified. + * @param mm The mmap'ed file. + * @param offset The offset to move to. + */ +APR_DECLARE(apr_status_t) apr_mmap_offset(void **addr, apr_mmap_t *mm, + apr_off_t offset); + +#endif /* APR_HAS_MMAP */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_MMAP_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_network_io.h b/c/dependencies/windows/apr/x86_debug/include/apr_network_io.h new file mode 100644 index 00000000..7d6957bc --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_network_io.h @@ -0,0 +1,951 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_NETWORK_IO_H +#define APR_NETWORK_IO_H +/** + * @file apr_network_io.h + * @brief APR Network library + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_file_io.h" +#include "apr_errno.h" +#include "apr_inherit.h" +#include "apr_perms_set.h" + +#if APR_HAVE_NETINET_IN_H +#include +#endif +#if APR_HAVE_SYS_UN_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_network_io Network Routines + * @ingroup APR + * @{ + */ + +#ifndef APR_MAX_SECS_TO_LINGER +/** Maximum seconds to linger */ +#define APR_MAX_SECS_TO_LINGER 30 +#endif + +#ifndef APRMAXHOSTLEN +/** Maximum hostname length */ +#define APRMAXHOSTLEN 256 +#endif + +#ifndef APR_ANYADDR +/** Default 'any' address */ +#define APR_ANYADDR "0.0.0.0" +#endif + +/** + * @defgroup apr_sockopt Socket option definitions + * @{ + */ +#define APR_SO_LINGER 1 /**< Linger */ +#define APR_SO_KEEPALIVE 2 /**< Keepalive */ +#define APR_SO_DEBUG 4 /**< Debug */ +#define APR_SO_NONBLOCK 8 /**< Non-blocking IO */ +#define APR_SO_REUSEADDR 16 /**< Reuse addresses */ +#define APR_SO_SNDBUF 64 /**< Send buffer */ +#define APR_SO_RCVBUF 128 /**< Receive buffer */ +#define APR_SO_DISCONNECTED 256 /**< Disconnected */ +#define APR_TCP_NODELAY 512 /**< For SCTP sockets, this is mapped + * to STCP_NODELAY internally. + */ +#define APR_TCP_NOPUSH 1024 /**< No push */ +#define APR_RESET_NODELAY 2048 /**< This flag is ONLY set internally + * when we set APR_TCP_NOPUSH with + * APR_TCP_NODELAY set to tell us that + * APR_TCP_NODELAY should be turned on + * again when NOPUSH is turned off + */ +#define APR_INCOMPLETE_READ 4096 /**< Set on non-blocking sockets + * (timeout != 0) on which the + * previous read() did not fill a buffer + * completely. the next apr_socket_recv() + * will first call select()/poll() rather than + * going straight into read(). (Can also + * be set by an application to force a + * select()/poll() call before the next + * read, in cases where the app expects + * that an immediate read would fail.) + */ +#define APR_INCOMPLETE_WRITE 8192 /**< like APR_INCOMPLETE_READ, but for write + * @see APR_INCOMPLETE_READ + */ +#define APR_IPV6_V6ONLY 16384 /**< Don't accept IPv4 connections on an + * IPv6 listening socket. + */ +#define APR_TCP_DEFER_ACCEPT 32768 /**< Delay accepting of new connections + * until data is available. + * @see apr_socket_accept_filter + */ +#define APR_SO_BROADCAST 65536 /**< Allow broadcast + */ +#define APR_SO_FREEBIND 131072 /**< Allow binding to addresses not owned + * by any interface + */ + +/** @} */ + +/** Define what type of socket shutdown should occur. */ +typedef enum { + APR_SHUTDOWN_READ, /**< no longer allow read request */ + APR_SHUTDOWN_WRITE, /**< no longer allow write requests */ + APR_SHUTDOWN_READWRITE /**< no longer allow read or write requests */ +} apr_shutdown_how_e; + +#define APR_IPV4_ADDR_OK 0x01 /**< @see apr_sockaddr_info_get() */ +#define APR_IPV6_ADDR_OK 0x02 /**< @see apr_sockaddr_info_get() */ + +#if (!APR_HAVE_IN_ADDR) +/** + * We need to make sure we always have an in_addr type, so APR will just + * define it ourselves, if the platform doesn't provide it. + */ +struct in_addr { + apr_uint32_t s_addr; /**< storage to hold the IP# */ +}; +#endif + +/** @def APR_INADDR_NONE + * Not all platforms have a real INADDR_NONE. This macro replaces + * INADDR_NONE on all platforms. + */ +#ifdef INADDR_NONE +#define APR_INADDR_NONE INADDR_NONE +#else +#define APR_INADDR_NONE ((unsigned int) 0xffffffff) +#endif + +/** + * @def APR_INET + * Not all platforms have these defined, so we'll define them here + * The default values come from FreeBSD 4.1.1 + */ +#define APR_INET AF_INET +/** @def APR_UNSPEC + * Let the system decide which address family to use + */ +#ifdef AF_UNSPEC +#define APR_UNSPEC AF_UNSPEC +#else +#define APR_UNSPEC 0 +#endif +#if APR_HAVE_IPV6 +/** @def APR_INET6 +* IPv6 Address Family. Not all platforms may have this defined. +*/ + +#define APR_INET6 AF_INET6 +#endif + +#if APR_HAVE_SOCKADDR_UN +#if defined (AF_UNIX) +#define APR_UNIX AF_UNIX +#elif defined(AF_LOCAL) +#define APR_UNIX AF_LOCAL +#else +#error "Neither AF_UNIX nor AF_LOCAL is defined" +#endif +#else /* !APR_HAVE_SOCKADDR_UN */ +#if defined (AF_UNIX) +#define APR_UNIX AF_UNIX +#elif defined(AF_LOCAL) +#define APR_UNIX AF_LOCAL +#else +/* TODO: Use a smarter way to detect unique APR_UNIX value */ +#define APR_UNIX 1234 +#endif +#endif + +/** + * @defgroup IP_Proto IP Protocol Definitions for use when creating sockets + * @{ + */ +#define APR_PROTO_TCP 6 /**< TCP */ +#define APR_PROTO_UDP 17 /**< UDP */ +#define APR_PROTO_SCTP 132 /**< SCTP */ +/** @} */ + +/** + * Enum used to denote either the local and remote endpoint of a + * connection. + */ +typedef enum { + APR_LOCAL, /**< Socket information for local end of connection */ + APR_REMOTE /**< Socket information for remote end of connection */ +} apr_interface_e; + +/** + * The specific declaration of inet_addr's ... some platforms fall back + * inet_network (this is not good, but necessary) + */ + +#if APR_HAVE_INET_ADDR +#define apr_inet_addr inet_addr +#elif APR_HAVE_INET_NETWORK /* only DGUX, as far as I know */ +/** + * @warning + * not generally safe... inet_network() and inet_addr() perform + * different functions */ +#define apr_inet_addr inet_network +#endif + +/** A structure to represent sockets */ +typedef struct apr_socket_t apr_socket_t; +/** + * A structure to encapsulate headers and trailers for apr_socket_sendfile + */ +typedef struct apr_hdtr_t apr_hdtr_t; +/** A structure to represent in_addr */ +typedef struct in_addr apr_in_addr_t; +/** A structure to represent an IP subnet */ +typedef struct apr_ipsubnet_t apr_ipsubnet_t; + +/** @remark use apr_uint16_t just in case some system has a short that isn't 16 bits... */ +typedef apr_uint16_t apr_port_t; + +/** @remark It's defined here as I think it should all be platform safe... + * @see apr_sockaddr_t + */ +typedef struct apr_sockaddr_t apr_sockaddr_t; +/** + * APRs socket address type, used to ensure protocol independence + */ +struct apr_sockaddr_t { + /** The pool to use... */ + apr_pool_t *pool; + /** The hostname */ + char *hostname; + /** Either a string of the port number or the service name for the port */ + char *servname; + /** The numeric port */ + apr_port_t port; + /** The family */ + apr_int32_t family; + /** How big is the sockaddr we're using? */ + apr_socklen_t salen; + /** How big is the ip address structure we're using? */ + int ipaddr_len; + /** How big should the address buffer be? 16 for v4 or 46 for v6 + * used in inet_ntop... */ + int addr_str_len; + /** This points to the IP address structure within the appropriate + * sockaddr structure. */ + void *ipaddr_ptr; + /** If multiple addresses were found by apr_sockaddr_info_get(), this + * points to a representation of the next address. */ + apr_sockaddr_t *next; + /** Union of either IPv4 or IPv6 sockaddr. */ + union { + /** IPv4 sockaddr structure */ + struct sockaddr_in sin; +#if APR_HAVE_IPV6 + /** IPv6 sockaddr structure */ + struct sockaddr_in6 sin6; +#endif +#if APR_HAVE_SA_STORAGE + /** Placeholder to ensure that the size of this union is not + * dependent on whether APR_HAVE_IPV6 is defined. */ + struct sockaddr_storage sas; +#endif +#if APR_HAVE_SOCKADDR_UN + /** Unix domain socket sockaddr structure */ + struct sockaddr_un unx; +#endif + } sa; +}; + +#if APR_HAS_SENDFILE +/** + * Support reusing the socket on platforms which support it (from disconnect, + * specifically Win32. + * @remark Optional flag passed into apr_socket_sendfile() + */ +#define APR_SENDFILE_DISCONNECT_SOCKET 1 +#endif + +/** A structure to encapsulate headers and trailers for apr_socket_sendfile */ +struct apr_hdtr_t { + /** An iovec to store the headers sent before the file. */ + struct iovec* headers; + /** number of headers in the iovec */ + int numheaders; + /** An iovec to store the trailers sent after the file. */ + struct iovec* trailers; + /** number of trailers in the iovec */ + int numtrailers; +}; + +/* function definitions */ + +/** + * Create a socket. + * @param new_sock The new socket that has been set up. + * @param family The address family of the socket (e.g., APR_INET). + * @param type The type of the socket (e.g., SOCK_STREAM). + * @param protocol The protocol of the socket (e.g., APR_PROTO_TCP). + * @param cont The pool for the apr_socket_t and associated storage. + * @note The pool will be used by various functions that operate on the + * socket. The caller must ensure that it is not used by other threads + * at the same time. + */ +APR_DECLARE(apr_status_t) apr_socket_create(apr_socket_t **new_sock, + int family, int type, + int protocol, + apr_pool_t *cont); + +/** + * Shutdown either reading, writing, or both sides of a socket. + * @param thesocket The socket to close + * @param how How to shutdown the socket. One of: + *
+ *            APR_SHUTDOWN_READ         no longer allow read requests
+ *            APR_SHUTDOWN_WRITE        no longer allow write requests
+ *            APR_SHUTDOWN_READWRITE    no longer allow read or write requests 
+ * 
+ * @see apr_shutdown_how_e + * @remark This does not actually close the socket descriptor, it just + * controls which calls are still valid on the socket. + */ +APR_DECLARE(apr_status_t) apr_socket_shutdown(apr_socket_t *thesocket, + apr_shutdown_how_e how); + +/** + * Close a socket. + * @param thesocket The socket to close + */ +APR_DECLARE(apr_status_t) apr_socket_close(apr_socket_t *thesocket); + +/** + * Bind the socket to its associated port + * @param sock The socket to bind + * @param sa The socket address to bind to + * @remark This may be where we will find out if there is any other process + * using the selected port. + */ +APR_DECLARE(apr_status_t) apr_socket_bind(apr_socket_t *sock, + apr_sockaddr_t *sa); + +/** + * Listen to a bound socket for connections. + * @param sock The socket to listen on + * @param backlog The number of outstanding connections allowed in the sockets + * listen queue. If this value is less than zero, the listen + * queue size is set to zero. + */ +APR_DECLARE(apr_status_t) apr_socket_listen(apr_socket_t *sock, + apr_int32_t backlog); + +/** + * Accept a new connection request + * @param new_sock A copy of the socket that is connected to the socket that + * made the connection request. This is the socket which should + * be used for all future communication. + * @param sock The socket we are listening on. + * @param connection_pool The pool for the new socket. + * @note The pool will be used by various functions that operate on the + * socket. The caller must ensure that it is not used by other threads + * at the same time. + */ +APR_DECLARE(apr_status_t) apr_socket_accept(apr_socket_t **new_sock, + apr_socket_t *sock, + apr_pool_t *connection_pool); + +/** + * Issue a connection request to a socket either on the same machine + * or a different one. + * @param sock The socket we wish to use for our side of the connection + * @param sa The address of the machine we wish to connect to. + */ +APR_DECLARE(apr_status_t) apr_socket_connect(apr_socket_t *sock, + apr_sockaddr_t *sa); + +/** + * Determine whether the receive part of the socket has been closed by + * the peer (such that a subsequent call to apr_socket_read would + * return APR_EOF), if the socket's receive buffer is empty. This + * function does not block waiting for I/O. + * + * @param sock The socket to check + * @param atreadeof If APR_SUCCESS is returned, *atreadeof is set to + * non-zero if a subsequent read would return APR_EOF + * @return an error is returned if it was not possible to determine the + * status, in which case *atreadeof is not changed. + */ +APR_DECLARE(apr_status_t) apr_socket_atreadeof(apr_socket_t *sock, + int *atreadeof); + +/** + * Create apr_sockaddr_t from hostname, address family, and port. + * @param sa The new apr_sockaddr_t. + * @param hostname The hostname or numeric address string to resolve/parse, or + * NULL to build an address that corresponds to 0.0.0.0 or :: + * or in case of APR_UNIX family it is absolute socket filename. + * @param family The address family to use, or APR_UNSPEC if the system should + * decide. + * @param port The port number. + * @param flags Special processing flags: + *
+ *       APR_IPV4_ADDR_OK          first query for IPv4 addresses; only look
+ *                                 for IPv6 addresses if the first query failed;
+ *                                 only valid if family is APR_UNSPEC and hostname
+ *                                 isn't NULL; mutually exclusive with
+ *                                 APR_IPV6_ADDR_OK
+ *       APR_IPV6_ADDR_OK          first query for IPv6 addresses; only look
+ *                                 for IPv4 addresses if the first query failed;
+ *                                 only valid if family is APR_UNSPEC and hostname
+ *                                 isn't NULL and APR_HAVE_IPV6; mutually exclusive
+ *                                 with APR_IPV4_ADDR_OK
+ * 
+ * @param p The pool for the apr_sockaddr_t and associated storage. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_info_get(apr_sockaddr_t **sa, + const char *hostname, + apr_int32_t family, + apr_port_t port, + apr_int32_t flags, + apr_pool_t *p); + +/** + * Copy apr_sockaddr_t src to dst on pool p. + * @param dst The destination apr_sockaddr_t. + * @param src The source apr_sockaddr_t. + * @param p The pool for the apr_sockaddr_t and associated storage. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_info_copy(apr_sockaddr_t **dst, + const apr_sockaddr_t *src, + apr_pool_t *p); + +/* Set the zone of an IPv6 link-local address object. + * @param sa Socket address object + * @param zone_id Zone ID (textual "eth0" or numeric "3"). + * @return Returns APR_EBADIP for non-IPv6 socket or an IPv6 address + * which isn't link-local. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_zone_set(apr_sockaddr_t *sa, + const char *zone_id); + + +/* Retrieve the zone of an IPv6 link-local address object. + * @param sa Socket address object + * @param name If non-NULL, set to the textual representation of the zone id + * @param id If non-NULL, set to the integer zone id + * @param p Pool from which *name is allocated if used. + * @return Returns APR_EBADIP for non-IPv6 socket or socket without any zone id + * set, or other error if the interface could not be mapped to a name. + * @remark Both name and id may be NULL, neither are modified if + * non-NULL in error cases. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_zone_get(const apr_sockaddr_t *sa, + const char **name, + apr_uint32_t *id, + apr_pool_t *p); + +/** + * Look up the host name from an apr_sockaddr_t. + * @param hostname The hostname. + * @param sa The apr_sockaddr_t. + * @param flags Special processing flags. + * @remark Results can vary significantly between platforms + * when processing wildcard socket addresses. + */ +APR_DECLARE(apr_status_t) apr_getnameinfo(char **hostname, + apr_sockaddr_t *sa, + apr_int32_t flags); + +/** + * Parse hostname/IP address with scope id and port. + * + * Any of the following strings are accepted: + * 8080 (just the port number) + * www.apache.org (just the hostname) + * www.apache.org:8080 (hostname and port number) + * [fe80::1]:80 (IPv6 numeric address string only) + * [fe80::1%eth0] (IPv6 numeric address string and scope id) + * + * Invalid strings: + * (empty string) + * [abc] (not valid IPv6 numeric address string) + * abc:65536 (invalid port number) + * + * @param addr The new buffer containing just the hostname. On output, *addr + * will be NULL if no hostname/IP address was specfied. + * @param scope_id The new buffer containing just the scope id. On output, + * *scope_id will be NULL if no scope id was specified. + * @param port The port number. On output, *port will be 0 if no port was + * specified. + * ### FIXME: 0 is a legal port (per RFC 1700). this should + * ### return something besides zero if the port is missing. + * @param str The input string to be parsed. + * @param p The pool from which *addr and *scope_id are allocated. + * @remark If scope id shouldn't be allowed, check for scope_id != NULL in + * addition to checking the return code. If addr/hostname should be + * required, check for addr == NULL in addition to checking the + * return code. + */ +APR_DECLARE(apr_status_t) apr_parse_addr_port(char **addr, + char **scope_id, + apr_port_t *port, + const char *str, + apr_pool_t *p); + +/** + * Get name of the current machine + * @param buf A buffer to store the hostname in. + * @param len The maximum length of the hostname that can be stored in the + * buffer provided. The suggested length is APRMAXHOSTLEN + 1. + * @param cont The pool to use. + * @remark If the buffer was not large enough, an error will be returned. + */ +APR_DECLARE(apr_status_t) apr_gethostname(char *buf, int len, apr_pool_t *cont); + +/** + * Return the data associated with the current socket + * @param data The user data associated with the socket. + * @param key The key to associate with the user data. + * @param sock The currently open socket. + */ +APR_DECLARE(apr_status_t) apr_socket_data_get(void **data, const char *key, + apr_socket_t *sock); + +/** + * Set the data associated with the current socket. + * @param sock The currently open socket. + * @param data The user data to associate with the socket. + * @param key The key to associate with the data. + * @param cleanup The cleanup to call when the socket is destroyed. + */ +APR_DECLARE(apr_status_t) apr_socket_data_set(apr_socket_t *sock, void *data, + const char *key, + apr_status_t (*cleanup)(void*)); + +/** + * Send data over a network. + * @param sock The socket to send the data over. + * @param buf The buffer which contains the data to be sent. + * @param len On entry, the number of bytes to send; on exit, the number + * of bytes sent. + * @remark + *
+ * This functions acts like a blocking write by default.  To change 
+ * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK
+ * socket option.
+ *
+ * It is possible for both bytes to be sent and an error to be returned.
+ *
+ * APR_EINTR is never returned.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_socket_send(apr_socket_t *sock, const char *buf, + apr_size_t *len); + +/** + * Send multiple buffers over a network. + * @param sock The socket to send the data over. + * @param vec The array of iovec structs containing the data to send + * @param nvec The number of iovec structs in the array + * @param len Receives the number of bytes actually written + * @remark + *
+ * This functions acts like a blocking write by default.  To change 
+ * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK
+ * socket option.
+ * The number of bytes actually sent is stored in argument 4.
+ *
+ * It is possible for both bytes to be sent and an error to be returned.
+ *
+ * APR_EINTR is never returned.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_socket_sendv(apr_socket_t *sock, + const struct iovec *vec, + apr_int32_t nvec, apr_size_t *len); + +/** + * @param sock The socket to send from + * @param where The apr_sockaddr_t describing where to send the data + * @param flags The flags to use + * @param buf The data to send + * @param len The length of the data to send + */ +APR_DECLARE(apr_status_t) apr_socket_sendto(apr_socket_t *sock, + apr_sockaddr_t *where, + apr_int32_t flags, const char *buf, + apr_size_t *len); + +/** + * Read data from a socket. On success, the address of the peer from + * which the data was sent is copied into the @a from parameter, and the + * @a len parameter is updated to give the number of bytes written to + * @a buf. + * + * @param from Updated with the address from which the data was received + * @param sock The socket to use + * @param flags The flags to use + * @param buf The buffer to use + * @param len The length of the available buffer + */ + +APR_DECLARE(apr_status_t) apr_socket_recvfrom(apr_sockaddr_t *from, + apr_socket_t *sock, + apr_int32_t flags, char *buf, + apr_size_t *len); + +#if APR_HAS_SENDFILE || defined(DOXYGEN) + +/** + * Send a file from an open file descriptor to a socket, along with + * optional headers and trailers + * @param sock The socket to which we're writing + * @param file The open file from which to read + * @param hdtr A structure containing the headers and trailers to send + * @param offset Offset into the file where we should begin writing + * @param len (input) - Number of bytes to send from the file + * (output) - Number of bytes actually sent, + * including headers, file, and trailers + * @param flags APR flags that are mapped to OS specific flags + * @remark This functions acts like a blocking write by default. To change + * this behavior, use apr_socket_timeout_set() or the + * APR_SO_NONBLOCK socket option. + * The number of bytes actually sent is stored in the len parameter. + * The offset parameter is passed by reference for no reason; its + * value will never be modified by the apr_socket_sendfile() function. + */ +APR_DECLARE(apr_status_t) apr_socket_sendfile(apr_socket_t *sock, + apr_file_t *file, + apr_hdtr_t *hdtr, + apr_off_t *offset, + apr_size_t *len, + apr_int32_t flags); + +#endif /* APR_HAS_SENDFILE */ + +/** + * Read data from a network. + * @param sock The socket to read the data from. + * @param buf The buffer to store the data in. + * @param len On entry, the number of bytes to receive; on exit, the number + * of bytes received. + * @remark + *
+ * This functions acts like a blocking read by default.  To change 
+ * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK
+ * socket option.
+ * The number of bytes actually received is stored in argument 3.
+ *
+ * It is possible for both bytes to be received and an APR_EOF or
+ * other error to be returned.
+ *
+ * APR_EINTR is never returned.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_socket_recv(apr_socket_t *sock, + char *buf, apr_size_t *len); + +/** + * Setup socket options for the specified socket + * @param sock The socket to set up. + * @param opt The option we would like to configure. One of: + *
+ *            APR_SO_DEBUG      --  turn on debugging information 
+ *            APR_SO_KEEPALIVE  --  keep connections active
+ *            APR_SO_LINGER     --  lingers on close if data is present
+ *            APR_SO_NONBLOCK   --  Turns blocking on/off for socket
+ *                                  When this option is enabled, use
+ *                                  the APR_STATUS_IS_EAGAIN() macro to
+ *                                  see if a send or receive function
+ *                                  could not transfer data without
+ *                                  blocking.
+ *            APR_SO_REUSEADDR  --  The rules used in validating addresses
+ *                                  supplied to bind should allow reuse
+ *                                  of local addresses.
+ *            APR_SO_SNDBUF     --  Set the SendBufferSize
+ *            APR_SO_RCVBUF     --  Set the ReceiveBufferSize
+ *            APR_SO_FREEBIND   --  Allow binding to non-local IP address.
+ * 
+ * @param on Value for the option. + */ +APR_DECLARE(apr_status_t) apr_socket_opt_set(apr_socket_t *sock, + apr_int32_t opt, apr_int32_t on); + +/** + * Setup socket timeout for the specified socket + * @param sock The socket to set up. + * @param t Value for the timeout. + *
+ *   t > 0  -- read and write calls return APR_TIMEUP if specified time
+ *             elapsess with no data read or written
+ *   t == 0 -- read and write calls never block
+ *   t < 0  -- read and write calls block
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_socket_timeout_set(apr_socket_t *sock, + apr_interval_time_t t); + +/** + * Query socket options for the specified socket + * @param sock The socket to query + * @param opt The option we would like to query. One of: + *
+ *            APR_SO_DEBUG      --  turn on debugging information 
+ *            APR_SO_KEEPALIVE  --  keep connections active
+ *            APR_SO_LINGER     --  lingers on close if data is present
+ *            APR_SO_NONBLOCK   --  Turns blocking on/off for socket
+ *            APR_SO_REUSEADDR  --  The rules used in validating addresses
+ *                                  supplied to bind should allow reuse
+ *                                  of local addresses.
+ *            APR_SO_SNDBUF     --  Set the SendBufferSize
+ *            APR_SO_RCVBUF     --  Set the ReceiveBufferSize
+ *            APR_SO_DISCONNECTED -- Query the disconnected state of the socket.
+ *                                  (Currently only used on Windows)
+ * 
+ * @param on Socket option returned on the call. + */ +APR_DECLARE(apr_status_t) apr_socket_opt_get(apr_socket_t *sock, + apr_int32_t opt, apr_int32_t *on); + +/** + * Query socket timeout for the specified socket + * @param sock The socket to query + * @param t Socket timeout returned from the query. + */ +APR_DECLARE(apr_status_t) apr_socket_timeout_get(apr_socket_t *sock, + apr_interval_time_t *t); + +/** + * Query the specified socket if at the OOB/Urgent data mark + * @param sock The socket to query + * @param atmark Is set to true if socket is at the OOB/urgent mark, + * otherwise is set to false. + */ +APR_DECLARE(apr_status_t) apr_socket_atmark(apr_socket_t *sock, + int *atmark); + +/** + * Return an address associated with a socket; either the address to + * which the socket is bound locally or the address of the peer + * to which the socket is connected. + * @param sa The returned apr_sockaddr_t. + * @param which Whether to retrieve the local or remote address + * @param sock The socket to use + */ +APR_DECLARE(apr_status_t) apr_socket_addr_get(apr_sockaddr_t **sa, + apr_interface_e which, + apr_socket_t *sock); + +/** + * Return the IP address (in numeric address string format) in + * an APR socket address. APR will allocate storage for the IP address + * string from the pool of the apr_sockaddr_t. + * @param addr The IP address. + * @param sockaddr The socket address to reference. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_ip_get(char **addr, + apr_sockaddr_t *sockaddr); + +/** + * Write the IP address (in numeric address string format) of the APR + * socket address @a sockaddr into the buffer @a buf (of size @a buflen). + * @param sockaddr The socket address to reference. + */ +APR_DECLARE(apr_status_t) apr_sockaddr_ip_getbuf(char *buf, apr_size_t buflen, + apr_sockaddr_t *sockaddr); + +/** + * See if the IP addresses in two APR socket addresses are + * equivalent. Appropriate logic is present for comparing + * IPv4-mapped IPv6 addresses with IPv4 addresses. + * + * @param addr1 One of the APR socket addresses. + * @param addr2 The other APR socket address. + * @remark The return value will be non-zero if the addresses + * are equivalent. + */ +APR_DECLARE(int) apr_sockaddr_equal(const apr_sockaddr_t *addr1, + const apr_sockaddr_t *addr2); + +/** + * See if the IP address in an APR socket address refers to the wildcard + * address for the protocol family (e.g., INADDR_ANY for IPv4). + * + * @param addr The APR socket address to examine. + * @remark The return value will be non-zero if the address is + * initialized and is the wildcard address. + */ +APR_DECLARE(int) apr_sockaddr_is_wildcard(const apr_sockaddr_t *addr); + +/** +* Return the type of the socket. +* @param sock The socket to query. +* @param type The returned type (e.g., SOCK_STREAM). +*/ +APR_DECLARE(apr_status_t) apr_socket_type_get(apr_socket_t *sock, + int *type); + +/** + * Given an apr_sockaddr_t and a service name, set the port for the service + * @param sockaddr The apr_sockaddr_t that will have its port set + * @param servname The name of the service you wish to use + */ +APR_DECLARE(apr_status_t) apr_getservbyname(apr_sockaddr_t *sockaddr, + const char *servname); +/** + * Build an ip-subnet representation from an IP address and optional netmask or + * number-of-bits. + * @param ipsub The new ip-subnet representation + * @param ipstr The input IP address string + * @param mask_or_numbits The input netmask or number-of-bits string, or NULL + * @param p The pool to allocate from + */ +APR_DECLARE(apr_status_t) apr_ipsubnet_create(apr_ipsubnet_t **ipsub, + const char *ipstr, + const char *mask_or_numbits, + apr_pool_t *p); + +/** + * Test the IP address in an apr_sockaddr_t against a pre-built ip-subnet + * representation. + * @param ipsub The ip-subnet representation + * @param sa The socket address to test + * @return non-zero if the socket address is within the subnet, 0 otherwise + */ +APR_DECLARE(int) apr_ipsubnet_test(apr_ipsubnet_t *ipsub, apr_sockaddr_t *sa); + +#if APR_HAS_SO_ACCEPTFILTER || defined(DOXYGEN) +/** + * Set an OS level accept filter. + * @param sock The socket to put the accept filter on. + * @param name The accept filter + * @param args Any extra args to the accept filter. Passing NULL here removes + * the accept filter. + * @bug name and args should have been declared as const char *, as they are in + * APR 2.0 + */ +apr_status_t apr_socket_accept_filter(apr_socket_t *sock, char *name, + char *args); +#endif + +/** + * Return the protocol of the socket. + * @param sock The socket to query. + * @param protocol The returned protocol (e.g., APR_PROTO_TCP). + */ +APR_DECLARE(apr_status_t) apr_socket_protocol_get(apr_socket_t *sock, + int *protocol); + +/** + * Get the pool used by the socket. + */ +APR_POOL_DECLARE_ACCESSOR(socket); + +/** + * Set a socket to be inherited by child processes. + */ +APR_DECLARE_INHERIT_SET(socket); + +/** + * Unset a socket from being inherited by child processes. + */ +APR_DECLARE_INHERIT_UNSET(socket); + +/** + * Set socket permissions. + */ +APR_PERMS_SET_IMPLEMENT(socket); + +/** + * @defgroup apr_mcast IP Multicast + * @{ + */ + +/** + * Join a Multicast Group + * @param sock The socket to join a multicast group + * @param join The address of the multicast group to join + * @param iface Address of the interface to use. If NULL is passed, the + * default multicast interface will be used. (OS Dependent) + * @param source Source Address to accept transmissions from (non-NULL + * implies Source-Specific Multicast) + */ +APR_DECLARE(apr_status_t) apr_mcast_join(apr_socket_t *sock, + apr_sockaddr_t *join, + apr_sockaddr_t *iface, + apr_sockaddr_t *source); + +/** + * Leave a Multicast Group. All arguments must be the same as + * apr_mcast_join. + * @param sock The socket to leave a multicast group + * @param addr The address of the multicast group to leave + * @param iface Address of the interface to use. If NULL is passed, the + * default multicast interface will be used. (OS Dependent) + * @param source Source Address to accept transmissions from (non-NULL + * implies Source-Specific Multicast) + */ +APR_DECLARE(apr_status_t) apr_mcast_leave(apr_socket_t *sock, + apr_sockaddr_t *addr, + apr_sockaddr_t *iface, + apr_sockaddr_t *source); + +/** + * Set the Multicast Time to Live (ttl) for a multicast transmission. + * @param sock The socket to set the multicast ttl + * @param ttl Time to live to Assign. 0-255, default=1 + * @remark If the TTL is 0, packets will only be seen by sockets on + * the local machine, and only when multicast loopback is enabled. + */ +APR_DECLARE(apr_status_t) apr_mcast_hops(apr_socket_t *sock, + apr_byte_t ttl); + +/** + * Toggle IP Multicast Loopback + * @param sock The socket to set multicast loopback + * @param opt 0=disable, 1=enable + */ +APR_DECLARE(apr_status_t) apr_mcast_loopback(apr_socket_t *sock, + apr_byte_t opt); + + +/** + * Set the Interface to be used for outgoing Multicast Transmissions. + * @param sock The socket to set the multicast interface on + * @param iface Address of the interface to use for Multicast + */ +APR_DECLARE(apr_status_t) apr_mcast_interface(apr_socket_t *sock, + apr_sockaddr_t *iface); + +/** @} */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_NETWORK_IO_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_optional.h b/c/dependencies/windows/apr/x86_debug/include/apr_optional.h new file mode 100644 index 00000000..3301d66e --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_optional.h @@ -0,0 +1,92 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_OPTIONAL_H +#define APR_OPTIONAL_H + +#include "apu.h" +/** + * @file apr_optional.h + * @brief APR-UTIL registration of functions exported by modules + */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Opt Optional Functions + * @ingroup APR_Util + * + * Typesafe registration and retrieval of functions that may not be present + * (i.e. functions exported by optional modules) + * @{ + */ + +/** + * The type of an optional function. + * @param name The name of the function + */ +#define APR_OPTIONAL_FN_TYPE(name) apr_OFN_##name##_t + +/** + * Declare an optional function. + * @param ret The return type of the function + * @param name The name of the function + * @param args The function arguments (including brackets) + */ +#define APR_DECLARE_OPTIONAL_FN(ret,name,args) \ +typedef ret (APR_OPTIONAL_FN_TYPE(name)) args + +/** + * XXX: This doesn't belong here, then! + * Private function! DO NOT USE! + * @internal + */ + +typedef void (apr_opt_fn_t)(void); +/** @internal */ +APU_DECLARE_NONSTD(void) apr_dynamic_fn_register(const char *szName, + apr_opt_fn_t *pfn); + +/** + * Register an optional function. This can be later retrieved, type-safely, by + * name. Like all global functions, the name must be unique. Note that, + * confusingly but correctly, the function itself can be static! + * @param name The name of the function + */ +#define APR_REGISTER_OPTIONAL_FN(name) do { \ + APR_OPTIONAL_FN_TYPE(name) *apu__opt = name; \ + apr_dynamic_fn_register(#name,(apr_opt_fn_t *)apu__opt); \ +} while (0) + +/** @internal + * Private function! DO NOT USE! + */ +APU_DECLARE(apr_opt_fn_t *) apr_dynamic_fn_retrieve(const char *szName); + +/** + * Retrieve an optional function. Returns NULL if the function is not present. + * @param name The name of the function + */ +#define APR_RETRIEVE_OPTIONAL_FN(name) \ + (APR_OPTIONAL_FN_TYPE(name) *)apr_dynamic_fn_retrieve(#name) + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_OPTIONAL_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_optional_hooks.h b/c/dependencies/windows/apr/x86_debug/include/apr_optional_hooks.h new file mode 100644 index 00000000..8265f03f --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_optional_hooks.h @@ -0,0 +1,117 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file apr_optional_hooks.h + * @brief Apache optional hook functions + */ + + +#ifndef APR_OPTIONAL_HOOK_H +#define APR_OPTIONAL_HOOK_H + +#include "apr_tables.h" + +#ifdef __cplusplus +extern "C" { +#endif +/** + * @defgroup APR_Util_OPT_HOOK Optional Hook Functions + * @ingroup APR_Util_Hook + * @{ + */ +/** + * Function to implement the APR_OPTIONAL_HOOK Macro + * @internal + * @see APR_OPTIONAL_HOOK + * + * @param szName The name of the hook + * @param pfn A pointer to a function that will be called + * @param aszPre a NULL-terminated array of strings that name modules whose hooks should precede this one + * @param aszSucc a NULL-terminated array of strings that name modules whose hooks should succeed this one + * @param nOrder an integer determining order before honouring aszPre and aszSucc (for example HOOK_MIDDLE) + */ + + +APU_DECLARE(void) apr_optional_hook_add(const char *szName,void (*pfn)(void), + const char * const *aszPre, + const char * const *aszSucc, + int nOrder); + +/** + * Hook to an optional hook. + * + * @param ns The namespace prefix of the hook functions + * @param name The name of the hook + * @param pfn A pointer to a function that will be called + * @param aszPre a NULL-terminated array of strings that name modules whose hooks should precede this one + * @param aszSucc a NULL-terminated array of strings that name modules whose hooks should succeed this one + * @param nOrder an integer determining order before honouring aszPre and aszSucc (for example HOOK_MIDDLE) + */ + +#define APR_OPTIONAL_HOOK(ns,name,pfn,aszPre,aszSucc,nOrder) do { \ + ns##_HOOK_##name##_t *apu__hook = pfn; \ + apr_optional_hook_add(#name,(void (*)(void))apu__hook,aszPre, aszSucc, nOrder); \ +} while (0) + +/** + * @internal + * @param szName - the name of the function + * @return the hook structure for a given hook + */ +APU_DECLARE(apr_array_header_t *) apr_optional_hook_get(const char *szName); + +/** + * Implement an optional hook that runs until one of the functions + * returns something other than OK or DECLINE. + * + * @param ns The namespace prefix of the hook functions + * @param link The linkage declaration prefix of the hook + * @param ret The type of the return value of the hook + * @param ret The type of the return value of the hook + * @param name The name of the hook + * @param args_decl The declaration of the arguments for the hook + * @param args_use The names for the arguments for the hook + * @param ok Success value + * @param decline Decline value + */ +#define APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(ns,link,ret,name,args_decl,args_use,ok,decline) \ +link##_DECLARE(ret) ns##_run_##name args_decl \ + { \ + ns##_LINK_##name##_t *pHook; \ + int n; \ + ret rv; \ + apr_array_header_t *pHookArray=apr_optional_hook_get(#name); \ +\ + if(!pHookArray) \ + return ok; \ +\ + pHook=(ns##_LINK_##name##_t *)pHookArray->elts; \ + for(n=0 ; n < pHookArray->nelts ; ++n) \ + { \ + rv=(pHook[n].pFunc)args_use; \ +\ + if(rv != ok && rv != decline) \ + return rv; \ + } \ + return ok; \ + } + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_OPTIONAL_HOOK_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_perms_set.h b/c/dependencies/windows/apr/x86_debug/include/apr_perms_set.h new file mode 100644 index 00000000..92a1362b --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_perms_set.h @@ -0,0 +1,65 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_PERMS_SET_H +#define APR_PERMS_SET_H + +/** + * @file apr_perms_set.h + * @brief APR Process Locking Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_user.h" +#include "apr_file_info.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_perms_set Object permission set functions + * @ingroup APR + * @{ + */ + +/** Permission set callback function. */ +typedef apr_status_t (apr_perms_setfn_t)(void *object, apr_fileperms_t perms, + apr_uid_t uid, apr_gid_t gid); + +#define APR_PERMS_SET_IMPLEMENT(type) \ + APR_DECLARE(apr_status_t) apr_##type##_perms_set \ + (void *the##type, apr_fileperms_t perms, \ + apr_uid_t uid, apr_gid_t gid) + +#define APR_PERMS_SET_ENOTIMPL(type) \ + APR_DECLARE(apr_status_t) apr_##type##_perms_set \ + (void *the##type, apr_fileperms_t perms, \ + apr_uid_t uid, apr_gid_t gid) \ + { return APR_ENOTIMPL ; } + +#define APR_PERMS_SET_FN(type) apr_##type##_perms_set + + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_PERMS_SET */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_poll.h b/c/dependencies/windows/apr/x86_debug/include/apr_poll.h new file mode 100644 index 00000000..482d6ee1 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_poll.h @@ -0,0 +1,446 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_POLL_H +#define APR_POLL_H +/** + * @file apr_poll.h + * @brief APR Poll interface + */ +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_inherit.h" +#include "apr_file_io.h" +#include "apr_network_io.h" + +#if APR_HAVE_NETINET_IN_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_poll Poll Routines + * @ingroup APR + * @{ + */ + +/** + * @defgroup pollopts Poll options + * @ingroup apr_poll + * @{ + */ +#define APR_POLLIN 0x001 /**< Can read without blocking */ +#define APR_POLLPRI 0x002 /**< Priority data available */ +#define APR_POLLOUT 0x004 /**< Can write without blocking */ +#define APR_POLLERR 0x010 /**< Pending error */ +#define APR_POLLHUP 0x020 /**< Hangup occurred */ +#define APR_POLLNVAL 0x040 /**< Descriptor invalid */ +/** @} */ + +/** + * @defgroup pollflags Pollset Flags + * @ingroup apr_poll + * @{ + */ +#define APR_POLLSET_THREADSAFE 0x001 /**< Adding or removing a descriptor is + * thread-safe + */ +#define APR_POLLSET_NOCOPY 0x002 /**< Descriptors passed to apr_pollset_add() + * are not copied + */ +#define APR_POLLSET_WAKEABLE 0x004 /**< Poll operations are interruptable by + * apr_pollset_wakeup() or apr_pollcb_wakeup() + */ +#define APR_POLLSET_NODEFAULT 0x010 /**< Do not try to use the default method if + * the specified non-default method cannot be + * used + */ +/** @} */ + +/** + * Pollset Methods + */ +typedef enum { + APR_POLLSET_DEFAULT, /**< Platform default poll method */ + APR_POLLSET_SELECT, /**< Poll uses select method */ + APR_POLLSET_KQUEUE, /**< Poll uses kqueue method */ + APR_POLLSET_PORT, /**< Poll uses Solaris event port method */ + APR_POLLSET_EPOLL, /**< Poll uses epoll method */ + APR_POLLSET_POLL, /**< Poll uses poll method */ + APR_POLLSET_AIO_MSGQ /**< Poll uses z/OS asio method */ +} apr_pollset_method_e; + +/** Used in apr_pollfd_t to determine what the apr_descriptor is */ +typedef enum { + APR_NO_DESC, /**< nothing here */ + APR_POLL_SOCKET, /**< descriptor refers to a socket */ + APR_POLL_FILE, /**< descriptor refers to a file */ + APR_POLL_LASTDESC /**< @deprecated descriptor is the last one in the list */ +} apr_datatype_e ; + +/** Union of either an APR file or socket. */ +typedef union { + apr_file_t *f; /**< file */ + apr_socket_t *s; /**< socket */ +} apr_descriptor; + +/** @see apr_pollfd_t */ +typedef struct apr_pollfd_t apr_pollfd_t; + +/** Poll descriptor set. */ +struct apr_pollfd_t { + apr_pool_t *p; /**< associated pool */ + apr_datatype_e desc_type; /**< descriptor type */ + apr_int16_t reqevents; /**< requested events */ + apr_int16_t rtnevents; /**< returned events */ + apr_descriptor desc; /**< @see apr_descriptor */ + void *client_data; /**< allows app to associate context */ +}; + + +/* General-purpose poll API for arbitrarily large numbers of + * file descriptors + */ + +/** Opaque structure used for pollset API */ +typedef struct apr_pollset_t apr_pollset_t; + +/** + * Set up a pollset object + * @param pollset The pointer in which to return the newly created object + * @param size The maximum number of descriptors that this pollset can hold + * @param p The pool from which to allocate the pollset + * @param flags Optional flags to modify the operation of the pollset. + * + * @remark If flags contains APR_POLLSET_THREADSAFE, then a pollset is + * created on which it is safe to make concurrent calls to + * apr_pollset_add(), apr_pollset_remove() and apr_pollset_poll() + * from separate threads. This feature is only supported on some + * platforms; the apr_pollset_create() call will fail with + * APR_ENOTIMPL on platforms where it is not supported. + * @remark If flags contains APR_POLLSET_WAKEABLE, then a pollset is + * created with an additional internal pipe object used for the + * apr_pollset_wakeup() call. The actual size of pollset is + * in that case @a size + 1. This feature is only supported on some + * platforms; the apr_pollset_create() call will fail with + * APR_ENOTIMPL on platforms where it is not supported. + * @remark If flags contains APR_POLLSET_NOCOPY, then the apr_pollfd_t + * structures passed to apr_pollset_add() are not copied and + * must have a lifetime at least as long as the pollset. + * @remark Some poll methods (including APR_POLLSET_KQUEUE, + * APR_POLLSET_PORT, and APR_POLLSET_EPOLL) do not have a + * fixed limit on the size of the pollset. For these methods, + * the size parameter controls the maximum number of + * descriptors that will be returned by a single call to + * apr_pollset_poll(). + */ +APR_DECLARE(apr_status_t) apr_pollset_create(apr_pollset_t **pollset, + apr_uint32_t size, + apr_pool_t *p, + apr_uint32_t flags); + +/** + * Set up a pollset object + * @param pollset The pointer in which to return the newly created object + * @param size The maximum number of descriptors that this pollset can hold + * @param p The pool from which to allocate the pollset + * @param flags Optional flags to modify the operation of the pollset. + * @param method Poll method to use. See #apr_pollset_method_e. If this + * method cannot be used, the default method will be used unless the + * APR_POLLSET_NODEFAULT flag has been specified. + * + * @remark If flags contains APR_POLLSET_THREADSAFE, then a pollset is + * created on which it is safe to make concurrent calls to + * apr_pollset_add(), apr_pollset_remove() and apr_pollset_poll() + * from separate threads. This feature is only supported on some + * platforms; the apr_pollset_create_ex() call will fail with + * APR_ENOTIMPL on platforms where it is not supported. + * @remark If flags contains APR_POLLSET_WAKEABLE, then a pollset is + * created with additional internal pipe object used for the + * apr_pollset_wakeup() call. The actual size of pollset is + * in that case size + 1. This feature is only supported on some + * platforms; the apr_pollset_create_ex() call will fail with + * APR_ENOTIMPL on platforms where it is not supported. + * @remark If flags contains APR_POLLSET_NOCOPY, then the apr_pollfd_t + * structures passed to apr_pollset_add() are not copied and + * must have a lifetime at least as long as the pollset. + * @remark Some poll methods (including APR_POLLSET_KQUEUE, + * APR_POLLSET_PORT, and APR_POLLSET_EPOLL) do not have a + * fixed limit on the size of the pollset. For these methods, + * the size parameter controls the maximum number of + * descriptors that will be returned by a single call to + * apr_pollset_poll(). + */ +APR_DECLARE(apr_status_t) apr_pollset_create_ex(apr_pollset_t **pollset, + apr_uint32_t size, + apr_pool_t *p, + apr_uint32_t flags, + apr_pollset_method_e method); + +/** + * Destroy a pollset object + * @param pollset The pollset to destroy + */ +APR_DECLARE(apr_status_t) apr_pollset_destroy(apr_pollset_t *pollset); + +/** + * Add a socket or file descriptor to a pollset + * @param pollset The pollset to which to add the descriptor + * @param descriptor The descriptor to add + * @remark If you set client_data in the descriptor, that value + * will be returned in the client_data field whenever this + * descriptor is signalled in apr_pollset_poll(). + * @remark If the pollset has been created with APR_POLLSET_THREADSAFE + * and thread T1 is blocked in a call to apr_pollset_poll() for + * this same pollset that is being modified via apr_pollset_add() + * in thread T2, the currently executing apr_pollset_poll() call in + * T1 will either: (1) automatically include the newly added descriptor + * in the set of descriptors it is watching or (2) return immediately + * with APR_EINTR. Option (1) is recommended, but option (2) is + * allowed for implementations where option (1) is impossible + * or impractical. + * @remark If the pollset has been created with APR_POLLSET_NOCOPY, the + * apr_pollfd_t structure referenced by descriptor will not be copied + * and must have a lifetime at least as long as the pollset. + * @remark Do not add the same socket or file descriptor to the same pollset + * multiple times, even if the requested events differ for the + * different calls to apr_pollset_add(). If the events of interest + * for a descriptor change, you must first remove the descriptor + * from the pollset with apr_pollset_remove(), then add it again + * specifying all requested events. + */ +APR_DECLARE(apr_status_t) apr_pollset_add(apr_pollset_t *pollset, + const apr_pollfd_t *descriptor); + +/** + * Remove a descriptor from a pollset + * @param pollset The pollset from which to remove the descriptor + * @param descriptor The descriptor to remove + * @remark If the descriptor is not found, APR_NOTFOUND is returned. + * @remark If the pollset has been created with APR_POLLSET_THREADSAFE + * and thread T1 is blocked in a call to apr_pollset_poll() for + * this same pollset that is being modified via apr_pollset_remove() + * in thread T2, the currently executing apr_pollset_poll() call in + * T1 will either: (1) automatically exclude the newly added descriptor + * in the set of descriptors it is watching or (2) return immediately + * with APR_EINTR. Option (1) is recommended, but option (2) is + * allowed for implementations where option (1) is impossible + * or impractical. + * @remark apr_pollset_remove() cannot be used to remove a subset of requested + * events for a descriptor. The reqevents field in the apr_pollfd_t + * parameter must contain the same value when removing as when adding. + */ +APR_DECLARE(apr_status_t) apr_pollset_remove(apr_pollset_t *pollset, + const apr_pollfd_t *descriptor); + +/** + * Block for activity on the descriptor(s) in a pollset + * @param pollset The pollset to use + * @param timeout The amount of time in microseconds to wait. This is a + * maximum, not a minimum. If a descriptor is signalled, the + * function will return before this time. If timeout is + * negative, the function will block until a descriptor is + * signalled or until apr_pollset_wakeup() has been called. + * @param num Number of signalled descriptors (output parameter) + * @param descriptors Array of signalled descriptors (output parameter) + * @remark APR_EINTR will be returned if the pollset has been created with + * APR_POLLSET_WAKEABLE, apr_pollset_wakeup() has been called while + * waiting for activity, and there were no signalled descriptors at the + * time of the wakeup call. + * @remark Multiple signalled conditions for the same descriptor may be reported + * in one or more returned apr_pollfd_t structures, depending on the + * implementation. + */ +APR_DECLARE(apr_status_t) apr_pollset_poll(apr_pollset_t *pollset, + apr_interval_time_t timeout, + apr_int32_t *num, + const apr_pollfd_t **descriptors); + +/** + * Interrupt the blocked apr_pollset_poll() call. + * @param pollset The pollset to use + * @remark If the pollset was not created with APR_POLLSET_WAKEABLE the + * return value is APR_EINIT. + */ +APR_DECLARE(apr_status_t) apr_pollset_wakeup(apr_pollset_t *pollset); + +/** + * Poll the descriptors in the poll structure + * @param aprset The poll structure we will be using. + * @param numsock The number of descriptors we are polling + * @param nsds The number of descriptors signalled (output parameter) + * @param timeout The amount of time in microseconds to wait. This is a + * maximum, not a minimum. If a descriptor is signalled, the + * function will return before this time. If timeout is + * negative, the function will block until a descriptor is + * signalled or until apr_pollset_wakeup() has been called. + * @remark The number of descriptors signalled is returned in the third argument. + * This is a blocking call, and it will not return until either a + * descriptor has been signalled or the timeout has expired. + * @remark The rtnevents field in the apr_pollfd_t array will only be filled- + * in if the return value is APR_SUCCESS. + */ +APR_DECLARE(apr_status_t) apr_poll(apr_pollfd_t *aprset, apr_int32_t numsock, + apr_int32_t *nsds, + apr_interval_time_t timeout); + +/** + * Return a printable representation of the pollset method. + * @param pollset The pollset to use + */ +APR_DECLARE(const char *) apr_pollset_method_name(apr_pollset_t *pollset); + +/** + * Return a printable representation of the default pollset method + * (APR_POLLSET_DEFAULT). + */ +APR_DECLARE(const char *) apr_poll_method_defname(void); + +/** Opaque structure used for pollcb API */ +typedef struct apr_pollcb_t apr_pollcb_t; + +/** + * Set up a pollcb object + * @param pollcb The pointer in which to return the newly created object + * @param size The maximum number of descriptors that a single _poll can return. + * @param p The pool from which to allocate the pollcb + * @param flags Optional flags to modify the operation of the pollcb. + * + * @remark If flags contains APR_POLLSET_WAKEABLE, then a pollcb is + * created with an additional internal pipe object used for the + * apr_pollcb_wakeup() call. The actual size of pollcb is + * in that case @a size + 1. + * @remark Pollcb is only supported on some platforms; the apr_pollcb_create() + * call will fail with APR_ENOTIMPL on platforms where it is not supported. + */ +APR_DECLARE(apr_status_t) apr_pollcb_create(apr_pollcb_t **pollcb, + apr_uint32_t size, + apr_pool_t *p, + apr_uint32_t flags); + +/** + * Set up a pollcb object + * @param pollcb The pointer in which to return the newly created object + * @param size The maximum number of descriptors that a single _poll can return. + * @param p The pool from which to allocate the pollcb + * @param flags Optional flags to modify the operation of the pollcb. + * @param method Poll method to use. See #apr_pollset_method_e. If this + * method cannot be used, the default method will be used unless the + * APR_POLLSET_NODEFAULT flag has been specified. + * + * @remark If flags contains APR_POLLSET_WAKEABLE, then a pollcb is + * created with an additional internal pipe object used for the + * apr_pollcb_wakeup() call. The actual size of pollcb is + * in that case @a size + 1. + * @remark Pollcb is only supported on some platforms; the apr_pollcb_create_ex() + * call will fail with APR_ENOTIMPL on platforms where it is not supported. + */ +APR_DECLARE(apr_status_t) apr_pollcb_create_ex(apr_pollcb_t **pollcb, + apr_uint32_t size, + apr_pool_t *p, + apr_uint32_t flags, + apr_pollset_method_e method); + +/** + * Add a socket or file descriptor to a pollcb + * @param pollcb The pollcb to which to add the descriptor + * @param descriptor The descriptor to add + * @remark If you set client_data in the descriptor, that value will be + * returned in the client_data field whenever this descriptor is + * signalled in apr_pollcb_poll(). + * @remark Unlike the apr_pollset API, the descriptor is not copied, and users + * must retain the memory used by descriptor, as the same pointer will + * be returned to them from apr_pollcb_poll. + * @remark Do not add the same socket or file descriptor to the same pollcb + * multiple times, even if the requested events differ for the + * different calls to apr_pollcb_add(). If the events of interest + * for a descriptor change, you must first remove the descriptor + * from the pollcb with apr_pollcb_remove(), then add it again + * specifying all requested events. + */ +APR_DECLARE(apr_status_t) apr_pollcb_add(apr_pollcb_t *pollcb, + apr_pollfd_t *descriptor); +/** + * Remove a descriptor from a pollcb + * @param pollcb The pollcb from which to remove the descriptor + * @param descriptor The descriptor to remove + * @remark If the descriptor is not found, APR_NOTFOUND is returned. + * @remark apr_pollcb_remove() cannot be used to remove a subset of requested + * events for a descriptor. The reqevents field in the apr_pollfd_t + * parameter must contain the same value when removing as when adding. + */ +APR_DECLARE(apr_status_t) apr_pollcb_remove(apr_pollcb_t *pollcb, + apr_pollfd_t *descriptor); + +/** + * Function prototype for pollcb handlers + * @param baton Opaque baton passed into apr_pollcb_poll() + * @param descriptor Contains the notification for an active descriptor. + * The @a rtnevents member describes which events were triggered + * for this descriptor. + * @remark If the pollcb handler does not return APR_SUCCESS, the apr_pollcb_poll() + * call returns with the handler's return value. + */ +typedef apr_status_t (*apr_pollcb_cb_t)(void *baton, apr_pollfd_t *descriptor); + +/** + * Block for activity on the descriptor(s) in a pollcb + * @param pollcb The pollcb to use + * @param timeout The amount of time in microseconds to wait. This is a + * maximum, not a minimum. If a descriptor is signalled, the + * function will return before this time. If timeout is + * negative, the function will block until a descriptor is + * signalled or until apr_pollcb_wakeup() has been called. + * @param func Callback function to call for each active descriptor. + * @param baton Opaque baton passed to the callback function. + * @remark Multiple signalled conditions for the same descriptor may be reported + * in one or more calls to the callback function, depending on the + * implementation. + * @remark APR_EINTR will be returned if the pollset has been created with + * APR_POLLSET_WAKEABLE and apr_pollcb_wakeup() has been called while + * waiting for activity. + */ +APR_DECLARE(apr_status_t) apr_pollcb_poll(apr_pollcb_t *pollcb, + apr_interval_time_t timeout, + apr_pollcb_cb_t func, + void *baton); + +/** + * Interrupt the blocked apr_pollcb_poll() call. + * @param pollcb The pollcb to use + * @remark If the pollcb was not created with APR_POLLSET_WAKEABLE the + * return value is APR_EINIT. + */ +APR_DECLARE(apr_status_t) apr_pollcb_wakeup(apr_pollcb_t *pollcb); + +/** + * Return a printable representation of the pollcb method. + * @param pollcb The pollcb to use + */ +APR_DECLARE(const char *) apr_pollcb_method_name(apr_pollcb_t *pollcb); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_POLL_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_pools.h b/c/dependencies/windows/apr/x86_debug/include/apr_pools.h new file mode 100644 index 00000000..783c9c42 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_pools.h @@ -0,0 +1,815 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_POOLS_H +#define APR_POOLS_H + +/** + * @file apr_pools.h + * @brief APR memory allocation + * + * Resource allocation routines... + * + * designed so that we don't have to keep track of EVERYTHING so that + * it can be explicitly freed later (a fundamentally unsound strategy --- + * particularly in the presence of die()). + * + * Instead, we maintain pools, and allocate items (both memory and I/O + * handlers) from the pools --- currently there are two, one for + * per-transaction info, and one for config info. When a transaction is + * over, we can delete everything in the per-transaction apr_pool_t without + * fear, and without thinking too hard about it either. + * + * Note that most operations on pools are not thread-safe: a single pool + * should only be accessed by a single thread at any given time. The one + * exception to this rule is creating a subpool of a given pool: one or more + * threads can safely create subpools at the same time that another thread + * accesses the parent pool. + */ + +#include "apr.h" +#include "apr_errno.h" +#include "apr_general.h" /* for APR_STRINGIFY */ +#define APR_WANT_MEMFUNC /**< for no good reason? */ +#include "apr_want.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup apr_pools Memory Pool Functions + * @ingroup APR + * @{ + */ + +/** The fundamental pool type */ +typedef struct apr_pool_t apr_pool_t; + + +/** + * Declaration helper macro to construct apr_foo_pool_get()s. + * + * This standardized macro is used by opaque (APR) data types to return + * the apr_pool_t that is associated with the data type. + * + * APR_POOL_DECLARE_ACCESSOR() is used in a header file to declare the + * accessor function. A typical usage and result would be: + *
+ *    APR_POOL_DECLARE_ACCESSOR(file);
+ * becomes:
+ *    APR_DECLARE(apr_pool_t *) apr_file_pool_get(const apr_file_t *thefile);
+ * 
+ * @remark Doxygen unwraps this macro (via doxygen.conf) to provide + * actual help for each specific occurrence of apr_foo_pool_get. + * @remark the linkage is specified for APR. It would be possible to expand + * the macros to support other linkages. + */ +#define APR_POOL_DECLARE_ACCESSOR(type) \ + APR_DECLARE(apr_pool_t *) apr_##type##_pool_get \ + (const apr_##type##_t *the##type) + +/** + * Implementation helper macro to provide apr_foo_pool_get()s. + * + * In the implementation, the APR_POOL_IMPLEMENT_ACCESSOR() is used to + * actually define the function. It assumes the field is named "pool". + */ +#define APR_POOL_IMPLEMENT_ACCESSOR(type) \ + APR_DECLARE(apr_pool_t *) apr_##type##_pool_get \ + (const apr_##type##_t *the##type) \ + { return the##type->pool; } + + +/** + * Pool debug levels + * + *
+ * | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
+ * ---------------------------------
+ * |   |   |   |   |   |   |   | x |  General debug code enabled (useful in
+ *                                    combination with --with-efence).
+ *
+ * |   |   |   |   |   |   | x |   |  Verbose output on stderr (report
+ *                                    CREATE, CLEAR, DESTROY).
+ *
+ * |   |   |   | x |   |   |   |   |  Verbose output on stderr (report
+ *                                    PALLOC, PCALLOC).
+ *
+ * |   |   |   |   |   | x |   |   |  Lifetime checking. On each use of a
+ *                                    pool, check its lifetime.  If the pool
+ *                                    is out of scope, abort().
+ *                                    In combination with the verbose flag
+ *                                    above, it will output LIFE in such an
+ *                                    event prior to aborting.
+ *
+ * |   |   |   |   | x |   |   |   |  Pool owner checking.  On each use of a
+ *                                    pool, check if the current thread is the
+ *                                    pool's owner.  If not, abort().  In
+ *                                    combination with the verbose flag above,
+ *                                    it will output OWNER in such an event
+ *                                    prior to aborting.  Use the debug
+ *                                    function apr_pool_owner_set() to switch
+ *                                    a pool's ownership.
+ *
+ * When no debug level was specified, assume general debug mode.
+ * If level 0 was specified, debugging is switched off.
+ * 
+ */ +#if defined(APR_POOL_DEBUG) +/* If APR_POOL_DEBUG is blank, we get 1; if it is a number, we get -1. */ +#if (APR_POOL_DEBUG - APR_POOL_DEBUG -1 == 1) +#undef APR_POOL_DEBUG +#define APR_POOL_DEBUG 1 +#endif +#else +#define APR_POOL_DEBUG 0 +#endif + +/** the place in the code where the particular function was called */ +#define APR_POOL__FILE_LINE__ __FILE__ ":" APR_STRINGIFY(__LINE__) + + + +/** A function that is called when allocation fails. */ +typedef int (*apr_abortfunc_t)(int retcode); + +/* + * APR memory structure manipulators (pools, tables, and arrays). + */ + +/* + * Initialization + */ + +/** + * Setup all of the internal structures required to use pools + * @remark Programs do NOT need to call this directly. APR will call this + * automatically from apr_initialize. + * @internal + */ +APR_DECLARE(apr_status_t) apr_pool_initialize(void); + +/** + * Tear down all of the internal structures required to use pools + * @remark Programs do NOT need to call this directly. APR will call this + * automatically from apr_terminate. + * @internal + */ +APR_DECLARE(void) apr_pool_terminate(void); + + +/* + * Pool creation/destruction + */ + +#include "apr_allocator.h" + +/** + * Create a new pool. + * @param newpool The pool we have just created. + * @param parent The parent pool. If this is NULL, the new pool is a root + * pool. If it is non-NULL, the new pool will inherit all + * of its parent pool's attributes, except the apr_pool_t will + * be a sub-pool. + * @param abort_fn A function to use if the pool cannot allocate more memory. + * @param allocator The allocator to use with the new pool. If NULL the + * allocator of the parent pool will be used. + * @remark This function is thread-safe, in the sense that multiple threads + * can safely create subpools of the same parent pool concurrently. + * Similarly, a subpool can be created by one thread at the same + * time that another thread accesses the parent pool. + */ +APR_DECLARE(apr_status_t) apr_pool_create_ex(apr_pool_t **newpool, + apr_pool_t *parent, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +/** + * Create a new pool. + * @deprecated @see apr_pool_create_unmanaged_ex. + */ +APR_DECLARE(apr_status_t) apr_pool_create_core_ex(apr_pool_t **newpool, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator); + +/** + * Create a new unmanaged pool. + * @param newpool The pool we have just created. + * @param abort_fn A function to use if the pool cannot allocate more memory. + * @param allocator The allocator to use with the new pool. If NULL a + * new allocator will be created with the new pool as owner. + * @remark An unmanaged pool is a special pool without a parent; it will + * NOT be destroyed upon apr_terminate. It must be explicitly + * destroyed by calling apr_pool_destroy, to prevent memory leaks. + * Use of this function is discouraged, think twice about whether + * you really really need it. + * @warning Any child cleanups registered against the new pool, or + * against sub-pools thereof, will not be executed during an + * invocation of apr_proc_create(), so resources created in an + * "unmanaged" pool hierarchy will leak to child processes. + */ +APR_DECLARE(apr_status_t) apr_pool_create_unmanaged_ex(apr_pool_t **newpool, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator) + __attribute__((nonnull(1))); + +/** + * Debug version of apr_pool_create_ex. + * @param newpool @see apr_pool_create. + * @param parent @see apr_pool_create. + * @param abort_fn @see apr_pool_create. + * @param allocator @see apr_pool_create. + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @remark Only available when APR_POOL_DEBUG is defined. + * Call this directly if you have your apr_pool_create_ex + * calls in a wrapper function and wish to override + * the file_line argument to reflect the caller of + * your wrapper function. If you do not have + * apr_pool_create_ex in a wrapper, trust the macro + * and don't call apr_pool_create_ex_debug directly. + */ +APR_DECLARE(apr_status_t) apr_pool_create_ex_debug(apr_pool_t **newpool, + apr_pool_t *parent, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pool_create_ex(newpool, parent, abort_fn, allocator) \ + apr_pool_create_ex_debug(newpool, parent, abort_fn, allocator, \ + APR_POOL__FILE_LINE__) +#endif + +/** + * Debug version of apr_pool_create_core_ex. + * @deprecated @see apr_pool_create_unmanaged_ex_debug. + */ +APR_DECLARE(apr_status_t) apr_pool_create_core_ex_debug(apr_pool_t **newpool, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator, + const char *file_line); + +/** + * Debug version of apr_pool_create_unmanaged_ex. + * @param newpool @see apr_pool_create_unmanaged. + * @param abort_fn @see apr_pool_create_unmanaged. + * @param allocator @see apr_pool_create_unmanaged. + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @remark Only available when APR_POOL_DEBUG is defined. + * Call this directly if you have your apr_pool_create_unmanaged_ex + * calls in a wrapper function and wish to override + * the file_line argument to reflect the caller of + * your wrapper function. If you do not have + * apr_pool_create_core_ex in a wrapper, trust the macro + * and don't call apr_pool_create_core_ex_debug directly. + */ +APR_DECLARE(apr_status_t) apr_pool_create_unmanaged_ex_debug(apr_pool_t **newpool, + apr_abortfunc_t abort_fn, + apr_allocator_t *allocator, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pool_create_core_ex(newpool, abort_fn, allocator) \ + apr_pool_create_unmanaged_ex_debug(newpool, abort_fn, allocator, \ + APR_POOL__FILE_LINE__) + +#define apr_pool_create_unmanaged_ex(newpool, abort_fn, allocator) \ + apr_pool_create_unmanaged_ex_debug(newpool, abort_fn, allocator, \ + APR_POOL__FILE_LINE__) + +#endif + +/** + * Create a new pool. + * @param newpool The pool we have just created. + * @param parent The parent pool. If this is NULL, the new pool is a root + * pool. If it is non-NULL, the new pool will inherit all + * of its parent pool's attributes, except the apr_pool_t will + * be a sub-pool. + * @remark This function is thread-safe, in the sense that multiple threads + * can safely create subpools of the same parent pool concurrently. + * Similarly, a subpool can be created by one thread at the same + * time that another thread accesses the parent pool. + */ +#if defined(DOXYGEN) +APR_DECLARE(apr_status_t) apr_pool_create(apr_pool_t **newpool, + apr_pool_t *parent); +#else +#if APR_POOL_DEBUG +#define apr_pool_create(newpool, parent) \ + apr_pool_create_ex_debug(newpool, parent, NULL, NULL, \ + APR_POOL__FILE_LINE__) +#else +#define apr_pool_create(newpool, parent) \ + apr_pool_create_ex(newpool, parent, NULL, NULL) +#endif +#endif + +/** + * Create a new unmanaged pool. + * @param newpool The pool we have just created. + */ +#if defined(DOXYGEN) +APR_DECLARE(apr_status_t) apr_pool_create_core(apr_pool_t **newpool); +APR_DECLARE(apr_status_t) apr_pool_create_unmanaged(apr_pool_t **newpool); +#else +#if APR_POOL_DEBUG +#define apr_pool_create_core(newpool) \ + apr_pool_create_unmanaged_ex_debug(newpool, NULL, NULL, \ + APR_POOL__FILE_LINE__) +#define apr_pool_create_unmanaged(newpool) \ + apr_pool_create_unmanaged_ex_debug(newpool, NULL, NULL, \ + APR_POOL__FILE_LINE__) +#else +#define apr_pool_create_core(newpool) \ + apr_pool_create_unmanaged_ex(newpool, NULL, NULL) +#define apr_pool_create_unmanaged(newpool) \ + apr_pool_create_unmanaged_ex(newpool, NULL, NULL) +#endif +#endif + +/** + * Find the pool's allocator + * @param pool The pool to get the allocator from. + */ +APR_DECLARE(apr_allocator_t *) apr_pool_allocator_get(apr_pool_t *pool) + __attribute__((nonnull(1))); + +/** + * Clear all memory in the pool and run all the cleanups. This also destroys all + * subpools. + * @param p The pool to clear + * @remark This does not actually free the memory, it just allows the pool + * to re-use this memory for the next allocation. + * @see apr_pool_destroy() + */ +APR_DECLARE(void) apr_pool_clear(apr_pool_t *p) __attribute__((nonnull(1))); + +/** + * Debug version of apr_pool_clear. + * @param p See: apr_pool_clear. + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @remark Only available when APR_POOL_DEBUG is defined. + * Call this directly if you have your apr_pool_clear + * calls in a wrapper function and wish to override + * the file_line argument to reflect the caller of + * your wrapper function. If you do not have + * apr_pool_clear in a wrapper, trust the macro + * and don't call apr_pool_destroy_clear directly. + */ +APR_DECLARE(void) apr_pool_clear_debug(apr_pool_t *p, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pool_clear(p) \ + apr_pool_clear_debug(p, APR_POOL__FILE_LINE__) +#endif + +/** + * Destroy the pool. This takes similar action as apr_pool_clear() and then + * frees all the memory. + * @param p The pool to destroy + * @remark This will actually free the memory + */ +APR_DECLARE(void) apr_pool_destroy(apr_pool_t *p) __attribute__((nonnull(1))); + +/** + * Debug version of apr_pool_destroy. + * @param p See: apr_pool_destroy. + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @remark Only available when APR_POOL_DEBUG is defined. + * Call this directly if you have your apr_pool_destroy + * calls in a wrapper function and wish to override + * the file_line argument to reflect the caller of + * your wrapper function. If you do not have + * apr_pool_destroy in a wrapper, trust the macro + * and don't call apr_pool_destroy_debug directly. + */ +APR_DECLARE(void) apr_pool_destroy_debug(apr_pool_t *p, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pool_destroy(p) \ + apr_pool_destroy_debug(p, APR_POOL__FILE_LINE__) +#endif + + +/* + * Memory allocation + */ + +/** + * Allocate a block of memory from a pool + * @param p The pool to allocate from + * @param size The amount of memory to allocate + * @return The allocated memory + */ +APR_DECLARE(void *) apr_palloc(apr_pool_t *p, apr_size_t size) +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) + __attribute__((alloc_size(2))) +#endif + __attribute__((nonnull(1))); + +/** + * Debug version of apr_palloc + * @param p See: apr_palloc + * @param size See: apr_palloc + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @return See: apr_palloc + */ +APR_DECLARE(void *) apr_palloc_debug(apr_pool_t *p, apr_size_t size, + const char *file_line) +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) + __attribute__((alloc_size(2))) +#endif + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_palloc(p, size) \ + apr_palloc_debug(p, size, APR_POOL__FILE_LINE__) +#endif + +/** + * Allocate a block of memory from a pool and set all of the memory to 0 + * @param p The pool to allocate from + * @param size The amount of memory to allocate + * @return The allocated memory + */ +#if defined(DOXYGEN) +APR_DECLARE(void *) apr_pcalloc(apr_pool_t *p, apr_size_t size); +#elif !APR_POOL_DEBUG +#define apr_pcalloc(p, size) memset(apr_palloc(p, size), 0, size) +#endif + +/** + * Debug version of apr_pcalloc + * @param p See: apr_pcalloc + * @param size See: apr_pcalloc + * @param file_line Where the function is called from. + * This is usually APR_POOL__FILE_LINE__. + * @return See: apr_pcalloc + */ +APR_DECLARE(void *) apr_pcalloc_debug(apr_pool_t *p, apr_size_t size, + const char *file_line) + __attribute__((nonnull(1))); + +#if APR_POOL_DEBUG +#define apr_pcalloc(p, size) \ + apr_pcalloc_debug(p, size, APR_POOL__FILE_LINE__) +#endif + + +/* + * Pool Properties + */ + +/** + * Set the function to be called when an allocation failure occurs. + * @remark If the program wants APR to exit on a memory allocation error, + * then this function can be called to set the callback to use (for + * performing cleanup and then exiting). If this function is not called, + * then APR will return an error and expect the calling program to + * deal with the error accordingly. + */ +APR_DECLARE(void) apr_pool_abort_set(apr_abortfunc_t abortfunc, + apr_pool_t *pool) + __attribute__((nonnull(2))); + +/** + * Get the abort function associated with the specified pool. + * @param pool The pool for retrieving the abort function. + * @return The abort function for the given pool. + */ +APR_DECLARE(apr_abortfunc_t) apr_pool_abort_get(apr_pool_t *pool) + __attribute__((nonnull(1))); + +/** + * Get the parent pool of the specified pool. + * @param pool The pool for retrieving the parent pool. + * @return The parent of the given pool. + */ +APR_DECLARE(apr_pool_t *) apr_pool_parent_get(apr_pool_t *pool) + __attribute__((nonnull(1))); + +/** + * Determine if pool a is an ancestor of pool b. + * @param a The pool to search + * @param b The pool to search for + * @return True if a is an ancestor of b, NULL is considered an ancestor + * of all pools. + * @remark if compiled with APR_POOL_DEBUG, this function will also + * return true if A is a pool which has been guaranteed by the caller + * (using apr_pool_join) to have a lifetime at least as long as some + * ancestor of pool B. + */ +APR_DECLARE(int) apr_pool_is_ancestor(apr_pool_t *a, apr_pool_t *b); + +/** + * Tag a pool (give it a name) + * @param pool The pool to tag + * @param tag The tag + */ +APR_DECLARE(void) apr_pool_tag(apr_pool_t *pool, const char *tag) + __attribute__((nonnull(1))); + + +/* + * User data management + */ + +/** + * Set the data associated with the current pool + * @param data The user data associated with the pool. + * @param key The key to use for association + * @param cleanup The cleanup program to use to cleanup the data (NULL if none) + * @param pool The current pool + * @warning The data to be attached to the pool should have a life span + * at least as long as the pool it is being attached to. + * + * Users of APR must take EXTREME care when choosing a key to + * use for their data. It is possible to accidentally overwrite + * data by choosing a key that another part of the program is using. + * Therefore it is advised that steps are taken to ensure that unique + * keys are used for all of the userdata objects in a particular pool + * (the same key in two different pools or a pool and one of its + * subpools is okay) at all times. Careful namespace prefixing of + * key names is a typical way to help ensure this uniqueness. + * + */ +APR_DECLARE(apr_status_t) apr_pool_userdata_set(const void *data, + const char *key, + apr_status_t (*cleanup)(void *), + apr_pool_t *pool) + __attribute__((nonnull(2,4))); + +/** + * Set the data associated with the current pool + * @param data The user data associated with the pool. + * @param key The key to use for association + * @param cleanup The cleanup program to use to cleanup the data (NULL if none) + * @param pool The current pool + * @note same as apr_pool_userdata_set(), except that this version doesn't + * make a copy of the key (this function is useful, for example, when + * the key is a string literal) + * @warning This should NOT be used if the key could change addresses by + * any means between the apr_pool_userdata_setn() call and a + * subsequent apr_pool_userdata_get() on that key, such as if a + * static string is used as a userdata key in a DSO and the DSO could + * be unloaded and reloaded between the _setn() and the _get(). You + * MUST use apr_pool_userdata_set() in such cases. + * @warning More generally, the key and the data to be attached to the + * pool should have a life span at least as long as the pool itself. + * + */ +APR_DECLARE(apr_status_t) apr_pool_userdata_setn( + const void *data, const char *key, + apr_status_t (*cleanup)(void *), + apr_pool_t *pool) + __attribute__((nonnull(2,4))); + +/** + * Return the data associated with the current pool. + * @param data The user data associated with the pool. + * @param key The key for the data to retrieve + * @param pool The current pool. + */ +APR_DECLARE(apr_status_t) apr_pool_userdata_get(void **data, const char *key, + apr_pool_t *pool) + __attribute__((nonnull(1,2,3))); + + +/** + * @defgroup PoolCleanup Pool Cleanup Functions + * + * Cleanups are performed in the reverse order they were registered. That is: + * Last In, First Out. A cleanup function can safely allocate memory from + * the pool that is being cleaned up. It can also safely register additional + * cleanups which will be run LIFO, directly after the current cleanup + * terminates. Cleanups have to take caution in calling functions that + * create subpools. Subpools, created during cleanup will NOT automatically + * be cleaned up. In other words, cleanups are to clean up after themselves. + * + * @{ + */ + +/** + * Register a function to be called when a pool is cleared or destroyed + * @param p The pool to register the cleanup with + * @param data The data to pass to the cleanup function. + * @param plain_cleanup The function to call when the pool is cleared + * or destroyed + * @param child_cleanup The function to call when a child process is about + * to exec - this function is called in the child, obviously! + */ +APR_DECLARE(void) apr_pool_cleanup_register( + apr_pool_t *p, const void *data, + apr_status_t (*plain_cleanup)(void *), + apr_status_t (*child_cleanup)(void *)) + __attribute__((nonnull(3,4))); + +/** + * Register a function to be called when a pool is cleared or destroyed. + * + * Unlike apr_pool_cleanup_register which registers a cleanup + * that is called AFTER all subpools are destroyed, this function registers + * a function that will be called before any of the subpools are destroyed. + * + * @param p The pool to register the cleanup with + * @param data The data to pass to the cleanup function. + * @param plain_cleanup The function to call when the pool is cleared + * or destroyed + */ +APR_DECLARE(void) apr_pool_pre_cleanup_register( + apr_pool_t *p, const void *data, + apr_status_t (*plain_cleanup)(void *)) + __attribute__((nonnull(3))); + +/** + * Remove a previously registered cleanup function. + * + * The cleanup most recently registered with @a p having the same values of + * @a data and @a cleanup will be removed. + * + * @param p The pool to remove the cleanup from + * @param data The data of the registered cleanup + * @param cleanup The function to remove from cleanup + * @remarks For some strange reason only the plain_cleanup is handled by this + * function + */ +APR_DECLARE(void) apr_pool_cleanup_kill(apr_pool_t *p, const void *data, + apr_status_t (*cleanup)(void *)) + __attribute__((nonnull(3))); + +/** + * Replace the child cleanup function of a previously registered cleanup. + * + * The cleanup most recently registered with @a p having the same values of + * @a data and @a plain_cleanup will have the registered child cleanup + * function replaced with @a child_cleanup. + * + * @param p The pool of the registered cleanup + * @param data The data of the registered cleanup + * @param plain_cleanup The plain cleanup function of the registered cleanup + * @param child_cleanup The function to register as the child cleanup + */ +APR_DECLARE(void) apr_pool_child_cleanup_set( + apr_pool_t *p, const void *data, + apr_status_t (*plain_cleanup)(void *), + apr_status_t (*child_cleanup)(void *)) + __attribute__((nonnull(3,4))); + +/** + * Run the specified cleanup function immediately and unregister it. + * + * The cleanup most recently registered with @a p having the same values of + * @a data and @a cleanup will be removed and @a cleanup will be called + * with @a data as the argument. + * + * @param p The pool to remove the cleanup from + * @param data The data to remove from cleanup + * @param cleanup The function to remove from cleanup + */ +APR_DECLARE(apr_status_t) apr_pool_cleanup_run(apr_pool_t *p, void *data, + apr_status_t (*cleanup)(void *)) + __attribute__((nonnull(3))); + +/** + * An empty cleanup function. + * + * Passed to apr_pool_cleanup_register() when no cleanup is required. + * + * @param data The data to cleanup, will not be used by this function. + */ +APR_DECLARE_NONSTD(apr_status_t) apr_pool_cleanup_null(void *data); + +/** + * Run all registered child cleanups, in preparation for an exec() + * call in a forked child -- close files, etc., but *don't* flush I/O + * buffers, *don't* wait for subprocesses, and *don't* free any + * memory. + */ +APR_DECLARE(void) apr_pool_cleanup_for_exec(void); + +/** @} */ + +/** + * @defgroup PoolDebug Pool Debugging functions. + * + * pools have nested lifetimes -- sub_pools are destroyed when the + * parent pool is cleared. We allow certain liberties with operations + * on things such as tables (and on other structures in a more general + * sense) where we allow the caller to insert values into a table which + * were not allocated from the table's pool. The table's data will + * remain valid as long as all the pools from which its values are + * allocated remain valid. + * + * For example, if B is a sub pool of A, and you build a table T in + * pool B, then it's safe to insert data allocated in A or B into T + * (because B lives at most as long as A does, and T is destroyed when + * B is cleared/destroyed). On the other hand, if S is a table in + * pool A, it is safe to insert data allocated in A into S, but it + * is *not safe* to insert data allocated from B into S... because + * B can be cleared/destroyed before A is (which would leave dangling + * pointers in T's data structures). + * + * In general we say that it is safe to insert data into a table T + * if the data is allocated in any ancestor of T's pool. This is the + * basis on which the APR_POOL_DEBUG code works -- it tests these ancestor + * relationships for all data inserted into tables. APR_POOL_DEBUG also + * provides tools (apr_pool_find, and apr_pool_is_ancestor) for other + * folks to implement similar restrictions for their own data + * structures. + * + * However, sometimes this ancestor requirement is inconvenient -- + * sometimes it's necessary to create a sub pool where the sub pool is + * guaranteed to have the same lifetime as the parent pool. This is a + * guarantee implemented by the *caller*, not by the pool code. That + * is, the caller guarantees they won't destroy the sub pool + * individually prior to destroying the parent pool. + * + * In this case the caller must call apr_pool_join() to indicate this + * guarantee to the APR_POOL_DEBUG code. + * + * These functions are only implemented when #APR_POOL_DEBUG is set. + * + * @{ + */ +#if APR_POOL_DEBUG || defined(DOXYGEN) +/** + * Guarantee that a subpool has the same lifetime as the parent. + * @param p The parent pool + * @param sub The subpool + */ +APR_DECLARE(void) apr_pool_join(apr_pool_t *p, apr_pool_t *sub) + __attribute__((nonnull(2))); + +/** + * Find a pool from something allocated in it. + * @param mem The thing allocated in the pool + * @return The pool it is allocated in + */ +APR_DECLARE(apr_pool_t *) apr_pool_find(const void *mem); + +/** + * Report the number of bytes currently in the pool + * @param p The pool to inspect + * @param recurse Recurse/include the subpools' sizes + * @return The number of bytes + */ +APR_DECLARE(apr_size_t) apr_pool_num_bytes(apr_pool_t *p, int recurse) + __attribute__((nonnull(1))); + +/** + * Lock a pool + * @param pool The pool to lock + * @param flag The flag + */ +APR_DECLARE(void) apr_pool_lock(apr_pool_t *pool, int flag); + +/* @} */ + +#else /* APR_POOL_DEBUG or DOXYGEN */ + +#ifdef apr_pool_join +#undef apr_pool_join +#endif +#define apr_pool_join(a,b) + +#ifdef apr_pool_lock +#undef apr_pool_lock +#endif +#define apr_pool_lock(pool, lock) + +#endif /* APR_POOL_DEBUG or DOXYGEN */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_POOLS_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_portable.h b/c/dependencies/windows/apr/x86_debug/include/apr_portable.h new file mode 100644 index 00000000..f56997e4 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_portable.h @@ -0,0 +1,549 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* This header file is where you should put ANY platform specific information. + * This should be the only header file that programs need to include that + * actually has platform dependent code which refers to the . + */ +#ifndef APR_PORTABLE_H +#define APR_PORTABLE_H +/** + * @file apr_portable.h + * @brief APR Portability Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" +#include "apr_network_io.h" +#include "apr_errno.h" +#include "apr_global_mutex.h" +#include "apr_proc_mutex.h" +#include "apr_time.h" +#include "apr_dso.h" +#include "apr_shm.h" + +#if APR_HAVE_DIRENT_H +#include +#endif +#if APR_HAVE_FCNTL_H +#include +#endif +#if APR_HAVE_PTHREAD_H +#include +#endif +#if APR_HAVE_SEMAPHORE_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_portabile Portability Routines + * @ingroup APR + * @{ + */ + +#ifdef WIN32 +/* The primitives for Windows types */ +typedef HANDLE apr_os_file_t; +typedef HANDLE apr_os_dir_t; +typedef SOCKET apr_os_sock_t; +typedef HANDLE apr_os_proc_mutex_t; +typedef HANDLE apr_os_thread_t; +typedef HANDLE apr_os_proc_t; +typedef DWORD apr_os_threadkey_t; +typedef FILETIME apr_os_imp_time_t; +typedef SYSTEMTIME apr_os_exp_time_t; +typedef HANDLE apr_os_dso_handle_t; +typedef HANDLE apr_os_shm_t; + +#elif defined(OS2) +typedef HFILE apr_os_file_t; +typedef HDIR apr_os_dir_t; +typedef int apr_os_sock_t; +typedef HMTX apr_os_proc_mutex_t; +typedef TID apr_os_thread_t; +typedef PID apr_os_proc_t; +typedef PULONG apr_os_threadkey_t; +typedef struct timeval apr_os_imp_time_t; +typedef struct tm apr_os_exp_time_t; +typedef HMODULE apr_os_dso_handle_t; +typedef void* apr_os_shm_t; + +#elif defined(__BEOS__) +#include +#include + +struct apr_os_proc_mutex_t { + sem_id sem; + int32 ben; +}; + +typedef int apr_os_file_t; +typedef DIR apr_os_dir_t; +typedef int apr_os_sock_t; +typedef struct apr_os_proc_mutex_t apr_os_proc_mutex_t; +typedef thread_id apr_os_thread_t; +typedef thread_id apr_os_proc_t; +typedef int apr_os_threadkey_t; +typedef struct timeval apr_os_imp_time_t; +typedef struct tm apr_os_exp_time_t; +typedef image_id apr_os_dso_handle_t; +typedef void* apr_os_shm_t; + +#elif defined(NETWARE) +typedef int apr_os_file_t; +typedef DIR apr_os_dir_t; +typedef int apr_os_sock_t; +typedef NXMutex_t apr_os_proc_mutex_t; +typedef NXThreadId_t apr_os_thread_t; +typedef long apr_os_proc_t; +typedef NXKey_t apr_os_threadkey_t; +typedef struct timeval apr_os_imp_time_t; +typedef struct tm apr_os_exp_time_t; +typedef void * apr_os_dso_handle_t; +typedef void* apr_os_shm_t; + +#else +/* Any other OS should go above this one. This is the lowest common + * denominator typedefs for all UNIX-like systems. :) + */ + +/** Basic OS process mutex structure. */ +struct apr_os_proc_mutex_t { +#if APR_HAS_SYSVSEM_SERIALIZE || APR_HAS_FCNTL_SERIALIZE || APR_HAS_FLOCK_SERIALIZE + /** Value used for SYS V Semaphore, FCNTL and FLOCK serialization */ + int crossproc; +#endif +#if APR_HAS_PROC_PTHREAD_SERIALIZE + /** Value used for PTHREAD serialization */ + pthread_mutex_t *pthread_interproc; +#endif +#if APR_HAS_THREADS + /* If no threads, no need for thread locks */ +#if APR_USE_PTHREAD_SERIALIZE + /** This value is currently unused within APR and Apache */ + pthread_mutex_t *intraproc; +#endif +#endif +#if APR_HAS_POSIXSEM_SERIALIZE + /** Value used for POSIX semaphores serialization */ + sem_t *psem_interproc; +#endif +}; + +typedef int apr_os_file_t; /**< native file */ +typedef DIR apr_os_dir_t; /**< native dir */ +typedef int apr_os_sock_t; /**< native dir */ +typedef struct apr_os_proc_mutex_t apr_os_proc_mutex_t; /**< native process + * mutex + */ +#if APR_HAS_THREADS && APR_HAVE_PTHREAD_H +typedef pthread_t apr_os_thread_t; /**< native thread */ +typedef pthread_key_t apr_os_threadkey_t; /**< native thread address + * space */ +#endif +typedef pid_t apr_os_proc_t; /**< native pid */ +typedef struct timeval apr_os_imp_time_t; /**< native timeval */ +typedef struct tm apr_os_exp_time_t; /**< native tm */ +/** @var apr_os_dso_handle_t + * native dso types + */ +#if defined(HPUX) || defined(HPUX10) || defined(HPUX11) +#include +typedef shl_t apr_os_dso_handle_t; +#elif defined(DARWIN) +#include +typedef NSModule apr_os_dso_handle_t; +#else +typedef void * apr_os_dso_handle_t; +#endif +typedef void* apr_os_shm_t; /**< native SHM */ + +#endif + +/** + * @typedef apr_os_sock_info_t + * @brief alias for local OS socket + */ +/** + * everything APR needs to know about an active socket to construct + * an APR socket from it; currently, this is platform-independent + */ +struct apr_os_sock_info_t { + apr_os_sock_t *os_sock; /**< always required */ + struct sockaddr *local; /**< NULL if not yet bound */ + struct sockaddr *remote; /**< NULL if not connected */ + int family; /**< always required (APR_INET, APR_INET6, etc.) */ + int type; /**< always required (SOCK_STREAM, SOCK_DGRAM, etc.) */ + int protocol; /**< 0 or actual protocol (APR_PROTO_SCTP, APR_PROTO_TCP, etc.) */ +}; + +typedef struct apr_os_sock_info_t apr_os_sock_info_t; + +#if APR_PROC_MUTEX_IS_GLOBAL || defined(DOXYGEN) +/** Opaque global mutex type */ +#define apr_os_global_mutex_t apr_os_proc_mutex_t +/** @return apr_os_global_mutex */ +#define apr_os_global_mutex_get apr_os_proc_mutex_get +#else + /** Thread and process mutex for those platforms where process mutexes + * are not held in threads. + */ + struct apr_os_global_mutex_t { + apr_pool_t *pool; + apr_proc_mutex_t *proc_mutex; +#if APR_HAS_THREADS + apr_thread_mutex_t *thread_mutex; +#endif /* APR_HAS_THREADS */ + }; + typedef struct apr_os_global_mutex_t apr_os_global_mutex_t; + +APR_DECLARE(apr_status_t) apr_os_global_mutex_get(apr_os_global_mutex_t *ospmutex, + apr_global_mutex_t *pmutex); +#endif + + +/** + * convert the file from apr type to os specific type. + * @param thefile The os specific file we are converting to + * @param file The apr file to convert. + * @remark On Unix, it is only possible to get a file descriptor from + * an apr file type. + */ +APR_DECLARE(apr_status_t) apr_os_file_get(apr_os_file_t *thefile, + apr_file_t *file); + +/** + * convert the dir from apr type to os specific type. + * @param thedir The os specific dir we are converting to + * @param dir The apr dir to convert. + */ +APR_DECLARE(apr_status_t) apr_os_dir_get(apr_os_dir_t **thedir, + apr_dir_t *dir); + +/** + * Convert the socket from an apr type to an OS specific socket + * @param thesock The socket to convert. + * @param sock The os specific equivalent of the apr socket.. + */ +APR_DECLARE(apr_status_t) apr_os_sock_get(apr_os_sock_t *thesock, + apr_socket_t *sock); + +/** + * Convert the proc mutex from apr type to os specific type + * @param ospmutex The os specific proc mutex we are converting to. + * @param pmutex The apr proc mutex to convert. + */ +APR_DECLARE(apr_status_t) apr_os_proc_mutex_get(apr_os_proc_mutex_t *ospmutex, + apr_proc_mutex_t *pmutex); + +/** + * Convert the proc mutex from apr type to os specific type, also + * providing the mechanism used by the apr mutex. + * @param ospmutex The os specific proc mutex we are converting to. + * @param pmutex The apr proc mutex to convert. + * @param mech The mechanism used by the apr proc mutex (if not NULL). + * @remark Allows for disambiguation for platforms with multiple mechanisms + * available. + */ +APR_DECLARE(apr_status_t) apr_os_proc_mutex_get_ex(apr_os_proc_mutex_t *ospmutex, + apr_proc_mutex_t *pmutex, + apr_lockmech_e *mech); + +/** + * Get the exploded time in the platforms native format. + * @param ostime the native time format + * @param aprtime the time to convert + */ +APR_DECLARE(apr_status_t) apr_os_exp_time_get(apr_os_exp_time_t **ostime, + apr_time_exp_t *aprtime); + +/** + * Get the imploded time in the platforms native format. + * @param ostime the native time format + * @param aprtime the time to convert + */ +APR_DECLARE(apr_status_t) apr_os_imp_time_get(apr_os_imp_time_t **ostime, + apr_time_t *aprtime); + +/** + * convert the shm from apr type to os specific type. + * @param osshm The os specific shm representation + * @param shm The apr shm to convert. + */ +APR_DECLARE(apr_status_t) apr_os_shm_get(apr_os_shm_t *osshm, + apr_shm_t *shm); + +#if APR_HAS_THREADS || defined(DOXYGEN) +/** + * @defgroup apr_os_thread Thread portability Routines + * @{ + */ +/** + * convert the thread to os specific type from apr type. + * @param thethd The apr thread to convert + * @param thd The os specific thread we are converting to + */ +APR_DECLARE(apr_status_t) apr_os_thread_get(apr_os_thread_t **thethd, + apr_thread_t *thd); + +/** + * convert the thread private memory key to os specific type from an apr type. + * @param thekey The apr handle we are converting from. + * @param key The os specific handle we are converting to. + */ +APR_DECLARE(apr_status_t) apr_os_threadkey_get(apr_os_threadkey_t *thekey, + apr_threadkey_t *key); + +/** + * convert the thread from os specific type to apr type. + * @param thd The apr thread we are converting to. + * @param thethd The os specific thread to convert + * @param cont The pool to use if it is needed. + */ +APR_DECLARE(apr_status_t) apr_os_thread_put(apr_thread_t **thd, + apr_os_thread_t *thethd, + apr_pool_t *cont); + +/** + * convert the thread private memory key from os specific type to apr type. + * @param key The apr handle we are converting to. + * @param thekey The os specific handle to convert + * @param cont The pool to use if it is needed. + */ +APR_DECLARE(apr_status_t) apr_os_threadkey_put(apr_threadkey_t **key, + apr_os_threadkey_t *thekey, + apr_pool_t *cont); +/** + * Get the thread ID + */ +APR_DECLARE(apr_os_thread_t) apr_os_thread_current(void); + +/** + * Compare two thread id's + * @param tid1 1st Thread ID to compare + * @param tid2 2nd Thread ID to compare + * @return non-zero if the two threads are equal, zero otherwise + */ +APR_DECLARE(int) apr_os_thread_equal(apr_os_thread_t tid1, + apr_os_thread_t tid2); + +/** @} */ +#endif /* APR_HAS_THREADS */ + +/** + * convert the file from os specific type to apr type. + * @param file The apr file we are converting to. + * @param thefile The os specific file to convert + * @param flags The flags that were used to open this file. + * @param cont The pool to use if it is needed. + * @remark On Unix, it is only possible to put a file descriptor into + * an apr file type. + */ +APR_DECLARE(apr_status_t) apr_os_file_put(apr_file_t **file, + apr_os_file_t *thefile, + apr_int32_t flags, apr_pool_t *cont); + +/** + * convert the file from os specific type to apr type. + * @param file The apr file we are converting to. + * @param thefile The os specific pipe to convert + * @param cont The pool to use if it is needed. + * @remark On Unix, it is only possible to put a file descriptor into + * an apr file type. + */ +APR_DECLARE(apr_status_t) apr_os_pipe_put(apr_file_t **file, + apr_os_file_t *thefile, + apr_pool_t *cont); + +/** + * convert the file from os specific type to apr type. + * @param file The apr file we are converting to. + * @param thefile The os specific pipe to convert + * @param register_cleanup A cleanup will be registered on the apr_file_t + * to issue apr_file_close(). + * @param cont The pool to use if it is needed. + * @remark On Unix, it is only possible to put a file descriptor into + * an apr file type. + */ +APR_DECLARE(apr_status_t) apr_os_pipe_put_ex(apr_file_t **file, + apr_os_file_t *thefile, + int register_cleanup, + apr_pool_t *cont); + +/** + * convert the dir from os specific type to apr type. + * @param dir The apr dir we are converting to. + * @param thedir The os specific dir to convert + * @param cont The pool to use when creating to apr directory. + */ +APR_DECLARE(apr_status_t) apr_os_dir_put(apr_dir_t **dir, + apr_os_dir_t *thedir, + apr_pool_t *cont); + +/** + * Convert a socket from the os specific type to the APR type. If + * sock points to NULL, a socket will be created from the pool + * provided. If **sock does not point to NULL, the structure pointed + * to by sock will be reused and updated with the given socket. + * @param sock The pool to use. + * @param thesock The socket to convert to. + * @param cont The socket we are converting to an apr type. + * @remark If it is a true socket, it is best to call apr_os_sock_make() + * and provide APR with more information about the socket. + */ +APR_DECLARE(apr_status_t) apr_os_sock_put(apr_socket_t **sock, + apr_os_sock_t *thesock, + apr_pool_t *cont); + +/** + * Create a socket from an existing descriptor and local and remote + * socket addresses. + * @param apr_sock The new socket that has been set up + * @param os_sock_info The os representation of the socket handle and + * other characteristics of the socket + * @param cont The pool to use + * @remark If you only know the descriptor/handle or if it isn't really + * a true socket, use apr_os_sock_put() instead. + */ +APR_DECLARE(apr_status_t) apr_os_sock_make(apr_socket_t **apr_sock, + apr_os_sock_info_t *os_sock_info, + apr_pool_t *cont); + +/** + * Convert the proc mutex from os specific type to apr type + * @param pmutex The apr proc mutex we are converting to. + * @param ospmutex The os specific proc mutex to convert. + * @param cont The pool to use if it is needed. + */ +APR_DECLARE(apr_status_t) apr_os_proc_mutex_put(apr_proc_mutex_t **pmutex, + apr_os_proc_mutex_t *ospmutex, + apr_pool_t *cont); + +/** + * Convert the proc mutex from os specific type to apr type, using the + * specified mechanism. + * @param pmutex The apr proc mutex we are converting to. + * @param ospmutex The os specific proc mutex to convert. + * @param mech The apr mutex locking mechanism + * @param register_cleanup Whether to destroy the os mutex with the apr + * one (either on explicit destroy or pool cleanup). + * @param cont The pool to use if it is needed. + * @remark Allows for disambiguation for platforms with multiple mechanisms + * available. + */ +APR_DECLARE(apr_status_t) apr_os_proc_mutex_put_ex(apr_proc_mutex_t **pmutex, + apr_os_proc_mutex_t *ospmutex, + apr_lockmech_e mech, + int register_cleanup, + apr_pool_t *cont); + +/** + * Put the imploded time in the APR format. + * @param aprtime the APR time format + * @param ostime the time to convert + * @param cont the pool to use if necessary + */ +APR_DECLARE(apr_status_t) apr_os_imp_time_put(apr_time_t *aprtime, + apr_os_imp_time_t **ostime, + apr_pool_t *cont); + +/** + * Put the exploded time in the APR format. + * @param aprtime the APR time format + * @param ostime the time to convert + * @param cont the pool to use if necessary + */ +APR_DECLARE(apr_status_t) apr_os_exp_time_put(apr_time_exp_t *aprtime, + apr_os_exp_time_t **ostime, + apr_pool_t *cont); + +/** + * convert the shared memory from os specific type to apr type. + * @param shm The apr shm representation of osshm + * @param osshm The os specific shm identity + * @param cont The pool to use if it is needed. + * @remark On fork()ed architectures, this is typically nothing more than + * the memory block mapped. On non-fork architectures, this is typically + * some internal handle to pass the mapping from process to process. + */ +APR_DECLARE(apr_status_t) apr_os_shm_put(apr_shm_t **shm, + apr_os_shm_t *osshm, + apr_pool_t *cont); + + +#if APR_HAS_DSO || defined(DOXYGEN) +/** + * @defgroup apr_os_dso DSO (Dynamic Loading) Portability Routines + * @{ + */ +/** + * convert the dso handle from os specific to apr + * @param dso The apr handle we are converting to + * @param thedso the os specific handle to convert + * @param pool the pool to use if it is needed + */ +APR_DECLARE(apr_status_t) apr_os_dso_handle_put(apr_dso_handle_t **dso, + apr_os_dso_handle_t thedso, + apr_pool_t *pool); + +/** + * convert the apr dso handle into an os specific one + * @param aprdso The apr dso handle to convert + * @param dso The os specific dso to return + */ +APR_DECLARE(apr_status_t) apr_os_dso_handle_get(apr_os_dso_handle_t *dso, + apr_dso_handle_t *aprdso); + +/** @} */ +#endif /* APR_HAS_DSO */ + + +#if APR_HAS_OS_UUID +/** + * Private: apr-util's apr_uuid module when supported by the platform + */ +APR_DECLARE(apr_status_t) apr_os_uuid_get(unsigned char *uuid_data); +#endif + + +/** + * Get the name of the system default character set. + * @param pool the pool to allocate the name from, if needed + */ +APR_DECLARE(const char*) apr_os_default_encoding(apr_pool_t *pool); + + +/** + * Get the name of the current locale character set. + * @param pool the pool to allocate the name from, if needed + * @remark Defers to apr_os_default_encoding() if the current locale's + * data can't be retrieved on this system. + */ +APR_DECLARE(const char*) apr_os_locale_encoding(apr_pool_t *pool); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_PORTABLE_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_proc_mutex.h b/c/dependencies/windows/apr/x86_debug/include/apr_proc_mutex.h new file mode 100644 index 00000000..418c9504 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_proc_mutex.h @@ -0,0 +1,192 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_PROC_MUTEX_H +#define APR_PROC_MUTEX_H + +/** + * @file apr_proc_mutex.h + * @brief APR Process Locking Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_perms_set.h" +#include "apr_time.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_proc_mutex Process Locking Routines + * @ingroup APR + * @{ + */ + +/** + * Enumerated potential types for APR process locking methods + * @warning Check APR_HAS_foo_SERIALIZE defines to see if the platform supports + * APR_LOCK_foo. Only APR_LOCK_DEFAULT is portable. + */ +typedef enum { + APR_LOCK_FCNTL, /**< fcntl() */ + APR_LOCK_FLOCK, /**< flock() */ + APR_LOCK_SYSVSEM, /**< System V Semaphores */ + APR_LOCK_PROC_PTHREAD, /**< POSIX pthread process-based locking */ + APR_LOCK_POSIXSEM, /**< POSIX semaphore process-based locking */ + APR_LOCK_DEFAULT, /**< Use the default process lock */ + APR_LOCK_DEFAULT_TIMED /**< Use the default process timed lock */ +} apr_lockmech_e; + +/** Opaque structure representing a process mutex. */ +typedef struct apr_proc_mutex_t apr_proc_mutex_t; + +/* Function definitions */ + +/** + * Create and initialize a mutex that can be used to synchronize processes. + * @param mutex the memory address where the newly created mutex will be + * stored. + * @param fname A file name to use if the lock mechanism requires one. This + * argument should always be provided. The lock code itself will + * determine if it should be used. + * @param mech The mechanism to use for the interprocess lock, if any; one of + *
+ *            APR_LOCK_FCNTL
+ *            APR_LOCK_FLOCK
+ *            APR_LOCK_SYSVSEM
+ *            APR_LOCK_POSIXSEM
+ *            APR_LOCK_PROC_PTHREAD
+ *            APR_LOCK_DEFAULT     pick the default mechanism for the platform
+ * 
+ * @param pool the pool from which to allocate the mutex. + * @see apr_lockmech_e + * @warning Check APR_HAS_foo_SERIALIZE defines to see if the platform supports + * APR_LOCK_foo. Only APR_LOCK_DEFAULT is portable. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_create(apr_proc_mutex_t **mutex, + const char *fname, + apr_lockmech_e mech, + apr_pool_t *pool); + +/** + * Re-open a mutex in a child process. + * @param mutex The newly re-opened mutex structure. + * @param fname A file name to use if the mutex mechanism requires one. This + * argument should always be provided. The mutex code itself will + * determine if it should be used. This filename should be the + * same one that was passed to apr_proc_mutex_create(). + * @param pool The pool to operate on. + * @remark This function must be called to maintain portability, even + * if the underlying lock mechanism does not require it. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_child_init(apr_proc_mutex_t **mutex, + const char *fname, + apr_pool_t *pool); + +/** + * Acquire the lock for the given mutex. If the mutex is already locked, + * the current thread will be put to sleep until the lock becomes available. + * @param mutex the mutex on which to acquire the lock. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_lock(apr_proc_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex. If the mutex has already + * been acquired, the call returns immediately with APR_EBUSY. Note: it + * is important that the APR_STATUS_IS_EBUSY(s) macro be used to determine + * if the return value was APR_EBUSY, for portability reasons. + * @param mutex the mutex on which to attempt the lock acquiring. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_trylock(apr_proc_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex until timeout expires. + * If the acquisition time outs, the call returns with APR_TIMEUP. + * @param mutex the mutex on which to attempt the lock acquiring. + * @param timeout the relative timeout (microseconds). + * @note A negative or nul timeout means immediate attempt, returning + * APR_TIMEUP without blocking if it the lock is already acquired. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_timedlock(apr_proc_mutex_t *mutex, + apr_interval_time_t timeout); + +/** + * Release the lock for the given mutex. + * @param mutex the mutex from which to release the lock. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_unlock(apr_proc_mutex_t *mutex); + +/** + * Destroy the mutex and free the memory associated with the lock. + * @param mutex the mutex to destroy. + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_destroy(apr_proc_mutex_t *mutex); + +/** + * Destroy the mutex and free the memory associated with the lock. + * @param mutex the mutex to destroy. + * @note This function is generally used to kill a cleanup on an already + * created mutex + */ +APR_DECLARE(apr_status_t) apr_proc_mutex_cleanup(void *mutex); + +/** + * Return the name of the lockfile for the mutex, or NULL + * if the mutex doesn't use a lock file + */ + +APR_DECLARE(const char *) apr_proc_mutex_lockfile(apr_proc_mutex_t *mutex); + +/** + * Get the mechanism of the mutex, as it relates to the actual method + * used for the underlying apr_proc_mutex_t. + * @param mutex the mutex to get the mechanism from. + */ +APR_DECLARE(apr_lockmech_e) apr_proc_mutex_mech(apr_proc_mutex_t *mutex); + +/** + * Get the mechanism's name of the mutex, as it relates to the actual method + * used for the underlying apr_proc_mutex_t. + * @param mutex the mutex to get the mechanism's name from. + */ +APR_DECLARE(const char *) apr_proc_mutex_name(apr_proc_mutex_t *mutex); + +/** + * Display the name of the default mutex: APR_LOCK_DEFAULT + */ +APR_DECLARE(const char *) apr_proc_mutex_defname(void); + +/** + * Set mutex permissions. + */ +APR_PERMS_SET_IMPLEMENT(proc_mutex); + +/** + * Get the pool used by this proc_mutex. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(proc_mutex); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_PROC_MUTEX_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_queue.h b/c/dependencies/windows/apr/x86_debug/include/apr_queue.h new file mode 100644 index 00000000..a3a41704 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_queue.h @@ -0,0 +1,138 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_QUEUE_H +#define APR_QUEUE_H + +/** + * @file apr_queue.h + * @brief Thread Safe FIFO bounded queue + * @note Since most implementations of the queue are backed by a condition + * variable implementation, it isn't available on systems without threads. + * Although condition variables are sometimes available without threads. + */ + +#include "apu.h" +#include "apr_errno.h" +#include "apr_pools.h" + +#if APR_HAS_THREADS + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_Util_FIFO Thread Safe FIFO bounded queue + * @ingroup APR_Util + * @{ + */ + +/** + * opaque structure + */ +typedef struct apr_queue_t apr_queue_t; + +/** + * create a FIFO queue + * @param queue The new queue + * @param queue_capacity maximum size of the queue + * @param a pool to allocate queue from + */ +APU_DECLARE(apr_status_t) apr_queue_create(apr_queue_t **queue, + unsigned int queue_capacity, + apr_pool_t *a); + +/** + * push/add an object to the queue, blocking if the queue is already full + * + * @param queue the queue + * @param data the data + * @returns APR_EINTR the blocking was interrupted (try again) + * @returns APR_EOF the queue has been terminated + * @returns APR_SUCCESS on a successful push + */ +APU_DECLARE(apr_status_t) apr_queue_push(apr_queue_t *queue, void *data); + +/** + * pop/get an object from the queue, blocking if the queue is already empty + * + * @param queue the queue + * @param data the data + * @returns APR_EINTR the blocking was interrupted (try again) + * @returns APR_EOF if the queue has been terminated + * @returns APR_SUCCESS on a successful pop + */ +APU_DECLARE(apr_status_t) apr_queue_pop(apr_queue_t *queue, void **data); + +/** + * push/add an object to the queue, returning immediately if the queue is full + * + * @param queue the queue + * @param data the data + * @returns APR_EINTR the blocking operation was interrupted (try again) + * @returns APR_EAGAIN the queue is full + * @returns APR_EOF the queue has been terminated + * @returns APR_SUCCESS on a successful push + */ +APU_DECLARE(apr_status_t) apr_queue_trypush(apr_queue_t *queue, void *data); + +/** + * pop/get an object to the queue, returning immediately if the queue is empty + * + * @param queue the queue + * @param data the data + * @returns APR_EINTR the blocking operation was interrupted (try again) + * @returns APR_EAGAIN the queue is empty + * @returns APR_EOF the queue has been terminated + * @returns APR_SUCCESS on a successful pop + */ +APU_DECLARE(apr_status_t) apr_queue_trypop(apr_queue_t *queue, void **data); + +/** + * returns the size of the queue. + * + * @warning this is not threadsafe, and is intended for reporting/monitoring + * of the queue. + * @param queue the queue + * @returns the size of the queue + */ +APU_DECLARE(unsigned int) apr_queue_size(apr_queue_t *queue); + +/** + * interrupt all the threads blocking on this queue. + * + * @param queue the queue + */ +APU_DECLARE(apr_status_t) apr_queue_interrupt_all(apr_queue_t *queue); + +/** + * terminate the queue, sending an interrupt to all the + * blocking threads + * + * @param queue the queue + */ +APU_DECLARE(apr_status_t) apr_queue_term(apr_queue_t *queue); + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif /* APR_HAS_THREADS */ + +#endif /* APRQUEUE_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_random.h b/c/dependencies/windows/apr/x86_debug/include/apr_random.h new file mode 100644 index 00000000..29154358 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_random.h @@ -0,0 +1,153 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_RANDOM_H +#define APR_RANDOM_H + +/** + * @file apr_random.h + * @brief APR PRNG routines + */ + +#include "apr_pools.h" +#include "apr_thread_proc.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_random PRNG Routines + * @ingroup APR + * @{ + */ + +typedef struct apr_crypto_hash_t apr_crypto_hash_t; + +typedef void apr_crypto_hash_init_t(apr_crypto_hash_t *hash); +typedef void apr_crypto_hash_add_t(apr_crypto_hash_t *hash, const void *data, + apr_size_t bytes); +typedef void apr_crypto_hash_finish_t(apr_crypto_hash_t *hash, + unsigned char *result); + + +/* FIXME: make this opaque */ +struct apr_crypto_hash_t { + apr_crypto_hash_init_t *init; + apr_crypto_hash_add_t *add; + apr_crypto_hash_finish_t *finish; + apr_size_t size; + void *data; +}; + +/** + * Allocate and initialize the SHA-256 context + * @param p The pool to allocate from + */ +APR_DECLARE(apr_crypto_hash_t *) apr_crypto_sha256_new(apr_pool_t *p); + +/** Opaque PRNG structure. */ +typedef struct apr_random_t apr_random_t; + +/** + * Initialize a PRNG state + * @param g The PRNG state + * @param p The pool to allocate from + * @param pool_hash Pool hash functions + * @param key_hash Key hash functions + * @param prng_hash PRNG hash functions + */ +APR_DECLARE(void) apr_random_init(apr_random_t *g, apr_pool_t *p, + apr_crypto_hash_t *pool_hash, + apr_crypto_hash_t *key_hash, + apr_crypto_hash_t *prng_hash); +/** + * Allocate and initialize (apr_crypto_sha256_new) a new PRNG state. + * @param p The pool to allocate from + */ +APR_DECLARE(apr_random_t *) apr_random_standard_new(apr_pool_t *p); + +/** + * Mix the randomness pools. + * @param g The PRNG state + * @param entropy_ Entropy buffer + * @param bytes Length of entropy_ in bytes + */ +APR_DECLARE(void) apr_random_add_entropy(apr_random_t *g, + const void *entropy_, + apr_size_t bytes); +/** + * Generate cryptographically insecure random bytes. + * @param g The RNG state + * @param random Buffer to fill with random bytes + * @param bytes Length of buffer in bytes + */ +APR_DECLARE(apr_status_t) apr_random_insecure_bytes(apr_random_t *g, + void *random, + apr_size_t bytes); + +/** + * Generate cryptographically secure random bytes. + * @param g The RNG state + * @param random Buffer to fill with random bytes + * @param bytes Length of buffer in bytes + */ +APR_DECLARE(apr_status_t) apr_random_secure_bytes(apr_random_t *g, + void *random, + apr_size_t bytes); +/** + * Ensures that E bits of conditional entropy are mixed into the PRNG + * before any further randomness is extracted. + * @param g The RNG state + */ +APR_DECLARE(void) apr_random_barrier(apr_random_t *g); + +/** + * Return APR_SUCCESS if the cryptographic PRNG has been seeded with + * enough data, APR_ENOTENOUGHENTROPY otherwise. + * @param r The RNG state + */ +APR_DECLARE(apr_status_t) apr_random_secure_ready(apr_random_t *r); + +/** + * Return APR_SUCCESS if the PRNG has been seeded with enough data, + * APR_ENOTENOUGHENTROPY otherwise. + * @param r The PRNG state + */ +APR_DECLARE(apr_status_t) apr_random_insecure_ready(apr_random_t *r); + +/** + * Mix the randomness pools after forking. + * @param proc The resulting process handle from apr_proc_fork() + * @remark Call this in the child after forking to mix the randomness + * pools. Note that its generally a bad idea to fork a process with a + * real PRNG in it - better to have the PRNG externally and get the + * randomness from there. However, if you really must do it, then you + * should supply all your entropy to all the PRNGs - don't worry, they + * won't produce the same output. + * @remark Note that apr_proc_fork() calls this for you, so only weird + * applications need ever call it themselves. + * @internal + */ +APR_DECLARE(void) apr_random_after_fork(apr_proc_t *proc); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_RANDOM_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_redis.h b/c/dependencies/windows/apr/x86_debug/include/apr_redis.h new file mode 100644 index 00000000..66a828b0 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_redis.h @@ -0,0 +1,459 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_redis.h + * @brief Client interface for redis + * @remark To use this interface you must have a separate redis + * for more information. + */ + +#ifndef APR_REDIS_H +#define APR_REDIS_H + +#include "apr.h" +#include "apr_pools.h" +#include "apr_time.h" +#include "apr_strings.h" +#include "apr_network_io.h" +#include "apr_ring.h" +#include "apr_buckets.h" +#include "apr_reslist.h" +#include "apr_hash.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#ifndef RC_DEFAULT_SERVER_PORT +#define RC_DEFAULT_SERVER_PORT 6379 +#endif + +#ifndef RC_DEFAULT_SERVER_MIN +#define RC_DEFAULT_SERVER_MIN 0 +#endif + +#ifndef RC_DEFAULT_SERVER_SMAX +#define RC_DEFAULT_SERVER_SMAX 1 +#endif + +#ifndef RC_DEFAULT_SERVER_TTL +#define RC_DEFAULT_SERVER_TTL 600 +#endif + +/** + * @defgroup APR_Util_RC Redis Client Routines + * @ingroup APR_Util + * @{ + */ + +/** Specifies the status of a redis server */ +typedef enum +{ + APR_RC_SERVER_LIVE, /**< Server is alive and responding to requests */ + APR_RC_SERVER_DEAD /**< Server is not responding to requests */ +} apr_redis_server_status_t; + +/** Opaque redis client connection object */ +typedef struct apr_redis_conn_t apr_redis_conn_t; + +/** Redis Server Info Object */ +typedef struct apr_redis_server_t apr_redis_server_t; +struct apr_redis_server_t +{ + const char *host; /**< Hostname of this Server */ + apr_port_t port; /**< Port of this Server */ + apr_redis_server_status_t status; /**< @see apr_redis_server_status_t */ +#if APR_HAS_THREADS || defined(DOXYGEN) + apr_reslist_t *conns; /**< Resource list of actual client connections */ +#else + apr_redis_conn_t *conn; +#endif + apr_pool_t *p; /** Pool to use for private allocations */ +#if APR_HAS_THREADS + apr_thread_mutex_t *lock; +#endif + apr_time_t btime; + apr_uint32_t rwto; + struct + { + int major; + int minor; + int patch; + char *number; + } version; +}; + +typedef struct apr_redis_t apr_redis_t; + +/* Custom hash callback function prototype, user for server selection. +* @param baton user selected baton +* @param data data to hash +* @param data_len length of data +*/ +typedef apr_uint32_t (*apr_redis_hash_func)(void *baton, + const char *data, + const apr_size_t data_len); +/* Custom Server Select callback function prototype. +* @param baton user selected baton +* @param rc redis instance, use rc->live_servers to select a node +* @param hash hash of the selected key. +*/ +typedef apr_redis_server_t* (*apr_redis_server_func)(void *baton, + apr_redis_t *rc, + const apr_uint32_t hash); + +/** Container for a set of redis servers */ +struct apr_redis_t +{ + apr_uint32_t flags; /**< Flags, Not currently used */ + apr_uint16_t nalloc; /**< Number of Servers Allocated */ + apr_uint16_t ntotal; /**< Number of Servers Added */ + apr_redis_server_t **live_servers; /**< Array of Servers */ + apr_pool_t *p; /** Pool to use for allocations */ + void *hash_baton; + apr_redis_hash_func hash_func; + void *server_baton; + apr_redis_server_func server_func; +}; + +/** + * Creates a crc32 hash used to split keys between servers + * @param rc The redis client object to use + * @param data Data to be hashed + * @param data_len Length of the data to use + * @return crc32 hash of data + * @remark The crc32 hash is not compatible with old redisd clients. + */ +APU_DECLARE(apr_uint32_t) apr_redis_hash(apr_redis_t *rc, + const char *data, + const apr_size_t data_len); + +/** + * Pure CRC32 Hash. Used by some clients. + */ +APU_DECLARE(apr_uint32_t) apr_redis_hash_crc32(void *baton, + const char *data, + const apr_size_t data_len); + +/** + * hash compatible with the standard Perl Client. + */ +APU_DECLARE(apr_uint32_t) apr_redis_hash_default(void *baton, + const char *data, + const apr_size_t data_len); + +/** + * Picks a server based on a hash + * @param rc The redis client object to use + * @param hash Hashed value of a Key + * @return server that controls specified hash + * @see apr_redis_hash + */ +APU_DECLARE(apr_redis_server_t *) apr_redis_find_server_hash(apr_redis_t *rc, + const apr_uint32_t hash); + +/** + * server selection compatible with the standard Perl Client. + */ +APU_DECLARE(apr_redis_server_t *) apr_redis_find_server_hash_default(void *baton, + apr_redis_t *rc, + const apr_uint32_t hash); + +/** + * Adds a server to a client object + * @param rc The redis client object to use + * @param server Server to add + * @remark Adding servers is not thread safe, and should be done once at startup. + * @warning Changing servers after startup may cause keys to go to + * different servers. + */ +APU_DECLARE(apr_status_t) apr_redis_add_server(apr_redis_t *rc, + apr_redis_server_t *server); + + +/** + * Finds a Server object based on a hostname/port pair + * @param rc The redis client object to use + * @param host Hostname of the server + * @param port Port of the server + * @return Server with matching Hostname and Port, or NULL if none was found. + */ +APU_DECLARE(apr_redis_server_t *) apr_redis_find_server(apr_redis_t *rc, + const char *host, + apr_port_t port); + +/** + * Enables a Server for use again + * @param rc The redis client object to use + * @param rs Server to Activate + */ +APU_DECLARE(apr_status_t) apr_redis_enable_server(apr_redis_t *rc, + apr_redis_server_t *rs); + + +/** + * Disable a Server + * @param rc The redis client object to use + * @param rs Server to Disable + */ +APU_DECLARE(apr_status_t) apr_redis_disable_server(apr_redis_t *rc, + apr_redis_server_t *rs); + +/** + * Creates a new Server Object + * @param p Pool to use + * @param host hostname of the server + * @param port port of the server + * @param min minimum number of client sockets to open + * @param smax soft maximum number of client connections to open + * @param max hard maximum number of client connections + * @param ttl time to live in microseconds of a client connection + * @param rwto r/w timeout value in seconds of a client connection + * @param ns location of the new server object + * @see apr_reslist_create + * @remark min, smax, and max are only used when APR_HAS_THREADS + */ +APU_DECLARE(apr_status_t) apr_redis_server_create(apr_pool_t *p, + const char *host, + apr_port_t port, + apr_uint32_t min, + apr_uint32_t smax, + apr_uint32_t max, + apr_uint32_t ttl, + apr_uint32_t rwto, + apr_redis_server_t **ns); +/** + * Creates a new redisd client object + * @param p Pool to use + * @param max_servers maximum number of servers + * @param flags Not currently used + * @param rc location of the new redis client object + */ +APU_DECLARE(apr_status_t) apr_redis_create(apr_pool_t *p, + apr_uint16_t max_servers, + apr_uint32_t flags, + apr_redis_t **rc); + +/** + * Gets a value from the server, allocating the value out of p + * @param rc client to use + * @param p Pool to use + * @param key null terminated string containing the key + * @param baton location of the allocated value + * @param len length of data at baton + * @param flags any flags set by the client for this key + * @return + */ +APU_DECLARE(apr_status_t) apr_redis_getp(apr_redis_t *rc, + apr_pool_t *p, + const char* key, + char **baton, + apr_size_t *len, + apr_uint16_t *flags); + +/** + * Sets a value by key on the server + * @param rc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param flags any flags set by the client for this key + */ +APU_DECLARE(apr_status_t) apr_redis_set(apr_redis_t *rc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint16_t flags); + +/** + * Sets a value by key on the server + * @param rc client to use + * @param key null terminated string containing the key + * @param baton data to store on the server + * @param data_size length of data at baton + * @param timeout time in seconds for the data to live on the server + * @param flags any flags set by the client for this key + */ +APU_DECLARE(apr_status_t) apr_redis_setex(apr_redis_t *rc, + const char *key, + char *baton, + const apr_size_t data_size, + apr_uint32_t timeout, + apr_uint16_t flags); + +/** + * Deletes a key from a server + * @param rc client to use + * @param key null terminated string containing the key + * @param timeout time for the delete to stop other clients from adding + */ +APU_DECLARE(apr_status_t) apr_redis_delete(apr_redis_t *rc, + const char *key, + apr_uint32_t timeout); + +/** + * Query a server's version + * @param rs server to query + * @param p Pool to allocate answer from + * @param baton location to store server version string + */ +APU_DECLARE(apr_status_t) apr_redis_version(apr_redis_server_t *rs, + apr_pool_t *p, + char **baton); + +/** + * Query a server's INFO + * @param rs server to query + * @param p Pool to allocate answer from + * @param baton location to store server INFO response string + */ +APU_DECLARE(apr_status_t) apr_redis_info(apr_redis_server_t *rs, + apr_pool_t *p, + char **baton); + +/** + * Increments a value + * @param rc client to use + * @param key null terminated string containing the key + * @param inc number to increment by + * @param new_value new value after incrementing + */ +APU_DECLARE(apr_status_t) apr_redis_incr(apr_redis_t *rc, + const char *key, + apr_int32_t inc, + apr_uint32_t *new_value); +/** + * Decrements a value + * @param rc client to use + * @param key null terminated string containing the key + * @param inc number to decrement by + * @param new_value new value after decrementing + */ +APU_DECLARE(apr_status_t) apr_redis_decr(apr_redis_t *rc, + const char *key, + apr_int32_t inc, + apr_uint32_t *new_value); + + +/** + * Pings the server + * @param rs Server to ping + */ +APU_DECLARE(apr_status_t) apr_redis_ping(apr_redis_server_t *rs); + +/** + * Gets multiple values from the server, allocating the values out of p + * @param rc client to use + * @param temp_pool Pool used for temporary allocations. May be cleared inside this + * call. + * @param data_pool Pool used to allocate data for the returned values. + * @param values hash of apr_redis_value_t keyed by strings, contains the + * result of the multiget call. + * @return + */ +APU_DECLARE(apr_status_t) apr_redis_multgetp(apr_redis_t *rc, + apr_pool_t *temp_pool, + apr_pool_t *data_pool, + apr_hash_t *values); + +typedef enum +{ + APR_RS_SERVER_MASTER, /**< Server is a master */ + APR_RS_SERVER_SLAVE, /**< Server is a slave */ + APR_RS_SERVER_UNKNOWN /**< Server role is unknown */ +} apr_redis_server_role_t; + +typedef struct +{ +/* # Server */ + /** Major version number of this server */ + apr_uint32_t major; + /** Minor version number of this server */ + apr_uint32_t minor; + /** Patch version number of this server */ + apr_uint32_t patch; + /** Process id of this server process */ + apr_uint32_t process_id; + /** Number of seconds this server has been running */ + apr_uint32_t uptime_in_seconds; + /** Bitsize of the arch on the current machine */ + apr_uint32_t arch_bits; + +/* # Clients */ + /** Number of connected clients */ + apr_uint32_t connected_clients; + /** Number of blocked clients */ + apr_uint32_t blocked_clients; + +/* # Memory */ + /** Max memory of this server */ + apr_uint64_t maxmemory; + /** Amount of used memory */ + apr_uint64_t used_memory; + /** Total memory available on this server */ + apr_uint64_t total_system_memory; + +/* # Stats */ + /** Total connections received */ + apr_uint64_t total_connections_received; + /** Total commands processed */ + apr_uint64_t total_commands_processed; + /** Total commands rejected */ + apr_uint64_t rejected_connections; + /** Total net input bytes */ + apr_uint64_t total_net_input_bytes; + /** Total net output bytes */ + apr_uint64_t total_net_output_bytes; + /** Keyspace hits */ + apr_uint64_t keyspace_hits; + /** Keyspace misses */ + apr_uint64_t keyspace_misses; + +/* # Replication */ + /** Role */ + apr_redis_server_role_t role; + /** Number of connected slave */ + apr_uint32_t connected_slaves; + +/* # CPU */ + /** Accumulated CPU user time for this process */ + apr_uint32_t used_cpu_sys; + /** Accumulated CPU system time for this process */ + apr_uint32_t used_cpu_user; + +/* # Cluster */ + /** Is cluster enabled */ + apr_uint32_t cluster_enabled; +} apr_redis_stats_t; + +/** + * Query a server for statistics + * @param rs server to query + * @param p Pool to allocate answer from + * @param stats location of the new statistics structure + */ +APU_DECLARE(apr_status_t) apr_redis_stats(apr_redis_server_t *rs, + apr_pool_t *p, + apr_redis_stats_t **stats); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_REDIS_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_reslist.h b/c/dependencies/windows/apr/x86_debug/include/apr_reslist.h new file mode 100644 index 00000000..02a8192b --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_reslist.h @@ -0,0 +1,183 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_RESLIST_H +#define APR_RESLIST_H + +/** + * @file apr_reslist.h + * @brief APR-UTIL Resource List Routines + */ + +#include "apr.h" +#include "apu.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_time.h" + +/** + * @defgroup APR_Util_RL Resource List Routines + * @ingroup APR_Util + * @{ + */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** Opaque resource list object */ +typedef struct apr_reslist_t apr_reslist_t; + +/* Generic constructor called by resource list when it needs to create a + * resource. + * @param resource opaque resource + * @param params flags + * @param pool Pool + */ +typedef apr_status_t (*apr_reslist_constructor)(void **resource, void *params, + apr_pool_t *pool); + +/* Generic destructor called by resource list when it needs to destroy a + * resource. + * @param resource opaque resource + * @param params flags + * @param pool Pool + */ +typedef apr_status_t (*apr_reslist_destructor)(void *resource, void *params, + apr_pool_t *pool); + +/* Cleanup order modes */ +#define APR_RESLIST_CLEANUP_DEFAULT 0 /**< default pool cleanup */ +#define APR_RESLIST_CLEANUP_FIRST 1 /**< use pool pre cleanup */ + +/** + * Create a new resource list with the following parameters: + * @param reslist An address where the pointer to the new resource + * list will be stored. + * @param min Allowed minimum number of available resources. Zero + * creates new resources only when needed. + * @param smax Resources will be destroyed during reslist maintenance to + * meet this maximum restriction as they expire (reach their ttl). + * @param hmax Absolute maximum limit on the number of total resources. + * @param ttl If non-zero, sets the maximum amount of time in microseconds an + * unused resource is valid. Any resource which has exceeded this + * time will be destroyed, either when encountered by + * apr_reslist_acquire() or during reslist maintenance. + * @param con Constructor routine that is called to create a new resource. + * @param de Destructor routine that is called to destroy an expired resource. + * @param params Passed to constructor and deconstructor + * @param pool The pool from which to create this resource list. Also the + * same pool that is passed to the constructor and destructor + * routines. + * @remark If APR has been compiled without thread support, hmax will be + * automatically set to 1 and values of min and smax will be forced to + * 1 for any non-zero value. + */ +APU_DECLARE(apr_status_t) apr_reslist_create(apr_reslist_t **reslist, + int min, int smax, int hmax, + apr_interval_time_t ttl, + apr_reslist_constructor con, + apr_reslist_destructor de, + void *params, + apr_pool_t *pool); + +/** + * Destroy the given resource list and all resources controlled by + * this list. + * FIXME: Should this block until all resources become available, + * or maybe just destroy all the free ones, or maybe destroy + * them even though they might be in use by something else? + * Currently it will abort if there are resources that haven't + * been released, so there is an assumption that all resources + * have been released to the list before calling this function. + * @param reslist The reslist to destroy + */ +APU_DECLARE(apr_status_t) apr_reslist_destroy(apr_reslist_t *reslist); + +/** + * Retrieve a resource from the list, creating a new one if necessary. + * If we have met our maximum number of resources, we will block + * until one becomes available. + * @param reslist The resource list. + * @param resource An address where the pointer to the resource + * will be stored. + */ +APU_DECLARE(apr_status_t) apr_reslist_acquire(apr_reslist_t *reslist, + void **resource); + +/** + * Return a resource back to the list of available resources. + * @param reslist The resource list. + * @param resource The resource to return to the list. + */ +APU_DECLARE(apr_status_t) apr_reslist_release(apr_reslist_t *reslist, + void *resource); + +/** + * Set the timeout the acquire will wait for a free resource + * when the maximum number of resources is exceeded. + * @param reslist The resource list. + * @param timeout Timeout to wait. The zero waits forever. + */ +APU_DECLARE(void) apr_reslist_timeout_set(apr_reslist_t *reslist, + apr_interval_time_t timeout); + +/** + * Return the number of outstanding resources. + * @param reslist The resource list. + */ +APU_DECLARE(apr_uint32_t) apr_reslist_acquired_count(apr_reslist_t *reslist); + +/** + * Invalidate a resource in the pool - e.g. a database connection + * that returns a "lost connection" error and can't be restored. + * Use this instead of apr_reslist_release if the resource is bad. + * @param reslist The resource list. + * @param resource The resource to invalidate. + */ +APU_DECLARE(apr_status_t) apr_reslist_invalidate(apr_reslist_t *reslist, + void *resource); + +/** + * Perform routine maintenance on the resource list. This call + * may instantiate new resources or expire old resources. + * @param reslist The resource list. + */ +APU_DECLARE(apr_status_t) apr_reslist_maintain(apr_reslist_t *reslist); + +/** + * Set reslist cleanup order. + * @param reslist The resource list. + * @param mode Cleanup order mode + *
+ *           APR_RESLIST_CLEANUP_DEFAULT  default pool cleanup order
+ *           APR_RESLIST_CLEANUP_FIRST    use pool pre cleanup
+ * 
+ * @remark If APR_RESLIST_CLEANUP_FIRST is used the destructors will + * be called before child pools of the pool used to create the reslist + * are destroyed. This allows to explicitly destroy the child pools + * inside reslist destructors. + */ +APU_DECLARE(void) apr_reslist_cleanup_order_set(apr_reslist_t *reslist, + apr_uint32_t mode); + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif /* ! APR_RESLIST_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_ring.h b/c/dependencies/windows/apr/x86_debug/include/apr_ring.h new file mode 100644 index 00000000..eec735fc --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_ring.h @@ -0,0 +1,513 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * This code draws heavily from the 4.4BSD macros + * and Dean Gaudet's "splim/ring.h". + * + * + * + * We'd use Dean's code directly if we could guarantee the + * availability of inline functions. + */ + +#ifndef APR_RING_H +#define APR_RING_H + +/** + * @file apr_ring.h + * @brief APR Rings + */ + +/* + * for offsetof() + */ +#include "apr_general.h" + +/** + * @defgroup apr_ring Ring Macro Implementations + * @ingroup APR + * A ring is a kind of doubly-linked list that can be manipulated + * without knowing where its head is. + * @{ + */ + +/** + * The Ring Element + * + * A ring element struct is linked to the other elements in the ring + * through its ring entry field, e.g. + *
+ *      struct my_element_t {
+ *          APR_RING_ENTRY(my_element_t) link;
+ *          int foo;
+ *          char *bar;
+ *      };
+ * 
+ * + * An element struct may be put on more than one ring if it has more + * than one APR_RING_ENTRY field. Each APR_RING_ENTRY has a corresponding + * APR_RING_HEAD declaration. + * + * @warning For strict C standards compliance you should put the APR_RING_ENTRY + * first in the element struct unless the head is always part of a larger + * object with enough earlier fields to accommodate the offsetof() used + * to compute the ring sentinel below. You can usually ignore this caveat. + */ +#define APR_RING_ENTRY(elem) \ + struct { \ + struct elem * volatile next; \ + struct elem * volatile prev; \ + } + +/** + * The Ring Head + * + * Each ring is managed via its head, which is a struct declared like this: + *
+ *      APR_RING_HEAD(my_ring_t, my_element_t);
+ *      struct my_ring_t ring, *ringp;
+ * 
+ * + * This struct looks just like the element link struct so that we can + * be sure that the typecasting games will work as expected. + * + * The first element in the ring is next after the head, and the last + * element is just before the head. + */ +#define APR_RING_HEAD(head, elem) \ + struct head { \ + struct elem * volatile next; \ + struct elem * volatile prev; \ + } + +/** + * The Ring Sentinel + * + * This is the magic pointer value that occurs before the first and + * after the last elements in the ring, computed from the address of + * the ring's head. The head itself isn't an element, but in order to + * get rid of all the special cases when dealing with the ends of the + * ring, we play typecasting games to make it look like one. + * + * Here is a diagram to illustrate the arrangements of the next and + * prev pointers of each element in a single ring. Note that they point + * to the start of each element, not to the APR_RING_ENTRY structure. + * + *
+ *     +->+------+<-+  +->+------+<-+  +->+------+<-+
+ *     |  |struct|  |  |  |struct|  |  |  |struct|  |
+ *    /   | elem |   \/   | elem |   \/   | elem |  \
+ * ...    |      |   /\   |      |   /\   |      |   ...
+ *        +------+  |  |  +------+  |  |  +------+
+ *   ...--|prev  |  |  +--|ring  |  |  +--|prev  |
+ *        |  next|--+     | entry|--+     |  next|--...
+ *        +------+        +------+        +------+
+ *        | etc. |        | etc. |        | etc. |
+ *        :      :        :      :        :      :
+ * 
+ * + * The APR_RING_HEAD is nothing but a bare APR_RING_ENTRY. The prev + * and next pointers in the first and last elements don't actually + * point to the head, they point to a phantom place called the + * sentinel. Its value is such that last->next->next == first because + * the offset from the sentinel to the head's next pointer is the same + * as the offset from the start of an element to its next pointer. + * This also works in the opposite direction. + * + *
+ *        last                            first
+ *     +->+------+<-+  +->sentinel<-+  +->+------+<-+
+ *     |  |struct|  |  |            |  |  |struct|  |
+ *    /   | elem |   \/              \/   | elem |  \
+ * ...    |      |   /\              /\   |      |   ...
+ *        +------+  |  |  +------+  |  |  +------+
+ *   ...--|prev  |  |  +--|ring  |  |  +--|prev  |
+ *        |  next|--+     |  head|--+     |  next|--...
+ *        +------+        +------+        +------+
+ *        | etc. |                        | etc. |
+ *        :      :                        :      :
+ * 
+ * + * Note that the offset mentioned above is different for each kind of + * ring that the element may be on, and each kind of ring has a unique + * name for its APR_RING_ENTRY in each element, and has its own type + * for its APR_RING_HEAD. + * + * Note also that if the offset is non-zero (which is required if an + * element has more than one APR_RING_ENTRY), the unreality of the + * sentinel may have bad implications on very perverse implementations + * of C -- see the warning in APR_RING_ENTRY. + * + * @param hp The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SENTINEL(hp, elem, link) \ + (struct elem *)((char *)(&(hp)->next) - APR_OFFSETOF(struct elem, link)) + +/** + * The first element of the ring + * @param hp The head of the ring + */ +#define APR_RING_FIRST(hp) (hp)->next +/** + * The last element of the ring + * @param hp The head of the ring + */ +#define APR_RING_LAST(hp) (hp)->prev +/** + * The next element in the ring + * @param ep The current element + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_NEXT(ep, link) (ep)->link.next +/** + * The previous element in the ring + * @param ep The current element + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_PREV(ep, link) (ep)->link.prev + + +/** + * Initialize a ring + * @param hp The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INIT(hp, elem, link) do { \ + APR_RING_FIRST((hp)) = APR_RING_SENTINEL((hp), elem, link); \ + APR_RING_LAST((hp)) = APR_RING_SENTINEL((hp), elem, link); \ + } while (0) + +/** + * Determine if a ring is empty + * @param hp The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + * @return true or false + */ +#define APR_RING_EMPTY(hp, elem, link) \ + (APR_RING_FIRST((hp)) == APR_RING_SENTINEL((hp), elem, link)) + +/** + * Initialize a singleton element + * @param ep The element + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_ELEM_INIT(ep, link) do { \ + APR_RING_NEXT((ep), link) = (ep); \ + APR_RING_PREV((ep), link) = (ep); \ + } while (0) + + +/** + * Splice the sequence ep1..epN into the ring before element lep + * (..lep.. becomes ..ep1..epN..lep..) + * @warning This doesn't work for splicing before the first element or on + * empty rings... see APR_RING_SPLICE_HEAD for one that does + * @param lep Element in the ring to splice before + * @param ep1 First element in the sequence to splice in + * @param epN Last element in the sequence to splice in + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SPLICE_BEFORE(lep, ep1, epN, link) do { \ + APR_RING_NEXT((epN), link) = (lep); \ + APR_RING_PREV((ep1), link) = APR_RING_PREV((lep), link); \ + APR_RING_NEXT(APR_RING_PREV((lep), link), link) = (ep1); \ + APR_RING_PREV((lep), link) = (epN); \ + } while (0) + +/** + * Splice the sequence ep1..epN into the ring after element lep + * (..lep.. becomes ..lep..ep1..epN..) + * @warning This doesn't work for splicing after the last element or on + * empty rings... see APR_RING_SPLICE_TAIL for one that does + * @param lep Element in the ring to splice after + * @param ep1 First element in the sequence to splice in + * @param epN Last element in the sequence to splice in + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SPLICE_AFTER(lep, ep1, epN, link) do { \ + APR_RING_PREV((ep1), link) = (lep); \ + APR_RING_NEXT((epN), link) = APR_RING_NEXT((lep), link); \ + APR_RING_PREV(APR_RING_NEXT((lep), link), link) = (epN); \ + APR_RING_NEXT((lep), link) = (ep1); \ + } while (0) + +/** + * Insert the element nep into the ring before element lep + * (..lep.. becomes ..nep..lep..) + * @warning This doesn't work for inserting before the first element or on + * empty rings... see APR_RING_INSERT_HEAD for one that does + * @param lep Element in the ring to insert before + * @param nep Element to insert + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INSERT_BEFORE(lep, nep, link) \ + APR_RING_SPLICE_BEFORE((lep), (nep), (nep), link) + +/** + * Insert the element nep into the ring after element lep + * (..lep.. becomes ..lep..nep..) + * @warning This doesn't work for inserting after the last element or on + * empty rings... see APR_RING_INSERT_TAIL for one that does + * @param lep Element in the ring to insert after + * @param nep Element to insert + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INSERT_AFTER(lep, nep, link) \ + APR_RING_SPLICE_AFTER((lep), (nep), (nep), link) + + +/** + * Splice the sequence ep1..epN into the ring before the first element + * (..hp.. becomes ..hp..ep1..epN..) + * @param hp Head of the ring + * @param ep1 First element in the sequence to splice in + * @param epN Last element in the sequence to splice in + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SPLICE_HEAD(hp, ep1, epN, elem, link) \ + APR_RING_SPLICE_AFTER(APR_RING_SENTINEL((hp), elem, link), \ + (ep1), (epN), link) + +/** + * Splice the sequence ep1..epN into the ring after the last element + * (..hp.. becomes ..ep1..epN..hp..) + * @param hp Head of the ring + * @param ep1 First element in the sequence to splice in + * @param epN Last element in the sequence to splice in + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_SPLICE_TAIL(hp, ep1, epN, elem, link) \ + APR_RING_SPLICE_BEFORE(APR_RING_SENTINEL((hp), elem, link), \ + (ep1), (epN), link) + +/** + * Insert the element nep into the ring before the first element + * (..hp.. becomes ..hp..nep..) + * @param hp Head of the ring + * @param nep Element to insert + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INSERT_HEAD(hp, nep, elem, link) \ + APR_RING_SPLICE_HEAD((hp), (nep), (nep), elem, link) + +/** + * Insert the element nep into the ring after the last element + * (..hp.. becomes ..nep..hp..) + * @param hp Head of the ring + * @param nep Element to insert + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_INSERT_TAIL(hp, nep, elem, link) \ + APR_RING_SPLICE_TAIL((hp), (nep), (nep), elem, link) + +/** + * Concatenate ring h2 onto the end of ring h1, leaving h2 empty. + * @param h1 Head of the ring to concatenate onto + * @param h2 Head of the ring to concatenate + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_CONCAT(h1, h2, elem, link) do { \ + if (!APR_RING_EMPTY((h2), elem, link)) { \ + APR_RING_SPLICE_BEFORE(APR_RING_SENTINEL((h1), elem, link), \ + APR_RING_FIRST((h2)), \ + APR_RING_LAST((h2)), link); \ + APR_RING_INIT((h2), elem, link); \ + } \ + } while (0) + +/** + * Prepend ring h2 onto the beginning of ring h1, leaving h2 empty. + * @param h1 Head of the ring to prepend onto + * @param h2 Head of the ring to prepend + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_PREPEND(h1, h2, elem, link) do { \ + if (!APR_RING_EMPTY((h2), elem, link)) { \ + APR_RING_SPLICE_AFTER(APR_RING_SENTINEL((h1), elem, link), \ + APR_RING_FIRST((h2)), \ + APR_RING_LAST((h2)), link); \ + APR_RING_INIT((h2), elem, link); \ + } \ + } while (0) + +/** + * Unsplice a sequence of elements from a ring + * @warning The unspliced sequence is left with dangling pointers at either end + * @param ep1 First element in the sequence to unsplice + * @param epN Last element in the sequence to unsplice + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_UNSPLICE(ep1, epN, link) do { \ + APR_RING_NEXT(APR_RING_PREV((ep1), link), link) = \ + APR_RING_NEXT((epN), link); \ + APR_RING_PREV(APR_RING_NEXT((epN), link), link) = \ + APR_RING_PREV((ep1), link); \ + } while (0) + +/** + * Remove a single element from a ring + * @warning The unspliced element is left with dangling pointers at either end + * @param ep Element to remove + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_REMOVE(ep, link) \ + APR_RING_UNSPLICE((ep), (ep), link) + +/** + * Iterate over a ring + * @param ep The current element + * @param head The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_FOREACH(ep, head, elem, link) \ + for (ep = APR_RING_FIRST(head); \ + ep != APR_RING_SENTINEL(head, elem, link); \ + ep = APR_RING_NEXT(ep, link)) + +/** + * Iterate over a ring safe against removal of the current element + * @param ep1 The current element + * @param ep2 Iteration cursor + * @param head The head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_FOREACH_SAFE(ep1, ep2, head, elem, link) \ + for (ep1 = APR_RING_FIRST(head), ep2 = APR_RING_NEXT(ep1, link); \ + ep1 != APR_RING_SENTINEL(head, elem, link); \ + ep1 = ep2, ep2 = APR_RING_NEXT(ep1, link)) + +/* Debugging tools: */ + +#ifdef APR_RING_DEBUG +#include +#include + +#define APR_RING_CHECK_ONE(msg, ptr) \ + fprintf(stderr, "*** %s %p\n", msg, ptr) + +#define APR_RING_CHECK(hp, elem, link, msg) \ + APR_RING_CHECK_ELEM(APR_RING_SENTINEL(hp, elem, link), elem, link, msg) + +#define APR_RING_CHECK_ELEM(ep, elem, link, msg) do { \ + struct elem *start = (ep); \ + struct elem *here = start; \ + fprintf(stderr, "*** ring check start -- %s\n", msg); \ + do { \ + fprintf(stderr, "\telem %p\n", here); \ + fprintf(stderr, "\telem->next %p\n", \ + APR_RING_NEXT(here, link)); \ + fprintf(stderr, "\telem->prev %p\n", \ + APR_RING_PREV(here, link)); \ + fprintf(stderr, "\telem->next->prev %p\n", \ + APR_RING_PREV(APR_RING_NEXT(here, link), link)); \ + fprintf(stderr, "\telem->prev->next %p\n", \ + APR_RING_NEXT(APR_RING_PREV(here, link), link)); \ + if (APR_RING_PREV(APR_RING_NEXT(here, link), link) != here) { \ + fprintf(stderr, "\t*** elem->next->prev != elem\n"); \ + break; \ + } \ + if (APR_RING_NEXT(APR_RING_PREV(here, link), link) != here) { \ + fprintf(stderr, "\t*** elem->prev->next != elem\n"); \ + break; \ + } \ + here = APR_RING_NEXT(here, link); \ + } while (here != start); \ + fprintf(stderr, "*** ring check end\n"); \ + } while (0) + +#define APR_RING_CHECK_CONSISTENCY(hp, elem, link) \ + APR_RING_CHECK_ELEM_CONSISTENCY(APR_RING_SENTINEL(hp, elem, link),\ + elem, link) + +#define APR_RING_CHECK_ELEM_CONSISTENCY(ep, elem, link) do { \ + struct elem *start = (ep); \ + struct elem *here = start; \ + do { \ + assert(APR_RING_PREV(APR_RING_NEXT(here, link), link) == here); \ + assert(APR_RING_NEXT(APR_RING_PREV(here, link), link) == here); \ + here = APR_RING_NEXT(here, link); \ + } while (here != start); \ + } while (0) + +#else +/** + * Print a single pointer value to STDERR + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param msg Descriptive message + * @param ptr Pointer value to print + */ +#define APR_RING_CHECK_ONE(msg, ptr) +/** + * Dump all ring pointers to STDERR, starting with the head and looping all + * the way around the ring back to the head. Aborts if an inconsistency + * is found. + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param hp Head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + * @param msg Descriptive message + */ +#define APR_RING_CHECK(hp, elem, link, msg) +/** + * Loops around a ring and checks all the pointers for consistency. Pops + * an assertion if any inconsistency is found. Same idea as APR_RING_CHECK() + * except that it's silent if all is well. + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param hp Head of the ring + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_CHECK_CONSISTENCY(hp, elem, link) +/** + * Dump all ring pointers to STDERR, starting with the given element and + * looping all the way around the ring back to that element. Aborts if + * an inconsistency is found. + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param ep The element + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + * @param msg Descriptive message + */ +#define APR_RING_CHECK_ELEM(ep, elem, link, msg) +/** + * Loops around a ring, starting with the given element, and checks all + * the pointers for consistency. Pops an assertion if any inconsistency + * is found. Same idea as APR_RING_CHECK_ELEM() except that it's silent + * if all is well. + * (This is a no-op unless APR_RING_DEBUG is defined.) + * @param ep The element + * @param elem The name of the element struct + * @param link The name of the APR_RING_ENTRY in the element struct + */ +#define APR_RING_CHECK_ELEM_CONSISTENCY(ep, elem, link) +#endif + +/** @} */ + +#endif /* !APR_RING_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_rmm.h b/c/dependencies/windows/apr/x86_debug/include/apr_rmm.h new file mode 100644 index 00000000..976fe9c5 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_rmm.h @@ -0,0 +1,137 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_RMM_H +#define APR_RMM_H +/** + * @file apr_rmm.h + * @brief APR-UTIL Relocatable Memory Management Routines + */ +/** + * @defgroup APR_Util_RMM Relocatable Memory Management Routines + * @ingroup APR_Util + * @{ + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apu.h" +#include "apr_anylock.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** Structure to access Relocatable, Managed Memory */ +typedef struct apr_rmm_t apr_rmm_t; + +/** Fundamental allocation unit, within a specific apr_rmm_t */ +typedef apr_size_t apr_rmm_off_t; + +/** + * Initialize a relocatable memory block to be managed by the apr_rmm API. + * @param rmm The relocatable memory block + * @param lock An apr_anylock_t of the appropriate type of lock, or NULL + * if no locking is required. + * @param membuf The block of relocatable memory to be managed + * @param memsize The size of relocatable memory block to be managed + * @param cont The pool to use for local storage and management + * @remark Both @param membuf and @param memsize must be aligned + * (for instance using APR_ALIGN_DEFAULT). + */ +APU_DECLARE(apr_status_t) apr_rmm_init(apr_rmm_t **rmm, apr_anylock_t *lock, + void *membuf, apr_size_t memsize, + apr_pool_t *cont); + +/** + * Destroy a managed memory block. + * @param rmm The relocatable memory block to destroy + */ +APU_DECLARE(apr_status_t) apr_rmm_destroy(apr_rmm_t *rmm); + +/** + * Attach to a relocatable memory block already managed by the apr_rmm API. + * @param rmm The relocatable memory block + * @param lock An apr_anylock_t of the appropriate type of lock + * @param membuf The block of relocatable memory already under management + * @param cont The pool to use for local storage and management + */ +APU_DECLARE(apr_status_t) apr_rmm_attach(apr_rmm_t **rmm, apr_anylock_t *lock, + void *membuf, apr_pool_t *cont); + +/** + * Detach from the managed block of memory. + * @param rmm The relocatable memory block to detach from + */ +APU_DECLARE(apr_status_t) apr_rmm_detach(apr_rmm_t *rmm); + +/** + * Allocate memory from the block of relocatable memory. + * @param rmm The relocatable memory block + * @param reqsize How much memory to allocate + */ +APU_DECLARE(apr_rmm_off_t) apr_rmm_malloc(apr_rmm_t *rmm, apr_size_t reqsize); + +/** + * Realloc memory from the block of relocatable memory. + * @param rmm The relocatable memory block + * @param entity The memory allocation to realloc + * @param reqsize The new size + */ +APU_DECLARE(apr_rmm_off_t) apr_rmm_realloc(apr_rmm_t *rmm, void *entity, apr_size_t reqsize); + +/** + * Allocate memory from the block of relocatable memory and initialize it to zero. + * @param rmm The relocatable memory block + * @param reqsize How much memory to allocate + */ +APU_DECLARE(apr_rmm_off_t) apr_rmm_calloc(apr_rmm_t *rmm, apr_size_t reqsize); + +/** + * Free allocation returned by apr_rmm_malloc or apr_rmm_calloc. + * @param rmm The relocatable memory block + * @param entity The memory allocation to free + */ +APU_DECLARE(apr_status_t) apr_rmm_free(apr_rmm_t *rmm, apr_rmm_off_t entity); + +/** + * Retrieve the physical address of a relocatable allocation of memory + * @param rmm The relocatable memory block + * @param entity The memory allocation to free + * @return address The address, aligned with APR_ALIGN_DEFAULT. + */ +APU_DECLARE(void *) apr_rmm_addr_get(apr_rmm_t *rmm, apr_rmm_off_t entity); + +/** + * Compute the offset of a relocatable allocation of memory + * @param rmm The relocatable memory block + * @param entity The physical address to convert to an offset + */ +APU_DECLARE(apr_rmm_off_t) apr_rmm_offset_get(apr_rmm_t *rmm, void *entity); + +/** + * Compute the required overallocation of memory needed to fit n allocs + * @param n The number of alloc/calloc regions desired + */ +APU_DECLARE(apr_size_t) apr_rmm_overhead_get(int n); + +#ifdef __cplusplus +} +#endif +/** @} */ +#endif /* ! APR_RMM_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_sdbm.h b/c/dependencies/windows/apr/x86_debug/include/apr_sdbm.h new file mode 100644 index 00000000..5759508b --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_sdbm.h @@ -0,0 +1,176 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * sdbm - ndbm work-alike hashed database library + * based on Per-Ake Larson's Dynamic Hashing algorithms. BIT 18 (1978). + * author: oz@nexus.yorku.ca + * status: ex-public domain + */ + +#ifndef APR_SDBM_H +#define APR_SDBM_H + +#include "apu.h" +#include "apr_errno.h" +#include "apr_file_io.h" /* for apr_fileperms_t */ + +/** + * @file apr_sdbm.h + * @brief apr-util SDBM library + */ +/** + * @defgroup APR_Util_DBM_SDBM SDBM library + * @ingroup APR_Util_DBM + * @{ + */ + +/** + * Structure for referencing an sdbm + */ +typedef struct apr_sdbm_t apr_sdbm_t; + +/** + * Structure for referencing the datum record within an sdbm + */ +typedef struct { + /** pointer to the data stored/retrieved */ + char *dptr; + /** size of data */ + /* apr_ssize_t for release 2.0??? */ + int dsize; +} apr_sdbm_datum_t; + +/* The extensions used for the database files */ +/** SDBM Directory file extension */ +#define APR_SDBM_DIRFEXT ".dir" +/** SDBM page file extension */ +#define APR_SDBM_PAGFEXT ".pag" + +/* flags to sdbm_store */ +#define APR_SDBM_INSERT 0 /**< Insert */ +#define APR_SDBM_REPLACE 1 /**< Replace */ +#define APR_SDBM_INSERTDUP 2 /**< Insert with duplicates */ + +/** + * Open an sdbm database by file name + * @param db The newly opened database + * @param name The sdbm file to open + * @param mode The flag values (APR_READ and APR_BINARY flags are implicit) + *
+ *           APR_WRITE          open for read-write access
+ *           APR_CREATE         create the sdbm if it does not exist
+ *           APR_TRUNCATE       empty the contents of the sdbm
+ *           APR_EXCL           fail for APR_CREATE if the file exists
+ *           APR_DELONCLOSE     delete the sdbm when closed
+ *           APR_SHARELOCK      support locking across process/machines
+ * 
+ * @param perms Permissions to apply to if created + * @param p The pool to use when creating the sdbm + * @remark The sdbm name is not a true file name, as sdbm appends suffixes + * for seperate data and index files. + */ +APU_DECLARE(apr_status_t) apr_sdbm_open(apr_sdbm_t **db, const char *name, + apr_int32_t mode, + apr_fileperms_t perms, apr_pool_t *p); + +/** + * Close an sdbm file previously opened by apr_sdbm_open + * @param db The database to close + */ +APU_DECLARE(apr_status_t) apr_sdbm_close(apr_sdbm_t *db); + +/** + * Lock an sdbm database for concurency of multiple operations + * @param db The database to lock + * @param type The lock type + *
+ *           APR_FLOCK_SHARED
+ *           APR_FLOCK_EXCLUSIVE
+ * 
+ * @remark Calls to apr_sdbm_lock may be nested. All apr_sdbm functions + * perform implicit locking. Since an APR_FLOCK_SHARED lock cannot be + * portably promoted to an APR_FLOCK_EXCLUSIVE lock, apr_sdbm_store and + * apr_sdbm_delete calls will fail if an APR_FLOCK_SHARED lock is held. + * The apr_sdbm_lock call requires the database to be opened with the + * APR_SHARELOCK mode value. + */ +APU_DECLARE(apr_status_t) apr_sdbm_lock(apr_sdbm_t *db, int type); + +/** + * Release an sdbm lock previously aquired by apr_sdbm_lock + * @param db The database to unlock + */ +APU_DECLARE(apr_status_t) apr_sdbm_unlock(apr_sdbm_t *db); + +/** + * Fetch an sdbm record value by key + * @param db The database + * @param value The value datum retrieved for this record + * @param key The key datum to find this record + */ +APU_DECLARE(apr_status_t) apr_sdbm_fetch(apr_sdbm_t *db, + apr_sdbm_datum_t *value, + apr_sdbm_datum_t key); + +/** + * Store an sdbm record value by key + * @param db The database + * @param key The key datum to store this record by + * @param value The value datum to store in this record + * @param opt The method used to store the record + *
+ *           APR_SDBM_INSERT     return an error if the record exists
+ *           APR_SDBM_REPLACE    overwrite any existing record for key
+ * 
+ */ +APU_DECLARE(apr_status_t) apr_sdbm_store(apr_sdbm_t *db, apr_sdbm_datum_t key, + apr_sdbm_datum_t value, int opt); + +/** + * Delete an sdbm record value by key + * @param db The database + * @param key The key datum of the record to delete + * @remark It is not an error to delete a non-existent record. + */ +APU_DECLARE(apr_status_t) apr_sdbm_delete(apr_sdbm_t *db, + const apr_sdbm_datum_t key); + +/** + * Retrieve the first record key from a dbm + * @param db The database + * @param key The key datum of the first record + * @remark The keys returned are not ordered. To traverse the list of keys + * for an sdbm opened with APR_SHARELOCK, the caller must use apr_sdbm_lock + * prior to retrieving the first record, and hold the lock until after the + * last call to apr_sdbm_nextkey. + */ +APU_DECLARE(apr_status_t) apr_sdbm_firstkey(apr_sdbm_t *db, apr_sdbm_datum_t *key); + +/** + * Retrieve the next record key from an sdbm + * @param db The database + * @param key The key datum of the next record + */ +APU_DECLARE(apr_status_t) apr_sdbm_nextkey(apr_sdbm_t *db, apr_sdbm_datum_t *key); + +/** + * Returns true if the sdbm database opened for read-only access + * @param db The database to test + */ +APU_DECLARE(int) apr_sdbm_rdonly(apr_sdbm_t *db); +/** @} */ +#endif /* APR_SDBM_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_sha1.h b/c/dependencies/windows/apr/x86_debug/include/apr_sha1.h new file mode 100644 index 00000000..2a4edf36 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_sha1.h @@ -0,0 +1,121 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* NIST Secure Hash Algorithm + * heavily modified by Uwe Hollerbach uh@alumni.caltech edu + * from Peter C. Gutmann's implementation as found in + * Applied Cryptography by Bruce Schneier + * This code is hereby placed in the public domain + */ + +#ifndef APR_SHA1_H +#define APR_SHA1_H + +#include "apu.h" +#include "apr_general.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_sha1.h + * @brief APR-UTIL SHA1 library + */ + +/** size of the SHA1 DIGEST */ +#define APR_SHA1_DIGESTSIZE 20 + +/** + * Define the Magic String prefix that identifies a password as being + * hashed using our algorithm. + */ +#define APR_SHA1PW_ID "{SHA}" + +/** length of the SHA Password */ +#define APR_SHA1PW_IDLEN 5 + +/** @see apr_sha1_ctx_t */ +typedef struct apr_sha1_ctx_t apr_sha1_ctx_t; + +/** + * SHA1 context structure + */ +struct apr_sha1_ctx_t { + /** message digest */ + apr_uint32_t digest[5]; + /** 64-bit bit counts */ + apr_uint32_t count_lo, count_hi; + /** SHA data buffer */ + apr_uint32_t data[16]; + /** unprocessed amount in data */ + int local; +}; + +/** + * Provide a means to SHA1 crypt/encode a plaintext password in a way which + * makes password file compatible with those commonly use in netscape web + * and ldap installations. + * @param clear The plaintext password + * @param len The length of the plaintext password + * @param out The encrypted/encoded password + * @note SHA1 support is useful for migration purposes, but is less + * secure than Apache's password format, since Apache's (MD5) + * password format uses a random eight character salt to generate + * one of many possible hashes for the same password. Netscape + * uses plain SHA1 without a salt, so the same password + * will always generate the same hash, making it easier + * to break since the search space is smaller. + */ +APU_DECLARE(void) apr_sha1_base64(const char *clear, int len, char *out); + +/** + * Initialize the SHA digest + * @param context The SHA context to initialize + */ +APU_DECLARE(void) apr_sha1_init(apr_sha1_ctx_t *context); + +/** + * Update the SHA digest + * @param context The SHA1 context to update + * @param input The buffer to add to the SHA digest + * @param inputLen The length of the input buffer + */ +APU_DECLARE(void) apr_sha1_update(apr_sha1_ctx_t *context, const char *input, + unsigned int inputLen); + +/** + * Update the SHA digest with binary data + * @param context The SHA1 context to update + * @param input The buffer to add to the SHA digest + * @param inputLen The length of the input buffer + */ +APU_DECLARE(void) apr_sha1_update_binary(apr_sha1_ctx_t *context, + const unsigned char *input, + unsigned int inputLen); + +/** + * Finish computing the SHA digest + * @param digest the output buffer in which to store the digest + * @param context The context to finalize + */ +APU_DECLARE(void) apr_sha1_final(unsigned char digest[APR_SHA1_DIGESTSIZE], + apr_sha1_ctx_t *context); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_SHA1_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_shm.h b/c/dependencies/windows/apr/x86_debug/include/apr_shm.h new file mode 100644 index 00000000..635c654b --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_shm.h @@ -0,0 +1,229 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_SHM_H +#define APR_SHM_H + +/** + * @file apr_shm.h + * @brief APR Shared Memory Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_perms_set.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_shm Shared Memory Routines + * @ingroup APR + * @{ + */ + +/** + * Private, platform-specific data struture representing a shared memory + * segment. + */ +typedef struct apr_shm_t apr_shm_t; + +/** + * Create and make accessible a shared memory segment with default + * properties. + * @param m The shared memory structure to create. + * @param reqsize The desired size of the segment. + * @param filename The file to use for shared memory on platforms that + * require it. + * @param pool the pool from which to allocate the shared memory + * structure. + * @remark A note about Anonymous vs. Named shared memory segments: + * Not all plaforms support anonymous shared memory segments, but in + * some cases it is prefered over other types of shared memory + * implementations. Passing a NULL 'file' parameter to this function + * will cause the subsystem to use anonymous shared memory segments. + * If such a system is not available, APR_ENOTIMPL is returned. + * @remark A note about allocation sizes: + * On some platforms it is necessary to store some metainformation + * about the segment within the actual segment. In order to supply + * the caller with the requested size it may be necessary for the + * implementation to request a slightly greater segment length + * from the subsystem. In all cases, the apr_shm_baseaddr_get() + * function will return the first usable byte of memory. + * + */ +APR_DECLARE(apr_status_t) apr_shm_create(apr_shm_t **m, + apr_size_t reqsize, + const char *filename, + apr_pool_t *pool); + +/** + * Special processing flags for apr_shm_create_ex() and apr_shm_attach_ex(). + */ +#define APR_SHM_NS_LOCAL 1 /* Create or attach to named shared memory + * segment in the "Local" namespace on + * Windows. (Ignored on other platforms.) + * By default, the "Global" namespace is + * used for privileged processes and the + * "Local" namespace is used otherwise. + */ +#define APR_SHM_NS_GLOBAL 2 /* Create or attach to named shared memory + * segment in the "Global" namespace on + * Windows. (Ignored on other platforms.) + */ + +/** + * Create and make accessible a shared memory segment with platform- + * specific processing. + * @param m The shared memory structure to create. + * @param reqsize The desired size of the segment. + * @param filename The file to use for shared memory on platforms that + * require it. + * @param pool the pool from which to allocate the shared memory + * structure. + * @param flags mask of APR_SHM_* (defined above) + * @remark A note about Anonymous vs. Named shared memory segments: + * Not all plaforms support anonymous shared memory segments, but in + * some cases it is prefered over other types of shared memory + * implementations. Passing a NULL 'file' parameter to this function + * will cause the subsystem to use anonymous shared memory segments. + * If such a system is not available, APR_ENOTIMPL is returned. + * @remark A note about allocation sizes: + * On some platforms it is necessary to store some metainformation + * about the segment within the actual segment. In order to supply + * the caller with the requested size it may be necessary for the + * implementation to request a slightly greater segment length + * from the subsystem. In all cases, the apr_shm_baseaddr_get() + * function will return the first usable byte of memory. + * + */ +APR_DECLARE(apr_status_t) apr_shm_create_ex(apr_shm_t **m, + apr_size_t reqsize, + const char *filename, + apr_pool_t *pool, + apr_int32_t flags); + +/** + * Remove named resource associated with a shared memory segment, + * preventing attachments to the resource, but not destroying it. + * @param filename The filename associated with shared-memory segment which + * needs to be removed + * @param pool The pool used for file operations + * @remark This function is only supported on platforms which support + * name-based shared memory segments, and will return APR_ENOTIMPL on + * platforms without such support. Removing the file while the shm + * is in use is not entirely portable, caller may use this to enhance + * obscurity of the resource, but be prepared for the call to fail, + * and for concurrent attempts to create a resource of the same name + * to also fail. The pool cleanup of apr_shm_create (apr_shm_destroy) + * also removes the named resource. + */ +APR_DECLARE(apr_status_t) apr_shm_remove(const char *filename, + apr_pool_t *pool); + +/** + * Delete named resource associated with a shared memory segment, + * preventing attachments to the resource. + * @param m The shared memory segment structure to delete. + * @remark This function is only supported on platforms which support + * name-based shared memory segments, and will return APR_ENOTIMPL on + * platforms without such support. Removing the file while the shm + * is in use is not entirely portable, caller may use this to enhance + * obscurity of the resource, but be prepared for the call to fail, + * and for concurrent attempts to create a resource of the same name + * to also fail. The pool cleanup of apr_shm_create (apr_shm_destroy) + * also removes the named resource. + */ +APR_DECLARE(apr_status_t) apr_shm_delete(apr_shm_t *m); + +/** + * Destroy a shared memory segment and associated memory. + * @param m The shared memory segment structure to destroy. + */ +APR_DECLARE(apr_status_t) apr_shm_destroy(apr_shm_t *m); + +/** + * Attach to a shared memory segment that was created + * by another process. + * @param m The shared memory structure to create. + * @param filename The file used to create the original segment. + * (This MUST match the original filename.) + * @param pool the pool from which to allocate the shared memory + * structure for this process. + */ +APR_DECLARE(apr_status_t) apr_shm_attach(apr_shm_t **m, + const char *filename, + apr_pool_t *pool); + +/** + * Attach to a shared memory segment that was created + * by another process, with platform-specific processing. + * @param m The shared memory structure to create. + * @param filename The file used to create the original segment. + * (This MUST match the original filename.) + * @param pool the pool from which to allocate the shared memory + * structure for this process. + * @param flags mask of APR_SHM_* (defined above) + */ +APR_DECLARE(apr_status_t) apr_shm_attach_ex(apr_shm_t **m, + const char *filename, + apr_pool_t *pool, + apr_int32_t flags); + +/** + * Detach from a shared memory segment without destroying it. + * @param m The shared memory structure representing the segment + * to detach from. + */ +APR_DECLARE(apr_status_t) apr_shm_detach(apr_shm_t *m); + +/** + * Retrieve the base address of the shared memory segment. + * NOTE: This address is only usable within the callers address + * space, since this API does not guarantee that other attaching + * processes will maintain the same address mapping. + * @param m The shared memory segment from which to retrieve + * the base address. + * @return address, aligned by APR_ALIGN_DEFAULT. + */ +APR_DECLARE(void *) apr_shm_baseaddr_get(const apr_shm_t *m); + +/** + * Retrieve the length of a shared memory segment in bytes. + * @param m The shared memory segment from which to retrieve + * the segment length. + */ +APR_DECLARE(apr_size_t) apr_shm_size_get(const apr_shm_t *m); + +/** + * Set shared memory permissions. + */ +APR_PERMS_SET_IMPLEMENT(shm); + +/** + * Get the pool used by this shared memory segment. + */ +APR_POOL_DECLARE_ACCESSOR(shm); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_SHM_T */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_signal.h b/c/dependencies/windows/apr/x86_debug/include/apr_signal.h new file mode 100644 index 00000000..20631333 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_signal.h @@ -0,0 +1,109 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_SIGNAL_H +#define APR_SIGNAL_H + +/** + * @file apr_signal.h + * @brief APR Signal Handling + */ + +#include "apr.h" +#include "apr_pools.h" + +#if APR_HAVE_SIGNAL_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_signal Signal Handling + * @ingroup APR + * @{ + */ + +#if APR_HAVE_SIGACTION || defined(DOXYGEN) + +#if defined(DARWIN) && !defined(__cplusplus) && !defined(_ANSI_SOURCE) +/* work around Darwin header file bugs + * http://www.opensource.apple.com/bugs/X/BSD%20Kernel/2657228.html + */ +#undef SIG_DFL +#undef SIG_IGN +#undef SIG_ERR +#define SIG_DFL (void (*)(int))0 +#define SIG_IGN (void (*)(int))1 +#define SIG_ERR (void (*)(int))-1 +#endif + +/** Function prototype for signal handlers */ +typedef void apr_sigfunc_t(int); + +/** + * Set the signal handler function for a given signal + * @param signo The signal (eg... SIGWINCH) + * @param func the function to get called + */ +APR_DECLARE(apr_sigfunc_t *) apr_signal(int signo, apr_sigfunc_t * func); + +#if defined(SIG_IGN) && !defined(SIG_ERR) +#define SIG_ERR ((apr_sigfunc_t *) -1) +#endif + +#else /* !APR_HAVE_SIGACTION */ +#define apr_signal(a, b) signal(a, b) +#endif + + +/** + * Get the description for a specific signal number + * @param signum The signal number + * @return The description of the signal + */ +APR_DECLARE(const char *) apr_signal_description_get(int signum); + +/** + * APR-private function for initializing the signal package + * @internal + * @param pglobal The internal, global pool + */ +void apr_signal_init(apr_pool_t *pglobal); + +/** + * Block the delivery of a particular signal + * @param signum The signal number + * @return status + */ +APR_DECLARE(apr_status_t) apr_signal_block(int signum); + +/** + * Enable the delivery of a particular signal + * @param signum The signal number + * @return status + */ +APR_DECLARE(apr_status_t) apr_signal_unblock(int signum); + +/** @} */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* APR_SIGNAL_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_siphash.h b/c/dependencies/windows/apr/x86_debug/include/apr_siphash.h new file mode 100644 index 00000000..42aa8874 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_siphash.h @@ -0,0 +1,148 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + SipHash reference C implementation + Copyright (c) 2012-2014 Jean-Philippe Aumasson + + Copyright (c) 2012-2014 Daniel J. Bernstein + To the extent possible under law, the author(s) have dedicated all copyright + and related and neighboring rights to this software to the public domain + worldwide. This software is distributed without any warranty. + You should have received a copy of the CC0 Public Domain Dedication along + with this software. If not, see + . + */ + +#ifndef APR_SIPHASH_H +#define APR_SIPHASH_H + +#include "apr.h" +#include "apu.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file apr_siphash.h + * @brief APR-UTIL siphash library + * "SipHash-c-d is a family of pseudorandom functions (a.k.a. keyed + * hash functions) optimized for speed on short messages", designed by + * Jean-Philippe Aumasson and Daniel J. Bernstein. It generates a 64bit + * hash (or MAC) from the message and a 128bit key. + * See http://cr.yp.to/siphash/siphash-20120620.pdf for the details, + * c is the number of compression rounds, d the number of finalization + * rounds; we also define fast implementations for c = 2 with d = 4 (aka + * siphash-2-4), and c = 4 with d = 8 (aka siphash-4-8), as recommended + * parameters per the authors. + */ + +/** size of the siphash digest */ +#define APR_SIPHASH_DSIZE 8 + +/** size of the siphash key */ +#define APR_SIPHASH_KSIZE 16 + + +/** + * @brief Computes SipHash-c-d, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key. + * @param src The message + * @param len The length of the message + * @param key The secret key + * @param c The number of compression rounds + * @param d The number of finalization rounds + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(apr_uint64_t) apr_siphash(const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE], + unsigned int c, unsigned int d); + +/** + * @brief Computes SipHash-c-d, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key, into a possibly + * unaligned buffer (using the little endian representation as defined by the + * authors for interoperabilty) usable as a MAC. + * @param out The output buffer (or MAC) + * @param src The message + * @param len The length of the message + * @param key The secret key + * @param c The number of compression rounds + * @param d The number of finalization rounds + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(void) apr_siphash_auth(unsigned char out[APR_SIPHASH_DSIZE], + const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE], + unsigned int c, unsigned int d); + +/** + * @brief Computes SipHash-2-4, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key. + * @param src The message to hash + * @param len The length of the message + * @param key The secret key + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(apr_uint64_t) apr_siphash24(const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE]); + +/** + * @brief Computes SipHash-2-4, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key, into a possibly + * unaligned buffer (using the little endian representation as defined by the + * authors for interoperabilty) usable as a MAC. + * @param out The output buffer (or MAC) + * @param src The message + * @param len The length of the message + * @param key The secret key + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(void) apr_siphash24_auth(unsigned char out[APR_SIPHASH_DSIZE], + const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE]); + +/** + * @brief Computes SipHash-4-8, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key. + * @param src The message + * @param len The length of the message + * @param key The secret key + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(apr_uint64_t) apr_siphash48(const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE]); + +/** + * @brief Computes SipHash-4-8, producing a 64bit (APR_SIPHASH_DSIZE) hash + * from a message and a 128bit (APR_SIPHASH_KSIZE) secret key, into a possibly + * unaligned buffer (using the little endian representation as defined by the + * authors for interoperabilty) usable as a MAC. + * @param out The output buffer (or MAC) + * @param src The message + * @param len The length of the message + * @param key The secret key + * @return The hash value as a 64bit unsigned integer + */ +APU_DECLARE(void) apr_siphash48_auth(unsigned char out[APR_SIPHASH_DSIZE], + const void *src, apr_size_t len, + const unsigned char key[APR_SIPHASH_KSIZE]); + +#ifdef __cplusplus +} +#endif + +#endif /* APR_SIPHASH_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_skiplist.h b/c/dependencies/windows/apr/x86_debug/include/apr_skiplist.h new file mode 100644 index 00000000..eeab10bf --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_skiplist.h @@ -0,0 +1,381 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_SKIPLIST_H +#define APR_SKIPLIST_H +/** + * @file apr_skiplist.h + * @brief APR skip list implementation + */ + +#include "apr.h" +#include "apr_portable.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_skiplist Skip list implementation + * Refer to http://en.wikipedia.org/wiki/Skip_list for information + * about the purpose of and ideas behind skip lists. + * @ingroup APR + * @{ + */ + +/** + * apr_skiplist_compare is the function type that must be implemented + * per object type that is used in a skip list for comparisons to maintain + * order + * */ +typedef int (*apr_skiplist_compare) (void *, void *); + +/** + * apr_skiplist_freefunc is the function type that must be implemented + * to handle elements as they are removed from a skip list. + */ +typedef void (*apr_skiplist_freefunc) (void *); + +/** Opaque structure used to represent the skip list */ +struct apr_skiplist; +/** Opaque structure used to represent the skip list */ +typedef struct apr_skiplist apr_skiplist; + +/** + * Opaque structure used to represent abstract nodes in the skip list + * (an abstraction above the raw elements which are collected in the + * skip list). + */ +struct apr_skiplistnode; +/** Opaque structure */ +typedef struct apr_skiplistnode apr_skiplistnode; + +/** + * Allocate memory using the same mechanism as the skip list. + * @param sl The skip list + * @param size The amount to allocate + * @remark If a pool was provided to apr_skiplist_init(), memory will + * be allocated from the pool or from a free list maintained with + * the skip list. Otherwise, memory will be allocated using the + * C standard library heap functions. + */ +APR_DECLARE(void *) apr_skiplist_alloc(apr_skiplist *sl, size_t size); + +/** + * Free memory using the same mechanism as the skip list. + * @param sl The skip list + * @param mem The object to free + * @remark If a pool was provided to apr_skiplist_init(), memory will + * be added to a free list maintained with the skip list and be available + * to operations on the skip list or to other calls to apr_skiplist_alloc(). + * Otherwise, memory will be freed using the C standard library heap + * functions. + */ +APR_DECLARE(void) apr_skiplist_free(apr_skiplist *sl, void *mem); + +/** + * Allocate a new skip list + * @param sl The pointer in which to return the newly created skip list + * @param p The pool from which to allocate the skip list (optional). + * @remark Unlike most APR functions, a pool is optional. If no pool + * is provided, the C standard library heap functions will be used instead. + */ +APR_DECLARE(apr_status_t) apr_skiplist_init(apr_skiplist **sl, apr_pool_t *p); + +/** + * Set the comparison functions to be used for searching the skip list. + * @param sl The skip list + * @param XXX1 FIXME + * @param XXX2 FIXME + * + * @remark If existing comparison functions are being replaced, the index + * will be replaced during this call. That is a potentially expensive + * operation. + */ +APR_DECLARE(void) apr_skiplist_set_compare(apr_skiplist *sl, apr_skiplist_compare XXX1, + apr_skiplist_compare XXX2); + +/** + * Set the indexing functions to the specified comparison functions and + * rebuild the index. + * @param sl The skip list + * @param XXX1 FIXME + * @param XXX2 FIXME + * + * @remark If an index already exists, it will not be replaced and the + * comparison functions will not be changed. + */ +APR_DECLARE(void) apr_skiplist_add_index(apr_skiplist *sl, apr_skiplist_compare XXX1, + apr_skiplist_compare XXX2); + +/** + * Return the list maintained by the skip list abstraction. + * @param sl The skip list + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_getlist(apr_skiplist *sl); + +/** + * Return the next matching element in the skip list using the specified + * comparison function. + * @param sl The skip list + * @param data The value to search for + * @param iter A pointer to the returned skip list node representing the element + * found + * @param func The comparison function to use + */ +APR_DECLARE(void *) apr_skiplist_find_compare(apr_skiplist *sl, + void *data, + apr_skiplistnode **iter, + apr_skiplist_compare func); + +/** + * Return the next matching element in the skip list using the current comparison + * function. + * @param sl The skip list + * @param data The value to search for + * @param iter A pointer to the returned skip list node representing the element + * found + */ +APR_DECLARE(void *) apr_skiplist_find(apr_skiplist *sl, void *data, apr_skiplistnode **iter); + +/** + * Return the last matching element in the skip list using the specified + * comparison function. + * @param sl The skip list + * @param data The value to search for + * @param iter A pointer to the returned skip list node representing the element + * found + * @param comp The comparison function to use + */ +APR_DECLARE(void *) apr_skiplist_last_compare(apr_skiplist *sl, void *data, + apr_skiplistnode **iter, + apr_skiplist_compare comp); + +/** + * Return the last matching element in the skip list using the current comparison + * function. + * @param sl The skip list + * @param data The value to search for + * @param iter A pointer to the returned skip list node representing the element + * found + */ +APR_DECLARE(void *) apr_skiplist_last(apr_skiplist *sl, void *data, + apr_skiplistnode **iter); + +/** + * Return the next element in the skip list. + * @param sl The skip list + * @param iter On entry, a pointer to the skip list node to start with; on return, + * a pointer to the skip list node representing the element returned + * @remark If iter points to a NULL value on entry, NULL will be returned. + */ +APR_DECLARE(void *) apr_skiplist_next(apr_skiplist *sl, apr_skiplistnode **iter); + +/** + * Return the previous element in the skip list. + * @param sl The skip list + * @param iter On entry, a pointer to the skip list node to start with; on return, + * a pointer to the skip list node representing the element returned + * @remark If iter points to a NULL value on entry, NULL will be returned. + */ +APR_DECLARE(void *) apr_skiplist_previous(apr_skiplist *sl, apr_skiplistnode **iter); + +/** + * Return the element of the skip list node + * @param iter The skip list node + */ +APR_DECLARE(void *) apr_skiplist_element(apr_skiplistnode *iter); + +/** + * Insert an element into the skip list using the specified comparison function + * if it does not already exist. + * @param sl The skip list + * @param data The element to insert + * @param comp The comparison function to use for placement into the skip list + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_insert_compare(apr_skiplist *sl, + void *data, apr_skiplist_compare comp); + +/** + * Insert an element into the skip list using the existing comparison function + * if it does not already exist. + * @param sl The skip list + * @param data The element to insert + * @remark If no comparison function has been set for the skip list, the element + * will not be inserted and NULL will be returned. + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_insert(apr_skiplist* sl, void *data); + +/** + * Add an element into the skip list using the specified comparison function + * allowing for duplicates. + * @param sl The skip list + * @param data The element to add + * @param comp The comparison function to use for placement into the skip list + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_add_compare(apr_skiplist *sl, + void *data, apr_skiplist_compare comp); + +/** + * Add an element into the skip list using the existing comparison function + * allowing for duplicates. + * @param sl The skip list + * @param data The element to insert + * @remark If no comparison function has been set for the skip list, the element + * will not be inserted and NULL will be returned. + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_add(apr_skiplist* sl, void *data); + +/** + * Add an element into the skip list using the specified comparison function + * removing the existing duplicates. + * @param sl The skip list + * @param data The element to insert + * @param comp The comparison function to use for placement into the skip list + * @param myfree A function to be called for each removed duplicate + * @remark If no comparison function has been set for the skip list, the element + * will not be inserted, none will be replaced, and NULL will be returned. + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_replace_compare(apr_skiplist *sl, + void *data, apr_skiplist_freefunc myfree, + apr_skiplist_compare comp); + +/** + * Add an element into the skip list using the existing comparison function + * removing the existing duplicates. + * @param sl The skip list + * @param data The element to insert + * @param myfree A function to be called for each removed duplicate + * @remark If no comparison function has been set for the skip list, the element + * will not be inserted, none will be replaced, and NULL will be returned. + */ +APR_DECLARE(apr_skiplistnode *) apr_skiplist_replace(apr_skiplist *sl, + void *data, apr_skiplist_freefunc myfree); + +/** + * Remove a node from the skip list. + * @param sl The skip list + * @param iter The skip list node to remove + * @param myfree A function to be called for the removed element + */ +APR_DECLARE(int) apr_skiplist_remove_node(apr_skiplist *sl, + apr_skiplistnode *iter, + apr_skiplist_freefunc myfree); + +/** + * Remove an element from the skip list using the specified comparison function for + * locating the element. In the case of duplicates, the 1st entry will be removed. + * @param sl The skip list + * @param data The element to remove + * @param myfree A function to be called for each removed element + * @param comp The comparison function to use for placement into the skip list + * @remark If the element is not found, 0 will be returned. Otherwise, the heightXXX + * will be returned. + */ +APR_DECLARE(int) apr_skiplist_remove_compare(apr_skiplist *sl, void *data, + apr_skiplist_freefunc myfree, apr_skiplist_compare comp); + +/** + * Remove an element from the skip list using the existing comparison function for + * locating the element. In the case of duplicates, the 1st entry will be removed. + * @param sl The skip list + * @param data The element to remove + * @param myfree A function to be called for each removed element + * @remark If the element is not found, 0 will be returned. Otherwise, the heightXXX + * will be returned. + * @remark If no comparison function has been set for the skip list, the element + * will not be removed and 0 will be returned. + */ +APR_DECLARE(int) apr_skiplist_remove(apr_skiplist *sl, void *data, apr_skiplist_freefunc myfree); + +/** + * Remove all elements from the skip list. + * @param sl The skip list + * @param myfree A function to be called for each removed element + */ +APR_DECLARE(void) apr_skiplist_remove_all(apr_skiplist *sl, apr_skiplist_freefunc myfree); + +/** + * Remove each element from the skip list. + * @param sl The skip list + * @param myfree A function to be called for each removed element + */ +APR_DECLARE(void) apr_skiplist_destroy(apr_skiplist *sl, apr_skiplist_freefunc myfree); + +/** + * Return the first element in the skip list, removing the element from the skip list. + * @param sl The skip list + * @param myfree A function to be called for the removed element + * @remark NULL will be returned if there are no elements + */ +APR_DECLARE(void *) apr_skiplist_pop(apr_skiplist *sl, apr_skiplist_freefunc myfree); + +/** + * Return the first element in the skip list, leaving the element in the skip list. + * @param sl The skip list + * @remark NULL will be returned if there are no elements + */ +APR_DECLARE(void *) apr_skiplist_peek(apr_skiplist *sl); + +/** + * Return the size of the list (number of elements), in O(1). + * @param sl The skip list + */ +APR_DECLARE(size_t) apr_skiplist_size(const apr_skiplist *sl); + +/** + * Return the height of the list (number of skip paths), in O(1). + * @param sl The skip list + */ +APR_DECLARE(int) apr_skiplist_height(const apr_skiplist *sl); + +/** + * Return the predefined maximum height of the skip list. + * @param sl The skip list + */ +APR_DECLARE(int) apr_skiplist_preheight(const apr_skiplist *sl); + +/** + * Set a predefined maximum height for the skip list. + * @param sl The skip list + * @param to The preheight to set, or a nul/negative value to disable. + * @remark When a preheight is used, the height of each inserted element is + * computed randomly up to this preheight instead of the current skip list's + * height plus one used by the default implementation. Using a preheight can + * probably ensure more fairness with long living elements (since with an + * adaptative height, former elements may have been created with a low height, + * hence a longest path to reach them while the skip list grows). On the other + * hand, the default behaviour (preheight <= 0) with a growing and decreasing + * maximum height is more adaptative/suitable for short living values. + * @note Should be called before any insertion/add. + */ +APR_DECLARE(void) apr_skiplist_set_preheight(apr_skiplist *sl, int to); + +/** + * Merge two skip lists. XXX SEMANTICS + * @param sl1 One of two skip lists to be merged + * @param sl2 The other of two skip lists to be merged + */ +APR_DECLARE(apr_skiplist *) apr_skiplist_merge(apr_skiplist *sl1, apr_skiplist *sl2); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_SKIPLIST_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_strings.h b/c/dependencies/windows/apr/x86_debug/include/apr_strings.h new file mode 100644 index 00000000..d5f8719d --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_strings.h @@ -0,0 +1,380 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* Portions of this file are covered by */ +/* -*- mode: c; c-file-style: "k&r" -*- + + strnatcmp.c -- Perform 'natural order' comparisons of strings in C. + Copyright (C) 2000 by Martin Pool + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef APR_STRINGS_H +#define APR_STRINGS_H + +/** + * @file apr_strings.h + * @brief APR Strings library + */ + +#include "apr.h" +#include "apr_errno.h" +#include "apr_pools.h" +#define APR_WANT_IOVEC +#include "apr_want.h" + +#if APR_HAVE_STDARG_H +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_strings String routines + * @ingroup APR + * @{ + */ + +/** + * Do a natural order comparison of two strings. + * @param a The first string to compare + * @param b The second string to compare + * @return Either <0, 0, or >0. If the first string is less than the second + * this returns <0, if they are equivalent it returns 0, and if the + * first string is greater than second string it retuns >0. + */ +APR_DECLARE(int) apr_strnatcmp(char const *a, char const *b); + +/** + * Do a natural order comparison of two strings ignoring the case of the + * strings. + * @param a The first string to compare + * @param b The second string to compare + * @return Either <0, 0, or >0. If the first string is less than the second + * this returns <0, if they are equivalent it returns 0, and if the + * first string is greater than second string it retuns >0. + */ +APR_DECLARE(int) apr_strnatcasecmp(char const *a, char const *b); + +/** + * duplicate a string into memory allocated out of a pool + * @param p The pool to allocate out of + * @param s The string to duplicate + * @return The new string or NULL if s == NULL + */ +APR_DECLARE(char *) apr_pstrdup(apr_pool_t *p, const char *s); + +/** + * Create a null-terminated string by making a copy of a sequence + * of characters and appending a null byte + * @param p The pool to allocate out of + * @param s The block of characters to duplicate + * @param n The number of characters to duplicate + * @return The new string or NULL if s == NULL + * @remark This is a faster alternative to apr_pstrndup(), for use + * when you know that the string being duplicated really + * has 'n' or more characters. If the string might contain + * fewer characters, use apr_pstrndup(). + */ +APR_DECLARE(char *) apr_pstrmemdup(apr_pool_t *p, const char *s, apr_size_t n) +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) + __attribute__((alloc_size(3))) +#endif + ; + +/** + * Duplicate at most n characters of a string into memory allocated + * out of a pool; the new string will be NUL-terminated + * @param p The pool to allocate out of + * @param s The string to duplicate + * @param n The maximum number of characters to duplicate + * @return The new string or NULL if s == NULL + * @remark The amount of memory allocated from the pool is the length + * of the returned string including the NUL terminator + */ +APR_DECLARE(char *) apr_pstrndup(apr_pool_t *p, const char *s, apr_size_t n); + +/** + * Duplicate a block of memory. + * + * @param p The pool to allocate from + * @param m The memory to duplicate + * @param n The number of bytes to duplicate + * @return The new block of memory or NULL if m == NULL + */ +APR_DECLARE(void *) apr_pmemdup(apr_pool_t *p, const void *m, apr_size_t n) +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) + __attribute__((alloc_size(3))) +#endif + ; + +/** + * Concatenate multiple strings, allocating memory out a pool + * @param p The pool to allocate out of + * @param ... The strings to concatenate. The final string must be NULL + * @return The new string + */ +APR_DECLARE_NONSTD(char *) apr_pstrcat(apr_pool_t *p, ...) +#if defined(__GNUC__) && __GNUC__ >= 4 + __attribute__((sentinel)) +#endif + ; + +/** + * Concatenate multiple strings specified in a writev-style vector + * @param p The pool from which to allocate + * @param vec The strings to concatenate + * @param nvec The number of strings to concatenate + * @param nbytes (output) strlen of new string (pass in NULL to omit) + * @return The new string + */ +APR_DECLARE(char *) apr_pstrcatv(apr_pool_t *p, const struct iovec *vec, + apr_size_t nvec, apr_size_t *nbytes); + +/** + * printf-style style printing routine. The data is output to a string + * allocated from a pool + * @param p The pool to allocate out of + * @param fmt The format of the string + * @param ap The arguments to use while printing the data + * @return The new string + */ +APR_DECLARE(char *) apr_pvsprintf(apr_pool_t *p, const char *fmt, va_list ap); + +/** + * printf-style style printing routine. The data is output to a string + * allocated from a pool + * @param p The pool to allocate out of + * @param fmt The format of the string + * @param ... The arguments to use while printing the data + * @return The new string + */ +APR_DECLARE_NONSTD(char *) apr_psprintf(apr_pool_t *p, const char *fmt, ...) + __attribute__((format(printf,2,3))); + +/** + * Copy up to dst_size characters from src to dst; does not copy + * past a NUL terminator in src, but always terminates dst with a NUL + * regardless. + * @param dst The destination string + * @param src The source string + * @param dst_size The space available in dst; dst always receives + * NUL termination, so if src is longer than + * dst_size, the actual number of characters copied is + * dst_size - 1. + * @return Pointer to the NUL terminator of the destination string, dst + * @remark + *
+ * Note the differences between this function and strncpy():
+ *  1) strncpy() doesn't always NUL terminate; apr_cpystrn() does.
+ *  2) strncpy() pads the destination string with NULs, which is often 
+ *     unnecessary; apr_cpystrn() does not.
+ *  3) strncpy() returns a pointer to the beginning of the dst string;
+ *     apr_cpystrn() returns a pointer to the NUL terminator of dst, 
+ *     to allow a check for truncation.
+ * 
+ */ +APR_DECLARE(char *) apr_cpystrn(char *dst, const char *src, + apr_size_t dst_size); + +/** + * Remove all whitespace from a string + * @param dest The destination string. It is okay to modify the string + * in place. Namely dest == src + * @param src The string to rid the spaces from. + * @return A pointer to the destination string's null terminator. + */ +APR_DECLARE(char *) apr_collapse_spaces(char *dest, const char *src); + +/** + * Convert the arguments to a program from one string to an array of + * strings terminated by a NULL pointer + * @param arg_str The arguments to convert + * @param argv_out Output location. This is a pointer to an array of strings. + * @param token_context Pool to use. + */ +APR_DECLARE(apr_status_t) apr_tokenize_to_argv(const char *arg_str, + char ***argv_out, + apr_pool_t *token_context); + +/** + * Split a string into separate null-terminated tokens. The tokens are + * delimited in the string by one or more characters from the sep + * argument. + * @param str The string to separate; this should be specified on the + * first call to apr_strtok() for a given string, and NULL + * on subsequent calls. + * @param sep The set of delimiters + * @param last State saved by apr_strtok() between calls. + * @return The next token from the string + * @note the 'last' state points to the trailing NUL char of the final + * token, otherwise it points to the character following the current + * token (all successive or empty occurances of sep are skiped on the + * subsequent call to apr_strtok). Therefore it is possible to avoid + * a strlen() determination, with the following logic; + * toklen = last - retval; if (*last) --toklen; + */ +APR_DECLARE(char *) apr_strtok(char *str, const char *sep, char **last); + +/** + * @defgroup APR_Strings_Snprintf snprintf implementations + * @warning + * These are snprintf implementations based on apr_vformatter(). + * + * Note that various standards and implementations disagree on the return + * value of snprintf, and side-effects due to %n in the formatting string. + * apr_snprintf (and apr_vsnprintf) behaves as follows: + * + * Process the format string until the entire string is exhausted, or + * the buffer fills. If the buffer fills then stop processing immediately + * (so no further %n arguments are processed), and return the buffer + * length. In all cases the buffer is NUL terminated. It will return the + * number of characters inserted into the buffer, not including the + * terminating NUL. As a special case, if len is 0, apr_snprintf will + * return the number of characters that would have been inserted if + * the buffer had been infinite (in this case, *buffer can be NULL) + * + * In no event does apr_snprintf return a negative number. + * @{ + */ + +/** + * snprintf routine based on apr_vformatter. This means it understands the + * same extensions. + * @param buf The buffer to write to + * @param len The size of the buffer + * @param format The format string + * @param ... The arguments to use to fill out the format string. + */ +APR_DECLARE_NONSTD(int) apr_snprintf(char *buf, apr_size_t len, + const char *format, ...) + __attribute__((format(printf,3,4))); + +/** + * vsnprintf routine based on apr_vformatter. This means it understands the + * same extensions. + * @param buf The buffer to write to + * @param len The size of the buffer + * @param format The format string + * @param ap The arguments to use to fill out the format string. + */ +APR_DECLARE(int) apr_vsnprintf(char *buf, apr_size_t len, const char *format, + va_list ap); +/** @} */ + +/** + * create a string representation of an int, allocated from a pool + * @param p The pool from which to allocate + * @param n The number to format + * @return The string representation of the number + */ +APR_DECLARE(char *) apr_itoa(apr_pool_t *p, int n); + +/** + * create a string representation of a long, allocated from a pool + * @param p The pool from which to allocate + * @param n The number to format + * @return The string representation of the number + */ +APR_DECLARE(char *) apr_ltoa(apr_pool_t *p, long n); + +/** + * create a string representation of an apr_off_t, allocated from a pool + * @param p The pool from which to allocate + * @param n The number to format + * @return The string representation of the number + */ +APR_DECLARE(char *) apr_off_t_toa(apr_pool_t *p, apr_off_t n); + +/** + * Convert a numeric string into an apr_off_t numeric value. + * @param offset The value of the parsed string. + * @param buf The string to parse. It may contain optional whitespace, + * followed by an optional '+' (positive, default) or '-' (negative) + * character, followed by an optional '0x' prefix if base is 0 or 16, + * followed by numeric digits appropriate for base. + * @param end A pointer to the end of the valid character in buf. If + * not NULL, it is set to the first invalid character in buf. + * @param base A numeric base in the range between 2 and 36 inclusive, + * or 0. If base is zero, buf will be treated as base ten unless its + * digits are prefixed with '0x', in which case it will be treated as + * base 16. + * @bug *end breaks type safety; where *buf is const, *end needs to be + * declared as const in APR 2.0 + */ +APR_DECLARE(apr_status_t) apr_strtoff(apr_off_t *offset, const char *buf, + char **end, int base); + +/** + * parse a numeric string into a 64-bit numeric value + * @param buf The string to parse. It may contain optional whitespace, + * followed by an optional '+' (positive, default) or '-' (negative) + * character, followed by an optional '0x' prefix if base is 0 or 16, + * followed by numeric digits appropriate for base. + * @param end A pointer to the end of the valid character in buf. If + * not NULL, it is set to the first invalid character in buf. + * @param base A numeric base in the range between 2 and 36 inclusive, + * or 0. If base is zero, buf will be treated as base ten unless its + * digits are prefixed with '0x', in which case it will be treated as + * base 16. + * @return The numeric value of the string. On overflow, errno is set + * to ERANGE. On success, errno is set to 0. + */ +APR_DECLARE(apr_int64_t) apr_strtoi64(const char *buf, char **end, int base); + +/** + * parse a base-10 numeric string into a 64-bit numeric value. + * Equivalent to apr_strtoi64(buf, (char**)NULL, 10). + * @param buf The string to parse + * @return The numeric value of the string. On overflow, errno is set + * to ERANGE. On success, errno is set to 0. + */ +APR_DECLARE(apr_int64_t) apr_atoi64(const char *buf); + +/** + * Format a binary size (magnitiudes are 2^10 rather than 10^3) from an apr_off_t, + * as bytes, K, M, T, etc, to a four character compacted human readable string. + * @param size The size to format + * @param buf The 5 byte text buffer (counting the trailing null) + * @return The buf passed to apr_strfsize() + * @remark All negative sizes report ' - ', apr_strfsize only formats positive values. + */ +APR_DECLARE(char *) apr_strfsize(apr_off_t size, char *buf); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* !APR_STRINGS_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_strmatch.h b/c/dependencies/windows/apr/x86_debug/include/apr_strmatch.h new file mode 100644 index 00000000..53fadad5 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_strmatch.h @@ -0,0 +1,81 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_STRMATCH_H +#define APR_STRMATCH_H +/** + * @file apr_strmatch.h + * @brief APR-UTIL string matching routines + */ + +#include "apu.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_StrMatch String matching routines + * @ingroup APR_Util + * @{ + */ + +/** @see apr_strmatch_pattern */ +typedef struct apr_strmatch_pattern apr_strmatch_pattern; + +/** + * Precompiled search pattern + */ +struct apr_strmatch_pattern { + /** Function called to compare */ + const char *(*compare)(const apr_strmatch_pattern *this_pattern, + const char *s, apr_size_t slen); + const char *pattern; /**< Current pattern */ + apr_size_t length; /**< Current length */ + void *context; /**< hook to add precomputed metadata */ +}; + +#if defined(DOXYGEN) +/** + * Search for a precompiled pattern within a string + * @param pattern The pattern + * @param s The string in which to search for the pattern + * @param slen The length of s (excluding null terminator) + * @return A pointer to the first instance of the pattern in s, or + * NULL if not found + */ +APU_DECLARE(const char *) apr_strmatch(const apr_strmatch_pattern *pattern, + const char *s, apr_size_t slen); +#else +#define apr_strmatch(pattern, s, slen) (*((pattern)->compare))((pattern), (s), (slen)) +#endif + +/** + * Precompile a pattern for matching using the Boyer-Moore-Horspool algorithm + * @param p The pool from which to allocate the pattern + * @param s The pattern string + * @param case_sensitive Whether the matching should be case-sensitive + * @return a pointer to the compiled pattern, or NULL if compilation fails + */ +APU_DECLARE(const apr_strmatch_pattern *) apr_strmatch_precompile(apr_pool_t *p, const char *s, int case_sensitive); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_STRMATCH_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_support.h b/c/dependencies/windows/apr/x86_debug/include/apr_support.h new file mode 100644 index 00000000..79c8cb47 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_support.h @@ -0,0 +1,57 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_SUPPORT_H +#define APR_SUPPORT_H + +/** + * @file apr_support.h + * @brief APR Support functions + */ + +#include "apr.h" +#include "apr_network_io.h" +#include "apr_file_io.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_support Internal APR support functions + * @ingroup APR + * @{ + */ + +/** + * Wait for IO to occur or timeout. + * + * @param f The file to wait on. + * @param s The socket to wait on if @a f is @c NULL. + * @param for_read If non-zero wait for data to be available to read, + * otherwise wait for data to be able to be written. + * @return APR_TIMEUP if we run out of time. + */ +apr_status_t apr_wait_for_io_or_timeout(apr_file_t *f, apr_socket_t *s, + int for_read); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_SUPPORT_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_tables.h b/c/dependencies/windows/apr/x86_debug/include/apr_tables.h new file mode 100644 index 00000000..27974c0e --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_tables.h @@ -0,0 +1,507 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_TABLES_H +#define APR_TABLES_H + +/** + * @file apr_tables.h + * @brief APR Table library + */ + +#include "apr.h" +#include "apr_pools.h" + +#if APR_HAVE_STDARG_H +#include /* for va_list */ +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_tables Table and Array Functions + * @ingroup APR + * Arrays are used to store data which is referenced sequentially or + * as a stack. Functions are provided to push and pop individual + * elements as well as to operate on the entire array. + * + * Tables are used to store data which can be referenced by key. + * Limited capabilities are provided for tables with multiple elements + * which share a key; while key lookup will return only a single + * element, iteration is available. Additionally, a table can be + * compressed to resolve duplicates. + * + * Both arrays and tables may store string or binary data; some features, + * such as concatenation or merging of elements, work only for string + * data. + * @{ + */ + +/** the table abstract data type */ +typedef struct apr_table_t apr_table_t; + +/** @see apr_array_header_t */ +typedef struct apr_array_header_t apr_array_header_t; + +/** An opaque array type */ +struct apr_array_header_t { + /** The pool the array is allocated out of */ + apr_pool_t *pool; + /** The amount of memory allocated for each element of the array */ + int elt_size; + /** The number of active elements in the array */ + int nelts; + /** The number of elements allocated in the array */ + int nalloc; + /** The elements in the array */ + char *elts; +}; + +/** + * The (opaque) structure for string-content tables. + */ +typedef struct apr_table_entry_t apr_table_entry_t; + +/** The type for each entry in a string-content table */ +struct apr_table_entry_t { + /** The key for the current table entry */ + char *key; /* maybe NULL in future; + * check when iterating thru table_elts + */ + /** The value for the current table entry */ + char *val; + + /** A checksum for the key, for use by the apr_table internals */ + apr_uint32_t key_checksum; +}; + +/** + * Get the elements from a table. + * @param t The table + * @return An array containing the contents of the table + */ +APR_DECLARE(const apr_array_header_t *) apr_table_elts(const apr_table_t *t); + +/** + * Determine if the table is empty (either NULL or having no elements). + * @param t The table to check + * @return True if empty, False otherwise + */ +APR_DECLARE(int) apr_is_empty_table(const apr_table_t *t); + +/** + * Determine if the array is empty (either NULL or having no elements). + * @param a The array to check + * @return True if empty, False otherwise + */ +APR_DECLARE(int) apr_is_empty_array(const apr_array_header_t *a); + +/** + * Create an array. + * @param p The pool to allocate the memory out of + * @param nelts the number of elements in the initial array + * @param elt_size The size of each element in the array. + * @return The new array + */ +APR_DECLARE(apr_array_header_t *) apr_array_make(apr_pool_t *p, + int nelts, int elt_size); + +/** + * Add a new element to an array (as a first-in, last-out stack). + * @param arr The array to add an element to. + * @return Location for the new element in the array. + * @remark If there are no free spots in the array, then this function will + * allocate new space for the new element. + */ +APR_DECLARE(void *) apr_array_push(apr_array_header_t *arr); + +/** A helper macro for accessing a member of an APR array. + * + * @param ary the array + * @param i the index into the array to return + * @param type the type of the objects stored in the array + * + * @return the item at index i + */ +#define APR_ARRAY_IDX(ary,i,type) (((type *)(ary)->elts)[i]) + +/** A helper macro for pushing elements into an APR array. + * + * @param ary the array + * @param type the type of the objects stored in the array + * + * @return the location where the new object should be placed + */ +#define APR_ARRAY_PUSH(ary,type) (*((type *)apr_array_push(ary))) + +/** + * Remove an element from an array (as a first-in, last-out stack). + * @param arr The array to remove an element from. + * @return Location of the element in the array. + * @remark If there are no elements in the array, NULL is returned. + */ +APR_DECLARE(void *) apr_array_pop(apr_array_header_t *arr); + +/** + * Remove all elements from an array. + * @param arr The array to remove all elements from. + * @remark As the underlying storage is allocated from a pool, no + * memory is freed by this operation, but is available for reuse. + */ +APR_DECLARE(void) apr_array_clear(apr_array_header_t *arr); + +/** + * Concatenate two arrays together. + * @param dst The destination array, and the one to go first in the combined + * array + * @param src The source array to add to the destination array + */ +APR_DECLARE(void) apr_array_cat(apr_array_header_t *dst, + const apr_array_header_t *src); + +/** + * Copy the entire array. + * @param p The pool to allocate the copy of the array out of + * @param arr The array to copy + * @return An exact copy of the array passed in + * @remark The alternate apr_array_copy_hdr() copies only the header, and arranges + * for the elements to be copied if (and only if) the code subsequently + * does a push or arraycat. + */ +APR_DECLARE(apr_array_header_t *) apr_array_copy(apr_pool_t *p, + const apr_array_header_t *arr); +/** + * Copy the headers of the array, and arrange for the elements to be copied if + * and only if the code subsequently does a push or arraycat. + * @param p The pool to allocate the copy of the array out of + * @param arr The array to copy + * @return An exact copy of the array passed in + * @remark The alternate apr_array_copy() copies the *entire* array. + */ +APR_DECLARE(apr_array_header_t *) apr_array_copy_hdr(apr_pool_t *p, + const apr_array_header_t *arr); + +/** + * Append one array to the end of another, creating a new array in the process. + * @param p The pool to allocate the new array out of + * @param first The array to put first in the new array. + * @param second The array to put second in the new array. + * @return A new array containing the data from the two arrays passed in. +*/ +APR_DECLARE(apr_array_header_t *) apr_array_append(apr_pool_t *p, + const apr_array_header_t *first, + const apr_array_header_t *second); + +/** + * Generate a new string from the apr_pool_t containing the concatenated + * sequence of substrings referenced as elements within the array. The string + * will be empty if all substrings are empty or null, or if there are no + * elements in the array. If sep is non-NUL, it will be inserted between + * elements as a separator. + * @param p The pool to allocate the string out of + * @param arr The array to generate the string from + * @param sep The separator to use + * @return A string containing all of the data in the array. + */ +APR_DECLARE(char *) apr_array_pstrcat(apr_pool_t *p, + const apr_array_header_t *arr, + const char sep); + +/** + * Make a new table. + * @param p The pool to allocate the pool out of + * @param nelts The number of elements in the initial table. + * @return The new table. + * @warning This table can only store text data + */ +APR_DECLARE(apr_table_t *) apr_table_make(apr_pool_t *p, int nelts); + +/** + * Create a new table and copy another table into it. + * @param p The pool to allocate the new table out of + * @param t The table to copy + * @return A copy of the table passed in + * @warning The table keys and respective values are not copied + */ +APR_DECLARE(apr_table_t *) apr_table_copy(apr_pool_t *p, + const apr_table_t *t); + +/** + * Create a new table whose contents are deep copied from the given + * table. A deep copy operation copies all fields, and makes copies + * of dynamically allocated memory pointed to by the fields. + * @param p The pool to allocate the new table out of + * @param t The table to clone + * @return A deep copy of the table passed in + */ +APR_DECLARE(apr_table_t *) apr_table_clone(apr_pool_t *p, + const apr_table_t *t); + +/** + * Delete all of the elements from a table. + * @param t The table to clear + */ +APR_DECLARE(void) apr_table_clear(apr_table_t *t); + +/** + * Get the value associated with a given key from the table. After this call, + * the data is still in the table. + * @param t The table to search for the key + * @param key The key to search for (case does not matter) + * @return The value associated with the key, or NULL if the key does not exist. + */ +APR_DECLARE(const char *) apr_table_get(const apr_table_t *t, const char *key); + +/** + * Get values associated with a given key from the table. If more than one + * value exists, return a comma separated list of values. After this call, the + * data is still in the table. + * @param p The pool to allocate the combined value from, if necessary + * @param t The table to search for the key + * @param key The key to search for (case does not matter) + * @return The value associated with the key, or NULL if the key does not exist. + */ +APR_DECLARE(const char *) apr_table_getm(apr_pool_t *p, const apr_table_t *t, + const char *key); + +/** + * Add a key/value pair to a table. If another element already exists with the + * same key, this will overwrite the old data. + * @param t The table to add the data to. + * @param key The key to use (case does not matter) + * @param val The value to add + * @remark When adding data, this function makes a copy of both the key and the + * value. + */ +APR_DECLARE(void) apr_table_set(apr_table_t *t, const char *key, + const char *val); + +/** + * Add a key/value pair to a table. If another element already exists with the + * same key, this will overwrite the old data. + * @param t The table to add the data to. + * @param key The key to use (case does not matter) + * @param val The value to add + * @warning When adding data, this function does not make a copy of the key or + * the value, so care should be taken to ensure that the values will + * not change after they have been added.. + */ +APR_DECLARE(void) apr_table_setn(apr_table_t *t, const char *key, + const char *val); + +/** + * Remove data from the table. + * @param t The table to remove data from + * @param key The key of the data being removed (case does not matter) + */ +APR_DECLARE(void) apr_table_unset(apr_table_t *t, const char *key); + +/** + * Add data to a table by merging the value with data that has already been + * stored. The merging is done by concatenating the two values, separated + * by the string ", ". + * @param t The table to search for the data + * @param key The key to merge data for (case does not matter) + * @param val The data to add + * @remark If the key is not found, then this function acts like apr_table_add() + */ +APR_DECLARE(void) apr_table_merge(apr_table_t *t, const char *key, + const char *val); + +/** + * Add data to a table by merging the value with data that has already been + * stored. The merging is done by concatenating the two values, separated + * by the string ", ". + * @param t The table to search for the data + * @param key The key to merge data for (case does not matter) + * @param val The data to add + * @remark If the key is not found, then this function acts like apr_table_addn() + */ +APR_DECLARE(void) apr_table_mergen(apr_table_t *t, const char *key, + const char *val); + +/** + * Add data to a table, regardless of whether there is another element with the + * same key. + * @param t The table to add to + * @param key The key to use + * @param val The value to add. + * @remark When adding data, this function makes a copy of both the key and the + * value. + */ +APR_DECLARE(void) apr_table_add(apr_table_t *t, const char *key, + const char *val); + +/** + * Add data to a table, regardless of whether there is another element with the + * same key. + * @param t The table to add to + * @param key The key to use + * @param val The value to add. + * @remark When adding data, this function does not make a copy of the key or the + * value, so care should be taken to ensure that the values will not + * change after they have been added. + */ +APR_DECLARE(void) apr_table_addn(apr_table_t *t, const char *key, + const char *val); + +/** + * Merge two tables into one new table. + * @param p The pool to use for the new table + * @param overlay The first table to put in the new table + * @param base The table to add at the end of the new table + * @return A new table containing all of the data from the two passed in + */ +APR_DECLARE(apr_table_t *) apr_table_overlay(apr_pool_t *p, + const apr_table_t *overlay, + const apr_table_t *base); + +/** + * Declaration prototype for the iterator callback function of apr_table_do() + * and apr_table_vdo(). + * @param rec The data passed as the first argument to apr_table_[v]do() + * @param key The key from this iteration of the table + * @param value The value from this iteration of the table + * @remark Iteration continues while this callback function returns non-zero. + * To export the callback function for apr_table_[v]do() it must be declared + * in the _NONSTD convention. + * @see apr_table_do @see apr_table_vdo + */ +typedef int (apr_table_do_callback_fn_t)(void *rec, const char *key, + const char *value); + +/** + * Iterate over a table running the provided function once for every + * element in the table. The varargs array must be a list of zero or + * more (char *) keys followed by a NULL pointer. If zero keys are + * given, the @param comp function will be invoked for every element + * in the table. Otherwise, the function is invoked only for those + * elements matching the keys specified. + * + * If an invocation of the comp function returns zero, + * iteration will continue using the next specified key, if any. + * + * @param comp The function to run + * @param rec The data to pass as the first argument to the function + * @param t The table to iterate over + * @param ... A varargs array of zero or more (char *) keys followed by NULL + * @return FALSE if one of the comp() iterations returned zero; TRUE if all + * iterations returned non-zero + * @see apr_table_do_callback_fn_t @see apr_table_vdo + */ +APR_DECLARE_NONSTD(int) apr_table_do(apr_table_do_callback_fn_t *comp, + void *rec, const apr_table_t *t, ...) +#if defined(__GNUC__) && __GNUC__ >= 4 + __attribute__((sentinel)) +#endif + ; + +/** + * Iterate over a table running the provided function once for every + * element in the table. The vp varargs parameter must be a + * list of zero or more (char *) keys followed by a NULL pointer. If + * zero keys are given, the @param comp function will be invoked for + * every element in the table. Otherwise, the function is invoked + * only for those elements matching the keys specified. + * + * If an invocation of the comp function returns zero, + * iteration will continue using the next specified key, if any. + * + * @param comp The function to run + * @param rec The data to pass as the first argument to the function + * @param t The table to iterate over + * @param vp List of zero or more (char *) keys followed by NULL + * @return FALSE if one of the comp() iterations returned zero; TRUE if all + * iterations returned non-zero + * @see apr_table_do_callback_fn_t @see apr_table_do + */ +APR_DECLARE(int) apr_table_vdo(apr_table_do_callback_fn_t *comp, + void *rec, const apr_table_t *t, va_list vp); + +/** flag for overlap to use apr_table_setn */ +#define APR_OVERLAP_TABLES_SET (0) +/** flag for overlap to use apr_table_mergen */ +#define APR_OVERLAP_TABLES_MERGE (1) +/** flag for overlap to use apr_table_addn */ +#define APR_OVERLAP_TABLES_ADD (2) +/** + * For each element in table b, either use setn or mergen to add the data + * to table a. Which method is used is determined by the flags passed in. + * @param a The table to add the data to. + * @param b The table to iterate over, adding its data to table a + * @param flags How to add the table to table a. One of: + * APR_OVERLAP_TABLES_SET Use apr_table_setn + * APR_OVERLAP_TABLES_MERGE Use apr_table_mergen + * APR_OVERLAP_TABLES_ADD Use apr_table_addn + * @remark When merging duplicates, the two values are concatenated, + * separated by the string ", ". + * @remark This function is highly optimized, and uses less memory and CPU cycles + * than a function that just loops through table b calling other functions. + */ +/** + * Conceptually, apr_table_overlap does this: + * + *
+ *  apr_array_header_t *barr = apr_table_elts(b);
+ *  apr_table_entry_t *belt = (apr_table_entry_t *)barr->elts;
+ *  int i;
+ *
+ *  for (i = 0; i < barr->nelts; ++i) {
+ *      if (flags & APR_OVERLAP_TABLES_MERGE) {
+ *          apr_table_mergen(a, belt[i].key, belt[i].val);
+ *      }
+ *      else if (flags & APR_OVERLAP_TABLES_ADD) {
+ *          apr_table_addn(a, belt[i].key, belt[i].val);
+ *      }
+ *      else {
+ *          apr_table_setn(a, belt[i].key, belt[i].val);
+ *      }
+ *  }
+ * 
+ * + * Except that it is more efficient (less space and cpu-time) especially + * when b has many elements. + * + * Notice the assumptions on the keys and values in b -- they must be + * in an ancestor of a's pool. In practice b and a are usually from + * the same pool. + */ + +APR_DECLARE(void) apr_table_overlap(apr_table_t *a, const apr_table_t *b, + unsigned flags); + +/** + * Eliminate redundant entries in a table by either overwriting + * or merging duplicates. + * + * @param t Table. + * @param flags APR_OVERLAP_TABLES_MERGE to merge, or + * APR_OVERLAP_TABLES_SET to overwrite, or + * APR_OVERLAP_TABLES_ADD to add + * @remark When merging duplicates, the two values are concatenated, + * separated by the string ", ". + */ +APR_DECLARE(void) apr_table_compress(apr_table_t *t, unsigned flags); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_TABLES_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_thread_cond.h b/c/dependencies/windows/apr/x86_debug/include/apr_thread_cond.h new file mode 100644 index 00000000..199f1ded --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_thread_cond.h @@ -0,0 +1,139 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_THREAD_COND_H +#define APR_THREAD_COND_H + +/** + * @file apr_thread_cond.h + * @brief APR Condition Variable Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_time.h" +#include "apr_thread_mutex.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#if APR_HAS_THREADS || defined(DOXYGEN) + +/** + * @defgroup apr_thread_cond Condition Variable Routines + * @ingroup APR + * @{ + */ + +/** Opaque structure for thread condition variables */ +typedef struct apr_thread_cond_t apr_thread_cond_t; + +/** + * Note: destroying a condition variable (or likewise, destroying or + * clearing the pool from which a condition variable was allocated) if + * any threads are blocked waiting on it gives undefined results. + */ + +/** + * Create and initialize a condition variable that can be used to signal + * and schedule threads in a single process. + * @param cond the memory address where the newly created condition variable + * will be stored. + * @param pool the pool from which to allocate the condition. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_create(apr_thread_cond_t **cond, + apr_pool_t *pool); + +/** + * Put the active calling thread to sleep until signaled to wake up. Each + * condition variable must be associated with a mutex, and that mutex must + * be locked before calling this function, or the behavior will be + * undefined. As the calling thread is put to sleep, the given mutex + * will be simultaneously released; and as this thread wakes up the lock + * is again simultaneously acquired. + * @param cond the condition variable on which to block. + * @param mutex the mutex that must be locked upon entering this function, + * is released while the thread is asleep, and is again acquired before + * returning from this function. + * @remark Spurious wakeups may occur. Before and after every call to wait on + * a condition variable, the caller should test whether the condition is already + * met. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_wait(apr_thread_cond_t *cond, + apr_thread_mutex_t *mutex); + +/** + * Put the active calling thread to sleep until signaled to wake up or + * the timeout is reached. Each condition variable must be associated + * with a mutex, and that mutex must be locked before calling this + * function, or the behavior will be undefined. As the calling thread + * is put to sleep, the given mutex will be simultaneously released; + * and as this thread wakes up the lock is again simultaneously acquired. + * @param cond the condition variable on which to block. + * @param mutex the mutex that must be locked upon entering this function, + * is released while the thread is asleep, and is again acquired before + * returning from this function. + * @param timeout The amount of time in microseconds to wait. This is + * a maximum, not a minimum. If the condition is signaled, we + * will wake up before this time, otherwise the error APR_TIMEUP + * is returned. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_timedwait(apr_thread_cond_t *cond, + apr_thread_mutex_t *mutex, + apr_interval_time_t timeout); + +/** + * Signals a single thread, if one exists, that is blocking on the given + * condition variable. That thread is then scheduled to wake up and acquire + * the associated mutex. Although it is not required, if predictable scheduling + * is desired, that mutex must be locked while calling this function. + * @param cond the condition variable on which to produce the signal. + * @remark If no threads are waiting on the condition variable, nothing happens. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_signal(apr_thread_cond_t *cond); + +/** + * Signals all threads blocking on the given condition variable. + * Each thread that was signaled is then scheduled to wake up and acquire + * the associated mutex. This will happen in a serialized manner. + * @param cond the condition variable on which to produce the broadcast. + * @remark If no threads are waiting on the condition variable, nothing happens. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_broadcast(apr_thread_cond_t *cond); + +/** + * Destroy the condition variable and free the associated memory. + * @param cond the condition variable to destroy. + */ +APR_DECLARE(apr_status_t) apr_thread_cond_destroy(apr_thread_cond_t *cond); + +/** + * Get the pool used by this thread_cond. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(thread_cond); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_THREAD_COND_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_thread_mutex.h b/c/dependencies/windows/apr/x86_debug/include/apr_thread_mutex.h new file mode 100644 index 00000000..8eb61729 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_thread_mutex.h @@ -0,0 +1,123 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_THREAD_MUTEX_H +#define APR_THREAD_MUTEX_H + +/** + * @file apr_thread_mutex.h + * @brief APR Thread Mutex Routines + */ + +#include "apr.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#if APR_HAS_THREADS || defined(DOXYGEN) + +/** + * @defgroup apr_thread_mutex Thread Mutex Routines + * @ingroup APR + * @{ + */ + +/** Opaque thread-local mutex structure */ +typedef struct apr_thread_mutex_t apr_thread_mutex_t; + +#define APR_THREAD_MUTEX_DEFAULT 0x0 /**< platform-optimal lock behavior */ +#define APR_THREAD_MUTEX_NESTED 0x1 /**< enable nested (recursive) locks */ +#define APR_THREAD_MUTEX_UNNESTED 0x2 /**< disable nested locks */ +#define APR_THREAD_MUTEX_TIMED 0x4 /**< enable timed locks */ + +/* Delayed the include to avoid a circular reference */ +#include "apr_pools.h" +#include "apr_time.h" + +/** + * Create and initialize a mutex that can be used to synchronize threads. + * @param mutex the memory address where the newly created mutex will be + * stored. + * @param flags Or'ed value of: + *
+ *           APR_THREAD_MUTEX_DEFAULT   platform-optimal lock behavior.
+ *           APR_THREAD_MUTEX_NESTED    enable nested (recursive) locks.
+ *           APR_THREAD_MUTEX_UNNESTED  disable nested locks (non-recursive).
+ * 
+ * @param pool the pool from which to allocate the mutex. + * @warning Be cautious in using APR_THREAD_MUTEX_DEFAULT. While this is the + * most optimal mutex based on a given platform's performance characteristics, + * it will behave as either a nested or an unnested lock. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_create(apr_thread_mutex_t **mutex, + unsigned int flags, + apr_pool_t *pool); +/** + * Acquire the lock for the given mutex. If the mutex is already locked, + * the current thread will be put to sleep until the lock becomes available. + * @param mutex the mutex on which to acquire the lock. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_lock(apr_thread_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex. If the mutex has already + * been acquired, the call returns immediately with APR_EBUSY. Note: it + * is important that the APR_STATUS_IS_EBUSY(s) macro be used to determine + * if the return value was APR_EBUSY, for portability reasons. + * @param mutex the mutex on which to attempt the lock acquiring. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_trylock(apr_thread_mutex_t *mutex); + +/** + * Attempt to acquire the lock for the given mutex until timeout expires. + * If the acquisition time outs, the call returns with APR_TIMEUP. + * @param mutex the mutex on which to attempt the lock acquiring. + * @param timeout the relative timeout (microseconds). + * @note A timeout negative or nul means immediate attempt, returning + * APR_TIMEUP without blocking if it the lock is already acquired. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_timedlock(apr_thread_mutex_t *mutex, + apr_interval_time_t timeout); + +/** + * Release the lock for the given mutex. + * @param mutex the mutex from which to release the lock. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_unlock(apr_thread_mutex_t *mutex); + +/** + * Destroy the mutex and free the memory associated with the lock. + * @param mutex the mutex to destroy. + */ +APR_DECLARE(apr_status_t) apr_thread_mutex_destroy(apr_thread_mutex_t *mutex); + +/** + * Get the pool used by this thread_mutex. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(thread_mutex); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_THREAD_MUTEX_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_thread_pool.h b/c/dependencies/windows/apr/x86_debug/include/apr_thread_pool.h new file mode 100644 index 00000000..cbf382b3 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_thread_pool.h @@ -0,0 +1,299 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +#ifndef APU_THREAD_POOL_H +#define APU_THREAD_POOL_H + +#include "apu.h" +#include "apr_thread_proc.h" + +/** + * @file apr_thread_pool.h + * @brief APR Thread Pool Library + + * @remarks This library implements a thread pool using apr_thread_t. A thread + * pool is a set of threads that can be created in advance or on demand until a + * maximum number. When a task is scheduled, the thread pool will find an idle + * thread to handle the task. In case all existing threads are busy and the + * number of tasks in the queue is higher than the adjustable threshold, the + * pool will try to create a new thread to serve the task if the maximum number + * has not been reached. Otherwise, the task will be put into a queue based on + * priority, which can be valued from 0 to 255, with higher values being served + * first. If there are tasks with the same priority, the new task might be put at + * the top or at the bottom - it depends on which function is used to put the task. + * + * @remarks There may be the case where the thread pool can use up to the maximum + * number of threads at peak load, but having those threads idle afterwards. A + * maximum number of idle threads can be set so that the extra idling threads will + * be terminated to save system resources. + */ +#if APR_HAS_THREADS + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_Util_TP Thread Pool routines + * @ingroup APR_Util + * @{ + */ + +/** Opaque Thread Pool structure. */ +typedef struct apr_thread_pool apr_thread_pool_t; + +#define APR_THREAD_TASK_PRIORITY_LOWEST 0 +#define APR_THREAD_TASK_PRIORITY_LOW 63 +#define APR_THREAD_TASK_PRIORITY_NORMAL 127 +#define APR_THREAD_TASK_PRIORITY_HIGH 191 +#define APR_THREAD_TASK_PRIORITY_HIGHEST 255 + +/** + * Create a thread pool + * @param me The pointer in which to return the newly created apr_thread_pool + * object, or NULL if thread pool creation fails. + * @param init_threads The number of threads to be created initially, this number + * will also be used as the initial value for the maximum number of idle threads. + * @param max_threads The maximum number of threads that can be created + * @param pool The pool to use + * @return APR_SUCCESS if the thread pool was created successfully. Otherwise, + * the error code. + */ +APU_DECLARE(apr_status_t) apr_thread_pool_create(apr_thread_pool_t **me, + apr_size_t init_threads, + apr_size_t max_threads, + apr_pool_t *pool); + +/** + * Destroy the thread pool and stop all the threads + * @return APR_SUCCESS if all threads are stopped. + */ +APU_DECLARE(apr_status_t) apr_thread_pool_destroy(apr_thread_pool_t *me); + +/** + * Schedule a task to the bottom of the tasks of same priority. + * @param me The thread pool + * @param func The task function + * @param param The parameter for the task function + * @param priority The priority of the task. + * @param owner Owner of this task. + * @return APR_SUCCESS if the task had been scheduled successfully + */ +APU_DECLARE(apr_status_t) apr_thread_pool_push(apr_thread_pool_t *me, + apr_thread_start_t func, + void *param, + apr_byte_t priority, + void *owner); +/** + * Schedule a task to be run after a delay + * @param me The thread pool + * @param func The task function + * @param param The parameter for the task function + * @param time Time in microseconds + * @param owner Owner of this task. + * @return APR_SUCCESS if the task had been scheduled successfully + */ +APU_DECLARE(apr_status_t) apr_thread_pool_schedule(apr_thread_pool_t *me, + apr_thread_start_t func, + void *param, + apr_interval_time_t time, + void *owner); + +/** + * Schedule a task to the top of the tasks of same priority. + * @param me The thread pool + * @param func The task function + * @param param The parameter for the task function + * @param priority The priority of the task. + * @param owner Owner of this task. + * @return APR_SUCCESS if the task had been scheduled successfully + */ +APU_DECLARE(apr_status_t) apr_thread_pool_top(apr_thread_pool_t *me, + apr_thread_start_t func, + void *param, + apr_byte_t priority, + void *owner); + +/** + * Cancel tasks submitted by the owner. If there is any task from the owner that + * is currently running, the function will spin until the task finished. + * @param me The thread pool + * @param owner Owner of the task + * @return APR_SUCCESS if the task has been cancelled successfully + * @note The task function should not be calling cancel, otherwise the function + * may get stuck forever. The function assert if it detect such a case. + */ +APU_DECLARE(apr_status_t) apr_thread_pool_tasks_cancel(apr_thread_pool_t *me, + void *owner); + +/** + * Get the current number of tasks waiting in the queue + * @param me The thread pool + * @return Number of tasks in the queue + */ +APU_DECLARE(apr_size_t) apr_thread_pool_tasks_count(apr_thread_pool_t *me); + +/** + * Get the current number of scheduled tasks waiting in the queue + * @param me The thread pool + * @return Number of scheduled tasks in the queue + */ +APU_DECLARE(apr_size_t) apr_thread_pool_scheduled_tasks_count(apr_thread_pool_t *me); + +/** + * Get the current number of threads + * @param me The thread pool + * @return Total number of threads + */ +APU_DECLARE(apr_size_t) apr_thread_pool_threads_count(apr_thread_pool_t *me); + +/** + * Get the current number of busy threads + * @param me The thread pool + * @return Number of busy threads + */ +APU_DECLARE(apr_size_t) apr_thread_pool_busy_count(apr_thread_pool_t *me); + +/** + * Get the current number of idle threads + * @param me The thread pool + * @return Number of idle threads + */ +APU_DECLARE(apr_size_t) apr_thread_pool_idle_count(apr_thread_pool_t *me); + +/** + * Access function for the maximum number of idle threads. Number of current + * idle threads will be reduced to the new limit. + * @param me The thread pool + * @param cnt The number + * @return The number of threads that were stopped. + */ +APU_DECLARE(apr_size_t) apr_thread_pool_idle_max_set(apr_thread_pool_t *me, + apr_size_t cnt); + +/** + * Get number of tasks that have run + * @param me The thread pool + * @return Number of tasks that have run + */ +APU_DECLARE(apr_size_t) + apr_thread_pool_tasks_run_count(apr_thread_pool_t * me); + +/** + * Get high water mark of the number of tasks waiting to run + * @param me The thread pool + * @return High water mark of tasks waiting to run + */ +APU_DECLARE(apr_size_t) + apr_thread_pool_tasks_high_count(apr_thread_pool_t * me); + +/** + * Get high water mark of the number of threads + * @param me The thread pool + * @return High water mark of threads in thread pool + */ +APU_DECLARE(apr_size_t) + apr_thread_pool_threads_high_count(apr_thread_pool_t * me); + +/** + * Get the number of idle threads that were destroyed after timing out + * @param me The thread pool + * @return Number of idle threads that timed out + */ +APU_DECLARE(apr_size_t) + apr_thread_pool_threads_idle_timeout_count(apr_thread_pool_t * me); + +/** + * Access function for the maximum number of idle threads + * @param me The thread pool + * @return The current maximum number + */ +APU_DECLARE(apr_size_t) apr_thread_pool_idle_max_get(apr_thread_pool_t *me); + +/** + * Access function for the maximum number of threads. + * @param me The thread pool + * @param cnt Number of threads + * @return The original maximum number of threads + */ +APU_DECLARE(apr_size_t) apr_thread_pool_thread_max_set(apr_thread_pool_t *me, + apr_size_t cnt); + +/** + * Access function for the maximum wait time (in microseconds) of an + * idling thread that exceeds the maximum number of idling threads. + * A non-zero value allows for the reaping of idling threads to shrink + * over time. Which helps reduce thrashing. + * @param me The thread pool + * @param timeout The number of microseconds an idle thread should wait + * till it reaps itself + * @return The original maximum wait time + */ +APU_DECLARE(apr_interval_time_t) + apr_thread_pool_idle_wait_set(apr_thread_pool_t * me, + apr_interval_time_t timeout); + +/** + * Access function for the maximum wait time (in microseconds) of an + * idling thread that exceeds the maximum number of idling threads + * @param me The thread pool + * @return The current maximum wait time + */ +APU_DECLARE(apr_interval_time_t) + apr_thread_pool_idle_wait_get(apr_thread_pool_t * me); + +/** + * Access function for the maximum number of threads + * @param me The thread pool + * @return The current maximum number + */ +APU_DECLARE(apr_size_t) apr_thread_pool_thread_max_get(apr_thread_pool_t *me); + +/** + * Access function for the threshold of tasks in queue to trigger a new thread. + * @param me The thread pool + * @param cnt The new threshold + * @return The original threshold + */ +APU_DECLARE(apr_size_t) apr_thread_pool_threshold_set(apr_thread_pool_t *me, + apr_size_t val); + +/** + * Access function for the threshold of tasks in queue to trigger a new thread. + * @param me The thread pool + * @return The current threshold + */ +APU_DECLARE(apr_size_t) apr_thread_pool_threshold_get(apr_thread_pool_t * me); + +/** + * Get owner of the task currently been executed by the thread. + * @param thd The thread is executing a task + * @param owner Pointer to receive owner of the task. + * @return APR_SUCCESS if the owner is retrieved successfully + */ +APU_DECLARE(apr_status_t) apr_thread_pool_task_owner_get(apr_thread_t *thd, + void **owner); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* APR_HAS_THREADS */ +#endif /* !APR_THREAD_POOL_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_thread_proc.h b/c/dependencies/windows/apr/x86_debug/include/apr_thread_proc.h new file mode 100644 index 00000000..ea3c43f9 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_thread_proc.h @@ -0,0 +1,846 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_THREAD_PROC_H +#define APR_THREAD_PROC_H + +/** + * @file apr_thread_proc.h + * @brief APR Thread and Process Library + */ + +#include "apr.h" +#include "apr_file_io.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_perms_set.h" + +#if APR_HAVE_STRUCT_RLIMIT +#include +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_thread_proc Threads and Process Functions + * @ingroup APR + * @{ + */ + +typedef enum { + APR_SHELLCMD, /**< use the shell to invoke the program */ + APR_PROGRAM, /**< invoke the program directly, no copied env */ + APR_PROGRAM_ENV, /**< invoke the program, replicating our environment */ + APR_PROGRAM_PATH, /**< find program on PATH, use our environment */ + APR_SHELLCMD_ENV /**< use the shell to invoke the program, + * replicating our environment + */ +} apr_cmdtype_e; + +typedef enum { + APR_WAIT, /**< wait for the specified process to finish */ + APR_NOWAIT /**< do not wait -- just see if it has finished */ +} apr_wait_how_e; + +/* I am specifically calling out the values so that the macros below make + * more sense. Yes, I know I don't need to, but I am hoping this makes what + * I am doing more clear. If you want to add more reasons to exit, continue + * to use bitmasks. + */ +typedef enum { + APR_PROC_EXIT = 1, /**< process exited normally */ + APR_PROC_SIGNAL = 2, /**< process exited due to a signal */ + APR_PROC_SIGNAL_CORE = 4 /**< process exited and dumped a core file */ +} apr_exit_why_e; + +/** did we exit the process */ +#define APR_PROC_CHECK_EXIT(x) (x & APR_PROC_EXIT) +/** did we get a signal */ +#define APR_PROC_CHECK_SIGNALED(x) (x & APR_PROC_SIGNAL) +/** did we get core */ +#define APR_PROC_CHECK_CORE_DUMP(x) (x & APR_PROC_SIGNAL_CORE) + +/** @see apr_procattr_io_set */ +#define APR_NO_PIPE 0 +/** @see apr_procattr_io_set and apr_file_pipe_create_ex */ +#define APR_FULL_BLOCK 1 +/** @see apr_procattr_io_set and apr_file_pipe_create_ex */ +#define APR_FULL_NONBLOCK 2 +/** @see apr_procattr_io_set */ +#define APR_PARENT_BLOCK 3 +/** @see apr_procattr_io_set */ +#define APR_CHILD_BLOCK 4 +/** @see apr_procattr_io_set */ +#define APR_NO_FILE 8 + +/** @see apr_file_pipe_create_ex */ +#define APR_READ_BLOCK 3 +/** @see apr_file_pipe_create_ex */ +#define APR_WRITE_BLOCK 4 + +/** @see apr_procattr_io_set + * @note Win32 only effective with version 1.2.12, portably introduced in 1.3.0 + */ +#define APR_NO_FILE 8 + +/** @see apr_procattr_limit_set */ +#define APR_LIMIT_CPU 0 +/** @see apr_procattr_limit_set */ +#define APR_LIMIT_MEM 1 +/** @see apr_procattr_limit_set */ +#define APR_LIMIT_NPROC 2 +/** @see apr_procattr_limit_set */ +#define APR_LIMIT_NOFILE 3 + +/** + * @defgroup APR_OC Other Child Flags + * @{ + */ +#define APR_OC_REASON_DEATH 0 /**< child has died, caller must call + * unregister still */ +#define APR_OC_REASON_UNWRITABLE 1 /**< write_fd is unwritable */ +#define APR_OC_REASON_RESTART 2 /**< a restart is occurring, perform + * any necessary cleanup (including + * sending a special signal to child) + */ +#define APR_OC_REASON_UNREGISTER 3 /**< unregister has been called, do + * whatever is necessary (including + * kill the child) */ +#define APR_OC_REASON_LOST 4 /**< somehow the child exited without + * us knowing ... buggy os? */ +#define APR_OC_REASON_RUNNING 5 /**< a health check is occurring, + * for most maintainence functions + * this is a no-op. + */ +/** @} */ + +/** The APR process type */ +typedef struct apr_proc_t { + /** The process ID */ + pid_t pid; + /** Parent's side of pipe to child's stdin */ + apr_file_t *in; + /** Parent's side of pipe to child's stdout */ + apr_file_t *out; + /** Parent's side of pipe to child's stdouterr */ + apr_file_t *err; +#if APR_HAS_PROC_INVOKED || defined(DOXYGEN) + /** Diagnositics/debugging string of the command invoked for + * this process [only present if APR_HAS_PROC_INVOKED is true] + * @remark Only enabled on Win32 by default. + * @bug This should either always or never be present in release + * builds - since it breaks binary compatibility. We may enable + * it always in APR 1.0 yet leave it undefined in most cases. + */ + char *invoked; +#endif +#if defined(WIN32) || defined(DOXYGEN) + /** (Win32 only) Creator's handle granting access to the process + * @remark This handle is closed and reset to NULL in every case + * corresponding to a waitpid() on Unix which returns the exit status. + * Therefore Win32 correspond's to Unix's zombie reaping characteristics + * and avoids potential handle leaks. + */ + HANDLE hproc; +#endif +} apr_proc_t; + +/** + * The prototype for APR child errfn functions. (See the description + * of apr_procattr_child_errfn_set() for more information.) + * It is passed the following parameters: + * @param pool Pool associated with the apr_proc_t. If your child + * error function needs user data, associate it with this + * pool. + * @param err APR error code describing the error + * @param description Text description of type of processing which failed + */ +typedef void (apr_child_errfn_t)(apr_pool_t *proc, apr_status_t err, + const char *description); + +/** Opaque Thread structure. */ +typedef struct apr_thread_t apr_thread_t; + +/** Opaque Thread attributes structure. */ +typedef struct apr_threadattr_t apr_threadattr_t; + +/** Opaque Process attributes structure. */ +typedef struct apr_procattr_t apr_procattr_t; + +/** Opaque control variable for one-time atomic variables. */ +typedef struct apr_thread_once_t apr_thread_once_t; + +/** Opaque thread private address space. */ +typedef struct apr_threadkey_t apr_threadkey_t; + +/** Opaque record of child process. */ +typedef struct apr_other_child_rec_t apr_other_child_rec_t; + +/** + * The prototype for any APR thread worker functions. + */ +typedef void *(APR_THREAD_FUNC *apr_thread_start_t)(apr_thread_t*, void*); + +typedef enum { + APR_KILL_NEVER, /**< process is never killed (i.e., never sent + * any signals), but it will be reaped if it exits + * before the pool is cleaned up */ + APR_KILL_ALWAYS, /**< process is sent SIGKILL on apr_pool_t cleanup */ + APR_KILL_AFTER_TIMEOUT, /**< SIGTERM, wait 3 seconds, SIGKILL */ + APR_JUST_WAIT, /**< wait forever for the process to complete */ + APR_KILL_ONLY_ONCE /**< send SIGTERM and then wait */ +} apr_kill_conditions_e; + +/* Thread Function definitions */ + +#if APR_HAS_THREADS + +/** + * Create and initialize a new threadattr variable + * @param new_attr The newly created threadattr. + * @param cont The pool to use + */ +APR_DECLARE(apr_status_t) apr_threadattr_create(apr_threadattr_t **new_attr, + apr_pool_t *cont); + +/** + * Set if newly created threads should be created in detached state. + * @param attr The threadattr to affect + * @param on Non-zero if detached threads should be created. + */ +APR_DECLARE(apr_status_t) apr_threadattr_detach_set(apr_threadattr_t *attr, + apr_int32_t on); + +/** + * Get the detach state for this threadattr. + * @param attr The threadattr to reference + * @return APR_DETACH if threads are to be detached, or APR_NOTDETACH + * if threads are to be joinable. + */ +APR_DECLARE(apr_status_t) apr_threadattr_detach_get(apr_threadattr_t *attr); + +/** + * Set the stack size of newly created threads. + * @param attr The threadattr to affect + * @param stacksize The stack size in bytes + */ +APR_DECLARE(apr_status_t) apr_threadattr_stacksize_set(apr_threadattr_t *attr, + apr_size_t stacksize); + +/** + * Set the stack guard area size of newly created threads. + * @param attr The threadattr to affect + * @param guardsize The stack guard area size in bytes + * @note Thread library implementations commonly use a "guard area" + * after each thread's stack which is not readable or writable such that + * stack overflows cause a segfault; this consumes e.g. 4K of memory + * and increases memory management overhead. Setting the guard area + * size to zero hence trades off reliable behaviour on stack overflow + * for performance. */ +APR_DECLARE(apr_status_t) apr_threadattr_guardsize_set(apr_threadattr_t *attr, + apr_size_t guardsize); + +/** + * Create a new thread of execution + * @param new_thread The newly created thread handle. + * @param attr The threadattr to use to determine how to create the thread + * @param func The function to start the new thread in + * @param data Any data to be passed to the starting function + * @param cont The pool to use + */ +APR_DECLARE(apr_status_t) apr_thread_create(apr_thread_t **new_thread, + apr_threadattr_t *attr, + apr_thread_start_t func, + void *data, apr_pool_t *cont); + +/** + * stop the current thread + * @param thd The thread to stop + * @param retval The return value to pass back to any thread that cares + */ +APR_DECLARE(apr_status_t) apr_thread_exit(apr_thread_t *thd, + apr_status_t retval); + +/** + * block until the desired thread stops executing. + * @param retval The return value from the dead thread. + * @param thd The thread to join + */ +APR_DECLARE(apr_status_t) apr_thread_join(apr_status_t *retval, + apr_thread_t *thd); + +/** + * force the current thread to yield the processor + */ +APR_DECLARE(void) apr_thread_yield(void); + +/** + * Initialize the control variable for apr_thread_once. If this isn't + * called, apr_initialize won't work. + * @param control The control variable to initialize + * @param p The pool to allocate data from. + */ +APR_DECLARE(apr_status_t) apr_thread_once_init(apr_thread_once_t **control, + apr_pool_t *p); + +/** + * Run the specified function one time, regardless of how many threads + * call it. + * @param control The control variable. The same variable should + * be passed in each time the function is tried to be + * called. This is how the underlying functions determine + * if the function has ever been called before. + * @param func The function to call. + */ +APR_DECLARE(apr_status_t) apr_thread_once(apr_thread_once_t *control, + void (*func)(void)); + +/** + * detach a thread + * @param thd The thread to detach + */ +APR_DECLARE(apr_status_t) apr_thread_detach(apr_thread_t *thd); + +/** + * Return user data associated with the current thread. + * @param data The user data associated with the thread. + * @param key The key to associate with the data + * @param thread The currently open thread. + */ +APR_DECLARE(apr_status_t) apr_thread_data_get(void **data, const char *key, + apr_thread_t *thread); + +/** + * Set user data associated with the current thread. + * @param data The user data to associate with the thread. + * @param key The key to use for associating the data with the thread + * @param cleanup The cleanup routine to use when the thread is destroyed. + * @param thread The currently open thread. + */ +APR_DECLARE(apr_status_t) apr_thread_data_set(void *data, const char *key, + apr_status_t (*cleanup) (void *), + apr_thread_t *thread); + +/** + * Create and initialize a new thread private address space + * @param key The thread private handle. + * @param dest The destructor to use when freeing the private memory. + * @param cont The pool to use + */ +APR_DECLARE(apr_status_t) apr_threadkey_private_create(apr_threadkey_t **key, + void (*dest)(void *), + apr_pool_t *cont); + +/** + * Get a pointer to the thread private memory + * @param new_mem The data stored in private memory + * @param key The handle for the desired thread private memory + */ +APR_DECLARE(apr_status_t) apr_threadkey_private_get(void **new_mem, + apr_threadkey_t *key); + +/** + * Set the data to be stored in thread private memory + * @param priv The data to be stored in private memory + * @param key The handle for the desired thread private memory + */ +APR_DECLARE(apr_status_t) apr_threadkey_private_set(void *priv, + apr_threadkey_t *key); + +/** + * Free the thread private memory + * @param key The handle for the desired thread private memory + */ +APR_DECLARE(apr_status_t) apr_threadkey_private_delete(apr_threadkey_t *key); + +/** + * Return the pool associated with the current threadkey. + * @param data The user data associated with the threadkey. + * @param key The key associated with the data + * @param threadkey The currently open threadkey. + */ +APR_DECLARE(apr_status_t) apr_threadkey_data_get(void **data, const char *key, + apr_threadkey_t *threadkey); + +/** + * Return the pool associated with the current threadkey. + * @param data The data to set. + * @param key The key to associate with the data. + * @param cleanup The cleanup routine to use when the file is destroyed. + * @param threadkey The currently open threadkey. + */ +APR_DECLARE(apr_status_t) apr_threadkey_data_set(void *data, const char *key, + apr_status_t (*cleanup) (void *), + apr_threadkey_t *threadkey); + +#endif + +/** + * Create and initialize a new procattr variable + * @param new_attr The newly created procattr. + * @param cont The pool to use + */ +APR_DECLARE(apr_status_t) apr_procattr_create(apr_procattr_t **new_attr, + apr_pool_t *cont); + +/** + * Determine if any of stdin, stdout, or stderr should be linked to pipes + * when starting a child process. + * @param attr The procattr we care about. + * @param in Should stdin be a pipe back to the parent? + * @param out Should stdout be a pipe back to the parent? + * @param err Should stderr be a pipe back to the parent? + * @note If APR_NO_PIPE, there will be no special channel, the child + * inherits the parent's corresponding stdio stream. If APR_NO_FILE is + * specified, that corresponding stream is closed in the child (and will + * be INVALID_HANDLE_VALUE when inspected on Win32). This can have ugly + * side effects, as the next file opened in the child on Unix will fall + * into the stdio stream fd slot! + */ +APR_DECLARE(apr_status_t) apr_procattr_io_set(apr_procattr_t *attr, + apr_int32_t in, apr_int32_t out, + apr_int32_t err); + +/** + * Set the child_in and/or parent_in values to existing apr_file_t values. + * @param attr The procattr we care about. + * @param child_in apr_file_t value to use as child_in. Must be a valid file. + * @param parent_in apr_file_t value to use as parent_in. Must be a valid file. + * @remark This is NOT a required initializer function. This is + * useful if you have already opened a pipe (or multiple files) + * that you wish to use, perhaps persistently across multiple + * process invocations - such as a log file. You can save some + * extra function calls by not creating your own pipe since this + * creates one in the process space for you. + * @bug Note that calling this function with two NULL files on some platforms + * creates an APR_FULL_BLOCK pipe, but this behavior is neither portable nor + * is it supported. @see apr_procattr_io_set instead for simple pipes. + */ +APR_DECLARE(apr_status_t) apr_procattr_child_in_set(struct apr_procattr_t *attr, + apr_file_t *child_in, + apr_file_t *parent_in); + +/** + * Set the child_out and parent_out values to existing apr_file_t values. + * @param attr The procattr we care about. + * @param child_out apr_file_t value to use as child_out. Must be a valid file. + * @param parent_out apr_file_t value to use as parent_out. Must be a valid file. + * @remark This is NOT a required initializer function. This is + * useful if you have already opened a pipe (or multiple files) + * that you wish to use, perhaps persistently across multiple + * process invocations - such as a log file. + * @bug Note that calling this function with two NULL files on some platforms + * creates an APR_FULL_BLOCK pipe, but this behavior is neither portable nor + * is it supported. @see apr_procattr_io_set instead for simple pipes. + */ +APR_DECLARE(apr_status_t) apr_procattr_child_out_set(struct apr_procattr_t *attr, + apr_file_t *child_out, + apr_file_t *parent_out); + +/** + * Set the child_err and parent_err values to existing apr_file_t values. + * @param attr The procattr we care about. + * @param child_err apr_file_t value to use as child_err. Must be a valid file. + * @param parent_err apr_file_t value to use as parent_err. Must be a valid file. + * @remark This is NOT a required initializer function. This is + * useful if you have already opened a pipe (or multiple files) + * that you wish to use, perhaps persistently across multiple + * process invocations - such as a log file. + * @bug Note that calling this function with two NULL files on some platforms + * creates an APR_FULL_BLOCK pipe, but this behavior is neither portable nor + * is it supported. @see apr_procattr_io_set instead for simple pipes. + */ +APR_DECLARE(apr_status_t) apr_procattr_child_err_set(struct apr_procattr_t *attr, + apr_file_t *child_err, + apr_file_t *parent_err); + +/** + * Set which directory the child process should start executing in. + * @param attr The procattr we care about. + * @param dir Which dir to start in. By default, this is the same dir as + * the parent currently resides in, when the createprocess call + * is made. + */ +APR_DECLARE(apr_status_t) apr_procattr_dir_set(apr_procattr_t *attr, + const char *dir); + +/** + * Set what type of command the child process will call. + * @param attr The procattr we care about. + * @param cmd The type of command. One of: + *
+ *            APR_SHELLCMD     --  Anything that the shell can handle
+ *            APR_PROGRAM      --  Executable program   (default) 
+ *            APR_PROGRAM_ENV  --  Executable program, copy environment
+ *            APR_PROGRAM_PATH --  Executable program on PATH, copy env
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_procattr_cmdtype_set(apr_procattr_t *attr, + apr_cmdtype_e cmd); + +/** + * Determine if the child should start in detached state. + * @param attr The procattr we care about. + * @param detach Should the child start in detached state? Default is no. + */ +APR_DECLARE(apr_status_t) apr_procattr_detach_set(apr_procattr_t *attr, + apr_int32_t detach); + +#if APR_HAVE_STRUCT_RLIMIT +/** + * Set the Resource Utilization limits when starting a new process. + * @param attr The procattr we care about. + * @param what Which limit to set, one of: + *
+ *                 APR_LIMIT_CPU
+ *                 APR_LIMIT_MEM
+ *                 APR_LIMIT_NPROC
+ *                 APR_LIMIT_NOFILE
+ * 
+ * @param limit Value to set the limit to. + */ +APR_DECLARE(apr_status_t) apr_procattr_limit_set(apr_procattr_t *attr, + apr_int32_t what, + struct rlimit *limit); +#endif + +/** + * Specify an error function to be called in the child process if APR + * encounters an error in the child prior to running the specified program. + * @param attr The procattr describing the child process to be created. + * @param errfn The function to call in the child process. + * @remark At the present time, it will only be called from apr_proc_create() + * on platforms where fork() is used. It will never be called on other + * platforms, on those platforms apr_proc_create() will return the error + * in the parent process rather than invoke the callback in the now-forked + * child process. + */ +APR_DECLARE(apr_status_t) apr_procattr_child_errfn_set(apr_procattr_t *attr, + apr_child_errfn_t *errfn); + +/** + * Specify that apr_proc_create() should do whatever it can to report + * failures to the caller of apr_proc_create(), rather than find out in + * the child. + * @param attr The procattr describing the child process to be created. + * @param chk Flag to indicate whether or not extra work should be done + * to try to report failures to the caller. + * @remark This flag only affects apr_proc_create() on platforms where + * fork() is used. This leads to extra overhead in the calling + * process, but that may help the application handle such + * errors more gracefully. + */ +APR_DECLARE(apr_status_t) apr_procattr_error_check_set(apr_procattr_t *attr, + apr_int32_t chk); + +/** + * Determine if the child should start in its own address space or using the + * current one from its parent + * @param attr The procattr we care about. + * @param addrspace Should the child start in its own address space? Default + * is no on NetWare and yes on other platforms. + */ +APR_DECLARE(apr_status_t) apr_procattr_addrspace_set(apr_procattr_t *attr, + apr_int32_t addrspace); + +/** + * Set the username used for running process + * @param attr The procattr we care about. + * @param username The username used + * @param password User password if needed. Password is needed on WIN32 + * or any other platform having + * APR_PROCATTR_USER_SET_REQUIRES_PASSWORD set. + */ +APR_DECLARE(apr_status_t) apr_procattr_user_set(apr_procattr_t *attr, + const char *username, + const char *password); + +/** + * Set the group used for running process + * @param attr The procattr we care about. + * @param groupname The group name used + */ +APR_DECLARE(apr_status_t) apr_procattr_group_set(apr_procattr_t *attr, + const char *groupname); + + +/** + * Register permission set function + * @param attr The procattr we care about. + * @param perms_set_fn Permission set callback + * @param data Data to pass to permission callback function + * @param perms Permissions to set + */ +APR_DECLARE(apr_status_t) apr_procattr_perms_set_register(apr_procattr_t *attr, + apr_perms_setfn_t *perms_set_fn, + void *data, + apr_fileperms_t perms); + +#if APR_HAS_FORK +/** + * This is currently the only non-portable call in APR. This executes + * a standard unix fork. + * @param proc The resulting process handle. + * @param cont The pool to use. + * @remark returns APR_INCHILD for the child, and APR_INPARENT for the parent + * or an error. + */ +APR_DECLARE(apr_status_t) apr_proc_fork(apr_proc_t *proc, apr_pool_t *cont); +#endif + +/** + * Create a new process and execute a new program within that process. + * @param new_proc The resulting process handle. + * @param progname The program to run + * @param args the arguments to pass to the new program. The first + * one should be the program name. + * @param env The new environment table for the new process. This + * should be a list of NULL-terminated strings. This argument + * is ignored for APR_PROGRAM_ENV, APR_PROGRAM_PATH, and + * APR_SHELLCMD_ENV types of commands. + * @param attr the procattr we should use to determine how to create the new + * process + * @param pool The pool to use. + * @note This function returns without waiting for the new process to terminate; + * use apr_proc_wait for that. + */ +APR_DECLARE(apr_status_t) apr_proc_create(apr_proc_t *new_proc, + const char *progname, + const char * const *args, + const char * const *env, + apr_procattr_t *attr, + apr_pool_t *pool); + +/** + * Wait for a child process to die + * @param proc The process handle that corresponds to the desired child process + * @param exitcode The returned exit status of the child, if a child process + * dies, or the signal that caused the child to die. + * On platforms that don't support obtaining this information, + * the status parameter will be returned as APR_ENOTIMPL. + * @param exitwhy Why the child died, the bitwise or of: + *
+ *            APR_PROC_EXIT         -- process terminated normally
+ *            APR_PROC_SIGNAL       -- process was killed by a signal
+ *            APR_PROC_SIGNAL_CORE  -- process was killed by a signal, and
+ *                                     generated a core dump.
+ * 
+ * @param waithow How should we wait. One of: + *
+ *            APR_WAIT   -- block until the child process dies.
+ *            APR_NOWAIT -- return immediately regardless of if the 
+ *                          child is dead or not.
+ * 
+ * @remark The child's status is in the return code to this process. It is one of: + *
+ *            APR_CHILD_DONE     -- child is no longer running.
+ *            APR_CHILD_NOTDONE  -- child is still running.
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_proc_wait(apr_proc_t *proc, + int *exitcode, apr_exit_why_e *exitwhy, + apr_wait_how_e waithow); + +/** + * Wait for any current child process to die and return information + * about that child. + * @param proc Pointer to NULL on entry, will be filled out with child's + * information + * @param exitcode The returned exit status of the child, if a child process + * dies, or the signal that caused the child to die. + * On platforms that don't support obtaining this information, + * the status parameter will be returned as APR_ENOTIMPL. + * @param exitwhy Why the child died, the bitwise or of: + *
+ *            APR_PROC_EXIT         -- process terminated normally
+ *            APR_PROC_SIGNAL       -- process was killed by a signal
+ *            APR_PROC_SIGNAL_CORE  -- process was killed by a signal, and
+ *                                     generated a core dump.
+ * 
+ * @param waithow How should we wait. One of: + *
+ *            APR_WAIT   -- block until the child process dies.
+ *            APR_NOWAIT -- return immediately regardless of if the 
+ *                          child is dead or not.
+ * 
+ * @param p Pool to allocate child information out of. + * @bug Passing proc as a *proc rather than **proc was an odd choice + * for some platforms... this should be revisited in 1.0 + */ +APR_DECLARE(apr_status_t) apr_proc_wait_all_procs(apr_proc_t *proc, + int *exitcode, + apr_exit_why_e *exitwhy, + apr_wait_how_e waithow, + apr_pool_t *p); + +#define APR_PROC_DETACH_FOREGROUND 0 /**< Do not detach */ +#define APR_PROC_DETACH_DAEMONIZE 1 /**< Detach */ + +/** + * Detach the process from the controlling terminal. + * @param daemonize set to non-zero if the process should daemonize + * and become a background process, else it will + * stay in the foreground. + */ +APR_DECLARE(apr_status_t) apr_proc_detach(int daemonize); + +/** + * Register an other_child -- a child associated to its registered + * maintence callback. This callback is invoked when the process + * dies, is disconnected or disappears. + * @param proc The child process to register. + * @param maintenance maintenance is a function that is invoked with a + * reason and the data pointer passed here. + * @param data Opaque context data passed to the maintenance function. + * @param write_fd An fd that is probed for writing. If it is ever unwritable + * then the maintenance is invoked with reason + * OC_REASON_UNWRITABLE. + * @param p The pool to use for allocating memory. + * @bug write_fd duplicates the proc->out stream, it's really redundant + * and should be replaced in the APR 1.0 API with a bitflag of which + * proc->in/out/err handles should be health checked. + * @bug no platform currently tests the pipes health. + */ +APR_DECLARE(void) apr_proc_other_child_register(apr_proc_t *proc, + void (*maintenance) (int reason, + void *, + int status), + void *data, apr_file_t *write_fd, + apr_pool_t *p); + +/** + * Stop watching the specified other child. + * @param data The data to pass to the maintenance function. This is + * used to find the process to unregister. + * @warning Since this can be called by a maintenance function while we're + * scanning the other_children list, all scanners should protect + * themself by loading ocr->next before calling any maintenance + * function. + */ +APR_DECLARE(void) apr_proc_other_child_unregister(void *data); + +/** + * Notify the maintenance callback of a registered other child process + * that application has detected an event, such as death. + * @param proc The process to check + * @param reason The reason code to pass to the maintenance function + * @param status The status to pass to the maintenance function + * @remark An example of code using this behavior; + *
+ * rv = apr_proc_wait_all_procs(&proc, &exitcode, &status, APR_WAIT, p);
+ * if (APR_STATUS_IS_CHILD_DONE(rv)) {
+ * \#if APR_HAS_OTHER_CHILD
+ *     if (apr_proc_other_child_alert(&proc, APR_OC_REASON_DEATH, status)
+ *             == APR_SUCCESS) {
+ *         ;  (already handled)
+ *     }
+ *     else
+ * \#endif
+ *         [... handling non-otherchild processes death ...]
+ * 
+ */ +APR_DECLARE(apr_status_t) apr_proc_other_child_alert(apr_proc_t *proc, + int reason, + int status); + +/** + * Test one specific other child processes and invoke the maintenance callback + * with the appropriate reason code, if still running, or the appropriate reason + * code if the process is no longer healthy. + * @param ocr The registered other child + * @param reason The reason code (e.g. APR_OC_REASON_RESTART) if still running + */ +APR_DECLARE(void) apr_proc_other_child_refresh(apr_other_child_rec_t *ocr, + int reason); + +/** + * Test all registered other child processes and invoke the maintenance callback + * with the appropriate reason code, if still running, or the appropriate reason + * code if the process is no longer healthy. + * @param reason The reason code (e.g. APR_OC_REASON_RESTART) to running processes + */ +APR_DECLARE(void) apr_proc_other_child_refresh_all(int reason); + +/** + * Terminate a process. + * @param proc The process to terminate. + * @param sig How to kill the process. + */ +APR_DECLARE(apr_status_t) apr_proc_kill(apr_proc_t *proc, int sig); + +/** + * Register a process to be killed when a pool dies. + * @param a The pool to use to define the processes lifetime + * @param proc The process to register + * @param how How to kill the process, one of: + *
+ *         APR_KILL_NEVER         -- process is never sent any signals
+ *         APR_KILL_ALWAYS        -- process is sent SIGKILL on apr_pool_t cleanup
+ *         APR_KILL_AFTER_TIMEOUT -- SIGTERM, wait 3 seconds, SIGKILL
+ *         APR_JUST_WAIT          -- wait forever for the process to complete
+ *         APR_KILL_ONLY_ONCE     -- send SIGTERM and then wait
+ * 
+ */ +APR_DECLARE(void) apr_pool_note_subprocess(apr_pool_t *a, apr_proc_t *proc, + apr_kill_conditions_e how); + +#if APR_HAS_THREADS + +#if (APR_HAVE_SIGWAIT || APR_HAVE_SIGSUSPEND) && !defined(OS2) + +/** + * Setup the process for a single thread to be used for all signal handling. + * @warning This must be called before any threads are created + */ +APR_DECLARE(apr_status_t) apr_setup_signal_thread(void); + +/** + * Make the current thread listen for signals. This thread will loop + * forever, calling a provided function whenever it receives a signal. That + * functions should return 1 if the signal has been handled, 0 otherwise. + * @param signal_handler The function to call when a signal is received + * apr_status_t apr_signal_thread((int)(*signal_handler)(int signum)) + * @note Synchronous signals like SIGABRT/SIGSEGV/SIGBUS/... are ignored by + * apr_signal_thread() and thus can't be waited by this function (they remain + * handled by the operating system or its native signals interface). + * @remark In APR version 1.6 and ealier, SIGUSR2 was part of these ignored + * signals and thus was never passed in to the signal_handler. From APR 1.7 + * this is no more the case so SIGUSR2 can be handled in signal_handler and + * acted upon like the other asynchronous signals. + */ +APR_DECLARE(apr_status_t) apr_signal_thread(int(*signal_handler)(int signum)); + +#endif /* (APR_HAVE_SIGWAIT || APR_HAVE_SIGSUSPEND) && !defined(OS2) */ + +/** + * Get the child-pool used by the thread from the thread info. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(thread); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_THREAD_PROC_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_thread_rwlock.h b/c/dependencies/windows/apr/x86_debug/include/apr_thread_rwlock.h new file mode 100644 index 00000000..0bd958fb --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_thread_rwlock.h @@ -0,0 +1,129 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_THREAD_RWLOCK_H +#define APR_THREAD_RWLOCK_H + +/** + * @file apr_thread_rwlock.h + * @brief APR Reader/Writer Lock Routines + */ + +#include "apr.h" +#include "apr_pools.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#if APR_HAS_THREADS + +/** + * @defgroup apr_thread_rwlock Reader/Writer Lock Routines + * @ingroup APR + * @{ + */ + +/** Opaque read-write thread-safe lock. */ +typedef struct apr_thread_rwlock_t apr_thread_rwlock_t; + +/** + * Note: The following operations have undefined results: unlocking a + * read-write lock which is not locked in the calling thread; write + * locking a read-write lock which is already locked by the calling + * thread; destroying a read-write lock more than once; clearing or + * destroying the pool from which a locked read-write lock is + * allocated. + */ + +/** + * Create and initialize a read-write lock that can be used to synchronize + * threads. + * @param rwlock the memory address where the newly created readwrite lock + * will be stored. + * @param pool the pool from which to allocate the mutex. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_create(apr_thread_rwlock_t **rwlock, + apr_pool_t *pool); +/** + * Acquire a shared-read lock on the given read-write lock. This will allow + * multiple threads to enter the same critical section while they have acquired + * the read lock. + * @param rwlock the read-write lock on which to acquire the shared read. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_rdlock(apr_thread_rwlock_t *rwlock); + +/** + * Attempt to acquire the shared-read lock on the given read-write lock. This + * is the same as apr_thread_rwlock_rdlock(), only that the function fails + * if there is another thread holding the write lock, or if there are any + * write threads blocking on the lock. If the function fails for this case, + * APR_EBUSY will be returned. Note: it is important that the + * APR_STATUS_IS_EBUSY(s) macro be used to determine if the return value was + * APR_EBUSY, for portability reasons. + * @param rwlock the rwlock on which to attempt the shared read. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_tryrdlock(apr_thread_rwlock_t *rwlock); + +/** + * Acquire an exclusive-write lock on the given read-write lock. This will + * allow only one single thread to enter the critical sections. If there + * are any threads currently holding the read-lock, this thread is put to + * sleep until it can have exclusive access to the lock. + * @param rwlock the read-write lock on which to acquire the exclusive write. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_wrlock(apr_thread_rwlock_t *rwlock); + +/** + * Attempt to acquire the exclusive-write lock on the given read-write lock. + * This is the same as apr_thread_rwlock_wrlock(), only that the function fails + * if there is any other thread holding the lock (for reading or writing), + * in which case the function will return APR_EBUSY. Note: it is important + * that the APR_STATUS_IS_EBUSY(s) macro be used to determine if the return + * value was APR_EBUSY, for portability reasons. + * @param rwlock the rwlock on which to attempt the exclusive write. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_trywrlock(apr_thread_rwlock_t *rwlock); + +/** + * Release either the read or write lock currently held by the calling thread + * associated with the given read-write lock. + * @param rwlock the read-write lock to be released (unlocked). + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_unlock(apr_thread_rwlock_t *rwlock); + +/** + * Destroy the read-write lock and free the associated memory. + * @param rwlock the rwlock to destroy. + */ +APR_DECLARE(apr_status_t) apr_thread_rwlock_destroy(apr_thread_rwlock_t *rwlock); + +/** + * Get the pool used by this thread_rwlock. + * @return apr_pool_t the pool + */ +APR_POOL_DECLARE_ACCESSOR(thread_rwlock); + +#endif /* APR_HAS_THREADS */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_THREAD_RWLOCK_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_time.h b/c/dependencies/windows/apr/x86_debug/include/apr_time.h new file mode 100644 index 00000000..b0efd791 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_time.h @@ -0,0 +1,237 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_TIME_H +#define APR_TIME_H + +/** + * @file apr_time.h + * @brief APR Time Library + */ + +#include "apr.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_time Time Routines + * @ingroup APR + * @{ + */ + +/** month names */ +APR_DECLARE_DATA extern const char apr_month_snames[12][4]; +/** day names */ +APR_DECLARE_DATA extern const char apr_day_snames[7][4]; + + +/** number of microseconds since 00:00:00 January 1, 1970 UTC */ +typedef apr_int64_t apr_time_t; + + +/** mechanism to properly type apr_time_t literals */ +#define APR_TIME_C(val) APR_INT64_C(val) + +/** mechanism to properly print apr_time_t values */ +#define APR_TIME_T_FMT APR_INT64_T_FMT + +/** intervals for I/O timeouts, in microseconds */ +typedef apr_int64_t apr_interval_time_t; +/** short interval for I/O timeouts, in microseconds */ +typedef apr_int32_t apr_short_interval_time_t; + +/** number of microseconds per second */ +#define APR_USEC_PER_SEC APR_TIME_C(1000000) + +/** @return apr_time_t as a second */ +#define apr_time_sec(time) ((time) / APR_USEC_PER_SEC) + +/** @return apr_time_t as a usec */ +#define apr_time_usec(time) ((time) % APR_USEC_PER_SEC) + +/** @return apr_time_t as a msec */ +#define apr_time_msec(time) (((time) / 1000) % 1000) + +/** @return apr_time_t as a msec */ +#define apr_time_as_msec(time) ((time) / 1000) + +/** @return milliseconds as an apr_time_t */ +#define apr_time_from_msec(msec) ((apr_time_t)(msec) * 1000) + +/** @return seconds as an apr_time_t */ +#define apr_time_from_sec(sec) ((apr_time_t)(sec) * APR_USEC_PER_SEC) + +/** @return a second and usec combination as an apr_time_t */ +#define apr_time_make(sec, usec) ((apr_time_t)(sec) * APR_USEC_PER_SEC \ + + (apr_time_t)(usec)) + +/** + * @return the current time + */ +APR_DECLARE(apr_time_t) apr_time_now(void); + +/** @see apr_time_exp_t */ +typedef struct apr_time_exp_t apr_time_exp_t; + +/** + * a structure similar to ANSI struct tm with the following differences: + * - tm_usec isn't an ANSI field + * - tm_gmtoff isn't an ANSI field (it's a BSDism) + */ +struct apr_time_exp_t { + /** microseconds past tm_sec */ + apr_int32_t tm_usec; + /** (0-61) seconds past tm_min */ + apr_int32_t tm_sec; + /** (0-59) minutes past tm_hour */ + apr_int32_t tm_min; + /** (0-23) hours past midnight */ + apr_int32_t tm_hour; + /** (1-31) day of the month */ + apr_int32_t tm_mday; + /** (0-11) month of the year */ + apr_int32_t tm_mon; + /** year since 1900 */ + apr_int32_t tm_year; + /** (0-6) days since Sunday */ + apr_int32_t tm_wday; + /** (0-365) days since January 1 */ + apr_int32_t tm_yday; + /** daylight saving time */ + apr_int32_t tm_isdst; + /** seconds east of UTC */ + apr_int32_t tm_gmtoff; +}; + +/* Delayed the include to avoid a circular reference */ +#include "apr_pools.h" + +/** + * Convert an ansi time_t to an apr_time_t + * @param result the resulting apr_time_t + * @param input the time_t to convert + */ +APR_DECLARE(apr_status_t) apr_time_ansi_put(apr_time_t *result, + time_t input); + +/** + * Convert a time to its human readable components using an offset + * from GMT. + * @param result the exploded time + * @param input the time to explode + * @param offs the number of seconds offset to apply + */ +APR_DECLARE(apr_status_t) apr_time_exp_tz(apr_time_exp_t *result, + apr_time_t input, + apr_int32_t offs); + +/** + * Convert a time to its human readable components (GMT). + * @param result the exploded time + * @param input the time to explode + */ +APR_DECLARE(apr_status_t) apr_time_exp_gmt(apr_time_exp_t *result, + apr_time_t input); + +/** + * Convert a time to its human readable components in the local timezone. + * @param result the exploded time + * @param input the time to explode + */ +APR_DECLARE(apr_status_t) apr_time_exp_lt(apr_time_exp_t *result, + apr_time_t input); + +/** + * Convert time value from human readable format to a numeric apr_time_t + * (elapsed microseconds since the epoch). + * @param result the resulting imploded time + * @param input the input exploded time + */ +APR_DECLARE(apr_status_t) apr_time_exp_get(apr_time_t *result, + apr_time_exp_t *input); + +/** + * Convert time value from human readable format to a numeric apr_time_t that + * always represents GMT. + * @param result the resulting imploded time + * @param input the input exploded time + */ +APR_DECLARE(apr_status_t) apr_time_exp_gmt_get(apr_time_t *result, + apr_time_exp_t *input); + +/** + * Sleep for the specified number of micro-seconds. + * @param t desired amount of time to sleep. + * @warning May sleep for longer than the specified time. + */ +APR_DECLARE(void) apr_sleep(apr_interval_time_t t); + +/** length of a RFC822 Date */ +#define APR_RFC822_DATE_LEN (30) +/** + * apr_rfc822_date formats dates in the RFC822 + * format in an efficient manner. It is a fixed length + * format which requires APR_RFC822_DATA_LEN bytes of storage, + * including the trailing NUL terminator. + * @param date_str String to write to. + * @param t the time to convert + */ +APR_DECLARE(apr_status_t) apr_rfc822_date(char *date_str, apr_time_t t); + +/** length of a CTIME date */ +#define APR_CTIME_LEN (25) +/** + * apr_ctime formats dates in the ctime() format + * in an efficient manner. It is a fixed length format + * and requires APR_CTIME_LEN bytes of storage including + * the trailing NUL terminator. + * Unlike ANSI/ISO C ctime(), apr_ctime() does not include + * a \\n at the end of the string. + * @param date_str String to write to. + * @param t the time to convert + */ +APR_DECLARE(apr_status_t) apr_ctime(char *date_str, apr_time_t t); + +/** + * Formats the exploded time according to the format specified + * @param s string to write to + * @param retsize The length of the returned string + * @param max The maximum length of the string + * @param format The format for the time string + * @param tm The time to convert + */ +APR_DECLARE(apr_status_t) apr_strftime(char *s, apr_size_t *retsize, + apr_size_t max, const char *format, + apr_time_exp_t *tm); + +/** + * Improve the clock resolution for the lifetime of the given pool. + * Generally this is only desirable on benchmarking and other very + * time-sensitive applications, and has no impact on most platforms. + * @param p The pool to associate the finer clock resolution + */ +APR_DECLARE(void) apr_time_clock_hires(apr_pool_t *p); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_TIME_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_uri.h b/c/dependencies/windows/apr/x86_debug/include/apr_uri.h new file mode 100644 index 00000000..02908a9d --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_uri.h @@ -0,0 +1,178 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apr_uri.h: External Interface of apr_uri.c + */ + +/** + * @file apr_uri.h + * @brief APR-UTIL URI Routines + */ + +#ifndef APR_URI_H +#define APR_URI_H + +#include "apu.h" + +#include "apr_network_io.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_URI URI + * @ingroup APR_Util + * @{ + */ + +#define APR_URI_FTP_DEFAULT_PORT 21 /**< default FTP port */ +#define APR_URI_SSH_DEFAULT_PORT 22 /**< default SSH port */ +#define APR_URI_TELNET_DEFAULT_PORT 23 /**< default telnet port */ +#define APR_URI_GOPHER_DEFAULT_PORT 70 /**< default Gopher port */ +#define APR_URI_HTTP_DEFAULT_PORT 80 /**< default HTTP port */ +#define APR_URI_POP_DEFAULT_PORT 110 /**< default POP port */ +#define APR_URI_NNTP_DEFAULT_PORT 119 /**< default NNTP port */ +#define APR_URI_IMAP_DEFAULT_PORT 143 /**< default IMAP port */ +#define APR_URI_PROSPERO_DEFAULT_PORT 191 /**< default Prospero port */ +#define APR_URI_WAIS_DEFAULT_PORT 210 /**< default WAIS port */ +#define APR_URI_LDAP_DEFAULT_PORT 389 /**< default LDAP port */ +#define APR_URI_HTTPS_DEFAULT_PORT 443 /**< default HTTPS port */ +#define APR_URI_RTSP_DEFAULT_PORT 554 /**< default RTSP port */ +#define APR_URI_SNEWS_DEFAULT_PORT 563 /**< default SNEWS port */ +#define APR_URI_ACAP_DEFAULT_PORT 674 /**< default ACAP port */ +#define APR_URI_NFS_DEFAULT_PORT 2049 /**< default NFS port */ +#define APR_URI_TIP_DEFAULT_PORT 3372 /**< default TIP port */ +#define APR_URI_SIP_DEFAULT_PORT 5060 /**< default SIP port */ + +/** Flags passed to unparse_uri_components(): */ +/** suppress "scheme://user\@site:port" */ +#define APR_URI_UNP_OMITSITEPART (1U<<0) +/** Just omit user */ +#define APR_URI_UNP_OMITUSER (1U<<1) +/** Just omit password */ +#define APR_URI_UNP_OMITPASSWORD (1U<<2) +/** omit "user:password\@" part */ +#define APR_URI_UNP_OMITUSERINFO (APR_URI_UNP_OMITUSER | \ + APR_URI_UNP_OMITPASSWORD) +/** Show plain text password (default: show XXXXXXXX) */ +#define APR_URI_UNP_REVEALPASSWORD (1U<<3) +/** Show "scheme://user\@site:port" only */ +#define APR_URI_UNP_OMITPATHINFO (1U<<4) +/** Omit the "?queryarg" from the path */ +#define APR_URI_UNP_OMITQUERY (1U<<5) + +/** @see apr_uri_t */ +typedef struct apr_uri_t apr_uri_t; + +/** + * A structure to encompass all of the fields in a uri + */ +struct apr_uri_t { + /** scheme ("http"/"ftp"/...) */ + char *scheme; + /** combined [user[:password]\@]host[:port] */ + char *hostinfo; + /** user name, as in http://user:passwd\@host:port/ */ + char *user; + /** password, as in http://user:passwd\@host:port/ */ + char *password; + /** hostname from URI (or from Host: header) */ + char *hostname; + /** port string (integer representation is in "port") */ + char *port_str; + /** the request path (or NULL if only scheme://host was given) */ + char *path; + /** Everything after a '?' in the path, if present */ + char *query; + /** Trailing "#fragment" string, if present */ + char *fragment; + + /** structure returned from gethostbyname() */ + struct hostent *hostent; + + /** The port number, numeric, valid only if port_str != NULL */ + apr_port_t port; + + /** has the structure been initialized */ + unsigned is_initialized:1; + + /** has the DNS been looked up yet */ + unsigned dns_looked_up:1; + /** has the dns been resolved yet */ + unsigned dns_resolved:1; +}; + +/* apr_uri.c */ +/** + * Return the default port for a given scheme. The schemes recognized are + * http, ftp, https, gopher, wais, nntp, snews, and prospero + * @param scheme_str The string that contains the current scheme + * @return The default port for this scheme + */ +APU_DECLARE(apr_port_t) apr_uri_port_of_scheme(const char *scheme_str); + +/** + * Unparse a apr_uri_t structure to an URI string. Optionally + * suppress the password for security reasons. + * @param p The pool to allocate out of + * @param uptr All of the parts of the uri + * @param flags How to unparse the uri. One of: + *
+ *    APR_URI_UNP_OMITSITEPART        Suppress "scheme://user\@site:port" 
+ *    APR_URI_UNP_OMITUSER            Just omit user 
+ *    APR_URI_UNP_OMITPASSWORD        Just omit password 
+ *    APR_URI_UNP_OMITUSERINFO        Omit "user:password\@" part
+ *    APR_URI_UNP_REVEALPASSWORD      Show plain text password (default: show XXXXXXXX)
+ *    APR_URI_UNP_OMITPATHINFO        Show "scheme://user\@site:port" only 
+ *    APR_URI_UNP_OMITQUERY           Omit "?queryarg" or "#fragment" 
+ * 
+ * @return The uri as a string + */ +APU_DECLARE(char *) apr_uri_unparse(apr_pool_t *p, + const apr_uri_t *uptr, + unsigned flags); + +/** + * Parse a given URI, fill in all supplied fields of a apr_uri_t + * structure. This eliminates the necessity of extracting host, port, + * path, query info repeatedly in the modules. + * @param p The pool to allocate out of + * @param uri The uri to parse + * @param uptr The apr_uri_t to fill out + * @return APR_SUCCESS for success or error code + */ +APU_DECLARE(apr_status_t) apr_uri_parse(apr_pool_t *p, const char *uri, + apr_uri_t *uptr); + +/** + * Special case for CONNECT parsing: it comes with the hostinfo part only + * @param p The pool to allocate out of + * @param hostinfo The hostinfo string to parse + * @param uptr The apr_uri_t to fill out + * @return APR_SUCCESS for success or error code + */ +APU_DECLARE(apr_status_t) apr_uri_parse_hostinfo(apr_pool_t *p, + const char *hostinfo, + apr_uri_t *uptr); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_URI_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_user.h b/c/dependencies/windows/apr/x86_debug/include/apr_user.h new file mode 100644 index 00000000..0e0a3ac5 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_user.h @@ -0,0 +1,158 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_USER_H +#define APR_USER_H + +/** + * @file apr_user.h + * @brief APR User ID Services + */ + +#include "apr.h" +#include "apr_errno.h" +#include "apr_pools.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apr_user User and Group ID Services + * @ingroup APR + * @{ + */ + +/** + * Structure for determining user ownership. + */ +#ifdef WIN32 +typedef PSID apr_uid_t; +#else +typedef uid_t apr_uid_t; +#endif + +/** + * Structure for determining group ownership. + */ +#ifdef WIN32 +typedef PSID apr_gid_t; +#else +typedef gid_t apr_gid_t; +#endif + +#if APR_HAS_USER + +/** + * Get the userid (and groupid) of the calling process + * @param userid Returns the user id + * @param groupid Returns the user's group id + * @param p The pool from which to allocate working space + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_uid_current(apr_uid_t *userid, + apr_gid_t *groupid, + apr_pool_t *p); + +/** + * Get the user name for a specified userid + * @param username Pointer to new string containing user name (on output) + * @param userid The userid + * @param p The pool from which to allocate the string + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_uid_name_get(char **username, apr_uid_t userid, + apr_pool_t *p); + +/** + * Get the userid (and groupid) for the specified username + * @param userid Returns the user id + * @param groupid Returns the user's group id + * @param username The username to look up + * @param p The pool from which to allocate working space + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_uid_get(apr_uid_t *userid, apr_gid_t *groupid, + const char *username, apr_pool_t *p); + +/** + * Get the home directory for the named user + * @param dirname Pointer to new string containing directory name (on output) + * @param username The named user + * @param p The pool from which to allocate the string + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_uid_homepath_get(char **dirname, + const char *username, + apr_pool_t *p); + +/** + * Compare two user identifiers for equality. + * @param left One uid to test + * @param right Another uid to test + * @return APR_SUCCESS if the apr_uid_t structures identify the same user, + * APR_EMISMATCH if not, APR_BADARG if an apr_uid_t is invalid. + * @remark This function is available only if APR_HAS_USER is defined. + */ +#if defined(WIN32) +APR_DECLARE(apr_status_t) apr_uid_compare(apr_uid_t left, apr_uid_t right); +#else +#define apr_uid_compare(left,right) (((left) == (right)) ? APR_SUCCESS : APR_EMISMATCH) +#endif + +/** + * Get the group name for a specified groupid + * @param groupname Pointer to new string containing group name (on output) + * @param groupid The groupid + * @param p The pool from which to allocate the string + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_gid_name_get(char **groupname, + apr_gid_t groupid, apr_pool_t *p); + +/** + * Get the groupid for a specified group name + * @param groupid Pointer to the group id (on output) + * @param groupname The group name to look up + * @param p The pool from which to allocate the string + * @remark This function is available only if APR_HAS_USER is defined. + */ +APR_DECLARE(apr_status_t) apr_gid_get(apr_gid_t *groupid, + const char *groupname, apr_pool_t *p); + +/** + * Compare two group identifiers for equality. + * @param left One gid to test + * @param right Another gid to test + * @return APR_SUCCESS if the apr_gid_t structures identify the same group, + * APR_EMISMATCH if not, APR_BADARG if an apr_gid_t is invalid. + * @remark This function is available only if APR_HAS_USER is defined. + */ +#if defined(WIN32) +APR_DECLARE(apr_status_t) apr_gid_compare(apr_gid_t left, apr_gid_t right); +#else +#define apr_gid_compare(left,right) (((left) == (right)) ? APR_SUCCESS : APR_EMISMATCH) +#endif + +#endif /* ! APR_HAS_USER */ + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_USER_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_uuid.h b/c/dependencies/windows/apr/x86_debug/include/apr_uuid.h new file mode 100644 index 00000000..5312a9f6 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_uuid.h @@ -0,0 +1,76 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_uuid.h + * @brief APR UUID library + */ +#ifndef APR_UUID_H +#define APR_UUID_H + +#include "apu.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup APR_UUID UUID Handling + * @ingroup APR + * @{ + */ + +/** + * we represent a UUID as a block of 16 bytes. + */ + +typedef struct { + unsigned char data[16]; /**< the actual UUID */ +} apr_uuid_t; + +/** UUIDs are formatted as: 00112233-4455-6677-8899-AABBCCDDEEFF */ +#define APR_UUID_FORMATTED_LENGTH 36 + + +/** + * Generate and return a (new) UUID + * @param uuid The resulting UUID + */ +APU_DECLARE(void) apr_uuid_get(apr_uuid_t *uuid); + +/** + * Format a UUID into a string, following the standard format + * @param buffer The buffer to place the formatted UUID string into. It must + * be at least APR_UUID_FORMATTED_LENGTH + 1 bytes long to hold + * the formatted UUID and a null terminator + * @param uuid The UUID to format + */ +APU_DECLARE(void) apr_uuid_format(char *buffer, const apr_uuid_t *uuid); + +/** + * Parse a standard-format string into a UUID + * @param uuid The resulting UUID + * @param uuid_str The formatted UUID + */ +APU_DECLARE(apr_status_t) apr_uuid_parse(apr_uuid_t *uuid, const char *uuid_str); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* APR_UUID_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_version.h b/c/dependencies/windows/apr/x86_debug/include/apr_version.h new file mode 100644 index 00000000..e96de383 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_version.h @@ -0,0 +1,164 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_VERSION_H +#define APR_VERSION_H + +/** + * @file apr_version.h + * @brief APR Versioning Interface + * + * APR's Version + * + * There are several different mechanisms for accessing the version. There + * is a string form, and a set of numbers; in addition, there are constants + * which can be compiled into your application, and you can query the library + * being used for its actual version. + * + * Note that it is possible for an application to detect that it has been + * compiled against a different version of APR by use of the compile-time + * constants and the use of the run-time query function. + * + * APR version numbering follows the guidelines specified in: + * + * http://apr.apache.org/versioning.html + */ + + +#define APR_COPYRIGHT "Copyright (c) 2000-2019 The Apache Software " \ + "Foundation or its licensors, as applicable." + +/* The numeric compile-time version constants. These constants are the + * authoritative version numbers for APR. + */ + +/** major version + * Major API changes that could cause compatibility problems for older + * programs such as structure size changes. No binary compatibility is + * possible across a change in the major version. + */ +#define APR_MAJOR_VERSION 1 + +/** minor version + * Minor API changes that do not cause binary compatibility problems. + * Reset to 0 when upgrading APR_MAJOR_VERSION + */ +#define APR_MINOR_VERSION 7 + +/** patch level + * The Patch Level never includes API changes, simply bug fixes. + * Reset to 0 when upgrading APR_MINOR_VERSION + */ +#define APR_PATCH_VERSION 0 + +/** + * The symbol APR_IS_DEV_VERSION is only defined for internal, + * "development" copies of APR. It is undefined for released versions + * of APR. + */ +/* #undef APR_IS_DEV_VERSION */ + +/** + * Check at compile time if the APR version is at least a certain + * level. + * @param major The major version component of the version checked + * for (e.g., the "1" of "1.3.0"). + * @param minor The minor version component of the version checked + * for (e.g., the "3" of "1.3.0"). + * @param patch The patch level component of the version checked + * for (e.g., the "0" of "1.3.0"). + * @remark This macro is available with APR versions starting with + * 1.3.0. + */ +#define APR_VERSION_AT_LEAST(major,minor,patch) \ +(((major) < APR_MAJOR_VERSION) \ + || ((major) == APR_MAJOR_VERSION && (minor) < APR_MINOR_VERSION) \ + || ((major) == APR_MAJOR_VERSION && (minor) == APR_MINOR_VERSION && (patch) <= APR_PATCH_VERSION)) + +#if defined(APR_IS_DEV_VERSION) || defined(DOXYGEN) +/** Internal: string form of the "is dev" flag */ +#ifndef APR_IS_DEV_STRING +#define APR_IS_DEV_STRING "-dev" +#endif +#else +#define APR_IS_DEV_STRING "" +#endif + +/* APR_STRINGIFY is defined here, and also in apr_general.h, so wrap it */ +#ifndef APR_STRINGIFY +/** Properly quote a value as a string in the C preprocessor */ +#define APR_STRINGIFY(n) APR_STRINGIFY_HELPER(n) +/** Helper macro for APR_STRINGIFY */ +#define APR_STRINGIFY_HELPER(n) #n +#endif + +/** The formatted string of APR's version */ +#define APR_VERSION_STRING \ + APR_STRINGIFY(APR_MAJOR_VERSION) "." \ + APR_STRINGIFY(APR_MINOR_VERSION) "." \ + APR_STRINGIFY(APR_PATCH_VERSION) \ + APR_IS_DEV_STRING + +/** An alternative formatted string of APR's version */ +/* macro for Win32 .rc files using numeric csv representation */ +#define APR_VERSION_STRING_CSV APR_MAJOR_VERSION ##, \ + ##APR_MINOR_VERSION ##, \ + ##APR_PATCH_VERSION + + +#ifndef APR_VERSION_ONLY + +/* The C language API to access the version at run time, + * as opposed to compile time. APR_VERSION_ONLY may be defined + * externally when preprocessing apr_version.h to obtain strictly + * the C Preprocessor macro declarations. + */ + +#include "apr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The numeric version information is broken out into fields within this + * structure. + */ +typedef struct { + int major; /**< major number */ + int minor; /**< minor number */ + int patch; /**< patch number */ + int is_dev; /**< is development (1 or 0) */ +} apr_version_t; + +/** + * Return APR's version information information in a numeric form. + * + * @param pvsn Pointer to a version structure for returning the version + * information. + */ +APR_DECLARE(void) apr_version(apr_version_t *pvsn); + +/** Return APR's version information as a string. */ +APR_DECLARE(const char *) apr_version_string(void); + +#ifdef __cplusplus +} +#endif + +#endif /* ndef APR_VERSION_ONLY */ + +#endif /* ndef APR_VERSION_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_want.h b/c/dependencies/windows/apr/x86_debug/include/apr_want.h new file mode 100644 index 00000000..2863b001 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_want.h @@ -0,0 +1,124 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr.h" /* configuration data */ +/** + * @file apr_want.h + * @brief APR Standard Headers Support + * + *
+ * Features:
+ *
+ *   APR_WANT_STRFUNC:  strcmp, strcat, strcpy, etc
+ *   APR_WANT_MEMFUNC:  memcmp, memcpy, etc
+ *   APR_WANT_STDIO:     and related bits
+ *   APR_WANT_IOVEC:    struct iovec
+ *   APR_WANT_BYTEFUNC: htons, htonl, ntohl, ntohs
+ *
+ * Typical usage:
+ *
+ *   \#define APR_WANT_STRFUNC
+ *   \#define APR_WANT_MEMFUNC
+ *   \#include "apr_want.h"
+ *
+ * The appropriate headers will be included.
+ *
+ * Note: it is safe to use this in a header (it won't interfere with other
+ *       headers' or source files' use of apr_want.h)
+ * 
+ */ + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_STRFUNC + +#if APR_HAVE_STRING_H +#include +#endif +#if APR_HAVE_STRINGS_H +#include +#endif + +#undef APR_WANT_STRFUNC +#endif + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_MEMFUNC + +#if APR_HAVE_STRING_H +#include +#endif + +#undef APR_WANT_MEMFUNC +#endif + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_STDIO + +#if APR_HAVE_STDIO_H +#include +#endif + +#undef APR_WANT_STDIO +#endif + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_IOVEC + +#if APR_HAVE_IOVEC + +#if APR_HAVE_SYS_UIO_H +#include +#endif + +#else + +#ifndef APR_IOVEC_DEFINED +#define APR_IOVEC_DEFINED +struct iovec +{ + void *iov_base; + size_t iov_len; +}; +#endif /* !APR_IOVEC_DEFINED */ + +#endif /* APR_HAVE_IOVEC */ + +#undef APR_WANT_IOVEC +#endif + +/* --------------------------------------------------------------------- */ + +#ifdef APR_WANT_BYTEFUNC + +/* Single Unix says they are in arpa/inet.h. Linux has them in + * netinet/in.h. FreeBSD has them in arpa/inet.h but requires that + * netinet/in.h be included first. + */ +#if APR_HAVE_NETINET_IN_H +#include +#endif +#if APR_HAVE_ARPA_INET_H +#include +#endif + +#undef APR_WANT_BYTEFUNC +#endif + +/* --------------------------------------------------------------------- */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_xlate.h b/c/dependencies/windows/apr/x86_debug/include/apr_xlate.h new file mode 100644 index 00000000..32636685 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_xlate.h @@ -0,0 +1,163 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_XLATE_H +#define APR_XLATE_H + +#include "apu.h" +#include "apr_pools.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @file apr_xlate.h + * @brief APR I18N translation library + */ + +/** + * @defgroup APR_XLATE I18N translation library + * @ingroup APR + * @{ + */ +/** Opaque translation buffer */ +typedef struct apr_xlate_t apr_xlate_t; + +/** + * Set up for converting text from one charset to another. + * @param convset The handle to be filled in by this function + * @param topage The name of the target charset + * @param frompage The name of the source charset + * @param pool The pool to use + * @remark + * Specify APR_DEFAULT_CHARSET for one of the charset + * names to indicate the charset of the source code at + * compile time. This is useful if there are literal + * strings in the source code which must be translated + * according to the charset of the source code. + * APR_DEFAULT_CHARSET is not useful if the source code + * of the caller was not encoded in the same charset as + * APR at compile time. + * + * @remark + * Specify APR_LOCALE_CHARSET for one of the charset + * names to indicate the charset of the current locale. + * + * @remark + * Return APR_EINVAL if unable to procure a convset, or APR_ENOTIMPL + * if charset transcoding is not available in this instance of + * apr-util at all (i.e., APR_HAS_XLATE is undefined). + */ +APU_DECLARE(apr_status_t) apr_xlate_open(apr_xlate_t **convset, + const char *topage, + const char *frompage, + apr_pool_t *pool); + +/** + * This is to indicate the charset of the sourcecode at compile time + * names to indicate the charset of the source code at + * compile time. This is useful if there are literal + * strings in the source code which must be translated + * according to the charset of the source code. + */ +#define APR_DEFAULT_CHARSET (const char *)0 +/** + * To indicate charset names of the current locale + */ +#define APR_LOCALE_CHARSET (const char *)1 + +/** + * Find out whether or not the specified conversion is single-byte-only. + * @param convset The handle allocated by apr_xlate_open, specifying the + * parameters of conversion + * @param onoff Output: whether or not the conversion is single-byte-only + * @remark + * Return APR_ENOTIMPL if charset transcoding is not available + * in this instance of apr-util (i.e., APR_HAS_XLATE is undefined). + */ +APU_DECLARE(apr_status_t) apr_xlate_sb_get(apr_xlate_t *convset, int *onoff); + +/** + * Convert a buffer of text from one codepage to another. + * @param convset The handle allocated by apr_xlate_open, specifying + * the parameters of conversion + * @param inbuf The address of the source buffer + * @param inbytes_left Input: the amount of input data to be translated + * Output: the amount of input data not yet translated + * @param outbuf The address of the destination buffer + * @param outbytes_left Input: the size of the output buffer + * Output: the amount of the output buffer not yet used + * @remark + * Returns APR_ENOTIMPL if charset transcoding is not available + * in this instance of apr-util (i.e., APR_HAS_XLATE is undefined). + * Returns APR_INCOMPLETE if the input buffer ends in an incomplete + * multi-byte character. + * + * To correctly terminate the output buffer for some multi-byte + * character set encodings, a final call must be made to this function + * after the complete input string has been converted, passing + * the inbuf and inbytes_left parameters as NULL. (Note that this + * mode only works from version 1.1.0 onwards) + */ +APU_DECLARE(apr_status_t) apr_xlate_conv_buffer(apr_xlate_t *convset, + const char *inbuf, + apr_size_t *inbytes_left, + char *outbuf, + apr_size_t *outbytes_left); + +/* @see apr_file_io.h the comment in apr_file_io.h about this hack */ +#ifdef APR_NOT_DONE_YET +/** + * The purpose of apr_xlate_conv_char is to translate one character + * at a time. This needs to be written carefully so that it works + * with double-byte character sets. + * @param convset The handle allocated by apr_xlate_open, specifying the + * parameters of conversion + * @param inchar The character to convert + * @param outchar The converted character + */ +APU_DECLARE(apr_status_t) apr_xlate_conv_char(apr_xlate_t *convset, + char inchar, char outchar); +#endif + +/** + * Convert a single-byte character from one charset to another. + * @param convset The handle allocated by apr_xlate_open, specifying the + * parameters of conversion + * @param inchar The single-byte character to convert. + * @warning This only works when converting between single-byte character sets. + * -1 will be returned if the conversion can't be performed. + */ +APU_DECLARE(apr_int32_t) apr_xlate_conv_byte(apr_xlate_t *convset, + unsigned char inchar); + +/** + * Close a codepage translation handle. + * @param convset The codepage translation handle to close + * @remark + * Return APR_ENOTIMPL if charset transcoding is not available + * in this instance of apr-util (i.e., APR_HAS_XLATE is undefined). + */ +APU_DECLARE(apr_status_t) apr_xlate_close(apr_xlate_t *convset); + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* ! APR_XLATE_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apr_xml.h b/c/dependencies/windows/apr/x86_debug/include/apr_xml.h new file mode 100644 index 00000000..87a696cc --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apr_xml.h @@ -0,0 +1,358 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file apr_xml.h + * @brief APR-UTIL XML Library + */ +#ifndef APR_XML_H +#define APR_XML_H + +/** + * @defgroup APR_Util_XML XML + * @ingroup APR_Util + * @{ + */ +#include "apr_pools.h" +#include "apr_tables.h" +#include "apr_file_io.h" + +#include "apu.h" +#if APR_CHARSET_EBCDIC +#include "apr_xlate.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @package Apache XML library + */ + +/* -------------------------------------------------------------------- */ + +/* ### these will need to move at some point to a more logical spot */ + +/** @see apr_text */ +typedef struct apr_text apr_text; + +/** Structure to keep a linked list of pieces of text */ +struct apr_text { + /** The current piece of text */ + const char *text; + /** a pointer to the next piece of text */ + struct apr_text *next; +}; + +/** @see apr_text_header */ +typedef struct apr_text_header apr_text_header; + +/** A list of pieces of text */ +struct apr_text_header { + /** The first piece of text in the list */ + apr_text *first; + /** The last piece of text in the list */ + apr_text *last; +}; + +/** + * Append a piece of text to the end of a list + * @param p The pool to allocate out of + * @param hdr The text header to append to + * @param text The new text to append + */ +APU_DECLARE(void) apr_text_append(apr_pool_t *p, apr_text_header *hdr, + const char *text); + + +/* -------------------------------------------------------------------- +** +** XML PARSING +*/ + +/* +** Qualified namespace values +** +** APR_XML_NS_DAV_ID +** We always insert the "DAV:" namespace URI at the head of the +** namespace array. This means that it will always be at ID==0, +** making it much easier to test for. +** +** APR_XML_NS_NONE +** This special ID is used for two situations: +** +** 1) The namespace prefix begins with "xml" (and we do not know +** what it means). Namespace prefixes with "xml" (any case) as +** their first three characters are reserved by the XML Namespaces +** specification for future use. mod_dav will pass these through +** unchanged. When this identifier is used, the prefix is LEFT in +** the element/attribute name. Downstream processing should not +** prepend another prefix. +** +** 2) The element/attribute does not have a namespace. +** +** a) No prefix was used, and a default namespace has not been +** defined. +** b) No prefix was used, and the default namespace was specified +** to mean "no namespace". This is done with a namespace +** declaration of: xmlns="" +** (this declaration is typically used to override a previous +** specification for the default namespace) +** +** In these cases, we need to record that the elem/attr has no +** namespace so that we will not attempt to prepend a prefix. +** All namespaces that are used will have a prefix assigned to +** them -- mod_dav will never set or use the default namespace +** when generating XML. This means that "no prefix" will always +** mean "no namespace". +** +** In both cases, the XML generation will avoid prepending a prefix. +** For the first case, this means the original prefix/name will be +** inserted into the output stream. For the latter case, it means +** the name will have no prefix, and since we never define a default +** namespace, this means it will have no namespace. +** +** Note: currently, mod_dav understands the "xmlns" prefix and the +** "xml:lang" attribute. These are handled specially (they aren't +** left within the XML tree), so the APR_XML_NS_NONE value won't ever +** really apply to these values. +*/ +#define APR_XML_NS_DAV_ID 0 /**< namespace ID for "DAV:" */ +#define APR_XML_NS_NONE -10 /**< no namespace for this elem/attr */ + +#define APR_XML_NS_ERROR_BASE -100 /**< used only during processing */ +/** Is this namespace an error? */ +#define APR_XML_NS_IS_ERROR(e) ((e) <= APR_XML_NS_ERROR_BASE) + +/** @see apr_xml_attr */ +typedef struct apr_xml_attr apr_xml_attr; +/** @see apr_xml_elem */ +typedef struct apr_xml_elem apr_xml_elem; +/** @see apr_xml_doc */ +typedef struct apr_xml_doc apr_xml_doc; + +/** apr_xml_attr: holds a parsed XML attribute */ +struct apr_xml_attr { + /** attribute name */ + const char *name; + /** index into namespace array */ + int ns; + + /** attribute value */ + const char *value; + + /** next attribute */ + struct apr_xml_attr *next; +}; + +/** apr_xml_elem: holds a parsed XML element */ +struct apr_xml_elem { + /** element name */ + const char *name; + /** index into namespace array */ + int ns; + /** xml:lang for attrs/contents */ + const char *lang; + + /** cdata right after start tag */ + apr_text_header first_cdata; + /** cdata after MY end tag */ + apr_text_header following_cdata; + + /** parent element */ + struct apr_xml_elem *parent; + /** next (sibling) element */ + struct apr_xml_elem *next; + /** first child element */ + struct apr_xml_elem *first_child; + /** first attribute */ + struct apr_xml_attr *attr; + + /* used only during parsing */ + /** last child element */ + struct apr_xml_elem *last_child; + /** namespaces scoped by this elem */ + struct apr_xml_ns_scope *ns_scope; + + /* used by modules during request processing */ + /** Place for modules to store private data */ + void *priv; +}; + +/** Is this XML element empty? */ +#define APR_XML_ELEM_IS_EMPTY(e) ((e)->first_child == NULL && \ + (e)->first_cdata.first == NULL) + +/** apr_xml_doc: holds a parsed XML document */ +struct apr_xml_doc { + /** root element */ + apr_xml_elem *root; + /** array of namespaces used */ + apr_array_header_t *namespaces; +}; + +/** Opaque XML parser structure */ +typedef struct apr_xml_parser apr_xml_parser; + +/** + * Create an XML parser + * @param pool The pool for allocating the parser and the parse results. + * @return The new parser. + */ +APU_DECLARE(apr_xml_parser *) apr_xml_parser_create(apr_pool_t *pool); + +/** + * Parse a File, producing a xml_doc + * @param p The pool for allocating the parse results. + * @param parser A pointer to *parser (needed so calling function can get + * errors), will be set to NULL on successful completion. + * @param ppdoc A pointer to *apr_xml_doc (which has the parsed results in it) + * @param xmlfd A file to read from. + * @param buffer_length Buffer length which would be suitable + * @return Any errors found during parsing. + */ +APU_DECLARE(apr_status_t) apr_xml_parse_file(apr_pool_t *p, + apr_xml_parser **parser, + apr_xml_doc **ppdoc, + apr_file_t *xmlfd, + apr_size_t buffer_length); + + +/** + * Feed input into the parser + * @param parser The XML parser for parsing this data. + * @param data The data to parse. + * @param len The length of the data. + * @return Any errors found during parsing. + * @remark Use apr_xml_parser_geterror() to get more error information. + */ +APU_DECLARE(apr_status_t) apr_xml_parser_feed(apr_xml_parser *parser, + const char *data, + apr_size_t len); + +/** + * Terminate the parsing and return the result + * @param parser The XML parser for parsing this data. + * @param pdoc The resulting parse information. May be NULL to simply + * terminate the parsing without fetching the info. + * @return Any errors found during the final stage of parsing. + * @remark Use apr_xml_parser_geterror() to get more error information. + */ +APU_DECLARE(apr_status_t) apr_xml_parser_done(apr_xml_parser *parser, + apr_xml_doc **pdoc); + +/** + * Fetch additional error information from the parser. + * @param parser The XML parser to query for errors. + * @param errbuf A buffer for storing error text. + * @param errbufsize The length of the error text buffer. + * @return The error buffer + */ +APU_DECLARE(char *) apr_xml_parser_geterror(apr_xml_parser *parser, + char *errbuf, + apr_size_t errbufsize); + + +/** + * Converts an XML element tree to flat text + * @param p The pool to allocate out of + * @param elem The XML element to convert + * @param style How to covert the XML. One of: + *
+ *     APR_XML_X2T_FULL                start tag, contents, end tag 
+ *     APR_XML_X2T_INNER               contents only 
+ *     APR_XML_X2T_LANG_INNER          xml:lang + inner contents 
+ *     APR_XML_X2T_FULL_NS_LANG        FULL + ns defns + xml:lang 
+ *     APR_XML_X2T_PARSED              original prefixes
+ * 
+ * @param namespaces The namespace of the current XML element + * @param ns_map Namespace mapping + * @param pbuf Buffer to put the converted text into + * @param psize Size of the converted text + */ +APU_DECLARE(void) apr_xml_to_text(apr_pool_t *p, const apr_xml_elem *elem, + int style, apr_array_header_t *namespaces, + int *ns_map, const char **pbuf, + apr_size_t *psize); + +/* style argument values: */ +#define APR_XML_X2T_FULL 0 /**< start tag, contents, end tag */ +#define APR_XML_X2T_INNER 1 /**< contents only */ +#define APR_XML_X2T_LANG_INNER 2 /**< xml:lang + inner contents */ +#define APR_XML_X2T_FULL_NS_LANG 3 /**< FULL + ns defns + xml:lang */ +#define APR_XML_X2T_PARSED 4 /**< original prefixes */ + +/** + * empty XML element + * @param p The pool to allocate out of + * @param elem The XML element to empty + * @return the string that was stored in the XML element + */ +APU_DECLARE(const char *) apr_xml_empty_elem(apr_pool_t *p, + const apr_xml_elem *elem); + +/** + * quote an XML string + * Replace '\<', '\>', and '\&' with '\<', '\>', and '\&'. + * @param p The pool to allocate out of + * @param s The string to quote + * @param quotes If quotes is true, then replace '"' with '\"'. + * @return The quoted string + * @note If the string does not contain special characters, it is not + * duplicated into the pool and the original string is returned. + */ +APU_DECLARE(const char *) apr_xml_quote_string(apr_pool_t *p, const char *s, + int quotes); + +/** + * Quote an XML element + * @param p The pool to allocate out of + * @param elem The element to quote + */ +APU_DECLARE(void) apr_xml_quote_elem(apr_pool_t *p, apr_xml_elem *elem); + +/* manage an array of unique URIs: apr_xml_insert_uri() and APR_XML_URI_ITEM() */ + +/** + * return the URI's (existing) index, or insert it and return a new index + * @param uri_array array to insert into + * @param uri The uri to insert + * @return int The uri's index + */ +APU_DECLARE(int) apr_xml_insert_uri(apr_array_header_t *uri_array, + const char *uri); + +/** Get the URI item for this XML element */ +#define APR_XML_GET_URI_ITEM(ary, i) (((const char * const *)(ary)->elts)[i]) + +#if APR_CHARSET_EBCDIC +/** + * Convert parsed tree in EBCDIC + * @param p The pool to allocate out of + * @param pdoc The apr_xml_doc to convert. + * @param xlate The translation handle to use. + * @return Any errors found during conversion. + */ +APU_DECLARE(apr_status_t) apr_xml_parser_convert_doc(apr_pool_t *p, + apr_xml_doc *pdoc, + apr_xlate_t *convset); +#endif + +#ifdef __cplusplus +} +#endif +/** @} */ +#endif /* APR_XML_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apu.h b/c/dependencies/windows/apr/x86_debug/include/apu.h new file mode 100644 index 00000000..21fbedff --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apu.h @@ -0,0 +1,146 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apu.h is duplicated from apu.hw at build time -- do not edit apu.h + */ +/* @file apu.h + * @brief APR-Utility main file + */ +/** + * @defgroup APR_Util APR Utility Functions + * @{ + */ + + +#ifndef APU_H +#define APU_H + +/** + * APU_DECLARE_EXPORT is defined when building the APR-UTIL dynamic library, + * so that all public symbols are exported. + * + * APU_DECLARE_STATIC is defined when including the APR-UTIL public headers, + * to provide static linkage when the dynamic library may be unavailable. + * + * APU_DECLARE_STATIC and APU_DECLARE_EXPORT are left undefined when + * including the APR-UTIL public headers, to import and link the symbols from + * the dynamic APR-UTIL library and assure appropriate indirection and calling + * conventions at compile time. + */ + +/* Make sure we have our platform identifier macro defined we ask for later. + */ +#if defined(_WIN32) && !defined(WIN32) +#define WIN32 1 +#endif + +#if defined(DOXYGEN) || !defined(WIN32) +/** + * The public APR-UTIL functions are declared with APU_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APU_DECLARE_NONSTD(). + * + * @fn APU_DECLARE(rettype) apr_func(args); + */ +#define APU_DECLARE(type) type +/** + * The public APR-UTIL functions using variable arguments are declared with + * APU_DECLARE_NONSTD(), as they must use the C language calling convention. + * + * @fn APU_DECLARE_NONSTD(rettype) apr_func(args, ...); + */ +#define APU_DECLARE_NONSTD(type) type +/** + * The public APR-UTIL variables are declared with APU_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * + * @fn APU_DECLARE_DATA type apr_variable; + * @note extern APU_DECLARE_DATA type apr_variable; syntax is required for + * declarations within headers to properly import the variable. + */ +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_STATIC) +#define APU_DECLARE(type) type __stdcall +#define APU_DECLARE_NONSTD(type) type __cdecl +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_EXPORT) +#define APU_DECLARE(type) __declspec(dllexport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllexport) +#else +#define APU_DECLARE(type) __declspec(dllimport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllimport) +#endif + +#if !defined(WIN32) || defined(APU_MODULE_DECLARE_STATIC) +/** + * Declare a dso module's exported module structure as APU_MODULE_DECLARE_DATA. + * + * Unless APU_MODULE_DECLARE_STATIC is defined at compile time, symbols + * declared with APU_MODULE_DECLARE_DATA are always exported. + * @code + * module APU_MODULE_DECLARE_DATA mod_tag + * @endcode + */ +#define APU_MODULE_DECLARE_DATA +#else +#define APU_MODULE_DECLARE_DATA __declspec(dllexport) +#endif + +/* + * we always have SDBM (it's in our codebase) + */ +#define APU_HAVE_SDBM 1 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_GDBM 0 +#define APU_HAVE_NDBM 0 +#define APU_HAVE_DB 0 + +#if APU_HAVE_DB +#define APU_HAVE_DB_VERSION 0 +#endif +#endif + +/* + * we always enable dynamic driver loads within apr_dbd + * Win32 always has odbc (it's always installed) + */ +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_PGSQL 0 +#define APU_HAVE_MYSQL 0 +#define APU_HAVE_SQLITE3 0 +#define APU_HAVE_SQLITE2 0 +#define APU_HAVE_ORACLE 0 +#define APU_HAVE_ODBC 1 +#endif + +#define APU_HAVE_CRYPTO 0 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_OPENSSL 0 +#define APU_HAVE_NSS 0 +#define APU_HAVE_COMMONCRYPTO 0 +#endif + +#define APU_HAVE_APR_ICONV 1 +#define APU_HAVE_ICONV 0 +#define APR_HAS_XLATE (APU_HAVE_APR_ICONV || APU_HAVE_ICONV) + +#endif /* APU_H */ +/** @} */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apu.h.in b/c/dependencies/windows/apr/x86_debug/include/apu.h.in new file mode 100644 index 00000000..0781a6a0 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apu.h.in @@ -0,0 +1,128 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apu.h is generated from apu.h.in by configure -- do not edit apu.h + */ +/* @file apu.h + * @brief APR-Utility main file + */ +/** + * @defgroup APR_Util APR Utility Functions + * @{ + */ + + +#ifndef APU_H +#define APU_H + +/** + * APU_DECLARE_EXPORT is defined when building the APR-UTIL dynamic library, + * so that all public symbols are exported. + * + * APU_DECLARE_STATIC is defined when including the APR-UTIL public headers, + * to provide static linkage when the dynamic library may be unavailable. + * + * APU_DECLARE_STATIC and APU_DECLARE_EXPORT are left undefined when + * including the APR-UTIL public headers, to import and link the symbols from + * the dynamic APR-UTIL library and assure appropriate indirection and calling + * conventions at compile time. + */ + +#if defined(DOXYGEN) || !defined(WIN32) +/** + * The public APR-UTIL functions are declared with APU_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APU_DECLARE_NONSTD(). + * + * @fn APU_DECLARE(rettype) apr_func(args); + */ +#define APU_DECLARE(type) type +/** + * The public APR-UTIL functions using variable arguments are declared with + * APU_DECLARE_NONSTD(), as they must use the C language calling convention. + * + * @fn APU_DECLARE_NONSTD(rettype) apr_func(args, ...); + */ +#define APU_DECLARE_NONSTD(type) type +/** + * The public APR-UTIL variables are declared with APU_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * + * @fn APU_DECLARE_DATA type apr_variable; + * @note APU_DECLARE_DATA extern type apr_variable; syntax is required for + * declarations within headers to properly import the variable. + */ +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_STATIC) +#define APU_DECLARE(type) type __stdcall +#define APU_DECLARE_NONSTD(type) type __cdecl +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_EXPORT) +#define APU_DECLARE(type) __declspec(dllexport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllexport) +#else +#define APU_DECLARE(type) __declspec(dllimport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllimport) +#endif + +#if !defined(WIN32) || defined(APU_MODULE_DECLARE_STATIC) +/** + * Declare a dso module's exported module structure as APU_MODULE_DECLARE_DATA. + * + * Unless APU_MODULE_DECLARE_STATIC is defined at compile time, symbols + * declared with APU_MODULE_DECLARE_DATA are always exported. + * @code + * module APU_MODULE_DECLARE_DATA mod_tag + * @endcode + */ +#define APU_MODULE_DECLARE_DATA +#else +#define APU_MODULE_DECLARE_DATA __declspec(dllexport) +#endif + +/* + * we always have SDBM (it's in our codebase) + */ +#define APU_HAVE_SDBM @apu_have_sdbm@ +#define APU_HAVE_GDBM @apu_have_gdbm@ +#define APU_HAVE_NDBM @apu_have_ndbm@ +#define APU_HAVE_DB @apu_have_db@ + +#if APU_HAVE_DB +#define APU_HAVE_DB_VERSION @apu_db_version@ +#endif + +#define APU_HAVE_PGSQL @apu_have_pgsql@ +#define APU_HAVE_MYSQL @apu_have_mysql@ +#define APU_HAVE_SQLITE3 @apu_have_sqlite3@ +#define APU_HAVE_SQLITE2 @apu_have_sqlite2@ +#define APU_HAVE_ORACLE @apu_have_oracle@ +#define APU_HAVE_ODBC @apu_have_odbc@ + +#define APU_HAVE_CRYPTO @apu_have_crypto@ +#define APU_HAVE_OPENSSL @apu_have_openssl@ +#define APU_HAVE_NSS @apu_have_nss@ +#define APU_HAVE_COMMONCRYPTO @apu_have_commoncrypto@ + +#define APU_HAVE_APR_ICONV @have_apr_iconv@ +#define APU_HAVE_ICONV @have_iconv@ +#define APR_HAS_XLATE (APU_HAVE_APR_ICONV || APU_HAVE_ICONV) + +#endif /* APU_H */ +/** @} */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apu.hnw b/c/dependencies/windows/apr/x86_debug/include/apu.hnw new file mode 100644 index 00000000..12e73818 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apu.hnw @@ -0,0 +1,124 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Note: This is a NetWare specific version of apu.h. It is renamed to + * apu.h at the start of a NetWare build. + */ +/* @file apu.h + * @brief APR-Utility main file + */ + +#ifdef NETWARE +#ifndef APU_H +#define APU_H +/** + * @defgroup APR_Util APR Utility Functions + * @{ + */ + + +/** + * APU_DECLARE_EXPORT is defined when building the APR-UTIL dynamic library, + * so that all public symbols are exported. + * + * APU_DECLARE_STATIC is defined when including the APR-UTIL public headers, + * to provide static linkage when the dynamic library may be unavailable. + * + * APU_DECLARE_STATIC and APU_DECLARE_EXPORT are left undefined when + * including the APR-UTIL public headers, to import and link the symbols from + * the dynamic APR-UTIL library and assure appropriate indirection and calling + * conventions at compile time. + */ + +/** + * The public APR-UTIL functions are declared with APU_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APU_DECLARE_NONSTD(). + * + * @fn APU_DECLARE(rettype) apr_func(args); + */ +#define APU_DECLARE(type) type +/** + * The public APR-UTIL functions using variable arguments are declared with + * APU_DECLARE_NONSTD(), as they must use the C language calling convention. + * + * @fn APU_DECLARE_NONSTD(rettype) apr_func(args, ...); + */ +#define APU_DECLARE_NONSTD(type) type +/** + * The public APR-UTIL variables are declared with APU_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * + * @fn APU_DECLARE_DATA type apr_variable; + * @note APU_DECLARE_DATA extern type apr_variable; syntax is required for + * declarations within headers to properly import the variable. + */ +#define APU_DECLARE_DATA + +/** + * Declare a dso module's exported module structure as APU_MODULE_DECLARE_DATA. + * + * Unless APU_MODULE_DECLARE_STATIC is defined at compile time, symbols + * declared with APU_MODULE_DECLARE_DATA are always exported. + * @code + * module APU_MODULE_DECLARE_DATA mod_tag + * @endcode + */ +#define APU_MODULE_DECLARE_DATA + +/* + * we always have SDBM (it's in our codebase) + */ +#define APU_HAVE_SDBM 1 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_GDBM 0 +#define APU_HAVE_NDBM 0 +#define APU_HAVE_DB 0 + +#if APU_HAVE_DB +#define APU_HAVE_DB_VERSION 0 +#endif +#endif + +/* + * we always enable dynamic driver loads within apr_dbd + */ +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_PGSQL 0 +#define APU_HAVE_MYSQL 0 +#define APU_HAVE_SQLITE3 0 +#define APU_HAVE_SQLITE2 0 +#define APU_HAVE_ORACLE 0 +#define APU_HAVE_ODBC 0 +#endif + +#define APU_HAVE_CRYPTO 0 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_OPENSSL 0 +#define APU_HAVE_NSS 0 +#define APU_HAVE_COMMONCRYPTO 0 +#endif + +#define APU_HAVE_APR_ICONV 0 +#define APU_HAVE_ICONV 1 +#define APR_HAS_XLATE (APU_HAVE_APR_ICONV || APU_HAVE_ICONV) + +#endif /* APU_H */ +#endif /* NETWARE */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/apu.hw b/c/dependencies/windows/apr/x86_debug/include/apu.hw new file mode 100644 index 00000000..a501d5d7 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apu.hw @@ -0,0 +1,146 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apu.h is duplicated from apu.hw at build time -- do not edit apu.h + */ +/* @file apu.h + * @brief APR-Utility main file + */ +/** + * @defgroup APR_Util APR Utility Functions + * @{ + */ + + +#ifndef APU_H +#define APU_H + +/** + * APU_DECLARE_EXPORT is defined when building the APR-UTIL dynamic library, + * so that all public symbols are exported. + * + * APU_DECLARE_STATIC is defined when including the APR-UTIL public headers, + * to provide static linkage when the dynamic library may be unavailable. + * + * APU_DECLARE_STATIC and APU_DECLARE_EXPORT are left undefined when + * including the APR-UTIL public headers, to import and link the symbols from + * the dynamic APR-UTIL library and assure appropriate indirection and calling + * conventions at compile time. + */ + +/* Make sure we have our platform identifier macro defined we ask for later. + */ +#if defined(_WIN32) && !defined(WIN32) +#define WIN32 1 +#endif + +#if defined(DOXYGEN) || !defined(WIN32) +/** + * The public APR-UTIL functions are declared with APU_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APU_DECLARE_NONSTD(). + * + * @fn APU_DECLARE(rettype) apr_func(args); + */ +#define APU_DECLARE(type) type +/** + * The public APR-UTIL functions using variable arguments are declared with + * APU_DECLARE_NONSTD(), as they must use the C language calling convention. + * + * @fn APU_DECLARE_NONSTD(rettype) apr_func(args, ...); + */ +#define APU_DECLARE_NONSTD(type) type +/** + * The public APR-UTIL variables are declared with APU_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * + * @fn APU_DECLARE_DATA type apr_variable; + * @note extern APU_DECLARE_DATA type apr_variable; syntax is required for + * declarations within headers to properly import the variable. + */ +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_STATIC) +#define APU_DECLARE(type) type __stdcall +#define APU_DECLARE_NONSTD(type) type __cdecl +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_EXPORT) +#define APU_DECLARE(type) __declspec(dllexport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllexport) +#else +#define APU_DECLARE(type) __declspec(dllimport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllimport) +#endif + +#if !defined(WIN32) || defined(APU_MODULE_DECLARE_STATIC) +/** + * Declare a dso module's exported module structure as APU_MODULE_DECLARE_DATA. + * + * Unless APU_MODULE_DECLARE_STATIC is defined at compile time, symbols + * declared with APU_MODULE_DECLARE_DATA are always exported. + * @code + * module APU_MODULE_DECLARE_DATA mod_tag + * @endcode + */ +#define APU_MODULE_DECLARE_DATA +#else +#define APU_MODULE_DECLARE_DATA __declspec(dllexport) +#endif + +/* + * we always have SDBM (it's in our codebase) + */ +#define APU_HAVE_SDBM 1 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_GDBM 0 +#define APU_HAVE_NDBM 0 +#define APU_HAVE_DB 0 + +#if APU_HAVE_DB +#define APU_HAVE_DB_VERSION 0 +#endif +#endif + +/* + * we always enable dynamic driver loads within apr_dbd + * Win32 always has odbc (it's always installed) + */ +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_PGSQL 0 +#define APU_HAVE_MYSQL 0 +#define APU_HAVE_SQLITE3 0 +#define APU_HAVE_SQLITE2 0 +#define APU_HAVE_ORACLE 0 +#define APU_HAVE_ODBC 1 +#endif + +#define APU_HAVE_CRYPTO 0 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_OPENSSL 0 +#define APU_HAVE_NSS 0 +#define APU_HAVE_COMMONCRYPTO 0 +#endif + +#define APU_HAVE_APR_ICONV 1 +#define APU_HAVE_ICONV 0 +#define APR_HAS_XLATE (APU_HAVE_APR_ICONV || APU_HAVE_ICONV) + +#endif /* APU_H */ +/** @} */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apu.hwc b/c/dependencies/windows/apr/x86_debug/include/apu.hwc new file mode 100644 index 00000000..a663ec3e --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apu.hwc @@ -0,0 +1,145 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * apu.h is duplicated from apu.hwc at build time -- do not edit apu.h + */ +/* @file apu.h + * @brief APR-Utility main file + */ +/** + * @defgroup APR_Util APR Utility Functions + * @{ + */ + + +#ifndef APU_H +#define APU_H + +/** + * APU_DECLARE_EXPORT is defined when building the APR-UTIL dynamic library, + * so that all public symbols are exported. + * + * APU_DECLARE_STATIC is defined when including the APR-UTIL public headers, + * to provide static linkage when the dynamic library may be unavailable. + * + * APU_DECLARE_STATIC and APU_DECLARE_EXPORT are left undefined when + * including the APR-UTIL public headers, to import and link the symbols from + * the dynamic APR-UTIL library and assure appropriate indirection and calling + * conventions at compile time. + */ + +/* Make sure we have our platform identifier macro defined we ask for later. + */ +#if defined(_WIN32) && !defined(WIN32) +#define WIN32 1 +#endif + +#if defined(DOXYGEN) || !defined(WIN32) +/** + * The public APR-UTIL functions are declared with APU_DECLARE(), so they may + * use the most appropriate calling convention. Public APR functions with + * variable arguments must use APU_DECLARE_NONSTD(). + * + * @fn APU_DECLARE(rettype) apr_func(args); + */ +#define APU_DECLARE(type) type +/** + * The public APR-UTIL functions using variable arguments are declared with + * APU_DECLARE_NONSTD(), as they must use the C language calling convention. + * + * @fn APU_DECLARE_NONSTD(rettype) apr_func(args, ...); + */ +#define APU_DECLARE_NONSTD(type) type +/** + * The public APR-UTIL variables are declared with APU_DECLARE_DATA. + * This assures the appropriate indirection is invoked at compile time. + * + * @fn APU_DECLARE_DATA type apr_variable; + * @note extern APU_DECLARE_DATA type apr_variable; syntax is required for + * declarations within headers to properly import the variable. + */ +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_STATIC) +#define APU_DECLARE(type) type __stdcall +#define APU_DECLARE_NONSTD(type) type __cdecl +#define APU_DECLARE_DATA +#elif defined(APU_DECLARE_EXPORT) +#define APU_DECLARE(type) __declspec(dllexport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllexport) +#else +#define APU_DECLARE(type) __declspec(dllimport) type __stdcall +#define APU_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl +#define APU_DECLARE_DATA __declspec(dllimport) +#endif + +#if !defined(WIN32) || defined(APU_MODULE_DECLARE_STATIC) +/** + * Declare a dso module's exported module structure as APU_MODULE_DECLARE_DATA. + * + * Unless APU_MODULE_DECLARE_STATIC is defined at compile time, symbols + * declared with APU_MODULE_DECLARE_DATA are always exported. + * @code + * module APU_MODULE_DECLARE_DATA mod_tag + * @endcode + */ +#define APU_MODULE_DECLARE_DATA +#else +#define APU_MODULE_DECLARE_DATA __declspec(dllexport) +#endif + +/* + * we always have SDBM (it's in our codebase) + */ +#define APU_HAVE_SDBM 1 + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_GDBM 0 +#define APU_HAVE_NDBM 0 +#define APU_HAVE_DB 0 + +#if APU_HAVE_DB +#define APU_HAVE_DB_VERSION 0 +#endif +#endif + +/* + * we always enable dynamic driver loads within apr_dbd + * Win32 always has odbc (it's always installed) + */ +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_PGSQL 0 +#define APU_HAVE_MYSQL 0 +#define APU_HAVE_SQLITE3 0 +#define APU_HAVE_SQLITE2 0 +#define APU_HAVE_ORACLE 0 +#define APU_HAVE_ODBC 1 +#endif + +#define APU_HAVE_CRYPTO @apu_have_crypto_10@ + +#ifndef APU_DSO_MODULE_BUILD +#define APU_HAVE_OPENSSL 0 +#define APU_HAVE_NSS 0 +#endif + +#define APU_HAVE_APR_ICONV @apu_have_apr_iconv_10@ +#define APU_HAVE_ICONV 0 +#define APR_HAS_XLATE (APU_HAVE_APR_ICONV || APU_HAVE_ICONV) + +#endif /* APU_H */ +/** @} */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apu_errno.h b/c/dependencies/windows/apr/x86_debug/include/apu_errno.h new file mode 100644 index 00000000..c0a8ec7d --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apu_errno.h @@ -0,0 +1,173 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APU_ERRNO_H +#define APU_ERRNO_H + +/** + * @file apu_errno.h + * @brief APR-Util Error Codes + */ + +#include "apr.h" +#include "apr_errno.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + * @defgroup apu_errno Error Codes + * @ingroup APR_Util + * @{ + */ + +/** + * @defgroup APR_Util_Error APR_Util Error Values + *
+ * APU ERROR VALUES
+ * APR_ENOKEY         The key provided was empty or NULL
+ * APR_ENOIV          The initialisation vector provided was NULL
+ * APR_EKEYTYPE       The key type was not recognised
+ * APR_ENOSPACE       The buffer supplied was not big enough
+ * APR_ECRYPT         An error occurred while encrypting or decrypting
+ * APR_EPADDING       Padding was not supported
+ * APR_EKEYLENGTH     The key length was incorrect
+ * APR_ENOCIPHER      The cipher provided was not recognised
+ * APR_ENODIGEST      The digest provided was not recognised
+ * APR_ENOENGINE      The engine provided was not recognised
+ * APR_EINITENGINE    The engine could not be initialised
+ * APR_EREINIT        Underlying crypto has already been initialised
+ * 
+ * + *
+ * APR STATUS VALUES
+ * APR_INCHILD        Program is currently executing in the child
+ * 
+ * @{ + */ +/** @see APR_STATUS_IS_ENOKEY */ +#define APR_ENOKEY (APR_UTIL_START_STATUS + 1) +/** @see APR_STATUS_IS_ENOIV */ +#define APR_ENOIV (APR_UTIL_START_STATUS + 2) +/** @see APR_STATUS_IS_EKEYTYPE */ +#define APR_EKEYTYPE (APR_UTIL_START_STATUS + 3) +/** @see APR_STATUS_IS_ENOSPACE */ +#define APR_ENOSPACE (APR_UTIL_START_STATUS + 4) +/** @see APR_STATUS_IS_ECRYPT */ +#define APR_ECRYPT (APR_UTIL_START_STATUS + 5) +/** @see APR_STATUS_IS_EPADDING */ +#define APR_EPADDING (APR_UTIL_START_STATUS + 6) +/** @see APR_STATUS_IS_EKEYLENGTH */ +#define APR_EKEYLENGTH (APR_UTIL_START_STATUS + 7) +/** @see APR_STATUS_IS_ENOCIPHER */ +#define APR_ENOCIPHER (APR_UTIL_START_STATUS + 8) +/** @see APR_STATUS_IS_ENODIGEST */ +#define APR_ENODIGEST (APR_UTIL_START_STATUS + 9) +/** @see APR_STATUS_IS_ENOENGINE */ +#define APR_ENOENGINE (APR_UTIL_START_STATUS + 10) +/** @see APR_STATUS_IS_EINITENGINE */ +#define APR_EINITENGINE (APR_UTIL_START_STATUS + 11) +/** @see APR_STATUS_IS_EREINIT */ +#define APR_EREINIT (APR_UTIL_START_STATUS + 12) +/** @} */ + +/** + * @defgroup APU_STATUS_IS Status Value Tests + * @warning For any particular error condition, more than one of these tests + * may match. This is because platform-specific error codes may not + * always match the semantics of the POSIX codes these tests (and the + * corresponding APR error codes) are named after. A notable example + * are the APR_STATUS_IS_ENOENT and APR_STATUS_IS_ENOTDIR tests on + * Win32 platforms. The programmer should always be aware of this and + * adjust the order of the tests accordingly. + * @{ + */ + +/** @} */ + +/** + * @addtogroup APR_Util_Error + * @{ + */ +/** + * The key was empty or not provided + */ +#define APR_STATUS_IS_ENOKEY(s) ((s) == APR_ENOKEY) +/** + * The initialisation vector was not provided + */ +#define APR_STATUS_IS_ENOIV(s) ((s) == APR_ENOIV) +/** + * The key type was not recognised + */ +#define APR_STATUS_IS_EKEYTYPE(s) ((s) == APR_EKEYTYPE) +/** + * The buffer provided was not big enough + */ +#define APR_STATUS_IS_ENOSPACE(s) ((s) == APR_ENOSPACE) +/** + * An error occurred while encrypting or decrypting + */ +#define APR_STATUS_IS_ECRYPT(s) ((s) == APR_ECRYPT) +/** + * An error occurred while padding + */ +#define APR_STATUS_IS_EPADDING(s) ((s) == APR_EPADDING) +/** + * An error occurred with the key length + */ +#define APR_STATUS_IS_EKEYLENGTH(s) ((s) == APR_EKEYLENGTH) +/** + * The cipher provided was not recognised + */ +#define APR_STATUS_IS_ENOCIPHER(s) ((s) == APR_ENOCIPHER) +/** + * The digest provided was not recognised + */ +#define APR_STATUS_IS_ENODIGEST(s) ((s) == APR_ENODIGEST) +/** + * The engine provided was not recognised + */ +#define APR_STATUS_IS_ENOENGINE(s) ((s) == APR_ENOENGINE) +/** + * The engine could not be initialised + */ +#define APR_STATUS_IS_EINITENGINE(s) ((s) == APR_EINITENGINE) +/** + * Crypto has already been initialised + */ +#define APR_STATUS_IS_EREINIT(s) ((s) == APR_EREINIT) +/** @} */ + +/** + * This structure allows the underlying API error codes to be returned + * along with plain text error messages that explain to us mere mortals + * what really happened. + */ +typedef struct apu_err_t { + const char *reason; + const char *msg; + int rc; +} apu_err_t; + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! APU_ERRNO_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apu_version.h b/c/dependencies/windows/apr/x86_debug/include/apu_version.h new file mode 100644 index 00000000..e4fb2e64 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apu_version.h @@ -0,0 +1,139 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APU_VERSION_H +#define APU_VERSION_H + +/** + * @file apu_version.h + * @brief APR-util Versioning Interface + * + * APR-util's Version + * + * There are several different mechanisms for accessing the version. There + * is a string form, and a set of numbers; in addition, there are constants + * which can be compiled into your application, and you can query the library + * being used for its actual version. + * + * Note that it is possible for an application to detect that it has been + * compiled against a different version of APU by use of the compile-time + * constants and the use of the run-time query function. + * + * APU version numbering follows the guidelines specified in: + * + * http://apr.apache.org/versioning.html + */ + + +#define APU_COPYRIGHT "Copyright (c) 2000-2016 The Apache Software " \ + "Foundation or its licensors, as applicable." + +/* The numeric compile-time version constants. These constants are the + * authoritative version numbers for APU. + */ + +/** major version + * Major API changes that could cause compatibility problems for older + * programs such as structure size changes. No binary compatibility is + * possible across a change in the major version. + */ +#define APU_MAJOR_VERSION 1 + +/** minor version + * Minor API changes that do not cause binary compatibility problems. + * Reset to 0 when upgrading APU_MAJOR_VERSION + */ +#define APU_MINOR_VERSION 6 + +/** patch level + * The Patch Level never includes API changes, simply bug fixes. + * Reset to 0 when upgrading APR_MINOR_VERSION + */ +#define APU_PATCH_VERSION 1 + +/** + * The symbol APU_IS_DEV_VERSION is only defined for internal, + * "development" copies of APU. It is undefined for released versions + * of APU. + */ +/* #undef APU_IS_DEV_VERSION */ + + +#if defined(APU_IS_DEV_VERSION) || defined(DOXYGEN) +/** Internal: string form of the "is dev" flag */ +#ifndef APU_IS_DEV_STRING +#define APU_IS_DEV_STRING "-dev" +#endif +#else +#define APU_IS_DEV_STRING "" +#endif + + +#ifndef APU_STRINGIFY +/** Properly quote a value as a string in the C preprocessor */ +#define APU_STRINGIFY(n) APU_STRINGIFY_HELPER(n) +/** Helper macro for APU_STRINGIFY */ +#define APU_STRINGIFY_HELPER(n) #n +#endif + +/** The formatted string of APU's version */ +#define APU_VERSION_STRING \ + APU_STRINGIFY(APU_MAJOR_VERSION) "." \ + APU_STRINGIFY(APU_MINOR_VERSION) "." \ + APU_STRINGIFY(APU_PATCH_VERSION) \ + APU_IS_DEV_STRING + +/** An alternative formatted string of APR's version */ +/* macro for Win32 .rc files using numeric csv representation */ +#define APU_VERSION_STRING_CSV APU_MAJOR_VERSION ##, \ + ##APU_MINOR_VERSION ##, \ + ##APU_PATCH_VERSION + + +#ifndef APU_VERSION_ONLY + +/* The C language API to access the version at run time, + * as opposed to compile time. APU_VERSION_ONLY may be defined + * externally when preprocessing apr_version.h to obtain strictly + * the C Preprocessor macro declarations. + */ + +#include "apr_version.h" + +#include "apu.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Return APR-util's version information information in a numeric form. + * + * @param pvsn Pointer to a version structure for returning the version + * information. + */ +APU_DECLARE(void) apu_version(apr_version_t *pvsn); + +/** Return APU's version information as a string. */ +APU_DECLARE(const char *) apu_version_string(void); + +#ifdef __cplusplus +} +#endif + +#endif /* ndef APU_VERSION_ONLY */ + +#endif /* ndef APU_VERSION_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apu_want.h b/c/dependencies/windows/apr/x86_debug/include/apu_want.h new file mode 100644 index 00000000..8bb56ce7 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apu_want.h @@ -0,0 +1,52 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apu.h" /* configuration data */ + +/** + * @file apu_want.h + * @brief APR Standard Headers Support + * + *
+ * Features:
+ *
+ *   APU_WANT_DB:       
+ *
+ * Typical usage:
+ *
+ *   #define APU_WANT_DB
+ *   #include "apu_want.h"
+ *
+ * The appropriate headers will be included.
+ *
+ * Note: it is safe to use this in a header (it won't interfere with other
+ *       headers' or source files' use of apu_want.h)
+ * 
+ */ + +/* --------------------------------------------------------------------- */ + +#ifdef APU_WANT_DB + +#if APU_HAVE_DB +/* win32 note.. you will need to change this for db1 */ +#include +#endif + +#undef APU_WANT_DB +#endif + +/* --------------------------------------------------------------------- */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apu_want.h.in b/c/dependencies/windows/apr/x86_debug/include/apu_want.h.in new file mode 100644 index 00000000..81297a75 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apu_want.h.in @@ -0,0 +1,51 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apu.h" /* configuration data */ + +/** + * @file apu_want.h + * @brief APR Standard Headers Support + * + *
+ * Features:
+ *
+ *   APU_WANT_DB:       <@apu_db_header@>
+ *
+ * Typical usage:
+ *
+ *   #define APU_WANT_DB
+ *   #include "apu_want.h"
+ *
+ * The appropriate headers will be included.
+ *
+ * Note: it is safe to use this in a header (it won't interfere with other
+ *       headers' or source files' use of apu_want.h)
+ * 
+ */ + +/* --------------------------------------------------------------------- */ + +#ifdef APU_WANT_DB + +#if APU_HAVE_DB +#include <@apu_db_header@> +#endif + +#undef APU_WANT_DB +#endif + +/* --------------------------------------------------------------------- */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apu_want.hnw b/c/dependencies/windows/apr/x86_debug/include/apu_want.hnw new file mode 100644 index 00000000..5d6edd3c --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apu_want.hnw @@ -0,0 +1,52 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apu.h" /* configuration data */ + +/** + * @file apu_want.h + * @brief APR Standard Headers Support + * + *
+ * Features:
+ *
+ *   APU_WANT_DB:       <@apu_db_header>
+ *
+ * Typical usage:
+ *
+ *   #define APU_WANT_DB
+ *   #include "apu_want.h"
+ *
+ * The appropriate headers will be included.
+ *
+ * Note: it is safe to use this in a header (it won't interfere with other
+ *       headers' or source files' use of apu_want.h)
+ * 
+ */ + +/* --------------------------------------------------------------------- */ + +#ifdef APU_WANT_DB + +#if APU_HAVE_DB +/* win32 note.. you will need to change this for db1 */ +#include +#endif + +#undef APU_WANT_DB +#endif + +/* --------------------------------------------------------------------- */ diff --git a/c/dependencies/windows/apr/x86_debug/include/apu_want.hw b/c/dependencies/windows/apr/x86_debug/include/apu_want.hw new file mode 100644 index 00000000..03b6ea98 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/apu_want.hw @@ -0,0 +1,52 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apu.h" /* configuration data */ + +/** + * @file apu_want.h + * @brief APR Standard Headers Support + * + *
+ * Features:
+ *
+ *   APU_WANT_DB:       
+ *
+ * Typical usage:
+ *
+ *   #define APU_WANT_DB
+ *   #include "apu_want.h"
+ *
+ * The appropriate headers will be included.
+ *
+ * Note: it is safe to use this in a header (it won't interfere with other
+ *       headers' or source files' use of apu_want.h)
+ * 
+ */ + +/* --------------------------------------------------------------------- */ + +#ifdef APU_WANT_DB + +#if APU_HAVE_DB +/* win32 note.. you will need to change this for db1 */ +#include +#endif + +#undef APU_WANT_DB +#endif + +/* --------------------------------------------------------------------- */ diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/aix/apr_arch_dso.h b/c/dependencies/windows/apr/x86_debug/include/arch/aix/apr_arch_dso.h new file mode 100644 index 00000000..d1cac684 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/aix/apr_arch_dso.h @@ -0,0 +1,41 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_dso.h" +#include "apr.h" + +#if APR_HAS_DSO + +void *dlopen(const char *path, int mode); +void *dlsym(void *handle, const char *symbol); +const char *dlerror(void); +int dlclose(void *handle); + +struct apr_dso_handle_t { + apr_pool_t *pool; + void *handle; + const char *errormsg; +}; + +#endif + +#endif diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/apr_private_common.h b/c/dependencies/windows/apr/x86_debug/include/arch/apr_private_common.h new file mode 100644 index 00000000..ec850c65 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/apr_private_common.h @@ -0,0 +1,41 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * This file contains private declarations common to all architectures. + */ + +#ifndef APR_PRIVATE_COMMON_H +#define APR_PRIVATE_COMMON_H + +#include "apr_pools.h" +#include "apr_tables.h" + +apr_status_t apr_filepath_list_split_impl(apr_array_header_t **pathelts, + const char *liststr, + char separator, + apr_pool_t *p); + +apr_status_t apr_filepath_list_merge_impl(char **liststr, + apr_array_header_t *pathelts, + char separator, + apr_pool_t *p); + +/* temporary defines to handle 64bit compile mismatches */ +#define APR_INT_TRUNC_CAST int +#define APR_UINT32_TRUNC_CAST apr_uint32_t + +#endif /*APR_PRIVATE_COMMON_H*/ diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/beos/apr_arch_dso.h b/c/dependencies/windows/apr/x86_debug/include/arch/beos/apr_arch_dso.h new file mode 100644 index 00000000..fbc5c2ff --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/beos/apr_arch_dso.h @@ -0,0 +1,41 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_errno.h" +#include "apr_dso.h" +#include "apr.h" +#include +#include + +#if APR_HAS_DSO + +struct apr_dso_handle_t { + image_id handle; /* Handle to the DSO loaded */ + apr_pool_t *pool; + const char *errormsg; /* if the load fails, we have an error + * message here :) + */ +}; + +#endif + +#endif diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/beos/apr_arch_proc_mutex.h b/c/dependencies/windows/apr/x86_debug/include/arch/beos/apr_arch_proc_mutex.h new file mode 100644 index 00000000..c60d8c62 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/beos/apr_arch_proc_mutex.h @@ -0,0 +1,36 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PROC_MUTEX_H +#define PROC_MUTEX_H + +#include "apr_pools.h" +#include "apr_proc_mutex.h" +#include "apr_file_io.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_portable.h" + +struct apr_proc_mutex_t { + apr_pool_t *pool; + + /* Our lock :) */ + sem_id Lock; + int32 LockCount; +}; + +#endif /* PROC_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/beos/apr_arch_thread_cond.h b/c/dependencies/windows/apr/x86_debug/include/arch/beos/apr_arch_thread_cond.h new file mode 100644 index 00000000..c9420b53 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/beos/apr_arch_thread_cond.h @@ -0,0 +1,46 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_COND_H +#define THREAD_COND_H + +#include +#include "apr_pools.h" +#include "apr_thread_cond.h" +#include "apr_file_io.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_portable.h" +#include "apr_ring.h" + +struct waiter_t { + APR_RING_ENTRY(waiter_t) link; + sem_id sem; +}; + +struct apr_thread_cond_t { + apr_pool_t *pool; + sem_id lock; + apr_thread_mutex_t *condlock; + thread_id owner; + /* active list */ + APR_RING_HEAD(active_list, waiter_t) alist; + /* free list */ + APR_RING_HEAD(free_list, waiter_t) flist; +}; + +#endif /* THREAD_COND_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/beos/apr_arch_thread_mutex.h b/c/dependencies/windows/apr/x86_debug/include/arch/beos/apr_arch_thread_mutex.h new file mode 100644 index 00000000..bb7d4ae8 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/beos/apr_arch_thread_mutex.h @@ -0,0 +1,42 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_MUTEX_H +#define THREAD_MUTEX_H + +#include +#include "apr_pools.h" +#include "apr_thread_mutex.h" +#include "apr_file_io.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_portable.h" + +struct apr_thread_mutex_t { + apr_pool_t *pool; + + /* Our lock :) */ + sem_id Lock; + int32 LockCount; + + /* If we nest locks we need these... */ + int nested; + apr_os_thread_t owner; + int owner_ref; +}; + +#endif /* THREAD_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/beos/apr_arch_thread_rwlock.h b/c/dependencies/windows/apr/x86_debug/include/arch/beos/apr_arch_thread_rwlock.h new file mode 100644 index 00000000..694b0d50 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/beos/apr_arch_thread_rwlock.h @@ -0,0 +1,45 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_RWLOCK_H +#define THREAD_RWLOCK_H + +#include +#include "apr_pools.h" +#include "apr_thread_rwlock.h" +#include "apr_file_io.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_portable.h" + +struct apr_thread_rwlock_t { + apr_pool_t *pool; + + /* Our lock :) */ + sem_id Lock; + int32 LockCount; + /* Read/Write lock stuff */ + sem_id Read; + int32 ReadCount; + sem_id Write; + int32 WriteCount; + int32 Nested; + + thread_id writer; +}; + +#endif /* THREAD_RWLOCK_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/beos/apr_arch_threadproc.h b/c/dependencies/windows/apr/x86_debug/include/arch/beos/apr_arch_threadproc.h new file mode 100644 index 00000000..13de0536 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/beos/apr_arch_threadproc.h @@ -0,0 +1,95 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr_thread_proc.h" +#include "apr_arch_file_io.h" +#include "apr_file_io.h" +#include "apr_thread_proc.h" +#include "apr_general.h" +#include "apr_portable.h" +#include +#include +#include +#include +#include + +#ifndef THREAD_PROC_H +#define THREAD_PROC_H + +#define SHELL_PATH "/bin/sh" + +#define PTHREAD_CANCEL_AYNCHRONOUS CANCEL_ASYNCH; +#define PTHREAD_CANCEL_DEFERRED CANCEL_DEFER; + +#define PTHREAD_CANCEL_ENABLE CANCEL_ENABLE; +#define PTHREAD_CANCEL_DISABLE CANCEL_DISABLE; + +#define BEOS_MAX_DATAKEYS 128 + +struct apr_thread_t { + apr_pool_t *pool; + thread_id td; + void *data; + apr_thread_start_t func; + apr_status_t exitval; +}; + +struct apr_threadattr_t { + apr_pool_t *pool; + int32 attr; + int detached; + int joinable; +}; + +struct apr_threadkey_t { + apr_pool_t *pool; + int32 key; +}; + +struct beos_private_data { + const void ** data; + int count; + volatile thread_id td; +}; + +struct beos_key { + int assigned; + int count; + sem_id lock; + int32 ben_lock; + void (* destructor) (void *); +}; + +struct apr_procattr_t { + apr_pool_t *pool; + apr_file_t *parent_in; + apr_file_t *child_in; + apr_file_t *parent_out; + apr_file_t *child_out; + apr_file_t *parent_err; + apr_file_t *child_err; + char *currdir; + apr_int32_t cmdtype; + apr_int32_t detached; +}; + +struct apr_thread_once_t { + sem_id sem; + int hit; +}; + +#endif /* ! THREAD_PROC_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_dso.h b/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_dso.h new file mode 100644 index 00000000..ea0fe8c2 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_dso.h @@ -0,0 +1,43 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_dso.h" +#include "apr.h" + +#include + +typedef struct sym_list sym_list; + +struct sym_list { + sym_list *next; + char *symbol; +}; + +struct apr_dso_handle_t { + apr_pool_t *pool; + void *handle; + const char *errormsg; + sym_list *symbols; + char *path; +}; + +#endif diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_file_io.h b/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_file_io.h new file mode 100644 index 00000000..8bd2a72c --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_file_io.h @@ -0,0 +1,176 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FILE_IO_H +#define FILE_IO_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_tables.h" +#include "apr_file_io.h" +#include "apr_file_info.h" +#include "apr_errno.h" +#include "apr_lib.h" +#include "apr_poll.h" + +/* System headers the file I/O library needs */ +#if APR_HAVE_FCNTL_H +#include +#endif +#if APR_HAVE_SYS_TYPES_H +#include +#endif +#if APR_HAVE_ERRNO_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#if APR_HAVE_STRINGS_H +#include +#endif +#if APR_HAVE_DIRENT_H +#include +#endif +#ifdef HAVE_SYS_STAT_H +#include +#endif +#if APR_HAVE_UNISTD_H +#include +#endif +#if APR_HAVE_STDIO_H +#include +#endif +#if APR_HAVE_STDLIB_H +#include +#endif +#if APR_HAVE_SYS_UIO_H +#include +#endif +#if APR_HAVE_SYS_TIME_H +#include +#endif + +#include + +/* End System headers */ + +#define APR_FILE_DEFAULT_BUFSIZE 4096 +/* For backwards compat */ +#define APR_FILE_BUFSIZE APR_FILE_DEFAULT_BUFSIZE + +#if APR_HAS_THREADS +#define file_lock(f) do { \ + if ((f)->thlock) \ + apr_thread_mutex_lock((f)->thlock); \ + } while (0) +#define file_unlock(f) do { \ + if ((f)->thlock) \ + apr_thread_mutex_unlock((f)->thlock); \ + } while (0) +#else +#define file_lock(f) do {} while (0) +#define file_unlock(f) do {} while (0) +#endif + +#if APR_HAS_LARGE_FILES +#define lseek(f,o,w) lseek64(f,o,w) +#define ftruncate(f,l) ftruncate64(f,l) +#endif + +typedef struct stat struct_stat; + +struct apr_file_t { + apr_pool_t *pool; + int filedes; + char *fname; + apr_int32_t flags; + int eof_hit; + int is_pipe; + apr_interval_time_t timeout; + int buffered; + enum {BLK_UNKNOWN, BLK_OFF, BLK_ON } blocking; + int ungetchar; /* Last char provided by an unget op. (-1 = no char)*/ + + /* if there is a timeout set, then this pollset is used */ + apr_pollset_t *pollset; + + /* Stuff for buffered mode */ + char *buffer; + apr_size_t bufpos; /* Read/Write position in buffer */ + apr_size_t bufsize; /* The buffer size */ + apr_off_t dataRead; /* amount of valid data read into buffer */ + int direction; /* buffer being used for 0 = read, 1 = write */ + apr_off_t filePtr; /* position in file of handle */ +#if APR_HAS_THREADS + struct apr_thread_mutex_t *thlock; +#endif +}; + +struct apr_dir_t { + apr_pool_t *pool; + char *dirname; + DIR *dirstruct; + struct dirent *entry; +}; + +typedef struct apr_stat_entry_t apr_stat_entry_t; + +struct apr_stat_entry_t { + struct stat info; + char *casedName; + apr_time_t expire; + NXPathCtx_t pathCtx; +}; + +#define MAX_SERVER_NAME 64 +#define MAX_VOLUME_NAME 64 +#define MAX_PATH_NAME 256 +#define MAX_FILE_NAME 256 + +#define DRIVE_ONLY 1 + +/* If the user passes d: vs. D: (or //mach/share vs. //MACH/SHARE), + * we need to fold the case to canonical form. This function is + * supposed to do so. + */ +apr_status_t filepath_root_case(char **rootpath, char *root, apr_pool_t *p); + +/* This function check to see of the given path includes a drive/volume + * specifier. If the _only_ parameter is set to DRIVE_ONLY then it + * check to see of the path only contains a drive/volume specifier and + * nothing else. + */ +apr_status_t filepath_has_drive(const char *rootpath, int only, apr_pool_t *p); + +/* This function compares the drive/volume specifiers for each given path. + * It returns zero if they match or non-zero if not. + */ +apr_status_t filepath_compare_drive(const char *path1, const char *path2, apr_pool_t *p); + +apr_status_t apr_unix_file_cleanup(void *); +apr_status_t apr_unix_child_file_cleanup(void *); + +mode_t apr_unix_perms2mode(apr_fileperms_t perms); +apr_fileperms_t apr_unix_mode2perms(mode_t mode); + +apr_status_t apr_file_flush_locked(apr_file_t *thefile); +apr_status_t apr_file_info_get_locked(apr_finfo_t *finfo, apr_int32_t wanted, + apr_file_t *thefile); + +#endif /* ! FILE_IO_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_global_mutex.h b/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_global_mutex.h new file mode 100644 index 00000000..4167d378 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_global_mutex.h @@ -0,0 +1,29 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GLOBAL_MUTEX_H +#define GLOBAL_MUTEX_H + +#include "apr_global_mutex.h" +#include "apr_thread_mutex.h" + +struct apr_global_mutex_t { + apr_pool_t *pool; + apr_thread_mutex_t *mutex; +}; + +#endif /* GLOBAL_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_internal_time.h b/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_internal_time.h new file mode 100644 index 00000000..59f10672 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_internal_time.h @@ -0,0 +1,26 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIME_INTERNAL_H +#define TIME_INTERNAL_H + +#include "apr.h" + +#define TZONE (*___timezone()) + +void apr_netware_setup_time(void); + +#endif /* TIME_INTERNAL_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_networkio.h b/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_networkio.h new file mode 100644 index 00000000..63f17abe --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_networkio.h @@ -0,0 +1,31 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETWORK_IO_H + +#ifdef USE_WINSOCK +/* Making sure that we include the correct networkio.h since the + the project file is configured to first look for headers in + arch/netware and then arch/unix. But in this specific case we + want arch/win32. +*/ +#include <../win32/apr_arch_networkio.h> +#else +#include <../unix/apr_arch_networkio.h> +#endif + +#endif /* ! NETWORK_IO_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_pre_nw.h b/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_pre_nw.h new file mode 100644 index 00000000..7380e118 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_pre_nw.h @@ -0,0 +1,57 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef __pre_nw__ +#define __pre_nw__ + +#include + +#ifndef __GNUC__ +#pragma precompile_target "precomp.mch" +#endif + +#define NETWARE + +#define N_PLAT_NLM + +#define FAR +#define far + +/* no-op for Codewarrior C compiler; a functions are cdecl + by default */ +#define cdecl + +/* if we have wchar_t enabled in C++, predefine this type to avoid + a conflict in Novell's header files */ +#ifndef __GNUC__ +#ifndef DOXYGEN +#if (__option(cplusplus) && __option(wchar_type)) +#define _WCHAR_T +#endif +#endif +#endif + +/* C9X defintion used by MSL C++ library */ +#define DECIMAL_DIG 17 + +/* some code may want to use the MS convention for long long */ +#ifndef __int64 +#define __int64 long long +#endif + +#endif + + + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_proc_mutex.h b/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_proc_mutex.h new file mode 100644 index 00000000..7a634c2e --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_proc_mutex.h @@ -0,0 +1,29 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PROC_MUTEX_H +#define PROC_MUTEX_H + +#include "apr_proc_mutex.h" +#include "apr_thread_mutex.h" + +struct apr_proc_mutex_t { + apr_pool_t *pool; + apr_thread_mutex_t *mutex; +}; + +#endif /* PROC_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_thread_cond.h b/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_thread_cond.h new file mode 100644 index 00000000..b11a5f86 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_thread_cond.h @@ -0,0 +1,29 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_COND_H +#define THREAD_COND_H + +#include "apr_thread_cond.h" +#include + +struct apr_thread_cond_t { + apr_pool_t *pool; + NXCond_t *cond; +}; + +#endif /* THREAD_COND_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_thread_mutex.h b/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_thread_mutex.h new file mode 100644 index 00000000..18702fc7 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_thread_mutex.h @@ -0,0 +1,32 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_MUTEX_H +#define THREAD_MUTEX_H + +#include "apr_thread_mutex.h" +#include "apr_thread_cond.h" +#include + +struct apr_thread_mutex_t { + apr_pool_t *pool; + NXMutex_t *mutex; + apr_thread_cond_t *cond; + int locked, num_waiters; +}; + +#endif /* THREAD_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_thread_rwlock.h b/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_thread_rwlock.h new file mode 100644 index 00000000..d2dbd42f --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_thread_rwlock.h @@ -0,0 +1,29 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_RWLOCK_H +#define THREAD_RWLOCK_H + +#include "apr_thread_rwlock.h" +#include + +struct apr_thread_rwlock_t { + apr_pool_t *pool; + NXRwLock_t *rwlock; +}; + +#endif /* THREAD_RWLOCK_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_threadproc.h b/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_threadproc.h new file mode 100644 index 00000000..2fee2c00 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_arch_threadproc.h @@ -0,0 +1,80 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" + +#include + +#ifndef THREAD_PROC_H +#define THREAD_PROC_H + +#define SHELL_PATH "" +#define APR_DEFAULT_STACK_SIZE 65536 + +struct apr_thread_t { + apr_pool_t *pool; + NXContext_t ctx; + NXThreadId_t td; + char *thread_name; + apr_int32_t cancel; + apr_int32_t cancel_how; + void *data; + apr_thread_start_t func; + apr_status_t exitval; +}; + +struct apr_threadattr_t { + apr_pool_t *pool; + apr_size_t stack_size; + apr_int32_t detach; + char *thread_name; +}; + +struct apr_threadkey_t { + apr_pool_t *pool; + NXKey_t key; +}; + +struct apr_procattr_t { + apr_pool_t *pool; + apr_file_t *parent_in; + apr_file_t *child_in; + apr_file_t *parent_out; + apr_file_t *child_out; + apr_file_t *parent_err; + apr_file_t *child_err; + char *currdir; + apr_int32_t cmdtype; + apr_int32_t detached; + apr_int32_t addrspace; +}; + +struct apr_thread_once_t { + unsigned long value; +}; + +/* +struct apr_proc_t { + apr_pool_t *pool; + pid_t pid; + apr_procattr_t *attr; +}; +*/ + +#endif /* ! THREAD_PROC_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_private.h b/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_private.h new file mode 100644 index 00000000..04f336de --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/netware/apr_private.h @@ -0,0 +1,205 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Note: + * This is the netware-specific autoconf-like config file + * which unix creates at ./configure time. + */ + +#ifdef NETWARE + +#ifndef APR_PRIVATE_H +#define APR_PRIVATE_H + +/* Pick up publicly advertised headers and symbols before the + * APR internal private headers and symbols + */ +#include + +/* Pick up privately consumed headers */ +#include + +/* Include alloca.h to get compiler-dependent defines */ +#include + +#include +#include +#include +#include +#include +#include +#include + +/* Use this section to define all of the HAVE_FOO_H + * that are required to build properly. + */ +#define HAVE_DLFCN_H 1 +#define HAVE_LIMITS_H 1 +#define HAVE_SIGNAL_H 1 +#define HAVE_STDDEF_H 1 +#define HAVE_STDLIB_H 1 +#ifndef USE_WINSOCK +#define HAVE_SYS_SELECT_H 1 +#define HAVE_WRITEV 1 +#endif +#define HAVE_SYS_STAT_H 1 +#define HAVE_SYS_MMAN_H 1 +#define HAVE_FCNTL_H 1 +#define HAVE_ICONV_H 1 +#define HAVE_UTIME_H 1 + +#define HAVE_STRICMP 1 +#define HAVE_STRNICMP 1 +#define HAVE_STRDUP 1 +#define HAVE_STRSTR 1 +#define HAVE_MEMCHR 1 +#define HAVE_CALLOC 1 +#define HAVE_UTIME 1 + +#define HAVE_GETENV 1 +#define HAVE_SETENV 1 +#define HAVE_UNSETENV 1 + +#define HAVE_WRITEV 1 + +#define HAVE_GETPASS_R 1 +/* + * Hack around older NDKs which have only the getpassword() function, + * a threadsafe, API-equivalent of getpass_r(). + */ +#if (CURRENT_NDK_THRESHOLD < 709060000) +#define getpass_r getpassword +#endif + +/*#define DSO_USE_DLFCN */ + +#ifdef NW_BUILD_IPV6 +#define HAVE_GETADDRINFO 1 +#define HAVE_GETNAMEINFO 1 +#endif + +/* 1 is used for SIGABRT on netware */ +/* 2 is used for SIGFPE on netware */ +/* 3 is used for SIGILL on netware */ +/* 4 is used for SIGINT on netware */ +/* 5 is used for SIGSEGV on netware */ +/* 6 is used for SIGTERM on netware */ +/* 7 is used for SIGPOLL on netware */ + +#if (CURRENT_NDK_THRESHOLD < 306030000) +#define SIGKILL 11 +#define SIGALRM 13 +#define SIGCHLD 14 +#define SIGCONT 15 +#define SIGHUP 16 +#define SIGPIPE 17 +#define SIGQUIT 18 +#define SIGSTOP 19 +#define SIGTSTP 20 +#define SIGTTIN 21 +#define SIGTTOU 22 +#define SIGUSR1 23 +#define SIGUSR2 24 +#endif + +#define SIGTRAP 25 +#define SIGIOT 26 +#define SIGSTKFLT 28 +#define SIGURG 29 +#define SIGXCPU 30 +#define SIGXFSZ 31 +#define SIGVTALRM 32 +#define SIGPROF 33 +#define SIGWINCH 34 +#define SIGIO 35 + +#if (CURRENT_NDK_THRESHOLD < 406230000) +#undef SA_NOCLDSTOP +#define SA_NOCLDSTOP 0x00000001 +#endif +#ifndef SIGBUS +#define SIGBUS SIGSEGV +#endif + +#define _getch getcharacter + +#define SIZEOF_SHORT 2 +#define SIZEOF_INT 4 +#define SIZEOF_LONGLONG 8 +#define SIZEOF_CHAR 1 +#define SIZEOF_SSIZE_T SIZEOF_INT + +void netware_pool_proc_cleanup(); + +/* NLM registration routines for managing which NLMs + are using the library. */ +int register_NLM(void *NLMHandle); +int unregister_NLM(void *NLMHandle); + +/* Application global data management */ +extern int gLibId; +extern void *gLibHandle; + +typedef struct app_data { + int initialized; + void* gPool; + void* gs_aHooksToSort; + void* gs_phOptionalHooks; + void* gs_phOptionalFunctions; + void* gs_nlmhandle; + rtag_t gs_startup_rtag; + rtag_t gs_socket_rtag; + rtag_t gs_lookup_rtag; + rtag_t gs_event_rtag; + rtag_t gs_pcp_rtag; + void* gs_ldap_xref_lock; + void* gs_xref_head; +} APP_DATA; + +int setGlobalPool(void *data); +void* getGlobalPool(); +int setStatCache(void *data); +void* getStatCache(); + +/* Redefine malloc to use the library malloc call so + that all of the memory resources will be owned + and can be shared by the library. */ +#undef malloc +#define malloc(x) library_malloc(gLibHandle,x) +#ifndef __MWERKS__ +#define _alloca alloca +#endif + +/* 64-bit integer conversion function */ +#define APR_INT64_STRFN strtoll + +#if APR_HAS_LARGE_FILES +#define APR_OFF_T_STRFN strtoll +#else +#define APR_OFF_T_STRFN strtol +#endif + +/* used to check DWORD overflow for 64bit compiles */ +#define APR_DWORD_MAX 0xFFFFFFFFUL + +/* + * Include common private declarations. + */ +#include "../apr_private_common.h" + +#endif /*APR_PRIVATE_H*/ +#endif /*NETWARE*/ diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_dso.h b/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_dso.h new file mode 100644 index 00000000..2bda6b7c --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_dso.h @@ -0,0 +1,37 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_dso.h" +#include "apr.h" + +#if APR_HAS_DSO + +struct apr_dso_handle_t { + apr_pool_t *cont; /* Context for returning error strings */ + HMODULE handle; /* Handle to the DSO loaded */ + apr_status_t load_error; + char *failed_module; +}; + +#endif + +#endif diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_file_io.h b/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_file_io.h new file mode 100644 index 00000000..79a57964 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_file_io.h @@ -0,0 +1,86 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FILE_IO_H +#define FILE_IO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_thread_mutex.h" +#include "apr_file_io.h" +#include "apr_file_info.h" +#include "apr_errno.h" +#include "apr_poll.h" + +/* We have an implementation of mkstemp but it's not very multi-threading + * friendly & is part of the POSIX emulation rather than native so don't + * use it. + */ +#undef HAVE_MKSTEMP + +#define APR_FILE_DEFAULT_BUFSIZE 4096 +#define APR_FILE_BUFSIZE APR_FILE_DEFAULT_BUFSIZE + +struct apr_file_t { + apr_pool_t *pool; + HFILE filedes; + char * fname; + int isopen; + int buffered; + int eof_hit; + apr_int32_t flags; + int timeout; + int pipe; + HEV pipeSem; + enum { BLK_UNKNOWN, BLK_OFF, BLK_ON } blocking; + + /* Stuff for buffered mode */ + char *buffer; + apr_size_t bufsize; /* Read/Write position in buffer */ + apr_size_t bufpos; /* Read/Write position in buffer */ + unsigned long dataRead; /* amount of valid data read into buffer */ + int direction; /* buffer being used for 0 = read, 1 = write */ + unsigned long filePtr; /* position in file of handle */ + apr_thread_mutex_t *mutex; /* mutex semaphore, must be owned to access + the above fields */ +}; + +struct apr_dir_t { + apr_pool_t *pool; + char *dirname; + ULONG handle; + FILEFINDBUF3 entry; + int validentry; +}; + +apr_status_t apr_file_cleanup(void *); +apr_status_t apr_os2_time_to_apr_time(apr_time_t *result, FDATE os2date, + FTIME os2time); +apr_status_t apr_apr_time_to_os2_time(FDATE *os2date, FTIME *os2time, + apr_time_t aprtime); + +/* see win32/fileio.h for description of these */ +extern const char c_is_fnchar[256]; + +#define IS_FNCHAR(c) c_is_fnchar[(unsigned char)c] + +apr_status_t filepath_root_test(char *path, apr_pool_t *p); +apr_status_t filepath_drive_get(char **rootpath, char drive, + apr_int32_t flags, apr_pool_t *p); +apr_status_t filepath_root_case(char **rootpath, char *root, apr_pool_t *p); + +#endif /* ! FILE_IO_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_inherit.h b/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_inherit.h new file mode 100644 index 00000000..494772ac --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_inherit.h @@ -0,0 +1,50 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INHERIT_H +#define INHERIT_H + +#include "apr_inherit.h" + +#define APR_INHERIT (1 << 24) /* Must not conflict with other bits */ + +#define APR_IMPLEMENT_INHERIT_SET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_set(apr_##name##_t *the##name) \ +{ \ + int rv; \ + ULONG state; \ + if (((rv = DosQueryFHState(attr->parent_err->filedes, &state)) \ + != 0) || \ + ((rv = DosSetFHState(attr->parent_err->filedes, \ + state & ~OPEN_FLAGS_NOINHERIT)) != 0)) \ + return APR_FROM_OS_ERROR(rv); \ + return APR_SUCCESS; \ +} + +#define APR_IMPLEMENT_INHERIT_UNSET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_unset(apr_##name##_t *the##name)\ +{ \ + int rv; \ + ULONG state; \ + if (((rv = DosQueryFHState(attr->parent_err->filedes, &state)) \ + != 0) || \ + ((rv = DosSetFHState(attr->parent_err->filedes, \ + state | OPEN_FLAGS_NOINHERIT)) != 0)) \ + return APR_FROM_OS_ERROR(rv); \ + return APR_SUCCESS; \ +} + +#endif /* ! INHERIT_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_networkio.h b/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_networkio.h new file mode 100644 index 00000000..10c6de81 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_networkio.h @@ -0,0 +1,76 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETWORK_IO_H +#define NETWORK_IO_H + +#include "apr_private.h" +#include "apr_network_io.h" +#include "apr_general.h" +#include "apr_arch_os2calls.h" +#include "apr_poll.h" + +#if APR_HAVE_NETDB_H +#include +#endif + +typedef struct sock_userdata_t sock_userdata_t; +struct sock_userdata_t { + sock_userdata_t *next; + const char *key; + void *data; +}; + +struct apr_socket_t { + apr_pool_t *pool; + int socketdes; + int type; + int protocol; + apr_sockaddr_t *local_addr; + apr_sockaddr_t *remote_addr; + apr_interval_time_t timeout; + int nonblock; + int local_port_unknown; + int local_interface_unknown; + int remote_addr_unknown; + apr_int32_t options; + apr_int32_t inherit; + sock_userdata_t *userdata; + + /* if there is a timeout set, then this pollset is used */ + apr_pollset_t *pollset; +}; + +/* Error codes returned from sock_errno() */ +#define SOCBASEERR 10000 +#define SOCEPERM (SOCBASEERR+1) /* Not owner */ +#define SOCESRCH (SOCBASEERR+3) /* No such process */ +#define SOCEINTR (SOCBASEERR+4) /* Interrupted system call */ +#define SOCENXIO (SOCBASEERR+6) /* No such device or address */ +#define SOCEBADF (SOCBASEERR+9) /* Bad file number */ +#define SOCEACCES (SOCBASEERR+13) /* Permission denied */ +#define SOCEFAULT (SOCBASEERR+14) /* Bad address */ +#define SOCEINVAL (SOCBASEERR+22) /* Invalid argument */ +#define SOCEMFILE (SOCBASEERR+24) /* Too many open files */ +#define SOCEPIPE (SOCBASEERR+32) /* Broken pipe */ +#define SOCEOS2ERR (SOCBASEERR+100) /* OS/2 Error */ + +const char *apr_inet_ntop(int af, const void *src, char *dst, apr_size_t size); +int apr_inet_pton(int af, const char *src, void *dst); +void apr_sockaddr_vars_set(apr_sockaddr_t *, int, apr_port_t); + +#endif /* ! NETWORK_IO_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_os2calls.h b/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_os2calls.h new file mode 100644 index 00000000..3c739bfd --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_os2calls.h @@ -0,0 +1,59 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr_errno.h" +#include +#include + +extern int (*apr_os2_socket)(int, int, int); +extern int (*apr_os2_select)(int *, int, int, int, long); +extern int (*apr_os2_sock_errno)(); +extern int (*apr_os2_accept)(int, struct sockaddr *, int *); +extern int (*apr_os2_bind)(int, struct sockaddr *, int); +extern int (*apr_os2_connect)(int, struct sockaddr *, int); +extern int (*apr_os2_getpeername)(int, struct sockaddr *, int *); +extern int (*apr_os2_getsockname)(int, struct sockaddr *, int *); +extern int (*apr_os2_getsockopt)(int, int, int, char *, int *); +extern int (*apr_os2_ioctl)(int, int, caddr_t, int); +extern int (*apr_os2_listen)(int, int); +extern int (*apr_os2_recv)(int, char *, int, int); +extern int (*apr_os2_send)(int, const char *, int, int); +extern int (*apr_os2_setsockopt)(int, int, int, char *, int); +extern int (*apr_os2_shutdown)(int, int); +extern int (*apr_os2_soclose)(int); +extern int (*apr_os2_writev)(int, struct iovec *, int); +extern int (*apr_os2_sendto)(int, const char *, int, int, const struct sockaddr *, int); +extern int (*apr_os2_recvfrom)(int, char *, int, int, struct sockaddr *, int *); + +#define socket apr_os2_socket +#define select apr_os2_select +#define sock_errno apr_os2_sock_errno +#define accept apr_os2_accept +#define bind apr_os2_bind +#define connect apr_os2_connect +#define getpeername apr_os2_getpeername +#define getsockname apr_os2_getsockname +#define getsockopt apr_os2_getsockopt +#define ioctl apr_os2_ioctl +#define listen apr_os2_listen +#define recv apr_os2_recv +#define send apr_os2_send +#define setsockopt apr_os2_setsockopt +#define shutdown apr_os2_shutdown +#define soclose apr_os2_soclose +#define writev apr_os2_writev +#define sendto apr_os2_sendto +#define recvfrom apr_os2_recvfrom diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_proc_mutex.h b/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_proc_mutex.h new file mode 100644 index 00000000..8caf3369 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_proc_mutex.h @@ -0,0 +1,31 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PROC_MUTEX_H +#define PROC_MUTEX_H + +#include "apr_proc_mutex.h" +#include "apr_file_io.h" + +struct apr_proc_mutex_t { + apr_pool_t *pool; + HMTX hMutex; + TID owner; + int lock_count; +}; + +#endif /* PROC_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_thread_cond.h b/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_thread_cond.h new file mode 100644 index 00000000..aa0a7ca6 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_thread_cond.h @@ -0,0 +1,33 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_COND_H +#define THREAD_COND_H + +#include "apr_thread_cond.h" +#include "apr_file_io.h" + +struct apr_thread_cond_t { + apr_pool_t *pool; + HEV semaphore; + HMTX mutex; + unsigned long num_waiting; + unsigned long num_wake; + unsigned long generation; +}; + +#endif /* THREAD_COND_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_thread_mutex.h b/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_thread_mutex.h new file mode 100644 index 00000000..3ae2a41d --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_thread_mutex.h @@ -0,0 +1,29 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_MUTEX_H +#define THREAD_MUTEX_H + +#include "apr_thread_mutex.h" +#include "apr_file_io.h" + +struct apr_thread_mutex_t { + apr_pool_t *pool; + HMTX hMutex; +}; + +#endif /* THREAD_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_thread_rwlock.h b/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_thread_rwlock.h new file mode 100644 index 00000000..7187d5cb --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_thread_rwlock.h @@ -0,0 +1,31 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_RWLOCK_H +#define THREAD_RWLOCK_H + +#include "apr_thread_rwlock.h" +#include "apr_file_io.h" + +struct apr_thread_rwlock_t { + apr_pool_t *pool; + int readers; + HMTX write_lock; + HEV read_done; +}; + +#endif /* THREAD_RWLOCK_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_threadproc.h b/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_threadproc.h new file mode 100644 index 00000000..c8017adb --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/os2/apr_arch_threadproc.h @@ -0,0 +1,67 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr_thread_proc.h" +#include "apr_file_io.h" + +#ifndef THREAD_PROC_H +#define THREAD_PROC_H + +#define APR_THREADATTR_DETACHED 1 + +#define SHELL_PATH "cmd.exe" +#define APR_THREAD_STACKSIZE 65536 + +struct apr_threadattr_t { + apr_pool_t *pool; + unsigned long attr; + apr_size_t stacksize; +}; + +struct apr_thread_t { + apr_pool_t *pool; + struct apr_threadattr_t *attr; + unsigned long tid; + apr_thread_start_t func; + void *data; + apr_status_t exitval; +}; + +struct apr_threadkey_t { + apr_pool_t *pool; + unsigned long *key; +}; + +struct apr_procattr_t { + apr_pool_t *pool; + apr_file_t *parent_in; + apr_file_t *child_in; + apr_file_t *parent_out; + apr_file_t *child_out; + apr_file_t *parent_err; + apr_file_t *child_err; + char *currdir; + apr_int32_t cmdtype; + apr_int32_t detached; +}; + +struct apr_thread_once_t { + unsigned long sem; + char hit; +}; + +#endif /* ! THREAD_PROC_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/os390/apr_arch_dso.h b/c/dependencies/windows/apr/x86_debug/include/arch/os390/apr_arch_dso.h new file mode 100644 index 00000000..4263297b --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/os390/apr_arch_dso.h @@ -0,0 +1,39 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_dso.h" +#include "apr.h" + +#if APR_HAS_DSO + +#include + +struct apr_dso_handle_t { + dllhandle *handle; /* Handle to the DSO loaded */ + int failing_errno; /* Don't save the buffer returned by + strerror(); it gets reused */ + apr_pool_t *pool; +}; + +#endif + +#endif diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_atomic.h b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_atomic.h new file mode 100644 index 00000000..559257de --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_atomic.h @@ -0,0 +1,53 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ATOMIC_H +#define ATOMIC_H + +#include "apr.h" +#include "apr_pools.h" +#include "apr_private.h" +#include "apr_atomic.h" + +#if defined(USE_ATOMICS_GENERIC) +/* noop */ +#elif HAVE_ATOMIC_BUILTINS +# define USE_ATOMICS_BUILTINS +#elif defined(SOLARIS2) && SOLARIS2 >= 10 +# define USE_ATOMICS_SOLARIS +# define NEED_ATOMICS_GENERIC64 +#elif defined(__GNUC__) && defined(__STRICT_ANSI__) +/* force use of generic atomics if building e.g. with -std=c89, which + * doesn't allow inline asm */ +# define USE_ATOMICS_GENERIC +#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) +# define USE_ATOMICS_IA32 +# define NEED_ATOMICS_GENERIC64 +#elif defined(__GNUC__) && (defined(__PPC__) || defined(__ppc__)) +# define USE_ATOMICS_PPC +# define NEED_ATOMICS_GENERIC64 +#elif defined(__GNUC__) && (defined(__s390__) || defined(__s390x__)) +# define USE_ATOMICS_S390 +# define NEED_ATOMICS_GENERIC64 +#else +# define USE_ATOMICS_GENERIC +#endif + +#if defined(USE_ATOMICS_GENERIC) || defined (NEED_ATOMICS_GENERIC64) +apr_status_t apr__atomic_generic64_init(apr_pool_t *p); +#endif + +#endif /* ATOMIC_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_dso.h b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_dso.h new file mode 100644 index 00000000..d82182d4 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_dso.h @@ -0,0 +1,63 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_dso.h" +#include "apr.h" + +#if APR_HAS_DSO + +#ifdef HAVE_MACH_O_DYLD_H +#include +#endif + +#ifdef HAVE_DLFCN_H +#include +#endif + +#ifdef HAVE_DL_H +#include +#endif + +#ifndef RTLD_NOW +#define RTLD_NOW 1 +#endif + +#ifndef RTLD_GLOBAL +#define RTLD_GLOBAL 0 +#endif + +#if (defined(__DragonFly__) ||\ + defined(__FreeBSD__) ||\ + defined(__OpenBSD__) ||\ + defined(__NetBSD__) ) && !defined(__ELF__) +#define DLSYM_NEEDS_UNDERSCORE +#endif + +struct apr_dso_handle_t { + apr_pool_t *pool; + void *handle; + const char *errormsg; +}; + +#endif + +#endif diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_file_io.h b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_file_io.h new file mode 100644 index 00000000..77a90917 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_file_io.h @@ -0,0 +1,174 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FILE_IO_H +#define FILE_IO_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_tables.h" +#include "apr_file_io.h" +#include "apr_file_info.h" +#include "apr_errno.h" +#include "apr_lib.h" +#include "apr_thread_mutex.h" +#ifndef WAITIO_USES_POLL +#include "apr_poll.h" +#endif + +/* System headers the file I/O library needs */ +#if APR_HAVE_FCNTL_H +#include +#endif +#if APR_HAVE_SYS_TYPES_H +#include +#endif +#if APR_HAVE_ERRNO_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#if APR_HAVE_STRINGS_H +#include +#endif +#if APR_HAVE_DIRENT_H +#include +#endif +#ifdef HAVE_SYS_STAT_H +#include +#endif +#if APR_HAVE_UNISTD_H +#include +#endif +#if APR_HAVE_STDIO_H +#include +#endif +#if APR_HAVE_STDLIB_H +#include +#endif +#if APR_HAVE_SYS_UIO_H +#include +#endif +#if APR_HAVE_SYS_TIME_H +#include +#endif +#ifdef BEOS +#include +#endif +/* Hunting down DEV_BSIZE if not from dirent.h, sys/stat.h etc */ +#ifdef HAVE_SYS_PARAM_H +#include +#endif + +#if BEOS_BONE +# ifndef BONE7 + /* prior to BONE/7 fd_set & select were defined in sys/socket.h */ +# include +# else + /* Be moved the fd_set stuff and also the FIONBIO definition... */ +# include +# endif +#endif +/* End System headers */ + +#define APR_FILE_DEFAULT_BUFSIZE 4096 +/* For backwards-compat */ +#define APR_FILE_BUFSIZE APR_FILE_DEFAULT_BUFSIZE + +struct apr_file_t { + apr_pool_t *pool; + int filedes; + char *fname; + apr_int32_t flags; + int eof_hit; + int is_pipe; + apr_interval_time_t timeout; + int buffered; + enum {BLK_UNKNOWN, BLK_OFF, BLK_ON } blocking; + int ungetchar; /* Last char provided by an unget op. (-1 = no char)*/ +#ifndef WAITIO_USES_POLL + /* if there is a timeout set, then this pollset is used */ + apr_pollset_t *pollset; +#endif + /* Stuff for buffered mode */ + char *buffer; + apr_size_t bufpos; /* Read/Write position in buffer */ + apr_size_t bufsize; /* The size of the buffer */ + unsigned long dataRead; /* amount of valid data read into buffer */ + int direction; /* buffer being used for 0 = read, 1 = write */ + apr_off_t filePtr; /* position in file of handle */ +#if APR_HAS_THREADS + struct apr_thread_mutex_t *thlock; +#endif +}; + +#if APR_HAS_THREADS +#define file_lock(f) do { \ + if ((f)->thlock) \ + apr_thread_mutex_lock((f)->thlock); \ + } while (0) +#define file_unlock(f) do { \ + if ((f)->thlock) \ + apr_thread_mutex_unlock((f)->thlock); \ + } while (0) +#else +#define file_lock(f) do {} while (0) +#define file_unlock(f) do {} while (0) +#endif + +#if APR_HAS_LARGE_FILES && defined(_LARGEFILE64_SOURCE) +#define stat(f,b) stat64(f,b) +#define lstat(f,b) lstat64(f,b) +#define fstat(f,b) fstat64(f,b) +#define lseek(f,o,w) lseek64(f,o,w) +#define ftruncate(f,l) ftruncate64(f,l) +typedef struct stat64 struct_stat; +#else +typedef struct stat struct_stat; +#endif + +/* readdir64_r is only used in specific cases: */ +#if APR_HAS_THREADS && defined(_POSIX_THREAD_SAFE_FUNCTIONS) \ + && !defined(READDIR_IS_THREAD_SAFE) && defined(HAVE_READDIR64_R) +#define APR_USE_READDIR64_R +#endif + +struct apr_dir_t { + apr_pool_t *pool; + char *dirname; + DIR *dirstruct; +#ifdef APR_USE_READDIR64_R + struct dirent64 *entry; +#else + struct dirent *entry; +#endif +}; + +apr_status_t apr_unix_file_cleanup(void *); +apr_status_t apr_unix_child_file_cleanup(void *); + +mode_t apr_unix_perms2mode(apr_fileperms_t perms); +apr_fileperms_t apr_unix_mode2perms(mode_t mode); + +apr_status_t apr_file_flush_locked(apr_file_t *thefile); +apr_status_t apr_file_info_get_locked(apr_finfo_t *finfo, apr_int32_t wanted, + apr_file_t *thefile); + + +#endif /* ! FILE_IO_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_global_mutex.h b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_global_mutex.h new file mode 100644 index 00000000..3add9ecf --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_global_mutex.h @@ -0,0 +1,37 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GLOBAL_MUTEX_H +#define GLOBAL_MUTEX_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_global_mutex.h" +#include "apr_arch_proc_mutex.h" +#include "apr_arch_thread_mutex.h" + +struct apr_global_mutex_t { + apr_pool_t *pool; + apr_proc_mutex_t *proc_mutex; +#if APR_HAS_THREADS + apr_thread_mutex_t *thread_mutex; +#endif /* APR_HAS_THREADS */ +}; + +#endif /* GLOBAL_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_inherit.h b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_inherit.h new file mode 100644 index 00000000..21543c1e --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_inherit.h @@ -0,0 +1,64 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INHERIT_H +#define INHERIT_H + +#include "apr_inherit.h" + +#define APR_INHERIT (1 << 24) /* Must not conflict with other bits */ + +#define APR_IMPLEMENT_INHERIT_SET(name, flag, pool, cleanup) \ +apr_status_t apr_##name##_inherit_set(apr_##name##_t *the##name) \ +{ \ + if (the##name->flag & APR_FOPEN_NOCLEANUP) \ + return APR_EINVAL; \ + if (!(the##name->flag & APR_INHERIT)) { \ + int flags = fcntl(the##name->name##des, F_GETFD); \ + if (flags == -1) \ + return errno; \ + flags &= ~(FD_CLOEXEC); \ + if (fcntl(the##name->name##des, F_SETFD, flags) == -1) \ + return errno; \ + the##name->flag |= APR_INHERIT; \ + apr_pool_child_cleanup_set(the##name->pool, \ + (void *)the##name, \ + cleanup, apr_pool_cleanup_null); \ + } \ + return APR_SUCCESS; \ +} + +#define APR_IMPLEMENT_INHERIT_UNSET(name, flag, pool, cleanup) \ +apr_status_t apr_##name##_inherit_unset(apr_##name##_t *the##name) \ +{ \ + if (the##name->flag & APR_FOPEN_NOCLEANUP) \ + return APR_EINVAL; \ + if (the##name->flag & APR_INHERIT) { \ + int flags; \ + if ((flags = fcntl(the##name->name##des, F_GETFD)) == -1) \ + return errno; \ + flags |= FD_CLOEXEC; \ + if (fcntl(the##name->name##des, F_SETFD, flags) == -1) \ + return errno; \ + the##name->flag &= ~APR_INHERIT; \ + apr_pool_child_cleanup_set(the##name->pool, \ + (void *)the##name, \ + cleanup, cleanup); \ + } \ + return APR_SUCCESS; \ +} + +#endif /* ! INHERIT_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_internal_time.h b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_internal_time.h new file mode 100644 index 00000000..6e12c674 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_internal_time.h @@ -0,0 +1,24 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIME_INTERNAL_H +#define TIME_INTERNAL_H + +#include "apr.h" + +void apr_unix_setup_time(void); + +#endif /* TIME_INTERNAL_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_misc.h b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_misc.h new file mode 100644 index 00000000..82351250 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_misc.h @@ -0,0 +1,67 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MISC_H +#define MISC_H + +#include "apr.h" +#include "apr_portable.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_getopt.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" +#include "apr_errno.h" +#include "apr_getopt.h" + +#if APR_HAVE_STDIO_H +#include +#endif +#if APR_HAVE_SIGNAL_H +#include +#endif +#if APR_HAVE_PTHREAD_H +#include +#endif + +#if APR_HAVE_STDLIB_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif + +#ifdef BEOS +#include +#endif + +struct apr_other_child_rec_t { + apr_pool_t *p; + struct apr_other_child_rec_t *next; + apr_proc_t *proc; + void (*maintenance) (int, void *, int); + void *data; + apr_os_file_t write_fd; +}; + +#if defined(WIN32) || defined(NETWARE) +#define WSAHighByte 2 +#define WSALowByte 0 +#endif + +#endif /* ! MISC_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_networkio.h b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_networkio.h new file mode 100644 index 00000000..5f3189d9 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_networkio.h @@ -0,0 +1,145 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETWORK_IO_H +#define NETWORK_IO_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_network_io.h" +#include "apr_errno.h" +#include "apr_general.h" +#include "apr_lib.h" +#ifndef WAITIO_USES_POLL +#include "apr_poll.h" +#endif + +/* System headers the network I/O library needs */ +#if APR_HAVE_SYS_TYPES_H +#include +#endif +#if APR_HAVE_SYS_UIO_H +#include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#endif +#if APR_HAVE_ERRNO_H +#include +#endif +#if APR_HAVE_SYS_TIME_H +#include +#endif +#if APR_HAVE_UNISTD_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#if APR_HAVE_NETINET_TCP_H +#include +#endif +#if APR_HAVE_NETINET_SCTP_UIO_H +#include +#endif +#if APR_HAVE_NETINET_SCTP_H +#include +#endif +#if APR_HAVE_NETINET_IN_H +#include +#endif +#if APR_HAVE_ARPA_INET_H +#include +#endif +#if APR_HAVE_SYS_SOCKET_H +#include +#endif +#if APR_HAVE_SYS_SOCKIO_H +#include +#endif +#if APR_HAVE_NETDB_H +#include +#endif +#if APR_HAVE_FCNTL_H +#include +#endif +#if APR_HAVE_SYS_SENDFILE_H +#include +#endif +#if APR_HAVE_SYS_IOCTL_H +#include +#endif +/* End System Headers */ + +#ifndef HAVE_POLLIN +#define POLLIN 1 +#define POLLPRI 2 +#define POLLOUT 4 +#define POLLERR 8 +#define POLLHUP 16 +#define POLLNVAL 32 +#endif + +typedef struct sock_userdata_t sock_userdata_t; +struct sock_userdata_t { + sock_userdata_t *next; + const char *key; + void *data; +}; + +struct apr_socket_t { + apr_pool_t *pool; + int socketdes; + int type; + int protocol; + apr_sockaddr_t *local_addr; + apr_sockaddr_t *remote_addr; + apr_interval_time_t timeout; +#ifndef HAVE_POLL + int connected; +#endif +#if APR_HAVE_SOCKADDR_UN + int bound; +#endif + int local_port_unknown; + int local_interface_unknown; + int remote_addr_unknown; + apr_int32_t options; + apr_int32_t inherit; + sock_userdata_t *userdata; +#ifndef WAITIO_USES_POLL + /* if there is a timeout set, then this pollset is used */ + apr_pollset_t *pollset; +#endif +}; + +const char *apr_inet_ntop(int af, const void *src, char *dst, apr_size_t size); +int apr_inet_pton(int af, const char *src, void *dst); +void apr_sockaddr_vars_set(apr_sockaddr_t *, int, apr_port_t); + +#define apr_is_option_set(skt, option) \ + (((skt)->options & (option)) == (option)) + +#define apr_set_option(skt, option, on) \ + do { \ + if (on) \ + (skt)->options |= (option); \ + else \ + (skt)->options &= ~(option); \ + } while (0) + +#endif /* ! NETWORK_IO_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_poll_private.h b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_poll_private.h new file mode 100644 index 00000000..ff813123 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_poll_private.h @@ -0,0 +1,189 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_ARCH_POLL_PRIVATE_H +#define APR_ARCH_POLL_PRIVATE_H + +#if HAVE_POLL_H +#include +#endif + +#if HAVE_SYS_POLL_H +#include +#endif + +#ifdef HAVE_PORT_CREATE +#include +#include +#endif + +#ifdef HAVE_KQUEUE +#include +#include +#include +#endif + +#ifdef HAVE_EPOLL +#include +#endif + +#ifdef NETWARE +#define HAS_SOCKETS(dt) (dt == APR_POLL_SOCKET) ? 1 : 0 +#define HAS_PIPES(dt) (dt == APR_POLL_FILE) ? 1 : 0 +#endif + +#if defined(HAVE_AIO_H) && defined(HAVE_AIO_MSGQ) +#define _AIO_OS390 /* enable a bunch of z/OS aio.h definitions */ +#include /* aiocb */ +#endif + +/* Choose the best method platform specific to use in apr_pollset */ +#ifdef HAVE_KQUEUE +#define POLLSET_USES_KQUEUE +#define POLLSET_DEFAULT_METHOD APR_POLLSET_KQUEUE +#elif defined(HAVE_PORT_CREATE) +#define POLLSET_USES_PORT +#define POLLSET_DEFAULT_METHOD APR_POLLSET_PORT +#elif defined(HAVE_EPOLL) +#define POLLSET_USES_EPOLL +#define POLLSET_DEFAULT_METHOD APR_POLLSET_EPOLL +#elif defined(HAVE_AIO_MSGQ) +#define POLLSET_USES_AIO_MSGQ +#define POLLSET_DEFAULT_METHOD APR_POLLSET_AIO_MSGQ +#elif defined(HAVE_POLL) +#define POLLSET_USES_POLL +#define POLLSET_DEFAULT_METHOD APR_POLLSET_POLL +#else +#define POLLSET_USES_SELECT +#define POLLSET_DEFAULT_METHOD APR_POLLSET_SELECT +#endif + +#ifdef WIN32 +#define POLL_USES_SELECT +#undef POLLSET_DEFAULT_METHOD +#define POLLSET_DEFAULT_METHOD APR_POLLSET_SELECT +#else +#ifdef HAVE_POLL +#define POLL_USES_POLL +#else +#define POLL_USES_SELECT +#endif +#endif + +#if defined(POLLSET_USES_KQUEUE) || defined(POLLSET_USES_EPOLL) || defined(POLLSET_USES_PORT) || defined(POLLSET_USES_AIO_MSGQ) + +#include "apr_ring.h" + +#if APR_HAS_THREADS +#include "apr_thread_mutex.h" +#define pollset_lock_rings() \ + if (pollset->flags & APR_POLLSET_THREADSAFE) \ + apr_thread_mutex_lock(pollset->p->ring_lock); +#define pollset_unlock_rings() \ + if (pollset->flags & APR_POLLSET_THREADSAFE) \ + apr_thread_mutex_unlock(pollset->p->ring_lock); +#else +#define pollset_lock_rings() +#define pollset_unlock_rings() +#endif + +typedef struct pfd_elem_t pfd_elem_t; + +struct pfd_elem_t { + APR_RING_ENTRY(pfd_elem_t) link; + apr_pollfd_t pfd; +#ifdef HAVE_PORT_CREATE + int on_query_ring; +#endif +}; + +#endif + +typedef struct apr_pollset_private_t apr_pollset_private_t; +typedef struct apr_pollset_provider_t apr_pollset_provider_t; +typedef struct apr_pollcb_provider_t apr_pollcb_provider_t; + +struct apr_pollset_t +{ + apr_pool_t *pool; + apr_uint32_t nelts; + apr_uint32_t nalloc; + apr_uint32_t flags; + /* Pipe descriptors used for wakeup */ + apr_file_t *wakeup_pipe[2]; + apr_pollfd_t wakeup_pfd; + apr_pollset_private_t *p; + const apr_pollset_provider_t *provider; +}; + +typedef union { +#if defined(HAVE_EPOLL) + struct epoll_event *epoll; +#endif +#if defined(HAVE_PORT_CREATE) + port_event_t *port; +#endif +#if defined(HAVE_KQUEUE) + struct kevent *ke; +#endif +#if defined(HAVE_POLL) + struct pollfd *ps; +#endif + void *undef; +} apr_pollcb_pset; + +struct apr_pollcb_t { + apr_pool_t *pool; + apr_uint32_t nelts; + apr_uint32_t nalloc; + apr_uint32_t flags; + /* Pipe descriptors used for wakeup */ + apr_file_t *wakeup_pipe[2]; + apr_pollfd_t wakeup_pfd; + int fd; + apr_pollcb_pset pollset; + apr_pollfd_t **copyset; + const apr_pollcb_provider_t *provider; +}; + +struct apr_pollset_provider_t { + apr_status_t (*create)(apr_pollset_t *, apr_uint32_t, apr_pool_t *, apr_uint32_t); + apr_status_t (*add)(apr_pollset_t *, const apr_pollfd_t *); + apr_status_t (*remove)(apr_pollset_t *, const apr_pollfd_t *); + apr_status_t (*poll)(apr_pollset_t *, apr_interval_time_t, apr_int32_t *, const apr_pollfd_t **); + apr_status_t (*cleanup)(apr_pollset_t *); + const char *name; +}; + +struct apr_pollcb_provider_t { + apr_status_t (*create)(apr_pollcb_t *, apr_uint32_t, apr_pool_t *, apr_uint32_t); + apr_status_t (*add)(apr_pollcb_t *, apr_pollfd_t *); + apr_status_t (*remove)(apr_pollcb_t *, apr_pollfd_t *); + apr_status_t (*poll)(apr_pollcb_t *, apr_interval_time_t, apr_pollcb_cb_t, void *); + apr_status_t (*cleanup)(apr_pollcb_t *); + const char *name; +}; + +/* + * Private functions used for the implementation of both apr_pollcb_* and + * apr_pollset_* + */ +apr_status_t apr_poll_create_wakeup_pipe(apr_pool_t *pool, apr_pollfd_t *pfd, + apr_file_t **wakeup_pipe); +apr_status_t apr_poll_close_wakeup_pipe(apr_file_t **wakeup_pipe); +void apr_poll_drain_wakeup_pipe(apr_file_t **wakeup_pipe); + +#endif /* APR_ARCH_POLL_PRIVATE_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_proc_mutex.h b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_proc_mutex.h new file mode 100644 index 00000000..cfa0049f --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_proc_mutex.h @@ -0,0 +1,121 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PROC_MUTEX_H +#define PROC_MUTEX_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_proc_mutex.h" +#include "apr_pools.h" +#include "apr_portable.h" +#include "apr_file_io.h" +#include "apr_arch_file_io.h" +#include "apr_time.h" + +/* System headers required by Locks library */ +#if APR_HAVE_SYS_TYPES_H +#include +#endif +#if APR_HAVE_STDIO_H +#include +#endif +#if APR_HAVE_FCNTL_H +#include +#endif + +#ifdef HAVE_SYS_IPC_H +#include +#endif +#ifdef HAVE_SYS_SEM_H +#include +#endif +#ifdef HAVE_SYS_FILE_H +#include +#endif +#if APR_HAVE_STDLIB_H +#include +#endif +#if APR_HAVE_UNISTD_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#ifdef HAVE_SYS_MMAN_H +#include +#endif +#if APR_HAVE_PTHREAD_H +#include +#endif +/* End System Headers */ + +struct apr_proc_mutex_unix_lock_methods_t { + unsigned int flags; + apr_status_t (*create)(apr_proc_mutex_t *, const char *); + apr_status_t (*acquire)(apr_proc_mutex_t *); + apr_status_t (*tryacquire)(apr_proc_mutex_t *); + apr_status_t (*timedacquire)(apr_proc_mutex_t *, apr_interval_time_t); + apr_status_t (*release)(apr_proc_mutex_t *); + apr_status_t (*cleanup)(void *); + apr_status_t (*child_init)(apr_proc_mutex_t **, apr_pool_t *, const char *); + apr_status_t (*perms_set)(apr_proc_mutex_t *, apr_fileperms_t, apr_uid_t, apr_gid_t); + apr_lockmech_e mech; + const char *name; +}; +typedef struct apr_proc_mutex_unix_lock_methods_t apr_proc_mutex_unix_lock_methods_t; + +/* bit values for flags field in apr_unix_lock_methods_t */ +#define APR_PROCESS_LOCK_MECH_IS_GLOBAL 1 + +#if !APR_HAVE_UNION_SEMUN && defined(APR_HAS_SYSVSEM_SERIALIZE) +union semun { + int val; + struct semid_ds *buf; + unsigned short *array; +}; +#endif + +struct apr_proc_mutex_t { + apr_pool_t *pool; + const apr_proc_mutex_unix_lock_methods_t *meth; + int curr_locked; + char *fname; + + apr_os_proc_mutex_t os; /* Native mutex holder. */ + +#if APR_HAS_FCNTL_SERIALIZE || APR_HAS_FLOCK_SERIALIZE + apr_file_t *interproc; /* For apr_file_ calls on native fd. */ + int interproc_closing; /* whether the native fd is opened/closed with + * 'interproc' or apr_os_file_put()ed (hence + * needing an an explicit close for consistency + * with other methods). + */ +#endif +#if APR_HAS_PROC_PTHREAD_SERIALIZE + int pthread_refcounting; /* Whether the native mutex is refcounted or + * apr_os_proc_mutex_put()ed, which makes + * refcounting impossible/undesirable. + */ +#endif +}; + +void apr_proc_mutex_unix_setup_lock(void); + +#endif /* PROC_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_shm.h b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_shm.h new file mode 100644 index 00000000..e9d25cad --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_shm.h @@ -0,0 +1,74 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SHM_H +#define SHM_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_shm.h" +#include "apr_pools.h" +#include "apr_file_io.h" +#include "apr_network_io.h" +#include "apr_portable.h" + +#if APR_HAVE_UNISTD_H +#include +#endif +#ifdef HAVE_SYS_MMAN_H +#include +#endif +#ifdef HAVE_SYS_IPC_H +#include +#endif +#ifdef HAVE_SYS_MUTEX_H +#include +#endif +#ifdef HAVE_SYS_SHM_H +#include +#endif +#if !defined(SHM_R) +#define SHM_R 0400 +#endif +#if !defined(SHM_W) +#define SHM_W 0200 +#endif +#ifdef HAVE_SYS_FILE_H +#include +#endif + +/* Not all systems seem to have MAP_FAILED defined, but it should always + * just be (void *)-1. */ +#ifndef MAP_FAILED +#define MAP_FAILED ((void *)-1) +#endif + +struct apr_shm_t { + apr_pool_t *pool; + void *base; /* base real address */ + void *usable; /* base usable address */ + apr_size_t reqsize; /* requested segment size */ + apr_size_t realsize; /* actual segment size */ + const char *filename; /* NULL if anonymous */ +#if APR_USE_SHMEM_SHMGET || APR_USE_SHMEM_SHMGET_ANON + int shmid; /* shmem ID returned from shmget() */ + key_t shmkey; /* shmem key IPC_ANON or returned from ftok() */ +#endif +}; + +#endif /* SHM_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_thread_cond.h b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_thread_cond.h new file mode 100644 index 00000000..5c2b51d1 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_thread_cond.h @@ -0,0 +1,42 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_COND_H +#define THREAD_COND_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_lib.h" +#include "apr_thread_mutex.h" +#include "apr_thread_cond.h" +#include "apr_pools.h" + +#if APR_HAVE_PTHREAD_H +#include +#endif + +/* XXX: Should we have a better autoconf search, something like + * APR_HAS_PTHREAD_COND? -aaron */ +#if APR_HAS_THREADS +struct apr_thread_cond_t { + apr_pool_t *pool; + pthread_cond_t cond; +}; +#endif + +#endif /* THREAD_COND_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_thread_mutex.h b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_thread_mutex.h new file mode 100644 index 00000000..4fe46c3b --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_thread_mutex.h @@ -0,0 +1,42 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_MUTEX_H +#define THREAD_MUTEX_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_thread_mutex.h" +#include "apr_thread_cond.h" +#include "apr_portable.h" +#include "apr_atomic.h" + +#if APR_HAVE_PTHREAD_H +#include +#endif + +#if APR_HAS_THREADS +struct apr_thread_mutex_t { + apr_pool_t *pool; + pthread_mutex_t mutex; + apr_thread_cond_t *cond; + int locked, num_waiters; +}; +#endif + +#endif /* THREAD_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_thread_rwlock.h b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_thread_rwlock.h new file mode 100644 index 00000000..2cb43af6 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_thread_rwlock.h @@ -0,0 +1,49 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_RWLOCK_H +#define THREAD_RWLOCK_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_thread_rwlock.h" +#include "apr_pools.h" + +#if APR_HAVE_PTHREAD_H +/* this gives us pthread_rwlock_t */ +#include +#endif + +#if APR_HAS_THREADS +#ifdef HAVE_PTHREAD_RWLOCKS + +struct apr_thread_rwlock_t { + apr_pool_t *pool; + pthread_rwlock_t rwlock; +}; + +#else + +struct apr_thread_rwlock_t { + apr_pool_t *pool; +}; +#endif + +#endif + +#endif /* THREAD_RWLOCK_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_threadproc.h b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_threadproc.h new file mode 100644 index 00000000..7a3b3c09 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/unix/apr_arch_threadproc.h @@ -0,0 +1,119 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr.h" +#include "apr_private.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" +#include "apr_arch_file_io.h" +#include "apr_perms_set.h" + +/* System headers required for thread/process library */ +#if APR_HAVE_PTHREAD_H +#include +#endif +#ifdef HAVE_SYS_RESOURCE_H +#include +#endif +#if APR_HAVE_SIGNAL_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#if APR_HAVE_SYS_WAIT_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#ifdef HAVE_SCHED_H +#include +#endif +/* End System Headers */ + + +#ifndef THREAD_PROC_H +#define THREAD_PROC_H + +#define SHELL_PATH "/bin/sh" + +#if APR_HAS_THREADS + +struct apr_thread_t { + apr_pool_t *pool; + pthread_t *td; + void *data; + apr_thread_start_t func; + apr_status_t exitval; +}; + +struct apr_threadattr_t { + apr_pool_t *pool; + pthread_attr_t attr; +}; + +struct apr_threadkey_t { + apr_pool_t *pool; + pthread_key_t key; +}; + +struct apr_thread_once_t { + pthread_once_t once; +}; + +#endif + +typedef struct apr_procattr_pscb_t apr_procattr_pscb_t; +struct apr_procattr_pscb_t { + struct apr_procattr_pscb_t *next; + apr_perms_setfn_t *perms_set_fn; + apr_fileperms_t perms; + const void *data; +}; + +struct apr_procattr_t { + apr_pool_t *pool; + apr_file_t *parent_in; + apr_file_t *child_in; + apr_file_t *parent_out; + apr_file_t *child_out; + apr_file_t *parent_err; + apr_file_t *child_err; + char *currdir; + apr_int32_t cmdtype; + apr_int32_t detached; +#ifdef RLIMIT_CPU + struct rlimit *limit_cpu; +#endif +#if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS) + struct rlimit *limit_mem; +#endif +#ifdef RLIMIT_NPROC + struct rlimit *limit_nproc; +#endif +#ifdef RLIMIT_NOFILE + struct rlimit *limit_nofile; +#endif + apr_child_errfn_t *errfn; + apr_int32_t errchk; + apr_uid_t uid; + apr_gid_t gid; + apr_procattr_pscb_t *perms_set_callbacks; +}; + +#endif /* ! THREAD_PROC_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_atime.h b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_atime.h new file mode 100644 index 00000000..35f2041a --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_atime.h @@ -0,0 +1,63 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ATIME_H +#define ATIME_H + +#include "apr_private.h" +#include "apr_time.h" +#if APR_HAVE_TIME_H +#include +#endif + +struct atime_t { + apr_pool_t *cntxt; + apr_time_t currtime; + SYSTEMTIME *explodedtime; +}; + + +/* Number of micro-seconds between the beginning of the Windows epoch + * (Jan. 1, 1601) and the Unix epoch (Jan. 1, 1970) + */ +#define APR_DELTA_EPOCH_IN_USEC APR_TIME_C(11644473600000000); + + +static APR_INLINE void FileTimeToAprTime(apr_time_t *result, FILETIME *input) +{ + /* Convert FILETIME one 64 bit number so we can work with it. */ + *result = input->dwHighDateTime; + *result = (*result) << 32; + *result |= input->dwLowDateTime; + *result /= 10; /* Convert from 100 nano-sec periods to micro-seconds. */ + *result -= APR_DELTA_EPOCH_IN_USEC; /* Convert from Windows epoch to Unix epoch */ + return; +} + + +static APR_INLINE void AprTimeToFileTime(LPFILETIME pft, apr_time_t t) +{ + LONGLONG ll; + t += APR_DELTA_EPOCH_IN_USEC; + ll = t * 10; + pft->dwLowDateTime = (DWORD)ll; + pft->dwHighDateTime = (DWORD) (ll >> 32); + return; +} + + +#endif /* ! ATIME_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_dso.h b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_dso.h new file mode 100644 index 00000000..e2e4e40f --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_dso.h @@ -0,0 +1,36 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DSO_H +#define DSO_H + +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_dso.h" +#include "apr.h" + +#if APR_HAS_DSO + +struct apr_dso_handle_t { + apr_pool_t *cont; + void *handle; + apr_status_t load_error; +}; + +#endif + +#endif diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_file_io.h b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_file_io.h new file mode 100644 index 00000000..9fb8df19 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_file_io.h @@ -0,0 +1,266 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FILE_IO_H +#define FILE_IO_H + +#include "apr.h" +#include "apr_private.h" +#include "apr_pools.h" +#include "apr_general.h" +#include "apr_tables.h" +#include "apr_thread_mutex.h" +#include "apr_file_io.h" +#include "apr_file_info.h" +#include "apr_errno.h" +#include "apr_arch_misc.h" +#include "apr_poll.h" + +#ifdef HAVE_SYS_STAT_H +#include +#endif +#if APR_HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_FCNTL_H +#include +#endif +#ifdef HAVE_TIME_H +#include +#endif +#if APR_HAVE_DIRENT_H +#include +#endif +#ifdef HAVE_MALLOC_H +#include +#endif + +#if APR_HAS_UNICODE_FS +#include "arch/win32/apr_arch_utf8.h" +#include + +/* Helper functions for the WinNT ApiW() functions. APR treats all + * resource identifiers (files, etc) by their UTF-8 name, to provide + * access to all named identifiers. [UTF-8 completely maps Unicode + * into char type strings.] + * + * The _path flavors below provide us fast mappings of the + * Unicode filename //?/D:/path and //?/UNC/mach/share/path mappings, + * which allow unlimited (well, 32000 wide character) length names. + * These prefixes may appear in Unicode, but must not appear in the + * Ascii API calls. So we tack them on in utf8_to_unicode_path, and + * strip them right back off in unicode_to_utf8_path. + */ +apr_status_t utf8_to_unicode_path(apr_wchar_t* dststr, apr_size_t dstchars, + const char* srcstr); +apr_status_t unicode_to_utf8_path(char* dststr, apr_size_t dstchars, + const apr_wchar_t* srcstr); + +#endif /* APR_HAS_UNICODE_FS */ + +/* Another Helper functions for the WinNT ApiW() functions. We need to + * derive some 'resource' names (max length 255 characters, prefixed with + * Global/ or Local/ on WinNT) from something that looks like a filename. + * Since 'resource' names never contain slashes, convert these to '_'s + * and return the appropriate char* or wchar* for ApiA or ApiW calls. + */ + +void *res_name_from_filename(const char *file, int global, apr_pool_t *pool); + +#define APR_FILE_MAX MAX_PATH + +#define APR_FILE_DEFAULT_BUFSIZE 4096 +/* For backwards-compat */ +#define APR_FILE_BUFSIZE APR_FILE_DEFAULT_BUFSIZE + +/* obscure ommissions from msvc's sys/stat.h */ +#ifdef _MSC_VER +#define S_IFIFO _S_IFIFO /* pipe */ +#define S_IFBLK 0060000 /* Block Special */ +#define S_IFLNK 0120000 /* Symbolic Link */ +#define S_IFSOCK 0140000 /* Socket */ +#define S_IFWHT 0160000 /* Whiteout */ +#endif + +/* Internal Flags for apr_file_open */ +#define APR_OPENINFO 0x00100000 /* Open without READ or WRITE access */ +#define APR_OPENLINK 0x00200000 /* Open a link itself, if supported */ +#define APR_READCONTROL 0x00400000 /* Read the file's owner/perms */ +#define APR_WRITECONTROL 0x00800000 /* Modify the file's owner/perms */ +/* #define APR_INHERIT 0x01000000 -- Defined in apr_arch_inherit.h! */ +#define APR_STDIN_FLAG 0x02000000 /* Obtained via apr_file_open_stdin() */ +#define APR_STDOUT_FLAG 0x04000000 /* Obtained via apr_file_open_stdout() */ +#define APR_STDERR_FLAG 0x06000000 /* Obtained via apr_file_open_stderr() */ +#define APR_STD_FLAGS (APR_STDIN_FLAG | APR_STDOUT_FLAG | APR_STDERR_FLAG) +#define APR_WRITEATTRS 0x08000000 /* Modify the file's attributes */ + +/* Entries missing from the MSVC 5.0 Win32 SDK: + */ +#ifndef FILE_ATTRIBUTE_DEVICE +#define FILE_ATTRIBUTE_DEVICE 0x00000040 +#endif +#ifndef FILE_ATTRIBUTE_REPARSE_POINT +#define FILE_ATTRIBUTE_REPARSE_POINT 0x00000400 +#endif +#ifndef FILE_FLAG_OPEN_NO_RECALL +#define FILE_FLAG_OPEN_NO_RECALL 0x00100000 +#endif +#ifndef FILE_FLAG_OPEN_REPARSE_POINT +#define FILE_FLAG_OPEN_REPARSE_POINT 0x00200000 +#endif +#ifndef TRUSTEE_IS_WELL_KNOWN_GROUP +#define TRUSTEE_IS_WELL_KNOWN_GROUP 5 +#endif + +/* Information bits available from the WIN32 FindFirstFile function */ +#define APR_FINFO_WIN32_DIR (APR_FINFO_NAME | APR_FINFO_TYPE \ + | APR_FINFO_CTIME | APR_FINFO_ATIME \ + | APR_FINFO_MTIME | APR_FINFO_SIZE) + +/* Sneak the Readonly bit through finfo->protection for internal use _only_ */ +#define APR_FREADONLY 0x10000000 + +/* Private function for apr_stat/lstat/getfileinfo/dir_read */ +int fillin_fileinfo(apr_finfo_t *finfo, WIN32_FILE_ATTRIBUTE_DATA *wininfo, + int byhandle, int finddata, const char *fname, + apr_int32_t wanted); + +/* Private function that extends apr_stat/lstat/getfileinfo/dir_read */ +apr_status_t more_finfo(apr_finfo_t *finfo, const void *ufile, + apr_int32_t wanted, int whatfile); + +/* whatfile types for the ufile arg */ +#define MORE_OF_HANDLE 0 +#define MORE_OF_FSPEC 1 +#define MORE_OF_WFSPEC 2 + +/* quick run-down of fields in windows' apr_file_t structure that may have + * obvious uses. + * fname -- the filename as passed to the open call. + * dwFileAttricutes -- Attributes used to open the file. + * append -- Windows doesn't support the append concept when opening files. + * APR needs to keep track of this, and always make sure we append + * correctly when writing to a file with this flag set TRUE. + */ + +/* for apr_poll.c */ +#define filedes filehand + +struct apr_file_t { + apr_pool_t *pool; + HANDLE filehand; + BOOLEAN pipe; /* Is this a pipe of a file? */ + OVERLAPPED *pOverlapped; + apr_interval_time_t timeout; + apr_int32_t flags; + + /* File specific info */ + apr_finfo_t *finfo; + char *fname; + DWORD dwFileAttributes; + int eof_hit; + BOOLEAN buffered; /* Use buffered I/O? */ + int ungetchar; /* Last char provided by an unget op. (-1 = no char) */ + int append; + + /* Stuff for buffered mode */ + char *buffer; + apr_size_t bufpos; /* Read/Write position in buffer */ + apr_size_t bufsize; /* The size of the buffer */ + apr_size_t dataRead; /* amount of valid data read into buffer */ + int direction; /* buffer being used for 0 = read, 1 = write */ + apr_off_t filePtr; /* position in file of handle */ + apr_thread_mutex_t *mutex; /* mutex semaphore, must be owned to access + * the above fields */ + +#if APR_FILES_AS_SOCKETS + /* if there is a timeout set, then this pollset is used */ + apr_pollset_t *pollset; +#endif + /* Pipe specific info */ +}; + +struct apr_dir_t { + apr_pool_t *pool; + HANDLE dirhand; + apr_size_t rootlen; + char *dirname; + char *name; + union { +#if APR_HAS_UNICODE_FS + struct { + WIN32_FIND_DATAW *entry; + } w; +#endif +#if APR_HAS_ANSI_FS + struct { + WIN32_FIND_DATAA *entry; + } n; +#endif + }; + int bof; +}; + +/* There are many goofy characters the filesystem can't accept + * or can confound the cmd.exe shell. Here's the list + * [declared in filesys.c] + */ +extern const char apr_c_is_fnchar[256]; + +#define IS_FNCHAR(c) (apr_c_is_fnchar[(unsigned char)(c)] & 1) +#define IS_SHCHAR(c) ((apr_c_is_fnchar[(unsigned char)(c)] & 2) == 2) + + +/* If the user passes APR_FILEPATH_TRUENAME to either + * apr_filepath_root or apr_filepath_merge, this fn determines + * that the root really exists. It's expensive, wouldn't want + * to do this too frequenly. + */ +apr_status_t filepath_root_test(char *path, apr_pool_t *p); + + +/* The apr_filepath_merge wants to canonicalize the cwd to the + * addpath if the user passes NULL as the old root path (this + * isn't true of an empty string "", which won't be concatenated. + * + * But we need to figure out what the cwd of a given volume is, + * when the user passes D:foo. This fn will determine D:'s cwd. + * + * If flags includes the bit APR_FILEPATH_NATIVE, the path returned + * is in the os-native format. + */ +apr_status_t filepath_drive_get(char **rootpath, char drive, + apr_int32_t flags, apr_pool_t *p); + + +/* If the user passes d: vs. D: (or //mach/share vs. //MACH/SHARE), + * we need to fold the case to canonical form. This function is + * supposed to do so. + */ +apr_status_t filepath_root_case(char **rootpath, char *root, apr_pool_t *p); + + +apr_status_t file_cleanup(void *); + +extern apr_status_t +apr_file_socket_pipe_create(apr_file_t **in, + apr_file_t **out, + apr_pool_t *p); + +extern apr_status_t +apr_file_socket_pipe_close(apr_file_t *file); + +#endif /* ! FILE_IO_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_inherit.h b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_inherit.h new file mode 100644 index 00000000..8969af66 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_inherit.h @@ -0,0 +1,123 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INHERIT_H +#define INHERIT_H + +#include "apr_inherit.h" + +#define APR_INHERIT (1 << 24) /* Must not conflict with other bits */ + +#if APR_HAS_UNICODE_FS && APR_HAS_ANSI_FS +/* !defined(_WIN32_WCE) is implicit here */ + +#define APR_IMPLEMENT_INHERIT_SET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_set(apr_##name##_t *the##name) \ +{ \ + IF_WIN_OS_IS_UNICODE \ + { \ +/* if (!SetHandleInformation(the##name->filehand, \ + * HANDLE_FLAG_INHERIT, \ + * HANDLE_FLAG_INHERIT)) \ + * return apr_get_os_error(); \ + */ } \ + ELSE_WIN_OS_IS_ANSI \ + { \ + HANDLE temp, hproc = GetCurrentProcess(); \ + if (!DuplicateHandle(hproc, the##name->filehand, \ + hproc, &temp, 0, TRUE, \ + DUPLICATE_SAME_ACCESS)) \ + return apr_get_os_error(); \ + CloseHandle(the##name->filehand); \ + the##name->filehand = temp; \ + } \ + return APR_SUCCESS; \ +} + +#define APR_IMPLEMENT_INHERIT_UNSET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_unset(apr_##name##_t *the##name)\ +{ \ + IF_WIN_OS_IS_UNICODE \ + { \ +/* if (!SetHandleInformation(the##name->filehand, \ + * HANDLE_FLAG_INHERIT, 0)) \ + * return apr_get_os_error(); \ + */ } \ + ELSE_WIN_OS_IS_ANSI \ + { \ + HANDLE temp, hproc = GetCurrentProcess(); \ + if (!DuplicateHandle(hproc, the##name->filehand, \ + hproc, &temp, 0, FALSE, \ + DUPLICATE_SAME_ACCESS)) \ + return apr_get_os_error(); \ + CloseHandle(the##name->filehand); \ + the##name->filehand = temp; \ + } \ + return APR_SUCCESS; \ +} + +#elif APR_HAS_ANSI_FS || defined(_WIN32_WCE) + +#define APR_IMPLEMENT_INHERIT_SET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_set(apr_##name##_t *the##name) \ +{ \ + HANDLE temp, hproc = GetCurrentProcess(); \ + if (!DuplicateHandle(hproc, the##name->filehand, \ + hproc, &temp, 0, TRUE, \ + DUPLICATE_SAME_ACCESS)) \ + return apr_get_os_error(); \ + CloseHandle(the##name->filehand); \ + the##name->filehand = temp; \ + return APR_SUCCESS; \ +} + +#define APR_IMPLEMENT_INHERIT_UNSET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_unset(apr_##name##_t *the##name)\ +{ \ + HANDLE temp, hproc = GetCurrentProcess(); \ + if (!DuplicateHandle(hproc, the##name->filehand, \ + hproc, &temp, 0, FALSE, \ + DUPLICATE_SAME_ACCESS)) \ + return apr_get_os_error(); \ + CloseHandle(the##name->filehand); \ + the##name->filehand = temp; \ + return APR_SUCCESS; \ +} + +#else /* APR_HAS_UNICODE_FS && !APR_HAS_ANSI_FS && !defined(_WIN32_WCE) */ + +#define APR_IMPLEMENT_INHERIT_SET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_set(apr_##name##_t *the##name) \ +{ \ +/* if (!SetHandleInformation(the##name->filehand, \ + * HANDLE_FLAG_INHERIT, \ + * HANDLE_FLAG_INHERIT)) \ + * return apr_get_os_error(); \ + */ return APR_SUCCESS; \ +} + +#define APR_IMPLEMENT_INHERIT_UNSET(name, flag, pool, cleanup) \ +APR_DECLARE(apr_status_t) apr_##name##_inherit_unset(apr_##name##_t *the##name)\ +{ \ +/* if (!SetHandleInformation(the##name->filehand, \ + * HANDLE_FLAG_INHERIT, 0)) \ + * return apr_get_os_error(); \ + */ return APR_SUCCESS; \ +} + +#endif /* defined(APR_HAS_UNICODE_FS) */ + +#endif /* ! INHERIT_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_misc.h b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_misc.h new file mode 100644 index 00000000..15312adf --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_misc.h @@ -0,0 +1,509 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MISC_H +#define MISC_H + +#include "apr.h" +#include "apr_portable.h" +#include "apr_private.h" +#include "apr_general.h" +#include "apr_pools.h" +#include "apr_getopt.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" +#include "apr_errno.h" +#include "apr_getopt.h" + +#if APR_HAVE_STDIO_H +#include +#endif +#if APR_HAVE_SIGNAL_H +#include +#endif +#if APR_HAVE_PTHREAD_H +#include +#endif +#if APR_HAVE_STDLIB_H +#include +#endif +#if APR_HAVE_STRING_H +#include +#endif +#ifndef _WIN32_WCE +#include +#endif + +#if defined(HAVE_IF_INDEXTONAME) && defined(_MSC_VER) +#include +#endif + +struct apr_other_child_rec_t { + apr_pool_t *p; + struct apr_other_child_rec_t *next; + apr_proc_t *proc; + void (*maintenance) (int, void *, int); + void *data; + apr_os_file_t write_fd; +}; + +#define WSAHighByte 2 +#define WSALowByte 0 + +/* start.c and apr_app.c helpers and communication within misc.c + * + * They are not for public consumption, although apr_app_init_complete + * must be an exported symbol to avoid reinitialization. + */ +extern int APR_DECLARE_DATA apr_app_init_complete; + +int apr_wastrtoastr(char const * const * *retarr, + wchar_t const * const *arr, int args); + +/* Platform specific designation of run time os version. + * Gaps allow for specific service pack levels that + * export new kernel or winsock functions or behavior. + */ +typedef enum { + APR_WIN_UNK = 0, + APR_WIN_UNSUP = 1, + APR_WIN_95 = 10, + APR_WIN_95_B = 11, + APR_WIN_95_OSR2 = 12, + APR_WIN_98 = 14, + APR_WIN_98_SE = 16, + APR_WIN_ME = 18, + + APR_WIN_UNICODE = 20, /* Prior versions support only narrow chars */ + + APR_WIN_CE_3 = 23, /* CE is an odd beast, not supporting */ + /* some pre-NT features, such as the */ + APR_WIN_NT = 30, /* narrow charset APIs (fooA fns), while */ + APR_WIN_NT_3_5 = 35, /* not supporting some NT-family features. */ + APR_WIN_NT_3_51 = 36, + + APR_WIN_NT_4 = 40, + APR_WIN_NT_4_SP2 = 42, + APR_WIN_NT_4_SP3 = 43, + APR_WIN_NT_4_SP4 = 44, + APR_WIN_NT_4_SP5 = 45, + APR_WIN_NT_4_SP6 = 46, + + APR_WIN_2000 = 50, + APR_WIN_2000_SP1 = 51, + APR_WIN_2000_SP2 = 52, + APR_WIN_XP = 60, + APR_WIN_XP_SP1 = 61, + APR_WIN_XP_SP2 = 62, + APR_WIN_2003 = 70, + APR_WIN_VISTA = 80, + APR_WIN_7 = 90 +} apr_oslevel_e; + +extern APR_DECLARE_DATA apr_oslevel_e apr_os_level; + +apr_status_t apr_get_oslevel(apr_oslevel_e *); + +/* The APR_HAS_ANSI_FS symbol is PRIVATE, and internal to APR. + * APR only supports char data for filenames. Like most applications, + * characters >127 are essentially undefined. APR_HAS_UNICODE_FS lets + * the application know that utf-8 is the encoding method of APR, and + * only incidently hints that we have Wide OS calls. + * + * APR_HAS_ANSI_FS is simply an OS flag to tell us all calls must be + * the unicode eqivilant. + */ + +#if defined(_WIN32_WCE) || defined(WINNT) +#define APR_HAS_ANSI_FS 0 +#else +#define APR_HAS_ANSI_FS 1 +#endif + +/* IF_WIN_OS_IS_UNICODE / ELSE_WIN_OS_IS_ANSI help us keep the code trivial + * where have runtime tests for unicode-ness, that aren't needed in any + * build which supports only WINNT or WCE. + */ +#if APR_HAS_ANSI_FS && APR_HAS_UNICODE_FS +#define IF_WIN_OS_IS_UNICODE if (apr_os_level >= APR_WIN_UNICODE) +#define ELSE_WIN_OS_IS_ANSI else +#else /* APR_HAS_UNICODE_FS */ +#define IF_WIN_OS_IS_UNICODE +#define ELSE_WIN_OS_IS_ANSI +#endif /* WINNT */ + +#if defined(_MSC_VER) && !defined(_WIN32_WCE) +#include "crtdbg.h" + +static APR_INLINE void* apr_malloc_dbg(size_t size, const char* filename, + int linenumber) +{ + return _malloc_dbg(size, _CRT_BLOCK, filename, linenumber); +} + +static APR_INLINE void* apr_realloc_dbg(void* userData, size_t newSize, + const char* filename, int linenumber) +{ + return _realloc_dbg(userData, newSize, _CRT_BLOCK, filename, linenumber); +} + +#else + +static APR_INLINE void* apr_malloc_dbg(size_t size, const char* filename, + int linenumber) +{ + return malloc(size); +} + +static APR_INLINE void* apr_realloc_dbg(void* userData, size_t newSize, + const char* filename, int linenumber) +{ + return realloc(userData, newSize); +} + +#endif /* ! _MSC_VER */ + +typedef enum { + DLL_WINBASEAPI = 0, /* kernel32 From WinBase.h */ + DLL_WINADVAPI = 1, /* advapi32 From WinBase.h */ + DLL_WINSOCKAPI = 2, /* mswsock From WinSock.h */ + DLL_WINSOCK2API = 3, /* ws2_32 From WinSock2.h */ + DLL_SHSTDAPI = 4, /* shell32 From ShellAPI.h */ + DLL_NTDLL = 5, /* ntdll From our real kernel */ + DLL_IPHLPAPI = 6, /* Iphlpapi From Iphlpapi.h */ + DLL_defined = 7 /* must define as last idx_ + 1 */ +} apr_dlltoken_e; + +FARPROC apr_load_dll_func(apr_dlltoken_e fnLib, char *fnName, int ordinal); + +/* The apr_load_dll_func call WILL return 0 set error to + * ERROR_INVALID_FUNCTION if the function cannot be loaded + */ +#define APR_DECLARE_LATE_DLL_FUNC(lib, rettype, calltype, fn, ord, args, names) \ + typedef rettype (calltype *apr_winapi_fpt_##fn) args; \ + static apr_winapi_fpt_##fn apr_winapi_pfn_##fn = NULL; \ + static int apr_winapi_chk_##fn = 0; \ + static APR_INLINE int apr_winapi_ld_##fn(void) \ + { if (apr_winapi_pfn_##fn) return 1; \ + if (apr_winapi_chk_##fn ++) return 0; \ + if (!apr_winapi_pfn_##fn) \ + apr_winapi_pfn_##fn = (apr_winapi_fpt_##fn) \ + apr_load_dll_func(lib, #fn, ord); \ + if (apr_winapi_pfn_##fn) return 1; else return 0; }; \ + static APR_INLINE rettype apr_winapi_##fn args \ + { if (apr_winapi_ld_##fn()) \ + return (*(apr_winapi_pfn_##fn)) names; \ + else { SetLastError(ERROR_INVALID_FUNCTION); return 0;} }; \ + +#define APR_HAVE_LATE_DLL_FUNC(fn) apr_winapi_ld_##fn() + +/* Provide late bound declarations of every API function missing from + * one or more supported releases of the Win32 API + * + * lib is the enumerated token from apr_dlltoken_e, and must correspond + * to the string table entry in start.c used by the apr_load_dll_func(). + * Token names (attempt to) follow Windows.h declarations prefixed by DLL_ + * in order to facilitate comparison. Use the exact declaration syntax + * and names from Windows.h to prevent ambigutity and bugs. + * + * rettype and calltype follow the original declaration in Windows.h + * fn is the true function name - beware Ansi/Unicode #defined macros + * ord is the ordinal within the library, use 0 if it varies between versions + * args is the parameter list following the original declaration, in parens + * names is the parameter list sans data types, enclosed in parens + * + * #undef/re#define the Ansi/Unicode generic name to abate confusion + * In the case of non-text functions, simply #define the original name + */ + +#if !defined(_WIN32_WCE) && !defined(WINNT) +/* This group is available to all versions of WINNT 4.0 SP6 and later */ + +#ifdef GetFileAttributesExA +#undef GetFileAttributesExA +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, GetFileAttributesExA, 0, ( + IN LPCSTR lpFileName, + IN GET_FILEEX_INFO_LEVELS fInfoLevelId, + OUT LPVOID lpFileInformation), + (lpFileName, fInfoLevelId, lpFileInformation)); +#define GetFileAttributesExA apr_winapi_GetFileAttributesExA +#undef GetFileAttributesEx +#define GetFileAttributesEx apr_winapi_GetFileAttributesExA + +#ifdef GetFileAttributesExW +#undef GetFileAttributesExW +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, GetFileAttributesExW, 0, ( + IN LPCWSTR lpFileName, + IN GET_FILEEX_INFO_LEVELS fInfoLevelId, + OUT LPVOID lpFileInformation), + (lpFileName, fInfoLevelId, lpFileInformation)); +#define GetFileAttributesExW apr_winapi_GetFileAttributesExW + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, CancelIo, 0, ( + IN HANDLE hFile), + (hFile)); +#define CancelIo apr_winapi_CancelIo + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, TryEnterCriticalSection, 0, ( + LPCRITICAL_SECTION lpCriticalSection), + (lpCriticalSection)); +#define TryEnterCriticalSection apr_winapi_TryEnterCriticalSection + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, SwitchToThread, 0, ( + void), + ()); +#define SwitchToThread apr_winapi_SwitchToThread + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINADVAPI, BOOL, WINAPI, GetEffectiveRightsFromAclW, 0, ( + IN PACL pacl, + IN PTRUSTEE_W pTrustee, + OUT PACCESS_MASK pAccessRights), + (pacl, pTrustee, pAccessRights)); +#define GetEffectiveRightsFromAclW apr_winapi_GetEffectiveRightsFromAclW + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINADVAPI, BOOL, WINAPI, GetNamedSecurityInfoW, 0, ( + IN LPWSTR pObjectName, + IN SE_OBJECT_TYPE ObjectType, + IN SECURITY_INFORMATION SecurityInfo, + OUT PSID *ppsidOwner, + OUT PSID *ppsidGroup, + OUT PACL *ppDacl, + OUT PACL *ppSacl, + OUT PSECURITY_DESCRIPTOR *ppSecurityDescriptor), + (pObjectName, ObjectType, SecurityInfo, ppsidOwner, ppsidGroup, + ppDacl, ppSacl, ppSecurityDescriptor)); +#define GetNamedSecurityInfoW apr_winapi_GetNamedSecurityInfoW + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINADVAPI, BOOL, WINAPI, GetNamedSecurityInfoA, 0, ( + IN LPSTR pObjectName, + IN SE_OBJECT_TYPE ObjectType, + IN SECURITY_INFORMATION SecurityInfo, + OUT PSID *ppsidOwner, + OUT PSID *ppsidGroup, + OUT PACL *ppDacl, + OUT PACL *ppSacl, + OUT PSECURITY_DESCRIPTOR *ppSecurityDescriptor), + (pObjectName, ObjectType, SecurityInfo, ppsidOwner, ppsidGroup, + ppDacl, ppSacl, ppSecurityDescriptor)); +#define GetNamedSecurityInfoA apr_winapi_GetNamedSecurityInfoA +#undef GetNamedSecurityInfo +#define GetNamedSecurityInfo apr_winapi_GetNamedSecurityInfoA + +APR_DECLARE_LATE_DLL_FUNC(DLL_WINADVAPI, BOOL, WINAPI, GetSecurityInfo, 0, ( + IN HANDLE handle, + IN SE_OBJECT_TYPE ObjectType, + IN SECURITY_INFORMATION SecurityInfo, + OUT PSID *ppsidOwner, + OUT PSID *ppsidGroup, + OUT PACL *ppDacl, + OUT PACL *ppSacl, + OUT PSECURITY_DESCRIPTOR *ppSecurityDescriptor), + (handle, ObjectType, SecurityInfo, ppsidOwner, ppsidGroup, + ppDacl, ppSacl, ppSecurityDescriptor)); +#define GetSecurityInfo apr_winapi_GetSecurityInfo + +APR_DECLARE_LATE_DLL_FUNC(DLL_SHSTDAPI, LPWSTR *, WINAPI, CommandLineToArgvW, 0, ( + LPCWSTR lpCmdLine, + int *pNumArgs), + (lpCmdLine, pNumArgs)); +#define CommandLineToArgvW apr_winapi_CommandLineToArgvW + +#endif /* !defined(_WIN32_WCE) && !defined(WINNT) */ + +#if !defined(_WIN32_WCE) +/* This group is NOT available to all versions of WinNT, + * these we must always look up + */ + +#ifdef GetCompressedFileSizeA +#undef GetCompressedFileSizeA +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, DWORD, WINAPI, GetCompressedFileSizeA, 0, ( + IN LPCSTR lpFileName, + OUT LPDWORD lpFileSizeHigh), + (lpFileName, lpFileSizeHigh)); +#define GetCompressedFileSizeA apr_winapi_GetCompressedFileSizeA +#undef GetCompressedFileSize +#define GetCompressedFileSize apr_winapi_GetCompressedFileSizeA + +#ifdef GetCompressedFileSizeW +#undef GetCompressedFileSizeW +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, DWORD, WINAPI, GetCompressedFileSizeW, 0, ( + IN LPCWSTR lpFileName, + OUT LPDWORD lpFileSizeHigh), + (lpFileName, lpFileSizeHigh)); +#define GetCompressedFileSizeW apr_winapi_GetCompressedFileSizeW + + +APR_DECLARE_LATE_DLL_FUNC(DLL_NTDLL, LONG, WINAPI, NtQueryTimerResolution, 0, ( + ULONG *pMaxRes, /* Minimum NS Resolution */ + ULONG *pMinRes, /* Maximum NS Resolution */ + ULONG *pCurRes), /* Current NS Resolution */ + (pMaxRes, pMinRes, pCurRes)); +#define QueryTimerResolution apr_winapi_NtQueryTimerResolution + +APR_DECLARE_LATE_DLL_FUNC(DLL_NTDLL, LONG, WINAPI, NtSetTimerResolution, 0, ( + ULONG ReqRes, /* Requested NS Clock Resolution */ + BOOL Acquire, /* Aquire (1) or Release (0) our interest */ + ULONG *pNewRes), /* The NS Clock Resolution granted */ + (ReqRes, Acquire, pNewRes)); +#define SetTimerResolution apr_winapi_NtSetTimerResolution + +typedef struct PBI { + LONG ExitStatus; + PVOID PebBaseAddress; + apr_uintptr_t AffinityMask; + LONG BasePriority; + apr_uintptr_t UniqueProcessId; + apr_uintptr_t InheritedFromUniqueProcessId; +} PBI, *PPBI; + +APR_DECLARE_LATE_DLL_FUNC(DLL_NTDLL, LONG, WINAPI, NtQueryInformationProcess, 0, ( + HANDLE hProcess, /* Obvious */ + INT info, /* Use 0 for PBI documented above */ + PVOID pPI, /* The PIB buffer */ + ULONG LenPI, /* Use sizeof(PBI) */ + ULONG *pSizePI), /* returns pPI buffer used (may pass NULL) */ + (hProcess, info, pPI, LenPI, pSizePI)); +#define QueryInformationProcess apr_winapi_NtQueryInformationProcess + +APR_DECLARE_LATE_DLL_FUNC(DLL_NTDLL, LONG, WINAPI, NtQueryObject, 0, ( + HANDLE hObject, /* Obvious */ + INT info, /* Use 0 for PBI documented above */ + PVOID pOI, /* The PIB buffer */ + ULONG LenOI, /* Use sizeof(PBI) */ + ULONG *pSizeOI), /* returns pPI buffer used (may pass NULL) */ + (hObject, info, pOI, LenOI, pSizeOI)); +#define QueryObject apr_winapi_NtQueryObject + +typedef struct IOSB { + union { + UINT Status; + PVOID reserved; + }; + apr_uintptr_t Information; /* Varies by op, consumed buffer size for FSI below */ +} IOSB, *PIOSB; + +typedef struct FSI { + LONGLONG AllocationSize; + LONGLONG EndOfFile; + ULONG NumberOfLinks; + BOOL DeletePending; + BOOL Directory; +} FSI, *PFSI; + +APR_DECLARE_LATE_DLL_FUNC(DLL_NTDLL, LONG, WINAPI, ZwQueryInformationFile, 0, ( + HANDLE hObject, /* Obvious */ + PVOID pIOSB, /* Point to the IOSB buffer for detailed return results */ + PVOID pFI, /* The buffer, using FIB above */ + ULONG LenFI, /* Use sizeof(FI) */ + ULONG info), /* Use 5 for FSI documented above*/ + (hObject, pIOSB, pFI, LenFI, info)); +#define ZwQueryInformationFile apr_winapi_ZwQueryInformationFile + +#ifdef CreateToolhelp32Snapshot +#undef CreateToolhelp32Snapshot +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, HANDLE, WINAPI, CreateToolhelp32Snapshot, 0, ( + DWORD dwFlags, + DWORD th32ProcessID), + (dwFlags, th32ProcessID)); +#define CreateToolhelp32Snapshot apr_winapi_CreateToolhelp32Snapshot + +#ifdef Process32FirstW +#undef Process32FirstW +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, Process32FirstW, 0, ( + HANDLE hSnapshot, + LPPROCESSENTRY32W lppe), + (hSnapshot, lppe)); +#define Process32FirstW apr_winapi_Process32FirstW + +#ifdef Process32NextW +#undef Process32NextW +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, Process32NextW, 0, ( + HANDLE hSnapshot, + LPPROCESSENTRY32W lppe), + (hSnapshot, lppe)); +#define Process32NextW apr_winapi_Process32NextW + +#if !defined(POLLERR) +/* Event flag definitions for WSAPoll(). */ +#define POLLRDNORM 0x0100 +#define POLLRDBAND 0x0200 +#define POLLIN (POLLRDNORM | POLLRDBAND) +#define POLLPRI 0x0400 + +#define POLLWRNORM 0x0010 +#define POLLOUT (POLLWRNORM) +#define POLLWRBAND 0x0020 + +#define POLLERR 0x0001 +#define POLLHUP 0x0002 +#define POLLNVAL 0x0004 + +typedef struct pollfd { + SOCKET fd; + SHORT events; + SHORT revents; + +} WSAPOLLFD, *PWSAPOLLFD, FAR *LPWSAPOLLFD; + +#endif /* !defined(POLLERR) */ +#ifdef WSAPoll +#undef WSAPoll +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINSOCK2API, int, WSAAPI, WSAPoll, 0, ( + IN OUT LPWSAPOLLFD fdArray, + IN ULONG fds, + IN INT timeout), + (fdArray, fds, timeout)); +#define WSAPoll apr_winapi_WSAPoll +#define HAVE_POLL 1 + +#ifdef SetDllDirectoryW +#undef SetDllDirectoryW +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_WINBASEAPI, BOOL, WINAPI, SetDllDirectoryW, 0, ( + IN LPCWSTR lpPathName), + (lpPathName)); +#define SetDllDirectoryW apr_winapi_SetDllDirectoryW + +#ifdef if_nametoindex +#undef if_nametoindex +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_IPHLPAPI, NET_IFINDEX, WINAPI, if_nametoindex, 0, ( + IN PCSTR InterfaceName), + (InterfaceName)); +#define if_nametoindex apr_winapi_if_nametoindex + +#ifdef if_indextoname +#undef if_indextoname +#endif +APR_DECLARE_LATE_DLL_FUNC(DLL_IPHLPAPI, PCHAR, NETIOAPI_API_, if_indextoname, 0, ( + NET_IFINDEX InterfaceIndex, + PCHAR InterfaceName), + (InterfaceIndex, InterfaceName)); +#define if_indextoname apr_winapi_if_indextoname + +#endif /* !defined(_WIN32_WCE) */ + +#endif /* ! MISC_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_networkio.h b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_networkio.h new file mode 100644 index 00000000..04be5559 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_networkio.h @@ -0,0 +1,90 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETWORK_IO_H +#define NETWORK_IO_H + +#include "apr_network_io.h" +#include "apr_general.h" +#include "apr_poll.h" + +typedef struct sock_userdata_t sock_userdata_t; +struct sock_userdata_t { + sock_userdata_t *next; + const char *key; + void *data; +}; + +struct apr_socket_t { + apr_pool_t *pool; + SOCKET socketdes; + int type; /* SOCK_STREAM, SOCK_DGRAM */ + int protocol; + apr_sockaddr_t *local_addr; + apr_sockaddr_t *remote_addr; + int timeout_ms; /* MUST MATCH if timeout > 0 */ + apr_interval_time_t timeout; + apr_int32_t disconnected; + int local_port_unknown; + int local_interface_unknown; + int remote_addr_unknown; + apr_int32_t options; + apr_int32_t inherit; +#if APR_HAS_SENDFILE + /* As of 07.20.04, the overlapped structure is only used by + * apr_socket_sendfile and that's where it will be allocated + * and initialized. + */ + OVERLAPPED *overlapped; +#endif + sock_userdata_t *userdata; + + /* if there is a timeout set, then this pollset is used */ + apr_pollset_t *pollset; +}; + +#ifdef _WIN32_WCE +#ifndef WSABUF +typedef struct _WSABUF { + u_long len; /* the length of the buffer */ + char FAR * buf; /* the pointer to the buffer */ +} WSABUF, FAR * LPWSABUF; +#endif +#else +#ifdef _MSC_VER +#define HAVE_STRUCT_IPMREQ +#endif +#endif + +apr_status_t status_from_res_error(int); + +const char *apr_inet_ntop(int af, const void *src, char *dst, apr_size_t size); +int apr_inet_pton(int af, const char *src, void *dst); +void apr_sockaddr_vars_set(apr_sockaddr_t *, int, apr_port_t); + +#define apr_is_option_set(skt, option) \ + (((skt)->options & (option)) == (option)) + +#define apr_set_option(skt, option, on) \ + do { \ + if (on) \ + (skt)->options |= (option); \ + else \ + (skt)->options &= ~(option); \ + } while (0) + +#endif /* ! NETWORK_IO_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_proc_mutex.h b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_proc_mutex.h new file mode 100644 index 00000000..4e3e3993 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_proc_mutex.h @@ -0,0 +1,29 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PROC_MUTEX_H +#define PROC_MUTEX_H + +#include "apr_proc_mutex.h" + +struct apr_proc_mutex_t { + apr_pool_t *pool; + HANDLE handle; + const char *fname; +}; + +#endif /* PROC_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_thread_cond.h b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_thread_cond.h new file mode 100644 index 00000000..c7f69f80 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_thread_cond.h @@ -0,0 +1,32 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_COND_H +#define THREAD_COND_H + +#include "apr_thread_cond.h" + +struct apr_thread_cond_t { + apr_pool_t *pool; + HANDLE semaphore; + CRITICAL_SECTION csection; + unsigned long num_waiting; + unsigned long num_wake; + unsigned long generation; +}; + +#endif /* THREAD_COND_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_thread_mutex.h b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_thread_mutex.h new file mode 100644 index 00000000..13d3c1cb --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_thread_mutex.h @@ -0,0 +1,40 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_MUTEX_H +#define THREAD_MUTEX_H + +#include "apr_pools.h" + +typedef enum thread_mutex_type { + thread_mutex_critical_section, + thread_mutex_unnested_event, + thread_mutex_nested_mutex +} thread_mutex_type; + +/* handle applies only to unnested_event on all platforms + * and nested_mutex on Win9x only. Otherwise critical_section + * is used for NT nexted mutexes providing optimal performance. + */ +struct apr_thread_mutex_t { + apr_pool_t *pool; + thread_mutex_type type; + HANDLE handle; + CRITICAL_SECTION section; +}; + +#endif /* THREAD_MUTEX_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_thread_rwlock.h b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_thread_rwlock.h new file mode 100644 index 00000000..1177e529 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_thread_rwlock.h @@ -0,0 +1,30 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef THREAD_RWLOCK_H +#define THREAD_RWLOCK_H + +#include "apr_thread_rwlock.h" + +struct apr_thread_rwlock_t { + apr_pool_t *pool; + HANDLE write_mutex; + HANDLE read_event; + LONG readers; +}; + +#endif /* THREAD_RWLOCK_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_threadproc.h b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_threadproc.h new file mode 100644 index 00000000..d3ce9c51 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_threadproc.h @@ -0,0 +1,74 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr_private.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" + +#ifndef THREAD_PROC_H +#define THREAD_PROC_H + +#define SHELL_PATH "cmd.exe" + +struct apr_thread_t { + apr_pool_t *pool; + HANDLE td; + apr_int32_t cancel; + apr_int32_t cancel_how; + void *data; + apr_thread_start_t func; + apr_status_t exitval; +}; + +struct apr_threadattr_t { + apr_pool_t *pool; + apr_int32_t detach; + apr_size_t stacksize; +}; + +struct apr_threadkey_t { + apr_pool_t *pool; + DWORD key; +}; + +struct apr_procattr_t { + apr_pool_t *pool; + apr_file_t *parent_in; + apr_file_t *child_in; + apr_file_t *parent_out; + apr_file_t *child_out; + apr_file_t *parent_err; + apr_file_t *child_err; + char *currdir; + apr_int32_t cmdtype; + apr_int32_t detached; + apr_child_errfn_t *errfn; + apr_int32_t errchk; +#ifndef _WIN32_WCE + HANDLE user_token; + LPSECURITY_ATTRIBUTES sa; + LPVOID sd; +#endif +}; + +struct apr_thread_once_t { + long value; +}; + +extern apr_status_t apr_threadproc_init(apr_pool_t *pool); + +#endif /* ! THREAD_PROC_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_utf8.h b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_utf8.h new file mode 100644 index 00000000..84f8bf77 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_arch_utf8.h @@ -0,0 +1,56 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef UTF8_H +#define UTF8_H + +#include "apr.h" +#include "apr_lib.h" +#include "apr_errno.h" + +/* If we ever support anything more exciting than char... this could move. + */ +typedef apr_uint16_t apr_wchar_t; + +/** + * An APR internal function for fast utf-8 octet-encoded Unicode conversion + * to the ucs-2 wide Unicode format. This function is used for filename and + * other resource conversions for platforms providing native Unicode support. + * + * @tip Only the errors APR_EINVAL and APR_INCOMPLETE may occur, the former + * when the character code is invalid (in or out of context) and the later + * when more characters were expected, but insufficient characters remain. + */ +APR_DECLARE(apr_status_t) apr_conv_utf8_to_ucs2(const char *in, + apr_size_t *inbytes, + apr_wchar_t *out, + apr_size_t *outwords); + +/** + * An APR internal function for fast ucs-2 wide Unicode format conversion to + * the utf-8 octet-encoded Unicode. This function is used for filename and + * other resource conversions for platforms providing native Unicode support. + * + * @tip Only the errors APR_EINVAL and APR_INCOMPLETE may occur, the former + * when the character code is invalid (in or out of context) and the later + * when more words were expected, but insufficient words remain. + */ +APR_DECLARE(apr_status_t) apr_conv_ucs2_to_utf8(const apr_wchar_t *in, + apr_size_t *inwords, + char *out, + apr_size_t *outbytes); + +#endif /* def UTF8_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_dbg_win32_handles.h b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_dbg_win32_handles.h new file mode 100644 index 00000000..471cd66d --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_dbg_win32_handles.h @@ -0,0 +1,217 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_DBG_WIN32_HANDLES_H +#define APR_DBG_WIN32_HANDLES_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* USAGE: + * + * Add the following include to apr_private.h for internal debugging, + * or copy this header into apr/include add the include below to apr.h + * for really global debugging; + * + * #include "apr_dbg_win32_handles.h" + * + * apr_dbg_log is the crux of this function ... it uses Win32 API and + * no apr calls itself to log all activity to a file named for the + * executing application with a .pid suffix. Ergo several instances + * may be executing and logged at once. + * + * HANDLE apr_dbg_log(char* fn, HANDLE ha, char* fl, int ln, int nh + * [, HANDLE *hv, char *dsc...]) + * + * returns: the handle passed in ha, which is cast back to the real return type. + * + * formats one line into the debug log file if nh is zero; + * ha (hex) seq(hex) tid(hex) fn fl ln + * xxxxxxxx xxxxxxxx xxxxxxxx func() sourcefile:lineno + * The macro apr_dbg_rv makes this simple to implement for many APIs + * that simply take args that don't interest us, and return a handle. + * + * formats multiple lines (nh) into the debug log file for each hv/dsc pair + * (nh must correspond to the number of pairs); + * hv (hex) seq(hex) tid(hex) fn dsc fl ln + * xxxxxxxx xxxxxxxx xxxxxxxx func(arg) sourcefile:lineno + * In this later usage, hv is the still the return value but is not + * treated as a handle. + */ + +APR_DECLARE_NONSTD(HANDLE) apr_dbg_log(char* fn, HANDLE ha, char* fl, int ln, + int nh,/* HANDLE *hv, char *dsc */...); + +#define apr_dbg_rv(fn, args) (apr_dbg_log(#fn,(fn) args,__FILE__,__LINE__,0)) + +#define CloseHandle(h) \ + ((BOOL)apr_dbg_log("CloseHandle", \ + (HANDLE)(CloseHandle)(h), \ + __FILE__,__LINE__,1, \ + &(h),"")) + +#define CreateEventA(sd,b1,b2,nm) apr_dbg_rv(CreateEventA,(sd,b1,b2,nm)) +#define CreateEventW(sd,b1,b2,nm) apr_dbg_rv(CreateEventW,(sd,b1,b2,nm)) + +#define CreateFileA(nm,d1,d2,sd,d3,d4,h) apr_dbg_rv(CreateFileA,(nm,d1,d2,sd,d3,d4,h)) +#define CreateFileW(nm,d1,d2,sd,d3,d4,h) apr_dbg_rv(CreateFileW,(nm,d1,d2,sd,d3,d4,h)) + +#define CreateFileMappingA(fh,sd,d1,d2,d3,nm) apr_dbg_rv(CreateFileMappingA,(fh,sd,d1,d2,d3,nm)) +#define CreateFileMappingW(fh,sd,d1,d2,d3,nm) apr_dbg_rv(CreateFileMappingW,(fh,sd,d1,d2,d3,nm)) + +#define CreateMutexA(sd,b,nm) apr_dbg_rv(CreateMutexA,(sd,b,nm)) +#define CreateMutexW(sd,b,nm) apr_dbg_rv(CreateMutexW,(sd,b,nm)) + +#define CreateIoCompletionPort(h1,h2,pd1,d2) apr_dbg_rv(CreateIoCompletionPort,(h1,h2,pd1,d2)) + +#define CreateNamedPipeA(nm,d1,d2,d3,d4,d5,d6,sd) apr_dbg_rv(CreateNamedPipeA,(nm,d1,d2,d3,d4,d5,d6,sd)) +#define CreateNamedPipeW(nm,d1,d2,d3,d4,d5,d6,sd) apr_dbg_rv(CreateNamedPipeW,(nm,d1,d2,d3,d4,d5,d6,sd)) + +#define CreatePipe(ph1,ph2,sd,d) \ + ((BOOL)apr_dbg_log("CreatePipe", \ + (HANDLE)(CreatePipe)(ph1,ph2,sd,d), \ + __FILE__,__LINE__,2, \ + (ph1),"hRead", \ + (ph2),"hWrite")) + +#define CreateProcessA(s1,s2,sd1,sd2,b,d1,s3,s4,pd2,hr) \ + ((BOOL)apr_dbg_log("CreateProcessA", \ + (HANDLE)(CreateProcessA)(s1,s2,sd1,sd2,b,d1,s3,s4,pd2,hr), \ + __FILE__,__LINE__,2, \ + &((hr)->hProcess),"hProcess", \ + &((hr)->hThread),"hThread")) +#define CreateProcessW(s1,s2,sd1,sd2,b,d1,s3,s4,pd2,hr) \ + ((BOOL)apr_dbg_log("CreateProcessW", \ + (HANDLE)(CreateProcessW)(s1,s2,sd1,sd2,b,d1,s3,s4,pd2,hr), \ + __FILE__,__LINE__,2, \ + &((hr)->hProcess),"hProcess", \ + &((hr)->hThread),"hThread")) + +#define CreateSemaphoreA(sd,d1,d2,nm) apr_dbg_rv(CreateSemaphoreA,(sd,d1,d2,nm)) +#define CreateSemaphoreW(sd,d1,d2,nm) apr_dbg_rv(CreateSemaphoreW,(sd,d1,d2,nm)) + +#define CreateThread(sd,d1,fn,pv,d2,pd3) apr_dbg_rv(CreateThread,(sd,d1,fn,pv,d2,pd3)) + +#define DeregisterEventSource(h) \ + ((BOOL)apr_dbg_log("DeregisterEventSource", \ + (HANDLE)(DeregisterEventSource)(h), \ + __FILE__,__LINE__,1, \ + &(h),"")) + +#define DuplicateHandle(h1,h2,h3,ph4,d1,b,d2) \ + ((BOOL)apr_dbg_log("DuplicateHandle", \ + (HANDLE)(DuplicateHandle)(h1,h2,h3,ph4,d1,b,d2), \ + __FILE__,__LINE__,2, \ + (ph4),((h3)==GetCurrentProcess()) \ + ? "Target" : "EXTERN Target", \ + &(h2),((h1)==GetCurrentProcess()) \ + ? "Source" : "EXTERN Source")) + +#define GetCurrentProcess() \ + (apr_dbg_log("GetCurrentProcess", \ + (GetCurrentProcess)(),__FILE__,__LINE__,0)) + +#define GetCurrentThread() \ + (apr_dbg_log("GetCurrentThread", \ + (GetCurrentThread)(),__FILE__,__LINE__,0)) + +#define GetModuleHandleA(nm) apr_dbg_rv(GetModuleHandleA,(nm)) +#define GetModuleHandleW(nm) apr_dbg_rv(GetModuleHandleW,(nm)) + +#define GetStdHandle(d) apr_dbg_rv(GetStdHandle,(d)) + +#define LoadLibraryA(nm) apr_dbg_rv(LoadLibraryA,(nm)) +#define LoadLibraryW(nm) apr_dbg_rv(LoadLibraryW,(nm)) + +#define LoadLibraryExA(nm,h,d) apr_dbg_rv(LoadLibraryExA,(nm,h,d)) +#define LoadLibraryExW(nm,h,d) apr_dbg_rv(LoadLibraryExW,(nm,h,d)) + +#define OpenEventA(d,b,nm) apr_dbg_rv(OpenEventA,(d,b,nm)) +#define OpenEventW(d,b,nm) apr_dbg_rv(OpenEventW,(d,b,nm)) + +#define OpenFileMappingA(d,b,nm) apr_dbg_rv(OpenFileMappingA,(d,b,nm)) +#define OpenFileMappingW(d,b,nm) apr_dbg_rv(OpenFileMappingW,(d,b,nm)) + +#define RegisterEventSourceA(s1,s2) apr_dbg_rv(RegisterEventSourceA,(s1,s2)) +#define RegisterEventSourceW(s1,s2) apr_dbg_rv(RegisterEventSourceW,(s1,s2)) + +#define SetEvent(h) \ + ((BOOL)apr_dbg_log("SetEvent", \ + (HANDLE)(SetEvent)(h), \ + __FILE__,__LINE__,1, \ + &(h),"")) + +#define SetStdHandle(d,h) \ + ((BOOL)apr_dbg_log("SetStdHandle", \ + (HANDLE)(SetStdHandle)(d,h), \ + __FILE__,__LINE__,1,&(h),"")) + +#define socket(i1,i2,i3) \ + ((SOCKET)apr_dbg_log("socket", \ + (HANDLE)(socket)(i1,i2,i3), \ + __FILE__,__LINE__,0)) + +#define WaitForSingleObject(h,d) \ + ((DWORD)apr_dbg_log("WaitForSingleObject", \ + (HANDLE)(WaitForSingleObject)(h,d), \ + __FILE__,__LINE__,1,&(h),"Signaled")) + +#define WaitForSingleObjectEx(h,d,b) \ + ((DWORD)apr_dbg_log("WaitForSingleObjectEx", \ + (HANDLE)(WaitForSingleObjectEx)(h,d,b), \ + __FILE__,__LINE__,1,&(h),"Signaled")) + +#define WaitForMultipleObjects(d1,ah,b,d2) \ + ((DWORD)apr_dbg_log("WaitForMultipleObjects", \ + (HANDLE)(WaitForMultipleObjects)(d1,ah,b,d2), \ + __FILE__,__LINE__,1,ah,"Signaled")) + +#define WaitForMultipleObjectsEx(d1,ah,b1,d2,b2) \ + ((DWORD)apr_dbg_log("WaitForMultipleObjectsEx", \ + (HANDLE)(WaitForMultipleObjectsEx)(d1,ah,b1,d2,b2), \ + __FILE__,__LINE__,1,ah,"Signaled")) + +#define WSASocketA(i1,i2,i3,pi,g,dw) \ + ((SOCKET)apr_dbg_log("WSASocketA", \ + (HANDLE)(WSASocketA)(i1,i2,i3,pi,g,dw), \ + __FILE__,__LINE__,0)) + +#define WSASocketW(i1,i2,i3,pi,g,dw) \ + ((SOCKET)apr_dbg_log("WSASocketW", \ + (HANDLE)(WSASocketW)(i1,i2,i3,pi,g,dw), \ + __FILE__,__LINE__,0)) + +#define closesocket(sh) \ + ((int)apr_dbg_log("closesocket", \ + (HANDLE)(closesocket)(sh), \ + __FILE__,__LINE__,1,&(sh),"")) + +#define _beginthread(fn,d,pv) \ + ((unsigned long)apr_dbg_log("_beginthread", \ + (HANDLE)(_beginthread)(fn,d,pv), \ + __FILE__,__LINE__,0)) + +#define _beginthreadex(sd,d1,fn,pv,d2,pd3) \ + ((unsigned long)apr_dbg_log("_beginthreadex", \ + (HANDLE)(_beginthreadex)(sd,d1,fn,pv,d2,pd3), \ + __FILE__,__LINE__,0)) + +#ifdef __cplusplus +} +#endif + +#endif /* !defined(APR_DBG_WIN32_HANDLES_H) */ diff --git a/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_private.h b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_private.h new file mode 100644 index 00000000..c631ad43 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/arch/win32/apr_private.h @@ -0,0 +1,175 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Note: + * This is the windows specific autoconf-like config file + * which unix would create at build time. + */ + +#ifdef WIN32 + +#ifndef APR_PRIVATE_H +#define APR_PRIVATE_H + +/* Include the public APR symbols, include our idea of the 'right' + * subset of the Windows.h header. This saves us repetition. + */ +#include "apr.h" + +/* + * Add a _very_few_ declarations missing from the restricted set of headers + * (If this list becomes extensive, re-enable the required headers above!) + * winsock headers were excluded by WIN32_LEAN_AND_MEAN, so include them now + */ +#ifndef SW_HIDE +#define SW_HIDE 0 +#endif + +/* For the misc.h late-loaded dynamic symbols, we need some obscure types + * Avoid dragging in wtypes.h unless it's absolutely necessary [generally + * not with APR itself, until some GUI-related security is introduced.] + */ +#ifndef _WIN32_WCE +#define HAVE_ACLAPI 1 +#ifdef __wtypes_h__ +#include +#else +#define __wtypes_h__ +#include +#undef __wtypes_h__ +#endif +#else +#define HAVE_ACLAPI 0 +#endif + +#if APR_HAVE_SYS_TYPES_H +#include +#endif +#if APR_HAVE_STDDEF_H +#include +#endif +#include +#if APR_HAVE_TIME_H +#include +#endif + +/* Use this section to define all of the HAVE_FOO_H + * that are required to build properly. + */ +#define HAVE_LIMITS_H 1 +#define HAVE_MALLOC_H 1 +#define HAVE_SIGNAL_H 1 +/* #define HAVE_STDDEF_H 1 why not? */ +#define HAVE_STDLIB_H 1 + +#define HAVE_STRICMP 1 +#define HAVE_STRNICMP 1 +#define HAVE_STRDUP 1 +#define HAVE_STRSTR 1 +#define HAVE_MEMCHR 1 + +#define SIGHUP 1 +/* 2 is used for SIGINT on windows */ +#define SIGQUIT 3 +/* 4 is used for SIGILL on windows */ +#define SIGTRAP 5 +#define SIGIOT 6 +#define SIGBUS 7 +/* 8 is used for SIGFPE on windows */ +#define SIGKILL 9 +#define SIGUSR1 10 +/* 11 is used for SIGSEGV on windows */ +#define SIGUSR2 12 +#define SIGPIPE 13 +#define SIGALRM 14 +/* 15 is used for SIGTERM on windows */ +#define SIGSTKFLT 16 +#define SIGCHLD 17 +#define SIGCONT 18 +#define SIGSTOP 19 +#define SIGTSTP 20 +/* 21 is used for SIGBREAK on windows */ +/* 22 is used for SIGABRT on windows */ +#define SIGTTIN 23 +#define SIGTTOU 24 +#define SIGURG 25 +#define SIGXCPU 26 +#define SIGXFSZ 27 +#define SIGVTALRM 28 +#define SIGPROF 29 +#define SIGWINCH 30 +#define SIGIO 31 + +/* APR COMPATABILITY FUNCTIONS + * This section should be used to define functions and + * macros which are need to make Windows features look + * like POSIX features. + */ +typedef void (Sigfunc)(int); + +#define sleep(t) Sleep((t) * 1000) + +#define SIZEOF_SHORT 2 +#define SIZEOF_INT 4 +#define SIZEOF_LONGLONG 8 +#define SIZEOF_CHAR 1 +#define SIZEOF_SSIZE_T SIZEOF_INT + +unsigned __stdcall SignalHandling(void *); +int thread_ready(void); + +#if !APR_HAVE_ERRNO_H +APR_DECLARE_DATA int errno; +#define ENOSPC 1 +#endif + +#if APR_HAVE_IPV6 +#define HAVE_GETADDRINFO 1 +#define HAVE_GETNAMEINFO 1 +#define HAVE_IF_INDEXTONAME 1 +#define HAVE_IF_NAMETOINDEX 1 +#endif + +/* MSVC 7.0 introduced _strtoi64 */ +#if _MSC_VER >= 1300 && _INTEGRAL_MAX_BITS >= 64 && !defined(_WIN32_WCE) +#define APR_INT64_STRFN _strtoi64 +#endif + +#if APR_HAS_LARGE_FILES +#ifdef APR_INT64_STRFN +#define APR_OFF_T_STRFN APR_INT64_STRFN +#else +#define APR_OFF_T_STRFN apr_strtoi64 +#endif +#else +#if defined(_WIN32_WCE) +#define APR_OFF_T_STRFN strtol +#else +#define APR_OFF_T_STRFN strtoi +#endif +#endif + +/* used to check for DWORD overflow in 64bit compiles */ +#define APR_DWORD_MAX 0xFFFFFFFFUL + +/* + * Include common private declarations. + */ +#include "../apr_private_common.h" + +#endif /*APR_PRIVATE_H*/ +#endif /*WIN32*/ diff --git a/c/dependencies/windows/apr/x86_debug/include/private/apr_crypto_internal.h b/c/dependencies/windows/apr/x86_debug/include/private/apr_crypto_internal.h new file mode 100644 index 00000000..1ea838bf --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/private/apr_crypto_internal.h @@ -0,0 +1,297 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_CRYPTO_INTERNAL_H +#define APR_CRYPTO_INTERNAL_H + +#include + +#include "apr_crypto.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if APU_HAVE_CRYPTO + +struct apr_crypto_driver_t { + + /** name */ + const char *name; + + /** + * @brief: allow driver to perform once-only initialisation. + * Called once only. + * @param pool The pool to register the cleanup in. + * @param params Optional init parameter string. + * @param rc Driver-specific additional error code + */ + apr_status_t (*init)(apr_pool_t *pool, const char *params, + const apu_err_t **result); + + /** + * @brief Create a context for supporting encryption. Keys, certificates, + * algorithms and other parameters will be set per context. More than + * one context can be created at one time. A cleanup will be automatically + * registered with the given pool to guarantee a graceful shutdown. + * @param f - context pointer will be written here + * @param provider - provider to use + * @param params - array of key parameters + * @param pool - process pool + * @return APR_ENOENGINE when the engine specified does not exist. APR_EINITENGINE + * if the engine cannot be initialised. + */ + apr_status_t (*make)(apr_crypto_t **f, const apr_crypto_driver_t *provider, + const char *params, apr_pool_t *pool); + + /** + * @brief Get a hash table of key types, keyed by the name of the type against + * a pointer to apr_crypto_block_key_type_t. + * + * @param types - hashtable of key types keyed to constants. + * @param f - encryption context + * @return APR_SUCCESS for success + */ + apr_status_t (*get_block_key_types)(apr_hash_t **types, + const apr_crypto_t *f); + + /** + * @brief Get a hash table of key modes, keyed by the name of the mode against + * a pointer to apr_crypto_block_key_mode_t. + * + * @param modes - hashtable of key modes keyed to constants. + * @param f - encryption context + * @return APR_SUCCESS for success + */ + apr_status_t (*get_block_key_modes)(apr_hash_t **modes, + const apr_crypto_t *f); + + /** + * @brief Create a key from the given passphrase. By default, the PBKDF2 + * algorithm is used to generate the key from the passphrase. It is expected + * that the same pass phrase will generate the same key, regardless of the + * backend crypto platform used. The key is cleaned up when the context + * is cleaned, and may be reused with multiple encryption or decryption + * operations. + * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If + * *key is not NULL, *key must point at a previously created structure. + * @param key The key returned, see note. + * @param ivSize The size of the initialisation vector will be returned, based + * on whether an IV is relevant for this type of crypto. + * @param pass The passphrase to use. + * @param passLen The passphrase length in bytes + * @param salt The salt to use. + * @param saltLen The salt length in bytes + * @param type 3DES_192, AES_128, AES_192, AES_256. + * @param mode Electronic Code Book / Cipher Block Chaining. + * @param doPad Pad if necessary. + * @param iterations Iteration count + * @param f The context to use. + * @param p The pool to use. + * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend + * error occurred while generating the key. APR_ENOCIPHER if the type or mode + * is not supported by the particular backend. APR_EKEYTYPE if the key type is + * not known. APR_EPADDING if padding was requested but is not supported. + * APR_ENOTIMPL if not implemented. + */ + apr_status_t (*passphrase)(apr_crypto_key_t **key, apr_size_t *ivSize, + const char *pass, apr_size_t passLen, const unsigned char * salt, + apr_size_t saltLen, const apr_crypto_block_key_type_e type, + const apr_crypto_block_key_mode_e mode, const int doPad, + const int iterations, const apr_crypto_t *f, apr_pool_t *p); + + /** + * @brief Initialise a context for encrypting arbitrary data using the given key. + * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If + * *ctx is not NULL, *ctx must point at a previously created structure. + * @param ctx The block context returned, see note. + * @param iv Optional initialisation vector. If the buffer pointed to is NULL, + * an IV will be created at random, in space allocated from the pool. + * If the buffer pointed to is not NULL, the IV in the buffer will be + * used. + * @param key The key structure. + * @param blockSize The block size of the cipher. + * @param p The pool to use. + * @return Returns APR_ENOIV if an initialisation vector is required but not specified. + * Returns APR_EINIT if the backend failed to initialise the context. Returns + * APR_ENOTIMPL if not implemented. + */ + apr_status_t (*block_encrypt_init)(apr_crypto_block_t **ctx, + const unsigned char **iv, const apr_crypto_key_t *key, + apr_size_t *blockSize, apr_pool_t *p); + + /** + * @brief Encrypt data provided by in, write it to out. + * @note The number of bytes written will be written to outlen. If + * out is NULL, outlen will contain the maximum size of the + * buffer needed to hold the data, including any data + * generated by apr_crypto_block_encrypt_finish below. If *out points + * to NULL, a buffer sufficiently large will be created from + * the pool provided. If *out points to a not-NULL value, this + * value will be used as a buffer instead. + * @param out Address of a buffer to which data will be written, + * see note. + * @param outlen Length of the output will be written here. + * @param in Address of the buffer to read. + * @param inlen Length of the buffer to read. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if + * not implemented. + */ + apr_status_t (*block_encrypt)(unsigned char **out, apr_size_t *outlen, + const unsigned char *in, apr_size_t inlen, apr_crypto_block_t *ctx); + + /** + * @brief Encrypt final data block, write it to out. + * @note If necessary the final block will be written out after being + * padded. Typically the final block will be written to the + * same buffer used by apr_crypto_block_encrypt, offset by the + * number of bytes returned as actually written by the + * apr_crypto_block_encrypt() call. After this call, the context + * is cleaned and can be reused by apr_crypto_block_encrypt_init(). + * @param out Address of a buffer to which data will be written. This + * buffer must already exist, and is usually the same + * buffer used by apr_evp_crypt(). See note. + * @param outlen Length of the output will be written here. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. + * @return APR_EPADDING if padding was enabled and the block was incorrectly + * formatted. + * @return APR_ENOTIMPL if not implemented. + */ + apr_status_t (*block_encrypt_finish)(unsigned char *out, + apr_size_t *outlen, apr_crypto_block_t *ctx); + + /** + * @brief Initialise a context for decrypting arbitrary data using the given key. + * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If + * *ctx is not NULL, *ctx must point at a previously created structure. + * @param ctx The block context returned, see note. + * @param blockSize The block size of the cipher. + * @param iv Optional initialisation vector. If the buffer pointed to is NULL, + * an IV will be created at random, in space allocated from the pool. + * If the buffer is not NULL, the IV in the buffer will be used. + * @param key The key structure. + * @param p The pool to use. + * @return Returns APR_ENOIV if an initialisation vector is required but not specified. + * Returns APR_EINIT if the backend failed to initialise the context. Returns + * APR_ENOTIMPL if not implemented. + */ + apr_status_t (*block_decrypt_init)(apr_crypto_block_t **ctx, + apr_size_t *blockSize, const unsigned char *iv, + const apr_crypto_key_t *key, apr_pool_t *p); + + /** + * @brief Decrypt data provided by in, write it to out. + * @note The number of bytes written will be written to outlen. If + * out is NULL, outlen will contain the maximum size of the + * buffer needed to hold the data, including any data + * generated by apr_crypto_block_decrypt_finish below. If *out points + * to NULL, a buffer sufficiently large will be created from + * the pool provided. If *out points to a not-NULL value, this + * value will be used as a buffer instead. + * @param out Address of a buffer to which data will be written, + * see note. + * @param outlen Length of the output will be written here. + * @param in Address of the buffer to read. + * @param inlen Length of the buffer to read. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if + * not implemented. + */ + apr_status_t (*block_decrypt)(unsigned char **out, apr_size_t *outlen, + const unsigned char *in, apr_size_t inlen, apr_crypto_block_t *ctx); + + /** + * @brief Decrypt final data block, write it to out. + * @note If necessary the final block will be written out after being + * padded. Typically the final block will be written to the + * same buffer used by apr_crypto_block_decrypt, offset by the + * number of bytes returned as actually written by the + * apr_crypto_block_decrypt() call. After this call, the context + * is cleaned and can be reused by apr_crypto_block_decrypt_init(). + * @param out Address of a buffer to which data will be written. This + * buffer must already exist, and is usually the same + * buffer used by apr_evp_crypt(). See note. + * @param outlen Length of the output will be written here. + * @param ctx The block context to use. + * @return APR_ECRYPT if an error occurred. + * @return APR_EPADDING if padding was enabled and the block was incorrectly + * formatted. + * @return APR_ENOTIMPL if not implemented. + */ + apr_status_t (*block_decrypt_finish)(unsigned char *out, + apr_size_t *outlen, apr_crypto_block_t *ctx); + + /** + * @brief Clean encryption / decryption context. + * @note After cleanup, a context is free to be reused if necessary. + * @param ctx The block context to use. + * @return Returns APR_ENOTIMPL if not supported. + */ + apr_status_t (*block_cleanup)(apr_crypto_block_t *ctx); + + /** + * @brief Clean encryption / decryption context. + * @note After cleanup, a context is free to be reused if necessary. + * @param f The context to use. + * @return Returns APR_ENOTIMPL if not supported. + */ + apr_status_t (*cleanup)(apr_crypto_t *f); + + /** + * @brief Clean encryption / decryption context. + * @note After cleanup, a context is free to be reused if necessary. + * @return Returns APR_ENOTIMPL if not supported. + */ + apr_status_t (*shutdown)(void); + + /** + * @brief: fetch the most recent error from this driver. + * @param result - the result structure + * @param f - context pointer + * @return APR_SUCCESS for success. + */ + apr_status_t (*error)(const apu_err_t **result, const apr_crypto_t *f); + + /** + * @brief Create a key from the provided secret or passphrase. The key is cleaned + * up when the context is cleaned, and may be reused with multiple encryption + * or decryption operations. + * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If + * *key is not NULL, *key must point at a previously created structure. + * @param key The key returned, see note. + * @param rec The key record, from which the key will be derived. + * @param f The context to use. + * @param p The pool to use. + * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend + * error occurred while generating the key. APR_ENOCIPHER if the type or mode + * is not supported by the particular backend. APR_EKEYTYPE if the key type is + * not known. APR_EPADDING if padding was requested but is not supported. + * APR_ENOTIMPL if not implemented. + */ + apr_status_t (*key)(apr_crypto_key_t **key, const apr_crypto_key_rec_t *rec, + const apr_crypto_t *f, apr_pool_t *p); + +}; + +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/c/dependencies/windows/apr/x86_debug/include/private/apr_dbd_internal.h b/c/dependencies/windows/apr/x86_debug/include/private/apr_dbd_internal.h new file mode 100644 index 00000000..671ffb21 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/private/apr_dbd_internal.h @@ -0,0 +1,365 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* Overview of what this is and does: + * http://www.apache.org/~niq/dbd.html + */ + +#ifndef APR_DBD_INTERNAL_H +#define APR_DBD_INTERNAL_H + +#include + +#include "apr_dbd.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define TXN_IGNORE_ERRORS(t) \ + ((t) && ((t)->mode & APR_DBD_TRANSACTION_IGNORE_ERRORS)) +#define TXN_NOTICE_ERRORS(t) \ + ((t) && !((t)->mode & APR_DBD_TRANSACTION_IGNORE_ERRORS)) + +#define TXN_DO_COMMIT(t) (!((t)->mode & APR_DBD_TRANSACTION_ROLLBACK)) +#define TXN_DO_ROLLBACK(t) ((t)->mode & APR_DBD_TRANSACTION_ROLLBACK) + +#define TXN_MODE_BITS \ + (APR_DBD_TRANSACTION_ROLLBACK|APR_DBD_TRANSACTION_IGNORE_ERRORS) + +struct apr_dbd_driver_t { + /** name */ + const char *name; + + /** init: allow driver to perform once-only initialisation. + * Called once only. May be NULL + */ + void (*init)(apr_pool_t *pool); + + /** native_handle: return the native database handle of the underlying db + * + * @param handle - apr_dbd handle + * @return - native handle + */ + void *(*native_handle)(apr_dbd_t *handle); + + /** open: obtain a database connection from the server rec. + * Must be explicitly closed when you're finished with it. + * WARNING: only use this when you need a connection with + * a lifetime other than a request + * + * @param pool - a pool to use for error messages (if any). + * @param params - connection parameters. + * @param error - descriptive error. + * @return database handle, or NULL on error. + */ + apr_dbd_t *(*open)(apr_pool_t *pool, const char *params, + const char **error); + + /** check_conn: check status of a database connection + * + * @param pool - a pool to use for error messages (if any). + * @param handle - the connection to check + * @return APR_SUCCESS or error + */ + apr_status_t (*check_conn)(apr_pool_t *pool, apr_dbd_t *handle); + + /** close: close/release a connection obtained from open() + * + * @param handle - the connection to release + * @return APR_SUCCESS or error + */ + apr_status_t (*close)(apr_dbd_t *handle); + + /** set_dbname: select database name. May be a no-op if not supported. + * + * @param pool - working pool + * @param handle - the connection + * @param name - the database to select + * @return 0 for success or error code + */ + int (*set_dbname)(apr_pool_t* pool, apr_dbd_t *handle, const char *name); + + /** transaction: start a transaction. May be a no-op. + * + * @param pool - a pool to use for error messages (if any). + * @param handle - the connection + * @param trans - ptr to a transaction. May be null on entry + * @return 0 for success or error code + */ + int (*start_transaction)(apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_transaction_t **trans); + + /** end_transaction: end a transaction + * (commit on success, rollback on error). + * May be a no-op. + * + * @param trans - the transaction. + * @return 0 for success or error code + */ + int (*end_transaction)(apr_dbd_transaction_t *trans); + + /** query: execute an SQL query that doesn't return a result set + * + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the SQL statement to execute + * @return 0 for success or error code + */ + int (*query)(apr_dbd_t *handle, int *nrows, const char *statement); + + /** select: execute an SQL query that returns a result set + * + * @param pool - pool to allocate the result set + * @param handle - the connection + * @param res - pointer to result set pointer. May point to NULL on entry + * @param statement - the SQL statement to execute + * @param random - 1 to support random access to results (seek any row); + * 0 to support only looping through results in order + * (async access - faster) + * @return 0 for success or error code + */ + int (*select)(apr_pool_t *pool, apr_dbd_t *handle, apr_dbd_results_t **res, + const char *statement, int random); + + /** num_cols: get the number of columns in a results set + * + * @param res - result set. + * @return number of columns + */ + int (*num_cols)(apr_dbd_results_t *res); + + /** num_tuples: get the number of rows in a results set + * of a synchronous select + * + * @param res - result set. + * @return number of rows, or -1 if the results are asynchronous + */ + int (*num_tuples)(apr_dbd_results_t *res); + + /** get_row: get a row from a result set + * + * @param pool - pool to allocate the row + * @param res - result set pointer + * @param row - pointer to row pointer. May point to NULL on entry + * @param rownum - row number, or -1 for "next row". Ignored if random + * access is not supported. + * @return 0 for success, -1 for rownum out of range or data finished + */ + int (*get_row)(apr_pool_t *pool, apr_dbd_results_t *res, + apr_dbd_row_t **row, int rownum); + + /** get_entry: get an entry from a row + * + * @param row - row pointer + * @param col - entry number + * @param val - entry to fill + * @return 0 for success, -1 for no data, +1 for general error + */ + const char* (*get_entry)(const apr_dbd_row_t *row, int col); + + /** error: get current error message (if any) + * + * @param handle - the connection + * @param errnum - error code from operation that returned an error + * @return the database current error message, or message for errnum + * (implementation-dependent whether errnum is ignored) + */ + const char *(*error)(apr_dbd_t *handle, int errnum); + + /** escape: escape a string so it is safe for use in query/select + * + * @param pool - pool to alloc the result from + * @param string - the string to escape + * @param handle - the connection + * @return the escaped, safe string + */ + const char *(*escape)(apr_pool_t *pool, const char *string, + apr_dbd_t *handle); + + /** prepare: prepare a statement + * + * @param pool - pool to alloc the result from + * @param handle - the connection + * @param query - the SQL query + * @param label - A label for the prepared statement. + * use NULL for temporary prepared statements + * (eg within a Request in httpd) + * @param nargs - number of parameters in the query + * @param nvals - number of values passed in p[b]query/select + * @param types - pointer to an array with types of parameters + * @param statement - statement to prepare. May point to null on entry. + * @return 0 for success or error code + */ + int (*prepare)(apr_pool_t *pool, apr_dbd_t *handle, const char *query, + const char *label, int nargs, int nvals, + apr_dbd_type_e *types, apr_dbd_prepared_t **statement); + + /** pvquery: query using a prepared statement + args + * + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param args - args to prepared statement + * @return 0 for success or error code + */ + int (*pvquery)(apr_pool_t *pool, apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, va_list args); + + /** pvselect: select using a prepared statement + args + * + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param args - args to prepared statement + * @return 0 for success or error code + */ + int (*pvselect)(apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, int random, va_list args); + + /** pquery: query using a prepared statement + args + * + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param args - args to prepared statement + * @return 0 for success or error code + */ + int (*pquery)(apr_pool_t *pool, apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, const char **args); + + /** pselect: select using a prepared statement + args + * + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param args - args to prepared statement + * @return 0 for success or error code + */ + int (*pselect)(apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, apr_dbd_prepared_t *statement, + int random, const char **args); + + + /** get_name: get a column title from a result set + * + * @param res - result set pointer + * @param col - entry number + * @return param name, or NULL if col is out of bounds. + */ + const char* (*get_name)(const apr_dbd_results_t *res, int col); + + /** transaction_mode_get: get the mode of transaction + * + * @param trans - the transaction. + * @return mode of transaction + */ + int (*transaction_mode_get)(apr_dbd_transaction_t *trans); + + /** transaction_mode_set: get the mode of transaction + * + * @param trans - the transaction. + * @param mode - new mode of the transaction + * @return the mode of transaction in force after the call + */ + int (*transaction_mode_set)(apr_dbd_transaction_t *trans, int mode); + + /** format of prepared statement parameters */ + const char *pformat; + + /** pvbquery: query using a prepared statement + binary args + * + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ + int (*pvbquery)(apr_pool_t *pool, apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement, va_list args); + + /** pvbselect: select using a prepared statement + binary args + * + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ + int (*pvbselect)(apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, + apr_dbd_prepared_t *statement, int random, va_list args); + + /** pbquery: query using a prepared statement + binary args + * + * @param pool - working pool + * @param handle - the connection + * @param nrows - number of rows affected. + * @param statement - the prepared statement to execute + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ + int (*pbquery)(apr_pool_t *pool, apr_dbd_t *handle, int *nrows, + apr_dbd_prepared_t *statement,const void **args); + + /** pbselect: select using a prepared statement + binary args + * + * @param pool - working pool + * @param handle - the connection + * @param res - pointer to query results. May point to NULL on entry + * @param statement - the prepared statement to execute + * @param random - Whether to support random-access to results + * @param args - binary args to prepared statement + * @return 0 for success or error code + */ + int (*pbselect)(apr_pool_t *pool, apr_dbd_t *handle, + apr_dbd_results_t **res, apr_dbd_prepared_t *statement, + int random, const void **args); + + /** datum_get: get a binary entry from a row + * + * @param row - row pointer + * @param col - entry number + * @param type - type of data to get + * @param data - pointer to data, allocated by the caller + * @return APR_SUCCESS, an error code on error or if col is out of bounds + */ + apr_status_t (*datum_get)(const apr_dbd_row_t *row, int col, + apr_dbd_type_e type, void *data); +}; + +/* Export mutex lock/unlock for drivers that need it + * deprecated; create a per-dbd mutex within the (*init) function + * to avoid blocking other providers running on other threads + */ +APU_DECLARE(apr_status_t) apr_dbd_mutex_lock(void); +APU_DECLARE(apr_status_t) apr_dbd_mutex_unlock(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/c/dependencies/windows/apr/x86_debug/include/private/apr_dbd_odbc_v2.h b/c/dependencies/windows/apr/x86_debug/include/private/apr_dbd_odbc_v2.h new file mode 100644 index 00000000..b8da7b18 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/private/apr_dbd_odbc_v2.h @@ -0,0 +1,119 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/* ONLY USED FOR ODBC Version 2 -DODBCV2 +* +* Re-define everything to work (more-or-less) in an ODBC V2 environment +* Random access to retrieved rows is not supported - i.e. calls to apr_dbd_select() cannot +* have a 'random' argument of 1. apr_dbd_get_row() must always pass rownum as 0 (get next row) +* +*/ + +#define SQLHANDLE SQLHENV /* Presumes that ENV, DBC, and STMT handles are all the same datatype */ +#define SQL_NULL_HANDLE 0 +#define SQL_HANDLE_STMT 1 +#define SQL_HANDLE_DBC 2 +#define SQL_HANDLE_ENV 3 +#define SQL_NO_DATA SQL_NO_DATA_FOUND + +#ifndef SQL_SUCCEEDED +#define SQL_SUCCEEDED(rc) (((rc)&(~1))==0) +#endif + +#undef SQLSetEnvAttr +#define SQLSetEnvAttr(henv, Attribute, Value, StringLength) (0) + +#undef SQLAllocHandle +#define SQLAllocHandle(type, parent, hndl) \ +( (type == SQL_HANDLE_STMT) ? SQLAllocStmt(parent, hndl) \ + : (type == SQL_HANDLE_ENV) ? SQLAllocEnv(hndl) \ + : SQLAllocConnect(parent, hndl) \ +) + +#undef SQLFreeHandle +#define SQLFreeHandle(type, hndl) \ +( (type == SQL_HANDLE_STMT) ? SQLFreeStmt(hndl, SQL_DROP) \ + : (type == SQL_HANDLE_ENV) ? SQLFreeEnv(hndl) \ + : SQLFreeConnect(hndl) \ +) + +#undef SQLGetDiagRec +#define SQLGetDiagRec(type, h, i, state, native, buffer, bufsize, reslen) \ + SQLError( (type == SQL_HANDLE_ENV) ? h : NULL, \ + (type == SQL_HANDLE_DBC) ? h : NULL, \ + (type == SQL_HANDLE_STMT) ? h : NULL, \ + state, native, buffer, bufsize, reslen) + +#undef SQLCloseCursor +#define SQLCloseCursor(stmt) SQLFreeStmt(stmt, SQL_CLOSE) + +#undef SQLGetConnectAttr +#define SQLGetConnectAttr(hdbc, fOption, ValuePtr, BufferLength, NULL) \ + SQLGetConnectOption(hdbc, fOption, ValuePtr) + +#undef SQLSetConnectAttr +#define SQLSetConnectAttr(hdbc, fOption, ValuePtr, BufferLength) \ + SQLSetConnectOption(hdbc, fOption, (SQLUINTEGER) ValuePtr) + +#undef SQLSetStmtAttr +#define SQLSetStmtAttr(hstmt, fOption, ValuePtr, BufferLength) (0); return APR_ENOTIMPL; + +#undef SQLEndTran +#define SQLEndTran(hType, hdbc,type) SQLTransact(henv, hdbc, type) + +#undef SQLFetchScroll +#define SQLFetchScroll(stmt, orient, rownum) (0); return APR_ENOTIMPL; + +#define SQL_DESC_TYPE SQL_COLUMN_TYPE +#define SQL_DESC_CONCISE_TYPE SQL_COLUMN_TYPE +#define SQL_DESC_DISPLAY_SIZE SQL_COLUMN_DISPLAY_SIZE +#define SQL_DESC_OCTET_LENGTH SQL_COLUMN_LENGTH +#define SQL_DESC_UNSIGNED SQL_COLUMN_UNSIGNED + +#undef SQLColAttribute +#define SQLColAttribute(s, c, f, a, l, m, n) SQLColAttributes(s, c, f, a, l, m, n) + +#define SQL_ATTR_ACCESS_MODE SQL_ACCESS_MODE +#define SQL_ATTR_AUTOCOMMIT SQL_AUTOCOMMIT +#define SQL_ATTR_CONNECTION_TIMEOUT 113 +#define SQL_ATTR_CURRENT_CATALOG SQL_CURRENT_QUALIFIER +#define SQL_ATTR_DISCONNECT_BEHAVIOR 114 +#define SQL_ATTR_ENLIST_IN_DTC 1207 +#define SQL_ATTR_ENLIST_IN_XA 1208 + +#define SQL_ATTR_CONNECTION_DEAD 1209 +#define SQL_CD_TRUE 1L /* Connection is closed/dead */ +#define SQL_CD_FALSE 0L /* Connection is open/available */ + +#define SQL_ATTR_LOGIN_TIMEOUT SQL_LOGIN_TIMEOUT +#define SQL_ATTR_ODBC_CURSORS SQL_ODBC_CURSORS +#define SQL_ATTR_PACKET_SIZE SQL_PACKET_SIZE +#define SQL_ATTR_QUIET_MODE SQL_QUIET_MODE +#define SQL_ATTR_TRACE SQL_OPT_TRACE +#define SQL_ATTR_TRACEFILE SQL_OPT_TRACEFILE +#define SQL_ATTR_TRANSLATE_LIB SQL_TRANSLATE_DLL +#define SQL_ATTR_TRANSLATE_OPTION SQL_TRANSLATE_OPTION +#define SQL_ATTR_TXN_ISOLATION SQL_TXN_ISOLATION + +#define SQL_ATTR_CURSOR_SCROLLABLE -1 + +#define SQL_C_SBIGINT (SQL_BIGINT+SQL_SIGNED_OFFSET) /* SIGNED BIGINT */ +#define SQL_C_UBIGINT (SQL_BIGINT+SQL_UNSIGNED_OFFSET) /* UNSIGNED BIGINT */ + +#define SQL_FALSE 0 +#define SQL_TRUE 1 + diff --git a/c/dependencies/windows/apr/x86_debug/include/private/apr_dbm_private.h b/c/dependencies/windows/apr/x86_debug/include/private/apr_dbm_private.h new file mode 100644 index 00000000..020d3a6b --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/private/apr_dbm_private.h @@ -0,0 +1,121 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APR_DBM_PRIVATE_H +#define APR_DBM_PRIVATE_H + +#include "apr.h" +#include "apr_errno.h" +#include "apr_pools.h" +#include "apr_dbm.h" +#include "apr_file_io.h" + +#include "apu.h" + +/* ### for now, include the DBM selection; this will go away once we start + ### building and linking all of the DBMs at once. */ +#include "apu_select_dbm.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** @internal */ + +/** + * Most DBM libraries take a POSIX mode for creating files. Don't trust + * the mode_t type, some platforms may not support it, int is safe. + */ +APU_DECLARE(int) apr_posix_perms2mode(apr_fileperms_t perm); + +/** + * Structure to describe the operations of the DBM + */ +typedef struct { + /** The name of the DBM Type */ + const char *name; + + /** Open the DBM */ + apr_status_t (*open)(apr_dbm_t **pdb, const char *pathname, + apr_int32_t mode, apr_fileperms_t perm, + apr_pool_t *pool); + + /** Close the DBM */ + void (*close)(apr_dbm_t *dbm); + + /** Fetch a dbm record value by key */ + apr_status_t (*fetch)(apr_dbm_t *dbm, apr_datum_t key, + apr_datum_t * pvalue); + + /** Store a dbm record value by key */ + apr_status_t (*store)(apr_dbm_t *dbm, apr_datum_t key, apr_datum_t value); + + /** Delete a dbm record value by key */ + apr_status_t (*del)(apr_dbm_t *dbm, apr_datum_t key); + + /** Search for a key within the dbm */ + int (*exists)(apr_dbm_t *dbm, apr_datum_t key); + + /** Retrieve the first record key from a dbm */ + apr_status_t (*firstkey)(apr_dbm_t *dbm, apr_datum_t * pkey); + + /** Retrieve the next record key from a dbm */ + apr_status_t (*nextkey)(apr_dbm_t *dbm, apr_datum_t * pkey); + + /** Proactively toss any memory associated with the apr_datum_t. */ + void (*freedatum)(apr_dbm_t *dbm, apr_datum_t data); + + /** Get the names that the DBM will use for a given pathname. */ + void (*getusednames)(apr_pool_t *pool, + const char *pathname, + const char **used1, + const char **used2); + +} apr_dbm_type_t; + + +/** + * The actual DBM + */ +struct apr_dbm_t +{ + /** Associated pool */ + apr_pool_t *pool; + + /** pointer to DB Implementation Specific data */ + void *file; + + /** Current integer error code */ + int errcode; + /** Current string error code */ + const char *errmsg; + + /** the type of DBM */ + const apr_dbm_type_t *type; +}; + + +/* Declare all of the DBM provider tables */ +APU_MODULE_DECLARE_DATA extern const apr_dbm_type_t apr_dbm_type_sdbm; +APU_MODULE_DECLARE_DATA extern const apr_dbm_type_t apr_dbm_type_gdbm; +APU_MODULE_DECLARE_DATA extern const apr_dbm_type_t apr_dbm_type_ndbm; +APU_MODULE_DECLARE_DATA extern const apr_dbm_type_t apr_dbm_type_db; + +#ifdef __cplusplus +} +#endif + +#endif /* APR_DBM_PRIVATE_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/private/apr_encode_private.h b/c/dependencies/windows/apr/x86_debug/include/private/apr_encode_private.h new file mode 100644 index 00000000..8db2e016 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/private/apr_encode_private.h @@ -0,0 +1,84 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file apr_encode_private.h + * @brief APR-UTIL Encoding Private + */ +#ifndef APR_ENCODE_PRIVATE_H +#define APR_ENCODE_PRIVATE_H + +#include "apr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup APR_Util_Encode_Private + * @ingroup APR_Util + * @{ + */ + +#if APR_CHARSET_EBCDIC + static int convert_a2e[256] = { + 0x00, 0x01, 0x02, 0x03, 0x37, 0x2D, 0x2E, 0x2F, 0x16, 0x05, 0x15, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, + 0x10, 0x11, 0x12, 0x13, 0x3C, 0x3D, 0x32, 0x26, 0x18, 0x19, 0x3F, 0x27, 0x1C, 0x1D, 0x1E, 0x1F, + 0x40, 0x5A, 0x7F, 0x7B, 0x5B, 0x6C, 0x50, 0x7D, 0x4D, 0x5D, 0x5C, 0x4E, 0x6B, 0x60, 0x4B, 0x61, + 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0x7A, 0x5E, 0x4C, 0x7E, 0x6E, 0x6F, + 0x7C, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, + 0xD7, 0xD8, 0xD9, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xAD, 0xE0, 0xBD, 0x5F, 0x6D, + 0x79, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, + 0x97, 0x98, 0x99, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xC0, 0x4F, 0xD0, 0xA1, 0x07, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x06, 0x17, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x09, 0x0A, 0x1B, + 0x30, 0x31, 0x1A, 0x33, 0x34, 0x35, 0x36, 0x08, 0x38, 0x39, 0x3A, 0x3B, 0x04, 0x14, 0x3E, 0xFF, + 0x41, 0xAA, 0x4A, 0xB1, 0x9F, 0xB2, 0x6A, 0xB5, 0xBB, 0xB4, 0x9A, 0x8A, 0xB0, 0xCA, 0xAF, 0xBC, + 0x90, 0x8F, 0xEA, 0xFA, 0xBE, 0xA0, 0xB6, 0xB3, 0x9D, 0xDA, 0x9B, 0x8B, 0xB7, 0xB8, 0xB9, 0xAB, + 0x64, 0x65, 0x62, 0x66, 0x63, 0x67, 0x9E, 0x68, 0x74, 0x71, 0x72, 0x73, 0x78, 0x75, 0x76, 0x77, + 0xAC, 0x69, 0xED, 0xEE, 0xEB, 0xEF, 0xEC, 0xBF, 0x80, 0xFD, 0xFE, 0xFB, 0xFC, 0xBA, 0xAE, 0x59, + 0x44, 0x45, 0x42, 0x46, 0x43, 0x47, 0x9C, 0x48, 0x54, 0x51, 0x52, 0x53, 0x58, 0x55, 0x56, 0x57, + 0x8C, 0x49, 0xCD, 0xCE, 0xCB, 0xCF, 0xCC, 0xE1, 0x70, 0xDD, 0xDE, 0xDB, 0xDC, 0x8D, 0x8E, 0xDF}; + + static int convert_e2a[256] = { + 0x00, 0x01, 0x02, 0x03, 0x9C, 0x09, 0x86, 0x7F, 0x97, 0x8D, 0x8E, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, + 0x10, 0x11, 0x12, 0x13, 0x9D, 0x0A, 0x08, 0x87, 0x18, 0x19, 0x92, 0x8F, 0x1C, 0x1D, 0x1E, 0x1F, + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x17, 0x1B, 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x05, 0x06, 0x07, + 0x90, 0x91, 0x16, 0x93, 0x94, 0x95, 0x96, 0x04, 0x98, 0x99, 0x9A, 0x9B, 0x14, 0x15, 0x9E, 0x1A, + 0x20, 0xA0, 0xE2, 0xE4, 0xE0, 0xE1, 0xE3, 0xE5, 0xE7, 0xF1, 0xA2, 0x2E, 0x3C, 0x28, 0x2B, 0x7C, + 0x26, 0xE9, 0xEA, 0xEB, 0xE8, 0xED, 0xEE, 0xEF, 0xEC, 0xDF, 0x21, 0x24, 0x2A, 0x29, 0x3B, 0x5E, + 0x2D, 0x2F, 0xC2, 0xC4, 0xC0, 0xC1, 0xC3, 0xC5, 0xC7, 0xD1, 0xA6, 0x2C, 0x25, 0x5F, 0x3E, 0x3F, + 0xF8, 0xC9, 0xCA, 0xCB, 0xC8, 0xCD, 0xCE, 0xCF, 0xCC, 0x60, 0x3A, 0x23, 0x40, 0x27, 0x3D, 0x22, + 0xD8, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xAB, 0xBB, 0xF0, 0xFD, 0xFE, 0xB1, + 0xB0, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0xAA, 0xBA, 0xE6, 0xB8, 0xC6, 0xA4, + 0xB5, 0x7E, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0xA1, 0xBF, 0xD0, 0x5B, 0xDE, 0xAE, + 0xAC, 0xA3, 0xA5, 0xB7, 0xA9, 0xA7, 0xB6, 0xBC, 0xBD, 0xBE, 0xDD, 0xA8, 0xAF, 0x5D, 0xB4, 0xD7, + 0x7B, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0xAD, 0xF4, 0xF6, 0xF2, 0xF3, 0xF5, + 0x7D, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0xB9, 0xFB, 0xFC, 0xF9, 0xFA, 0xFF, + 0x5C, 0xF7, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0xB2, 0xD4, 0xD6, 0xD2, 0xD3, 0xD5, + 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0xB3, 0xDB, 0xDC, 0xD9, 0xDA, 0x9F}; +#define decode ENCODE_TO_ASCII(ch) convert_e2a[(unsigned char)ch] +#define decode ENCODE_TO_NATIVE(ch) convert_a2e[(unsigned char)ch] +#else /* APR_CHARSET_EBCDIC */ +#define ENCODE_TO_ASCII(ch) (ch) +#define ENCODE_TO_NATIVE(ch) (ch) +#endif /* !APR_CHARSET_EBCDIC */ + +/** @} */ +#ifdef __cplusplus +} +#endif + +#endif /* !APR_ENCODE_PRIVATE_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/private/apu_config.h b/c/dependencies/windows/apr/x86_debug/include/private/apu_config.h new file mode 100644 index 00000000..b0e20393 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/private/apu_config.h @@ -0,0 +1,52 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Note: This is a Windows specific version of apu_config.hw. It is copied + * as apu_config.h at the start of a Windows build. + */ + +#ifdef WIN32 + +#ifndef APU_CONFIG_H +#define APU_CONFIG_H + +/* Compile win32 with DSO support for .dll builds */ +#ifdef APU_DECLARE_STATIC +#define APU_DSO_BUILD 0 +#else +#define APU_DSO_BUILD 1 +#endif + +/* Presume a standard, modern (5.x) mysql sdk/ +#define HAVE_MY_GLOBAL_H 1 + +/* my_sys.h is broken on VC/Win32, and apparently not required */ +/* #undef HAVE_MY_SYS_H 0 */ + +/* + * Windows does not have GDBM, and we always use the bundled (new) Expat + */ + +/* Define if you have the gdbm library (-lgdbm). */ +/* #undef HAVE_LIBGDBM */ + +/* define if Expat 1.0 or 1.1 was found */ +/* #undef APR_HAVE_OLD_EXPAT */ + + +#endif /* APU_CONFIG_H */ +#endif /* WIN32 */ diff --git a/c/dependencies/windows/apr/x86_debug/include/private/apu_config.hnw b/c/dependencies/windows/apr/x86_debug/include/private/apu_config.hnw new file mode 100644 index 00000000..c7a6124b --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/private/apu_config.hnw @@ -0,0 +1,53 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Note: This is a NetWare specific version of apu_config.hnw. It is copied + * as apu_config.h at the start of a NetWare build. + */ + +#ifdef NETWARE + +#ifndef APU_CONFIG_H +#define APU_CONFIG_H + +/* Always compile Netware with DSO support for .nlm builds */ +#define APU_DSO_BUILD 0 + +/* + * NetWare does not have GDBM, and we always use the bundled (new) Expat + */ + +/* Define if you have the gdbm library (-lgdbm). */ +/* #undef HAVE_LIBGDBM */ + +/* define if Expat 1.0 or 1.1 was found */ +/* #undef APR_HAVE_OLD_EXPAT */ + +/* NetWare uses its own ICONV implementation. */ +#define HAVE_ICONV_H 1 + +/* + * check for newer NDKs which use now correctly 'const char*' with iconv. + */ +#include +#if (CURRENT_NDK_THRESHOLD >= 705110000) +#define APU_ICONV_INBUF_CONST +#endif + +#endif /* APU_CONFIG_H */ +#endif /* NETWARE */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/private/apu_config.hw b/c/dependencies/windows/apr/x86_debug/include/private/apu_config.hw new file mode 100644 index 00000000..ac262fcb --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/private/apu_config.hw @@ -0,0 +1,52 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Note: This is a Windows specific version of apu_config.hw. It is copied + * as apu_config.h at the start of a Windows build. + */ + +#ifdef WIN32 + +#ifndef APU_CONFIG_H +#define APU_CONFIG_H + +/* Compile win32 with DSO support for .dll builds */ +#ifdef APU_DECLARE_STATIC +#define APU_DSO_BUILD 0 +#else +#define APU_DSO_BUILD 1 +#endif + +/* Presume a standard, modern (5.x) mysql sdk/ +#define HAVE_MY_GLOBAL_H 1 + +/* my_sys.h is broken on VC/Win32, and apparently not required */ +/* #undef HAVE_MY_SYS_H 0 */ + +/* + * Windows does not have GDBM, and we always use the bundled (new) Expat + */ + +/* Define if you have the gdbm library (-lgdbm). */ +/* #undef HAVE_LIBGDBM */ + +/* define if Expat 1.0 or 1.1 was found */ +/* #undef APR_HAVE_OLD_EXPAT */ + + +#endif /* APU_CONFIG_H */ +#endif /* WIN32 */ diff --git a/c/dependencies/windows/apr/x86_debug/include/private/apu_internal.h b/c/dependencies/windows/apr/x86_debug/include/private/apu_internal.h new file mode 100644 index 00000000..c95c9d50 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/private/apu_internal.h @@ -0,0 +1,73 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "apr.h" +#include "apr_dso.h" +#include "apu.h" + +#ifndef APU_INTERNAL_H +#define APU_INTERNAL_H + +#if APU_DSO_BUILD + +#ifdef __cplusplus +extern "C" { +#endif + +/* For modular dso loading, an internal interlock to allow us to + * continue to initialize modules by multiple threads, the caller + * of apu_dso_load must lock first, and not unlock until any init + * finalization is complete. + */ +apr_status_t apu_dso_init(apr_pool_t *pool); + +apr_status_t apu_dso_mutex_lock(void); +apr_status_t apu_dso_mutex_unlock(void); + +apr_status_t apu_dso_load(apr_dso_handle_t **dso, apr_dso_handle_sym_t *dsoptr, const char *module, + const char *modsym, apr_pool_t *pool); + +#if APR_HAS_LDAP + +/* For LDAP internal builds, wrap our LDAP namespace */ + +struct apr__ldap_dso_fntable { + int (*info)(apr_pool_t *pool, apr_ldap_err_t **result_err); + int (*init)(apr_pool_t *pool, LDAP **ldap, const char *hostname, + int portno, int secure, apr_ldap_err_t **result_err); + int (*ssl_init)(apr_pool_t *pool, const char *cert_auth_file, + int cert_file_type, apr_ldap_err_t **result_err); + int (*ssl_deinit)(void); + int (*get_option)(apr_pool_t *pool, LDAP *ldap, int option, + void *outvalue, apr_ldap_err_t **result_err); + int (*set_option)(apr_pool_t *pool, LDAP *ldap, int option, + const void *invalue, apr_ldap_err_t **result_err); + apr_status_t (*rebind_init)(apr_pool_t *pool); + apr_status_t (*rebind_add)(apr_pool_t *pool, LDAP *ld, + const char *bindDN, const char *bindPW); + apr_status_t (*rebind_remove)(LDAP *ld); +}; + +#endif /* APR_HAS_LDAP */ + +#ifdef __cplusplus +} +#endif + +#endif /* APU_DSO_BUILD */ + +#endif /* APU_INTERNAL_H */ + diff --git a/c/dependencies/windows/apr/x86_debug/include/private/apu_select_dbm.h b/c/dependencies/windows/apr/x86_debug/include/private/apu_select_dbm.h new file mode 100644 index 00000000..97c7b6c2 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/private/apu_select_dbm.h @@ -0,0 +1,28 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APU_SELECT_DBM_H +#define APU_SELECT_DBM_H + +/* +** The following macros control what features APRUTIL will use +*/ +#define APU_USE_SDBM 1 +#define APU_USE_GDBM 0 +#define APU_USE_NDBM 0 +#define APU_USE_DB 0 + +#endif /* !APU_SELECT_DBM_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/private/apu_select_dbm.h.in b/c/dependencies/windows/apr/x86_debug/include/private/apu_select_dbm.h.in new file mode 100644 index 00000000..d66be5fc --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/private/apu_select_dbm.h.in @@ -0,0 +1,28 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APU_SELECT_DBM_H +#define APU_SELECT_DBM_H + +/* +** The following macros control what features APRUTIL will use +*/ +#define APU_USE_SDBM @apu_use_sdbm@ +#define APU_USE_NDBM @apu_use_ndbm@ +#define APU_USE_GDBM @apu_use_gdbm@ +#define APU_USE_DB @apu_use_db@ + +#endif /* !APU_SELECT_DBM_H */ diff --git a/c/dependencies/windows/apr/x86_debug/include/private/apu_select_dbm.hw b/c/dependencies/windows/apr/x86_debug/include/private/apu_select_dbm.hw new file mode 100644 index 00000000..baa6c144 --- /dev/null +++ b/c/dependencies/windows/apr/x86_debug/include/private/apu_select_dbm.hw @@ -0,0 +1,28 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APU_SELECT_DBM_H +#define APU_SELECT_DBM_H + +/* +** The following macros control what features APRUTIL will use +*/ +#define APU_USE_SDBM 1 +#define APU_USE_GDBM 0 +#define APU_USE_NDBM 0 +#define APU_USE_DB 0 + +#endif /* !APU_SELECT_DBM_H */ diff --git a/c/dependencies/windows/apr/x86_debug/lib/apr.lib b/c/dependencies/windows/apr/x86_debug/lib/apr.lib new file mode 100644 index 00000000..c4801170 Binary files /dev/null and b/c/dependencies/windows/apr/x86_debug/lib/apr.lib differ diff --git a/c/dependencies/windows/apr/x86_debug/lib/apr.pdb b/c/dependencies/windows/apr/x86_debug/lib/apr.pdb new file mode 100644 index 00000000..73ba2479 Binary files /dev/null and b/c/dependencies/windows/apr/x86_debug/lib/apr.pdb differ diff --git a/c/dependencies/windows/apr/x86_debug/lib/aprapp.lib b/c/dependencies/windows/apr/x86_debug/lib/aprapp.lib new file mode 100644 index 00000000..447b2c94 Binary files /dev/null and b/c/dependencies/windows/apr/x86_debug/lib/aprapp.lib differ diff --git a/c/dependencies/windows/apr/x86_debug/lib/aprapp.pdb b/c/dependencies/windows/apr/x86_debug/lib/aprapp.pdb new file mode 100644 index 00000000..c1389195 Binary files /dev/null and b/c/dependencies/windows/apr/x86_debug/lib/aprapp.pdb differ diff --git a/c/dependencies/windows/apr/x86_debug/lib/apriconv.lib b/c/dependencies/windows/apr/x86_debug/lib/apriconv.lib new file mode 100644 index 00000000..04769580 Binary files /dev/null and b/c/dependencies/windows/apr/x86_debug/lib/apriconv.lib differ diff --git a/c/dependencies/windows/apr/x86_debug/lib/apriconv.pdb b/c/dependencies/windows/apr/x86_debug/lib/apriconv.pdb new file mode 100644 index 00000000..eb365f35 Binary files /dev/null and b/c/dependencies/windows/apr/x86_debug/lib/apriconv.pdb differ diff --git a/c/dependencies/windows/apr/x86_debug/lib/aprutil.lib b/c/dependencies/windows/apr/x86_debug/lib/aprutil.lib new file mode 100644 index 00000000..2a634bf5 Binary files /dev/null and b/c/dependencies/windows/apr/x86_debug/lib/aprutil.lib differ diff --git a/c/dependencies/windows/apr/x86_debug/lib/aprutil.pdb b/c/dependencies/windows/apr/x86_debug/lib/aprutil.pdb new file mode 100644 index 00000000..1d952911 Binary files /dev/null and b/c/dependencies/windows/apr/x86_debug/lib/aprutil.pdb differ diff --git a/c/dependencies/windows/apr/x86_debug/lib/libapr.lib b/c/dependencies/windows/apr/x86_debug/lib/libapr.lib new file mode 100644 index 00000000..e7edf0c3 Binary files /dev/null and b/c/dependencies/windows/apr/x86_debug/lib/libapr.lib differ diff --git a/c/dependencies/windows/apr/x86_debug/lib/libapr.pdb b/c/dependencies/windows/apr/x86_debug/lib/libapr.pdb new file mode 100644 index 00000000..0ebb25a9 Binary files /dev/null and b/c/dependencies/windows/apr/x86_debug/lib/libapr.pdb differ diff --git a/c/dependencies/windows/apr/x86_debug/lib/libapr_src.pdb b/c/dependencies/windows/apr/x86_debug/lib/libapr_src.pdb new file mode 100644 index 00000000..c0e22afb Binary files /dev/null and b/c/dependencies/windows/apr/x86_debug/lib/libapr_src.pdb differ diff --git a/c/dependencies/windows/apr/x86_debug/lib/libaprapp.lib b/c/dependencies/windows/apr/x86_debug/lib/libaprapp.lib new file mode 100644 index 00000000..7dc51551 Binary files /dev/null and b/c/dependencies/windows/apr/x86_debug/lib/libaprapp.lib differ diff --git a/c/dependencies/windows/apr/x86_debug/lib/libaprapp.pdb b/c/dependencies/windows/apr/x86_debug/lib/libaprapp.pdb new file mode 100644 index 00000000..ab6d8106 Binary files /dev/null and b/c/dependencies/windows/apr/x86_debug/lib/libaprapp.pdb differ diff --git a/c/dependencies/windows/apr/x86_debug/lib/libapriconv.lib b/c/dependencies/windows/apr/x86_debug/lib/libapriconv.lib new file mode 100644 index 00000000..18512b3a Binary files /dev/null and b/c/dependencies/windows/apr/x86_debug/lib/libapriconv.lib differ diff --git a/c/dependencies/windows/apr/x86_debug/lib/libapriconv.pdb b/c/dependencies/windows/apr/x86_debug/lib/libapriconv.pdb new file mode 100644 index 00000000..5319f303 Binary files /dev/null and b/c/dependencies/windows/apr/x86_debug/lib/libapriconv.pdb differ diff --git a/c/dependencies/windows/apr/x86_debug/lib/libapriconv_src.pdb b/c/dependencies/windows/apr/x86_debug/lib/libapriconv_src.pdb new file mode 100644 index 00000000..c924f292 Binary files /dev/null and b/c/dependencies/windows/apr/x86_debug/lib/libapriconv_src.pdb differ diff --git a/c/dependencies/windows/apr/x86_debug/lib/libaprutil.lib b/c/dependencies/windows/apr/x86_debug/lib/libaprutil.lib new file mode 100644 index 00000000..64b83fbf Binary files /dev/null and b/c/dependencies/windows/apr/x86_debug/lib/libaprutil.lib differ diff --git a/c/dependencies/windows/apr/x86_debug/lib/libaprutil.pdb b/c/dependencies/windows/apr/x86_debug/lib/libaprutil.pdb new file mode 100644 index 00000000..cdef6936 Binary files /dev/null and b/c/dependencies/windows/apr/x86_debug/lib/libaprutil.pdb differ diff --git a/c/dependencies/windows/apr/x86_debug/lib/libaprutil_src.pdb b/c/dependencies/windows/apr/x86_debug/lib/libaprutil_src.pdb new file mode 100644 index 00000000..f905b062 Binary files /dev/null and b/c/dependencies/windows/apr/x86_debug/lib/libaprutil_src.pdb differ diff --git a/c/examples/client_control/change_roles_via_session_filter.c b/c/examples/client_control/change_roles_via_session_filter.c new file mode 100644 index 00000000..af7758d2 --- /dev/null +++ b/c/examples/client_control/change_roles_via_session_filter.c @@ -0,0 +1,81 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_roles_changed( + int number_of_matching_sessions, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + SESSION_T *admin_session = utils_open_session(url, "admin", "password"); + SESSION_T *client_session = utils_open_session(url, "client", "password"); + + printf("Original value\n"); + utils_print_session_properties(admin_session, client_session->id, "$Roles"); + + SET_T *new_roles = set_new_string(1); + set_add(new_roles, "TOPIC_CONTROL"); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_CHANGE_ROLES_WITH_FILTER_PARAMS_T params = { + .filter = "$Principal is 'client'", + .roles_to_remove = NULL, + .roles_to_add = new_roles, + .on_roles_changed = on_roles_changed, + .on_error = on_error, + .context = coordinator + }; + diffusion_change_roles_with_filter(admin_session, params, NULL); + coordinator_wait(coordinator); + + printf("\nChanged value\n"); + utils_print_session_properties(admin_session, client_session->id, "$Roles"); + + session_close(client_session, NULL); + session_free(client_session); + + session_close(admin_session, NULL); + session_free(admin_session); + + coordinator_free(coordinator); + set_free(new_roles); +} \ No newline at end of file diff --git a/c/examples/client_control/change_roles_via_session_id.c b/c/examples/client_control/change_roles_via_session_id.c new file mode 100644 index 00000000..fe894758 --- /dev/null +++ b/c/examples/client_control/change_roles_via_session_id.c @@ -0,0 +1,83 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_roles_changed( + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *admin_session = utils_open_session(url, "admin", "password"); + + SESSION_T *client_session = utils_open_session(url, "client", "password"); + + printf("Original value\n"); + utils_print_session_properties(admin_session, client_session->id, "$Roles"); + + SET_T *new_roles = set_new_string(1); + set_add(new_roles, "TOPIC_CONTROL"); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_CHANGE_ROLES_WITH_SESSION_ID_PARAMS_T params = { + .session_id = client_session->id, + .roles_to_remove = NULL, + .roles_to_add = new_roles, + .on_roles_changed = on_roles_changed, + .on_error = on_error, + .context = coordinator + }; + diffusion_change_roles_with_session_id(admin_session, params, NULL); + coordinator_wait(coordinator); + + printf("\nChanged value\n"); + utils_print_session_properties(admin_session, client_session->id, "$Roles"); + + session_close(client_session, NULL); + session_free(client_session); + + session_close(admin_session, NULL); + session_free(admin_session); + + coordinator_free(coordinator); + set_free(new_roles); +} \ No newline at end of file diff --git a/c/examples/client_control/close_client_via_session_filter.c b/c/examples/client_control/close_client_via_session_filter.c new file mode 100644 index 00000000..293666d8 --- /dev/null +++ b/c/examples/client_control/close_client_via_session_filter.c @@ -0,0 +1,98 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_clients_closed( + int selected, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + +static void on_session_state_changed( + SESSION_T *session, + const SESSION_STATE_T old_state, + const SESSION_STATE_T new_state) +{ + printf( + "Session state changed from %s (%d) to %s (%d)\n", + session_state_as_string(old_state), old_state, + session_state_as_string(new_state), new_state + ); +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *admin_session = utils_open_session(url, "admin", "password"); + + CREDENTIALS_T *client_credentials = + credentials_create_password("password"); + + SESSION_LISTENER_T session_listener = { + .on_state_changed = &on_session_state_changed + }; + + SESSION_T *client_session = session_create( + url, "client", client_credentials, &session_listener, NULL, NULL + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_CLIENT_CLOSE_WITH_FILTER_PARAMS_T params = { + .filter = "$Principal is 'client'", + .on_clients_closed = on_clients_closed, + .on_error = on_error, + .context = coordinator + }; + + diffusion_client_close_with_filter(admin_session, params, NULL); + coordinator_wait(coordinator); + + // Sleep for a bit to see the notifications + sleep(2); + + // session_close(client_session, NULL); + session_free(client_session); + credentials_free(client_credentials); + + session_close(admin_session, NULL); + session_free(admin_session); + + coordinator_free(coordinator); +} \ No newline at end of file diff --git a/c/examples/client_control/close_client_via_session_id.c b/c/examples/client_control/close_client_via_session_id.c new file mode 100644 index 00000000..5df48d69 --- /dev/null +++ b/c/examples/client_control/close_client_via_session_id.c @@ -0,0 +1,94 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_closed(void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + +static void on_session_state_changed( + SESSION_T *session, + const SESSION_STATE_T old_state, + const SESSION_STATE_T new_state) +{ + printf( + "Session state changed from %s (%d) to %s (%d)\n", + session_state_as_string(old_state), old_state, + session_state_as_string(new_state), new_state + ); +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *admin_session = utils_open_session(url, "admin", "password"); + + CREDENTIALS_T *client_credentials = + credentials_create_password("password"); + + SESSION_LISTENER_T session_listener = { + .on_state_changed = &on_session_state_changed + }; + + SESSION_T *client_session = session_create( + url, "client", client_credentials, &session_listener, NULL, NULL + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_CLIENT_CLOSE_WITH_SESSION_PARAMS_T params = { + .session_id = client_session->id, + .on_closed = on_closed, + .on_error = on_error, + .context = coordinator + }; + + diffusion_client_close_with_session(admin_session, params, NULL); + coordinator_wait(coordinator); + + // Sleep for a bit to see the notifications + sleep(2); + + session_free(client_session); + credentials_free(client_credentials); + + session_close(admin_session, NULL); + session_free(admin_session); + + coordinator_free(coordinator); +} \ No newline at end of file diff --git a/c/examples/client_control/get_session_properties_via_session_id.c b/c/examples/client_control/get_session_properties_via_session_id.c new file mode 100644 index 00000000..8230ccb1 --- /dev/null +++ b/c/examples/client_control/get_session_properties_via_session_id.c @@ -0,0 +1,83 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_session_properties( + SESSION_T *session, + const SVC_GET_SESSION_PROPERTIES_RESPONSE_T *response, + void *context) +{ + printf("Received the following session properties:\n"); + utils_print_hash( + response->properties, context, utils_print_string, false + ); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *admin_session = utils_open_session(url, "admin", "password"); + + SESSION_T *client_session = utils_open_session(url, "client", "password"); + + SET_T *required_properties = set_new(1); + set_add(required_properties, PROPERTIES_SELECTOR_ALL_FIXED_PROPERTIES); + + COORDINATOR_T *coordinator = coordinator_init(); + + GET_SESSION_PROPERTIES_PARAMS_T get_session_properties_params = { + .on_session_properties = on_session_properties, + .on_error = on_error, + .session_id = client_session->id, + .required_properties = required_properties, + .context = coordinator + }; + + get_session_properties(admin_session, get_session_properties_params); + coordinator_wait(coordinator); + + session_close(client_session, NULL); + session_free(client_session); + + session_close(admin_session, NULL); + session_free(admin_session); + + coordinator_free(coordinator); + set_free(required_properties); +} \ No newline at end of file diff --git a/c/examples/client_control/queue_conflation_via_session_filter.c b/c/examples/client_control/queue_conflation_via_session_filter.c new file mode 100644 index 00000000..bd375e64 --- /dev/null +++ b/c/examples/client_control/queue_conflation_via_session_filter.c @@ -0,0 +1,73 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_clients_conflated_set( + int selected, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *admin_session = utils_open_session(url, "admin", "password"); + + SESSION_T *client_session = utils_open_session(url, "client", "password"); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_CLIENT_SET_CONFLATED_WITH_FILTER_PARAMS_T params = { + .filter = "$Principal is 'client'", + .on_clients_conflated_set = on_clients_conflated_set, + .on_error = on_error, + .context = coordinator + }; + + diffusion_client_set_conflated_with_filter(admin_session, params, NULL); + coordinator_wait(coordinator); + + session_close(client_session, NULL); + session_free(client_session); + + session_close(admin_session, NULL); + session_free(admin_session); + + coordinator_free(coordinator); +} \ No newline at end of file diff --git a/c/examples/client_control/set_session_properties_via_session_filter.c b/c/examples/client_control/set_session_properties_via_session_filter.c new file mode 100644 index 00000000..48acf387 --- /dev/null +++ b/c/examples/client_control/set_session_properties_via_session_filter.c @@ -0,0 +1,84 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_session_properties_set_filter( + const int number_of_matching_sessions, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *admin_session = utils_open_session(url, "admin", "password"); + + SESSION_T *client_session = utils_open_session(url, "client", "password"); + + printf("Original session properties\n"); + utils_print_session_properties(admin_session, client_session->id, NULL); + + HASH_T *new_session_properties = hash_new(2); + hash_add(new_session_properties, "$Language", "en-gb"); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_SET_SESSION_PROPERTIES_FILTER_PARAMS_T params = { + .filter = "$Principal is 'client'", + .properties = new_session_properties, + .on_session_properties_set = on_session_properties_set_filter, + .on_error = on_error, + .context = coordinator + }; + + diffusion_set_session_properties_filter(admin_session, params, NULL); + coordinator_wait(coordinator); + + printf("\nChanged session properties\n"); + utils_print_session_properties(admin_session, client_session->id, NULL); + + session_close(client_session, NULL); + session_free(client_session); + + session_close(admin_session, NULL); + session_free(admin_session); + + coordinator_free(coordinator); + hash_free(new_session_properties, NULL, NULL); +} \ No newline at end of file diff --git a/c/examples/client_control/set_session_properties_via_session_id.c b/c/examples/client_control/set_session_properties_via_session_id.c new file mode 100644 index 00000000..65d61050 --- /dev/null +++ b/c/examples/client_control/set_session_properties_via_session_id.c @@ -0,0 +1,84 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_session_properties_set( + const HASH_T *properties, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *admin_session = utils_open_session(url, "admin", "password"); + + SESSION_T *client_session = utils_open_session(url, "client", "password"); + + printf("Original session properties\n"); + utils_print_session_properties(admin_session, client_session->id, NULL); + + HASH_T *new_session_properties = hash_new(2); + hash_add(new_session_properties, "$Language", "en-gb"); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_SET_SESSION_PROPERTIES_PARAMS_T params = { + .session_id = client_session->id, + .properties = new_session_properties, + .on_session_properties_set = on_session_properties_set, + .on_error = on_error, + .context = coordinator + }; + + diffusion_set_session_properties(admin_session, params, NULL); + coordinator_wait(coordinator); + + printf("\nChanged session properties\n"); + utils_print_session_properties(admin_session, client_session->id, NULL); + + session_close(client_session, NULL); + session_free(client_session); + + session_close(admin_session, NULL); + session_free(admin_session); + + coordinator_free(coordinator); + hash_free(new_session_properties, NULL, NULL); +} \ No newline at end of file diff --git a/c/examples/connection/establishment/accept_all_certificates.c b/c/examples/connection/establishment/accept_all_certificates.c new file mode 100644 index 00000000..2bbcaff1 --- /dev/null +++ b/c/examples/connection/establishment/accept_all_certificates.c @@ -0,0 +1,53 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + // Define system environment variable indicating to trust self signed certificates + OS_SETENV("DIFFUSION_TRUST_SELF_SIGNED_CERTS", "true"); + + DIFFUSION_ERROR_T error = { 0 }; + SESSION_T *session = session_create( + "wss://localhost:8080", principal, credentials, NULL, NULL, &error + ); + if(session != NULL) { + char *sid_str = session_id_to_string(session->id); + printf("Connected Securely. Session Identifier: %s\n", sid_str); + free(sid_str); + } + else { + printf("Failed to create session: %s\n", error.message); + free(error.message); + } + + // Insert work here + + session_close(session, NULL); + session_free(session); +} \ No newline at end of file diff --git a/c/examples/connection/establishment/accept_specific_certificate.c b/c/examples/connection/establishment/accept_specific_certificate.c new file mode 100644 index 00000000..5d224fe3 --- /dev/null +++ b/c/examples/connection/establishment/accept_specific_certificate.c @@ -0,0 +1,93 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + +#ifndef WIN32 + #include + + char *os_dirname(char *path) { + char *folder_path = dirname(path); + // to maintain simetry with the Windows function, we allocate the memory + char *result = calloc(strlen(folder_path) + 1, sizeof(char)); + memmove(result, folder_path, strlen(folder_path)); + return result; + } + +#else + char *os_dirname(char *path) { + size_t len = 500; + char *result = calloc(len, sizeof(char)); + _splitpath_s( + path, NULL, 0, result, len, NULL, 0, NULL, 0 + ); + char last_char = result[strlen(result) - 1]; + if (last_char == '\\') { + char *trimmed_result = calloc(strlen(result), sizeof(char)); + memmove(trimmed_result, result, strlen(result) - 1); + free(result); + return trimmed_result; + } + return result; + } +#endif + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + extern char *g_executable_path; + + char *executable_folder_path = os_dirname(g_executable_path); + char *target_folder_path = utils_path_to_folder(executable_folder_path, "target"); + + char *certificate_relative_path = calloc(strlen(target_folder_path) + 40, sizeof(char)); + snprintf(certificate_relative_path, strlen(target_folder_path) + 40, "%s/resources/DiffusionData_CA.crt", target_folder_path); + + // Define system environment variable indicating to accept a specific certificate + OS_SETENV("DIFFUSION_TRUST_SELF_SIGNED_CERTS", "true"); + OS_SETENV("DIFFUSION_SSL_CA_FILE_PATH", certificate_relative_path); + + free(certificate_relative_path); + free(target_folder_path); + + DIFFUSION_ERROR_T error = { 0 }; + SESSION_T *session = session_create( + "wss://localhost:8080", principal, credentials, NULL, NULL, &error + ); + if(session != NULL) { + char *sid_str = session_id_to_string(session->id); + printf("Connected Securely. Session Identifier: %s\n", sid_str); + free(sid_str); + } + else { + printf("Failed to create session: %s\n", error.message); + free(error.message); + } + + // Insert work here + + session_close(session, NULL); + session_free(session); +} \ No newline at end of file diff --git a/c/examples/connection/establishment/connect_async.c b/c/examples/connection/establishment/connect_async.c new file mode 100644 index 00000000..b27aa3ea --- /dev/null +++ b/c/examples/connection/establishment/connect_async.c @@ -0,0 +1,72 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + +SESSION_T *g_session; + +static int on_connected( + SESSION_T *session) +{ + g_session = session; + char *sid = session_id_to_string(session->id); + printf("Connected. Session Identifier: %s\n", sid); + free(sid); + + return HANDLER_SUCCESS; +} + + +static int on_error( + SESSION_T *session, + DIFFUSION_ERROR_T *error) +{ + printf("An error has occurred: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_CREATE_CALLBACK_T *callbacks = calloc(1, sizeof(SESSION_CREATE_CALLBACK_T)); + callbacks->on_connected = &on_connected; + callbacks->on_error = &on_error; + + DIFFUSION_ERROR_T error = { 0 }; + session_create_async( + url, principal, credentials, NULL, NULL, callbacks, &error + ); + + // Wait for session to connect + sleep(3); + + // Insert work here + + session_close(g_session, NULL); + session_free(g_session); + + free(callbacks); + } \ No newline at end of file diff --git a/c/examples/connection/establishment/connect_sync.c b/c/examples/connection/establishment/connect_sync.c new file mode 100644 index 00000000..1b85f5d6 --- /dev/null +++ b/c/examples/connection/establishment/connect_sync.c @@ -0,0 +1,49 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + DIFFUSION_ERROR_T error = { 0 }; + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, &error + ); + if(session != NULL) { + char *sid_str = session_id_to_string(session->id); + printf("Connected. Session Identifier: %s\n", sid_str); + free(sid_str); + } + else { + printf("Failed to create session: %s\n", error.message); + free(error.message); + } + + // Insert work here + + session_close(session, NULL); + session_free(session); +} \ No newline at end of file diff --git a/c/examples/connection/establishment/connect_sync_with_context.c b/c/examples/connection/establishment/connect_sync_with_context.c new file mode 100644 index 00000000..493dba77 --- /dev/null +++ b/c/examples/connection/establishment/connect_sync_with_context.c @@ -0,0 +1,74 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" +MUTEX_DEF + +static void on_session_state_changed( + SESSION_T *session, + const SESSION_STATE_T old_state, + const SESSION_STATE_T new_state) +{ + printf( + "Session state changed from %s (%d) to %s (%d)\n", + session_state_as_string(old_state), old_state, + session_state_as_string(new_state), new_state + ); + + printf("The user context for the session is: %s\n", (char *) session->user_context); + MUTEX_BROADCAST +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + MUTEX_INIT + char *user_context = "This is the user context for the session to be created."; + + SESSION_LISTENER_T session_listener = { 0 }; + session_listener.on_state_changed = &on_session_state_changed; + + DIFFUSION_ERROR_T error = { 0 }; + SESSION_T *session = session_create_with_user_context( + url, principal, credentials, &session_listener, NULL, user_context, &error + ); + MUTEX_WAIT + + if(session != NULL) { + char *sid_str = session_id_to_string(session->id); + printf("Connected. Session Identifier: %s\n", sid_str); + free(sid_str); + } + else { + printf("Failed to create session: %s\n", error.message); + free(error.message); + } + + // Insert work here + + session_close(session, NULL); + session_free(session); + MUTEX_TERMINATE +} \ No newline at end of file diff --git a/c/examples/connection/establishment/connect_via_factory.c b/c/examples/connection/establishment/connect_via_factory.c new file mode 100644 index 00000000..59b0bee4 --- /dev/null +++ b/c/examples/connection/establishment/connect_via_factory.c @@ -0,0 +1,50 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + DIFFUSION_SESSION_FACTORY_T *session_factory = diffusion_session_factory_init(); + diffusion_session_factory_principal(session_factory, principal); + diffusion_session_factory_credentials(session_factory, credentials); + + SESSION_T *session = session_create_with_session_factory(session_factory, url); + if(session != NULL) { + char *sid_str = session_id_to_string(session->id); + printf("Connected. Session Identifier: %s\n", sid_str); + free(sid_str); + } + else { + printf("Failed to create session.\n"); + } + + // Insert work here + + session_close(session, NULL); + session_free(session); + diffusion_session_factory_free(session_factory); +} \ No newline at end of file diff --git a/c/examples/connection/resilience/reconnection_strategy.c b/c/examples/connection/resilience/reconnection_strategy.c new file mode 100644 index 00000000..5c41836c --- /dev/null +++ b/c/examples/connection/resilience/reconnection_strategy.c @@ -0,0 +1,45 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + RECONNECTION_STRATEGY_T reconnection_strategy = { + .retry_count = 3, + .retry_delay = 1000 + }; + + DIFFUSION_ERROR_T error = { 0 }; + SESSION_T *session = session_create( + url, principal, credentials, NULL, &reconnection_strategy, &error + ); + + // Insert work here + + session_close(session, NULL); + session_free(session); +} \ No newline at end of file diff --git a/c/examples/connection/resilience/session_establishment_retry_mechanism.c b/c/examples/connection/resilience/session_establishment_retry_mechanism.c new file mode 100644 index 00000000..0c0d7a2f --- /dev/null +++ b/c/examples/connection/resilience/session_establishment_retry_mechanism.c @@ -0,0 +1,46 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + DIFFUSION_RETRY_STRATEGY_T *strategy = diffusion_retry_strategy_create(250, 10, NULL); + + DIFFUSION_SESSION_FACTORY_T *session_factory = diffusion_session_factory_init(); + diffusion_session_factory_principal(session_factory, principal); + diffusion_session_factory_credentials(session_factory, credentials); + diffusion_session_factory_initial_retry_strategy(session_factory, strategy); + + SESSION_T *session = session_create_with_session_factory(session_factory, url); + + // Insert work here + + session_close(session, NULL); + session_free(session); + diffusion_session_factory_free(session_factory); + diffusion_retry_strategy_free(strategy); +} \ No newline at end of file diff --git a/c/examples/connection/session_state_listener.c b/c/examples/connection/session_state_listener.c new file mode 100644 index 00000000..2d9adef6 --- /dev/null +++ b/c/examples/connection/session_state_listener.c @@ -0,0 +1,66 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static void on_session_state_changed( + SESSION_T *session, + const SESSION_STATE_T old_state, + const SESSION_STATE_T new_state) +{ + printf( + "Session state changed from %s (%d) to %s (%d)\n", + session_state_as_string(old_state), old_state, + session_state_as_string(new_state), new_state + ); +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + SESSION_LISTENER_T session_listener = { + .on_state_changed = &on_session_state_changed + }; + + DIFFUSION_ERROR_T error = { 0 }; + SESSION_T *session = session_create( + url, principal, credentials, &session_listener, NULL, &error + ); + if(session != NULL) { + char *sid_str = session_id_to_string(session->id); + printf("Connected. Session Identifier: %s\n", sid_str); + free(sid_str); + } + else { + printf("Failed to create session: %s\n", error.message); + free(error.message); + } + + // Insert work here + + session_close(session, NULL); + session_free(session); +} \ No newline at end of file diff --git a/c/examples/examples.cmake b/c/examples/examples.cmake new file mode 100644 index 00000000..43c0f48d --- /dev/null +++ b/c/examples/examples.cmake @@ -0,0 +1,213 @@ +function(add_example FOLDER_PATH FILE_NAME COPY_RESOURCES) + string(REPLACE "/" "_" EXAMPLE_PREFIX ${FOLDER_PATH}) + set(EXAMPLE_NAME "${EXAMPLE_PREFIX}_${FILE_NAME}") + add_executable( + ${EXAMPLE_NAME} + "${EXAMPLES_SOURCE_FOLDER}/main.c" + "${EXAMPLES_SOURCE_FOLDER}/${FOLDER_PATH}/${FILE_NAME}.c" + "${EXAMPLES_SOURCE_FOLDER}/utils/utils.c" + "${EXAMPLES_SOURCE_FOLDER}/utils/coordinator.c" + ) + target_link_libraries(${EXAMPLE_NAME} PRIVATE ${DEPENDENCIES} Threads::Threads ${ADDITIONAL_LD_FLAGS}) + target_include_directories(${EXAMPLE_NAME} PUBLIC ${INCLUDE_DIRECTORIES}) + + if (${COPY_RESOURCES} STREQUAL "true") + cmake_path(SET RESOURCES_PATH ${TARGET}/resources) + + add_custom_command( + TARGET ${EXAMPLE_NAME} POST_BUILD + COMMAND ${CMAKE_COMMAND} -E make_directory "${RESOURCES_PATH}" + ) + + file(GLOB RESOURCES_FILES_LIST ${RESOURCES_SOURCE_FOLDER}/[^.]*) + + foreach(FILE IN ITEMS ${RESOURCES_FILES_LIST}) + add_custom_command( + TARGET ${EXAMPLE_NAME} POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${FILE}" "${RESOURCES_PATH}/" + ) + endforeach() + + if (WIN32) + cmake_path(SET LIB_PATH ${TARGET}/lib/${ARCHITECTURE}) + + add_custom_command( + TARGET ${EXAMPLE_NAME} POST_BUILD + COMMAND ${CMAKE_COMMAND} -E make_directory "${LIB_PATH}" + ) + + foreach(FILE IN ITEMS ${WINDOWS_PATH}) + message(STATUS "Copying ${FILE} to ${LIB_PATH}") + add_custom_command( + TARGET ${EXAMPLE_NAME} POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${FILE}" "${LIB_PATH}/" + ) + endforeach() + endif() + endif() +endfunction() + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror -O1 -fsanitize=address -g -fno-omit-frame-pointer -Wdeprecated-declarations") + +# Examples +file(GLOB_RECURSE SRCS ${EXAMPLES_SOURCE_FOLDER}/*.[hc]) + +add_example("connection/establishment" "connect_async" "false") +add_example("connection/establishment" "connect_sync_with_context" "false") +add_example("connection/establishment" "accept_all_certificates" "false") +add_example("connection/establishment" "accept_specific_certificate" "true") +add_example("connection/establishment" "connect_sync" "false") +add_example("connection/establishment" "connect_via_factory" "false") + +add_example("connection" "session_state_listener" "false") + +add_example("connection/resilience" "session_establishment_retry_mechanism" "false") +add_example("connection/resilience" "reconnection_strategy" "false") + +add_example("ping" "ping_server" "false") + +add_example("security" "change_principal" "false") +add_example("security" "reauthenticate" "false") +add_example("security" "get_global_permissions" "false") +add_example("security" "get_path_permissions" "false") + +add_example("pub_sub/publish" "add_topic" "false") +add_example("pub_sub/publish" "add_topic_custom_properties" "false") +add_example("pub_sub/publish" "add_and_set_topic" "false") +add_example("pub_sub/publish" "set_topic" "false") +add_example("pub_sub/publish" "add_and_set_topic_via_update_stream" "false") +add_example("pub_sub/publish" "set_topic_via_update_stream" "false") +add_example("pub_sub/publish/with_constraint" "add_and_set_topic_no_topic" "false") +add_example("pub_sub/publish/with_constraint" "add_and_set_topic_value" "false") +add_example("pub_sub/publish/with_constraint" "add_and_set_topic_session_lock" "false") +add_example("pub_sub/publish/with_constraint" "add_and_set_topic_json_value_with" "false") +add_example("pub_sub/publish/with_constraint" "add_and_set_topic_json_value_without" "false") +add_example("pub_sub/publish/with_constraint" "add_and_set_topic_and" "false") +add_example("pub_sub/publish/with_constraint" "add_and_set_topic_or" "false") +add_example("pub_sub/publish/with_constraint" "set_topic_no_value" "false") +add_example("pub_sub/publish/with_constraint" "set_topic_value" "false") +add_example("pub_sub/publish/with_constraint" "set_topic_session_lock" "false") +add_example("pub_sub/publish/with_constraint" "set_topic_json_value_with" "false") +add_example("pub_sub/publish/with_constraint" "set_topic_json_value_without" "false") + +add_example("pub_sub/subscribe" "cross_compatible" "false") +add_example("pub_sub/subscribe" "fallback_stream" "false") +add_example("pub_sub/subscribe" "multiple_topics_via_selector" "false") +add_example("pub_sub/subscribe" "selection_scopes" "false") +add_example("pub_sub/subscribe" "single_topic_via_path" "false") + +add_example("pub_sub/remove" "multiple_topics_via_selector" "false") +add_example("pub_sub/remove" "single_topic_via_path" "false") +add_example("pub_sub/remove" "automatic_topic_removal" "false") + +add_example("pub_sub/fetch" "topic_properties" "false") +add_example("pub_sub/fetch" "topic_via_paging" "false") + +add_example("pub_sub/json_patch" "add" "false") +add_example("pub_sub/json_patch" "copy" "false") +add_example("pub_sub/json_patch" "move" "false") +add_example("pub_sub/json_patch" "remove" "false") +add_example("pub_sub/json_patch" "replace" "false") +add_example("pub_sub/json_patch" "test" "false") + +add_example("time_series" "append_user_supplied_timestamp" "false") +add_example("time_series" "append_value_via_update_stream" "false") +add_example("time_series" "append_value" "false") +add_example("time_series" "create_topic" "false") +add_example("time_series" "edit_value" "false") +add_example("time_series" "range_query" "false") +add_example("time_series" "subscribe_cross_compatible" "false") +add_example("time_series" "subscribe" "false") + +add_example("messaging" "send_to_path" "false") +add_example("messaging" "send_to_session_id" "false") +add_example("messaging" "send_to_session_filter" "false") + +add_example("wrangling/topic_views/api" "add" "false") +add_example("wrangling/topic_views/api" "list" "false") +add_example("wrangling/topic_views/api" "remove" "false") + +add_example("wrangling/topic_views/dsl" "source_path_directive" "false") +add_example("wrangling/topic_views/dsl" "remote_topic_view" "false") +add_example("wrangling/topic_views/dsl" "scalar_directive" "false") +add_example("wrangling/topic_views/dsl" "expand_value" "false") +add_example("wrangling/topic_views/dsl" "insert_transformations" "false") + +add_example("wrangling/topic_views/dsl/process_transformations" "set" "false") +add_example("wrangling/topic_views/dsl/process_transformations" "remove" "false") +add_example("wrangling/topic_views/dsl/process_transformations" "continue" "false") + +add_example("wrangling/topic_views/dsl/patch_transformations" "add" "false") +add_example("wrangling/topic_views/dsl/patch_transformations" "remove" "false") +add_example("wrangling/topic_views/dsl/patch_transformations" "replace" "false") +add_example("wrangling/topic_views/dsl/patch_transformations" "move" "false") +add_example("wrangling/topic_views/dsl/patch_transformations" "copy" "false") +add_example("wrangling/topic_views/dsl/patch_transformations" "test" "false") + +add_example("wrangling/topic_views/dsl/options" "topic_property_mapping" "false") +add_example("wrangling/topic_views/dsl/options" "topic_value" "false") +add_example("wrangling/topic_views/dsl/options" "throttle" "false") +add_example("wrangling/topic_views/dsl/options" "delay" "false") +add_example("wrangling/topic_views/dsl/options" "separator" "false") +add_example("wrangling/topic_views/dsl/options" "preserve_topics" "false") +add_example("wrangling/topic_views/dsl/options" "topic_type" "false") + +add_example("wrangling/session_trees" "put_branch_mapping_table" "false") +add_example("wrangling/session_trees" "list_session_tree_branches_with_mappings" "false") +add_example("wrangling/session_trees" "get_branch_mapping_table" "false") +add_example("wrangling/session_trees" "use_case" "false") +add_example("wrangling/session_trees" "put_and_remove_branch_mapping_table" "false") + +add_example("monitoring" "missing_topic_notifications" "false") +add_example("monitoring" "topic_notifications" "false") +add_example("monitoring" "session_properties_listener" "false") + +add_example("session_management" "subscription_control" "false") +add_example("session_management" "authentication_control" "false") + +add_example("client_control" "get_session_properties_via_session_id" "false") +add_example("client_control" "set_session_properties_via_session_id" "false") +add_example("client_control" "set_session_properties_via_session_filter" "false") +add_example("client_control" "close_client_via_session_id" "false") +add_example("client_control" "close_client_via_session_filter" "false") +add_example("client_control" "change_roles_via_session_id" "false") +add_example("client_control" "change_roles_via_session_filter" "false") +add_example("client_control" "queue_conflation_via_session_filter" "false") + +add_example("server_configuration/metrics" "session_metric_collector_put" "false") +add_example("server_configuration/metrics" "session_metric_collector_list" "false") +add_example("server_configuration/metrics" "session_metric_collector_remove" "false") +add_example("server_configuration/metrics" "topic_metric_collector_put" "false") +add_example("server_configuration/metrics" "topic_metric_collector_list" "false") +add_example("server_configuration/metrics" "topic_metric_collector_remove" "false") + +add_example("server_configuration/security_control" "isolate_path" "false") +add_example("server_configuration/security_control" "deisolate_path" "false") +add_example("server_configuration/security_control" "set_path_permissions" "false") +add_example("server_configuration/security_control" "remove_path_permissions" "false") +add_example("server_configuration/security_control" "set_default_path_permissions" "false") +add_example("server_configuration/security_control" "set_global_permissions" "false") +add_example("server_configuration/security_control" "define_roles_hierarchy" "false") +add_example("server_configuration/security_control" "restrict_role_edit_permissions" "false") +add_example("server_configuration/security_control" "set_default_roles_for_anonymous_sessions" "false") +add_example("server_configuration/security_control" "set_default_roles_for_named_sessions" "false") + +add_example("server_configuration/system_authentication_control" "deny_anonymous_connections" "false") +add_example("server_configuration/system_authentication_control" "abstain_anonymous_connections" "false") +add_example("server_configuration/system_authentication_control" "allow_anonymous_connections" "false") +add_example("server_configuration/system_authentication_control" "add_principal" "false") +add_example("server_configuration/system_authentication_control" "add_locked_principal" "false") +add_example("server_configuration/system_authentication_control" "remove_principal" "false") +add_example("server_configuration/system_authentication_control" "assign_roles" "false") +add_example("server_configuration/system_authentication_control" "change_password" "false") +add_example("server_configuration/system_authentication_control" "verify_password" "false") +add_example("server_configuration/system_authentication_control" "trust_client_proposed_property_in" "false") +add_example("server_configuration/system_authentication_control" "trust_client_proposed_property_matches" "false") +add_example("server_configuration/system_authentication_control" "ignore_client_proposed_property" "false") + +add_example("remote_servers" "create_primary_initiator" "false") +add_example("remote_servers" "create_secondary_initiator" "false") +add_example("remote_servers" "create_secondary_acceptor" "false") +add_example("remote_servers" "list" "false") +add_example("remote_servers" "check" "false") +add_example("remote_servers" "remove" "false") diff --git a/c/examples/main.c b/c/examples/main.c new file mode 100644 index 00000000..81df52d9 --- /dev/null +++ b/c/examples/main.c @@ -0,0 +1,70 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#ifndef WIN32 + #include +#else + #define sleep(x) Sleep(1000 * x) +#endif + +#include "diffusion.h" +#include "args.h" + + +ARG_OPTS_T g_arg_options[] = { + ARG_OPTS_HELP, + {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, + {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, + {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, + END_OF_ARG_OPTS +}; + +char *g_executable_path; + + +void run_example(const char *url, const char *principal, CREDENTIALS_T *credentials); + + +int main(int argc, char **argv) +{ + HASH_T *options = parse_cmdline(argc, argv, g_arg_options); + if(options == NULL || hash_get(options, "help") != NULL) { + show_usage(argc, argv, g_arg_options); + return EXIT_FAILURE; + } + + const char *url = hash_get(options, "url"); + const char *principal = hash_get(options, "principal"); + const char *password = hash_get(options, "credentials"); + + g_executable_path = argv[0]; + + CREDENTIALS_T *credentials = NULL; + if(password != NULL) { + credentials = credentials_create_password(password); + } + run_example(url, principal, credentials); + + credentials_free(credentials); + hash_free(options, NULL, free); + + return EXIT_SUCCESS; +} diff --git a/c/examples/messaging/send_to_path.c b/c/examples/messaging/send_to_path.c new file mode 100644 index 00000000..1f00afbb --- /dev/null +++ b/c/examples/messaging/send_to_path.c @@ -0,0 +1,120 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" +MUTEX_DEF + +static int on_active( + SESSION_T *session, + const char *path, + const DIFFUSION_REGISTRATION_T *registered_handler) +{ + MUTEX_BROADCAST + return HANDLER_SUCCESS; +} + +static int on_request ( + SESSION_T *session, + DIFFUSION_DATATYPE request_datatype, + const DIFFUSION_VALUE_T *request, + const DIFFUSION_REQUEST_CONTEXT_T *request_context, + const DIFFUSION_RESPONDER_HANDLE_T *handle, + void *context) +{ + char *request_string_value; + read_diffusion_string_value(request, &request_string_value, NULL); + printf("Received message: %s\n", request_string_value); + free(request_string_value); + + BUF_T *response = buf_create(); + write_diffusion_string_value("Goodbye.", response); + diffusion_respond_to_request(session, handle, response, NULL); + buf_free(response); + return HANDLER_SUCCESS; +} + +static int on_response( + DIFFUSION_DATATYPE response_datatype, + const DIFFUSION_VALUE_T *response, + void *context) +{ + char *response_string_value; + read_diffusion_string_value(response, &response_string_value, NULL); + printf("Received response: %s\n", response_string_value); + free(response_string_value); + + MUTEX_BROADCAST + return HANDLER_SUCCESS; +} + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + MUTEX_INIT + SESSION_T *receiving_session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + const char *message_path = "my/message/path"; + + DIFFUSION_REQUEST_HANDLER_T request_handler = { + .request_datatype = DATATYPE_STRING, + .response_datatype = DATATYPE_STRING, + .on_active = on_active, + .on_request = on_request + }; + + ADD_REQUEST_HANDLER_PARAMS_T request_handler_params = { + .path = message_path, + .request_handler = &request_handler + }; + add_request_handler(receiving_session, request_handler_params); + MUTEX_WAIT + + SESSION_T *sending_session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + BUF_T *request = buf_create(); + write_diffusion_string_value("Hello.", request); + + SEND_REQUEST_PARAMS_T send_request_params = { + .path = message_path, + .request = request, + .on_response = on_response, + .request_datatype = DATATYPE_STRING, + .response_datatype = DATATYPE_STRING + }; + send_request(sending_session, send_request_params); + MUTEX_WAIT + + buf_free(request); + + session_close(receiving_session, NULL); + session_free(receiving_session); + + session_close(sending_session, NULL); + session_free(sending_session); + MUTEX_TERMINATE +} \ No newline at end of file diff --git a/c/examples/messaging/send_to_session_filter.c b/c/examples/messaging/send_to_session_filter.c new file mode 100644 index 00000000..259308a0 --- /dev/null +++ b/c/examples/messaging/send_to_session_filter.c @@ -0,0 +1,167 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" +MUTEX_DEF + +static int on_active( + SESSION_T *session, + const char *path, + const DIFFUSION_REGISTRATION_T *registered_handler) +{ + MUTEX_BROADCAST + return HANDLER_SUCCESS; +} + +static int on_request ( + SESSION_T *session, + const char *request_path, + DIFFUSION_DATATYPE request_datatype, + const DIFFUSION_VALUE_T *request, + const DIFFUSION_RESPONDER_HANDLE_T *handle, + void *context) +{ + char *request_string_value; + read_diffusion_string_value(request, &request_string_value, NULL); + printf("Received message: %s\n", request_string_value); + free(request_string_value); + + BUF_T *response = buf_create(); + write_diffusion_string_value("Goodbye.", response); + diffusion_respond_to_request(session, handle, response, NULL); + buf_free(response); + return HANDLER_SUCCESS; +} + +static int on_request_unexpected( + SESSION_T *session, + const char *request_path, + DIFFUSION_DATATYPE request_datatype, + const DIFFUSION_VALUE_T *request, + const DIFFUSION_RESPONDER_HANDLE_T *handle, + void *context) +{ + char *request_string_value; + read_diffusion_string_value(request, &request_string_value, NULL); + printf("Received message: %s\n", request_string_value); + free(request_string_value); + + BUF_T *response = buf_create(); + write_diffusion_string_value("I'm not supposed to receive a message.", response); + diffusion_respond_to_request(session, handle, response, NULL); + buf_free(response); + return HANDLER_SUCCESS; +} + +static int on_response( + DIFFUSION_DATATYPE response_datatype, + const DIFFUSION_VALUE_T *response, + void *context) +{ + char *response_string_value; + read_diffusion_string_value(response, &response_string_value, NULL); + printf("Received response: %s\n", response_string_value); + free(response_string_value); + MUTEX_BROADCAST + + return HANDLER_SUCCESS; +} + +static int on_number_sent( + int number_sent, + void *context) +{ + printf("Message sent to %d session(s).\n", number_sent); + return HANDLER_SUCCESS; +} + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + MUTEX_INIT + SESSION_T *receiving_session = session_create( + url, "admin", credentials, NULL, NULL, NULL + ); + SESSION_ID_T *receiving_session_id = receiving_session->id; + + const char *message_path = "my/message/path"; + + DIFFUSION_REQUEST_STREAM_T receiving_request_stream = { + .on_request = on_request + }; + set_request_stream( + receiving_session, + message_path, + DATATYPE_STRING, + DATATYPE_STRING, + &receiving_request_stream + ); + + SESSION_T *non_receiving_session = session_create( + url, "control", credentials, NULL, NULL, NULL + ); + + DIFFUSION_REQUEST_STREAM_T non_receiving_request_stream = { + .on_request = on_request_unexpected + }; + set_request_stream( + non_receiving_session, + message_path, + DATATYPE_STRING, + DATATYPE_STRING, + &non_receiving_request_stream + ); + + SESSION_T *sending_session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + BUF_T *request = buf_create(); + write_diffusion_string_value("Hello.", request); + + SEND_REQUEST_TO_FILTER_PARAMS_T send_request_params = { + .path = message_path, + .filter = "$Principal EQ 'admin'", + .request_datatype = DATATYPE_STRING, + .response_datatype = DATATYPE_STRING, + .request = request, + .on_number_sent = on_number_sent, + .on_response = on_response + }; + send_request_to_filter(sending_session, send_request_params); + MUTEX_WAIT + + buf_free(request); + + session_close(receiving_session, NULL); + session_free(receiving_session); + + session_close(non_receiving_session, NULL); + session_free(non_receiving_session); + + session_close(sending_session, NULL); + session_free(sending_session); + + MUTEX_TERMINATE +} \ No newline at end of file diff --git a/c/examples/messaging/send_to_session_id.c b/c/examples/messaging/send_to_session_id.c new file mode 100644 index 00000000..8dce5845 --- /dev/null +++ b/c/examples/messaging/send_to_session_id.c @@ -0,0 +1,157 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" +MUTEX_DEF + +static int on_active( + SESSION_T *session, + const char *path, + const DIFFUSION_REGISTRATION_T *registered_handler) +{ + MUTEX_BROADCAST + return HANDLER_SUCCESS; +} + +static int on_request ( + SESSION_T *session, + const char *request_path, + DIFFUSION_DATATYPE request_datatype, + const DIFFUSION_VALUE_T *request, + const DIFFUSION_RESPONDER_HANDLE_T *handle, + void *context) +{ + char *request_string_value; + read_diffusion_string_value(request, &request_string_value, NULL); + printf("Received message: %s\n", request_string_value); + free(request_string_value); + + BUF_T *response = buf_create(); + write_diffusion_string_value("Goodbye.", response); + diffusion_respond_to_request(session, handle, response, NULL); + buf_free(response); + return HANDLER_SUCCESS; +} + +static int on_request_unexpected( + SESSION_T *session, + const char *request_path, + DIFFUSION_DATATYPE request_datatype, + const DIFFUSION_VALUE_T *request, + const DIFFUSION_RESPONDER_HANDLE_T *handle, + void *context) +{ + char *request_string_value; + read_diffusion_string_value(request, &request_string_value, NULL); + printf("Received message: %s\n", request_string_value); + free(request_string_value); + + BUF_T *response = buf_create(); + write_diffusion_string_value("I'm not supposed to receive a message.", response); + diffusion_respond_to_request(session, handle, response, NULL); + buf_free(response); + return HANDLER_SUCCESS; +} + +static int on_response( + DIFFUSION_DATATYPE response_datatype, + const DIFFUSION_VALUE_T *response, + void *context) +{ + char *response_string_value; + read_diffusion_string_value(response, &response_string_value, NULL); + printf("Received response: %s\n", response_string_value); + free(response_string_value); + MUTEX_BROADCAST + + return HANDLER_SUCCESS; +} + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + MUTEX_INIT + SESSION_T *receiving_session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + SESSION_ID_T *receiving_session_id = receiving_session->id; + + const char *message_path = "my/message/path"; + + DIFFUSION_REQUEST_STREAM_T receiving_request_stream = { + .on_request = on_request + }; + set_request_stream( + receiving_session, + message_path, + DATATYPE_STRING, + DATATYPE_STRING, + &receiving_request_stream + ); + + SESSION_T *non_receiving_session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + DIFFUSION_REQUEST_STREAM_T non_receiving_request_stream = { + .on_request = on_request_unexpected + }; + set_request_stream( + non_receiving_session, + message_path, + DATATYPE_STRING, + DATATYPE_STRING, + &non_receiving_request_stream + ); + + SESSION_T *sending_session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + BUF_T *request = buf_create(); + write_diffusion_string_value("Hello.", request); + + SEND_REQUEST_TO_SESSION_PARAMS_T send_request_params = { + .recipient_session = receiving_session_id, + .path = message_path, + .request = request, + .on_response = on_response, + .request_datatype = DATATYPE_STRING, + .response_datatype = DATATYPE_STRING + }; + send_request_to_session(sending_session, send_request_params); + MUTEX_WAIT + + buf_free(request); + + session_close(receiving_session, NULL); + session_free(receiving_session); + + session_close(non_receiving_session, NULL); + session_free(non_receiving_session); + + session_close(sending_session, NULL); + session_free(sending_session); + MUTEX_TERMINATE +} \ No newline at end of file diff --git a/c/examples/monitoring/missing_topic_notifications.c b/c/examples/monitoring/missing_topic_notifications.c new file mode 100644 index 00000000..1eed34bb --- /dev/null +++ b/c/examples/monitoring/missing_topic_notifications.c @@ -0,0 +1,113 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" +MUTEX_DEF + +SESSION_T *g_control_session; + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + +static int on_missing_topic( + SESSION_T * session, + const SVC_MISSING_TOPIC_REQUEST_T *request, + void *context) +{ + printf("Received missing topic notification:\n"); + char *session_id = session_id_to_string(request->session_id); + printf("\tSession ID: %s\n", session_id); + free(session_id); + + printf("\tTopic Selector: %s\n", request->topic_selector); + + char *topic_path; + size_t topic_name_length = strlen(request->topic_selector); + if (request->topic_selector[0] == '>') { + topic_path = calloc(topic_name_length, sizeof(char)); + strncpy(topic_path, request->topic_selector + 1, topic_name_length - 1); + } + else { + topic_path = strdup(request->topic_selector); + } + + utils_create_string_topic( + g_control_session, topic_path, "Hello"); + + free(topic_path); + + MUTEX_BROADCAST + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + MUTEX_INIT + + SESSION_T *admin_session = utils_open_session(url, "admin", "password"); + + const char *topic_path_root = "my/topic/path"; + + MISSING_TOPIC_PARAMS_T missing_topic_params = { + .topic_path = topic_path_root, + .on_missing_topic = on_missing_topic, + .on_error = on_error + }; + + CONVERSATION_ID_T *missing_topic_cid = + missing_topic_register_handler(admin_session, missing_topic_params); + + g_control_session = utils_open_session(url, "control", "password"); + + VALUE_STREAM_T *value_stream_ptr = utils_subscribe( + g_control_session, "my/topic/path/does/not/exist/yet", DATATYPE_STRING + ); + MUTEX_WAIT + + // Sleep for a bit to see the notifications + sleep(2); + + + missing_topic_deregister_handler(admin_session, missing_topic_cid); + + // Sleep for a bit to see the notifications + sleep(2); + + session_close(g_control_session, NULL); + session_free(g_control_session); + + session_close(admin_session, NULL); + session_free(admin_session); + + conversation_id_free(missing_topic_cid); + free(value_stream_ptr); + MUTEX_TERMINATE +} \ No newline at end of file diff --git a/c/examples/monitoring/session_properties_listener.c b/c/examples/monitoring/session_properties_listener.c new file mode 100644 index 00000000..a028d30a --- /dev/null +++ b/c/examples/monitoring/session_properties_listener.c @@ -0,0 +1,152 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_listener_registered(SESSION_T *session, void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_registration_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + +static int on_session_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On session error: %s\n", error->message); + return HANDLER_SUCCESS; +} + +static int on_session_open( + SESSION_T *session, + const SESSION_PROPERTIES_EVENT_T *request, + void *context) +{ + char *session_id = session_id_to_string(&request->session_id); + printf("Session %s is now open with the following properties:\n", session_id); + utils_print_hash( + request->properties, NULL, utils_print_string, false + ); + + free(session_id); + return HANDLER_SUCCESS; +} + +static int on_session_update( + SESSION_T *session, + const SESSION_PROPERTIES_EVENT_T *request, + void *context) +{ + HASH_NUM_T *update_map = hash_num_new(10); + hash_num_add(update_map, SESSION_PROPERTIES_UPDATE_TYPE_UPDATED, "Properties Update"); + hash_num_add(update_map, SESSION_PROPERTIES_UPDATE_TYPE_RECONNECTED, "Reconnected"); + hash_num_add(update_map, SESSION_PROPERTIES_UPDATE_TYPE_FAILED_OVER, "Failed Over"); + hash_num_add(update_map, SESSION_PROPERTIES_UPDATE_TYPE_DISCONNECTED, "Disconnected"); + + char *update_type = hash_num_get(update_map, request->update_type); + char *session_id = session_id_to_string(&request->session_id); + printf("Session %s has been updated (%s) with the following properties:\n", session_id, update_type); + utils_print_hash( + request->properties, NULL, utils_print_string, false + ); + + free(session_id); + hash_num_free(update_map, NULL); + return HANDLER_SUCCESS; +} + +static int on_session_close( + SESSION_T *session, + const SESSION_PROPERTIES_EVENT_T *request, + void *context) +{ + HASH_NUM_T *close_reason_map = hash_num_new(10); + hash_num_add(close_reason_map, SESSION_CLOSE_REASON_CONNECTION_LOST, "Connection Lost"); + hash_num_add(close_reason_map, SESSION_CLOSE_REASON_IO_EXCEPTION, "Connection Lost"); + hash_num_add(close_reason_map, SESSION_CLOSE_REASON_CLIENT_UNRESPONSIVE, "Connection Lost"); + hash_num_add(close_reason_map, SESSION_CLOSE_REASON_MESSAGE_QUEUE_LIMIT_REACHED, "Connection Lost"); + hash_num_add(close_reason_map, SESSION_CLOSE_REASON_CLOSED_BY_CLIENT, "Connection Lost"); + hash_num_add(close_reason_map, SESSION_CLOSE_REASON_MESSAGE_TOO_LARGE, "Connection Lost"); + hash_num_add(close_reason_map, SESSION_CLOSE_REASON_INTERNAL_ERROR, "Connection Lost"); + hash_num_add(close_reason_map, SESSION_CLOSE_REASON_INVALID_INBOUND_MESSAGE, "Connection Lost"); + hash_num_add(close_reason_map, SESSION_CLOSE_REASON_INVALID_INBOUND_MESSAGE, "Connection Lost"); + hash_num_add(close_reason_map, SESSION_CLOSE_REASON_ABORTED, "Connection Lost"); + hash_num_add(close_reason_map, SESSION_CLOSE_REASON_LOST_MESSAGES, "Connection Lost"); + hash_num_add(close_reason_map, SESSION_CLOSE_REASON_CLOSED_BY_CONTROLLER, "Connection Lost"); + hash_num_add(close_reason_map, SESSION_CLOSE_REASON_FAILED_OVER, "Connection Lost"); + + char *close_reason = hash_num_get(close_reason_map, request->close_reason); + char *session_id = session_id_to_string(&request->session_id); + printf("Session %s has been closed (%s) with the following properties:\n", session_id, close_reason); + utils_print_hash( + request->properties, NULL, utils_print_string, false + ); + + free(session_id); + hash_num_free(close_reason_map, NULL); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + SET_T *required_properties = set_new_string(5); + set_add(required_properties, PROPERTIES_SELECTOR_ALL_FIXED_PROPERTIES); + set_add(required_properties, PROPERTIES_SELECTOR_ALL_USER_PROPERTIES); + + COORDINATOR_T *coordinator = coordinator_init(); + + SESSION_PROPERTIES_REGISTRATION_PARAMS_T params = { + .on_registered = on_listener_registered, + .on_registration_error = on_registration_error, + .on_session_open = on_session_open, + .on_session_close = on_session_close, + .on_session_error = on_session_error, + .on_session_update = on_session_update, + .required_properties = required_properties, + .context = coordinator + }; + session_properties_listener_register(session, params); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + set_free(required_properties); +} \ No newline at end of file diff --git a/c/examples/monitoring/topic_notifications.c b/c/examples/monitoring/topic_notifications.c new file mode 100644 index 00000000..b683645d --- /dev/null +++ b/c/examples/monitoring/topic_notifications.c @@ -0,0 +1,155 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + +DIFFUSION_REGISTRATION_T *g_registration; + +static void print_topic_notification( + const char *topic_path, + DIFFUSION_TOPIC_NOTIFICATION_TYPE_T type, + bool is_descendant) +{ + HASH_NUM_T *verb_map = hash_num_new(5); + hash_num_add(verb_map, TOPIC_ADDED, "added"); + hash_num_add(verb_map, TOPIC_SELECTED, "selected"); + hash_num_add(verb_map, TOPIC_REMOVED, "removed"); + hash_num_add(verb_map, TOPIC_DESELECTED, "deselected"); + + char *verb = hash_num_get(verb_map, type); + char *prefix = (is_descendant ? "Descendant ": ""); + printf("%sTopic %s has been %s.\n", prefix, topic_path, verb); + hash_num_free(verb_map, NULL); +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + +static int on_listener_registered( + const DIFFUSION_REGISTRATION_T *registration, + void *context) +{ + g_registration = diffusion_registration_dup(registration); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_topic_notification( + const char *topic_path, + const TOPIC_SPECIFICATION_T *specification, + DIFFUSION_TOPIC_NOTIFICATION_TYPE_T type, + void *context) +{ + print_topic_notification(topic_path, type, false); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_descendant_notification( + const char *topic_path, + DIFFUSION_TOPIC_NOTIFICATION_TYPE_T type, + void *context) +{ + print_topic_notification(topic_path, type, true); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_selected(void *context) +{ + printf("Topic notification is now selected.\n"); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_deselected(void *context) +{ + printf("Topic notification has been deselected.\n"); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static void on_close(void) +{ + printf("Topic notification listener has been closed.\n"); +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + SESSION_T *session = utils_open_session(url, "admin", "password"); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_TOPIC_NOTIFICATION_LISTENER_T listener = { + .on_registered = on_listener_registered, + .on_topic_notification = on_topic_notification, + .on_descendant_notification = on_descendant_notification, + .on_close = on_close, + .context = coordinator + }; + diffusion_topic_notification_add_listener(session, listener, NULL); + coordinator_wait(coordinator); + + DIFFUSION_TOPIC_NOTIFICATION_REGISTRATION_PARAMS_T params = { + .on_selected = on_selected, + .on_deselected = on_deselected, + .on_error = on_error, + .registration = g_registration, + .selector = ">my/topic/path", + .context = coordinator + }; + diffusion_topic_notification_registration_select(session, params, NULL); + coordinator_wait(coordinator); + + utils_create_string_topic( + session, "my/topic/path", "Good morning" + ); + + utils_create_string_topic( + session, "my/topic/path/descendant", "Good afternoon" + ); + + utils_create_string_topic( + session, "other/path/of/the/topic/tree", "This will not generate a notification" + ); + + utils_remove_topic( + session, "my/topic/path/descendant" + ); + + diffusion_topic_notification_registration_deselect(session, params, NULL); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + diffusion_registration_free(g_registration); +} \ No newline at end of file diff --git a/c/examples/ping/ping_server.c b/c/examples/ping/ping_server.c new file mode 100644 index 00000000..4a1a6617 --- /dev/null +++ b/c/examples/ping/ping_server.c @@ -0,0 +1,55 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" +MUTEX_DEF + +static int on_ping_response(SESSION_T * session, void *context_data) +{ + MUTEX_BROADCAST + printf("Received ping response.\n"); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + MUTEX_INIT + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + PING_USER_PARAMS_T ping_params = { + .on_ping_response = on_ping_response + }; + ping_user(session, ping_params); + MUTEX_WAIT + + // Insert work here + + session_close(session, NULL); + session_free(session); + MUTEX_TERMINATE +} \ No newline at end of file diff --git a/c/examples/pub_sub/fetch/topic_properties.c b/c/examples/pub_sub/fetch/topic_properties.c new file mode 100644 index 00000000..8da774a7 --- /dev/null +++ b/c/examples/pub_sub/fetch/topic_properties.c @@ -0,0 +1,153 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_fetch_result( + const DIFFUSION_FETCH_RESULT_T *fetch_result, + void *context) +{ + LIST_T *results = diffusion_fetch_result_get_topic_results(fetch_result); + int size = list_get_size(results); + + for (int i = 0; i < size; i++) { + DIFFUSION_TOPIC_RESULT_T *topic_result = list_get_data_indexed(results, i); + + char *topic_path = diffusion_topic_result_get_path(topic_result); + TOPIC_SPECIFICATION_T *spec = diffusion_topic_result_get_specification(topic_result); + HASH_T *properties = topic_specification_get_properties(spec); + + if (properties->size == 0) { + printf("%s has no non-default properties.\n", topic_path); + } + else { + printf("%s properties:\n", topic_path); + + char **keys = hash_keys(properties); + for(char **key = keys; *key != NULL; key++) { + printf(" %s: %s\n", *key, (char *) hash_get(properties, *key)); + } + free(keys); + } + hash_free(properties, free, free); + } + list_free(results, (void (*)(void *))diffusion_topic_result_free); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + HASH_T *properties = hash_new(3); + hash_add(properties, DIFFUSION_DONT_RETAIN_VALUE, "true"); + hash_add(properties, DIFFUSION_PERSISTENT, "false"); + hash_add(properties, DIFFUSION_PUBLISH_VALUES_ONLY, "true"); + + for (int i = 1; i <= 5; i++) { + char *json_topic_path = calloc(100, sizeof(char)); + snprintf(json_topic_path, 100, "my/topic/path/with/properties/%d", i); + + char *json_value = calloc(100, sizeof(char)); + snprintf(json_value, 100, "{\"diffusion\": \"data #%d\" }", i); + + utils_create_json_topic_with_properties( + session, json_topic_path, json_value, properties + ); + + free(json_value); + free(json_topic_path); + + char *string_topic_path = calloc(100, sizeof(char)); + snprintf(string_topic_path, 100, "my/topic/path/with/default/properties/%d", i); + + char *string_value = calloc(100, sizeof(char)); + snprintf(string_value, 100, "diffusion data #%d", i); + + utils_create_string_topic(session, string_topic_path, string_value); + + free(string_value); + free(string_topic_path); + } + hash_free(properties, NULL, NULL); + + const char *topic_selector = "?my/topic/path//"; + + SET_T *json_topic_type_set = set_new_int(1); + int json_topic_type = TOPIC_TYPE_JSON; + set_add(json_topic_type_set, &json_topic_type); + + DIFFUSION_FETCH_REQUEST_T *json_fetch_request = + diffusion_fetch_request_init(session); + diffusion_fetch_request_topic_types(json_fetch_request, json_topic_type_set, NULL); + diffusion_fetch_request_with_properties(json_fetch_request, NULL); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_FETCH_REQUEST_PARAMS_T json_fetch_request_params = { + .topic_selector = topic_selector, + .fetch_request = json_fetch_request, + .on_fetch_result = on_fetch_result, + .context = coordinator + }; + diffusion_fetch_request_fetch(session, json_fetch_request_params); + coordinator_wait(coordinator); + + diffusion_fetch_request_free(json_fetch_request); + set_free(json_topic_type_set); + + SET_T *string_topic_type_set = set_new_int(1); + int string_topic_type = TOPIC_TYPE_STRING; + set_add(string_topic_type_set, &string_topic_type); + + DIFFUSION_FETCH_REQUEST_T *string_fetch_request = + diffusion_fetch_request_init(session); + diffusion_fetch_request_topic_types(string_fetch_request, string_topic_type_set, NULL); + diffusion_fetch_request_with_properties(string_fetch_request, NULL); + + DIFFUSION_FETCH_REQUEST_PARAMS_T string_fetch_request_params = { + .topic_selector = topic_selector, + .fetch_request = string_fetch_request, + .on_fetch_result = on_fetch_result, + .context = coordinator + }; + diffusion_fetch_request_fetch(session, string_fetch_request_params); + coordinator_wait(coordinator); + + set_free(string_topic_type_set); + diffusion_fetch_request_free(string_fetch_request); + + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); +} \ No newline at end of file diff --git a/c/examples/pub_sub/fetch/topic_via_paging.c b/c/examples/pub_sub/fetch/topic_via_paging.c new file mode 100644 index 00000000..225980a0 --- /dev/null +++ b/c/examples/pub_sub/fetch/topic_via_paging.c @@ -0,0 +1,126 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +SESSION_T *g_session; +const char *g_topic_selector = "?my/topic/path//"; +DIFFUSION_FETCH_REQUEST_T *g_fetch_request; + + +static int on_fetch_result( + const DIFFUSION_FETCH_RESULT_T *fetch_result, + void *context) +{ + int results_size = diffusion_fetch_result_size(fetch_result); + LIST_T *results = diffusion_fetch_result_get_topic_results(fetch_result); + + for (int i = 0; i < results_size; i++) { + DIFFUSION_TOPIC_RESULT_T *topic_result = list_get_data_indexed(results, i); + + char *topic_path = diffusion_topic_result_get_path(topic_result); + DIFFUSION_VALUE_T *value = diffusion_topic_result_get_value(topic_result); + + char *string_value; + read_diffusion_string_value(value, &string_value, NULL); + + printf("%s: %s\n", topic_path, string_value); + free(string_value); + } + + if (diffusion_fetch_result_has_more(fetch_result)) { + printf("Loading next page.\n"); + + DIFFUSION_TOPIC_RESULT_T *last_topic_result = + list_get_data_last(results); + + diffusion_fetch_request_after( + g_fetch_request, + diffusion_topic_result_get_path(last_topic_result), + NULL + ); + + DIFFUSION_FETCH_REQUEST_PARAMS_T fetch_params = { + .topic_selector = g_topic_selector, + .fetch_request = g_fetch_request, + .on_fetch_result = on_fetch_result, + .context = context + }; + + diffusion_fetch_request_fetch(g_session, fetch_params); + } + else { + printf("All pages loaded. Fetch complete\n"); + coordinator_broadcast((COORDINATOR_T *) context); + } + list_free(results, (void (*)(void *))diffusion_topic_result_free); + + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + g_session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + for (int i = 1; i <= 25; i++) { + char *topic_path = calloc(100, sizeof(char)); + snprintf(topic_path, 100, "my/topic/path/%d", i); + + char *value = calloc(100, sizeof(char)); + snprintf(value, 100, "diffusion data #%d", i); + + utils_create_string_topic(g_session, topic_path, value); + + free(value); + free(topic_path); + } + + DIFFUSION_DATATYPE datatype = DATATYPE_STRING; + g_fetch_request = diffusion_fetch_request_init(g_session); + diffusion_fetch_request_with_values(g_fetch_request, &datatype, NULL); + diffusion_fetch_request_first(g_fetch_request, 10, NULL); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_FETCH_REQUEST_PARAMS_T fetch_request_params = { + .topic_selector = g_topic_selector, + .fetch_request = g_fetch_request, + .on_fetch_result = on_fetch_result, + .context = coordinator + }; + diffusion_fetch_request_fetch(g_session, fetch_request_params); + coordinator_wait(coordinator); + + session_close(g_session, NULL); + session_free(g_session); + + diffusion_fetch_request_free(g_fetch_request); + coordinator_free(coordinator); +} \ No newline at end of file diff --git a/c/examples/pub_sub/json_patch/add.c b/c/examples/pub_sub/json_patch/add.c new file mode 100644 index 00000000..a1f4be2c --- /dev/null +++ b/c/examples/pub_sub/json_patch/add.c @@ -0,0 +1,69 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + "my/topic/path", + "{ \ + \"Fred\": \"Flintstone\", \ + \"Barney\": \"Rubble\" \ + }" + ); + + const char *topic_selector = "?my/topic/path//"; + VALUE_STREAM_T *value_stream_ptr = + utils_subscribe(session, topic_selector, DATATYPE_JSON); + + utils_apply_json_patch( + session, + "my/topic/path", + "[ \ + { \ + \"op\": \"add\", \ + \"path\": \"/George\", \ + \"value\": \"Jetson\" \ + } \ + ]" + ); + + // Sleep for a bit to see the notifications + sleep(2); + + + session_close(session, NULL); + session_free(session); + free(value_stream_ptr); + } \ No newline at end of file diff --git a/c/examples/pub_sub/json_patch/copy.c b/c/examples/pub_sub/json_patch/copy.c new file mode 100644 index 00000000..0f254cca --- /dev/null +++ b/c/examples/pub_sub/json_patch/copy.c @@ -0,0 +1,74 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + "my/topic/path", + "{ \ + \"Meet the Flintstones\": { \ + \"Fred\": \"Flintstone\", \ + \"Barney\": \"Rubble\" \ + }, \ + \"The Jetsons\": { \ + \"George\": \"Jetson\" \ + } \ + }" + ); + + const char *topic_selector = "?my/topic/path//"; + VALUE_STREAM_T *value_stream_ptr = + utils_subscribe(session, topic_selector, DATATYPE_JSON); + + utils_apply_json_patch( + session, + "my/topic/path", + "[ \ + { \ + \"op\": \"copy\", \ + \"from\": \"/Meet the Flintstones/Fred\", \ + \"path\": \"/The Jetsons/Fred\" \ + } \ + ]" + ); + + // Sleep for a bit to see the notifications + sleep(2); + + + session_close(session, NULL); + session_free(session); + free(value_stream_ptr); + } \ No newline at end of file diff --git a/c/examples/pub_sub/json_patch/move.c b/c/examples/pub_sub/json_patch/move.c new file mode 100644 index 00000000..335dfa4e --- /dev/null +++ b/c/examples/pub_sub/json_patch/move.c @@ -0,0 +1,80 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + "my/topic/path", + "{ \ + \"Fred\": \"Flintstone\", \ + \"Barney\": \"Rubble\", \ + \"George\": \"Jetson\" \ + }" + ); + + const char *topic_selector = "?my/topic/path//"; + VALUE_STREAM_T *value_stream_ptr = + utils_subscribe(session, topic_selector, DATATYPE_JSON); + + utils_apply_json_patch( + session, + "my/topic/path", + "[ \ + { \ + \"op\": \"move\", \ + \"from\": \"/Fred\", \ + \"path\": \"/Meet The Flintstones~1Fred\" \ + }, \ + { \ + \"op\": \"move\", \ + \"from\": \"/Barney\", \ + \"path\": \"/Meet The Flintstones~1Barney\" \ + }, \ + { \ + \"op\": \"move\", \ + \"from\": \"/George\", \ + \"path\": \"/The Jetsons~1George\" \ + } \ + ]" + ); + + // Sleep for a bit to see the notifications + sleep(2); + + + session_close(session, NULL); + session_free(session); + free(value_stream_ptr); + } \ No newline at end of file diff --git a/c/examples/pub_sub/json_patch/remove.c b/c/examples/pub_sub/json_patch/remove.c new file mode 100644 index 00000000..9292e882 --- /dev/null +++ b/c/examples/pub_sub/json_patch/remove.c @@ -0,0 +1,69 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + "my/topic/path", + "{ \ + \"Fred\": \"Flintstone\", \ + \"Barney\": \"Rubble\", \ + \"George\": \"Jetson\" \ + }" + ); + + const char *topic_selector = "?my/topic/path//"; + VALUE_STREAM_T *value_stream_ptr = + utils_subscribe(session, topic_selector, DATATYPE_JSON); + + utils_apply_json_patch( + session, + "my/topic/path", + "[ \ + { \ + \"op\": \"remove\", \ + \"path\": \"/George\" \ + } \ + ]" + ); + + // Sleep for a bit to see the notifications + sleep(2); + + + session_close(session, NULL); + session_free(session); + free(value_stream_ptr); + } \ No newline at end of file diff --git a/c/examples/pub_sub/json_patch/replace.c b/c/examples/pub_sub/json_patch/replace.c new file mode 100644 index 00000000..0fe931e2 --- /dev/null +++ b/c/examples/pub_sub/json_patch/replace.c @@ -0,0 +1,70 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + "my/topic/path", + "{ \ + \"Fred\": \"Flintstone\", \ + \"Barney\": \"Rubble\", \ + \"George\": \"Jetson\" \ + }" + ); + + const char *topic_selector = "?my/topic/path//"; + VALUE_STREAM_T *value_stream_ptr = + utils_subscribe(session, topic_selector, DATATYPE_JSON); + + utils_apply_json_patch( + session, + "my/topic/path", + "[ \ + { \ + \"op\": \"replace\", \ + \"path\": \"/George\", \ + \"value\": \"Bedrock\" \ + } \ + ]" + ); + + // Sleep for a bit to see the notifications + sleep(2); + + + session_close(session, NULL); + session_free(session); + free(value_stream_ptr); + } \ No newline at end of file diff --git a/c/examples/pub_sub/json_patch/test.c b/c/examples/pub_sub/json_patch/test.c new file mode 100644 index 00000000..70384743 --- /dev/null +++ b/c/examples/pub_sub/json_patch/test.c @@ -0,0 +1,70 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + "my/topic/path", + "{ \ + \"Fred\": \"Flintstone\", \ + \"Barney\": \"Rubble\", \ + \"George\": \"Jetson\" \ + }" + ); + + const char *topic_selector = "?my/topic/path//"; + VALUE_STREAM_T *value_stream_ptr = + utils_subscribe(session, topic_selector, DATATYPE_JSON); + + utils_apply_json_patch( + session, + "my/topic/path", + "[ \ + { \ + \"op\": \"test\", \ + \"path\": \"/Fred\", \ + \"value\": \"Flintstone\" \ + } \ + ]" + ); + + // Sleep for a bit to see the notifications + sleep(2); + + + session_close(session, NULL); + session_free(session); + free(value_stream_ptr); + } \ No newline at end of file diff --git a/c/examples/pub_sub/publish/add_and_set_topic.c b/c/examples/pub_sub/publish/add_and_set_topic.c new file mode 100644 index 00000000..78981734 --- /dev/null +++ b/c/examples/pub_sub/publish/add_and_set_topic.c @@ -0,0 +1,86 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_update_add_and_set( + DIFFUSION_TOPIC_CREATION_RESULT_T result, + void *context) +{ + if (result == TOPIC_CREATED) { + printf("Topic has been created.\n"); + } + else if (result == TOPIC_EXISTS) { + printf("Topic already exists.\n"); + } + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/topic/path "; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + TOPIC_SPECIFICATION_T *topic_specification = topic_specification_init(TOPIC_TYPE_JSON); + BUF_T *value = buf_create(); + write_diffusion_json_value("{\"diffusion\": \"data\"}", value); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_TOPIC_UPDATE_ADD_AND_SET_PARAMS_T params = { + .datatype = DATATYPE_JSON, + .on_topic_update_add_and_set = on_topic_update_add_and_set, + .topic_path = topic_path, + .specification = topic_specification, + .update = value, + .on_error = on_error, + .context = coordinator + }; + + diffusion_topic_update_add_and_set(session, params); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + buf_free(value); + topic_specification_free(topic_specification); +} \ No newline at end of file diff --git a/c/examples/pub_sub/publish/add_and_set_topic_via_update_stream.c b/c/examples/pub_sub/publish/add_and_set_topic_via_update_stream.c new file mode 100644 index 00000000..ebfd11c2 --- /dev/null +++ b/c/examples/pub_sub/publish/add_and_set_topic_via_update_stream.c @@ -0,0 +1,96 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_update_add_and_set( + DIFFUSION_TOPIC_CREATION_RESULT_T result, + void *context) +{ + if (result == TOPIC_CREATED) { + printf("Topic has been created.\n"); + } + else if (result == TOPIC_EXISTS) { + printf("Topic already exists.\n"); + } + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/topic/path/with/update/stream"; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_TOPIC_UPDATE_STREAM_PARAMS_T update_stream_params = { + .on_topic_creation_result = on_topic_update_add_and_set, + .on_error = on_error, + .context = coordinator + }; + + TOPIC_SPECIFICATION_T *topic_specification = topic_specification_init(TOPIC_TYPE_JSON); + DIFFUSION_UPDATE_STREAM_BUILDER_T *builder = diffusion_update_stream_builder_init(); + diffusion_update_stream_builder_topic_specification(builder, topic_specification, NULL); + + DIFFUSION_TOPIC_UPDATE_STREAM_T *update_stream = + diffusion_update_stream_builder_create_update_stream( + builder, + topic_path, + DATATYPE_JSON, + NULL + ); + + BUF_T *value = buf_create(); + write_diffusion_json_value("{\"diffusion\": \"data\"}", value); + diffusion_topic_update_stream_set(session, update_stream, value, update_stream_params); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + buf_free(value); + + diffusion_topic_update_stream_free(update_stream); + diffusion_update_stream_builder_free(builder); + + topic_specification_free(topic_specification); +} \ No newline at end of file diff --git a/c/examples/pub_sub/publish/add_topic.c b/c/examples/pub_sub/publish/add_topic.c new file mode 100644 index 00000000..97c9c914 --- /dev/null +++ b/c/examples/pub_sub/publish/add_topic.c @@ -0,0 +1,84 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_added( + SESSION_T *session, + TOPIC_ADD_RESULT_CODE result_code, + void *context) +{ + if (result_code == TOPIC_ADD_RESULT_CREATED) { + printf("Topic has been created.\n"); + } + else if (result_code == TOPIC_ADD_RESULT_EXISTS) { + printf("Topic already exists.\n"); + } + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_topic_add_failed_with_specification( + SESSION_T *session, + TOPIC_ADD_FAIL_RESULT_CODE result_code, + const DIFFUSION_ERROR_T *error, + void *context) +{ + printf("Topic creation failed: %d %d %s\n", result_code, error->code, error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/topic/path"; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + ADD_TOPIC_CALLBACK_T callback = { + .on_topic_added_with_specification = on_topic_added, + .on_topic_add_failed_with_specification = on_topic_add_failed_with_specification, + .context = coordinator + }; + + TOPIC_SPECIFICATION_T *topic_specification = topic_specification_init(TOPIC_TYPE_JSON); + + add_topic_from_specification( + session, topic_path, topic_specification, callback + ); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + topic_specification_free(topic_specification); +} \ No newline at end of file diff --git a/c/examples/pub_sub/publish/add_topic_custom_properties.c b/c/examples/pub_sub/publish/add_topic_custom_properties.c new file mode 100644 index 00000000..7dfd2c72 --- /dev/null +++ b/c/examples/pub_sub/publish/add_topic_custom_properties.c @@ -0,0 +1,91 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_added_with_specification( + SESSION_T *session, + TOPIC_ADD_RESULT_CODE result_code, + void *context) +{ + if (result_code == TOPIC_ADD_RESULT_CREATED) { + printf("Topic has been created.\n"); + } + else if (result_code == TOPIC_ADD_RESULT_EXISTS) { + printf("Topic already exists.\n"); + } + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_topic_add_failed_with_specification( + SESSION_T *session, + TOPIC_ADD_FAIL_RESULT_CODE result_code, + const DIFFUSION_ERROR_T *error, + void *context) +{ + printf("Topic creation failed: %d %d %s\n", result_code, error->code, error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/topic/path/with/properties"; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + ADD_TOPIC_CALLBACK_T callback = { + .on_topic_added_with_specification = on_topic_added_with_specification, + .on_topic_add_failed_with_specification = on_topic_add_failed_with_specification, + .context = coordinator + }; + + HASH_T *properties = hash_new(5); + hash_add(properties, DIFFUSION_DONT_RETAIN_VALUE, "true"); + hash_add(properties, DIFFUSION_PERSISTENT, "true"); + hash_add(properties, DIFFUSION_PUBLISH_VALUES_ONLY, "true"); + + TOPIC_SPECIFICATION_T *topic_specification = + topic_specification_init_with_properties(TOPIC_TYPE_JSON, properties); + + add_topic_from_specification( + session, topic_path, topic_specification, callback + ); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + topic_specification_free(topic_specification); + hash_free(properties, NULL, NULL); +} \ No newline at end of file diff --git a/c/examples/pub_sub/publish/set_topic.c b/c/examples/pub_sub/publish/set_topic.c new file mode 100644 index 00000000..6b5945f2 --- /dev/null +++ b/c/examples/pub_sub/publish/set_topic.c @@ -0,0 +1,117 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_update( + void *context) +{ + printf("Topic has been updated.\n"); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + +static int on_topic_added( + SESSION_T *session, + TOPIC_ADD_RESULT_CODE result_code, + void *context) +{ + if (result_code == TOPIC_ADD_RESULT_CREATED) { + printf("Topic has been created.\n"); + } + else if (result_code == TOPIC_ADD_RESULT_EXISTS) { + printf("Topic already exists.\n"); + } + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_topic_add_failed_with_specification( + SESSION_T *session, + TOPIC_ADD_FAIL_RESULT_CODE result_code, + const DIFFUSION_ERROR_T *error, + void *context) +{ + printf("Topic creation failed: %d %d %s\n", result_code, error->code, error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/topic/path"; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + TOPIC_SPECIFICATION_T *topic_specification = topic_specification_init(TOPIC_TYPE_JSON); + + COORDINATOR_T *coordinator = coordinator_init(); + + ADD_TOPIC_CALLBACK_T create_topic_params = { + .on_topic_added_with_specification = on_topic_added, + .on_topic_add_failed_with_specification = on_topic_add_failed_with_specification, + .on_error = on_error, + .context = coordinator + }; + add_topic_from_specification( + session, topic_path, topic_specification, create_topic_params + ); + coordinator_wait(coordinator); + + topic_specification_free(topic_specification); + + BUF_T *value = buf_create(); + write_diffusion_json_value("{\"diffusion\": [ \"data\", \"more data\" ] }", value); + + DIFFUSION_TOPIC_UPDATE_SET_PARAMS_T params = { + .datatype = DATATYPE_JSON, + .on_topic_update = on_topic_update, + .topic_path = topic_path, + .update = value, + .on_error = on_error, + .context = coordinator + }; + + diffusion_topic_update_set(session, params); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + buf_free(value); +} \ No newline at end of file diff --git a/c/examples/pub_sub/publish/set_topic_via_update_stream.c b/c/examples/pub_sub/publish/set_topic_via_update_stream.c new file mode 100644 index 00000000..1fdcc9d2 --- /dev/null +++ b/c/examples/pub_sub/publish/set_topic_via_update_stream.c @@ -0,0 +1,132 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_update( + DIFFUSION_TOPIC_CREATION_RESULT_T result, + void *context) +{ + if (result == TOPIC_CREATED) { + printf("Topic has been created.\n"); + } + else if (result == TOPIC_EXISTS) { + printf("Topic already exists.\n"); + } + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + +static int on_topic_added( + SESSION_T *session, + TOPIC_ADD_RESULT_CODE result_code, + void *context) +{ + if (result_code == TOPIC_ADD_RESULT_CREATED) { + printf("Topic has been created.\n"); + } + else if (result_code == TOPIC_ADD_RESULT_EXISTS) { + printf("Topic already exists.\n"); + } + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_topic_add_failed_with_specification( + SESSION_T *session, + TOPIC_ADD_FAIL_RESULT_CODE result_code, + const DIFFUSION_ERROR_T *error, + void *context) +{ + printf("Topic creation failed: %d %d %s\n", result_code, error->code, error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/topic/path/with/update/stream"; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + TOPIC_SPECIFICATION_T *topic_specification = topic_specification_init(TOPIC_TYPE_JSON); + + COORDINATOR_T *coordinator = coordinator_init(); + + ADD_TOPIC_CALLBACK_T create_topic_params = { + .on_topic_added_with_specification = on_topic_added, + .on_topic_add_failed_with_specification = on_topic_add_failed_with_specification, + .on_error = on_error, + .context = coordinator + }; + add_topic_from_specification( + session, topic_path, topic_specification, create_topic_params + ); + coordinator_wait(coordinator); + + topic_specification_free(topic_specification); + + DIFFUSION_UPDATE_STREAM_BUILDER_T *builder = diffusion_update_stream_builder_init(); + + DIFFUSION_TOPIC_UPDATE_STREAM_T *update_stream = + diffusion_update_stream_builder_create_update_stream( + builder, + topic_path, + DATATYPE_JSON, + NULL + ); + + BUF_T *value = buf_create(); + write_diffusion_json_value("{\"diffusion\": [ \"data\", \"more data\" ] }", value); + + DIFFUSION_TOPIC_UPDATE_STREAM_PARAMS_T update_stream_params = { + .on_topic_creation_result = on_topic_update, + .on_error = on_error, + .context = coordinator + }; + + diffusion_topic_update_stream_set(session, update_stream, value, update_stream_params); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + buf_free(value); + diffusion_topic_update_stream_free(update_stream); + diffusion_update_stream_builder_free(builder); +} \ No newline at end of file diff --git a/c/examples/pub_sub/publish/with_constraint/add_and_set_topic_and.c b/c/examples/pub_sub/publish/with_constraint/add_and_set_topic_and.c new file mode 100644 index 00000000..66b9ac34 --- /dev/null +++ b/c/examples/pub_sub/publish/with_constraint/add_and_set_topic_and.c @@ -0,0 +1,123 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_update_add_and_set( + DIFFUSION_TOPIC_CREATION_RESULT_T result, + void *context) +{ + if (result == TOPIC_CREATED) { + printf("Topic has been created.\n"); + } + else if (result == TOPIC_EXISTS) { + printf("Topic already exists.\n"); + } + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/topic/path "; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + TOPIC_SPECIFICATION_T *topic_specification = topic_specification_init(TOPIC_TYPE_JSON); + BUF_T *value = buf_create(); + write_diffusion_json_value("{\"diffusion\": \"data\"}", value); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_TOPIC_UPDATE_ADD_AND_SET_PARAMS_T params = { + .datatype = DATATYPE_JSON, + .on_topic_update_add_and_set = on_topic_update_add_and_set, + .topic_path = topic_path, + .specification = topic_specification, + .update = value, + .on_error = on_error, + .context = coordinator + }; + + diffusion_topic_update_add_and_set(session, params); + coordinator_wait(coordinator); + + DIFFUSION_UPDATE_CONSTRAINT_VALUE_T *constraint_value = + diffusion_update_constraint_value_from_string("data"); + + DIFFUSION_TOPIC_UPDATE_CONSTRAINT_T *constraint_1 = + diffusion_topic_update_constraint_partial_json_comparison( + "/diffusion", DIFFUSION_TOPIC_UPDATE_CONSTRAINT_OPERATOR_IS, constraint_value + ); + + DIFFUSION_TOPIC_UPDATE_CONSTRAINT_T *constraint_2 = + diffusion_topic_update_constraint_partial_json_without_value("/bar"); + + DIFFUSION_TOPIC_UPDATE_CONSTRAINT_T *constraint = + diffusion_topic_update_constraint_and(constraint_1, constraint_2); + + BUF_T *new_value = buf_create(); + write_diffusion_json_value("{\"diffusion\": \"baz\"}", new_value); + + DIFFUSION_TOPIC_UPDATE_ADD_AND_SET_PARAMS_T new_set_params = { + .datatype = DATATYPE_JSON, + .on_topic_update_add_and_set = on_topic_update_add_and_set, + .topic_path = topic_path, + .specification = topic_specification, + .update = new_value, + .on_error = on_error, + .context = coordinator + }; + + diffusion_topic_update_add_and_set_with_constraint(session, constraint, new_set_params); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + buf_free(new_value); + + diffusion_topic_update_constraint_free(constraint); + diffusion_topic_update_constraint_free(constraint_2); + diffusion_topic_update_constraint_free(constraint_1); + diffusion_update_constraint_value_free(constraint_value); + + buf_free(value); + topic_specification_free(topic_specification); +} \ No newline at end of file diff --git a/c/examples/pub_sub/publish/with_constraint/add_and_set_topic_json_value_with.c b/c/examples/pub_sub/publish/with_constraint/add_and_set_topic_json_value_with.c new file mode 100644 index 00000000..9ff5512b --- /dev/null +++ b/c/examples/pub_sub/publish/with_constraint/add_and_set_topic_json_value_with.c @@ -0,0 +1,115 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_update_add_and_set( + DIFFUSION_TOPIC_CREATION_RESULT_T result, + void *context) +{ + if (result == TOPIC_CREATED) { + printf("Topic has been created.\n"); + } + else if (result == TOPIC_EXISTS) { + printf("Topic already exists.\n"); + } + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/topic/path "; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + TOPIC_SPECIFICATION_T *topic_specification = topic_specification_init(TOPIC_TYPE_JSON); + BUF_T *value = buf_create(); + write_diffusion_json_value("{\"diffusion\": \"bar\"}", value); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_TOPIC_UPDATE_ADD_AND_SET_PARAMS_T params = { + .datatype = DATATYPE_JSON, + .on_topic_update_add_and_set = on_topic_update_add_and_set, + .topic_path = topic_path, + .specification = topic_specification, + .update = value, + .on_error = on_error, + .context = coordinator + }; + + diffusion_topic_update_add_and_set(session, params); + coordinator_wait(coordinator); + + DIFFUSION_UPDATE_CONSTRAINT_VALUE_T *constraint_value = + diffusion_update_constraint_value_from_string("bar"); + + DIFFUSION_TOPIC_UPDATE_CONSTRAINT_T *constraint = + diffusion_topic_update_constraint_partial_json_comparison( + "/diffusion", DIFFUSION_TOPIC_UPDATE_CONSTRAINT_OPERATOR_IS, constraint_value + ); + + BUF_T *new_value = buf_create(); + write_diffusion_json_value("{\"diffusion\": \"baz\"}", new_value); + + DIFFUSION_TOPIC_UPDATE_ADD_AND_SET_PARAMS_T new_set_params = { + .datatype = DATATYPE_JSON, + .on_topic_update_add_and_set = on_topic_update_add_and_set, + .topic_path = topic_path, + .specification = topic_specification, + .update = new_value, + .on_error = on_error, + .context = coordinator + }; + + diffusion_topic_update_add_and_set_with_constraint(session, constraint, new_set_params); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + buf_free(new_value); + + diffusion_topic_update_constraint_free(constraint); + diffusion_update_constraint_value_free(constraint_value); + + buf_free(value); + topic_specification_free(topic_specification); +} \ No newline at end of file diff --git a/c/examples/pub_sub/publish/with_constraint/add_and_set_topic_json_value_without.c b/c/examples/pub_sub/publish/with_constraint/add_and_set_topic_json_value_without.c new file mode 100644 index 00000000..3ed10400 --- /dev/null +++ b/c/examples/pub_sub/publish/with_constraint/add_and_set_topic_json_value_without.c @@ -0,0 +1,109 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_update_add_and_set( + DIFFUSION_TOPIC_CREATION_RESULT_T result, + void *context) +{ + if (result == TOPIC_CREATED) { + printf("Topic has been created.\n"); + } + else if (result == TOPIC_EXISTS) { + printf("Topic already exists.\n"); + } + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/topic/path "; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + TOPIC_SPECIFICATION_T *topic_specification = topic_specification_init(TOPIC_TYPE_JSON); + BUF_T *value = buf_create(); + write_diffusion_json_value("{\"diffusion\": \"data\"}", value); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_TOPIC_UPDATE_ADD_AND_SET_PARAMS_T params = { + .datatype = DATATYPE_JSON, + .on_topic_update_add_and_set = on_topic_update_add_and_set, + .topic_path = topic_path, + .specification = topic_specification, + .update = value, + .on_error = on_error, + .context = coordinator + }; + + diffusion_topic_update_add_and_set(session, params); + coordinator_wait(coordinator); + + DIFFUSION_TOPIC_UPDATE_CONSTRAINT_T *constraint = + diffusion_topic_update_constraint_partial_json_without_value("/bar"); + + BUF_T *new_value = buf_create(); + write_diffusion_json_value("{\"diffusion\": \"baz\"}", new_value); + + DIFFUSION_TOPIC_UPDATE_ADD_AND_SET_PARAMS_T new_set_params = { + .datatype = DATATYPE_JSON, + .on_topic_update_add_and_set = on_topic_update_add_and_set, + .topic_path = topic_path, + .specification = topic_specification, + .update = new_value, + .on_error = on_error, + .context = coordinator + }; + + diffusion_topic_update_add_and_set_with_constraint(session, constraint, new_set_params); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + buf_free(new_value); + + diffusion_topic_update_constraint_free(constraint); + + buf_free(value); + topic_specification_free(topic_specification); +} \ No newline at end of file diff --git a/c/examples/pub_sub/publish/with_constraint/add_and_set_topic_no_topic.c b/c/examples/pub_sub/publish/with_constraint/add_and_set_topic_no_topic.c new file mode 100644 index 00000000..4a62112a --- /dev/null +++ b/c/examples/pub_sub/publish/with_constraint/add_and_set_topic_no_topic.c @@ -0,0 +1,90 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_update_add_and_set( + DIFFUSION_TOPIC_CREATION_RESULT_T result, + void *context) +{ + if (result == TOPIC_CREATED) { + printf("Topic has been created.\n"); + } + else if (result == TOPIC_EXISTS) { + printf("Topic already exists.\n"); + } + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/topic/path "; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + TOPIC_SPECIFICATION_T *topic_specification = topic_specification_init(TOPIC_TYPE_JSON); + BUF_T *value = buf_create(); + write_diffusion_json_value("{\"diffusion\": \"data\"}", value); + + DIFFUSION_TOPIC_UPDATE_CONSTRAINT_T *constraint = diffusion_topic_update_constraint_no_topic(); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_TOPIC_UPDATE_ADD_AND_SET_PARAMS_T params = { + .datatype = DATATYPE_JSON, + .on_topic_update_add_and_set = on_topic_update_add_and_set, + .topic_path = topic_path, + .specification = topic_specification, + .update = value, + .on_error = on_error, + .context = coordinator + }; + + diffusion_topic_update_add_and_set_with_constraint(session, constraint, params); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + diffusion_topic_update_constraint_free(constraint); + + buf_free(value); + topic_specification_free(topic_specification); +} \ No newline at end of file diff --git a/c/examples/pub_sub/publish/with_constraint/add_and_set_topic_or.c b/c/examples/pub_sub/publish/with_constraint/add_and_set_topic_or.c new file mode 100644 index 00000000..e29de01a --- /dev/null +++ b/c/examples/pub_sub/publish/with_constraint/add_and_set_topic_or.c @@ -0,0 +1,142 @@ +/** + * Copyright © 2025 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_update_add_and_set( + DIFFUSION_TOPIC_CREATION_RESULT_T result, + void *context) +{ + if (result == TOPIC_CREATED) { + printf("Topic has been created.\n"); + } + else if (result == TOPIC_EXISTS) { + printf("Topic already exists.\n"); + } + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/topic/path "; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + TOPIC_SPECIFICATION_T *topic_specification = topic_specification_init(TOPIC_TYPE_JSON); + BUF_T *value_1 = buf_create(); + write_diffusion_json_value("{\"diffusion\": \"data\"}", value_1); + + BUF_T *value_2 = buf_create(); + write_diffusion_json_value("{\"diffusion\": \"data2\"}", value_2); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_TOPIC_UPDATE_ADD_AND_SET_PARAMS_T params = { + .datatype = DATATYPE_JSON, + .on_topic_update_add_and_set = on_topic_update_add_and_set, + .topic_path = topic_path, + .specification = topic_specification, + .update = value_1, + .on_error = on_error, + .context = coordinator + }; + + diffusion_topic_update_add_and_set(session, params); + coordinator_wait(coordinator); + + DIFFUSION_UPDATE_CONSTRAINT_VALUE_T *constraint_value_1 = + diffusion_update_constraint_value_from_string("data"); + + DIFFUSION_TOPIC_UPDATE_CONSTRAINT_T *constraint_1 = + diffusion_topic_update_constraint_partial_json_comparison( + "/diffusion", DIFFUSION_TOPIC_UPDATE_CONSTRAINT_OPERATOR_IS, constraint_value_1 + ); + + DIFFUSION_UPDATE_CONSTRAINT_VALUE_T *constraint_value_2 = + diffusion_update_constraint_value_from_string("data2"); + + DIFFUSION_TOPIC_UPDATE_CONSTRAINT_T *constraint_2 = + diffusion_topic_update_constraint_partial_json_comparison( + "/diffusion", DIFFUSION_TOPIC_UPDATE_CONSTRAINT_OPERATOR_IS, constraint_value_2 + ); + + DIFFUSION_TOPIC_UPDATE_CONSTRAINT_T *constraint = + diffusion_topic_update_constraint_or(constraint_1, constraint_2); + + DIFFUSION_TOPIC_UPDATE_ADD_AND_SET_PARAMS_T new_set_params_1 = { + .datatype = DATATYPE_JSON, + .on_topic_update_add_and_set = on_topic_update_add_and_set, + .topic_path = topic_path, + .specification = topic_specification, + .update = value_1, + .on_error = on_error, + .context = coordinator + }; + + diffusion_topic_update_add_and_set_with_constraint(session, constraint, new_set_params_1); + coordinator_wait(coordinator); + + DIFFUSION_TOPIC_UPDATE_ADD_AND_SET_PARAMS_T new_set_params_2 = { + .datatype = DATATYPE_JSON, + .on_topic_update_add_and_set = on_topic_update_add_and_set, + .topic_path = topic_path, + .specification = topic_specification, + .update = value_2, + .on_error = on_error, + .context = coordinator + }; + + diffusion_topic_update_add_and_set_with_constraint(session, constraint, new_set_params_2); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + + diffusion_topic_update_constraint_free(constraint); + diffusion_topic_update_constraint_free(constraint_2); + diffusion_topic_update_constraint_free(constraint_1); + diffusion_update_constraint_value_free(constraint_value_1); + diffusion_update_constraint_value_free(constraint_value_2); + + buf_free(value_1); + buf_free(value_2); + topic_specification_free(topic_specification); +} \ No newline at end of file diff --git a/c/examples/pub_sub/publish/with_constraint/add_and_set_topic_session_lock.c b/c/examples/pub_sub/publish/with_constraint/add_and_set_topic_session_lock.c new file mode 100644 index 00000000..ed67c7e6 --- /dev/null +++ b/c/examples/pub_sub/publish/with_constraint/add_and_set_topic_session_lock.c @@ -0,0 +1,112 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + +DIFFUSION_SESSION_LOCK_T *g_session_lock; + +static int on_topic_update_add_and_set( + DIFFUSION_TOPIC_CREATION_RESULT_T result, + void *context) +{ + if (result == TOPIC_CREATED) { + printf("Topic has been created.\n"); + } + else if (result == TOPIC_EXISTS) { + printf("Topic already exists.\n"); + } + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +static int on_lock_acquired( + const DIFFUSION_SESSION_LOCK_T *session_lock, + void *context) +{ + g_session_lock = (DIFFUSION_SESSION_LOCK_T *) session_lock; + printf("Session lock acquired.\n"); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/topic/path "; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + char *lock_name = "session_lock_1"; + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_SESSION_LOCK_PARAMS_T lock_params = { + .on_lock_acquired = on_lock_acquired, + .on_error = on_error, + .context = coordinator + }; + diffusion_session_lock(session, lock_name, lock_params); + coordinator_wait(coordinator); + + TOPIC_SPECIFICATION_T *topic_specification = topic_specification_init(TOPIC_TYPE_JSON); + BUF_T *value = buf_create(); + write_diffusion_json_value("{\"diffusion\": \"data\"}", value); + + DIFFUSION_TOPIC_UPDATE_CONSTRAINT_T *constraint = + diffusion_topic_update_constraint_locked(g_session_lock); + + DIFFUSION_TOPIC_UPDATE_ADD_AND_SET_PARAMS_T params = { + .datatype = DATATYPE_JSON, + .on_topic_update_add_and_set = on_topic_update_add_and_set, + .topic_path = topic_path, + .specification = topic_specification, + .update = value, + .on_error = on_error, + .context = coordinator + }; + + diffusion_topic_update_add_and_set_with_constraint(session, constraint, params); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + diffusion_topic_update_constraint_free(constraint); + + buf_free(value); + topic_specification_free(topic_specification); +} \ No newline at end of file diff --git a/c/examples/pub_sub/publish/with_constraint/add_and_set_topic_value.c b/c/examples/pub_sub/publish/with_constraint/add_and_set_topic_value.c new file mode 100644 index 00000000..4fce1cb1 --- /dev/null +++ b/c/examples/pub_sub/publish/with_constraint/add_and_set_topic_value.c @@ -0,0 +1,107 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_update_add_and_set( + DIFFUSION_TOPIC_CREATION_RESULT_T result, + void *context) +{ + if (result == TOPIC_CREATED) { + printf("Topic has been created.\n"); + } + else if (result == TOPIC_EXISTS) { + printf("Topic already exists.\n"); + } + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/topic/path "; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + TOPIC_SPECIFICATION_T *topic_specification = topic_specification_init(TOPIC_TYPE_JSON); + BUF_T *value = buf_create(); + write_diffusion_json_value("{\"diffusion\": \"data\"}", value); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_TOPIC_UPDATE_ADD_AND_SET_PARAMS_T params = { + .datatype = DATATYPE_JSON, + .on_topic_update_add_and_set = on_topic_update_add_and_set, + .topic_path = topic_path, + .specification = topic_specification, + .update = value, + .on_error = on_error, + .context = coordinator + }; + + diffusion_topic_update_add_and_set(session, params); + coordinator_wait(coordinator); + + DIFFUSION_TOPIC_UPDATE_CONSTRAINT_T *constraint = diffusion_topic_update_constraint_value(value); + BUF_T *new_value = buf_create(); + write_diffusion_json_value("{\"diffusion\": \"data2\"}", new_value); + + DIFFUSION_TOPIC_UPDATE_ADD_AND_SET_PARAMS_T new_set_params = { + .datatype = DATATYPE_JSON, + .on_topic_update_add_and_set = on_topic_update_add_and_set, + .topic_path = topic_path, + .specification = topic_specification, + .update = new_value, + .on_error = on_error, + .context = coordinator + }; + + diffusion_topic_update_add_and_set_with_constraint(session, constraint, new_set_params); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + buf_free(new_value); + + diffusion_topic_update_constraint_free(constraint); + + buf_free(value); + topic_specification_free(topic_specification); +} \ No newline at end of file diff --git a/c/examples/pub_sub/publish/with_constraint/set_topic_json_value_with.c b/c/examples/pub_sub/publish/with_constraint/set_topic_json_value_with.c new file mode 100644 index 00000000..118d40a1 --- /dev/null +++ b/c/examples/pub_sub/publish/with_constraint/set_topic_json_value_with.c @@ -0,0 +1,122 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_update_add_and_set( + DIFFUSION_TOPIC_CREATION_RESULT_T result, + void *context) +{ + if (result == TOPIC_CREATED) { + printf("Topic has been created.\n"); + } + else if (result == TOPIC_EXISTS) { + printf("Topic already exists.\n"); + } + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_topic_update( + void *context) +{ + printf("Topic has been updated.\n"); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/topic/path "; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + TOPIC_SPECIFICATION_T *topic_specification = topic_specification_init(TOPIC_TYPE_JSON); + BUF_T *value = buf_create(); + write_diffusion_json_value("{\"diffusion\": \"bar\"}", value); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_TOPIC_UPDATE_ADD_AND_SET_PARAMS_T add_and_set_params = { + .datatype = DATATYPE_JSON, + .on_topic_update_add_and_set = on_topic_update_add_and_set, + .topic_path = topic_path, + .specification = topic_specification, + .update = value, + .on_error = on_error, + .context = coordinator + }; + + diffusion_topic_update_add_and_set(session, add_and_set_params); + coordinator_wait(coordinator); + + DIFFUSION_UPDATE_CONSTRAINT_VALUE_T *constraint_value = + diffusion_update_constraint_value_from_string("bar"); + + DIFFUSION_TOPIC_UPDATE_CONSTRAINT_T *constraint = + diffusion_topic_update_constraint_partial_json_comparison( + "/diffusion", DIFFUSION_TOPIC_UPDATE_CONSTRAINT_OPERATOR_IS, constraint_value + ); + + BUF_T *new_value = buf_create(); + write_diffusion_json_value("{\"diffusion\": \"baz\"}", new_value); + + DIFFUSION_TOPIC_UPDATE_SET_PARAMS_T params = { + .datatype = DATATYPE_JSON, + .on_topic_update = on_topic_update, + .topic_path = topic_path, + .update = new_value, + .on_error = on_error, + .context = coordinator + }; + + diffusion_topic_update_set_with_constraint(session, constraint, params); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + buf_free(new_value); + + diffusion_topic_update_constraint_free(constraint); + diffusion_update_constraint_value_free(constraint_value); + + buf_free(value); + topic_specification_free(topic_specification); +} \ No newline at end of file diff --git a/c/examples/pub_sub/publish/with_constraint/set_topic_json_value_without.c b/c/examples/pub_sub/publish/with_constraint/set_topic_json_value_without.c new file mode 100644 index 00000000..b6150a85 --- /dev/null +++ b/c/examples/pub_sub/publish/with_constraint/set_topic_json_value_without.c @@ -0,0 +1,116 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_update_add_and_set( + DIFFUSION_TOPIC_CREATION_RESULT_T result, + void *context) +{ + if (result == TOPIC_CREATED) { + printf("Topic has been created.\n"); + } + else if (result == TOPIC_EXISTS) { + printf("Topic already exists.\n"); + } + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_topic_update( + void *context) +{ + printf("Topic has been updated.\n"); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/topic/path "; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + TOPIC_SPECIFICATION_T *topic_specification = topic_specification_init(TOPIC_TYPE_JSON); + BUF_T *value = buf_create(); + write_diffusion_json_value("{\"diffusion\": \"data\"}", value); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_TOPIC_UPDATE_ADD_AND_SET_PARAMS_T add_and_set_params = { + .datatype = DATATYPE_JSON, + .on_topic_update_add_and_set = on_topic_update_add_and_set, + .topic_path = topic_path, + .specification = topic_specification, + .update = value, + .on_error = on_error, + .context = coordinator + }; + + diffusion_topic_update_add_and_set(session, add_and_set_params); + coordinator_wait(coordinator); + + DIFFUSION_TOPIC_UPDATE_CONSTRAINT_T *constraint = + diffusion_topic_update_constraint_partial_json_without_value("/bar"); + + BUF_T *new_value = buf_create(); + write_diffusion_json_value("{\"diffusion\": \"baz\"}", new_value); + + DIFFUSION_TOPIC_UPDATE_SET_PARAMS_T params = { + .datatype = DATATYPE_JSON, + .on_topic_update = on_topic_update, + .topic_path = topic_path, + .update = new_value, + .on_error = on_error, + .context = coordinator + }; + + diffusion_topic_update_set_with_constraint(session, constraint, params); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + buf_free(new_value); + + diffusion_topic_update_constraint_free(constraint); + + buf_free(value); + topic_specification_free(topic_specification); +} \ No newline at end of file diff --git a/c/examples/pub_sub/publish/with_constraint/set_topic_no_value.c b/c/examples/pub_sub/publish/with_constraint/set_topic_no_value.c new file mode 100644 index 00000000..3c4ce479 --- /dev/null +++ b/c/examples/pub_sub/publish/with_constraint/set_topic_no_value.c @@ -0,0 +1,120 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_update( + void *context) +{ + printf("Topic has been updated.\n"); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + +static int on_topic_added( + SESSION_T *session, + TOPIC_ADD_RESULT_CODE result_code, + void *context) +{ + if (result_code == TOPIC_ADD_RESULT_CREATED) { + printf("Topic has been created.\n"); + } + else if (result_code == TOPIC_ADD_RESULT_EXISTS) { + printf("Topic already exists.\n"); + } + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_topic_add_failed_with_specification( + SESSION_T *session, + TOPIC_ADD_FAIL_RESULT_CODE result_code, + const DIFFUSION_ERROR_T *error, + void *context) +{ + printf("Topic creation failed: %d %d %s\n", result_code, error->code, error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/topic/path"; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + TOPIC_SPECIFICATION_T *topic_specification = topic_specification_init(TOPIC_TYPE_JSON); + + COORDINATOR_T *coordinator = coordinator_init(); + + ADD_TOPIC_CALLBACK_T create_topic_params = { + .on_topic_added_with_specification = on_topic_added, + .on_topic_add_failed_with_specification = on_topic_add_failed_with_specification, + .on_error = on_error, + .context = coordinator + }; + add_topic_from_specification( + session, topic_path, topic_specification, create_topic_params); + coordinator_wait(coordinator); + + topic_specification_free(topic_specification); + + DIFFUSION_TOPIC_UPDATE_CONSTRAINT_T *constraint = + diffusion_topic_update_constraint_no_value(); + + BUF_T *value = buf_create(); + write_diffusion_json_value("{\"diffusion\": [ \"data\", \"more data\" ] }", value); + + DIFFUSION_TOPIC_UPDATE_SET_PARAMS_T params = { + .datatype = DATATYPE_JSON, + .on_topic_update = on_topic_update, + .topic_path = topic_path, + .update = value, + .on_error = on_error, + .context = coordinator + }; + + diffusion_topic_update_set_with_constraint(session, constraint, params); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + diffusion_topic_update_constraint_free(constraint); + buf_free(value); +} \ No newline at end of file diff --git a/c/examples/pub_sub/publish/with_constraint/set_topic_session_lock.c b/c/examples/pub_sub/publish/with_constraint/set_topic_session_lock.c new file mode 100644 index 00000000..6f968b06 --- /dev/null +++ b/c/examples/pub_sub/publish/with_constraint/set_topic_session_lock.c @@ -0,0 +1,140 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + +DIFFUSION_SESSION_LOCK_T *g_session_lock; + +static int on_topic_update( + void *context) +{ + printf("Topic has been updated.\n"); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + +static int on_topic_added( + SESSION_T *session, + TOPIC_ADD_RESULT_CODE result_code, + void *context) +{ + if (result_code == TOPIC_ADD_RESULT_CREATED) { + printf("Topic has been created.\n"); + } + else if (result_code == TOPIC_ADD_RESULT_EXISTS) { + printf("Topic already exists.\n"); + } + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_topic_add_failed_with_specification( + SESSION_T *session, + TOPIC_ADD_FAIL_RESULT_CODE result_code, + const DIFFUSION_ERROR_T *error, + void *context) +{ + printf("Topic creation failed: %d %d %s\n", result_code, error->code, error->message); + return HANDLER_SUCCESS; +} + +static int on_lock_acquired( + const DIFFUSION_SESSION_LOCK_T *session_lock, + void *context) +{ + g_session_lock = (DIFFUSION_SESSION_LOCK_T *) session_lock; + printf("Session lock acquired.\n"); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/topic/path"; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + char *lock_name = "session_lock_1"; + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_SESSION_LOCK_PARAMS_T lock_params = { + .on_lock_acquired = on_lock_acquired, + .on_error = on_error, + .context = coordinator + }; + diffusion_session_lock(session, lock_name, lock_params); + coordinator_wait(coordinator); + + TOPIC_SPECIFICATION_T *topic_specification = topic_specification_init(TOPIC_TYPE_JSON); + ADD_TOPIC_CALLBACK_T create_topic_params = { + .on_topic_added_with_specification = on_topic_added, + .on_topic_add_failed_with_specification = on_topic_add_failed_with_specification, + .on_error = on_error, + .context = coordinator + }; + add_topic_from_specification( + session, topic_path, topic_specification, create_topic_params + ); + coordinator_wait(coordinator); + + topic_specification_free(topic_specification); + + DIFFUSION_TOPIC_UPDATE_CONSTRAINT_T *constraint = + diffusion_topic_update_constraint_locked(g_session_lock); + + BUF_T *value = buf_create(); + write_diffusion_json_value("{\"diffusion\": [ \"data\", \"more data\" ] }", value); + + DIFFUSION_TOPIC_UPDATE_SET_PARAMS_T params = { + .datatype = DATATYPE_JSON, + .on_topic_update = on_topic_update, + .topic_path = topic_path, + .update = value, + .on_error = on_error, + .context = coordinator + }; + + diffusion_topic_update_set_with_constraint(session, constraint, params); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + diffusion_topic_update_constraint_free(constraint); + buf_free(value); +} \ No newline at end of file diff --git a/c/examples/pub_sub/publish/with_constraint/set_topic_value.c b/c/examples/pub_sub/publish/with_constraint/set_topic_value.c new file mode 100644 index 00000000..a59d3b51 --- /dev/null +++ b/c/examples/pub_sub/publish/with_constraint/set_topic_value.c @@ -0,0 +1,128 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_update_add_and_set( + DIFFUSION_TOPIC_CREATION_RESULT_T result, + void *context) +{ + if (result == TOPIC_CREATED) { + printf("Topic has been created.\n"); + } + else if (result == TOPIC_EXISTS) { + printf("Topic already exists.\n"); + } + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_topic_update( + void *context) +{ + printf("Topic has been updated.\n"); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/topic/path"; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + TOPIC_SPECIFICATION_T *topic_specification = topic_specification_init(TOPIC_TYPE_JSON); + BUF_T *value = buf_create(); + write_diffusion_json_value("{\"diffusion\": [ \"data\", \"more data\" ] }", value); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_TOPIC_UPDATE_ADD_AND_SET_PARAMS_T add_and_set_params = { + .datatype = DATATYPE_JSON, + .on_topic_update_add_and_set = on_topic_update_add_and_set, + .topic_path = topic_path, + .specification = topic_specification, + .update = value, + .on_error = on_error, + .context = coordinator + }; + diffusion_topic_update_add_and_set(session, add_and_set_params); + coordinator_wait(coordinator); + + topic_specification_free(topic_specification); + + DIFFUSION_UPDATE_CONSTRAINT_VALUE_T *constraint_value = + diffusion_update_constraint_value_from_json_string( + "{\"diffusion\": [ \"data\", \"more data\" ] }" + ); + + DIFFUSION_TOPIC_UPDATE_CONSTRAINT_T *constraint = + diffusion_topic_update_constraint_value_comparison( + DIFFUSION_TOPIC_UPDATE_CONSTRAINT_OPERATOR_IS, + constraint_value + ); + + BUF_T *new_value = buf_create(); + write_diffusion_json_value( + "{\"diffusion\": [ \"data\", \"more data\", \"yet more data\" ] }", + new_value + ); + + DIFFUSION_TOPIC_UPDATE_SET_PARAMS_T params = { + .datatype = DATATYPE_JSON, + .on_topic_update = on_topic_update, + .topic_path = topic_path, + .update = new_value, + .on_error = on_error, + .context = coordinator + }; + + diffusion_topic_update_set_with_constraint(session, constraint, params); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + buf_free(new_value); + + diffusion_topic_update_constraint_free(constraint); + + diffusion_update_constraint_value_free(constraint_value); + buf_free(value); +} \ No newline at end of file diff --git a/c/examples/pub_sub/remove/automatic_topic_removal.c b/c/examples/pub_sub/remove/automatic_topic_removal.c new file mode 100644 index 00000000..46c615b4 --- /dev/null +++ b/c/examples/pub_sub/remove/automatic_topic_removal.c @@ -0,0 +1,88 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic_with_topic_removal_policy( + session, + "my/topic/path/to/be/removed/time/after", + "when time after 'Tue, 4 May 2077 11:05:30 GMT'" + ); + + utils_create_json_topic_with_topic_removal_policy( + session, + "my/topic/path/to/be/removed/subscriptions", + "when subscriptions < 1 for 10m" + ); + + utils_create_json_topic_with_topic_removal_policy( + session, + "my/topic/path/to/be/removed/local/subscriptions", + "when local subscriptions < 1 for 10m" + ); + + utils_create_json_topic_with_topic_removal_policy( + session, + "my/topic/path/to/be/removed/no/updates", + "when no updates for 10m" + ); + + utils_create_json_topic_with_topic_removal_policy( + session, + "my/topic/path/to/be/removed/no/session", + "when no session has '$Principal is \"client\"' for 1h" + ); + + utils_create_json_topic_with_topic_removal_policy( + session, + "my/topic/path/to/be/removed/no/local/session", + "when no local session has 'Department is \"Accounts\"' for 1h after 1d" + ); + + utils_create_json_topic_with_topic_removal_policy( + session, + "my/topic/path/to/be/removed/subcriptions/or/updates", + "when subscriptions < 1 for 10m or no updates for 20m" + ); + + utils_create_json_topic_with_topic_removal_policy( + session, + "my/topic/path/to/be/removed/subcriptions/and/updates", + "when subscriptions < 1 for 10m and no updates for 20m" + ); + + + session_close(session, NULL); + session_free(session); + } \ No newline at end of file diff --git a/c/examples/pub_sub/remove/multiple_topics_via_selector.c b/c/examples/pub_sub/remove/multiple_topics_via_selector.c new file mode 100644 index 00000000..40de746d --- /dev/null +++ b/c/examples/pub_sub/remove/multiple_topics_via_selector.c @@ -0,0 +1,99 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_removed( + SESSION_T *session, + const DIFFUSION_TOPIC_REMOVAL_RESULT_T *response, + void *context) +{ + int removal_count = diffusion_topic_removal_result_removed_count(response); + printf("Removed %d topic(s).\n", removal_count); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + "my/topic/path/to/be/removed", + "{\"diffusion\": [ \"data\", \"more data\" ] }" + ); + + utils_create_json_topic( + session, + "my/topic/path/to/be/also/removed", + "{\"diffusion\": [ \"data\", \"also more data\" ] }" + ); + + utils_create_json_topic( + session, + "my/topic/path/will/not/be/removed", + "{\"diffusion\": [ \"no data\" ] }" + ); + + utils_create_json_topic( + session, + "my/topic/path/will/not/be/removed/either", + "{\"diffusion\": [ \"no data either\" ] }" + ); + + const char *topic_selector = "?my/topic/path/to/be//"; + + COORDINATOR_T *coordinator = coordinator_init(); + + TOPIC_REMOVAL_PARAMS_T remove_params = { + .topic_selector = topic_selector, + .on_removed = on_topic_removed, + .on_error = on_error, + .context = coordinator + }; + + topic_removal(session, remove_params); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); +} \ No newline at end of file diff --git a/c/examples/pub_sub/remove/single_topic_via_path.c b/c/examples/pub_sub/remove/single_topic_via_path.c new file mode 100644 index 00000000..68354e2a --- /dev/null +++ b/c/examples/pub_sub/remove/single_topic_via_path.c @@ -0,0 +1,93 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_removed( + SESSION_T *session, + const DIFFUSION_TOPIC_REMOVAL_RESULT_T *response, + void *context) +{ + int removal_count = diffusion_topic_removal_result_removed_count(response); + printf("Removed %d topic(s).\n", removal_count); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/topic/path/to/be/removed"; +; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + topic_path, + "{\"diffusion\": [ \"data\", \"more data\" ] }" + ); + + utils_create_json_topic( + session, + "my/topic/path/will/not/be/removed", + "{\"diffusion\": [ \"no data\" ] }" + ); + + utils_create_json_topic( + session, + "my/topic/path/will/not/be/removed/either", + "{\"diffusion\": [ \"no data either\" ] }" + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + TOPIC_REMOVAL_PARAMS_T remove_params = { + .topic_selector = topic_path, + .on_removed = on_topic_removed, + .on_error = on_error, + .context = coordinator + }; + + topic_removal(session, remove_params); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); +} \ No newline at end of file diff --git a/c/examples/pub_sub/subscribe/cross_compatible.c b/c/examples/pub_sub/subscribe/cross_compatible.c new file mode 100644 index 00000000..977576f2 --- /dev/null +++ b/c/examples/pub_sub/subscribe/cross_compatible.c @@ -0,0 +1,247 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_update_add_and_set( + DIFFUSION_TOPIC_CREATION_RESULT_T result, + void *context) +{ + if (result == TOPIC_CREATED) { + printf("Topic has been created.\n"); + } + else if (result == TOPIC_EXISTS) { + printf("Topic already exists.\n"); + } + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_json_subscription( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + void *context) +{ + printf("JSON stream subscribed to %s.\n", topic_path); + return HANDLER_SUCCESS; +} + +static int on_json_unsubscription( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + NOTIFY_UNSUBSCRIPTION_REASON_T reason, + void *context) +{ + printf("JSON stream unsubscribed from %s.\n", topic_path); + return HANDLER_SUCCESS; +} + +static int on_json_value( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + DIFFUSION_DATATYPE datatype, + const DIFFUSION_VALUE_T *const old_value, + const DIFFUSION_VALUE_T *const new_value, + void *context) +{ + char *old_value_json_string; + if (old_value == NULL) { + old_value_json_string = "NULL"; + } + else { + to_diffusion_json_string(old_value, &old_value_json_string, NULL); + } + + char *new_value_json_string; + if (new_value == NULL) { + new_value_json_string = "NULL"; + } + else { + to_diffusion_json_string(new_value, &new_value_json_string, NULL); + } + + printf( + "JSON stream %s changed from %s to %s.\n", + topic_path, old_value_json_string, new_value_json_string + ); + + if (old_value != NULL) { + free(old_value_json_string); + } + + if (new_value != NULL) { + free(new_value_json_string); + } + return HANDLER_SUCCESS; +} + +static int on_string_subscription( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + void *context) +{ + printf("String stream subscribed to %s.\n", topic_path); + return HANDLER_SUCCESS; +} + +static int on_string_unsubscription( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + NOTIFY_UNSUBSCRIPTION_REASON_T reason, + void *context) +{ + printf("String stream unsubscribed from %s.\n", topic_path); + return HANDLER_SUCCESS; +} + +static int on_string_value( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + DIFFUSION_DATATYPE datatype, + const DIFFUSION_VALUE_T *const old_value, + const DIFFUSION_VALUE_T *const new_value, + void *context) +{ + char *old_value_string; + if (old_value == NULL) { + old_value_string = "NULL"; + } + else { + read_diffusion_string_value(old_value, &old_value_string, NULL); + } + + char *new_value_string; + if (new_value == NULL) { + new_value_string = "NULL"; + } + else { + read_diffusion_string_value(new_value, &new_value_string, NULL); + } + + printf( + "String stream %s changed from %s to %s.\n", + topic_path, old_value_string, new_value_string + ); + + if (old_value != NULL) { + free(old_value_string); + } + + if (new_value != NULL) { + free(new_value_string); + } + return HANDLER_SUCCESS; +} + +static int on_subscribe( + SESSION_T*session, + void *context) +{ + printf("Subscription request received and approved by the server.\n"); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/int/topic/path"; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + TOPIC_SPECIFICATION_T *topic_specification = topic_specification_init(TOPIC_TYPE_INT64); + BUF_T *value = buf_create(); + write_diffusion_int64_value(123, value); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_TOPIC_UPDATE_ADD_AND_SET_PARAMS_T add_and_set_params = { + .datatype = DATATYPE_INT64, + .on_topic_update_add_and_set = on_topic_update_add_and_set, + .topic_path = topic_path, + .specification = topic_specification, + .update = value, + .on_error = on_error, + .context = coordinator + }; + diffusion_topic_update_add_and_set(session, add_and_set_params); + coordinator_wait(coordinator); + + buf_free(value); + topic_specification_free(topic_specification); + + // JSON is compatible with INT64 datatype + // So this stream will receive notifications from the INT64 topic + VALUE_STREAM_T json_value_stream = { + .datatype = DATATYPE_JSON, + .on_subscription = on_json_subscription, + .on_unsubscription = on_json_unsubscription, + .on_value = on_json_value + }; + + add_stream(session, topic_path, &json_value_stream); + + // String is not compatible with INT64 datatype + // This stream will receive notifications of + // on_subscription and on_unsubscription, but + // no on_value notifications + VALUE_STREAM_T string_value_stream = { + .datatype = DATATYPE_STRING, + .on_subscription = on_string_subscription, + .on_unsubscription = on_string_unsubscription, + .on_value = on_string_value + }; + + add_stream(session, topic_path, &string_value_stream); + + SUBSCRIPTION_PARAMS_T params = { + .topic_selector = topic_path, + .on_subscribe = on_subscribe, + .context = coordinator + }; + + subscribe(session, params); + coordinator_wait(coordinator); + + // Sleep for a bit to see the notifications + sleep(2); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + } \ No newline at end of file diff --git a/c/examples/pub_sub/subscribe/fallback_stream.c b/c/examples/pub_sub/subscribe/fallback_stream.c new file mode 100644 index 00000000..82bb8739 --- /dev/null +++ b/c/examples/pub_sub/subscribe/fallback_stream.c @@ -0,0 +1,158 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_subscription( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + void *context) +{ + printf("Subscribed to %s.\n", topic_path); + return HANDLER_SUCCESS; +} + +static int on_unsubscription( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + NOTIFY_UNSUBSCRIPTION_REASON_T reason, + void *context) +{ + printf("Unsubscribed from %s.\n", topic_path); + return HANDLER_SUCCESS; +} + +static int on_value( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + DIFFUSION_DATATYPE datatype, + const DIFFUSION_VALUE_T *const old_value, + const DIFFUSION_VALUE_T *const new_value, + void *context) +{ + char *old_value_json_string; + if (old_value == NULL) { + old_value_json_string = strdup("NULL"); + } + else { + to_diffusion_json_string(old_value, &old_value_json_string, NULL); + } + + char *new_value_json_string; + if (new_value == NULL) { + new_value_json_string = strdup("NULL"); + } + else { + to_diffusion_json_string(new_value, &new_value_json_string, NULL); + } + + printf( + "%s changed from %s to %s.\n", + topic_path, old_value_json_string, new_value_json_string + ); + + free(old_value_json_string); + free(new_value_json_string); + + return HANDLER_SUCCESS; +} + +static int on_subscribe( + SESSION_T*session, + void *context) +{ + printf("Subscription request received and approved by the server.\n"); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + "my/topic/path", + "{\"diffusion\": [ \"data\", \"some data\" ] }" + ); + + utils_create_json_topic( + session, + "my/other/topic/path", + "{\"diffusion\": [ \"data\", \"more data\" ] }" + ); + + VALUE_STREAM_T value_stream = { + .datatype = DATATYPE_JSON, + .on_subscription = on_subscription, + .on_unsubscription = on_unsubscription, + .on_value = on_value + }; + + add_fallback_stream(session, &value_stream); + + const char *topic_selector = "?my//"; + + COORDINATOR_T *coordinator = coordinator_init(); + + SUBSCRIPTION_PARAMS_T params = { + .topic_selector = topic_selector, + .on_subscribe = on_subscribe, + .context = coordinator + }; + + subscribe(session, params); + coordinator_wait(coordinator); + + // Sleep for a bit to see the notifications + sleep(2); + + utils_create_json_topic( + session, + "my/additional/topic/path", + "{\"diffusion\": [ \"data\", \"even more data\" ] }" + ); + + utils_create_json_topic( + session, + "this/topic/path/will/not/be/picked/up", + "{\"diffusion\": [ \"no data\" ] }" + ); + + // Sleep for a bit to see the notifications + sleep(2); + + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); +} \ No newline at end of file diff --git a/c/examples/pub_sub/subscribe/multiple_topics_via_selector.c b/c/examples/pub_sub/subscribe/multiple_topics_via_selector.c new file mode 100644 index 00000000..6bb06945 --- /dev/null +++ b/c/examples/pub_sub/subscribe/multiple_topics_via_selector.c @@ -0,0 +1,154 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_subscription( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + void *context) +{ + printf("Subscribed to %s.\n", topic_path); + return HANDLER_SUCCESS; +} + +static int on_unsubscription( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + NOTIFY_UNSUBSCRIPTION_REASON_T reason, + void *context) +{ + printf("Unsubscribed from %s.\n", topic_path); + return HANDLER_SUCCESS; +} + +static int on_value( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + DIFFUSION_DATATYPE datatype, + const DIFFUSION_VALUE_T *const old_value, + const DIFFUSION_VALUE_T *const new_value, + void *context) +{ + char *old_value_json_string; + if (old_value == NULL) { + old_value_json_string = "NULL"; + } + else { + to_diffusion_json_string(old_value, &old_value_json_string, NULL); + } + + char *new_value_json_string; + if (new_value == NULL) { + new_value_json_string = "NULL"; + } + else { + to_diffusion_json_string(new_value, &new_value_json_string, NULL); + } + + printf( + "%s changed from %s to %s.\n", + topic_path, old_value_json_string, new_value_json_string + ); + + if (old_value != NULL) { + free(old_value_json_string); + } + + if (new_value != NULL) { + free(new_value_json_string); + } + return HANDLER_SUCCESS; +} + +static int on_subscribe( + SESSION_T*session, + void *context) +{ + printf("Subscription request received and approved by the server.\n"); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + "my/topic/path", + "{\"diffusion\": [ \"data\", \"some data\" ] }" + ); + + utils_create_json_topic( + session, + "my/other/topic/path", + "{\"diffusion\": [ \"data\", \"more data\" ] }" + ); + + VALUE_STREAM_T value_stream = { + .datatype = DATATYPE_JSON, + .on_subscription = on_subscription, + .on_unsubscription = on_unsubscription, + .on_value = on_value + }; + + const char *topic_selector = "?my//"; + add_stream(session, topic_selector, &value_stream); + + COORDINATOR_T *coordinator = coordinator_init(); + + SUBSCRIPTION_PARAMS_T params = { + .topic_selector = topic_selector, + .on_subscribe = on_subscribe, + .context = coordinator + }; + + subscribe(session, params); + coordinator_wait(coordinator); + + // Sleep for a bit to see the notifications + sleep(2); + + utils_create_json_topic( + session, + "my/additional/topic/path", + "{\"diffusion\": [ \"data\", \"even more data\" ] }" + ); + + // Sleep for a bit to see the notifications + sleep(2); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); +} \ No newline at end of file diff --git a/c/examples/pub_sub/subscribe/selection_scopes.c b/c/examples/pub_sub/subscribe/selection_scopes.c new file mode 100644 index 00000000..d736b441 --- /dev/null +++ b/c/examples/pub_sub/subscribe/selection_scopes.c @@ -0,0 +1,185 @@ +/** + * Copyright © 2025 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_subscription( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + void *context) +{ + printf("Subscribed to %s.\n", topic_path); + return HANDLER_SUCCESS; +} + +static int on_unsubscription( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + NOTIFY_UNSUBSCRIPTION_REASON_T reason, + void *context) +{ + printf("Unsubscribed from %s.\n", topic_path); + return HANDLER_SUCCESS; +} + +static int on_value( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + DIFFUSION_DATATYPE datatype, + const DIFFUSION_VALUE_T *const old_value, + const DIFFUSION_VALUE_T *const new_value, + void *context) +{ + char *old_value_json_string; + if (old_value == NULL) { + old_value_json_string = "NULL"; + } + else { + to_diffusion_json_string(old_value, &old_value_json_string, NULL); + } + + char *new_value_json_string; + if (new_value == NULL) { + new_value_json_string = "NULL"; + } + else { + to_diffusion_json_string(new_value, &new_value_json_string, NULL); + } + + printf( + "%s changed from %s to %s.\n", + topic_path, old_value_json_string, new_value_json_string + ); + + if (old_value != NULL) { + free(old_value_json_string); + } + + if (new_value != NULL) { + free(new_value_json_string); + } + return HANDLER_SUCCESS; +} + +static int on_subscribe( + SESSION_T*session, + void *context) +{ + printf("Subscription request received and approved by the server.\n"); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_unsubscribe( + SESSION_T*session, + void *context) +{ + printf("Unsubscription request received and approved by the server.\n"); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path_1 = "my/topic/path"; + char *topic_path_2 = "my/other/topic/path"; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + topic_path_1, + "{\"diffusion\": [ \"data\"] }" + ); + + utils_create_json_topic( + session, + topic_path_2, + "{\"diffusion\": [ \"more data\" ] }" + ); + + VALUE_STREAM_T value_stream = { + .datatype = DATATYPE_JSON, + .on_subscription = on_subscription, + .on_unsubscription = on_unsubscription, + .on_value = on_value + }; + + add_stream(session, "?.*//", &value_stream); + + COORDINATOR_T *coordinator = coordinator_init(); + + SUBSCRIPTION_PARAMS_T params_subscribe_1 = { + .topic_selector = topic_path_1, + .on_subscribe = on_subscribe, + .context = coordinator + }; + + diffusion_subscribe_with_scope(session, "scopeA", params_subscribe_1, NULL); + coordinator_wait(coordinator); + + SUBSCRIPTION_PARAMS_T params_subscribe_2 = { + .topic_selector = topic_path_2, + .on_subscribe = on_subscribe, + .context = coordinator + }; + + diffusion_subscribe_with_scope(session, "scopeB", params_subscribe_2, NULL); + coordinator_wait(coordinator); + + // Sleep for a bit to see the notifications + sleep(2); + + UNSUBSCRIPTION_PARAMS_T params_unsubscribe = { + .on_unsubscribe = on_unsubscribe, + .on_error = on_error, + .topic_selector = "?.*//", + .context = coordinator + }; + + diffusion_unsubscribe_with_scope(session, "scopeA", params_unsubscribe, NULL); + coordinator_wait(coordinator); + + // Sleep for a bit to see the notifications + sleep(2); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); +} \ No newline at end of file diff --git a/c/examples/pub_sub/subscribe/single_topic_via_path.c b/c/examples/pub_sub/subscribe/single_topic_via_path.c new file mode 100644 index 00000000..256b2d4b --- /dev/null +++ b/c/examples/pub_sub/subscribe/single_topic_via_path.c @@ -0,0 +1,140 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_subscription( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + void *context) +{ + printf("Subscribed to %s.\n", topic_path); + return HANDLER_SUCCESS; +} + +static int on_unsubscription( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + NOTIFY_UNSUBSCRIPTION_REASON_T reason, + void *context) +{ + printf("Unsubscribed from %s.\n", topic_path); + return HANDLER_SUCCESS; +} + +static int on_value( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + DIFFUSION_DATATYPE datatype, + const DIFFUSION_VALUE_T *const old_value, + const DIFFUSION_VALUE_T *const new_value, + void *context) +{ + char *old_value_json_string; + if (old_value == NULL) { + old_value_json_string = "NULL"; + } + else { + to_diffusion_json_string(old_value, &old_value_json_string, NULL); + } + + char *new_value_json_string; + if (new_value == NULL) { + new_value_json_string = "NULL"; + } + else { + to_diffusion_json_string(new_value, &new_value_json_string, NULL); + } + + printf( + "%s changed from %s to %s.\n", + topic_path, old_value_json_string, new_value_json_string + ); + + if (old_value != NULL) { + free(old_value_json_string); + } + + if (new_value != NULL) { + free(new_value_json_string); + } + return HANDLER_SUCCESS; +} + +static int on_subscribe( + SESSION_T*session, + void *context) +{ + printf("Subscription request received and approved by the server.\n"); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/topic/path"; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + topic_path, + "{\"diffusion\": [ \"data\", \"more data\" ] }" + ); + + VALUE_STREAM_T value_stream = { + .datatype = DATATYPE_JSON, + .on_subscription = on_subscription, + .on_unsubscription = on_unsubscription, + .on_value = on_value + }; + + add_stream(session, topic_path, &value_stream); + + COORDINATOR_T *coordinator = coordinator_init(); + + SUBSCRIPTION_PARAMS_T params = { + .topic_selector = topic_path, + .on_subscribe = on_subscribe, + .context = coordinator + }; + + subscribe(session, params); + coordinator_wait(coordinator); + + // Sleep for a bit to see the notifications + sleep(2); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); +} \ No newline at end of file diff --git a/c/examples/remote_servers/check.c b/c/examples/remote_servers/check.c new file mode 100644 index 00000000..a4835734 --- /dev/null +++ b/c/examples/remote_servers/check.c @@ -0,0 +1,220 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +LIST_T *g_remote_server_names; + +static int on_remote_server_created( + DIFFUSION_REMOTE_SERVER_T *remote_server, + LIST_T *errors, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + + +static int on_remote_servers_listed( + LIST_T *remote_servers, + void *context) +{ + int size = list_get_size(remote_servers); + + for (int i = 0; i < size; i++) { + DIFFUSION_REMOTE_SERVER_T *remote_server = + list_get_data_indexed(remote_servers, i); + + char *name = diffusion_remote_server_get_name(remote_server); + char *url = diffusion_remote_server_get_url(remote_server); + + printf("\t%s (%s)\n", name, url); + + list_append_last(g_remote_server_names, name); + free(url); + } + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + + +static int on_remote_server_checked( + DIFFUSION_CHECK_REMOTE_SERVER_RESPONSE_T *response, + void *context) +{ + DIFFUSION_REMOTE_SERVER_CONNECTION_STATE_T state = + diffusion_check_remote_server_response_get_state(response); + + switch(state) { + case DIFFUSION_REMOTE_SERVER_CONNECTION_STATE_INACTIVE: + printf("\tInactive\n"); + break; + case DIFFUSION_REMOTE_SERVER_CONNECTION_STATE_CONNECTED: + printf("\tConnected\n"); + break; + case DIFFUSION_REMOTE_SERVER_CONNECTION_STATE_RETRYING: + printf("\tRetrying\n"); + break; + case DIFFUSION_REMOTE_SERVER_CONNECTION_STATE_FAILED: + printf("\tConnection Failed\n"); + break; + case DIFFUSION_REMOTE_SERVER_CONNECTION_STATE_MISSING: + printf("\tMissing\n"); + break; + default: + printf("\tUnexpected\n"); + break; + } + + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + SESSION_T *session = utils_open_session(url, "admin", "password"); + + CREDENTIALS_T *server_credentials = credentials_create_password("password"); + + DIFFUSION_REMOTE_SERVER_BUILDER_T *builder = + diffusion_remote_server_builder_init(); + + diffusion_remote_server_builder_principal(builder, "admin"); + diffusion_remote_server_builder_credentials(builder, server_credentials); + + diffusion_remote_server_builder_connection_option( + builder, DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_RECONNECTION_TIMEOUT, "120000" + ); + diffusion_remote_server_builder_connection_option( + builder, DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_MAXIMUM_QUEUE_SIZE, "1000" + ); + diffusion_remote_server_builder_connection_option( + builder, DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_CONNECTION_TIMEOUT, "15000" + ); + + DIFFUSION_REMOTE_SERVER_T *remote_server_1 = + diffusion_remote_server_builder_create_secondary_initiator( + builder, + "Remote Server 1", + "ws://new.server.url.com", + NULL + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_CREATE_REMOTE_SERVER_PARAMS_T params_create_1 = { + .remote_server = remote_server_1, + .on_remote_server_created = on_remote_server_created, + .on_error = on_error, + .context = coordinator + }; + + diffusion_create_remote_server(session, params_create_1, NULL); + coordinator_wait(coordinator); + + diffusion_remote_server_builder_reset(builder); + diffusion_remote_server_builder_principal(builder, "control"); + diffusion_remote_server_builder_credentials(builder, server_credentials); + + diffusion_remote_server_builder_connection_option( + builder, DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_RECONNECTION_TIMEOUT, "6000" + ); + diffusion_remote_server_builder_connection_option( + builder, DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_MAXIMUM_QUEUE_SIZE, "10000" + ); + diffusion_remote_server_builder_connection_option( + builder, DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_CONNECTION_TIMEOUT, "5000" + ); + + DIFFUSION_REMOTE_SERVER_T *remote_server_2 = + diffusion_remote_server_builder_create_secondary_initiator( + builder, + "Remote Server 2", + "ws://another.server.url.com", + NULL + ); + + DIFFUSION_CREATE_REMOTE_SERVER_PARAMS_T params_create_2 = { + .remote_server = remote_server_2, + .on_remote_server_created = on_remote_server_created, + .on_error = on_error, + .context = coordinator + }; + + diffusion_create_remote_server(session, params_create_2, NULL); + coordinator_wait(coordinator); + + g_remote_server_names = list_create(); + + DIFFUSION_LIST_REMOTE_SERVERS_PARAMS_T params_list = { + .on_remote_servers_listed = on_remote_servers_listed, + .on_error = on_error, + .context = coordinator + }; + + diffusion_list_remote_servers(session, params_list, NULL); + coordinator_wait(coordinator); + + int size = list_get_size(g_remote_server_names); + for (int i = 0; i < size; i++) { + char *remote_server_name = list_get_data_indexed(g_remote_server_names, i); + + printf("%s\n", remote_server_name); + + DIFFUSION_CHECK_REMOTE_SERVER_PARAMS_T params_check = { + .name = remote_server_name, + .on_remote_server_checked = on_remote_server_checked, + .on_error = on_error, + .context = coordinator + }; + + diffusion_check_remote_server(session, params_check, NULL); + coordinator_wait(coordinator); + } + list_free(g_remote_server_names, free); + + + session_close(session, NULL); + session_free(session); + + credentials_free(server_credentials); + coordinator_free(coordinator); + + diffusion_remote_server_free(remote_server_1); + diffusion_remote_server_free(remote_server_2); + + diffusion_remote_server_builder_free(builder); +} diff --git a/c/examples/remote_servers/create_primary_initiator.c b/c/examples/remote_servers/create_primary_initiator.c new file mode 100644 index 00000000..a4072486 --- /dev/null +++ b/c/examples/remote_servers/create_primary_initiator.c @@ -0,0 +1,92 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_remote_server_created( + DIFFUSION_REMOTE_SERVER_T *remote_server, + LIST_T *errors, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + SESSION_T *session = utils_open_session(url, "admin", "password"); + + DIFFUSION_REMOTE_SERVER_BUILDER_T *builder = + diffusion_remote_server_builder_init(); + + diffusion_remote_server_builder_retry_delay(builder, 250, NULL); + + LIST_T *urls = list_create(); + list_append_last(urls, "ws://localhost:8080"); + list_append_last(urls, "ws://localhost:8081"); + list_append_last(urls, "ws://localhost:8082"); + + DIFFUSION_REMOTE_SERVER_T *remote_server = + diffusion_remote_server_builder_create_primary_initiator( + builder, + "Remote Server 1", + urls, + "High Volume Connector", + NULL + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_CREATE_REMOTE_SERVER_PARAMS_T params = { + .remote_server = remote_server, + .on_remote_server_created = on_remote_server_created, + .on_error = on_error, + .context = coordinator + }; + + diffusion_create_remote_server(session, params, NULL); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + + diffusion_remote_server_free(remote_server); + + diffusion_remote_server_builder_free(builder); + list_free(urls, NULL); +} diff --git a/c/examples/remote_servers/create_secondary_acceptor.c b/c/examples/remote_servers/create_secondary_acceptor.c new file mode 100644 index 00000000..7e0e1580 --- /dev/null +++ b/c/examples/remote_servers/create_secondary_acceptor.c @@ -0,0 +1,101 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_remote_server_created( + DIFFUSION_REMOTE_SERVER_T *remote_server, + LIST_T *errors, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + DIFFUSION_REMOTE_SERVER_BUILDER_T *builder = + diffusion_remote_server_builder_init(); + + CREDENTIALS_T *no_credentials = credentials_create_none(); + + diffusion_remote_server_builder_principal(builder, ""); + diffusion_remote_server_builder_credentials(builder, no_credentials); + diffusion_remote_server_builder_missing_topic_notification_filter(builder, "?abc"); + + diffusion_remote_server_builder_connection_option( + builder, DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_WRITE_TIMEOUT, "2000" + ); + diffusion_remote_server_builder_connection_option( + builder, DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_MAXIMUM_QUEUE_SIZE, "1000" + ); + diffusion_remote_server_builder_connection_option( + builder, DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_CONNECTION_TIMEOUT, "15000" + ); + + DIFFUSION_REMOTE_SERVER_T *remote_server = + diffusion_remote_server_builder_create_secondary_acceptor( + builder, + "Remote Server 1", + "ws://new.server.url.com", + NULL + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_CREATE_REMOTE_SERVER_PARAMS_T params = { + .remote_server = remote_server, + .on_remote_server_created = on_remote_server_created, + .on_error = on_error, + .context = coordinator + }; + + diffusion_create_remote_server(session, params, NULL); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + credentials_free(no_credentials); + + diffusion_remote_server_free(remote_server); + diffusion_remote_server_builder_free(builder); +} diff --git a/c/examples/remote_servers/create_secondary_initiator.c b/c/examples/remote_servers/create_secondary_initiator.c new file mode 100644 index 00000000..f9ce3026 --- /dev/null +++ b/c/examples/remote_servers/create_secondary_initiator.c @@ -0,0 +1,103 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_remote_server_created( + DIFFUSION_REMOTE_SERVER_T *remote_server, + LIST_T *errors, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + CREDENTIALS_T *server_credentials = credentials_create_password("password"); + + DIFFUSION_REMOTE_SERVER_BUILDER_T *builder = + diffusion_remote_server_builder_init(); + + diffusion_remote_server_builder_principal(builder, "admin"); + diffusion_remote_server_builder_credentials(builder, server_credentials); + diffusion_remote_server_builder_missing_topic_notification_filter(builder, "?abc"); + + diffusion_remote_server_builder_connection_option( + builder, DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_RECONNECTION_TIMEOUT, "120000" + ); + diffusion_remote_server_builder_connection_option( + builder, DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_MAXIMUM_QUEUE_SIZE, "1000" + ); + diffusion_remote_server_builder_connection_option( + builder, DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_CONNECTION_TIMEOUT, "15000" + ); + + DIFFUSION_REMOTE_SERVER_T *remote_server = + diffusion_remote_server_builder_create_secondary_initiator( + builder, + "Remote Server 1", + "ws://new.server.url.com", + NULL + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_CREATE_REMOTE_SERVER_PARAMS_T params = { + .remote_server = remote_server, + .on_remote_server_created = on_remote_server_created, + .on_error = on_error, + .context = coordinator + }; + + diffusion_create_remote_server(session, params, NULL); + coordinator_wait(coordinator); + + + session_close(session, NULL); + session_free(session); + + credentials_free(server_credentials); + coordinator_free(coordinator); + + diffusion_remote_server_free(remote_server); + + diffusion_remote_server_builder_free(builder); +} diff --git a/c/examples/remote_servers/list.c b/c/examples/remote_servers/list.c new file mode 100644 index 00000000..98f76843 --- /dev/null +++ b/c/examples/remote_servers/list.c @@ -0,0 +1,164 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_remote_server_created( + DIFFUSION_REMOTE_SERVER_T *remote_server, + LIST_T *errors, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_remote_servers_listed( + LIST_T *remote_servers, + void *context) +{ + int size = list_get_size(remote_servers); + + for (int i = 0; i < size; i++) { + DIFFUSION_REMOTE_SERVER_T *remote_server = + list_get_data_indexed(remote_servers, i); + + char *name = diffusion_remote_server_get_name(remote_server); + char *url = diffusion_remote_server_get_url(remote_server); + + printf("\t%s (%s)\n", name, url); + + free(url); + free(name); + } + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + CREDENTIALS_T *server_credentials = credentials_create_password("password"); + + DIFFUSION_REMOTE_SERVER_BUILDER_T *builder = + diffusion_remote_server_builder_init(); + + diffusion_remote_server_builder_principal(builder, "admin"); + diffusion_remote_server_builder_credentials(builder, server_credentials); + + diffusion_remote_server_builder_connection_option( + builder, DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_RECONNECTION_TIMEOUT, "120000" + ); + diffusion_remote_server_builder_connection_option( + builder, DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_MAXIMUM_QUEUE_SIZE, "1000" + ); + diffusion_remote_server_builder_connection_option( + builder, DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_CONNECTION_TIMEOUT, "15000" + ); + + DIFFUSION_REMOTE_SERVER_T *remote_server_1 = + diffusion_remote_server_builder_create_secondary_initiator( + builder, + "Remote Server 1", + "ws://new.server.url.com", + NULL + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_CREATE_REMOTE_SERVER_PARAMS_T params_create_1 = { + .remote_server = remote_server_1, + .on_remote_server_created = on_remote_server_created, + .on_error = on_error, + .context = coordinator + }; + + diffusion_create_remote_server(session, params_create_1, NULL); + coordinator_wait(coordinator); + + diffusion_remote_server_builder_reset(builder); + diffusion_remote_server_builder_principal(builder, "control"); + diffusion_remote_server_builder_credentials(builder, server_credentials); + + diffusion_remote_server_builder_connection_option( + builder, DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_RECONNECTION_TIMEOUT, "6000" + ); + diffusion_remote_server_builder_connection_option( + builder, DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_MAXIMUM_QUEUE_SIZE, "10000" + ); + diffusion_remote_server_builder_connection_option( + builder, DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_CONNECTION_TIMEOUT, "5000" + ); + + DIFFUSION_REMOTE_SERVER_T *remote_server_2 = + diffusion_remote_server_builder_create_secondary_initiator( + builder, + "Remote Server 2", + "ws://another.server.url.com", + NULL + ); + + DIFFUSION_CREATE_REMOTE_SERVER_PARAMS_T params_create_2 = { + .remote_server = remote_server_2, + .on_remote_server_created = on_remote_server_created, + .on_error = on_error, + .context = coordinator + }; + + diffusion_create_remote_server(session, params_create_2, NULL); + coordinator_wait(coordinator); + + DIFFUSION_LIST_REMOTE_SERVERS_PARAMS_T params_list = { + .on_remote_servers_listed = on_remote_servers_listed, + .on_error = on_error, + .context = coordinator + }; + + diffusion_list_remote_servers(session, params_list, NULL); + coordinator_wait(coordinator); + + + session_close(session, NULL); + session_free(session); + + credentials_free(server_credentials); + coordinator_free(coordinator); + + diffusion_remote_server_free(remote_server_1); + diffusion_remote_server_free(remote_server_2); + + diffusion_remote_server_builder_free(builder); +} diff --git a/c/examples/remote_servers/remove.c b/c/examples/remote_servers/remove.c new file mode 100644 index 00000000..c8da83f2 --- /dev/null +++ b/c/examples/remote_servers/remove.c @@ -0,0 +1,123 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +LIST_T *g_remote_server_names; + +static int on_remote_server_created( + DIFFUSION_REMOTE_SERVER_T *remote_server, + LIST_T *errors, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + + +static int on_remote_server_removed(void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + const char *remote_server_name = "Remote Server 1"; + + CREDENTIALS_T *server_credentials = credentials_create_password("password"); + + DIFFUSION_REMOTE_SERVER_BUILDER_T *builder = + diffusion_remote_server_builder_init(); + + diffusion_remote_server_builder_principal(builder, "admin"); + diffusion_remote_server_builder_credentials(builder, server_credentials); + + diffusion_remote_server_builder_connection_option( + builder, DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_RECONNECTION_TIMEOUT, "120000" + ); + diffusion_remote_server_builder_connection_option( + builder, DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_MAXIMUM_QUEUE_SIZE, "1000" + ); + diffusion_remote_server_builder_connection_option( + builder, DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_CONNECTION_TIMEOUT, "15000" + ); + + DIFFUSION_REMOTE_SERVER_T *remote_server = + diffusion_remote_server_builder_create_secondary_initiator( + builder, + (char *) remote_server_name, + "ws://new.server.url.com", + NULL + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_CREATE_REMOTE_SERVER_PARAMS_T params_create = { + .remote_server = remote_server, + .on_remote_server_created = on_remote_server_created, + .on_error = on_error, + .context = coordinator + }; + + diffusion_create_remote_server(session, params_create, NULL); + coordinator_wait(coordinator); + + DIFFUSION_REMOVE_REMOTE_SERVER_PARAMS_T params_remove = { + .name = (char *) remote_server_name, + .on_remote_server_removed = on_remote_server_removed, + .on_error = on_error, + .context = coordinator + }; + + diffusion_remove_remote_server(session, params_remove, NULL); + coordinator_wait(coordinator); + + printf("%s has been removed\n", remote_server_name); + + session_close(session, NULL); + session_free(session); + + credentials_free(server_credentials); + coordinator_free(coordinator); + + diffusion_remote_server_free(remote_server); + + diffusion_remote_server_builder_free(builder); +} diff --git a/c/examples/security/change_principal.c b/c/examples/security/change_principal.c new file mode 100644 index 00000000..59aaf172 --- /dev/null +++ b/c/examples/security/change_principal.c @@ -0,0 +1,69 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_change_success( + SESSION_T * session, + void *context) +{ + printf("Principal has been changed to control.\n"); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_change_failure( + SESSION_T *session, + void *context) +{ + printf("An error has occurred while changing principal to control.\n"); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create(url, principal, credentials, NULL, NULL, NULL); + + COORDINATOR_T *coordinator = coordinator_init(); + + CHANGE_PRINCIPAL_PARAMS_T params = { + .principal = "control", + .credentials = credentials, + .on_change_principal = on_change_success, + .on_change_principal_failure = on_change_success, + .context = coordinator + }; + + change_principal(session, params); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); +} \ No newline at end of file diff --git a/c/examples/security/get_global_permissions.c b/c/examples/security/get_global_permissions.c new file mode 100644 index 00000000..24512826 --- /dev/null +++ b/c/examples/security/get_global_permissions.c @@ -0,0 +1,64 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_global_permissions_received( + const SET_T *global_permissions, + void *context) +{ + void **values = set_values(global_permissions); + printf("Received Global Permissions (%ld):\n", global_permissions->size); + for(int i = 0; values[i] != NULL; i++) { + GLOBAL_PERMISSIONS_T *permission = (GLOBAL_PERMISSIONS_T *) values[i]; + printf("\t%s\n", utils_print_global_permission(permission)); + } + free(values); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create(url, principal, credentials, NULL, NULL, NULL); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_GET_GLOBAL_PERMISSIONS_PARAMS_T params = { + .on_global_permissions = on_global_permissions_received, + .context = coordinator + }; + + diffusion_get_global_permissions(session, params, NULL); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); +} \ No newline at end of file diff --git a/c/examples/security/get_path_permissions.c b/c/examples/security/get_path_permissions.c new file mode 100644 index 00000000..eed81dfc --- /dev/null +++ b/c/examples/security/get_path_permissions.c @@ -0,0 +1,63 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_path_permissions_received( + const SET_T *path_permissions, + void *context) +{ + void **values = set_values(path_permissions); + printf("Received Path Permissions (%ld):\n", path_permissions->size); + for(int i = 0; values[i] != NULL; i++) { + PATH_PERMISSIONS_T *permission = (PATH_PERMISSIONS_T *) values[i]; + printf("\t%s\n", utils_print_path_permission(permission)); + } + free(values); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + SESSION_T *session = session_create(url, principal, credentials, NULL, NULL, NULL); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_GET_PATH_PERMISSIONS_PARAMS_T params = { + .path = ".*//", + .on_path_permissions = on_path_permissions_received, + .context = coordinator + }; + + diffusion_get_path_permissions(session, params, NULL); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); +} \ No newline at end of file diff --git a/c/examples/security/reauthenticate.c b/c/examples/security/reauthenticate.c new file mode 100644 index 00000000..3f0dc929 --- /dev/null +++ b/c/examples/security/reauthenticate.c @@ -0,0 +1,71 @@ +/** + * Copyright © 2025 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_reauthenticate( + const SESSION_T * session, + bool success, + void *context) +{ + printf("Session has %sbeen reauthenticated.\n", success ? "" : "not "); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create(url, principal, credentials, NULL, NULL, NULL); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_REAUTHENTICATE_PARAMS_T params = { + .principal = "control", + .credentials = credentials, + .properties = NULL, + .on_reauthenticate = on_reauthenticate, + .on_error = on_error, + .context = coordinator + }; + + diffusion_reauthenticate(session, params, NULL); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); +} \ No newline at end of file diff --git a/c/examples/server_configuration/metrics/session_metric_collector_list.c b/c/examples/server_configuration/metrics/session_metric_collector_list.c new file mode 100644 index 00000000..1c122feb --- /dev/null +++ b/c/examples/server_configuration/metrics/session_metric_collector_list.c @@ -0,0 +1,173 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_collector_set(void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + +static int on_session_metric_collectors_received( + const LIST_T *collectors, + void *context) +{ + int total_collectors = list_get_size(collectors); + + printf("Received the following session metric collectors:\n"); + for (int i = 0; i < total_collectors; i++) { + DIFFUSION_SESSION_METRIC_COLLECTOR_T *collector = + list_get_data_indexed(collectors, i); + + char *name; + diffusion_session_metric_collector_get_name( + collector, &name + ); + + char *session_filter; + diffusion_session_metric_collector_get_session_filter( + collector, &session_filter + ); + + bool removes_metrics_with_no_matches; + diffusion_session_metric_collector_removes_metrics_with_no_matches( + collector, &removes_metrics_with_no_matches + ); + + bool exports_to_prometheus; + diffusion_session_metric_collector_exports_to_prometheus( + collector, &exports_to_prometheus + ); + + int maximum_groups; + diffusion_session_metric_collector_maximum_groups( + collector, &maximum_groups + ); + + LIST_T *group_by_properties; + diffusion_session_metric_collector_get_group_by_properties( + collector, &group_by_properties + ); + + char *group_by_properties_string = + utils_list_to_string(group_by_properties); + + printf( + "\t%s: %s (%d, %s, %s, %s)\n", + name, session_filter, maximum_groups, + exports_to_prometheus ? "true" : "false", + removes_metrics_with_no_matches ? "true" : "false", + group_by_properties_string + ); + + list_free(group_by_properties, free); + free(group_by_properties_string); + free(session_filter); + free(name); + } + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + DIFFUSION_SESSION_METRIC_COLLECTOR_BUILDER_T *builder = + diffusion_session_metric_collector_builder_init(); + + diffusion_session_metric_collector_builder_export_to_prometheus(builder, false); + diffusion_session_metric_collector_builder_maximum_groups(builder, 10); + diffusion_session_metric_collector_builder_remove_metrics_with_no_matches(builder, true); + diffusion_session_metric_collector_builder_group_by_property(builder, "$Location"); + + DIFFUSION_SESSION_METRIC_COLLECTOR_T *collector_1 = + diffusion_session_metric_collector_builder_create( + builder, "Session Metric Collector 1", "$Principal is 'control'", NULL + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_METRICS_PUT_SESSION_METRIC_COLLECTOR_PARAMS_T put_params_1 = { + .collector = collector_1, + .on_collector_set = on_collector_set, + .on_error = on_error, + .context = coordinator + }; + + diffusion_metrics_put_session_metric_collector(session, put_params_1, NULL); + coordinator_wait(coordinator); + + diffusion_session_metric_collector_builder_export_to_prometheus(builder, true); + diffusion_session_metric_collector_builder_maximum_groups(builder, 250); + diffusion_session_metric_collector_builder_remove_metrics_with_no_matches(builder, false); + + DIFFUSION_SESSION_METRIC_COLLECTOR_T *collector_2 = + diffusion_session_metric_collector_builder_create( + builder, "Session Metric Collector 2", "$Principal is 'control'", NULL + ); + + DIFFUSION_METRICS_PUT_SESSION_METRIC_COLLECTOR_PARAMS_T put_params_2 = { + .collector = collector_2, + .on_collector_set = on_collector_set, + .on_error = on_error, + .context = coordinator + }; + + diffusion_metrics_put_session_metric_collector(session, put_params_2, NULL); + coordinator_wait(coordinator); + + diffusion_session_metric_collector_builder_free(builder); + + DIFFUSION_METRICS_LIST_SESSION_METRIC_COLLECTORS_PARAMS_T list_params = { + .on_collectors_received = on_session_metric_collectors_received, + .on_error = on_error, + .context = coordinator + }; + + diffusion_metrics_list_session_metric_collectors(session, list_params, NULL); + coordinator_wait(coordinator); + + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + diffusion_session_metric_collector_free(collector_1); + diffusion_session_metric_collector_free(collector_2); +} \ No newline at end of file diff --git a/c/examples/server_configuration/metrics/session_metric_collector_put.c b/c/examples/server_configuration/metrics/session_metric_collector_put.c new file mode 100644 index 00000000..b637d3c4 --- /dev/null +++ b/c/examples/server_configuration/metrics/session_metric_collector_put.c @@ -0,0 +1,85 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_collector_set(void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + char *collector_name = "Session Metric Collector 1"; + + DIFFUSION_SESSION_METRIC_COLLECTOR_BUILDER_T *builder = + diffusion_session_metric_collector_builder_init(); + + diffusion_session_metric_collector_builder_export_to_prometheus(builder, false); + diffusion_session_metric_collector_builder_maximum_groups(builder, 10); + diffusion_session_metric_collector_builder_remove_metrics_with_no_matches(builder, true); + diffusion_session_metric_collector_builder_group_by_property(builder, "$Location"); + + DIFFUSION_SESSION_METRIC_COLLECTOR_T *collector = + diffusion_session_metric_collector_builder_create( + builder, collector_name, "$Principal is 'control'", NULL + ); + + diffusion_session_metric_collector_builder_free(builder); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_METRICS_PUT_SESSION_METRIC_COLLECTOR_PARAMS_T params = { + .collector = collector, + .on_collector_set = on_collector_set, + .on_error = on_error, + .context = coordinator + }; + + diffusion_metrics_put_session_metric_collector(session, params, NULL); + coordinator_wait(coordinator); + + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + diffusion_session_metric_collector_free(collector); +} \ No newline at end of file diff --git a/c/examples/server_configuration/metrics/session_metric_collector_remove.c b/c/examples/server_configuration/metrics/session_metric_collector_remove.c new file mode 100644 index 00000000..b122a531 --- /dev/null +++ b/c/examples/server_configuration/metrics/session_metric_collector_remove.c @@ -0,0 +1,100 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_collector_set(void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_collector_removed(void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + DIFFUSION_SESSION_METRIC_COLLECTOR_BUILDER_T *builder = + diffusion_session_metric_collector_builder_init(); + + diffusion_session_metric_collector_builder_export_to_prometheus(builder, false); + diffusion_session_metric_collector_builder_maximum_groups(builder, 10); + diffusion_session_metric_collector_builder_remove_metrics_with_no_matches(builder, true); + diffusion_session_metric_collector_builder_group_by_property(builder, "$Location"); + + DIFFUSION_SESSION_METRIC_COLLECTOR_T *collector = + diffusion_session_metric_collector_builder_create( + builder, "Session Metric Collector 1", "$Principal is 'control'", NULL + ); + + diffusion_session_metric_collector_builder_free(builder); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_METRICS_PUT_SESSION_METRIC_COLLECTOR_PARAMS_T params = { + .collector = collector, + .on_collector_set = on_collector_set, + .on_error = on_error, + .context = coordinator + }; + + diffusion_metrics_put_session_metric_collector(session, params, NULL); + coordinator_wait(coordinator); + + DIFFUSION_METRICS_REMOVE_SESSION_METRIC_COLLECTOR_PARAMS_T remove_params = { + .collector_name = "Session Metric Collector 1", + .on_collector_removed = on_collector_removed, + .on_error = on_error, + .context = coordinator + }; + + diffusion_metrics_remove_session_metric_collector(session, remove_params, NULL); + coordinator_wait(coordinator); + + printf("Session Metric Collector 1 has been removed.\n"); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + diffusion_session_metric_collector_free(collector); +} \ No newline at end of file diff --git a/c/examples/server_configuration/metrics/topic_metric_collector_list.c b/c/examples/server_configuration/metrics/topic_metric_collector_list.c new file mode 100644 index 00000000..17682fec --- /dev/null +++ b/c/examples/server_configuration/metrics/topic_metric_collector_list.c @@ -0,0 +1,178 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_collector_set(void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +static int on_topic_metric_collectors_received( + const LIST_T *collectors, + void *context) +{ + int total_collectors = list_get_size(collectors); + + printf("Received the following topic metric collectors:\n"); + for (int i = 0; i < total_collectors; i++) { + DIFFUSION_TOPIC_METRIC_COLLECTOR_T *collector = + list_get_data_indexed(collectors, i); + + char *name; + diffusion_topic_metric_collector_get_name ( + collector, &name + ); + + char *topic_selector; + diffusion_topic_metric_collector_get_topic_selector( + collector, &topic_selector + ); + + bool groups_by_topic_type; + diffusion_topic_metric_collector_groups_by_topic_type( + collector, &groups_by_topic_type + ); + + bool groups_by_topic_view; + diffusion_topic_metric_collector_groups_by_topic_view( + collector, &groups_by_topic_view + ); + + bool exports_to_prometheus; + diffusion_topic_metric_collector_exports_to_prometheus( + collector, &exports_to_prometheus + ); + + int maximum_groups; + diffusion_topic_metric_collector_maximum_groups( + collector, &maximum_groups + ); + + int group_by_path_prefix_parts; + diffusion_topic_metric_collector_group_by_path_prefix_parts( + collector, &group_by_path_prefix_parts + ); + + printf( + "\t%s: %s (%d, %s, %s, %s, %d)\n", + name, topic_selector, maximum_groups, + exports_to_prometheus ? "true" : "false", + groups_by_topic_type ? "true" : "false", + groups_by_topic_view ? "true" : "false", + group_by_path_prefix_parts + ); + + free(topic_selector); + free(name); + } + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + DIFFUSION_TOPIC_METRIC_COLLECTOR_BUILDER_T *builder = + diffusion_topic_metric_collector_builder_init(); + + diffusion_topic_metric_collector_builder_export_to_prometheus(builder, false); + diffusion_topic_metric_collector_builder_maximum_groups(builder, 10); + diffusion_topic_metric_collector_builder_group_by_topic_type(builder, true); + diffusion_topic_metric_collector_builder_group_by_topic_view(builder, true); + diffusion_topic_metric_collector_builder_group_by_path_prefix_parts(builder, 15); + + DIFFUSION_TOPIC_METRIC_COLLECTOR_T *collector_1 = + diffusion_topic_metric_collector_builder_create( + builder, "Topic Metric Collector 1", "?my/topic//", NULL + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_METRICS_PUT_TOPIC_METRIC_COLLECTOR_PARAMS_T put_params_1 = { + .collector = collector_1, + .on_collector_set = on_collector_set, + .on_error = on_error, + .context = coordinator + }; + + diffusion_metrics_put_topic_metric_collector(session, put_params_1, NULL); + coordinator_wait(coordinator); + + diffusion_topic_metric_collector_builder_export_to_prometheus(builder, true); + diffusion_topic_metric_collector_builder_maximum_groups(builder, 250); + diffusion_topic_metric_collector_builder_group_by_topic_type(builder, false); + diffusion_topic_metric_collector_builder_group_by_topic_view(builder, true); + diffusion_topic_metric_collector_builder_group_by_path_prefix_parts(builder, 15); + + DIFFUSION_TOPIC_METRIC_COLLECTOR_T *collector_2 = + diffusion_topic_metric_collector_builder_create( + builder, "Topic Metric Collector 2", "?my/topic//", NULL + ); + + diffusion_topic_metric_collector_builder_free(builder); + + DIFFUSION_METRICS_PUT_TOPIC_METRIC_COLLECTOR_PARAMS_T put_params_2 = { + .collector = collector_2, + .on_collector_set = on_collector_set, + .on_error = on_error, + .context = coordinator + }; + + diffusion_metrics_put_topic_metric_collector(session, put_params_2, NULL); + coordinator_wait(coordinator); + + DIFFUSION_METRICS_LIST_TOPIC_METRIC_COLLECTORS_PARAMS_T list_params = { + .on_collectors_received = on_topic_metric_collectors_received, + .on_error = on_error, + .context = coordinator + }; + + diffusion_metrics_list_topic_metric_collectors(session, list_params, NULL); + coordinator_wait(coordinator); + + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + diffusion_topic_metric_collector_free(collector_1); + diffusion_topic_metric_collector_free(collector_2); +} \ No newline at end of file diff --git a/c/examples/server_configuration/metrics/topic_metric_collector_put.c b/c/examples/server_configuration/metrics/topic_metric_collector_put.c new file mode 100644 index 00000000..c194aa0a --- /dev/null +++ b/c/examples/server_configuration/metrics/topic_metric_collector_put.c @@ -0,0 +1,86 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_collector_set(void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + char *collector_name = "Topic Metric Collector 1"; + + DIFFUSION_TOPIC_METRIC_COLLECTOR_BUILDER_T *builder = + diffusion_topic_metric_collector_builder_init(); + + diffusion_topic_metric_collector_builder_export_to_prometheus(builder, false); + diffusion_topic_metric_collector_builder_maximum_groups(builder, 10); + diffusion_topic_metric_collector_builder_group_by_topic_type(builder, true); + diffusion_topic_metric_collector_builder_group_by_topic_view(builder, true); + diffusion_topic_metric_collector_builder_group_by_path_prefix_parts(builder, 15); + + DIFFUSION_TOPIC_METRIC_COLLECTOR_T *collector = + diffusion_topic_metric_collector_builder_create( + builder, collector_name, "?my/topic//", NULL + ); + + diffusion_topic_metric_collector_builder_free(builder); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_METRICS_PUT_TOPIC_METRIC_COLLECTOR_PARAMS_T params = { + .collector = collector, + .on_collector_set = on_collector_set, + .on_error = on_error, + .context = coordinator + }; + + diffusion_metrics_put_topic_metric_collector(session, params, NULL); + coordinator_wait(coordinator); + + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + diffusion_topic_metric_collector_free(collector); +} \ No newline at end of file diff --git a/c/examples/server_configuration/metrics/topic_metric_collector_remove.c b/c/examples/server_configuration/metrics/topic_metric_collector_remove.c new file mode 100644 index 00000000..ee1a38ea --- /dev/null +++ b/c/examples/server_configuration/metrics/topic_metric_collector_remove.c @@ -0,0 +1,103 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_collector_set(void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_collector_removed(void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + const char *collector_name = "Topic Metric Collector 1"; + + DIFFUSION_TOPIC_METRIC_COLLECTOR_BUILDER_T *builder = + diffusion_topic_metric_collector_builder_init(); + + diffusion_topic_metric_collector_builder_export_to_prometheus(builder, false); + diffusion_topic_metric_collector_builder_maximum_groups(builder, 10); + diffusion_topic_metric_collector_builder_group_by_topic_type(builder, true); + diffusion_topic_metric_collector_builder_group_by_topic_view(builder, true); + diffusion_topic_metric_collector_builder_group_by_path_prefix_parts(builder, 15); + + DIFFUSION_TOPIC_METRIC_COLLECTOR_T *collector_1 = + diffusion_topic_metric_collector_builder_create( + builder, (char *) collector_name, "?my/topic//", NULL + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_METRICS_PUT_TOPIC_METRIC_COLLECTOR_PARAMS_T put_params = { + .collector = collector_1, + .on_collector_set = on_collector_set, + .on_error = on_error, + .context = coordinator + }; + + diffusion_metrics_put_topic_metric_collector(session, put_params, NULL); + coordinator_wait(coordinator); + + DIFFUSION_METRICS_REMOVE_TOPIC_METRIC_COLLECTOR_PARAMS_T remove_params = { + .collector_name = (char *) collector_name, + .on_collector_removed = on_collector_removed, + .on_error = on_error, + .context = coordinator + }; + + diffusion_metrics_remove_topic_metric_collector(session, remove_params, NULL); + coordinator_wait(coordinator); + + printf("%s has been removed.\n", collector_name); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + diffusion_topic_metric_collector_free(collector_1); + diffusion_topic_metric_collector_builder_free(builder); +} \ No newline at end of file diff --git a/c/examples/server_configuration/security_control/define_roles_hierarchy.c b/c/examples/server_configuration/security_control/define_roles_hierarchy.c new file mode 100644 index 00000000..91f6cc2a --- /dev/null +++ b/c/examples/server_configuration/security_control/define_roles_hierarchy.c @@ -0,0 +1,91 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_security_store_updated( + SESSION_T *session, + const LIST_T *error_report, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + printf("Original Security Store Settings for role OPERATOR\n"); + utils_print_security_store(session, "OPERATOR"); + + LIST_T *list_roles = list_create(); + list_append_last(list_roles, "CLIENT"); + list_append_last(list_roles, "CLIENT_CONTROL"); + + SCRIPT_T *script = script_create(); + update_security_store_include_roles( + script, "OPERATOR", list_roles + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + const UPDATE_SECURITY_STORE_PARAMS_T params = { + .on_update = on_security_store_updated, + .on_error = on_error, + .update_script = script, + .context = coordinator + }; + + utils_print_script(script); + update_security_store(session, params); + coordinator_wait(coordinator); + + script_free(script); + list_free(list_roles, NULL); + printf("\nOPERATOR now includes CLIENT and CLIENT_CONTROL roles.\n"); + + printf("New Security Store settings for role OPERATOR\n"); + utils_print_security_store(session, "OPERATOR"); + + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); +} diff --git a/c/examples/server_configuration/security_control/deisolate_path.c b/c/examples/server_configuration/security_control/deisolate_path.c new file mode 100644 index 00000000..1016afdc --- /dev/null +++ b/c/examples/server_configuration/security_control/deisolate_path.c @@ -0,0 +1,101 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_security_store_updated( + SESSION_T *session, + const LIST_T *error_report, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + printf("Original Store\n"); + utils_print_security_store(session, NULL); + + const char *topic_path = "my/topic/path"; + + SCRIPT_T *isolate_path_script = script_create(); + update_security_store_isolate_path(isolate_path_script, topic_path); + + COORDINATOR_T *coordinator = coordinator_init(); + + const UPDATE_SECURITY_STORE_PARAMS_T isolate_path_params = { + .on_update = on_security_store_updated, + .on_error = on_error, + .update_script = isolate_path_script, + .context = coordinator + }; + + printf("\nIsolating %s permissions from parent and default path permissions.\n", topic_path); + utils_print_script(isolate_path_script); + + update_security_store(session, isolate_path_params); + coordinator_wait(coordinator); + + script_free(isolate_path_script); + + SCRIPT_T *deisolate_path_script = script_create(); + update_security_store_deisolate_path(deisolate_path_script, topic_path); + + const UPDATE_SECURITY_STORE_PARAMS_T deisolate_path_params = { + .on_update = on_security_store_updated, + .on_error = on_error, + .update_script = deisolate_path_script, + .context = coordinator + }; + + printf("\nRemoving %s permission isolation.\n", topic_path); + utils_print_script(deisolate_path_script); + + update_security_store(session, deisolate_path_params); + coordinator_wait(coordinator); + + script_free(deisolate_path_script); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); +} diff --git a/c/examples/server_configuration/security_control/isolate_path.c b/c/examples/server_configuration/security_control/isolate_path.c new file mode 100644 index 00000000..8cb6a968 --- /dev/null +++ b/c/examples/server_configuration/security_control/isolate_path.c @@ -0,0 +1,80 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_security_store_updated( + SESSION_T *session, + const LIST_T *error_report, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + const char *topic_path = "my/topic/path"; + + SCRIPT_T *script = script_create(); + update_security_store_isolate_path(script, topic_path); + + COORDINATOR_T *coordinator = coordinator_init(); + + const UPDATE_SECURITY_STORE_PARAMS_T params = { + .on_update = on_security_store_updated, + .on_error = on_error, + .update_script = script, + .context = coordinator + }; + + printf("\nIsolating %s permissions from parent and default path permissions.\n", topic_path); + utils_print_script(script); + + update_security_store(session, params); + coordinator_wait(coordinator); + + + session_close(session, NULL); + session_free(session); + + script_free(script); + coordinator_free(coordinator); +} diff --git a/c/examples/server_configuration/security_control/remove_path_permissions.c b/c/examples/server_configuration/security_control/remove_path_permissions.c new file mode 100644 index 00000000..9a5b5553 --- /dev/null +++ b/c/examples/server_configuration/security_control/remove_path_permissions.c @@ -0,0 +1,116 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_security_store_updated( + SESSION_T *session, + const LIST_T *error_report, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + const char *topic_path = "my/topic/path"; + + printf("Original Security Store Settings for role CLIENT\n"); + utils_print_security_store(session, "CLIENT"); + + SET_T *set_permissions = set_new(2); + set_add(set_permissions, &SECURITY_PATH_PERMISSIONS_TABLE[PATH_PERMISSION_UPDATE_TOPIC]); + set_add(set_permissions, &SECURITY_PATH_PERMISSIONS_TABLE[PATH_PERMISSION_MODIFY_TOPIC]); + + SCRIPT_T *set_script = script_create(); + update_security_store_path_permissions( + set_script, "CLIENT", topic_path, set_permissions + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + const UPDATE_SECURITY_STORE_PARAMS_T set_params = { + .on_update = on_security_store_updated, + .on_error = on_error, + .update_script = set_script, + .context = coordinator + }; + + printf("\nAllowing Role CLIENT to update and modify %s.\n", topic_path); + utils_print_script(set_script); + + update_security_store(session, set_params); + coordinator_wait(coordinator); + + script_free(set_script); + set_free(set_permissions); + + printf("Security Store settings for role CLIENT after new path permissions for %s\n", topic_path); + utils_print_security_store(session, "CLIENT"); + + SCRIPT_T *remove_script = script_create(); + update_security_store_remove_path_permissions( + remove_script, "CLIENT", topic_path + ); + + const UPDATE_SECURITY_STORE_PARAMS_T remove_params = { + .on_update = on_security_store_updated, + .on_error = on_error, + .update_script = remove_script, + .context = coordinator + }; + + printf("\nRemoving path permissions for Role CLIENT at %s.\n", topic_path); + utils_print_script(remove_script); + + update_security_store(session, remove_params); + coordinator_wait(coordinator); + + script_free(remove_script); + + printf("Security Store settings for role CLIENT after removal of path permissions\n"); + utils_print_security_store(session, "CLIENT"); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); +} diff --git a/c/examples/server_configuration/security_control/restrict_role_edit_permissions.c b/c/examples/server_configuration/security_control/restrict_role_edit_permissions.c new file mode 100644 index 00000000..621ade45 --- /dev/null +++ b/c/examples/server_configuration/security_control/restrict_role_edit_permissions.c @@ -0,0 +1,85 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_security_store_updated( + SESSION_T *session, + const LIST_T *error_report, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + printf("Original Security Store Settings for role OPERATOR\n"); + utils_print_security_store(session, "OPERATOR"); + + SCRIPT_T *script = script_create(); + update_security_store_role_locked_by_principal( + script, "OPERATOR", "admin" + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + const UPDATE_SECURITY_STORE_PARAMS_T params = { + .on_update = on_security_store_updated, + .on_error = on_error, + .update_script = script, + .context = coordinator + }; + + utils_print_script(script); + update_security_store(session, params); + coordinator_wait(coordinator); + + script_free(script); + printf("\nOPERATOR role has been locked by admin principal.\n"); + + printf("New Security Store settings for role OPERATOR\n"); + utils_print_security_store(session, "OPERATOR"); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); +} diff --git a/c/examples/server_configuration/security_control/set_default_path_permissions.c b/c/examples/server_configuration/security_control/set_default_path_permissions.c new file mode 100644 index 00000000..03b4ec57 --- /dev/null +++ b/c/examples/server_configuration/security_control/set_default_path_permissions.c @@ -0,0 +1,95 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_security_store_updated( + SESSION_T *session, + const LIST_T *error_report, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + printf("Original Security Store Settings for role CLIENT\n"); + utils_print_security_store(session, "CLIENT"); + + SET_T *set_permissions = set_new_int(2); + set_add(set_permissions, &SECURITY_PATH_PERMISSIONS_TABLE[PATH_PERMISSION_UPDATE_TOPIC]); + set_add(set_permissions, &SECURITY_PATH_PERMISSIONS_TABLE[PATH_PERMISSION_MODIFY_TOPIC]); + + SCRIPT_T *script = script_create(); + update_security_store_default_path_permissions( + script, "CLIENT", set_permissions + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + const UPDATE_SECURITY_STORE_PARAMS_T params = { + .on_update = on_security_store_updated, + .on_error = on_error, + .update_script = script, + .context = coordinator + }; + + printf( + "\nAdding the following permissions to the default path permisions of Role CLIENT: " + "MODIFY_TOPIC and UPDATE_TOPIC.\n" + ); + utils_print_script(script); + + update_security_store(session, params); + coordinator_wait(coordinator); + + script_free(script); + set_free(set_permissions); + + printf("New Security Store settings for role CLIENT\n"); + utils_print_security_store(session, "CLIENT"); + + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); +} diff --git a/c/examples/server_configuration/security_control/set_default_roles_for_anonymous_sessions.c b/c/examples/server_configuration/security_control/set_default_roles_for_anonymous_sessions.c new file mode 100644 index 00000000..ddfe4b36 --- /dev/null +++ b/c/examples/server_configuration/security_control/set_default_roles_for_anonymous_sessions.c @@ -0,0 +1,90 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_security_store_updated( + SESSION_T *session, + const LIST_T *error_report, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + printf("Original Security Store Settings\n"); + utils_print_security_store(session, ""); + + LIST_T *list_anon_roles = list_create(); + list_append_last(list_anon_roles, "CLIENT"); + list_append_last(list_anon_roles, "AUTHENTICATION_HANDLER"); + + SCRIPT_T *script = script_create(); + update_security_store_anonymous_session_roles( + script, list_anon_roles + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + const UPDATE_SECURITY_STORE_PARAMS_T params = { + .on_update = on_security_store_updated, + .on_error = on_error, + .update_script = script, + .context = coordinator + }; + + utils_print_script(script); + update_security_store(session, params); + coordinator_wait(coordinator); + + script_free(script); + list_free(list_anon_roles, NULL); + printf("\nAll anonymous sessions now have AUTHENTICATION_HANDLER privileges.\n"); + + printf("New Security Store settings\n"); + utils_print_security_store(session, ""); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); +} diff --git a/c/examples/server_configuration/security_control/set_default_roles_for_named_sessions.c b/c/examples/server_configuration/security_control/set_default_roles_for_named_sessions.c new file mode 100644 index 00000000..238ab9c9 --- /dev/null +++ b/c/examples/server_configuration/security_control/set_default_roles_for_named_sessions.c @@ -0,0 +1,90 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_security_store_updated( + SESSION_T *session, + const LIST_T *error_report, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + printf("Original Security Store Settings\n"); + utils_print_security_store(session, ""); + + LIST_T *list_roles = list_create(); + list_append_last(list_roles, "ADMINISTRATOR"); + list_append_last(list_roles, "CLIENT"); + + SCRIPT_T *script = script_create(); + update_security_store_named_session_roles( + script, list_roles + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + const UPDATE_SECURITY_STORE_PARAMS_T params = { + .on_update = on_security_store_updated, + .on_error = on_error, + .update_script = script, + .context = coordinator + }; + + utils_print_script(script); + update_security_store(session, params); + coordinator_wait(coordinator); + + script_free(script); + list_free(list_roles, NULL); + printf("\nAll named sessions now have ADMINISTRATOR privileges.\n"); + + printf("New Security Store settings\n"); + utils_print_security_store(session, ""); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); +} diff --git a/c/examples/server_configuration/security_control/set_global_permissions.c b/c/examples/server_configuration/security_control/set_global_permissions.c new file mode 100644 index 00000000..4c5b20df --- /dev/null +++ b/c/examples/server_configuration/security_control/set_global_permissions.c @@ -0,0 +1,95 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_security_store_updated( + SESSION_T *session, + const LIST_T *error_report, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + printf("Original Security Store Settings for role CLIENT\n"); + utils_print_security_store(session, "CLIENT"); + + SET_T *set_global_permissions = set_new_int(2); + set_add(set_global_permissions, &SECURITY_GLOBAL_PERMISSIONS_TABLE[GLOBAL_PERMISSION_VIEW_SERVER]); + set_add(set_global_permissions, &SECURITY_GLOBAL_PERMISSIONS_TABLE[GLOBAL_PERMISSION_VIEW_SESSION]); + + SCRIPT_T *script = script_create(); + update_security_store_global_role_permissions( + script, "CLIENT", set_global_permissions + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + const UPDATE_SECURITY_STORE_PARAMS_T params = { + .on_update = on_security_store_updated, + .on_error = on_error, + .update_script = script, + .context = coordinator + }; + + printf( + "\nAdding the following permissions to the global permisions of Role CLIENT: " + "VIEW_SERVER and VIEW_SESSION.\n" + ); + utils_print_script(script); + + update_security_store(session, params); + coordinator_wait(coordinator); + + script_free(script); + set_free(set_global_permissions); + + printf("New Security Store settings for role CLIENT\n"); + utils_print_security_store(session, "CLIENT"); + + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); +} diff --git a/c/examples/server_configuration/security_control/set_path_permissions.c b/c/examples/server_configuration/security_control/set_path_permissions.c new file mode 100644 index 00000000..c87134ff --- /dev/null +++ b/c/examples/server_configuration/security_control/set_path_permissions.c @@ -0,0 +1,94 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_security_store_updated( + SESSION_T *session, + const LIST_T *error_report, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + const char *topic_path = "my/topic/path"; + + printf("Original Security Store Settings for role CLIENT\n"); + utils_print_security_store(session, "CLIENT"); + + SET_T *set_permissions = set_new(2); + set_add(set_permissions, &SECURITY_PATH_PERMISSIONS_TABLE[PATH_PERMISSION_UPDATE_TOPIC]); + set_add(set_permissions, &SECURITY_PATH_PERMISSIONS_TABLE[PATH_PERMISSION_MODIFY_TOPIC]); + + SCRIPT_T *script = script_create(); + update_security_store_path_permissions( + script, "CLIENT", topic_path, set_permissions + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + const UPDATE_SECURITY_STORE_PARAMS_T params = { + .on_update = on_security_store_updated, + .on_error = on_error, + .update_script = script, + .context = coordinator + }; + + printf("\nAllowing Role CLIENT to update and modify %s.\n", topic_path); + utils_print_script(script); + + update_security_store(session, params); + coordinator_wait(coordinator); + + script_free(script); + set_free(set_permissions); + + printf("New Security Store settings for role CLIENT\n"); + utils_print_security_store(session, "CLIENT"); + + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); +} diff --git a/c/examples/server_configuration/system_authentication_control/abstain_anonymous_connections.c b/c/examples/server_configuration/system_authentication_control/abstain_anonymous_connections.c new file mode 100644 index 00000000..9920c931 --- /dev/null +++ b/c/examples/server_configuration/system_authentication_control/abstain_anonymous_connections.c @@ -0,0 +1,142 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" +MUTEX_DEF + +static int on_system_authentication_store_updated( + SESSION_T *session, + const LIST_T *error_report, + void *context) +{ + MUTEX_BROADCAST + return HANDLER_SUCCESS; +} + +static int on_auth_handler_active( + SESSION_T *session, + const DIFFUSION_REGISTRATION_T *registration) +{ + MUTEX_BROADCAST + return HANDLER_SUCCESS; +} + +static int on_authenticate( + SESSION_T *session, + const char *principal, + const CREDENTIALS_T *credentials, + const HASH_T *session_properties, + const HASH_T *proposed_session_properties, + const DIFFUSION_AUTHENTICATOR_T *authenticator) +{ + if (strlen(principal) == 0) { + printf( + "Anonymous connection attempt detected.\n" + "Session establishment rejected.\n\n" + ); + diffusion_authenticator_deny(session, authenticator, NULL); + } + else { + diffusion_authenticator_allow(session, authenticator, NULL); + } + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + +static int on_auth_handler_error( + const DIFFUSION_ERROR_T *error) +{ + printf("On authentication handler error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + MUTEX_INIT + + SESSION_T *admin_session = utils_open_session(url, "admin", "password"); + SCRIPT_T *script = script_create(); + update_auth_store_abstain_anonymous_connections(script); + + const UPDATE_SYSTEM_AUTHENTICATION_STORE_PARAMS_T params = { + .on_update = on_system_authentication_store_updated, + .on_error = on_error, + .update_script = script + }; + + update_system_authentication_store(admin_session, params); + MUTEX_WAIT + script_free(script); + + SESSION_T *auth_handler_session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + DIFFUSION_AUTHENTICATION_HANDLER_T auth_handler = { + .handler_name = "after-system-handler", + .on_active = on_auth_handler_active, + .on_authenticate = on_authenticate, + .on_error = on_auth_handler_error + }; + + DIFFUSION_AUTHENTICATION_HANDLER_PARAMS_T auth_handler_params = { + .handler = &auth_handler, + .on_error = on_error + }; + + diffusion_set_authentication_handler(auth_handler_session, auth_handler_params); + MUTEX_WAIT + + CREDENTIALS_T *anonymous_credentials = + credentials_create_none(); + + DIFFUSION_ERROR_T *error = calloc(1, sizeof(DIFFUSION_ERROR_T)); + SESSION_T *anonymous_session = session_create( + url, "", anonymous_credentials, NULL, NULL, error + ); + printf("Error while attempting to establish anonymous session:\n"); + printf("\t%d: %s\n", error->code, error->message); + diffusion_error_free(error); + + + session_close(admin_session, NULL); + session_free(admin_session); + + session_close(auth_handler_session, NULL); + session_free(auth_handler_session); + + + credentials_free(anonymous_credentials); + MUTEX_TERMINATE +} diff --git a/c/examples/server_configuration/system_authentication_control/add_locked_principal.c b/c/examples/server_configuration/system_authentication_control/add_locked_principal.c new file mode 100644 index 00000000..1f98f025 --- /dev/null +++ b/c/examples/server_configuration/system_authentication_control/add_locked_principal.c @@ -0,0 +1,82 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_system_authentication_store_updated( + SESSION_T *session, + const LIST_T *error_report, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + LIST_T *list_roles = list_create(); + list_append_last(list_roles, "ADMINISTRATOR"); + + SCRIPT_T *script = script_create(); + update_auth_store_add_locked_principal( + script, "super_user", "password12345", list_roles, "admin" + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + const UPDATE_SYSTEM_AUTHENTICATION_STORE_PARAMS_T params = { + .on_update = on_system_authentication_store_updated, + .on_error = on_error, + .update_script = script, + .context = coordinator + }; + + update_system_authentication_store(session, params); + coordinator_wait(coordinator); + + script_free(script); + list_free(list_roles, NULL); + + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); +} diff --git a/c/examples/server_configuration/system_authentication_control/add_principal.c b/c/examples/server_configuration/system_authentication_control/add_principal.c new file mode 100644 index 00000000..6eb61082 --- /dev/null +++ b/c/examples/server_configuration/system_authentication_control/add_principal.c @@ -0,0 +1,82 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_system_authentication_store_updated( + SESSION_T *session, + const LIST_T *error_report, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + LIST_T *list_roles = list_create(); + list_append_last(list_roles, "ADMINISTRATOR"); + + SCRIPT_T *script = script_create(); + update_auth_store_add_principal( + script, "super_user", "password12345", list_roles + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + const UPDATE_SYSTEM_AUTHENTICATION_STORE_PARAMS_T params = { + .on_update = on_system_authentication_store_updated, + .on_error = on_error, + .update_script = script, + .context = coordinator + }; + + update_system_authentication_store(session, params); + coordinator_wait(coordinator); + + script_free(script); + list_free(list_roles, NULL); + + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); +} diff --git a/c/examples/server_configuration/system_authentication_control/allow_anonymous_connections.c b/c/examples/server_configuration/system_authentication_control/allow_anonymous_connections.c new file mode 100644 index 00000000..1410c119 --- /dev/null +++ b/c/examples/server_configuration/system_authentication_control/allow_anonymous_connections.c @@ -0,0 +1,85 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_system_authentication_store_updated( + SESSION_T *session, + const LIST_T *error_report, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + LIST_T *list_anonymous_roles = list_create(); + list_append_last(list_anonymous_roles, "CLIENT"); + + SCRIPT_T *script = script_create(); + update_auth_store_allow_anonymous_connections(script, list_anonymous_roles); + + COORDINATOR_T *coordinator = coordinator_init(); + + const UPDATE_SYSTEM_AUTHENTICATION_STORE_PARAMS_T params = { + .on_update = on_system_authentication_store_updated, + .on_error = on_error, + .update_script = script, + .context = coordinator + }; + + update_system_authentication_store(session, params); + coordinator_wait(coordinator); + + script_free(script); + list_free(list_anonymous_roles, NULL); + + SESSION_T *anonymous_session = utils_open_session(url, "", NULL); + printf(" Anonymous session established.\n"); + + session_close(session, NULL); + session_free(session); + + session_close(anonymous_session, NULL); + session_free(anonymous_session); + + coordinator_free(coordinator); + } diff --git a/c/examples/server_configuration/system_authentication_control/assign_roles.c b/c/examples/server_configuration/system_authentication_control/assign_roles.c new file mode 100644 index 00000000..d20dfd7b --- /dev/null +++ b/c/examples/server_configuration/system_authentication_control/assign_roles.c @@ -0,0 +1,103 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_system_authentication_store_updated( + SESSION_T *session, + const LIST_T *error_report, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + LIST_T *list_original_roles = list_create(); + list_append_last(list_original_roles, "CLIENT"); + + SCRIPT_T *add_script = script_create(); + update_auth_store_add_principal( + add_script, "super_user", "password12345", list_original_roles + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + const UPDATE_SYSTEM_AUTHENTICATION_STORE_PARAMS_T add_params = { + .on_update = on_system_authentication_store_updated, + .on_error = on_error, + .update_script = add_script, + .context = coordinator + }; + + update_system_authentication_store(session, add_params); + coordinator_wait(coordinator); + + script_free(add_script); + list_free(list_original_roles, NULL); + + LIST_T *list_new_roles = list_create(); + list_append_last(list_new_roles, "ADMINISTRATOR"); + + SCRIPT_T *assign_script = script_create(); + update_auth_store_assign_roles( + assign_script, "super_user", list_new_roles + ); + + const UPDATE_SYSTEM_AUTHENTICATION_STORE_PARAMS_T assign_params = { + .on_update = on_system_authentication_store_updated, + .on_error = on_error, + .update_script = assign_script, + .context = coordinator + }; + + update_system_authentication_store(session, assign_params); + coordinator_wait(coordinator); + + script_free(assign_script); + list_free(list_new_roles, NULL); + + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); +} diff --git a/c/examples/server_configuration/system_authentication_control/change_password.c b/c/examples/server_configuration/system_authentication_control/change_password.c new file mode 100644 index 00000000..a84d372e --- /dev/null +++ b/c/examples/server_configuration/system_authentication_control/change_password.c @@ -0,0 +1,94 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_system_authentication_store_updated( + SESSION_T *session, + const LIST_T *error_report, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + SESSION_T *session = utils_open_session(url, "admin", "password"); + + LIST_T *list_original_roles = list_create(); + list_append_last(list_original_roles, "CLIENT"); + + SCRIPT_T *add_script = script_create(); + update_auth_store_add_principal( + add_script, "super_user", "password12345", list_original_roles + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + const UPDATE_SYSTEM_AUTHENTICATION_STORE_PARAMS_T add_params = { + .on_update = on_system_authentication_store_updated, + .on_error = on_error, + .update_script = add_script, + .context = coordinator + }; + update_system_authentication_store(session, add_params); + coordinator_wait(coordinator); + + script_free(add_script); + list_free(list_original_roles, NULL); + + SCRIPT_T *change_password_script = script_create(); + update_auth_store_set_password( + change_password_script, "super_user", "hunter2" + ); + + const UPDATE_SYSTEM_AUTHENTICATION_STORE_PARAMS_T change_password_params = { + .on_update = on_system_authentication_store_updated, + .on_error = on_error, + .update_script = change_password_script, + .context = coordinator + }; + update_system_authentication_store(session, change_password_params); + coordinator_wait(coordinator); + + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + script_free(change_password_script); +} diff --git a/c/examples/server_configuration/system_authentication_control/deny_anonymous_connections.c b/c/examples/server_configuration/system_authentication_control/deny_anonymous_connections.c new file mode 100644 index 00000000..55d65795 --- /dev/null +++ b/c/examples/server_configuration/system_authentication_control/deny_anonymous_connections.c @@ -0,0 +1,89 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_system_authentication_store_updated( + SESSION_T *session, + const LIST_T *error_report, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + SCRIPT_T *script = script_create(); + update_auth_store_deny_anonymous_connections(script); + + COORDINATOR_T *coordinator = coordinator_init(); + + const UPDATE_SYSTEM_AUTHENTICATION_STORE_PARAMS_T params = { + .on_update = on_system_authentication_store_updated, + .on_error = on_error, + .update_script = script, + .context = coordinator + }; + + update_system_authentication_store(session, params); + coordinator_wait(coordinator); + + coordinator_free(coordinator); + script_free(script); + + CREDENTIALS_T *anonymous_credentials = + credentials_create_none(); + + DIFFUSION_ERROR_T *error = calloc(1, sizeof(DIFFUSION_ERROR_T)); + SESSION_T *anonymous_session = session_create( + url, "", anonymous_credentials, NULL, NULL, error + ); + printf("Error while attempting to establish anonymous session:\n"); + printf("\t%d: %s\n", error->code, error->message); + diffusion_error_free(error); + + + session_close(session, NULL); + session_free(session); + + + credentials_free(anonymous_credentials); + } diff --git a/c/examples/server_configuration/system_authentication_control/ignore_client_proposed_property.c b/c/examples/server_configuration/system_authentication_control/ignore_client_proposed_property.c new file mode 100644 index 00000000..08001f49 --- /dev/null +++ b/c/examples/server_configuration/system_authentication_control/ignore_client_proposed_property.c @@ -0,0 +1,106 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_system_authentication_store_updated( + SESSION_T *session, + const LIST_T *error_report, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *admin_session = utils_open_session(url, "admin", "password"); + + SCRIPT_T *script = script_create(); + update_auth_store_trust_client_proposed_property_matches( + script, "Flintstone", ".*_Flintstone" + ); + update_auth_store_ignore_client_proposed_property( + script, "Rubble" + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + const UPDATE_SYSTEM_AUTHENTICATION_STORE_PARAMS_T params = { + .on_update = on_system_authentication_store_updated, + .on_error = on_error, + .update_script = script, + .context = coordinator + }; + + update_system_authentication_store(admin_session, params); + coordinator_wait(coordinator); + + coordinator_free(coordinator); + script_free(script); + + DIFFUSION_SESSION_FACTORY_T *session_factory = diffusion_session_factory_init(); + diffusion_session_factory_principal(session_factory, principal); + diffusion_session_factory_credentials(session_factory, credentials); + + // Establishing session with invalid values for the session property + // Due to the invalid value, the session property will not appear for the session + diffusion_session_factory_property(session_factory, "Rubble", "Barney_Rubble"); + + SESSION_T *invalid_value_session = session_create_with_session_factory(session_factory, url); + + utils_print_session_properties(admin_session, invalid_value_session->id, NULL); + + session_close(invalid_value_session, NULL); + session_free(invalid_value_session); + + // Establishing session with valid value for the session property + diffusion_session_factory_property(session_factory, "Flintstone", "Fred_Flintstone"); + + SESSION_T *valid_value_session = session_create_with_session_factory(session_factory, url); + + utils_print_session_properties(admin_session, valid_value_session->id, NULL); + + session_close(valid_value_session, NULL); + session_free(valid_value_session); + + session_close(admin_session, NULL); + session_free(admin_session); + + diffusion_session_factory_free(session_factory); +} diff --git a/c/examples/server_configuration/system_authentication_control/remove_principal.c b/c/examples/server_configuration/system_authentication_control/remove_principal.c new file mode 100644 index 00000000..5979b1f0 --- /dev/null +++ b/c/examples/server_configuration/system_authentication_control/remove_principal.c @@ -0,0 +1,95 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_system_authentication_store_updated( + SESSION_T *session, + const LIST_T *error_report, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + LIST_T *list_roles = list_create(); + list_append_last(list_roles, "ADMINISTRATOR"); + + SCRIPT_T *add_script = script_create(); + update_auth_store_add_principal( + add_script, "super_user", "password12345", list_roles + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + const UPDATE_SYSTEM_AUTHENTICATION_STORE_PARAMS_T add_params = { + .on_update = on_system_authentication_store_updated, + .on_error = on_error, + .update_script = add_script, + .context = coordinator + }; + + update_system_authentication_store(session, add_params); + coordinator_wait(coordinator); + + script_free(add_script); + list_free(list_roles, NULL); + + SCRIPT_T *remove_script = script_create(); + update_auth_store_remove_principal(remove_script, "super_user"); + + const UPDATE_SYSTEM_AUTHENTICATION_STORE_PARAMS_T remove_params = { + .on_update = on_system_authentication_store_updated, + .on_error = on_error, + .update_script = remove_script, + .context = coordinator + }; + + update_system_authentication_store(session, remove_params); + coordinator_wait(coordinator); + + script_free(remove_script); + coordinator_free(coordinator); + + session_close(session, NULL); + session_free(session); +} diff --git a/c/examples/server_configuration/system_authentication_control/trust_client_proposed_property_in.c b/c/examples/server_configuration/system_authentication_control/trust_client_proposed_property_in.c new file mode 100644 index 00000000..d79780f8 --- /dev/null +++ b/c/examples/server_configuration/system_authentication_control/trust_client_proposed_property_in.c @@ -0,0 +1,110 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_system_authentication_store_updated( + SESSION_T *session, + const LIST_T *error_report, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *admin_session = utils_open_session(url, "admin", "password"); + + SET_T *set_allowed_values = set_new_string(3); + set_add(set_allowed_values, "Fred"); + set_add(set_allowed_values, "Wilma"); + set_add(set_allowed_values, "Pebbles"); + + SCRIPT_T *script = script_create(); + update_auth_store_trust_client_proposed_property_in( + script, "Flintstone", set_allowed_values + ); + set_free(set_allowed_values); + + COORDINATOR_T *coordinator = coordinator_init(); + + const UPDATE_SYSTEM_AUTHENTICATION_STORE_PARAMS_T params = { + .on_update = on_system_authentication_store_updated, + .on_error = on_error, + .update_script = script, + .context = coordinator + }; + + update_system_authentication_store(admin_session, params); + coordinator_wait(coordinator); + + coordinator_free(coordinator); + script_free(script); + + DIFFUSION_SESSION_FACTORY_T *session_factory = diffusion_session_factory_init(); + diffusion_session_factory_principal(session_factory, principal); + diffusion_session_factory_credentials(session_factory, credentials); + + // Establishing session with invalid values for the session property + // Due to the invalid value, the session property will not appear for the session + diffusion_session_factory_property(session_factory, "Flintstone", "Barney"); + + SESSION_T *invalid_value_session = session_create_with_session_factory(session_factory, url); + + utils_print_session_properties(admin_session, invalid_value_session->id, NULL); + + session_close(invalid_value_session, NULL); + session_free(invalid_value_session); + + // Establishing session with valid value for the session property + diffusion_session_factory_property(session_factory, "Flintstone", "Fred"); + + SESSION_T *valid_value_session = session_create_with_session_factory(session_factory, url); + + utils_print_session_properties(admin_session, valid_value_session->id, NULL); + + session_close(valid_value_session, NULL); + session_free(valid_value_session); + + + session_close(admin_session, NULL); + session_free(admin_session); + + diffusion_session_factory_free(session_factory); +} diff --git a/c/examples/server_configuration/system_authentication_control/trust_client_proposed_property_matches.c b/c/examples/server_configuration/system_authentication_control/trust_client_proposed_property_matches.c new file mode 100644 index 00000000..0a7551e6 --- /dev/null +++ b/c/examples/server_configuration/system_authentication_control/trust_client_proposed_property_matches.c @@ -0,0 +1,104 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_system_authentication_store_updated( + SESSION_T *session, + const LIST_T *error_report, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *admin_session = utils_open_session(url, "admin", "password"); + + SCRIPT_T *script = script_create(); + update_auth_store_trust_client_proposed_property_matches( + script, "Flintstone", ".*_Flintstone" + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + const UPDATE_SYSTEM_AUTHENTICATION_STORE_PARAMS_T params = { + .on_update = on_system_authentication_store_updated, + .on_error = on_error, + .update_script = script, + .context = coordinator + }; + + update_system_authentication_store(admin_session, params); + coordinator_wait(coordinator); + + coordinator_free(coordinator); + script_free(script); + + DIFFUSION_SESSION_FACTORY_T *session_factory = diffusion_session_factory_init(); + diffusion_session_factory_principal(session_factory, principal); + diffusion_session_factory_credentials(session_factory, credentials); + + // Establishing session with invalid values for the session property + // Due to the invalid value, the session property will not appear for the session + diffusion_session_factory_property(session_factory, "Flintstone", "Barney_Rubble"); + + SESSION_T *invalid_value_session = session_create_with_session_factory(session_factory, url); + + utils_print_session_properties(admin_session, invalid_value_session->id, NULL); + + session_close(invalid_value_session, NULL); + session_free(invalid_value_session); + + // Establishing session with valid value for the session property + diffusion_session_factory_property(session_factory, "Flintstone", "Fred_Flintstone"); + + SESSION_T *valid_value_session = session_create_with_session_factory(session_factory, url); + + utils_print_session_properties(admin_session, valid_value_session->id, NULL); + + session_close(valid_value_session, NULL); + session_free(valid_value_session); + + + session_close(admin_session, NULL); + session_free(admin_session); + + diffusion_session_factory_free(session_factory); +} diff --git a/c/examples/server_configuration/system_authentication_control/verify_password.c b/c/examples/server_configuration/system_authentication_control/verify_password.c new file mode 100644 index 00000000..bdeb8998 --- /dev/null +++ b/c/examples/server_configuration/system_authentication_control/verify_password.c @@ -0,0 +1,123 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_system_authentication_store_updated( + SESSION_T *session, + const LIST_T *error_report, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + SESSION_T *admin_session = utils_open_session(url, "admin", "password"); + + // Verify with current password + // And set new password for admin principal + SCRIPT_T *script = script_create(); + update_auth_store_verify_password( + script, "control", "password" + ); + update_auth_store_set_password( + script, "control", "12345" + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + const UPDATE_SYSTEM_AUTHENTICATION_STORE_PARAMS_T params = { + .on_update = on_system_authentication_store_updated, + .on_error = on_error, + .update_script = script, + .context = coordinator + }; + + update_system_authentication_store(admin_session, params); + coordinator_wait(coordinator); + + script_free(script); + + // Login with the new password + SESSION_T *new_control_session = utils_open_session(url, "control", "12345"); + + // Attempt to verify with invalid password + // And set new password for admin principal + + SCRIPT_T *invalid_verification_script = script_create(); + update_auth_store_verify_password( + invalid_verification_script, "control", "this_is_not_the_right_password" + ); + update_auth_store_set_password( + invalid_verification_script, "control", "new_password" + ); + + const UPDATE_SYSTEM_AUTHENTICATION_STORE_PARAMS_T invalid_verification_params = { + .on_update = on_system_authentication_store_updated, + .on_error = on_error, + .update_script = invalid_verification_script, + .context = coordinator + }; + + update_system_authentication_store(admin_session, invalid_verification_params); + coordinator_wait(coordinator); + + script_free(invalid_verification_script); + + session_close(new_control_session, NULL); + session_free(new_control_session); + + // Attempt to login with new password + CREDENTIALS_T *new_invalid_control_credentials = + credentials_create_password("new_password"); + + DIFFUSION_ERROR_T *error = calloc(1, sizeof(DIFFUSION_ERROR_T)); + SESSION_T *new_invalid_control_session = session_create( + url, "control", new_invalid_control_credentials, NULL, NULL, error + ); + printf("Error while attempting to establish session:\n"); + printf("\t%d: %s\n", error->code, error->message); + diffusion_error_free(error); + credentials_free(new_invalid_control_credentials); + + + session_close(admin_session, NULL); + session_free(admin_session); + + coordinator_free(coordinator); +} diff --git a/c/examples/session_management/authentication_control.c b/c/examples/session_management/authentication_control.c new file mode 100644 index 00000000..8e8d4cb0 --- /dev/null +++ b/c/examples/session_management/authentication_control.c @@ -0,0 +1,134 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" +MUTEX_DEF + +static int on_auth_handler_active( + SESSION_T *session, + const DIFFUSION_REGISTRATION_T *registration) +{ + MUTEX_BROADCAST + return HANDLER_SUCCESS; +} + +static int on_authenticate( + SESSION_T *session, + const char *principal, + const CREDENTIALS_T *credentials, + const HASH_T *session_properties, + const HASH_T *proposed_session_properties, + const DIFFUSION_AUTHENTICATOR_T *authenticator) +{ + if (strlen(principal) == 0) { + printf( + "Anonymous connection attempt detected.\n" + "Session establishment rejected.\n\n" + ); + diffusion_authenticator_deny(session, authenticator, NULL); + } + else if(utils_string_starts_with("diffusion_", principal)) { + printf( + "Principal begins with diffusion_ prefix.\n" + "Session establishment accepted.\n\n" + ); + diffusion_authenticator_allow(session, authenticator, NULL); + } + else { + printf( + "Principal does not begin with diffusion_ prefix.\n" + "Session establishment rejected.\n\n" + ); + diffusion_authenticator_deny(session, authenticator, NULL); + } + MUTEX_BROADCAST + return HANDLER_SUCCESS; +} + +static int on_auth_handler_error( + const DIFFUSION_ERROR_T *error) +{ + printf("On authentication handler error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + MUTEX_INIT + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + DIFFUSION_AUTHENTICATION_HANDLER_T handler = { + .handler_name = "before-system-handler", + .on_active = on_auth_handler_active, + .on_authenticate = on_authenticate, + .on_error = on_auth_handler_error + }; + + DIFFUSION_AUTHENTICATION_HANDLER_PARAMS_T params = { + .handler = &handler + }; + + diffusion_set_authentication_handler(session, params); + MUTEX_WAIT + + CREDENTIALS_T *control_credentials = + credentials_create_password("password"); + + SESSION_T *control_session = session_create( + url, "control", control_credentials, NULL, NULL, NULL + ); + MUTEX_WAIT + + CREDENTIALS_T *anonymous_credentials = + credentials_create_none(); + + SESSION_T *anonymous_session = session_create( + url, "", anonymous_credentials, NULL, NULL, NULL + ); + MUTEX_WAIT + + CREDENTIALS_T *diffusion_control_credentials = + credentials_create_password("password"); + + SESSION_T *diffusion_control_session = session_create( + url, "diffusion_control", diffusion_control_credentials, NULL, NULL, NULL + ); + MUTEX_WAIT + + session_close(diffusion_control_session, NULL); + session_free(diffusion_control_session); + + session_close(session, NULL); + session_free(session); + + credentials_free(control_credentials); + credentials_free(anonymous_credentials); + credentials_free(diffusion_control_credentials); + MUTEX_TERMINATE +} \ No newline at end of file diff --git a/c/examples/session_management/subscription_control.c b/c/examples/session_management/subscription_control.c new file mode 100644 index 00000000..4a32aee9 --- /dev/null +++ b/c/examples/session_management/subscription_control.c @@ -0,0 +1,116 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" +MUTEX_DEF + +SESSION_T *g_control_session; + +static int on_listener_registered(SESSION_T *session, void *context) +{ + MUTEX_BROADCAST + return HANDLER_SUCCESS; +} + +static int on_complete(SESSION_T *session, void *context) +{ + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + +static int on_session_open( + SESSION_T *session, + const SESSION_PROPERTIES_EVENT_T *request, + void *context) +{ + char *principal = hash_get(request->properties, "$Principal"); + + if (strcmp(principal, "client") != 0) { + // Not the right type of principal, nothing to do. + return HANDLER_SUCCESS; + } + + SUBSCRIPTION_CONTROL_PARAMS_T params = { + .on_complete = on_complete, + .on_error = on_error, + .session_id = request->session_id, + .topic_selector = "?my/topic/path//" + }; + subscribe_client(session, params); + + // Sleep for a bit to see the notifications + sleep(5); + + unsubscribe_client(session, params); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + MUTEX_INIT + + g_control_session = utils_open_session(url, "admin", "password"); + + utils_create_string_topic( + g_control_session, "my/topic/path/hello", "Hello World!" + ); + + SET_T *required_properties = set_new_string(1); + set_add(required_properties, PROPERTIES_SELECTOR_ALL_FIXED_PROPERTIES); + + SESSION_PROPERTIES_REGISTRATION_PARAMS_T params = { + .on_registered = on_listener_registered, + .on_session_open = on_session_open, + .required_properties = required_properties + }; + session_properties_listener_register(g_control_session, params); + MUTEX_WAIT + + SESSION_T *session = utils_open_session(url, "client", "password"); + + VALUE_STREAM_T *value_stream_ptr = + utils_create_value_stream(session, "?.*//", DATATYPE_STRING); + + // Sleep for a bit to see the notifications + sleep(10); + + session_close(g_control_session, NULL); + session_free(g_control_session); + + session_close(session, NULL); + session_free(session); + + set_free(required_properties); + free(value_stream_ptr); + MUTEX_TERMINATE +} \ No newline at end of file diff --git a/c/examples/time_series/append_user_supplied_timestamp.c b/c/examples/time_series/append_user_supplied_timestamp.c new file mode 100644 index 00000000..d530d4b8 --- /dev/null +++ b/c/examples/time_series/append_user_supplied_timestamp.c @@ -0,0 +1,89 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_append( + const DIFFUSION_TIME_SERIES_EVENT_METADATA_T *event_metadata, + void *context) +{ + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/time/series/topic/path/user/supplied"; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + HASH_T *properties = hash_new(5); + hash_add(properties, DIFFUSION_TIME_SERIES_EVENT_VALUE_TYPE, "double"); + hash_add(properties, DIFFUSION_TIME_SERIES_RETAINED_RANGE, "limit 15 last 10s"); + hash_add(properties, DIFFUSION_TIME_SERIES_SUBSCRIPTION_RANGE, "limit 3"); + + utils_create_topic_with_properties( + session, + topic_path, + TOPIC_TYPE_TIME_SERIES, + DATATYPE_DOUBLE, + NULL, + properties + ); + hash_free(properties, NULL, NULL); + + COORDINATOR_T *coordinator = coordinator_init(); + + for (int i = 0; i < 25; i++) { + double random_value = utils_random_double(); + + long user_supplied_timestamp = 1000000 + i; + + BUF_T *value = buf_create(); + write_diffusion_double_value(random_value, value); + + DIFFUSION_TIME_SERIES_TIMESTAMP_APPEND_PARAMS_T params = { + .on_append = on_append, + .topic_path = topic_path, + .datatype = DATATYPE_DOUBLE, + .value = value, + .timestamp = user_supplied_timestamp, + .context = coordinator + }; + + diffusion_time_series_timestamp_append(session, params, NULL); + coordinator_wait(coordinator); + buf_free(value); + } + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + } \ No newline at end of file diff --git a/c/examples/time_series/append_value.c b/c/examples/time_series/append_value.c new file mode 100644 index 00000000..4af90cc8 --- /dev/null +++ b/c/examples/time_series/append_value.c @@ -0,0 +1,86 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_append( + const DIFFUSION_TIME_SERIES_EVENT_METADATA_T *event_metadata, + void *context) +{ + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/time/series/topic/path"; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + HASH_T *properties = hash_new(5); + hash_add(properties, DIFFUSION_TIME_SERIES_EVENT_VALUE_TYPE, "double"); + hash_add(properties, DIFFUSION_TIME_SERIES_RETAINED_RANGE, "limit 15 last 10s"); + hash_add(properties, DIFFUSION_TIME_SERIES_SUBSCRIPTION_RANGE, "limit 3"); + + utils_create_topic_with_properties( + session, + topic_path, + TOPIC_TYPE_TIME_SERIES, + DATATYPE_DOUBLE, + NULL, + properties + ); + hash_free(properties, NULL, NULL); + + COORDINATOR_T *coordinator = coordinator_init(); + + for (int i = 0; i < 25; i++) { + double random_value = utils_random_double(); + + BUF_T *value = buf_create(); + write_diffusion_double_value(random_value, value); + + DIFFUSION_TIME_SERIES_APPEND_PARAMS_T params = { + .on_append = on_append, + .topic_path = topic_path, + .datatype = DATATYPE_DOUBLE, + .value = value, + .context = coordinator + }; + + diffusion_time_series_append(session, params, NULL); + coordinator_wait(coordinator); + buf_free(value); + } + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + } \ No newline at end of file diff --git a/c/examples/time_series/append_value_via_update_stream.c b/c/examples/time_series/append_value_via_update_stream.c new file mode 100644 index 00000000..2ebf44ce --- /dev/null +++ b/c/examples/time_series/append_value_via_update_stream.c @@ -0,0 +1,89 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_append( + const DIFFUSION_TIME_SERIES_EVENT_METADATA_T *event_metadata, + void *context) +{ + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/time/series/topic/path"; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + HASH_T *properties = hash_new(5); + hash_add(properties, DIFFUSION_TIME_SERIES_EVENT_VALUE_TYPE, "double"); + hash_add(properties, DIFFUSION_TIME_SERIES_RETAINED_RANGE, "limit 15 last 10s"); + hash_add(properties, DIFFUSION_TIME_SERIES_SUBSCRIPTION_RANGE, "limit 3"); + + utils_create_topic_with_properties( + session, + topic_path, + TOPIC_TYPE_TIME_SERIES, + DATATYPE_DOUBLE, + NULL, + properties + ); + hash_free(properties, NULL, NULL); + + COORDINATOR_T *coordinator = coordinator_init(); + + for (int i = 0; i < 25; i++) { + double random_value = utils_random_double(); + + long user_supplied_timestamp = 1000000 + i; + + BUF_T *value = buf_create(); + write_diffusion_double_value(random_value, value); + + DIFFUSION_TIME_SERIES_TIMESTAMP_APPEND_PARAMS_T params = { + .on_append = on_append, + .topic_path = topic_path, + .datatype = DATATYPE_DOUBLE, + .value = value, + .timestamp = user_supplied_timestamp, + .context = coordinator + }; + + diffusion_time_series_timestamp_append(session, params, NULL); + coordinator_wait(coordinator); + buf_free(value); + } + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + } \ No newline at end of file diff --git a/c/examples/time_series/create_topic.c b/c/examples/time_series/create_topic.c new file mode 100644 index 00000000..4c1171d1 --- /dev/null +++ b/c/examples/time_series/create_topic.c @@ -0,0 +1,92 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_added_with_specification( + SESSION_T *session, + TOPIC_ADD_RESULT_CODE result_code, + void *context) +{ + if (result_code == TOPIC_ADD_RESULT_CREATED) { + printf("Topic has been created.\n"); + } + else if (result_code == TOPIC_ADD_RESULT_EXISTS) { + printf("Topic already exists.\n"); + } + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_topic_add_failed_with_specification( + SESSION_T *session, + TOPIC_ADD_FAIL_RESULT_CODE result_code, + const DIFFUSION_ERROR_T *error, + void *context) +{ + printf("Topic creation failed: %d %d %s\n", result_code, error->code, error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/time/series/topic/path"; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + HASH_T *properties = hash_new(5); + hash_add(properties, DIFFUSION_TIME_SERIES_EVENT_VALUE_TYPE, "double"); + hash_add(properties, DIFFUSION_TIME_SERIES_RETAINED_RANGE, "limit 15 last 10s"); + hash_add(properties, DIFFUSION_TIME_SERIES_SUBSCRIPTION_RANGE, "limit 3"); + + TOPIC_SPECIFICATION_T *topic_specification = + topic_specification_init_with_properties(TOPIC_TYPE_TIME_SERIES, properties); + + COORDINATOR_T *coordinator = coordinator_init(); + + ADD_TOPIC_CALLBACK_T callback = { + .on_topic_added_with_specification = on_topic_added_with_specification, + .on_topic_add_failed_with_specification = on_topic_add_failed_with_specification, + .context = coordinator + }; + + add_topic_from_specification( + session, topic_path, topic_specification, callback + ); + coordinator_wait(coordinator); + + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + topic_specification_free(topic_specification); + hash_free(properties, NULL, NULL); + } \ No newline at end of file diff --git a/c/examples/time_series/edit_value.c b/c/examples/time_series/edit_value.c new file mode 100644 index 00000000..99e42410 --- /dev/null +++ b/c/examples/time_series/edit_value.c @@ -0,0 +1,107 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_append( + const DIFFUSION_TIME_SERIES_EVENT_METADATA_T *event_metadata, + void *context) +{ + return HANDLER_SUCCESS; +} + +static int on_edit( + const DIFFUSION_TIME_SERIES_EVENT_METADATA_T *event_metadata, + void *context) +{ + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/time/series/topic/path"; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + HASH_T *properties = hash_new(5); + hash_add(properties, DIFFUSION_TIME_SERIES_EVENT_VALUE_TYPE, "double"); + hash_add(properties, DIFFUSION_TIME_SERIES_RETAINED_RANGE, "limit 15 last 10s"); + hash_add(properties, DIFFUSION_TIME_SERIES_SUBSCRIPTION_RANGE, "limit 3"); + + utils_create_topic_with_properties( + session, + topic_path, + TOPIC_TYPE_TIME_SERIES, + DATATYPE_DOUBLE, + NULL, + properties + ); + hash_free(properties, NULL, NULL); + + COORDINATOR_T *coordinator = coordinator_init(); + + for (int i = 0; i < 25; i++) { + double random_value = utils_random_double(); + + BUF_T *value = buf_create(); + write_diffusion_double_value(random_value, value); + + DIFFUSION_TIME_SERIES_APPEND_PARAMS_T params = { + .on_append = on_append, + .topic_path = topic_path, + .datatype = DATATYPE_DOUBLE, + .value = value, + .context = coordinator + }; + + diffusion_time_series_append(session, params, NULL); + coordinator_wait(coordinator); + buf_free(value); + } + + BUF_T *edit_value = buf_create(); + write_diffusion_double_value(3.14, edit_value); + DIFFUSION_TIME_SERIES_EDIT_PARAMS_T edit_params = { + .on_edit = on_edit, + .original_sequence = 20, + .topic_path = topic_path, + .datatype = DATATYPE_DOUBLE, + .value = edit_value, + .context = coordinator + }; + diffusion_time_series_edit(session, edit_params, NULL); + coordinator_wait(coordinator); + buf_free(edit_value); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + } \ No newline at end of file diff --git a/c/examples/time_series/range_query.c b/c/examples/time_series/range_query.c new file mode 100644 index 00000000..62ae92e5 --- /dev/null +++ b/c/examples/time_series/range_query.c @@ -0,0 +1,155 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_append( + const DIFFUSION_TIME_SERIES_EVENT_METADATA_T *event_metadata, + void *context) +{ + return HANDLER_SUCCESS; +} + +static int on_edit( + const DIFFUSION_TIME_SERIES_EVENT_METADATA_T *event_metadata, + void *context) +{ + return HANDLER_SUCCESS; +} + +static int on_query_result( + const DIFFUSION_TIME_SERIES_QUERY_RESULT_T *query_result, + void *context) +{ + LIST_T *events = diffusion_time_series_query_result_get_events(query_result); + int size = diffusion_time_series_query_result_get_selected_count(query_result); + + for(int i = 0; i < size; i++) { + DIFFUSION_TIME_SERIES_EVENT_T *event = list_get_data_indexed(events, i); + + long sequence = diffusion_time_series_event_get_sequence(event); + long timestamp = diffusion_time_series_event_get_timestamp(event); + DIFFUSION_VALUE_T *value = diffusion_time_series_event_get_value(event); + + double double_value; + DIFFUSION_API_ERROR error; + bool value_converted = read_diffusion_double_value(value, &double_value, &error); + if (value_converted == false) { + printf("Error while reading value %d: %d %s\n", i, get_diffusion_api_error_code(error), get_diffusion_api_error_description(error)); + break; + } + + printf("\t%ld (%ld): %g\n", sequence, timestamp, double_value); + + diffusion_value_free(value); + } + coordinator_broadcast((COORDINATOR_T *) context); + list_free(events, (void (*)(void *))diffusion_time_series_event_free); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/time/series/topic/path"; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + HASH_T *properties = hash_new(5); + hash_add(properties, DIFFUSION_TIME_SERIES_EVENT_VALUE_TYPE, "double"); + hash_add(properties, DIFFUSION_TIME_SERIES_RETAINED_RANGE, "limit 50 last 120s"); + hash_add(properties, DIFFUSION_TIME_SERIES_SUBSCRIPTION_RANGE, "limit 3"); + + utils_create_topic_with_properties( + session, + topic_path, + TOPIC_TYPE_TIME_SERIES, + DATATYPE_DOUBLE, + NULL, + properties + ); + hash_free(properties, NULL, NULL); + + COORDINATOR_T *coordinator = coordinator_init(); + + for (int i = 0; i < 25; i++) { + double random_value = utils_random_double(); + + BUF_T *value = buf_create(); + write_diffusion_double_value(random_value, value); + + DIFFUSION_TIME_SERIES_APPEND_PARAMS_T params = { + .on_append = on_append, + .topic_path = topic_path, + .datatype = DATATYPE_DOUBLE, + .value = value, + .context = coordinator + }; + + diffusion_time_series_append(session, params, NULL); + coordinator_wait(coordinator); + + buf_free(value); + } + + BUF_T *edit_value = buf_create(); + write_diffusion_double_value(3.14, edit_value); + DIFFUSION_TIME_SERIES_EDIT_PARAMS_T edit_params = { + .on_edit = on_edit, + .original_sequence = 10, + .topic_path = topic_path, + .datatype = DATATYPE_DOUBLE, + .value = edit_value, + .context = coordinator + }; + diffusion_time_series_edit(session, edit_params, NULL); + coordinator_wait(coordinator); + buf_free(edit_value); + + DIFFUSION_TIME_SERIES_RANGE_QUERY_T *range_query = diffusion_time_series_range_query(); + diffusion_time_series_range_query_for_values(range_query, NULL); + diffusion_time_series_range_query_from(range_query, 5, NULL); + diffusion_time_series_range_query_to(range_query, 15, NULL); + + DIFFUSION_TIME_SERIES_RANGE_QUERY_PARAMS_T query_params = { + .topic_path = topic_path, + .range_query = range_query, + .on_query_result = on_query_result, + .context = coordinator + }; + + diffusion_time_series_select_from(session, query_params, NULL); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + diffusion_time_series_range_query_free(range_query); + } \ No newline at end of file diff --git a/c/examples/time_series/subscribe.c b/c/examples/time_series/subscribe.c new file mode 100644 index 00000000..54a029c8 --- /dev/null +++ b/c/examples/time_series/subscribe.c @@ -0,0 +1,195 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_subscription( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + void *context) +{ + printf("Subscribed to %s.\n", topic_path); + return HANDLER_SUCCESS; +} + +static int on_unsubscription( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + NOTIFY_UNSUBSCRIPTION_REASON_T reason, + void *context) +{ + printf("Unsubscribed from %s.\n", topic_path); + return HANDLER_SUCCESS; +} + +static int on_value( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + DIFFUSION_DATATYPE datatype, + const DIFFUSION_VALUE_T *const old_value, + const DIFFUSION_VALUE_T *const new_value, + void *context) +{ + char *old_value_string; + if (old_value == NULL) { + old_value_string = strdup("NULL"); + } + else { + DIFFUSION_TIME_SERIES_EVENT_T *old_event; + read_diffusion_time_series_event(old_value, &old_event, NULL); + + DIFFUSION_VALUE_T *old_event_value = + diffusion_time_series_event_get_value(old_event); + + double old_value_double; + read_diffusion_double_value(old_event_value, &old_value_double, NULL); + + old_value_string = calloc(20, sizeof(char)); + snprintf(old_value_string, 20, "%g", old_value_double); + + diffusion_time_series_event_free(old_event); + diffusion_value_free(old_event_value); + } + + char *new_value_string; + if (new_value == NULL) { + new_value_string = strdup("NULL"); + } + else { + DIFFUSION_TIME_SERIES_EVENT_T *new_event; + read_diffusion_time_series_event(new_value, &new_event, NULL); + + DIFFUSION_VALUE_T *new_event_value = + diffusion_time_series_event_get_value(new_event); + + double new_value_double; + read_diffusion_double_value(new_event_value, &new_value_double, NULL); + new_value_string = calloc(20, sizeof(char)); + snprintf(new_value_string, 20, "%g", new_value_double); + + diffusion_time_series_event_free(new_event); + diffusion_value_free(new_event_value); + } + + printf( + "%s changed from %s to %s.\n", + topic_path, old_value_string, new_value_string + ); + + free(old_value_string); + free(new_value_string); + return HANDLER_SUCCESS; +} + +static int on_subscribe( + SESSION_T*session, + void *context) +{ + printf("Subscription request received and approved by the server.\n"); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + + +static int on_append( + const DIFFUSION_TIME_SERIES_EVENT_METADATA_T *event_metadata, + void *context) +{ + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/time/series/topic/path"; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + HASH_T *properties = hash_new(5); + hash_add(properties, DIFFUSION_TIME_SERIES_EVENT_VALUE_TYPE, "double"); + hash_add(properties, DIFFUSION_TIME_SERIES_RETAINED_RANGE, "limit 15 last 10s"); + hash_add(properties, DIFFUSION_TIME_SERIES_SUBSCRIPTION_RANGE, "limit 3"); + + utils_create_topic_with_properties( + session, + topic_path, + TOPIC_TYPE_TIME_SERIES, + DATATYPE_DOUBLE, + NULL, + properties + ); + hash_free(properties, NULL, NULL); + + VALUE_STREAM_T value_stream = { + .datatype = DATATYPE_DOUBLE, + .on_subscription = on_subscription, + .on_unsubscription = on_unsubscription, + .on_value = on_value + }; + + add_time_series_stream(session, topic_path, &value_stream); + + COORDINATOR_T *coordinator = coordinator_init(); + + SUBSCRIPTION_PARAMS_T params = { + .topic_selector = "?/my/time/series//", + .on_subscribe = on_subscribe, + .context = coordinator + }; + + subscribe(session, params); + coordinator_wait(coordinator); + + for (int i = 0; i < 25; i++) { + double random_value = utils_random_double(); + + BUF_T *value = buf_create(); + write_diffusion_double_value(random_value, value); + + DIFFUSION_TIME_SERIES_APPEND_PARAMS_T params = { + .on_append = on_append, + .topic_path = topic_path, + .datatype = DATATYPE_DOUBLE, + .value = value, + .context = coordinator + }; + + diffusion_time_series_append(session, params, NULL); + coordinator_wait(coordinator); + buf_free(value); + } + + // Sleep for a bit to see the notifications + sleep(2); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + } \ No newline at end of file diff --git a/c/examples/time_series/subscribe_cross_compatible.c b/c/examples/time_series/subscribe_cross_compatible.c new file mode 100644 index 00000000..a6ecdaa2 --- /dev/null +++ b/c/examples/time_series/subscribe_cross_compatible.c @@ -0,0 +1,189 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_subscription( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + void *context) +{ + printf("Subscribed to %s.\n", topic_path); + return HANDLER_SUCCESS; +} + +static int on_unsubscription( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + NOTIFY_UNSUBSCRIPTION_REASON_T reason, + void *context) +{ + printf("Unsubscribed from %s.\n", topic_path); + return HANDLER_SUCCESS; +} + +static int on_json_value( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + DIFFUSION_DATATYPE datatype, + const DIFFUSION_VALUE_T *const old_value, + const DIFFUSION_VALUE_T *const new_value, + void *context) +{ + char *old_value_string; + if (old_value == NULL) { + old_value_string = strdup("NULL"); + } + else { + DIFFUSION_TIME_SERIES_EVENT_T *old_event; + read_diffusion_time_series_event(old_value, &old_event, NULL); + + DIFFUSION_VALUE_T *old_event_value = + diffusion_time_series_event_get_value(old_event); + + to_diffusion_json_string(old_event_value, &old_value_string, NULL); + + diffusion_time_series_event_free(old_event); + diffusion_value_free(old_event_value); + } + + char *new_value_string; + if (new_value == NULL) { + new_value_string = strdup("NULL"); + } + else { + DIFFUSION_TIME_SERIES_EVENT_T *new_event; + read_diffusion_time_series_event(new_value, &new_event, NULL); + + DIFFUSION_VALUE_T *new_event_value = + diffusion_time_series_event_get_value(new_event); + + to_diffusion_json_string(new_event_value, &new_value_string, NULL); + + diffusion_time_series_event_free(new_event); + diffusion_value_free(new_event_value); + } + + printf( + "%s changed from %s to %s.\n", + topic_path, old_value_string, new_value_string + ); + + free(old_value_string); + free(new_value_string); + + return HANDLER_SUCCESS; +} + +static int on_subscribe( + SESSION_T*session, + void *context) +{ + printf("Subscription request received and approved by the server.\n"); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + + +static int on_append( + const DIFFUSION_TIME_SERIES_EVENT_METADATA_T *event_metadata, + void *context) +{ + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/time/series/topic/path"; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + HASH_T *properties = hash_new(5); + hash_add(properties, DIFFUSION_TIME_SERIES_EVENT_VALUE_TYPE, "double"); + hash_add(properties, DIFFUSION_TIME_SERIES_RETAINED_RANGE, "limit 15 last 10s"); + hash_add(properties, DIFFUSION_TIME_SERIES_SUBSCRIPTION_RANGE, "limit 3"); + + utils_create_topic_with_properties( + session, + topic_path, + TOPIC_TYPE_TIME_SERIES, + DATATYPE_DOUBLE, + NULL, + properties + ); + hash_free(properties, NULL, NULL); + + VALUE_STREAM_T value_stream = { + .datatype = DATATYPE_JSON, + .on_subscription = on_subscription, + .on_unsubscription = on_unsubscription, + .on_value = on_json_value + }; + + add_time_series_stream(session, topic_path, &value_stream); + + COORDINATOR_T *coordinator = coordinator_init(); + + SUBSCRIPTION_PARAMS_T params = { + .topic_selector = "?/my/time/series//", + .on_subscribe = on_subscribe, + .context = coordinator + }; + + subscribe(session, params); + coordinator_wait(coordinator); + + for (int i = 0; i < 25; i++) { + double random_value = utils_random_double(); + + BUF_T *value = buf_create(); + write_diffusion_double_value(random_value, value); + + DIFFUSION_TIME_SERIES_APPEND_PARAMS_T params = { + .on_append = on_append, + .topic_path = topic_path, + .datatype = DATATYPE_DOUBLE, + .value = value, + .context = coordinator + }; + + diffusion_time_series_append(session, params, NULL); + coordinator_wait(coordinator); + buf_free(value); + } + + // Sleep for a bit to see the notifications + sleep(2); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + } \ No newline at end of file diff --git a/c/examples/utils/coordinator.c b/c/examples/utils/coordinator.c new file mode 100644 index 00000000..e52403c3 --- /dev/null +++ b/c/examples/utils/coordinator.c @@ -0,0 +1,64 @@ +#include "coordinator.h" +#include "utils.h" + + +COORDINATOR_T *coordinator_init(void) +{ + COORDINATOR_T *result = calloc(1, sizeof(COORDINATOR_T)); + apr_initialize(); + apr_pool_create(&result->pool, NULL); + apr_thread_mutex_create(&result->mutex, APR_THREAD_MUTEX_NESTED, result->pool); + apr_thread_cond_create(&result->cond, result->pool); + apr_atomic_set32(&result->flag, 0); + result->timeout = 5000; + result->value = NULL; + result->response = NULL; + return result; +} + + +void coordinator_free(COORDINATOR_T *coordinator) +{ + if (coordinator == NULL) { + return; + } + apr_thread_mutex_destroy(coordinator->mutex); + apr_thread_cond_destroy(coordinator->cond); + apr_pool_destroy(coordinator->pool); + apr_terminate(); + + // value and response allocation resposibility is of who made them + free(coordinator); +} + + +void coordinator_wait(COORDINATOR_T *coordinator) +{ + if (coordinator == NULL) { + return; + } + if (apr_atomic_read32(&coordinator->flag) == 0) { + // needs to wait + apr_thread_mutex_lock(coordinator->mutex); + if(apr_thread_cond_timedwait(coordinator->cond, coordinator->mutex, coordinator->timeout * 1000) != APR_SUCCESS) { + LOG("Waiting expired."); + exit(1); + } + apr_thread_mutex_unlock(coordinator->mutex); + } + // reset flag + apr_atomic_set32(&coordinator->flag, 0); +} + + +void coordinator_broadcast(COORDINATOR_T *coordinator) +{ + if (coordinator == NULL) { + return; + } + apr_thread_mutex_lock(coordinator->mutex); + apr_atomic_set32(&coordinator->flag, 1); + apr_thread_cond_broadcast(coordinator->cond); + apr_thread_mutex_unlock(coordinator->mutex); +} + diff --git a/c/examples/utils/coordinator.h b/c/examples/utils/coordinator.h new file mode 100644 index 00000000..ceea6730 --- /dev/null +++ b/c/examples/utils/coordinator.h @@ -0,0 +1,32 @@ +#ifndef _diffusion_coordinator_ +#define _diffusion_coordinator_ 1 + + +#include "apr.h" +#include "apr_getopt.h" +#include "apr_thread_mutex.h" +#include "apr_thread_cond.h" +#include + +typedef struct coordinator_s { + apr_pool_t *pool; + apr_thread_cond_t *cond; + apr_thread_mutex_t *mutex; + unsigned long timeout; + volatile apr_uint32_t flag; + + void *response; + void *value; +} COORDINATOR_T; + + +COORDINATOR_T *coordinator_init(void); + +void coordinator_free(COORDINATOR_T *coordinator); + +void coordinator_wait(COORDINATOR_T *coordinator); + +void coordinator_broadcast(COORDINATOR_T *coordinator); + + +#endif \ No newline at end of file diff --git a/c/examples/utils/utils.c b/c/examples/utils/utils.c new file mode 100644 index 00000000..b4e0e813 --- /dev/null +++ b/c/examples/utils/utils.c @@ -0,0 +1,1406 @@ +#include "utils.h" + + +static int on_topic_update_add_and_set( + DIFFUSION_TOPIC_CREATION_RESULT_T result, + void *context) +{ + if (result == TOPIC_CREATED) { + printf("Topic has been created.\n"); + } + else if (result == TOPIC_EXISTS) { + printf("Topic already exists.\n"); + } + + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_topic_added_with_specification( + SESSION_T *session, + TOPIC_ADD_RESULT_CODE result_code, + void *context) +{ + if (result_code == TOPIC_ADD_RESULT_CREATED) { + printf("Topic has been created.\n"); + } + else if (result_code == TOPIC_ADD_RESULT_EXISTS) { + printf("Topic already exists.\n"); + } + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_topic_add_failed_with_specification( + SESSION_T *session, + TOPIC_ADD_FAIL_RESULT_CODE result_code, + const DIFFUSION_ERROR_T *error, + void *context) +{ + printf("Topic creation failed: %d %d %s\n", result_code, error->code, error->message); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + +static int on_topic_view_created( + const DIFFUSION_TOPIC_VIEW_T *topic_view, + void *context) +{ + char *name = diffusion_topic_view_get_name(topic_view); + printf("Topic view %s was created.\n", name); + free(name); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_subscription( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + void *context) +{ + printf("Subscribed to %s.\n", topic_path); + return HANDLER_SUCCESS; +} + +static int on_unsubscription( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + NOTIFY_UNSUBSCRIPTION_REASON_T reason, + void *context) +{ + HASH_NUM_T *unsubscription_reason_map = hash_num_new(10); + hash_num_add(unsubscription_reason_map, UNSUBSCRIPTION_REASON_CONTROL, "request by another client or server"); + hash_num_add(unsubscription_reason_map, UNSUBSCRIPTION_REASON_REMOVAL, "topic being removed"); + hash_num_add(unsubscription_reason_map, UNSUBSCRIPTION_REASON_AUTHORIZATION, "loss of authorisation to access topic"); + hash_num_add(unsubscription_reason_map, UNSUBSCRIPTION_REASON_UNKNOWN_UNSUBSCRIBE_REASON, "unkown reasons"); + hash_num_add(unsubscription_reason_map, UNSUBSCRIPTION_REASON_BACK_PRESSURE, "significant backlog of message on the server"); + hash_num_add(unsubscription_reason_map, UNSUBSCRIPTION_REASON_BRANCH_MAPPINGS, "session trees branch mapping alterations"); + hash_num_add(unsubscription_reason_map, UNSUBSCRIPTION_REASON_SUBSCRIPTION_REFRESH, "subscription refresh"); + hash_num_add(unsubscription_reason_map, UNSUBSCRIPTION_REASON_STREAM_CHANGE, "fallback stream being unsubscribed as new value stream was added"); + + char *unsubscription_reason = hash_num_get(unsubscription_reason_map, reason); + + printf("Unsubscribed from %s due to %s.\n", topic_path, unsubscription_reason); + hash_num_free(unsubscription_reason_map, NULL); + return HANDLER_SUCCESS; +} + +static int on_json_value( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + DIFFUSION_DATATYPE datatype, + const DIFFUSION_VALUE_T *const old_value, + const DIFFUSION_VALUE_T *const new_value, + void *context) +{ + char *old_value_json_string; + if (old_value == NULL) { + old_value_json_string = "NULL"; + } + else { + bool read_old = to_diffusion_json_string(old_value, &old_value_json_string, NULL); + if (read_old == false) { + printf("error while reading old value\n"); + return HANDLER_SUCCESS; + } + } + + char *new_value_json_string; + if (new_value == NULL) { + new_value_json_string = "NULL"; + } + else { + bool read_new = to_diffusion_json_string(new_value, &new_value_json_string, NULL); + if (read_new == false) { + printf("error while reading new value\n"); + return HANDLER_SUCCESS; + } + } + + printf( + "%s changed from %s to %s.\n", + topic_path, old_value_json_string, new_value_json_string + ); + + if (old_value != NULL) { + free(old_value_json_string); + } + + if (new_value != NULL) { + free(new_value_json_string); + } + return HANDLER_SUCCESS; +} + +static int on_string_value( + const char *const topic_path, + const TOPIC_SPECIFICATION_T *const specification, + DIFFUSION_DATATYPE datatype, + const DIFFUSION_VALUE_T *const old_value, + const DIFFUSION_VALUE_T *const new_value, + void *context) +{ + char *old_value_string; + if (old_value == NULL) { + old_value_string = "NULL"; + } + else { + bool read_old = read_diffusion_string_value(old_value, &old_value_string, NULL); + if (read_old == false) { + printf("error while reading old value\n"); + return HANDLER_SUCCESS; + } + } + + char *new_value_string; + if (new_value == NULL) { + new_value_string = "NULL"; + } + else { + bool read_new = read_diffusion_string_value(new_value, &new_value_string, NULL); + if (read_new == false) { + printf("error while reading new value\n"); + return HANDLER_SUCCESS; + } + } + + printf( + "%s changed from %s to %s.\n", + topic_path, old_value_string, new_value_string + ); + + if (old_value != NULL) { + free(old_value_string); + } + + if (new_value != NULL) { + free(new_value_string); + } + return HANDLER_SUCCESS; +} + +static int on_subscribe( + SESSION_T *session, + void *context) +{ + printf("Subscription request received and approved by the server.\n"); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_remote_server_created( + DIFFUSION_REMOTE_SERVER_T *remote_server, + LIST_T *errors, + void *context) +{ + char *name = diffusion_remote_server_get_name(remote_server); + printf("Remote server %s created.\n", name); + free(name); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_fetch_result_topic_properties( + const DIFFUSION_FETCH_RESULT_T *fetch_result, + void *context) +{ + LIST_T *results = diffusion_fetch_result_get_topic_results(fetch_result); + int size = list_get_size(results); + + for (int i = 0; i < size; i++) { + DIFFUSION_TOPIC_RESULT_T *topic_result = list_get_data_indexed(results, i); + + char *topic_path = diffusion_topic_result_get_path(topic_result); + TOPIC_SPECIFICATION_T *spec = diffusion_topic_result_get_specification(topic_result); + HASH_T *properties = topic_specification_get_properties(spec); + if (properties == NULL) { + continue; + } + + if (properties->size == 0) { + printf("%s has no non-default properties.\n", topic_path); + } + else { + printf("%s properties:\n", topic_path); + + char **keys = hash_keys(properties); + for(char **key = keys; *key != NULL; key++) { + printf(" %s: %s\n", *key, (char *) hash_get(properties, *key)); + } + free(keys); + } + hash_free(properties, free, free); + } + list_free(results, (void (*)(void *))diffusion_topic_result_free); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_topic_update( + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_topic_removed( + SESSION_T *session, + const DIFFUSION_TOPIC_REMOVAL_RESULT_T *response, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + + +static int on_range_query_result_int64( + const DIFFUSION_TIME_SERIES_QUERY_RESULT_T *query_result, + void *context) +{ + LIST_T *events = diffusion_time_series_query_result_get_events(query_result); + int size = diffusion_time_series_query_result_get_selected_count(query_result); + + for(int i = 0; i < size; i++) { + DIFFUSION_TIME_SERIES_EVENT_T *event = list_get_data_indexed(events, i); + + long sequence = diffusion_time_series_event_get_sequence(event); + long timestamp = diffusion_time_series_event_get_timestamp(event); + DIFFUSION_VALUE_T *value = diffusion_time_series_event_get_value(event); + + int64_t int64_value; + DIFFUSION_API_ERROR error; + bool value_converted = read_diffusion_int64_value(value, &int64_value, &error); + if (value_converted == false) { + printf("Error while reading value %d: %d %s\n", i, get_diffusion_api_error_code(error), get_diffusion_api_error_description(error)); + break; + } + + printf("\t%ld (%ld): %lld\n", sequence, timestamp, (long long) int64_value); + + diffusion_value_free(value); + } + coordinator_broadcast((COORDINATOR_T *) context); + list_free(events, (void (*)(void *))diffusion_time_series_event_free); + return HANDLER_SUCCESS; +} + +static int on_branch_mapping_table_set( + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_session_properties( + SESSION_T *session, + const SVC_GET_SESSION_PROPERTIES_RESPONSE_T *response, + void *context) +{ + COORDINATOR_T *coordinator = (COORDINATOR_T *) context; + + if (coordinator->value != NULL) + { + printf( + "Printing session properties that match '%s' pattern:\n", + (char *) coordinator->value + ); + } + else { + printf("Received the following session properties:\n"); + } + utils_print_hash( + response->properties, coordinator->value, utils_print_string, false + ); + + coordinator_broadcast(coordinator); + return HANDLER_SUCCESS; +} + +static int on_collector_removed(void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_get_security_store( + SESSION_T *session, + const SECURITY_STORE_T store, + void *context) +{ + COORDINATOR_T *coordinator = (COORDINATOR_T *)context; + + SECURITY_STORE_T *store_copy = security_store_dup(&store); + coordinator->response = store_copy; + + coordinator_broadcast(coordinator); + return HANDLER_SUCCESS; +} + +static int on_topic_view_removed( + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_remote_server_removed(void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_lock_released( + bool lock_owned, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_security_store_updated( + SESSION_T *session, + const LIST_T *error_report, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_system_authentication_store_updated( + SESSION_T *session, + const LIST_T *error_report, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_json_patch_result( + const DIFFUSION_JSON_PATCH_RESULT_T *result, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + + +SESSION_T *utils_open_session( + const char *url, + const char *principal, + const char *password) +{ + CREDENTIALS_T *credentials = (password == NULL) ? + credentials_create_none() : + credentials_create_password(password); + + DIFFUSION_ERROR_T error = { 0 }; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, &error + ); + if (session == NULL) { + LOG("Failed to open session: %s\n", error.message); + free(error.message); + } + credentials_free(credentials); + return session; +} + +void utils_remove_topic( + SESSION_T *session, + const char *topic_selector) +{ + COORDINATOR_T *coordinator = coordinator_init(); + + TOPIC_REMOVAL_PARAMS_T remove_params = { + .topic_selector = topic_selector, + .on_removed = on_topic_removed, + .on_error = on_error, + .context = coordinator + }; + + topic_removal(session, remove_params); + coordinator_wait(coordinator); + coordinator_free(coordinator); +} + +void utils_create_topic_with_properties( + SESSION_T *session, + const char *topic_path, + TOPIC_TYPE_T topic_type, + DIFFUSION_DATATYPE datatype, + BUF_T *value, + HASH_T *properties) +{ + printf("Creating %s\n", topic_path); + + COORDINATOR_T *coordinator = coordinator_init(); + + TOPIC_SPECIFICATION_T *topic_specification = + (properties == NULL) + ? topic_specification_init(topic_type) + : topic_specification_init_with_properties(topic_type, properties); + + if (value != NULL) { + // Add and set + DIFFUSION_TOPIC_UPDATE_ADD_AND_SET_PARAMS_T add_and_set_params = { + .datatype = datatype, + .on_topic_update_add_and_set = on_topic_update_add_and_set, + .topic_path = topic_path, + .specification = topic_specification, + .update = value, + .on_error = on_error, + .context = coordinator + }; + diffusion_topic_update_add_and_set(session, add_and_set_params); + } + else { + // Add only + ADD_TOPIC_CALLBACK_T callback = { + .on_topic_added_with_specification = on_topic_added_with_specification, + .on_topic_add_failed_with_specification = on_topic_add_failed_with_specification, + .context = coordinator + }; + add_topic_from_specification( + session, topic_path, topic_specification, callback + ); + } + coordinator_wait(coordinator); + + coordinator_free(coordinator); + topic_specification_free(topic_specification); +} + + +void utils_set_topic_value( + SESSION_T *session, + const char *topic_path, + DIFFUSION_DATATYPE datatype, + BUF_T *value) +{ + COORDINATOR_T *coordinator = coordinator_init(); + DIFFUSION_TOPIC_UPDATE_SET_PARAMS_T params = { + .datatype = datatype, + .on_topic_update = on_topic_update, + .topic_path = topic_path, + .update = value, + .on_error = on_error, + .context = coordinator + }; + + diffusion_topic_update_set(session, params); + + coordinator_wait(coordinator); + + coordinator_free(coordinator); +} + +void utils_create_json_topic_with_topic_removal_policy( + SESSION_T *session, + const char *topic_path, + const char *topic_removal_policy) +{ + HASH_T *properties = hash_new(3); + hash_add(properties, DIFFUSION_REMOVAL, topic_removal_policy); + + utils_create_json_topic_with_properties(session, topic_path, NULL, properties); + hash_free(properties, NULL, NULL); +} + + +void utils_create_json_topic_with_properties( + SESSION_T *session, + const char *topic_path, + const char *json_string, + HASH_T *properties) +{ + BUF_T *value = NULL; + if (json_string != NULL) { + value = buf_create(); + write_diffusion_json_value(json_string, value); + } + + utils_create_topic_with_properties( + session, topic_path, TOPIC_TYPE_JSON, DATATYPE_JSON, value, properties + ); + + buf_free(value); +} + + +void utils_create_json_topic( + SESSION_T *session, + const char *topic_path, + const char *json_string) +{ + utils_create_json_topic_with_properties( + session, topic_path, json_string, NULL + ); +} + + +void utils_set_json_topic_value( + SESSION_T *session, + const char *topic_path, + const char *json_string) +{ + BUF_T *value = buf_create(); + write_diffusion_json_value(json_string, value); + + utils_set_topic_value(session, topic_path, DATATYPE_JSON, value); + + buf_free(value); +} + + +void utils_create_int64_topic( + SESSION_T *session, + const char *topic_path, + int64_t int64_value) +{ + BUF_T *value = buf_create(); + write_diffusion_int64_value(int64_value, value); + + utils_create_topic_with_properties( + session, topic_path, TOPIC_TYPE_INT64, DATATYPE_INT64, value, NULL + ); + + buf_free(value); +} + + +void utils_set_int64_topic_value( + SESSION_T *session, + const char *topic_path, + int64_t int64_value) +{ + BUF_T *value = buf_create(); + write_diffusion_int64_value(int64_value, value); + + utils_set_topic_value(session, topic_path, DATATYPE_INT64, value); + + buf_free(value); +} + + +void utils_create_string_topic_with_properties( + SESSION_T *session, + const char *topic_path, + const char *value_string, + HASH_T *properties) +{ + BUF_T *value = buf_create(); + write_diffusion_string_value(value_string, value); + + utils_create_topic_with_properties( + session, topic_path, TOPIC_TYPE_STRING, DATATYPE_STRING, value, properties + ); + + buf_free(value); +} + + +void utils_create_string_topic( + SESSION_T *session, + const char *topic_path, + const char *value_string) +{ + utils_create_string_topic_with_properties( + session, topic_path, value_string, NULL + ); +} + + +void utils_create_topic_view( + SESSION_T *session, + const char *name, + const char *specification) +{ + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_CREATE_TOPIC_VIEW_PARAMS_T create_topic_view_params = { + .view = name, + .specification = specification, + .on_topic_view_created = on_topic_view_created, + .on_error = on_error, + .context = coordinator + }; + diffusion_topic_views_create_topic_view(session, create_topic_view_params, NULL); + + coordinator_wait(coordinator); + coordinator_free(coordinator); +} + + +void utils_create_remote_server( + SESSION_T *session, + char *name, + char *url, + char *principal, + char *password, + HASH_NUM_T *connection_options) +{ + CREDENTIALS_T *credentials = ( + (password == NULL) + ? credentials_create_none() + : credentials_create_password(password) + ); + + DIFFUSION_REMOTE_SERVER_BUILDER_T *builder = diffusion_remote_server_builder_init(); + diffusion_remote_server_builder_principal(builder, principal); + diffusion_remote_server_builder_credentials(builder, credentials); + diffusion_remote_server_builder_connection_options(builder, connection_options); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_REMOTE_SERVER_T *remote_server = + diffusion_remote_server_builder_create_secondary_initiator( + builder, name, url, NULL + ); + + DIFFUSION_CREATE_REMOTE_SERVER_PARAMS_T params = { + .remote_server = remote_server, + .on_remote_server_created = on_remote_server_created, + .on_error = on_error, + .context = coordinator + }; + diffusion_create_remote_server(session, params, NULL); + + coordinator_wait(coordinator); + + coordinator_free(coordinator); + credentials_free(credentials); + diffusion_remote_server_free(remote_server); + diffusion_remote_server_builder_free(builder); +} + + +VALUE_STREAM_T *utils_create_value_stream( + SESSION_T *session, + const char *topic_selector, + DIFFUSION_DATATYPE datatype) +{ + VALUE_STREAM_T *value_stream = calloc(1, sizeof(VALUE_STREAM_T)); + value_stream->datatype = datatype; + value_stream->on_subscription = on_subscription; + value_stream->on_unsubscription = on_unsubscription; + + if (datatype == DATATYPE_JSON) { + value_stream->on_value = on_json_value; + } + else if (datatype == DATATYPE_STRING) { + value_stream->on_value = on_string_value; + } + else { + printf("Missing on_value function for chosen datatype\n"); + free(value_stream); + return NULL; + } + + add_stream(session, topic_selector, value_stream); + + return value_stream; +} + + +VALUE_STREAM_T *utils_subscribe( + SESSION_T *session, + const char *topic_selector, + DIFFUSION_DATATYPE datatype) +{ + VALUE_STREAM_T *value_stream = utils_create_value_stream( + session, topic_selector, datatype + ); + + if (value_stream == NULL) { + return NULL; + } + + COORDINATOR_T *coordinator = coordinator_init(); + + SUBSCRIPTION_PARAMS_T params = { + .topic_selector = topic_selector, + .on_subscribe = on_subscribe, + .context = coordinator + }; + subscribe(session, params); + coordinator_wait(coordinator); + + coordinator_free(coordinator); + return value_stream; +} + + +void utils_get_topic_properties( + SESSION_T *session, + const char *topic_selector) +{ + DIFFUSION_FETCH_REQUEST_T *fetch_request = diffusion_fetch_request_init(session); + diffusion_fetch_request_with_properties(fetch_request, NULL); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_FETCH_REQUEST_PARAMS_T fetch_request_params = { + .topic_selector = topic_selector, + .fetch_request = fetch_request, + .on_fetch_result = on_fetch_result_topic_properties, + .context = coordinator + }; + + diffusion_fetch_request_fetch(session, fetch_request_params); + coordinator_wait(coordinator); + + coordinator_free(coordinator); + diffusion_fetch_request_free(fetch_request); +} + + +void utils_time_series_range_query_int64( + SESSION_T *session, + const char *topic_path) +{ + DIFFUSION_TIME_SERIES_RANGE_QUERY_T *range_query = + diffusion_time_series_range_query(); + diffusion_time_series_range_query_for_values(range_query, NULL); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_TIME_SERIES_RANGE_QUERY_PARAMS_T query_params = { + .topic_path = topic_path, + .range_query = range_query, + .on_query_result = on_range_query_result_int64, + .context = coordinator + }; + + diffusion_time_series_select_from(session, query_params, NULL); + coordinator_wait(coordinator); + + coordinator_free(coordinator); + diffusion_time_series_range_query_free(range_query); +} + + +void utils_build_branch_mapping_table( + SESSION_T * session, + const char *topic_path, + size_t mappings_length, + const UTILS_SESSION_TREES_MAPPING_T mappings[]) +{ + DIFFUSION_BRANCH_MAPPING_TABLE_BUILDER_T *builder = + diffusion_branch_mapping_table_builder_init(); + + if (mappings_length > 0) { + for (int i = 0; i < mappings_length; i++) { + UTILS_SESSION_TREES_MAPPING_T entry = mappings[i]; + diffusion_branch_mapping_table_builder_add_branch_mapping( + builder, entry.rule, entry.topic_path + ); + } + } + + DIFFUSION_BRANCH_MAPPING_TABLE_T *table = + diffusion_branch_mapping_table_builder_create_table( + builder, (char *) topic_path + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_SESSION_TREES_PUT_BRANCH_MAPPING_TABLE_PARAMS_T params = { + .on_table_set = on_branch_mapping_table_set, + .on_error = on_error, + .table = table, + .context = coordinator + }; + + diffusion_session_trees_put_branch_mapping_table(session, params, NULL); + coordinator_wait(coordinator); + + coordinator_free(coordinator); + diffusion_branch_mapping_table_free(table); + diffusion_branch_mapping_table_builder_free(builder); +} + + +void utils_remove_branch_mapping_table( + SESSION_T *session, + const char *topic_path) +{ + utils_build_branch_mapping_table(session, topic_path, 0, NULL); +} + + +void utils_print_session_properties( + SESSION_T *session, + SESSION_ID_T *session_id, + const char *properties_regex) +{ + SET_T *required_properties = set_new_string(1); + set_add(required_properties, PROPERTIES_SELECTOR_ALL_FIXED_PROPERTIES); + set_add(required_properties, PROPERTIES_SELECTOR_ALL_USER_PROPERTIES); + + COORDINATOR_T *coordinator = coordinator_init(); + coordinator->value = (properties_regex == NULL) ? NULL : strdup(properties_regex); + + GET_SESSION_PROPERTIES_PARAMS_T get_session_properties_params = { + .on_session_properties = on_session_properties, + .on_error = on_error, + .session_id = session_id, + .required_properties = required_properties, + .context = coordinator + }; + get_session_properties(session, get_session_properties_params); + coordinator_wait(coordinator); + + set_free(required_properties); + + free(coordinator->value); + coordinator_free(coordinator); +} + + +void utils_remove_session_metric_collector( + SESSION_T *session, + const char *name) +{ + char *name_copy = strdup(name); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_METRICS_REMOVE_SESSION_METRIC_COLLECTOR_PARAMS_T remove_params = { + .collector_name = name_copy, + .on_collector_removed = on_collector_removed, + .on_error = on_error, + .context = coordinator + }; + + diffusion_metrics_remove_session_metric_collector(session, remove_params, NULL); + coordinator_wait(coordinator); + + coordinator_free(coordinator); + free(name_copy); +} + + +void utils_remove_topic_metric_collector( + SESSION_T *session, + const char *name) +{ + char *name_copy = strdup(name); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_METRICS_REMOVE_TOPIC_METRIC_COLLECTOR_PARAMS_T remove_params = { + .collector_name = name_copy, + .on_collector_removed = on_collector_removed, + .on_error = on_error, + .context = coordinator + }; + + diffusion_metrics_remove_topic_metric_collector(session, remove_params, NULL); + coordinator_wait(coordinator); + + coordinator_free(coordinator); + free(name_copy); +} + + +SECURITY_STORE_T *utils_get_security_store( + SESSION_T *session) +{ + COORDINATOR_T *coordinator = coordinator_init(); + + const GET_SECURITY_STORE_PARAMS_T params = { + .on_get = on_get_security_store, + .on_error = on_error, + .context = coordinator + }; + + get_security_store(session, params); + + coordinator_wait(coordinator); + + SECURITY_STORE_T *store = coordinator->response; + coordinator_free(coordinator); + + return store; +} + +void utils_remove_role( + SESSION_T *session, + const char *role_name) +{ + if (session == NULL) { + return; + } + + SCRIPT_T *script_remove_role = script_create(); + + SET_T *set_no_permissions = set_new_int(2); + update_security_store_default_path_permissions( + script_remove_role, role_name, set_no_permissions + ); + update_security_store_global_role_permissions( + script_remove_role, role_name, set_no_permissions + ); + set_free(set_no_permissions); + + LIST_T *list_no_roles = list_create(); + update_security_store_include_roles( + script_remove_role, role_name, list_no_roles + ); + list_free(list_no_roles, NULL); + + utils_update_security_store(session, script_remove_role); + script_free(script_remove_role); +} + + +void utils_add_role_from_security_store( + SESSION_T *session, + SECURITY_STORE_T *store, + const char *role_name) +{ + if (session == NULL || store == NULL || store->roles == NULL) { + return; + } + + SECURITY_STORE_ROLE_T *role = + (SECURITY_STORE_ROLE_T *) hash_get(store->roles, role_name); + + if (role == NULL) { + return; + } + + SCRIPT_T *script_add_role = script_create(); + + LIST_T *list_included_roles = utils_set_to_list( + role->included_roles + ); + update_security_store_include_roles( + script_add_role, role_name, list_included_roles + ); + list_free(list_included_roles, NULL); + + update_security_store_global_role_permissions( + script_add_role, role_name, role->global_permissions + ); + + update_security_store_default_path_permissions( + script_add_role, role_name, role->default_path_permissions + ); + + if (role->path_permissions != NULL) { + char **keys = hash_keys(role->path_permissions); + for(char **ptr = keys; *ptr != NULL; ptr++) { + PATH_PERMISSIONS_T **arr_permissions = + (PATH_PERMISSIONS_T **) hash_get(role->path_permissions, *ptr); + + SET_T *set_path_permissions = set_new_int(3); + for(PATH_PERMISSIONS_T **arr_ptr = arr_permissions; + *arr_ptr != NULL; + arr_ptr++) { + set_add(set_path_permissions, *arr_ptr); + } + update_security_store_path_permissions( + script_add_role, role_name, *ptr, set_path_permissions + ); + set_free(set_path_permissions); + } + free(keys); + } + + if (role->locking_principal != NULL) { + update_security_store_role_locked_by_principal( + script_add_role, role_name, role->locking_principal + ); + } + + utils_update_security_store(session, script_add_role); + script_free(script_add_role); +} + + +void utils_print_security_store( + SESSION_T *session, + const char *selected_role) +{ + SECURITY_STORE_T *store = utils_get_security_store(session); + + // Show all available information + printf("Roles:\n"); + utils_print_security_roles(store->roles, selected_role); + + char *anon_roles = utils_set_to_string( + store->anon_roles_default, + utils_print_string + ); + printf("Anonymous session roles: %s\n", anon_roles); + free(anon_roles); + + char *named_roles = utils_set_to_string( + store->named_roles_default, + utils_print_string + ); + printf("Named session roles: %s\n", named_roles); + free(named_roles); + + char *isolated_paths = utils_set_to_string( + store->isolated_paths, + utils_print_string + ); + printf("Isolated paths: %s\n", isolated_paths); + free(isolated_paths); + + security_store_free(store); +} + + +void utils_remove_topic_view( + SESSION_T *session, + const char *topic_view_name) +{ + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_REMOVE_TOPIC_VIEW_PARAMS_T remove_params = { + .view = topic_view_name, + .on_topic_view_removed = on_topic_view_removed, + .on_error = on_error, + .context = coordinator + }; + + diffusion_topic_views_remove_topic_view(session, remove_params, NULL); + coordinator_wait(coordinator); + + coordinator_free(coordinator); +} + + +void utils_remove_remote_server( + SESSION_T *session, + const char *remote_server_name) +{ + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_REMOVE_REMOTE_SERVER_PARAMS_T params = { + .name = (char *) remote_server_name, + .on_remote_server_removed = on_remote_server_removed, + .on_error = on_error, + .context = coordinator + }; + + diffusion_remove_remote_server(session, params, NULL); + coordinator_wait(coordinator); + + coordinator_free(coordinator); +} + +void utils_release_lock( + SESSION_T *session, + DIFFUSION_SESSION_LOCK_T *lock) +{ + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_SESSION_LOCK_UNLOCK_PARAMS_T unlock_params = { + .on_unlock = on_lock_released, + .on_error = on_error, + .context = coordinator + }; + + diffusion_session_lock_unlock(session, lock, unlock_params); + coordinator_wait(coordinator); + + coordinator_free(coordinator); +} + +void utils_update_security_store( + SESSION_T *session, + SCRIPT_T *script) +{ + COORDINATOR_T *coordinator = coordinator_init(); + + const UPDATE_SECURITY_STORE_PARAMS_T params = { + .on_update = on_security_store_updated, + .on_error = on_error, + .update_script = script, + .context = coordinator + }; + + update_security_store(session, params); + coordinator_wait(coordinator); + + coordinator_free(coordinator); +} + + +void utils_update_system_authentication_store( + SESSION_T *session, + SCRIPT_T *script) +{ + COORDINATOR_T *coordinator = coordinator_init(); + + const UPDATE_SYSTEM_AUTHENTICATION_STORE_PARAMS_T params = { + .on_update = on_system_authentication_store_updated, + .on_error = on_error, + .update_script = script, + .context = coordinator + }; + + update_system_authentication_store(session, params); + coordinator_wait(coordinator); + + coordinator_free(coordinator); +} + + +void utils_apply_json_patch( + SESSION_T *session, + char *topic_path, + char *patch) +{ + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_APPLY_JSON_PATCH_PARAMS_T patch_params = { + .topic_path = topic_path, + .patch = patch, + .on_json_patch_result = on_json_patch_result, + .context = coordinator + }; + + diffusion_apply_json_patch(session, patch_params, NULL); + coordinator_wait(coordinator); + + coordinator_free(coordinator); +} + + +double utils_random_double(void) +{ + SEED_RANDOM(RANDOM()); + long random_long = RANDOM() % 1000; + double random_double = (double) (random_long / (double) 1000.0); + return random_double; +} + + +const char *utils_print_global_permission(void *value) +{ + if (value == NULL) { + return "Unknown value"; + } + return SECURITY_GLOBAL_PERMISSIONS_NAMES[*((uint32_t *)value)]; +} + +const char *utils_print_path_permission(void *value) +{ + if (value == NULL) { + return "Unknown value"; + } + return SECURITY_PATH_PERMISSIONS_NAMES[*((uint32_t *)value)]; +} + +const char *utils_print_string(void *value) +{ + char *ptr = (char *) value; + return ptr; +} + +const char *utils_print_path_permission_set(void *value) +{ + SET_T *set = (SET_T *) value; + return utils_set_to_string(set, utils_print_path_permission); +} + + +LIST_T *utils_set_to_list( + SET_T *set) +{ + LIST_T *result = list_create(); + void *entries = set_values(set); + for (void **entry = entries; *entry != NULL; entry++ ) { + list_append_last(result, *entry); + } + free(entries); + return result; +} + + +char *utils_set_to_string( + SET_T *set, + print_fn print_function) +{ + if (set == NULL) { + return NULL; + } + BUF_T *buffer = buf_create(); + void *entries = set_values(set); + for (void **entry = entries; *entry != NULL; entry++ ) { + const char *entry_string = print_function(*entry); + char *prefix = ((buffer->len == 0) ? "" : " "); + buf_sprintf(buffer, "%s%s", prefix, entry_string); + } + free(entries); + + char *result = buf_as_string(buffer); + buf_free(buffer); + + return result; +} + +void utils_print_security_roles( + HASH_T *hash, + const char *selected_role) +{ + char **keys = hash_keys(hash); + for(char **ptr = keys; *ptr != NULL; ptr++) { + SECURITY_STORE_ROLE_T *role = + (SECURITY_STORE_ROLE_T *)hash_get(hash, *ptr); + + if (selected_role != NULL && strcmp(role->name, selected_role) != 0) { + continue; + } + + printf("\t%s\n", role->name); + + char *included_roles = utils_set_to_string( + role->included_roles, + utils_print_string + ); + printf("\t\tIncluded Roles: %s\n", included_roles); + free(included_roles); + + char *global_permissions = utils_set_to_string( + role->global_permissions, + utils_print_global_permission + ); + printf("\t\tGlobal Permissions: %s\n", global_permissions); + free(global_permissions); + + char *default_path_permissions = utils_set_to_string( + role->default_path_permissions, + utils_print_path_permission + ); + printf("\t\tDefault Path Permissions: %s\n", default_path_permissions); + free(default_path_permissions); + + printf("\t\tPath Permissions:\n"); + utils_print_hash( + role->path_permissions, NULL, utils_print_path_permission_set, true + ); + + printf("\t\tLocking Principal: %s\n", role->locking_principal); + } + free(keys); +} + +void utils_print_hash( + HASH_T *hash, + const char *pattern, + print_fn print_function, + bool free_value_string) +{ + char **keys = hash_keys(hash); + for(char **ptr = keys; *ptr != NULL; ptr++) { + if (pattern == NULL || strncmp(*ptr, pattern, strlen(pattern)) == 0) { + void *value = hash_get(hash, *ptr); + char *value_string = (char *) print_function(value); + printf("\t%s: %s\n", *ptr, value_string); + if (free_value_string) { + free(value_string); + } + } + } + free(keys); +} + +bool utils_string_starts_with( + const char *prefix, + const char *string) +{ + size_t prefix_length = strlen(prefix); + size_t string_length = strlen(string); + return + string_length < prefix_length ? false : memcmp(prefix, string, prefix_length) == 0; +} + + +char *utils_list_to_string(LIST_T *list) +{ + if (list == NULL) { + return NULL; + } + int list_size = list_get_size(list); + size_t current_size = list_size * 10; + size_t used = 0; + char *result = calloc(current_size + 1, sizeof(char)); + for (int i = 0; i < list_size; i++) { + char *entry = list_get_data_indexed(list, i); + size_t remaining = current_size - used - 1; + size_t required = strlen(entry) + ((used > 0) ? 1 : 0); + if (remaining < required ) { + // not enough space, realloc string + current_size += required; + result = realloc(result, current_size); + char *new_ptr = realloc(result, current_size); + if (new_ptr == NULL) { + LOG("realloc failed to acquire memory"); + } + result = new_ptr; + } + char *prefix = ((used == 0) ? "" : " "); + snprintf(result + used, current_size, "%s%s", prefix, entry); + used += required; + } + result[used] = 0; + return result; +} + +void utils_print_script(SCRIPT_T *script) +{ + char *content = buf_as_string((BUF_T *)script); + printf("Script: %s\n", content); + free(content); +} + +char *utils_path_to_folder( + const char *path, + const char *folder) +{ + LIST_T *components = list_create(); + char *token = strtok((char *) path, OS_PATH_SEPARATOR); + size_t components_total_len = 0; + + while (token != NULL) { + list_append_last(components, OS_STRDUP(token)); + components_total_len += strlen(token); + if (strcmp(token, folder) == 0) { + // we have the needed path, stop here + break; + } + token = strtok(NULL, OS_PATH_SEPARATOR); + } + + int size = list_get_size(components); + size_t string_len = components_total_len + (size + 1) * strlen(OS_PATH_SEPARATOR) + 1; + char *result = calloc(string_len + 1, sizeof(char)); + + for (int i = 0; i < size; i++) { + char *component = (char *) list_get_data_indexed(components, i); + #ifdef WIN32 + if (i != 0) { + OS_STRCAT(result, string_len, OS_PATH_SEPARATOR); + } + #else + OS_STRCAT(result, string_len, OS_PATH_SEPARATOR); + #endif + OS_STRCAT(result, string_len, component); + } + return result; +} + diff --git a/c/examples/utils/utils.h b/c/examples/utils/utils.h new file mode 100644 index 00000000..ec20e647 --- /dev/null +++ b/c/examples/utils/utils.h @@ -0,0 +1,357 @@ +#ifndef _diffusion_utils_functions_ +#define _diffusion_utils_functions_ 1 + +#include +#include +#include + +#include "diffusion.h" + +#include "apr.h" +#include "apr_getopt.h" +#include "apr_thread_mutex.h" +#include "apr_thread_cond.h" +#include + +#include "coordinator.h" + +extern apr_pool_t *g_pool; +extern apr_thread_cond_t *g_cond; +extern apr_thread_mutex_t *g_mutex; +extern volatile apr_uint32_t g_flag; +extern unsigned long g_timeout; + +// Required global variables for synchronisation of threads + +// Macro to define +#define GET_TID ((unsigned int)(((unsigned long long)apr_os_thread_current()) % 1000)) + +#define LOG(format, ...) fprintf(stdout, "[%03d] %30s():%s:%d " format "\n", GET_TID, __FUNCTION__, __FILE__, __LINE__, ##__VA_ARGS__); fflush(stdout) + +#define MUTEX_DEF \ + apr_pool_t *g_pool; \ + apr_thread_cond_t *g_cond; \ + apr_thread_mutex_t *g_mutex; \ + volatile apr_uint32_t g_flag; \ + unsigned long g_timeout = 5000; + +// Macro to initialise +#define MUTEX_INIT \ + apr_initialize(); \ + apr_pool_create(&g_pool, NULL); \ + apr_thread_mutex_create(&g_mutex, APR_THREAD_MUTEX_NESTED, g_pool); \ + apr_thread_cond_create(&g_cond, g_pool); \ + apr_atomic_set32(&g_flag, 0); + +// Macro to terminate +#define MUTEX_TERMINATE \ + apr_thread_mutex_destroy(g_mutex); \ + apr_thread_cond_destroy(g_cond); \ + apr_pool_destroy(g_pool); \ + apr_terminate(); + +// Macro to wait +#define MUTEX_WAIT \ + if (apr_atomic_read32(&g_flag) == 0) { \ + apr_thread_mutex_lock(g_mutex); \ + if(apr_thread_cond_timedwait(g_cond, g_mutex, g_timeout * 1000) != APR_SUCCESS) { \ + LOG("Waiting expired."); \ + exit(1); \ + } \ + apr_thread_mutex_unlock(g_mutex); \ + apr_atomic_set32(&g_flag, 0); \ + } + +// Macro to broadcast +#define MUTEX_BROADCAST \ + apr_thread_mutex_lock(g_mutex); \ + apr_thread_cond_broadcast(g_cond); \ + apr_atomic_set32(&g_flag, 1); \ + apr_thread_mutex_unlock(g_mutex); + + +#ifndef WIN32 + #include + #include + #include + + #define OS_STRTOK(STRING, SEPARATOR, REMAINDER_PTR) strtok_r(STRING, SEPARATOR, REMAINDER_PTR) + #define OS_STRDUP(x) strdup(x) + #define OS_STRDUP_FN (void *(*) (void *)) strdup + #define OS_STRCAT(DEST, DEST_LEN, SOURCE) strcat(DEST, SOURCE) + #define OS_STRNCAT(DEST, DEST_LEN, SOURCE, COUNT) strncat(DEST, SOURCE, COUNT) + #define OS_PATH_SEPARATOR "/" + + #define SEED_RANDOM(SEED) srandom(SEED) + #define RANDOM() random() + #define OS_SETENV(X, Y) setenv(X, Y, 1) +#else + #define OS_STRTOK(STRING, SEPARATOR, REMAINDER_PTR) strtok_s(STRING, SEPARATOR, REMAINDER_PTR) + #define OS_STRDUP(x) _strdup(x) + #define OS_STRDUP_FN (void *(*) (void *)) _strdup + #define OS_STRCAT(DEST, DEST_LEN, SOURCE) strcat_s(DEST, DEST_LEN, SOURCE) + #define OS_STRNCAT(DEST, DEST_LEN, SOURCE, COUNT) strncat_s(DEST, DEST_LEN, SOURCE, COUNT) + #define OS_PATH_SEPARATOR "\\" + + #define WIN32_LEAN_AND_MEAN + #define getpid _getpid + + #define SEED_RANDOM(SEED) srand(SEED) + #define RANDOM() rand() + #define OS_SETENV(X, Y) _putenv_s(X, Y) + + #define sleep(x) Sleep(1000 * x) +#endif + + +typedef struct { + char *rule; + char *topic_path; +} UTILS_SESSION_TREES_MAPPING_T; + +typedef const char *(*print_fn)(void *value); + +SESSION_T *utils_open_session( + const char *url, + const char *principal, + const char *password +); + +void utils_remove_topic( + SESSION_T *session, + const char *topic_selector +); + +void utils_create_topic_with_properties( + SESSION_T *session, + const char *topic_path, + TOPIC_TYPE_T topic_type, + DIFFUSION_DATATYPE datatype, + BUF_T *value, + HASH_T *properties +); + +void utils_set_topic_value( + SESSION_T *session, + const char *topic_path, + DIFFUSION_DATATYPE datatype, + BUF_T *value +); + +void utils_create_int64_topic( + SESSION_T *session, + const char *topic_path, + int64_t int64_value +); + +void utils_set_int64_topic_value( +SESSION_T *session, + const char *topic_path, + int64_t int64_value +); + +void utils_create_json_topic( + SESSION_T *session, + const char *topic_path, + const char *json_string +); + +void utils_create_json_topic_with_topic_removal_policy( + SESSION_T *session, + const char *topic_path, + const char *topic_removal_policy +); + +void utils_create_json_topic_with_properties( + SESSION_T *session, + const char *topic_path, + const char *json_string, + HASH_T *properties +); + +void utils_set_json_topic_value( + SESSION_T *session, + const char *topic_path, + const char *json_string +); + +void utils_create_string_topic_with_properties( + SESSION_T *session, + const char *topic_path, + const char *value_string, + HASH_T *properties +); + +void utils_create_string_topic( + SESSION_T *session, + const char *topic_path, + const char *value_string +); + +void utils_create_topic_view( + SESSION_T *session, + const char *name, + const char *specification +); + +void utils_create_remote_server( + SESSION_T *session, + char *name, + char *url, + char *principal, + char *password, + HASH_NUM_T *connection_options +); + +VALUE_STREAM_T *utils_create_value_stream( + SESSION_T *session, + const char *topic_selector, + DIFFUSION_DATATYPE datatype +); + +VALUE_STREAM_T *utils_subscribe( + SESSION_T *session, + const char *topic_selector, + DIFFUSION_DATATYPE datatype +); + +void utils_get_topic_properties( + SESSION_T *session, + const char *topic_selector +); + +void utils_time_series_range_query_int64( + SESSION_T *session, + const char *topic_path +); + +void utils_build_branch_mapping_table( + SESSION_T * session, + const char *topic_path, + size_t mappings_length, + const UTILS_SESSION_TREES_MAPPING_T mappings[] +); + +void utils_remove_branch_mapping_table( + SESSION_T *session, + const char *topic_path +); + +void utils_print_session_properties( + SESSION_T *session, + SESSION_ID_T *session_id, + const char *properties_regex +); + +void utils_remove_session_metric_collector( + SESSION_T *session, + const char *name +); + +void utils_remove_topic_metric_collector( + SESSION_T *session, + const char *name +); + +SECURITY_STORE_T *utils_get_security_store( + SESSION_T *session +); + +void utils_remove_role( + SESSION_T *session, + const char *role_name +); + +void utils_add_role_from_security_store( + SESSION_T *session, + SECURITY_STORE_T *store, + const char *role_name +); + +void utils_print_security_store( + SESSION_T *session, + const char *selected_role +); + +void utils_remove_topic_view( + SESSION_T *session, + const char *topic_view_name +); + +void utils_remove_remote_server( + SESSION_T *session, + const char *remote_server_name +); + +void utils_release_lock( + SESSION_T *session, + DIFFUSION_SESSION_LOCK_T *lock +); + +void utils_update_security_store( + SESSION_T *session, + SCRIPT_T *script +); + +void utils_update_system_authentication_store( + SESSION_T *session, + SCRIPT_T *script +); + +void utils_apply_json_patch( + SESSION_T *session, + char *topic_path, + char *patch +); + +double utils_random_double(void); + +LIST_T *utils_set_to_list( + SET_T *set +); + +char *utils_set_to_string( + SET_T *set, + print_fn print_function +); + +void utils_print_security_roles( + HASH_T *hash, + const char *selected_role +); + +void utils_print_hash( + HASH_T *hash, + const char *pattern, + print_fn print_function, + bool free_value_string +); + +bool utils_string_starts_with( + const char *prefix, + const char *string +); + +bool utils_string_matches_regex( + const char *pattern, + const char *string +); + +char *utils_list_to_string(LIST_T *list); + +const char *utils_print_global_permission(void *value); + +const char *utils_print_path_permission(void *value); + +const char *utils_print_string(void *value); + +void utils_print_script(SCRIPT_T *script); + +char *utils_path_to_folder( + const char *path, + const char *folder +); + + + +#endif \ No newline at end of file diff --git a/c/examples/wrangling/session_trees/get_branch_mapping_table.c b/c/examples/wrangling/session_trees/get_branch_mapping_table.c new file mode 100644 index 00000000..a36e187f --- /dev/null +++ b/c/examples/wrangling/session_trees/get_branch_mapping_table.c @@ -0,0 +1,125 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_branch_mapping_table_received( + const DIFFUSION_BRANCH_MAPPING_TABLE_T *table, + void *context) +{ + char *session_tree_branch = + diffusion_branch_mapping_table_get_session_tree_branch( + (DIFFUSION_BRANCH_MAPPING_TABLE_T *) table + ); + printf("%s:\n", session_tree_branch); + free(session_tree_branch); + + LIST_T *branch_mappings = + diffusion_branch_mapping_table_get_branch_mappings( + (DIFFUSION_BRANCH_MAPPING_TABLE_T *) table + ); + + int mappings_length = list_get_size(branch_mappings); + for (int i = 0; i < mappings_length; i++) { + DIFFUSION_BRANCH_MAPPING_T *mapping = list_get_data_indexed(branch_mappings, i); + + char *session_filter = diffusion_branch_mapping_get_session_filter(mapping); + char *topic_tree_branch = diffusion_branch_mapping_get_topic_tree_branch(mapping); + + printf("\t%s: %s\n", session_filter, topic_tree_branch); + free(session_filter); + free(topic_tree_branch); + } + diffusion_branch_mapping_table_free_branch_mappings(branch_mappings); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + UTILS_SESSION_TREES_MAPPING_T mappings_1[] = { + { .rule = "$Principal is 'admin'", .topic_path = "my/topic/path/for/admin" }, + { .rule = "$Principal is 'control'", .topic_path = "my/topic/path/for/control" }, + { .rule = "$Principal is ''", .topic_path = "my/topic/path/for/anonymous" } + }; + + utils_build_branch_mapping_table( + session, "my/personal/path", 3, mappings_1 + ); + + UTILS_SESSION_TREES_MAPPING_T mappings_2[] = { + { .rule = "$Transport is 'WEBSOCKET'", .topic_path = "my/alternate/path/for/websocket" }, + { .rule = "$Transport is 'HTTP_LONG_POLL'", .topic_path = "my/alternate/path/for/http" }, + { .rule = "$Transport is 'TCP'", .topic_path = "my/alternate/path/for/tcp" } + }; + + utils_build_branch_mapping_table( + session, "my/alternate/path", 3, mappings_2 + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_SESSION_TREES_GET_BRANCH_MAPPING_TABLE_PARAMS_T get_table_params_1 = { + .on_table_received = on_branch_mapping_table_received, + .on_error = on_error, + .session_tree_branch = "my/personal/path", + .context = coordinator + }; + + diffusion_session_trees_get_branch_mapping_table(session, get_table_params_1, NULL); + coordinator_wait(coordinator); + + DIFFUSION_SESSION_TREES_GET_BRANCH_MAPPING_TABLE_PARAMS_T get_table_params_2 = { + .on_table_received = on_branch_mapping_table_received, + .on_error = on_error, + .session_tree_branch = "my/alternate/path", + .context = coordinator + }; + + diffusion_session_trees_get_branch_mapping_table(session, get_table_params_2, NULL); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + } \ No newline at end of file diff --git a/c/examples/wrangling/session_trees/list_session_tree_branches_with_mappings.c b/c/examples/wrangling/session_trees/list_session_tree_branches_with_mappings.c new file mode 100644 index 00000000..df822336 --- /dev/null +++ b/c/examples/wrangling/session_trees/list_session_tree_branches_with_mappings.c @@ -0,0 +1,97 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_session_tree_branches_received( + const LIST_T *session_tree_branches, + void *context) +{ + int size = list_get_size(session_tree_branches); + printf("Session Tree Branches:\n"); + for (int i = 0; i < size; i++) { + char *session_tree_branch = list_get_data_indexed(session_tree_branches, i); + printf("\t%s\n", session_tree_branch); + } + + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + UTILS_SESSION_TREES_MAPPING_T mappings_1[] = { + { .rule = "$Principal is 'admin'", .topic_path = "my/topic/path/for/admin" }, + { .rule = "$Principal is 'control'", .topic_path = "my/topic/path/for/control" }, + { .rule = "$Principal is ''", .topic_path = "my/topic/path/for/anonymous" } + }; + + utils_build_branch_mapping_table( + session, "my/personal/path", 3, mappings_1 + ); + + UTILS_SESSION_TREES_MAPPING_T mappings_2[] = { + { .rule = "$Transport is 'WEBSOCKET'", .topic_path = "my/alternate/path/for/websocket" }, + { .rule = "$Transport is 'HTTP_LONG_POLL'", .topic_path = "my/alternate/path/for/http" }, + { .rule = "$Transport is 'TCP'", .topic_path = "my/alternate/path/for/tcp" } + }; + + utils_build_branch_mapping_table( + session, "my/alternate/path", 3, mappings_2 + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_SESSION_TREES_GET_SESSION_TREE_BRANCHES_PARAMS_T params = { + .on_session_tree_branches_received = on_session_tree_branches_received, + .on_error = on_error, + .context = coordinator + }; + + diffusion_session_trees_get_session_tree_branches(session, params, NULL); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + } \ No newline at end of file diff --git a/c/examples/wrangling/session_trees/put_and_remove_branch_mapping_table.c b/c/examples/wrangling/session_trees/put_and_remove_branch_mapping_table.c new file mode 100644 index 00000000..69852e94 --- /dev/null +++ b/c/examples/wrangling/session_trees/put_and_remove_branch_mapping_table.c @@ -0,0 +1,92 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_branch_mapping_table_set( + void *context) +{ + printf("Session tree mapping table and mappings removed.\n"); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + // Administrator + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + UTILS_SESSION_TREES_MAPPING_T mappings[] = { + { .rule = "$Principal is 'admin'", .topic_path = "my/topic/path/for/admin" }, + { .rule = "$Principal is 'control'", .topic_path = "my/topic/path/for/control" }, + { .rule = "$Principal is ''", .topic_path = "my/topic/path/for/anonymous" } + }; + + const char *topic_path = "my/personal/path"; + utils_build_branch_mapping_table( + session, topic_path, 3, mappings + ); + + // To remove a branch mapping table, set it to empty + DIFFUSION_BRANCH_MAPPING_TABLE_BUILDER_T *builder = + diffusion_branch_mapping_table_builder_init(); + + DIFFUSION_BRANCH_MAPPING_TABLE_T *table = + diffusion_branch_mapping_table_builder_create_table( + builder, (char *) topic_path + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_SESSION_TREES_PUT_BRANCH_MAPPING_TABLE_PARAMS_T params = { + .on_table_set = on_branch_mapping_table_set, + .on_error = on_error, + .table = table, + .context = coordinator + }; + diffusion_session_trees_put_branch_mapping_table(session, params, NULL); + coordinator_wait(coordinator); + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + diffusion_branch_mapping_table_free(table); + diffusion_branch_mapping_table_builder_free(builder); + } \ No newline at end of file diff --git a/c/examples/wrangling/session_trees/put_branch_mapping_table.c b/c/examples/wrangling/session_trees/put_branch_mapping_table.c new file mode 100644 index 00000000..337cc2f7 --- /dev/null +++ b/c/examples/wrangling/session_trees/put_branch_mapping_table.c @@ -0,0 +1,92 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_branch_mapping_table_set( + void *context) +{ + printf("Branch mapping table updated\n"); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/personal/path"; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + DIFFUSION_BRANCH_MAPPING_TABLE_BUILDER_T *builder = + diffusion_branch_mapping_table_builder_init(); + + diffusion_branch_mapping_table_builder_add_branch_mapping( + builder, "$Principal is 'admin'", "my/topic/path/for/admin" + ); + + diffusion_branch_mapping_table_builder_add_branch_mapping( + builder, "$Principal is 'control'", "my/topic/path/for/control" + ); + + diffusion_branch_mapping_table_builder_add_branch_mapping( + builder, "$Principal is ''", "my/topic/path/for/anonymous" + ); + + DIFFUSION_BRANCH_MAPPING_TABLE_T *table = + diffusion_branch_mapping_table_builder_create_table(builder, topic_path); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_SESSION_TREES_PUT_BRANCH_MAPPING_TABLE_PARAMS_T params = { + .on_table_set = on_branch_mapping_table_set, + .on_error = on_error, + .table = table, + .context = coordinator + }; + diffusion_session_trees_put_branch_mapping_table(session, params, NULL); + coordinator_wait(coordinator); + + + session_close(session, NULL); + session_free(session); + + coordinator_free(coordinator); + diffusion_branch_mapping_table_free(table); + diffusion_branch_mapping_table_builder_free(builder); + } \ No newline at end of file diff --git a/c/examples/wrangling/session_trees/use_case.c b/c/examples/wrangling/session_trees/use_case.c new file mode 100644 index 00000000..9979fbb7 --- /dev/null +++ b/c/examples/wrangling/session_trees/use_case.c @@ -0,0 +1,131 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_security_store_updated( + SESSION_T *session, + const LIST_T *error_report, + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + // Administrator + SESSION_T *admin_session = utils_open_session(url, "admin", "password"); + + utils_create_string_topic( + admin_session, "my/topic/path/for/admin", "Good morning Administrator" + ); + + utils_create_string_topic( + admin_session, "my/topic/path/for/control", "Good afternoon Control Client" + ); + + utils_create_string_topic( + admin_session, "my/topic/path/for/anonymous", "Good night Anonymous" + ); + + UTILS_SESSION_TREES_MAPPING_T mappings[] = { + { .rule = "$Principal is 'admin'", .topic_path = "my/topic/path/for/admin" }, + { .rule = "$Principal is 'control'", .topic_path = "my/topic/path/for/control" }, + { .rule = "$Principal is ''", .topic_path = "my/topic/path/for/anonymous" } + }; + + utils_build_branch_mapping_table( + admin_session, "my/personal/path", 3, mappings + ); + + VALUE_STREAM_T *admin_value_stream_ptr = + utils_subscribe(admin_session, "my/personal/path", DATATYPE_STRING); + + // Allow CLIENT role to read and select my/personal/path + SET_T *set_permissions = set_new(2); + set_add(set_permissions, &SECURITY_PATH_PERMISSIONS_TABLE[PATH_PERMISSION_SELECT_TOPIC]); + set_add(set_permissions, &SECURITY_PATH_PERMISSIONS_TABLE[PATH_PERMISSION_READ_TOPIC]); + + SCRIPT_T *script = script_create(); + update_security_store_path_permissions( + script, "CLIENT", "my/personal/path", set_permissions + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + const UPDATE_SECURITY_STORE_PARAMS_T params = { + .on_update = on_security_store_updated, + .on_error = on_error, + .update_script = script, + .context = coordinator + }; + + update_security_store(admin_session, params); + coordinator_wait(coordinator); + + script_free(script); + set_free(set_permissions); + + // Control Client + SESSION_T *control_session = utils_open_session(url, "control", "password"); + + VALUE_STREAM_T *control_value_stream_ptr = + utils_subscribe(control_session, "my/personal/path", DATATYPE_STRING); + + // Anonymous + SESSION_T *anonymous_session = utils_open_session(url, "", NULL); + + VALUE_STREAM_T *anonymous_value_stream_ptr = + utils_subscribe(anonymous_session, "my/personal/path", DATATYPE_STRING); + + // Sleep for a bit to see the notifications + sleep(2); + + + session_close(anonymous_session, NULL); + session_free(anonymous_session); + free(anonymous_value_stream_ptr); + + session_close(control_session, NULL); + session_free(control_session); + free(control_value_stream_ptr); + + session_close(admin_session, NULL); + session_free(admin_session); + free(admin_value_stream_ptr); + } \ No newline at end of file diff --git a/c/examples/wrangling/topic_views/api/add.c b/c/examples/wrangling/topic_views/api/add.c new file mode 100644 index 00000000..bcaf5608 --- /dev/null +++ b/c/examples/wrangling/topic_views/api/add.c @@ -0,0 +1,84 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_view_created( + const DIFFUSION_TOPIC_VIEW_T *topic_view, + void *context) +{ + char *name = diffusion_topic_view_get_name(topic_view); + printf("Topic view %s was created.\n", name); + free(name); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/topic/path"; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + topic_path, + "{\"diffusion\": \"data\"}" + ); + + char *topic_view_name = "topic_view_1"; + char *topic_view_specification = "map my/topic/path to views/"; + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_CREATE_TOPIC_VIEW_PARAMS_T create_topic_view_params = { + .view = topic_view_name, + .specification = topic_view_specification, + .on_topic_view_created = on_topic_view_created, + .on_error = on_error, + .context = coordinator + }; + diffusion_topic_views_create_topic_view(session, create_topic_view_params, NULL); + coordinator_wait(coordinator); + + + coordinator_free(coordinator); + + session_close(session, NULL); + session_free(session); + } \ No newline at end of file diff --git a/c/examples/wrangling/topic_views/api/list.c b/c/examples/wrangling/topic_views/api/list.c new file mode 100644 index 00000000..9bad7b1a --- /dev/null +++ b/c/examples/wrangling/topic_views/api/list.c @@ -0,0 +1,100 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_views_list_received( + const LIST_T *topic_views, + void *context) +{ + int total_views = list_get_size(topic_views); + printf("Received %d topic view(s)\n", total_views); + + for(int i = 0; i < total_views; i++) { + DIFFUSION_TOPIC_VIEW_T *topic_view = + list_get_data_indexed(topic_views, i); + + char *name = diffusion_topic_view_get_name(topic_view); + char *specification = diffusion_topic_view_get_specification(topic_view); + SET_T *roles_set = diffusion_topic_view_get_roles(topic_view); + char *roles = utils_set_to_string(roles_set, utils_print_string); + + printf("%s:\n\t%s\n\t%s\n", name, specification, roles); + + free(roles); + free(specification); + free(name); + set_free(roles_set); + } + + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/topic/path"; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + topic_path, + "{\"diffusion\": \"data\"}" + ); + + utils_create_topic_view( + session, + "topic_view_1", + "map my/topic/path to views/" + ); + + utils_create_topic_view( + session, + "topic_view_2", + "map my/topic/path/array to views/" + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_TOPIC_VIEWS_LIST_PARAMS_T list_topic_views_params = { + .on_topic_views_list = on_topic_views_list_received, + .context = coordinator + }; + + diffusion_topic_views_list_topic_views(session, list_topic_views_params, NULL); + coordinator_wait(coordinator); + + + coordinator_free(coordinator); + + session_close(session, NULL); + session_free(session); + } \ No newline at end of file diff --git a/c/examples/wrangling/topic_views/api/remove.c b/c/examples/wrangling/topic_views/api/remove.c new file mode 100644 index 00000000..626e95b5 --- /dev/null +++ b/c/examples/wrangling/topic_views/api/remove.c @@ -0,0 +1,129 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_views_list_received( + const LIST_T *topic_views, + void *context) +{ + int total_views = list_get_size(topic_views); + printf("Received %d topic view(s)\n", total_views); + + for(int i = 0; i < total_views; i++) { + DIFFUSION_TOPIC_VIEW_T *topic_view = + list_get_data_indexed(topic_views, i); + + char *name = diffusion_topic_view_get_name(topic_view); + char *specification = diffusion_topic_view_get_specification(topic_view); + SET_T *roles_set = diffusion_topic_view_get_roles(topic_view); + char *roles = utils_set_to_string(roles_set, utils_print_string); + + printf("%s:\n\t%s\n\t%s\n", name, specification, roles); + + free(roles); + free(specification); + free(name); + set_free(roles_set); + } + + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_topic_view_removed( + void *context) +{ + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + char *topic_path = "my/topic/path"; + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + topic_path, + "{\"diffusion\": \"data\"}" + ); + + utils_create_topic_view( + session, + "topic_view_1", + "map my/topic/path to views/" + ); + + utils_create_topic_view( + session, + "topic_view_2", + "map my/topic/path/array to views/" + ); + + COORDINATOR_T *coordinator = coordinator_init(); + + DIFFUSION_TOPIC_VIEWS_LIST_PARAMS_T list_topic_views_params = { + .on_topic_views_list = on_topic_views_list_received, + .context = coordinator + }; + + printf("Listing topic views before removal\n"); + diffusion_topic_views_list_topic_views(session, list_topic_views_params, NULL); + coordinator_wait(coordinator); + + DIFFUSION_REMOVE_TOPIC_VIEW_PARAMS_T remove_params = { + .view = "topic_view_1", + .on_topic_view_removed = on_topic_view_removed, + .on_error = on_error, + .context = coordinator + }; + diffusion_topic_views_remove_topic_view(session, remove_params, NULL); + coordinator_wait(coordinator); + + printf("Listing topic views after removal\n"); + diffusion_topic_views_list_topic_views(session, list_topic_views_params, NULL); + coordinator_wait(coordinator); + + + coordinator_free(coordinator); + + session_close(session, NULL); + session_free(session); + } \ No newline at end of file diff --git a/c/examples/wrangling/topic_views/dsl/expand_value.c b/c/examples/wrangling/topic_views/dsl/expand_value.c new file mode 100644 index 00000000..d64dc830 --- /dev/null +++ b/c/examples/wrangling/topic_views/dsl/expand_value.c @@ -0,0 +1,86 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_view_created( + const DIFFUSION_TOPIC_VIEW_T *topic_view, + void *context) +{ + char *name = diffusion_topic_view_get_name(topic_view); + printf("Topic view %s was created.\n", name); + free(name); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + "my/topic/path", + "{ \ + \"currencies\": [ \ + \"USD\", \ + \"GBP\", \ + \"EUR\", \ + \"CHF\" \ + ] \ + }" + ); + + const char *topic_selector = "?views//"; + VALUE_STREAM_T *value_stream_ptr = + utils_subscribe(session, topic_selector, DATATYPE_JSON); + + utils_create_topic_view( + session, + "topic_view_1", + "map my/topic/path to views/currency" + ); + + // Sleep for a bit to see the notifications + sleep(2); + + + session_close(session, NULL); + session_free(session); + free(value_stream_ptr); + } \ No newline at end of file diff --git a/c/examples/wrangling/topic_views/dsl/insert_transformations.c b/c/examples/wrangling/topic_views/dsl/insert_transformations.c new file mode 100644 index 00000000..ec336d4a --- /dev/null +++ b/c/examples/wrangling/topic_views/dsl/insert_transformations.c @@ -0,0 +1,80 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + "my/topic/path/original_cast", + "[ \ + \"Fred Flintstone\", \ + \"Wilma Flintstone\", \ + \"Barney Rubble\", \ + \"Betty Rubble\" \ + ]" + ); + + utils_create_json_topic( + session, + "my/topic/path/additional_cast/1", + "\"Pebbles Flintstone\"" + ); + + utils_create_json_topic( + session, + "my/topic/path/additional_cast/2", + "\"Bamm-Bamm Rubble\"" + ); + + const char *topic_selector = "?views//"; + VALUE_STREAM_T *value_stream_ptr = + utils_subscribe(session, topic_selector, DATATYPE_JSON); + + utils_create_topic_view( + session, + "topic_view_1", + "map my/topic/path/original_cast \ + to views/the_flintstones \ + insert my/topic/path/additional_cast/1 at /- \ + insert my/topic/path/additional_cast/2 at /-" + ); + + // Sleep for a bit to see the notifications + sleep(2); + + + session_close(session, NULL); + session_free(session); + free(value_stream_ptr); + } \ No newline at end of file diff --git a/c/examples/wrangling/topic_views/dsl/options/delay.c b/c/examples/wrangling/topic_views/dsl/options/delay.c new file mode 100644 index 00000000..b161b829 --- /dev/null +++ b/c/examples/wrangling/topic_views/dsl/options/delay.c @@ -0,0 +1,65 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + const char *topic_path = "my/topic/path"; + + utils_create_int64_topic( + session, topic_path, 0 + ); + + const char *topic_selector = "?.*//"; + VALUE_STREAM_T *value_stream_ptr = + utils_subscribe(session, topic_selector, DATATYPE_JSON); + + utils_create_topic_view( + session, + "topic_view_1", + "map my/topic/path to views/ delay by 5 seconds" + ); + + for (int i = 0; i < 15; i++) { + utils_set_int64_topic_value(session, topic_path, (int64_t) time(NULL)); + sleep(1); + } + + // Sleep for a bit to see the notifications + sleep(8); + + + session_close(session, NULL); + session_free(session); + free(value_stream_ptr); + } \ No newline at end of file diff --git a/c/examples/wrangling/topic_views/dsl/options/preserve_topics.c b/c/examples/wrangling/topic_views/dsl/options/preserve_topics.c new file mode 100644 index 00000000..8eeed9a8 --- /dev/null +++ b/c/examples/wrangling/topic_views/dsl/options/preserve_topics.c @@ -0,0 +1,87 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + "my/topic/path", + "{ \ + \"name\": \"Fred Flintstone\" \ + }" + ); + + const char *topic_selector = "?views//"; + VALUE_STREAM_T *value_stream_ptr = + utils_subscribe(session, topic_selector, DATATYPE_JSON); + + utils_create_topic_view( + session, + "topic_view_1", + "map my/topic/path to views/preserved/ preserve topics" + ); + + utils_create_topic_view( + session, + "topic_view_2", + "map my/topic/path to views/not_preserved/" + ); + // Sleep for a bit to see the notifications + sleep(2); + + utils_set_json_topic_value( + session, + "my/topic/path", + "{ \ + \"name\": \"Wilma Flintstone\" \ + }" + ); + // Sleep for a bit to see the notifications + sleep(2); + + utils_set_json_topic_value( + session, + "my/topic/path", + "{ \ + \"name\": \"Pebbles Flintstone\" \ + }" + ); + // Sleep for a bit to see the notifications + sleep(2); + + + session_close(session, NULL); + session_free(session); + free(value_stream_ptr); + } \ No newline at end of file diff --git a/c/examples/wrangling/topic_views/dsl/options/separator.c b/c/examples/wrangling/topic_views/dsl/options/separator.c new file mode 100644 index 00000000..ad54a410 --- /dev/null +++ b/c/examples/wrangling/topic_views/dsl/options/separator.c @@ -0,0 +1,78 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + "my/topic/path/1", + "{ \ + \"name\": \"Fred/Flintstone\" \ + }" + ); + + utils_create_json_topic( + session, + "my/topic/path/2", + "{ \ + \"name\": \"Wilma/Flintstone\" \ + }" + ); + + utils_create_json_topic( + session, + "my/topic/path/3", + "{ \ + \"name\": \"Pebbles/Flintstone\" \ + }" + ); + + const char *topic_selector = "?views//"; + VALUE_STREAM_T *value_stream_ptr = + utils_subscribe(session, topic_selector, DATATYPE_JSON); + + utils_create_topic_view( + session, + "topic_view_1", + "map ?my/topic/path// to views/ separator '_'" + ); + + // Sleep for a bit to see the notifications + sleep(2); + + + session_close(session, NULL); + session_free(session); + free(value_stream_ptr); + } \ No newline at end of file diff --git a/c/examples/wrangling/topic_views/dsl/options/throttle.c b/c/examples/wrangling/topic_views/dsl/options/throttle.c new file mode 100644 index 00000000..2d6c4564 --- /dev/null +++ b/c/examples/wrangling/topic_views/dsl/options/throttle.c @@ -0,0 +1,65 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + const char *topic_path = "my/topic/path"; + + utils_create_int64_topic( + session, topic_path, 0 + ); + + const char *topic_selector = "?.*//"; + VALUE_STREAM_T *value_stream_ptr = + utils_subscribe(session, topic_selector, DATATYPE_JSON); + + utils_create_topic_view( + session, + "topic_view_1", + "map my/topic/path to views/ throttle to 1 update every 3 seconds" + ); + + for (int i = 0; i < 15; i++) { + utils_set_int64_topic_value(session, topic_path, (int64_t) time(NULL)); + sleep(1); + } + + // Sleep for a bit to see the notifications + sleep(2); + + + session_close(session, NULL); + session_free(session); + free(value_stream_ptr); + } \ No newline at end of file diff --git a/c/examples/wrangling/topic_views/dsl/options/topic_property_mapping.c b/c/examples/wrangling/topic_views/dsl/options/topic_property_mapping.c new file mode 100644 index 00000000..ad1090dd --- /dev/null +++ b/c/examples/wrangling/topic_views/dsl/options/topic_property_mapping.c @@ -0,0 +1,68 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + "my/topic/path", + "[ \ + \"Fred Flintstone\", \ + \"Wilma Flintstone\", \ + \"Barney Rubble\", \ + \"Betty Rubble\" \ + ]" + ); + + const char *topic_selector = "?views//"; + VALUE_STREAM_T *value_stream_ptr = + utils_subscribe(session, topic_selector, DATATYPE_JSON); + + utils_create_topic_view( + session, + "topic_view_1", + "map ?my/topic/path// to views/ with properties \ + 'CONFLATION':'off', 'COMPRESSION':'false', 'DONT_RETAIN_VALUE':'true'" + ); + + // Sleep for a bit to see the notifications + sleep(2); + + utils_get_topic_properties(session, "?views//"); + + + session_close(session, NULL); + session_free(session); + free(value_stream_ptr); + } \ No newline at end of file diff --git a/c/examples/wrangling/topic_views/dsl/options/topic_type.c b/c/examples/wrangling/topic_views/dsl/options/topic_type.c new file mode 100644 index 00000000..742c4961 --- /dev/null +++ b/c/examples/wrangling/topic_views/dsl/options/topic_type.c @@ -0,0 +1,60 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + const char *topic_path = "my/topic/path"; + utils_create_int64_topic( + session, topic_path, 0 + ); + + utils_create_topic_view( + session, + "topic_view_1", + "map my/topic/path to views/archive/ type TIME_SERIES" + ); + + for (int i = 0; i < 15; i++) { + utils_set_int64_topic_value(session, topic_path, (int64_t) time(NULL)); + sleep(1); + } + + utils_time_series_range_query_int64( + session, "views/archive/my/topic/path" + ); + + + session_close(session, NULL); + session_free(session); + } \ No newline at end of file diff --git a/c/examples/wrangling/topic_views/dsl/options/topic_value.c b/c/examples/wrangling/topic_views/dsl/options/topic_value.c new file mode 100644 index 00000000..21890543 --- /dev/null +++ b/c/examples/wrangling/topic_views/dsl/options/topic_value.c @@ -0,0 +1,66 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + "my/topic/path", + "{ \ + \"account\": \"1234\", \ + \"balance\": { \ + \"amount\": 12.57, \ + \"currency\": \"USD\" \ + } \ + }" + ); + + const char *topic_selector = "?views//"; + VALUE_STREAM_T *value_stream_ptr = + utils_subscribe(session, topic_selector, DATATYPE_JSON); + + utils_create_topic_view( + session, + "topic_view_1", + "map my/topic/path to views/ as " + ); + + // Sleep for a bit to see the notifications + sleep(2); + + + session_close(session, NULL); + session_free(session); + free(value_stream_ptr); + } \ No newline at end of file diff --git a/c/examples/wrangling/topic_views/dsl/patch_transformations/add.c b/c/examples/wrangling/topic_views/dsl/patch_transformations/add.c new file mode 100644 index 00000000..65bda0fd --- /dev/null +++ b/c/examples/wrangling/topic_views/dsl/patch_transformations/add.c @@ -0,0 +1,69 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + "my/topic/path", + "{ \ + \"Fred\": \"Flintstone\", \ + \"Barney\": \"Rubble\" \ + }" + ); + + const char *topic_selector = "?views//"; + VALUE_STREAM_T *value_stream_ptr = + utils_subscribe(session, topic_selector, DATATYPE_JSON); + + utils_create_topic_view( + session, + "topic_view_1", + "map ?my/topic/path// to views/ patch '[ \ + { \ + \"op\": \"add\", \ + \"path\": \"/George\", \ + \"value\": \"Jetson\" \ + } \ + ]'" + ); + + // Sleep for a bit to see the notifications + sleep(2); + + + session_close(session, NULL); + session_free(session); + free(value_stream_ptr); + } \ No newline at end of file diff --git a/c/examples/wrangling/topic_views/dsl/patch_transformations/copy.c b/c/examples/wrangling/topic_views/dsl/patch_transformations/copy.c new file mode 100644 index 00000000..196a0f8f --- /dev/null +++ b/c/examples/wrangling/topic_views/dsl/patch_transformations/copy.c @@ -0,0 +1,74 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + "my/topic/path", + "{ \ + \"Meet the Flintstones\": { \ + \"Fred\": \"Flintstone\", \ + \"Barney\": \"Rubble\" \ + }, \ + \"The Jetsons\": { \ + \"George\": \"Jetson\" \ + } \ + }" + ); + + const char *topic_selector = "?views//"; + VALUE_STREAM_T *value_stream_ptr = + utils_subscribe(session, topic_selector, DATATYPE_JSON); + + utils_create_topic_view( + session, + "topic_view_1", + "map ?my/topic/path// to views/ patch '[ \ + { \ + \"op\": \"copy\", \ + \"from\": \"/Meet the Flintstones/Fred\", \ + \"path\": \"/The Jetsons/Fred\" \ + } \ + ]'" + ); + + // Sleep for a bit to see the notifications + sleep(2); + + + session_close(session, NULL); + session_free(session); + free(value_stream_ptr); + } \ No newline at end of file diff --git a/c/examples/wrangling/topic_views/dsl/patch_transformations/move.c b/c/examples/wrangling/topic_views/dsl/patch_transformations/move.c new file mode 100644 index 00000000..8572b27c --- /dev/null +++ b/c/examples/wrangling/topic_views/dsl/patch_transformations/move.c @@ -0,0 +1,80 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + "my/topic/path", + "{ \ + \"Fred\": \"Flintstone\", \ + \"Barney\": \"Rubble\", \ + \"George\": \"Jetson\" \ + }" + ); + + const char *topic_selector = "?views//"; + VALUE_STREAM_T *value_stream_ptr = + utils_subscribe(session, topic_selector, DATATYPE_JSON); + + utils_create_topic_view( + session, + "topic_view_1", + "map ?my/topic/path// to views/ patch '[ \ + { \ + \"op\": \"move\", \ + \"from\": \"/Fred\", \ + \"path\": \"/Meet The Flintstones~1Fred\" \ + }, \ + { \ + \"op\": \"move\", \ + \"from\": \"/Barney\", \ + \"path\": \"/Meet The Flintstones~1Barney\" \ + }, \ + { \ + \"op\": \"move\", \ + \"from\": \"/George\", \ + \"path\": \"/The Jetsons~1George\" \ + } \ + ]'" + ); + + // Sleep for a bit to see the notifications + sleep(2); + + + session_close(session, NULL); + session_free(session); + free(value_stream_ptr); + } \ No newline at end of file diff --git a/c/examples/wrangling/topic_views/dsl/patch_transformations/remove.c b/c/examples/wrangling/topic_views/dsl/patch_transformations/remove.c new file mode 100644 index 00000000..9c91c724 --- /dev/null +++ b/c/examples/wrangling/topic_views/dsl/patch_transformations/remove.c @@ -0,0 +1,69 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + "my/topic/path", + "{ \ + \"Fred\": \"Flintstone\", \ + \"Barney\": \"Rubble\", \ + \"George\": \"Jetson\" \ + }" + ); + + const char *topic_selector = "?views//"; + VALUE_STREAM_T *value_stream_ptr = + utils_subscribe(session, topic_selector, DATATYPE_JSON); + + utils_create_topic_view( + session, + "topic_view_1", + "map ?my/topic/path// to views/ patch '[ \ + { \ + \"op\": \"remove\", \ + \"path\": \"/George\" \ + } \ + ]'" + ); + + // Sleep for a bit to see the notifications + sleep(2); + + + session_close(session, NULL); + session_free(session); + free(value_stream_ptr); + } \ No newline at end of file diff --git a/c/examples/wrangling/topic_views/dsl/patch_transformations/replace.c b/c/examples/wrangling/topic_views/dsl/patch_transformations/replace.c new file mode 100644 index 00000000..c7bc81c6 --- /dev/null +++ b/c/examples/wrangling/topic_views/dsl/patch_transformations/replace.c @@ -0,0 +1,70 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + "my/topic/path", + "{ \ + \"Fred\": \"Flintstone\", \ + \"Barney\": \"Rubble\", \ + \"George\": \"Jetson\" \ + }" + ); + + const char *topic_selector = "?views//"; + VALUE_STREAM_T *value_stream_ptr = + utils_subscribe(session, topic_selector, DATATYPE_JSON); + + utils_create_topic_view( + session, + "topic_view_1", + "map ?my/topic/path// to views/ patch '[ \ + { \ + \"op\": \"replace\", \ + \"path\": \"/George\", \ + \"value\": \"Bedrock\" \ + } \ + ]'" + ); + + // Sleep for a bit to see the notifications + sleep(2); + + + session_close(session, NULL); + session_free(session); + free(value_stream_ptr); + } \ No newline at end of file diff --git a/c/examples/wrangling/topic_views/dsl/patch_transformations/test.c b/c/examples/wrangling/topic_views/dsl/patch_transformations/test.c new file mode 100644 index 00000000..8d3bb688 --- /dev/null +++ b/c/examples/wrangling/topic_views/dsl/patch_transformations/test.c @@ -0,0 +1,70 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + "my/topic/path", + "{ \ + \"Fred\": \"Flintstone\", \ + \"Barney\": \"Rubble\", \ + \"George\": \"Jetson\" \ + }" + ); + + const char *topic_selector = "?views//"; + VALUE_STREAM_T *value_stream_ptr = + utils_subscribe(session, topic_selector, DATATYPE_JSON); + + utils_create_topic_view( + session, + "topic_view_1", + "map ?my/topic/path// to views/ patch '[ \ + { \ + \"op\": \"test\", \ + \"path\": \"/Fred\", \ + \"value\": \"Flintstone\" \ + } \ + ]'" + ); + + // Sleep for a bit to see the notifications + sleep(2); + + + session_close(session, NULL); + session_free(session); + free(value_stream_ptr); + } \ No newline at end of file diff --git a/c/examples/wrangling/topic_views/dsl/process_transformations/continue.c b/c/examples/wrangling/topic_views/dsl/process_transformations/continue.c new file mode 100644 index 00000000..0fd92ccc --- /dev/null +++ b/c/examples/wrangling/topic_views/dsl/process_transformations/continue.c @@ -0,0 +1,77 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + "my/topic/path/1", + "{ \ + \"name\": \"APPL\", \ + \"quantity\": 100, \ + \"price_per_share\": 12.34 \ + }" + ); + + utils_create_json_topic( + session, + "my/topic/path/2", + "{ \ + \"name\": \"AMZN\", \ + \"quantity\": 256, \ + \"price_per_share\": 87.65 \ + }" + ); + + const char *topic_selector = "?views//"; + VALUE_STREAM_T *value_stream_ptr = + utils_subscribe(session, topic_selector, DATATYPE_JSON); + + utils_create_topic_view( + session, + "topic_view_1", + "map ?my/topic/path// to views/ \ + process { \ + if '/price_per_share > 20' continue \ + }" + ); + + // Sleep for a bit to see the notifications + sleep(2); + + + session_close(session, NULL); + session_free(session); + free(value_stream_ptr); + } \ No newline at end of file diff --git a/c/examples/wrangling/topic_views/dsl/process_transformations/remove.c b/c/examples/wrangling/topic_views/dsl/process_transformations/remove.c new file mode 100644 index 00000000..78a9e0b0 --- /dev/null +++ b/c/examples/wrangling/topic_views/dsl/process_transformations/remove.c @@ -0,0 +1,79 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + "my/topic/path/1", + "{ \ + \"name\": \"APPL\", \ + \"quantity\": 100, \ + \"price_per_share\": 12.34 \ + }" + ); + + utils_create_json_topic( + session, + "my/topic/path/2", + "{ \ + \"name\": \"AMZN\", \ + \"quantity\": 256, \ + \"price_per_share\": 87.65 \ + }" + ); + + const char *topic_selector = "?views//"; + VALUE_STREAM_T *value_stream_ptr = + utils_subscribe(session, topic_selector, DATATYPE_JSON); + + utils_create_topic_view( + session, + "topic_view_1", + "map ?my/topic/path// to views/ \ + process { \ + set(/total, calc '/quantity * /price_per_share'); \ + remove(/quantity); \ + remove(/price_per_share) \ + }" + ); + + // Sleep for a bit to see the notifications + sleep(2); + + + session_close(session, NULL); + session_free(session); + free(value_stream_ptr); + } \ No newline at end of file diff --git a/c/examples/wrangling/topic_views/dsl/process_transformations/set.c b/c/examples/wrangling/topic_views/dsl/process_transformations/set.c new file mode 100644 index 00000000..a9620dd2 --- /dev/null +++ b/c/examples/wrangling/topic_views/dsl/process_transformations/set.c @@ -0,0 +1,87 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + "my/topic/path/1", + "{ \ + \"account\": \"1234\", \ + \"balance\": { \ + \"amount\": 12.57, \ + \"currency\": \"USD\" \ + } \ + }" + ); + + utils_create_json_topic( + session, + "my/topic/path/2", + "{ \ + \"account\": \"5678\", \ + \"balance\": { \ + \"amount\": 98.76, \ + \"currency\": \"USD\" \ + } \ + }" + ); + + const char *topic_selector = "?views//"; + VALUE_STREAM_T *value_stream_ptr = + utils_subscribe(session, topic_selector, DATATYPE_JSON); + + utils_create_topic_view( + session, + "topic_view_1", + "map ?my/topic/path// to views/ \ + process { \ + if '/balance/amount > 20' \ + set(/tier, 1) \ + else \ + set(/tier, 2) \ + } \ + process { \ + set(/balance/amount_in_cents, calc '/balance/amount * 100') \ + }" + ); + + // Sleep for a bit to see the notifications + sleep(2); + + + session_close(session, NULL); + session_free(session); + free(value_stream_ptr); + } \ No newline at end of file diff --git a/c/examples/wrangling/topic_views/dsl/remote_topic_view.c b/c/examples/wrangling/topic_views/dsl/remote_topic_view.c new file mode 100644 index 00000000..94f55482 --- /dev/null +++ b/c/examples/wrangling/topic_views/dsl/remote_topic_view.c @@ -0,0 +1,80 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_view_created( + const DIFFUSION_TOPIC_VIEW_T *topic_view, + void *context) +{ + char *name = diffusion_topic_view_get_name(topic_view); + printf("Topic view %s was created.\n", name); + free(name); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + + SESSION_T *session = utils_open_session(url, "admin", "password"); + + HASH_NUM_T *connection_options = hash_num_new(5); + hash_num_add(connection_options, DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_RECONNECTION_TIMEOUT, "120000"); + hash_num_add(connection_options, DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_MAXIMUM_QUEUE_SIZE, "1000"); + hash_num_add(connection_options, DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_CONNECTION_TIMEOUT, "15000"); + + utils_create_remote_server( + session, + "Remote Server 1", + "ws://new.server.url.com", + "admin", + "password", + connection_options + ); + hash_num_free(connection_options, NULL); + + utils_create_topic_view( + session, + "remote_topic_view_1", + "map my/topic/path from 'Remote Server 1' to views/remote/" + ); + + + session_close(session, NULL); + session_free(session); + + } \ No newline at end of file diff --git a/c/examples/wrangling/topic_views/dsl/scalar_directive.c b/c/examples/wrangling/topic_views/dsl/scalar_directive.c new file mode 100644 index 00000000..589a16af --- /dev/null +++ b/c/examples/wrangling/topic_views/dsl/scalar_directive.c @@ -0,0 +1,85 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_view_created( + const DIFFUSION_TOPIC_VIEW_T *topic_view, + void *context) +{ + char *name = diffusion_topic_view_get_name(topic_view); + printf("Topic view %s was created.\n", name); + free(name); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + "my/topic/path", + "{ \ + \"account\": \"1234\", \ + \"balance\": { \ + \"amount\": 12.57, \ + \"currency\": \"USD\" \ + } \ + }" + ); + + const char *topic_selector = "?views//"; + VALUE_STREAM_T *value_stream_ptr = + utils_subscribe(session, topic_selector, DATATYPE_JSON); + + utils_create_topic_view( + session, + "topic_view_1", + "map my/topic/path to views/currency//account/" + ); + + // Sleep for a bit to see the notifications + sleep(2); + + + session_close(session, NULL); + session_free(session); + free(value_stream_ptr); + } \ No newline at end of file diff --git a/c/examples/wrangling/topic_views/dsl/source_path_directive.c b/c/examples/wrangling/topic_views/dsl/source_path_directive.c new file mode 100644 index 00000000..3bf43f0f --- /dev/null +++ b/c/examples/wrangling/topic_views/dsl/source_path_directive.c @@ -0,0 +1,97 @@ +/** + * Copyright © 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This example is written in C99. Please use an appropriate C99 capable compiler + */ + +#include +#include +#include + +#include "diffusion.h" +#include "utils.h" + + +static int on_topic_view_created( + const DIFFUSION_TOPIC_VIEW_T *topic_view, + void *context) +{ + char *name = diffusion_topic_view_get_name(topic_view); + printf("Topic view %s was created.\n", name); + free(name); + coordinator_broadcast((COORDINATOR_T *) context); + return HANDLER_SUCCESS; +} + +static int on_error( + SESSION_T *session, + const DIFFUSION_ERROR_T *error) +{ + printf("On error: %s\n", error->message); + return HANDLER_SUCCESS; +} + + +void run_example( + const char *url, + const char *principal, + CREDENTIALS_T *credentials) +{ + + SESSION_T *session = session_create( + url, principal, credentials, NULL, NULL, NULL + ); + + utils_create_json_topic( + session, + "a/b/c/d/e/f/g", + "{ \ + \"account\": \"1234\", \ + \"balance\": { \ + \"amount\": 12.57, \ + \"currency\": \"USD\" \ + } \ + }" + ); + + const char *topic_selector = "?views//"; + VALUE_STREAM_T *value_stream_ptr = + utils_subscribe(session, topic_selector, DATATYPE_JSON); + + utils_create_topic_view( + session, + "topic_view_1", + "map a/b/c/d/e/f/g to views/" + ); + + utils_create_topic_view( + session, + "topic_view_2", + "map a/b/c/d/e/f/g to views/" + ); + + utils_create_topic_view( + session, + "topic_view_3", + "map a/b/c/d/e/f/g to views/" + ); + + // Sleep for a bit to see the notifications + sleep(2); + + + session_close(session, NULL); + session_free(session); + free(value_stream_ptr); + } \ No newline at end of file diff --git a/c/features/authentication_control/auth-service.c b/c/features/authentication_control/auth-service.c deleted file mode 100644 index 0c51bc49..00000000 --- a/c/features/authentication_control/auth-service.c +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Copyright © 2014 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 5.0 - */ - -/* - * Diffusion can be configured to delegate authentication requests to - * an external handler. This program provides an authentication - * handler to demonstrate this feature. A detailed description of - * security and authentication handlers can be found in the Diffusion - * user manual. - * - * Authentication handlers are registered with a name, which is typically specified in - * Server.xml - * - * Two handler names are provided by Diffusion and Diffusion Cloud by default; - * before-system-handler and after-system-handler, and additional - * handlers may be specified for Diffusion through the Server.xml file - * and an accompanying Java class that implements the - * AuthenticationHandler interface. - * - * This control authentication handler connects to Diffusion and attempts - * to register itself with a user-supplied name, which should match the name - * configured in Server.xml. - * - * The default behavior is to install as the "before-system-handler", - * which means that it will intercept authentication requests before - * Diffusion has a chance to act on them. - * - * It will: - *
    - *
  • Deny all anonymous connections
  • - *
  • Allow connections where the principal and credentials (i.e., username and password) match some hardcoded values
  • - *
  • Abstain from all other decisions, thereby letting Diffusion and other authentication handlers decide what to do.
  • - *
- */ - -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" -#include "conversation.h" - - -struct user_credentials_s { - const char *username; - const char *password; -}; - -// Username/password pairs that this handler accepts. -static const struct user_credentials_s USERS[] = { - { "fish", "chips" }, - { "ham", "eggs" }, - { NULL, NULL } -}; - - -DIFFUSION_REGISTRATION_T *g_registration = NULL; - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'n', "name", "Name under which to register the authorisation handler", ARG_OPTIONAL, ARG_HAS_VALUE, "before-system-handler"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - END_OF_ARG_OPTS -}; - -// When the authenticator handler is active, this function will be called. -static int on_authenticator_active( - SESSION_T *session, - const DIFFUSION_REGISTRATION_T *registration) -{ - g_registration = diffusion_registration_dup(registration); - - printf("Registered authentication handler\n"); - return HANDLER_SUCCESS; -} - - -// When the authenticator handler is closed, this function will be called. -static void on_authenticator_close() -{ - printf("Closed authentication handler\n"); -} - -/* - * This is the function that is called when authentication has been delegated - * from Diffusion. - * - * The available methods for an authentication response are: - * diffusion_authenticator_allow: The user is authenticated without user-defined - * properties - * diffusion_authenticator_allow_with_properties: The user is authenticated with - * modifications to the session properties. - * diffusion_authenticator_abstain: Allow another handler to make the decision - * diffusion_authenticator_deny: The user is NOT authenticated - * The response may return one of three values via the response parameter: - * - * The handler should return HANDLER_SUCCESS in all cases, unless an actual - * error occurs during the authentication process (in which case, - * HANDLER_FAILURE is appropriate). - */ -static int on_authenticator_authenticate( - SESSION_T *session, - const char *principal, - const CREDENTIALS_T *credentials, - const HASH_T *session_properties, - const HASH_T *proposed_session_properties, - const DIFFUSION_AUTHENTICATOR_T *authenticator) -{ - // No credentials, or not password type. We're not an authority for - // this type of authentication so abstain in case some other registered - // authentication handler can deal with the request. - if(credentials == NULL) { - printf("No credentials specified, abstaining\n"); - diffusion_authenticator_abstain(session, authenticator, NULL); - return HANDLER_SUCCESS; - } - if(credentials->type != PLAIN_PASSWORD) { - printf("Credentials are not PLAIN_PASSWORD, abstaining\n"); - diffusion_authenticator_abstain(session, authenticator, NULL); - return HANDLER_SUCCESS; - } - - printf("principal = %s\n", principal); - printf("credentials = %*s\n", - (int)credentials->data->len, - credentials->data->data); - - if(principal == NULL || strlen(principal) == 0) { - printf("Denying anonymous connection (no principal)\n"); - // Deny anonymous connections - diffusion_authenticator_deny(session, authenticator, NULL); - return HANDLER_SUCCESS; - } - - char *password = malloc(credentials->data->len + 1); - memmove(password, credentials->data->data, credentials->data->len); - password[credentials->data->len] = '\0'; - - int auth_decided = 0; - int i = 0; - while(USERS[i].username != NULL) { - - printf("Checking username %s vs %s\n", principal, USERS[i].username); - printf(" and password %s vs %s\n", password, USERS[i].password); - - if(strcmp(USERS[i].username, principal) == 0 && - strcmp(USERS[i].password, password) == 0) { - - puts("Allowed"); - diffusion_authenticator_allow(session, authenticator, NULL); - auth_decided = 1; - break; - } - i++; - } - - free(password); - - if(auth_decided == 0) { - puts("Abstained"); - diffusion_authenticator_abstain(session, authenticator, NULL); - } - return HANDLER_SUCCESS; -} - - -int main(int argc, char** argv) -{ - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if (options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *name = hash_get(options, "name"); - const char *principal = hash_get(options, "principal"); - const char *password = hash_get(options, "credentials"); - - CREDENTIALS_T *credentials = NULL; - if (password != NULL) { - credentials = credentials_create_password(password); - } - - /* - * Create a session with Diffusion. - */ - puts("Creating session"); - DIFFUSION_ERROR_T error = { 0 }; - SESSION_T *session = session_create(url, principal, credentials, NULL, NULL, &error); - if (session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - // Register the authentication handler. - DIFFUSION_AUTHENTICATION_HANDLER_T handler = { - .handler_name = (char *) name, - .on_active = on_authenticator_active, - .on_authenticate = on_authenticator_authenticate, - .on_close = on_authenticator_close - }; - - DIFFUSION_AUTHENTICATION_HANDLER_PARAMS_T params = { - .handler = &handler - }; - - puts("Setting authentication handler"); - diffusion_set_authentication_handler(session, params); - - // Wait a while before moving on to deregistration. - sleep(30); - - // Deregister the authentication handler. - printf("Closing authentication handler\n"); - diffusion_registration_close(session, g_registration); - - session_close(session, NULL); - session_free(session); - hash_free(options, NULL, free); - credentials_free(credentials); - diffusion_registration_free(g_registration); - g_registration = NULL; - - return EXIT_SUCCESS; -} diff --git a/c/features/client_control/change-roles-with-filter.c b/c/features/client_control/change-roles-with-filter.c deleted file mode 100644 index 02f78dba..00000000 --- a/c/features/client_control/change-roles-with-filter.c +++ /dev/null @@ -1,150 +0,0 @@ -/** - * Copyright © 2021 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.7 - */ - -/* - * This example shows how roles can be changed during an active session. - */ - -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "client"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - END_OF_ARG_OPTS -}; - - -// Callback to display that the roles has been successfully changed. -static int on_roles_changed_with_filter( - int number_of_matching_sessions, - void *context) -{ - printf("Successfully changed roles, affecting %d session(s).\n", number_of_matching_sessions); - return HANDLER_SUCCESS; -} - - -// Callback to display an error when attempting to change roles. -static int on_error( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("Failed to change roles: [%d] %s\n", error->code, diffusion_error_str(error->code)); - return HANDLER_SUCCESS; -} - - -int main(int argc, char** argv) -{ - // Standard command-line parsing. - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - const char *password = hash_get(options, "credentials"); - - // Create a control session with Diffusion. - CREDENTIALS_T *control_credentials = - credentials_create_password("password"); - - DIFFUSION_SESSION_FACTORY_T *session_factory = diffusion_session_factory_init(); - diffusion_session_factory_principal(session_factory, "control"); - diffusion_session_factory_credentials(session_factory, control_credentials); - - SESSION_T *control_session = session_create_with_session_factory(session_factory, url); - if (control_session == NULL) { - fprintf(stderr, "Failed to create control session\n"); - return EXIT_FAILURE; - } - - // Create multiple normal sessions with Diffusion, using `client` as Principal - CREDENTIALS_T *credentials = credentials_create_password(password); - - DIFFUSION_SESSION_FACTORY_T *client_session_factory = diffusion_session_factory_init(); - diffusion_session_factory_principal(client_session_factory, principal); - diffusion_session_factory_credentials(client_session_factory, credentials); - - int totalSessions = 3; - SESSION_T **sessions = calloc(totalSessions, sizeof(SESSION_T*)); - - for (int i = 0; i < totalSessions; i++) { - sessions[i] = session_create_with_session_factory(client_session_factory, url); - if (sessions[i] == NULL) { - fprintf(stderr, "Failed to create normal session %d\n", i); - return EXIT_FAILURE; - } - } - - SET_T *roles_to_add = set_new_string(1); - set_add(roles_to_add, "NEW_CLIENT_ROLE"); - - DIFFUSION_CHANGE_ROLES_WITH_FILTER_PARAMS_T params = { - .filter = "$Principal EQ 'client'", - .roles_to_remove = NULL, - .roles_to_add = roles_to_add, - .on_roles_changed = on_roles_changed_with_filter, - .on_error = on_error - }; - - DIFFUSION_API_ERROR api_error; - diffusion_change_roles_with_filter(control_session, params, &api_error); - - // Wait for a couple of seconds. - sleep(2); - - puts("Closing sessions"); - - // Close the connections and free resources - session_close(control_session, NULL); - session_free(control_session); - - for(int i = 0; i < totalSessions; i++) { - session_close(sessions[i], NULL); - session_free(sessions[i]); - } - free(sessions); - - set_free(roles_to_add); - credentials_free(control_credentials); - credentials_free(credentials); - hash_free(options, NULL, free); - - diffusion_session_factory_free(client_session_factory); - diffusion_session_factory_free(session_factory); - - return EXIT_SUCCESS; -} diff --git a/c/features/client_control/change-roles-with-session.c b/c/features/client_control/change-roles-with-session.c deleted file mode 100644 index 02868f66..00000000 --- a/c/features/client_control/change-roles-with-session.c +++ /dev/null @@ -1,146 +0,0 @@ -/** - * Copyright © 2021 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.7 - */ - -/* - * This example shows how roles can be changed during an active session. - */ - -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "client"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - END_OF_ARG_OPTS -}; - - -/* - * Callback to display that the roles have been successfully changed. - */ -static int on_roles_changed(void *context) -{ - printf("Successfully changed roles.\n"); - return HANDLER_SUCCESS; -} - - -/* - * Callback to display an error when attempting to change roles. - */ -static int on_error( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("Failed to change roles: [%d] %s\n", error->code, diffusion_error_str(error->code)); - return HANDLER_SUCCESS; -} - - -int main(int argc, char** argv) -{ - // Standard command-line parsing. - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - const char *password = hash_get(options, "credentials"); - - // Create a control session with Diffusion. - CREDENTIALS_T *control_credentials = - credentials_create_password("password"); - - DIFFUSION_SESSION_FACTORY_T *session_factory = diffusion_session_factory_init(); - diffusion_session_factory_principal(session_factory, "control"); - diffusion_session_factory_credentials(session_factory, control_credentials); - - SESSION_T *control_session = session_create_with_session_factory(session_factory, url); - if (control_session == NULL) { - fprintf(stderr, "Failed to create control session\n"); - return EXIT_FAILURE; - } - - // Create normal session with Diffusion, using `client` as Principal - CREDENTIALS_T *credentials = credentials_create_password(password); - - DIFFUSION_SESSION_FACTORY_T *client_session_factory = diffusion_session_factory_init(); - diffusion_session_factory_principal(client_session_factory, principal); - diffusion_session_factory_credentials(client_session_factory, credentials); - - SESSION_T *normal_session = session_create_with_session_factory(client_session_factory, url); - if (normal_session == NULL) { - fprintf(stderr, "Failed to create normal session\n"); - return EXIT_FAILURE; - } - - SET_T *roles_to_add = set_new_string(1); - set_add(roles_to_add, "AUTHENTICATION_HANDLER"); - - DIFFUSION_CHANGE_ROLES_WITH_SESSION_ID_PARAMS_T params = { - .session_id = normal_session->id, - .roles_to_remove = NULL, - .roles_to_add = roles_to_add, - .on_roles_changed = on_roles_changed, - .on_error = on_error - }; - - DIFFUSION_API_ERROR api_error; - diffusion_change_roles_with_session_id(control_session, params, &api_error); - - // Wait for a couple of seconds. - sleep(5); - - puts("Closing session"); - - // Close the connections and free resources - session_close(normal_session, NULL); - session_free(normal_session); - - session_close(control_session, NULL); - session_free(control_session); - - set_free(roles_to_add); - - credentials_free(control_credentials); - credentials_free(credentials); - - hash_free(options, NULL, free); - - diffusion_session_factory_free(client_session_factory); - diffusion_session_factory_free(session_factory); - - return EXIT_SUCCESS; -} diff --git a/c/features/client_control/close-with-filter.c b/c/features/client_control/close-with-filter.c deleted file mode 100644 index f885249c..00000000 --- a/c/features/client_control/close-with-filter.c +++ /dev/null @@ -1,144 +0,0 @@ -/** - * Copyright © 2021 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.7 - */ - -/* - * This example shows how to close a session via a control session using - * a session properties filter. - */ - -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "client"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - END_OF_ARG_OPTS -}; - - -// Callback to indicate that the affected sessions by the filter have been closed. -static int on_clients_closed( - int selected, - void *context) -{ - printf("%d session(s) closed\n", selected); - return HANDLER_SUCCESS; -} - - -// Callback to display an error when attempting to close a session. -static int on_error( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("Failed to close session(s): [%d] %s\n", error->code, diffusion_error_str(error->code)); - return HANDLER_SUCCESS; -} - - -int main(int argc, char** argv) -{ - // Standard command-line parsing. - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - const char *password = hash_get(options, "credentials"); - - // Create a control session with Diffusion. - CREDENTIALS_T *control_credentials = - credentials_create_password("password"); - - DIFFUSION_SESSION_FACTORY_T *session_factory = diffusion_session_factory_init(); - diffusion_session_factory_principal(session_factory, "control"); - diffusion_session_factory_credentials(session_factory, control_credentials); - - SESSION_T *control_session = session_create_with_session_factory(session_factory, url); - if (control_session == NULL) { - fprintf(stderr, "Failed to create control session\n"); - return EXIT_FAILURE; - } - - // Create multiple normal sessions with Diffusion, using `client` as Principal - CREDENTIALS_T *credentials = credentials_create_password(password); - - DIFFUSION_SESSION_FACTORY_T *client_session_factory = diffusion_session_factory_init(); - diffusion_session_factory_principal(client_session_factory, principal); - diffusion_session_factory_credentials(client_session_factory, credentials); - - int totalSessions = 3; - SESSION_T **sessions = calloc(totalSessions, sizeof(SESSION_T*)); - - for (int i = 0; i < totalSessions; i++) { - sessions[i] = session_create_with_session_factory(client_session_factory, url); - if (sessions[i] == NULL) { - fprintf(stderr, "Failed to create normal session %d\n", i); - return EXIT_FAILURE; - } - } - - // Close normal sessions using control session and diffusion_client_close_with_filter - DIFFUSION_CLIENT_CLOSE_WITH_FILTER_PARAMS_T params = { - .filter = "$Principal EQ 'client'", - .on_clients_closed = on_clients_closed, - .on_error = on_error - }; - - DIFFUSION_API_ERROR api_error; - diffusion_client_close_with_filter(control_session, params, &api_error); - - // Wait for a couple of seconds. - sleep(2); - - puts("Closing sessions"); - - // Close the connections and free resources. - session_close(control_session, NULL); - session_free(control_session); - - for(int i = 0; i < totalSessions; i++) { - session_free(sessions[i]); - } - free(sessions); - - diffusion_session_factory_free(client_session_factory); - diffusion_session_factory_free(session_factory); - credentials_free(control_credentials); - credentials_free(credentials); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/c/features/client_control/close-with-session.c b/c/features/client_control/close-with-session.c deleted file mode 100644 index e03aae88..00000000 --- a/c/features/client_control/close-with-session.c +++ /dev/null @@ -1,132 +0,0 @@ -/** - * Copyright © 2021 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.7 - */ - -/* - * This example shows how to close a session via a control session. - */ - -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "client"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - END_OF_ARG_OPTS -}; - - -// Callback to indicate that the session has been closed. -static int on_closed(void *context) -{ - printf("Session closed\n"); - return HANDLER_SUCCESS; -} - - -// Callback to display an error when attempting to close a session. -static int on_error( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("Failed to closed session: [%d] %s\n", error->code, diffusion_error_str(error->code)); - return HANDLER_SUCCESS; -} - - -int main(int argc, char** argv) -{ - // Standard command-line parsing. - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - const char *password = hash_get(options, "credentials"); - - // Create a control session with Diffusion. - CREDENTIALS_T *control_credentials = - credentials_create_password("password"); - - DIFFUSION_SESSION_FACTORY_T *session_factory = diffusion_session_factory_init(); - diffusion_session_factory_principal(session_factory, "control"); - diffusion_session_factory_credentials(session_factory, control_credentials); - - SESSION_T *control_session = session_create_with_session_factory(session_factory, url); - if (control_session == NULL) { - fprintf(stderr, "Failed to create control session\n"); - return EXIT_FAILURE; - } - - // Create normal session with Diffusion, using `client` as Principal - CREDENTIALS_T *credentials = credentials_create_password(password); - - DIFFUSION_SESSION_FACTORY_T *client_session_factory = diffusion_session_factory_init(); - diffusion_session_factory_principal(client_session_factory, principal); - diffusion_session_factory_credentials(client_session_factory, credentials); - - SESSION_T *normal_session = session_create_with_session_factory(client_session_factory, url); - if (normal_session == NULL) { - fprintf(stderr, "Failed to create normal session\n"); - return EXIT_FAILURE; - } - - // Close normal session using control session - DIFFUSION_CLIENT_CLOSE_WITH_SESSION_PARAMS_T params = { - .session_id = normal_session->id, - .on_closed = on_closed, - .on_error = on_error - }; - - DIFFUSION_API_ERROR api_error; - diffusion_client_close_with_session(control_session, params, &api_error); - - // Wait for a couple of seconds. - sleep(2); - - puts("Closing sessions"); - - // Close the connection and free resources - session_close(control_session, NULL); - session_free(control_session); - session_free(normal_session); - - diffusion_session_factory_free(session_factory); - diffusion_session_factory_free(client_session_factory); - credentials_free(control_credentials); - credentials_free(credentials); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/c/features/client_control/get-session-properties.c b/c/features/client_control/get-session-properties.c deleted file mode 100644 index dbfa72ae..00000000 --- a/c/features/client_control/get-session-properties.c +++ /dev/null @@ -1,142 +0,0 @@ -/** - * Copyright © 2020 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.6 - */ - -/* - * In this example, we attempt to receive session properties for a client - * with the specified client ID. - * - * In normal use, this could be used in conjunction with a session - * properties listener that can track connecting client sessions and - * their associated client IDs. - */ - -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - {'i', "sessionid", "Session ID of the client. If not specified, get properties for this session.", ARG_OPTIONAL, ARG_HAS_VALUE, NULL}, - {'r', "properties", "Comma separated list of properties to be requested.", ARG_OPTIONAL, ARG_HAS_VALUE, PROPERTIES_SELECTOR_ALL_FIXED_PROPERTIES}, - END_OF_ARG_OPTS -}; - -/* - * Callback invoked when session properties are received. - */ -int on_session_properties( - SESSION_T *session, - const SVC_GET_SESSION_PROPERTIES_RESPONSE_T *response, - void *context) -{ - char **keys = hash_keys(response->properties); - for(char **k = keys; *k != NULL; k++) { - char *v = hash_get(response->properties, *k); - printf("%s=%s\n", *k, v); - } - free(keys); - return HANDLER_SUCCESS; -} - - -int main(int argc, char **argv) -{ - /* - * Standard command-line parsing. - */ - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - CREDENTIALS_T *credentials = NULL; - const char *password = hash_get(options, "credentials"); - if(password != NULL) { - credentials = credentials_create_password(password); - } - - /* - * Create a session with Diffusion. - */ - DIFFUSION_ERROR_T error = { 0 }; - SESSION_T *session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "Failed to create session: %s\n", error.message); - return EXIT_FAILURE; - } - - SESSION_ID_T *sid; - char *sid_str = hash_get(options, "sessionid"); - if(sid_str != NULL) { - sid = session_id_create_from_string(sid_str); - } - else { - sid = session->id; - } - - SET_T *properties = set_new_string(10); - char *props_str = strdup(hash_get(options, "properties")); - char *str = props_str; - char *tok = NULL; - while((tok = strtok(str, ",")) != NULL) { - str = NULL; - set_add(properties, tok); - } - free(props_str); - - GET_SESSION_PROPERTIES_PARAMS_T params = { - .session_id = sid, - .required_properties = properties, - .on_session_properties = on_session_properties - }; - - /* - * Request the session properties, and wait for the response. - */ - get_session_properties(session, params); - - // Sleep for a while - sleep(5); - - /* - * Close the session and clean up. - */ - session_close(session, NULL); - session_free(session); - set_free(properties); - credentials_free(credentials); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/c/features/client_control/session-properties-listener.c b/c/features/client_control/session-properties-listener.c deleted file mode 100644 index 65aa17b3..00000000 --- a/c/features/client_control/session-properties-listener.c +++ /dev/null @@ -1,219 +0,0 @@ -/** - * Copyright © 2020 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.6 - */ - -/* - * This example demonstrates how to register a listener that receives - * notification of new client connections, clients closing and client - * properties being updated. - */ - -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" -#include "set.h" - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - END_OF_ARG_OPTS -}; - - -/* - * Helper function to print the properties hash key/value pairs. - */ -static void print_properties(HASH_T *properties) -{ - char **keys = hash_keys(properties); - for(char **k = keys; *k != NULL; k++) { - char *v = hash_get(properties, *k); - printf("%s=%s\n", *k, v); - } - free(keys); -} - - -/* - * Callback invoked when our listener registers successfully. - */ -static int on_registered( - SESSION_T *session, - void *context) -{ - printf("on_registered\n"); - return HANDLER_SUCCESS; -} - - -/* - * Callback invoked if our listener fails to register. - */ -static int on_registration_error( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("on_registration_error: %s\n", error->message); - return HANDLER_SUCCESS; -} - - -/* - * Callback invoked when we receive notification of a new client - * session. - */ -static int on_session_open( - SESSION_T *session, - const SESSION_PROPERTIES_EVENT_T *request, - void *context) -{ - char *sid_str = session_id_to_string(&request->session_id); - printf("on_session_open: %s\n", sid_str); - free(sid_str); - print_properties(request->properties); - return HANDLER_SUCCESS; -} - - -/* - * Callback invoked when an existing client session undergoes a change - * of properties. - */ -static int on_session_update( - SESSION_T *session, - const SESSION_PROPERTIES_EVENT_T *request, - void *context) -{ - printf("on_session_update\n"); - char *sid_str = session_id_to_string(&request->session_id); - printf("on_session_close: %s\n", sid_str); - free(sid_str); - printf("update type: %d\n", request->update_type); - return HANDLER_SUCCESS; -} - - -/* - * Callback invoked when a client session closes. - */ -static int on_session_close( - SESSION_T *session, - const SESSION_PROPERTIES_EVENT_T *request, - void *context) -{ - char *sid_str = session_id_to_string(&request->session_id); - printf("on_session_close: %s\n", sid_str); - free(sid_str); - printf("reason: %d\n", request->close_reason); - print_properties(request->properties); - return HANDLER_SUCCESS; -} - - -/* - * Callback invoked if an error occurs while procssing a session - * property event from the server. - */ -static int on_session_error( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("on_session_error: %s\n", error->message); - return HANDLER_SUCCESS; -} - -/* - * Program entry point. - */ -int main(int argc, char **argv) -{ - /* - * Standard command-line parsing. - */ - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - CREDENTIALS_T *credentials = NULL; - const char *password = hash_get(options, "credentials"); - if(password != NULL) { - credentials = credentials_create_password(password); - } - - /* - * Create a session with Diffusion. - */ - DIFFUSION_ERROR_T error = { 0 }; - SESSION_T *session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "Failed to create session: %s\n", error.message); - return EXIT_FAILURE; - } - - /* - * Register a session properties listener. - * - * Requests all "fixed" properties, i.e. those defined by - * Diffusion rather than user-defined properties. - */ - SET_T *required_properties = set_new_string(5); - set_add(required_properties, PROPERTIES_SELECTOR_ALL_FIXED_PROPERTIES); - - SESSION_PROPERTIES_REGISTRATION_PARAMS_T params = { - .on_registered = on_registered, - .on_registration_error = on_registration_error, - .on_session_open = on_session_open, - .on_session_close = on_session_close, - .on_session_update = on_session_update, - .on_session_error = on_session_error, - .required_properties = required_properties - }; - session_properties_listener_register(session, params); - - /* - * Wait for session events for 2 minutes. - */ - sleep(120); - - /* - * Close session and free resources. - */ - session_close(session, NULL); - session_free(session); - - set_free(required_properties); - credentials_free(credentials); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/c/features/messaging/send-request-to-filter.c b/c/features/messaging/send-request-to-filter.c deleted file mode 100644 index d6705184..00000000 --- a/c/features/messaging/send-request-to-filter.c +++ /dev/null @@ -1,181 +0,0 @@ -/** - * Copyright © 2018, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.2 - */ - -/* - * This example shows how a request can be sent through a filter to distribute to - * all clients matching the filter. - */ - -#include - -#ifndef WIN32 -#include -#else -#define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" - -char *response; - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - {'t', "request_path", "Request path", ARG_REQUIRED, ARG_HAS_VALUE, "echo"}, - {'d', "request", "Request to send", ARG_REQUIRED, ARG_HAS_VALUE, "hello client request!"}, - {'r', "response", "Response to send", ARG_REQUIRED, ARG_HAS_VALUE, "hello client response!"}, - END_OF_ARG_OPTS -}; - -static int on_number_sent(int number_sent, void *context) -{ - printf("Requests sent: %d\n", number_sent); - return HANDLER_SUCCESS; -} - -static int -on_request(SESSION_T *session, const char *request_path, DIFFUSION_DATATYPE request_datatype, - const DIFFUSION_VALUE_T *request, const DIFFUSION_RESPONDER_HANDLE_T *handle, void *context) -{ - - char *request_val; - read_diffusion_string_value(request, &request_val, NULL); - - printf("Request received: %s\n", request_val); - free(request_val); - - BUF_T *response_buf = buf_create(); - write_diffusion_string_value(response, response_buf); - diffusion_respond_to_request(session, handle, response_buf, NULL); - - buf_free(response_buf); - - return HANDLER_SUCCESS; -} - -static int -on_response(DIFFUSION_DATATYPE response_datatype, const DIFFUSION_VALUE_T *response, void *context) -{ - char *response_val; - read_diffusion_string_value(response, &response_val, NULL); - printf("Response received: %s\n\n", response_val); - free(response_val); - - return HANDLER_SUCCESS; -} - -int -main(int argc, char **argv) -{ - /* - * Standard command-line parsing. - */ - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - char *url = hash_get(options, "url"); - - const char *principal = hash_get(options, "principal"); - CREDENTIALS_T *credentials = NULL; - - const char *password = hash_get(options, "credentials"); - if(password != NULL) { - credentials = credentials_create_password(password); - } - - char *request_path = hash_get(options, "request_path"); - - /* - * Create 2 sessions with Diffusion. - */ - SESSION_T *client = NULL; - SESSION_T *sender = NULL; - - DIFFUSION_ERROR_T error = { 0 }; - client = session_create(url, principal, credentials, NULL, NULL, &error); - if(client == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - sender = session_create(url, "admin", credentials, NULL, NULL, &error); - if(sender == NULL) { - fprintf(stderr, "TEST: Failed to create sender session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - /* - * Create a payload. - */ - char *request_data = hash_get(options, "request"); - response = hash_get(options, "response"); - - BUF_T *request = buf_create(); - - write_diffusion_string_value(request_data, request); - - DIFFUSION_REQUEST_STREAM_T request_stream = { - .on_request = on_request - }; - - set_request_stream(client, request_path, DATATYPE_STRING, DATATYPE_STRING, &request_stream); - - /* - * Send to all non admin principal clients. - */ - SEND_REQUEST_TO_FILTER_PARAMS_T params = { - .path = request_path, - .filter = "$Principal NE 'admin'", - .request_datatype = DATATYPE_STRING, - .response_datatype = DATATYPE_STRING, - .on_response = on_response, - .on_number_sent = on_number_sent, - .request = request, - }; - - int counter = 1; - - while (counter <= 120) { - printf("Sending filter request to path {%s}.. #%d\n", request_path, counter); - send_request_to_filter(sender, params); - sleep(1); - ++counter; - } - - session_close(client, NULL); - session_free(client); - - session_close(sender, NULL); - session_free(sender); - - buf_free(request); - credentials_free(credentials); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} \ No newline at end of file diff --git a/c/features/messaging/send-request-to-path.c b/c/features/messaging/send-request-to-path.c deleted file mode 100644 index 4c654fb2..00000000 --- a/c/features/messaging/send-request-to-path.c +++ /dev/null @@ -1,190 +0,0 @@ -/** - * Copyright © 2018, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.2 - */ - -/* - * This example shows how a request can be sent to a request handler via - * a request path endpoint. - */ - -#include - -#ifndef WIN32 -#include -#else -#define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" - -char *response; - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - {'t', "request_path", "Request path", ARG_REQUIRED, ARG_HAS_VALUE, "echo"}, - {'d', "request", "Request to send", ARG_REQUIRED, ARG_HAS_VALUE, "hello client request!"}, - {'r', "response", "Response to send", ARG_REQUIRED, ARG_HAS_VALUE, "hello client response!"}, - END_OF_ARG_OPTS -}; - -static int -on_active(SESSION_T *session, const char *path, const DIFFUSION_REGISTRATION_T *registered_handler) -{ - printf("Request handler active\n"); - return HANDLER_SUCCESS; -} - -static int -on_request(SESSION_T *session, DIFFUSION_DATATYPE request_datatype, const DIFFUSION_VALUE_T *request, - const DIFFUSION_REQUEST_CONTEXT_T *request_context, const DIFFUSION_RESPONDER_HANDLE_T *handle, void *context) -{ - - char *request_val; - read_diffusion_string_value(request, &request_val, NULL); - - SESSION_ID_T *session_id = diffusion_request_context_get_session_id(request_context); - char *session_id_str = session_id_to_string(session_id); - - printf("Request received from %s: %s\n", session_id_str, request_val); - free(request_val); - - BUF_T *response_buf = buf_create(); - write_diffusion_string_value(response, response_buf); - diffusion_respond_to_request(session, handle, response_buf, NULL); - - buf_free(response_buf); - session_id_free(session_id); - free(session_id_str); - - return HANDLER_SUCCESS; -} - -static int -on_response(DIFFUSION_DATATYPE response_datatype, const DIFFUSION_VALUE_T *response, void *context) -{ - char *response_val; - read_diffusion_string_value(response, &response_val, NULL); - printf("Response received: %s\n\n", response_val); - free(response_val); - - return HANDLER_SUCCESS; -} - -int -main(int argc, char **argv) -{ - /* - * Standard command-line parsing. - */ - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - char *url = hash_get(options, "url"); - - const char *principal = hash_get(options, "principal"); - CREDENTIALS_T *credentials = NULL; - - const char *password = hash_get(options, "credentials"); - if(password != NULL) { - credentials = credentials_create_password(password); - } - - char *request_path = hash_get(options, "request_path"); - - /* - * Create 2 sessions with Diffusion. - */ - SESSION_T *session = NULL; - SESSION_T *handler = NULL; - - DIFFUSION_ERROR_T error = { 0 }; - session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - handler = session_create(url, "admin", credentials, NULL, NULL, &error); - if(handler == NULL) { - fprintf(stderr, "TEST: Failed to create handler session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - /* - * Create a payload. - */ - char *request_data = hash_get(options, "request"); - response = hash_get(options, "response"); - - BUF_T *request = buf_create(); - - write_diffusion_string_value(request_data, request); - - DIFFUSION_REQUEST_HANDLER_T request_handler = { - .request_datatype = DATATYPE_STRING, - .response_datatype = DATATYPE_STRING, - .on_active = on_active, - .on_request = on_request - }; - - ADD_REQUEST_HANDLER_PARAMS_T request_handler_params = { - .path = request_path, - .request_handler = &request_handler - }; - - add_request_handler(handler, request_handler_params); - - SEND_REQUEST_PARAMS_T send_request_params = { - .path = request_path, - .request = request, - .on_response = on_response, - .request_datatype = DATATYPE_STRING, - .response_datatype = DATATYPE_STRING - }; - - int counter = 1; - - while (counter <= 120) { - printf("Sending request to path {%s}.. #%d\n", request_path, counter); - send_request(session, send_request_params); - sleep(1); - ++counter; - } - - session_close(session, NULL); - session_free(session); - - session_close(handler, NULL); - session_free(handler); - - buf_free(request); - credentials_free(credentials); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} \ No newline at end of file diff --git a/c/features/messaging/send-request-to-session.c b/c/features/messaging/send-request-to-session.c deleted file mode 100644 index e3d6c744..00000000 --- a/c/features/messaging/send-request-to-session.c +++ /dev/null @@ -1,157 +0,0 @@ -/** - * Copyright © 2018, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.2 - */ - -/* - * This example shows how a request can be sent to another client via - * a request path endpoint. The session ID of the target client must be - * known. - */ - -#include - -#ifndef WIN32 -#include -#else -#define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" - -char *response; - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - {'t', "request_path", "Request path", ARG_REQUIRED, ARG_HAS_VALUE, "echo"}, - {'d', "request", "Request to send", ARG_REQUIRED, ARG_HAS_VALUE, "hello client request!"}, - {'r', "response", "Response to send", ARG_REQUIRED, ARG_HAS_VALUE, "hello client response!"}, - END_OF_ARG_OPTS -}; - -static int -on_request(SESSION_T *session, const char *request_path, DIFFUSION_DATATYPE request_datatype, - const DIFFUSION_VALUE_T *request, const DIFFUSION_RESPONDER_HANDLE_T *handle, void *context) -{ - - char *request_val; - read_diffusion_string_value(request, &request_val, NULL); - printf("Request received: %s\n", request_val); - free(request_val); - - BUF_T *response_buf = buf_create(); - write_diffusion_string_value(response, response_buf); - diffusion_respond_to_request(session, handle, response_buf, NULL); - buf_free(response_buf); - - return HANDLER_SUCCESS; -} - -static int -on_response(DIFFUSION_DATATYPE response_datatype, const DIFFUSION_VALUE_T *response, void *context) -{ - char *response_val; - read_diffusion_string_value(response, &response_val, NULL); - printf("Response received: %s\n\n", response_val); - free(response_val); - - return HANDLER_SUCCESS; -} - -int -main(int argc, char **argv) -{ - /* - * Standard command-line parsing. - */ - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - char *url = hash_get(options, "url"); - - const char *principal = hash_get(options, "principal"); - CREDENTIALS_T *credentials = NULL; - - const char *password = hash_get(options, "credentials"); - if(password != NULL) { - credentials = credentials_create_password(password); - } - - char *request_path = hash_get(options, "request_path"); - - /* - * Create a session with Diffusion. - */ - SESSION_T *session = NULL; - DIFFUSION_ERROR_T error = { 0 }; - session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - /* - * Create a payload. - */ - char *request_data = hash_get(options, "request"); - response = hash_get(options, "response"); - - BUF_T *request = buf_create(); - - write_diffusion_string_value(request_data, request); - - DIFFUSION_REQUEST_STREAM_T request_stream = { - .on_request = on_request - }; - - set_request_stream(session, request_path, DATATYPE_STRING, DATATYPE_STRING, &request_stream); - - SEND_REQUEST_TO_SESSION_PARAMS_T params = { - .recipient_session = session->id, - .path = request_path, - .request = request, - .request_datatype = DATATYPE_STRING, - .response_datatype = DATATYPE_STRING, - .on_response = on_response - }; - - int counter = 1; - - while (counter <= 120) { - printf("Sending request.. #%d\n", counter); - send_request_to_session(session, params); - sleep(1); - ++counter; - } - - session_close(session, NULL); - session_free(session); - buf_free(request); - credentials_free(credentials); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} \ No newline at end of file diff --git a/c/features/metrics/session-metric-collector.c b/c/features/metrics/session-metric-collector.c deleted file mode 100644 index dc1a39cf..00000000 --- a/c/features/metrics/session-metric-collector.c +++ /dev/null @@ -1,205 +0,0 @@ -/** - * Copyright © 2021 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.7 - */ - -/* - * This example creates, lists and removes session metric collectors. - */ -#include -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "admin"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - END_OF_ARG_OPTS -}; - -static int on_collector_set(void *context) -{ - printf("Session metric collector has been set.\n"); - return HANDLER_SUCCESS; -} - - -static int on_collector_removed(void *context) -{ - printf("Session metric collector has been removed.\n"); - return HANDLER_SUCCESS; -} - - -static int on_collectors_received(const LIST_T *collectors, void *context) -{ - int total_collectors = list_get_size(collectors); - - printf("Session metric collectors received:\n"); - for (int i = 0; i < total_collectors; i++) { - DIFFUSION_SESSION_METRIC_COLLECTOR_T *collector = list_get_data_indexed(collectors, i); - - char *name; - diffusion_session_metric_collector_get_name(collector, &name); - printf("\t%s\n", name); - free(name); - - char *session_filter; - diffusion_session_metric_collector_get_session_filter(collector, &session_filter); - printf("\t\tSession filter: %s\n", session_filter); - free(session_filter); - - bool exports_to_prometheus; - diffusion_session_metric_collector_exports_to_prometheus(collector, &exports_to_prometheus); - printf("\t\tExports to Prometheus: %s\n", exports_to_prometheus ? "YES" : "NO"); - - bool removes_metrics_with_no_matches; - diffusion_session_metric_collector_removes_metrics_with_no_matches(collector, &removes_metrics_with_no_matches); - printf("\t\tRemoves metrics with no matches: %s\n", removes_metrics_with_no_matches ? "YES" : "NO"); - - LIST_T *group_by_properties; - diffusion_session_metric_collector_get_group_by_properties(collector, &group_by_properties); - printf("\t\tGroup by properties:\n"); - for (int i = 0; i < list_get_size(group_by_properties); i++) { - printf("\t\t\t%s\n", (char *) list_get_data_indexed(group_by_properties, i)); - } - list_free(group_by_properties, (void (*) (void *))free); - } - return HANDLER_SUCCESS; -} - - -static int on_error( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("Error: %s\n", error->message); - return HANDLER_SUCCESS; -} - -/* - * Program entry point. - */ -int main(int argc, char** argv) -{ - /* - * Standard command-line parsing. - */ - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - CREDENTIALS_T *credentials = NULL; - const char *password = hash_get(options, "credentials"); - if(password != NULL) { - credentials = credentials_create_password(password); - } - - /* - * Create a session with the Diffusion server. - */ - SESSION_T *session; - DIFFUSION_ERROR_T error = { 0 }; - session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - /* - * Create a session metric collector, using its builder - */ - DIFFUSION_SESSION_METRIC_COLLECTOR_BUILDER_T *builder = - diffusion_session_metric_collector_builder_init(); - - builder = diffusion_session_metric_collector_builder_export_to_prometheus( - builder, - true); - builder = diffusion_session_metric_collector_builder_remove_metrics_with_no_matches( - builder, - true); - builder = diffusion_session_metric_collector_builder_group_by_property( - builder, - "$Location"); - - DIFFUSION_SESSION_METRIC_COLLECTOR_T *collector = - diffusion_session_metric_collector_builder_create_collector( - builder, - "Collector 1", - "$Principal is 'control'"); - /* - * Put the session metric collector in the Diffusion server. - */ - DIFFUSION_METRICS_PUT_SESSION_METRIC_COLLECTOR_PARAMS_T put_metric_collector_params = { - .on_collector_set = on_collector_set, - .on_error = on_error, - .collector = collector - }; - diffusion_metrics_put_session_metric_collector(session, put_metric_collector_params, NULL); - sleep(2); - - /* - * List all session metric collectors present in the server. - */ - DIFFUSION_METRICS_LIST_SESSION_METRIC_COLLECTORS_PARAMS_T list_metric_collectors_params = { - .on_collectors_received = on_collectors_received, - .on_error = on_error - }; - diffusion_metrics_list_session_metric_collectors(session, list_metric_collectors_params, NULL); - sleep(2); - - /* - * Remove session metric collection we created in this example. - */ - DIFFUSION_METRICS_REMOVE_SESSION_METRIC_COLLECTOR_PARAMS_T remove_metric_collector_params = { - .on_collector_removed = on_collector_removed, - .on_error = on_error, - .collector_name = "Collector 1", - }; - diffusion_metrics_remove_session_metric_collector(session, remove_metric_collector_params, NULL); - sleep(2); - - /* - * Close session and free resources. - */ - session_close(session, NULL); - session_free(session); - - credentials_free(credentials); - hash_free(options, NULL, free); - diffusion_session_metric_collector_free(collector); - diffusion_session_metric_collector_builder_free(builder); - - return EXIT_SUCCESS; -} diff --git a/c/features/metrics/topic-metric-collector.c b/c/features/metrics/topic-metric-collector.c deleted file mode 100644 index eec2edf0..00000000 --- a/c/features/metrics/topic-metric-collector.c +++ /dev/null @@ -1,196 +0,0 @@ -/** - * Copyright © 2021 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.7 - */ - -/* - * This example creates, lists and removes topic metric collectors. - */ -#include -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "admin"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - END_OF_ARG_OPTS -}; - - -static int on_collector_set(void *context) -{ - printf("Topic metric collector has been set.\n"); - return HANDLER_SUCCESS; -} - - -static int on_collector_removed(void *context) -{ - printf("Topic metric collector has been removed.\n"); - return HANDLER_SUCCESS; -} - - -static int on_collectors_received(const LIST_T *collectors, void *context) -{ - int total_collectors = list_get_size(collectors); - - printf("Topic metric collectors received:\n"); - for (int i = 0; i < total_collectors; i++) { - DIFFUSION_TOPIC_METRIC_COLLECTOR_T *collector = list_get_data_indexed(collectors, i); - - char *name; - diffusion_topic_metric_collector_get_name(collector, &name); - printf("\t%s\n", name); - free(name); - - char *topic_selector; - diffusion_topic_metric_collector_get_topic_selector(collector, &topic_selector); - printf("\t\tTopic selector: %s\n", topic_selector); - free(topic_selector); - - bool exports_to_prometheus; - diffusion_topic_metric_collector_exports_to_prometheus(collector, &exports_to_prometheus); - printf("\t\tExports to Prometheus: %s\n", exports_to_prometheus ? "YES" : "NO"); - - bool group_by_topic_type; - diffusion_topic_metric_collector_groups_by_topic_type(collector, &group_by_topic_type); - printf("\t\tGroup by topic type: %s\n", group_by_topic_type ? "YES" : "NO"); - - bool group_by_topic_view; - diffusion_topic_metric_collector_groups_by_topic_view(collector, &group_by_topic_view); - printf("\t\tGroup by topic view: %s\n", group_by_topic_view ? "YES" : "NO"); - } - return HANDLER_SUCCESS; -} - - -static int on_error( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("Error: %s\n", error->message); - return HANDLER_SUCCESS; -} - -/* - * Program entry point. - */ -int main(int argc, char** argv) -{ - /* - * Standard command-line parsing. - */ - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - CREDENTIALS_T *credentials = NULL; - const char *password = hash_get(options, "credentials"); - if(password != NULL) { - credentials = credentials_create_password(password); - } - - /* - * Create a session with the Diffusion server. - */ - SESSION_T *session; - DIFFUSION_ERROR_T error = { 0 }; - session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - /* - * Create a topic metric collector, using its builder - */ - DIFFUSION_TOPIC_METRIC_COLLECTOR_BUILDER_T *builder = - diffusion_topic_metric_collector_builder_init(); - - builder = diffusion_topic_metric_collector_builder_export_to_prometheus(builder, true); - builder = diffusion_topic_metric_collector_builder_group_by_topic_type(builder, true); - builder = diffusion_topic_metric_collector_builder_group_by_topic_view(builder, true); - - DIFFUSION_TOPIC_METRIC_COLLECTOR_T *collector = - diffusion_topic_metric_collector_builder_create_collector( - builder, - "Collector 1", - "*A/B/C/D//"); - /* - * Put the topic metric collector in the Diffusion server. - */ - DIFFUSION_METRICS_PUT_TOPIC_METRIC_COLLECTOR_PARAMS_T put_metric_collector_params = { - .on_collector_set = on_collector_set, - .on_error = on_error, - .collector = collector - }; - diffusion_metrics_put_topic_metric_collector(session, put_metric_collector_params, NULL); - sleep(2); - - /* - * List all topic metric collectors present in the server. - */ - DIFFUSION_METRICS_LIST_TOPIC_METRIC_COLLECTORS_PARAMS_T list_metric_collectors_params = { - .on_collectors_received = on_collectors_received, - .on_error = on_error - }; - diffusion_metrics_list_topic_metric_collectors(session, list_metric_collectors_params, NULL); - sleep(2); - - /* - * Remove topic metric collection we created in this example. - */ - DIFFUSION_METRICS_REMOVE_TOPIC_METRIC_COLLECTOR_PARAMS_T remove_metric_collector_params = { - .on_collector_removed = on_collector_removed, - .on_error = on_error, - .collector_name = "Collector 1", - }; - diffusion_metrics_remove_topic_metric_collector(session, remove_metric_collector_params, NULL); - sleep(2); - - /* - * Close session and free resources. - */ - session_close(session, NULL); - session_free(session); - - credentials_free(credentials); - hash_free(options, NULL, free); - diffusion_topic_metric_collector_free(collector); - diffusion_topic_metric_collector_builder_free(builder); - - return EXIT_SUCCESS; -} diff --git a/c/features/remote_servers/remote-servers.c b/c/features/remote_servers/remote-servers.c deleted file mode 100644 index 252668f4..00000000 --- a/c/features/remote_servers/remote-servers.c +++ /dev/null @@ -1,345 +0,0 @@ -/** - * Copyright © 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.7 - */ - -/* - * This example creates, lists, checks and removes a remote server. - */ -#include -#include -#include - -#ifndef WIN32 -#include -#else -#define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "admin"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - END_OF_ARG_OPTS -}; - - -static char *get_connection_option_string( - DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_T option) -{ - switch(option) { - case DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_RECONNECTION_TIMEOUT: - return "reconnection_timeout"; - case DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_RETRY_DELAY: - return "retry_delay"; - case DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_RECOVERY_BUFFER_SIZE: - return "recovery_buffer_size"; - case DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_INPUT_BUFFER_SIZE: - return "input_buffer_size"; - case DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_OUTPUT_BUFFER_SIZE: - return "output_buffer_size"; - case DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_MAXIMUM_QUEUE_SIZE: - return "maximum_queue_size"; - case DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_CONNECTION_TIMEOUT: - return "connection_timeout"; - case DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_WRITE_TIMEOUT: - return "write_timeout"; - default: - return "unknown"; - } -} - - -static void print_connection_options( - HASH_NUM_T *connection_options) -{ - unsigned long *keys = hash_num_keys(connection_options); - for (unsigned long i = 0; i < connection_options->size; i++) { - char *val = (char *)hash_num_get(connection_options, keys[i]); - printf("\t%s: %s\n", get_connection_option_string(keys[i]), val); - } - free(keys); -} - - -static void print_remote_server( - DIFFUSION_REMOTE_SERVER_T *remote_server) -{ - char *name = diffusion_remote_server_get_name(remote_server); - char *principal = diffusion_remote_server_get_principal(remote_server); - char *url = diffusion_remote_server_get_url(remote_server); - char *missing_topic_notification_filter = - diffusion_remote_server_get_missing_topic_notification_filter(remote_server); - HASH_NUM_T *connection_options = diffusion_remote_server_get_connection_options(remote_server); - - printf("Name: %s\n", name); - printf("URL: %s\n", url); - printf("Principal: %s\n", principal); - printf("Missing Topic Notification Filter: %s\n", missing_topic_notification_filter); - printf("Connection Options:\n"); - print_connection_options(connection_options); - - free(name); - free(principal); - free(url); - free(missing_topic_notification_filter); - hash_num_free(connection_options, free); -} - - -static int on_remote_server_created( - DIFFUSION_REMOTE_SERVER_T *remote_server, - LIST_T *errors, - void *context) -{ - if (remote_server == NULL) { - printf("The following errors occurred while creating the remote server:\n"); - for (int i = 0; i < list_get_size(errors); i++) { - ERROR_REPORT_T *report = list_get_data_indexed(errors, i); - printf("\t[%d, %d] %s\n", report->line, report->column, report->message); - } - } - else { - printf("Remote Server successfully created\n"); - print_remote_server(remote_server); - } - return HANDLER_SUCCESS; -} - - -static int on_remote_servers_listed( - LIST_T *remote_servers, - void *context) -{ - int list_size = list_get_size(remote_servers); - printf("Remote Servers found: %d\n", list_size); - for (int i = 0; i < list_size; i++) { - DIFFUSION_REMOTE_SERVER_T *remote_server = list_get_data_indexed(remote_servers, i); - print_remote_server(remote_server); - printf("\n"); - } - return HANDLER_SUCCESS; -} - - -static char *get_server_state_string( - DIFFUSION_REMOTE_SERVER_CONNECTION_STATE_T state) -{ - switch(state) { - case DIFFUSION_REMOTE_SERVER_CONNECTION_STATE_INACTIVE: - return "inactive"; - case DIFFUSION_REMOTE_SERVER_CONNECTION_STATE_CONNECTED: - return "connected"; - case DIFFUSION_REMOTE_SERVER_CONNECTION_STATE_RETRYING: - return "retrying"; - case DIFFUSION_REMOTE_SERVER_CONNECTION_STATE_FAILED: - return "failed"; - case DIFFUSION_REMOTE_SERVER_CONNECTION_STATE_MISSING: - return "missing"; - default: - return "unknown"; - } -} - - -static int on_remote_server_checked( - DIFFUSION_CHECK_REMOTE_SERVER_RESPONSE_T *response, - void *context) -{ - DIFFUSION_REMOTE_SERVER_CONNECTION_STATE_T state = - diffusion_check_remote_server_response_get_state(response); - - printf("Received remote server status: %s.\n", get_server_state_string(state)); - if (state == DIFFUSION_REMOTE_SERVER_CONNECTION_STATE_FAILED) { - char *failure_message = - diffusion_check_remote_server_response_get_failure_message(response); - printf("Failure message: %s\n", failure_message); - free(failure_message); - } - return HANDLER_SUCCESS; -} - - -static int on_remote_server_removed(void *context) -{ - printf("Remote server has been successfully removed.\n"); - return HANDLER_SUCCESS; -} - - -static int on_error( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("Error: %s\n", error->message); - return HANDLER_SUCCESS; -} - -/* - * Program entry point. - */ -int main(int argc, char** argv) -{ - /* - * Standard command-line parsing. - */ - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - CREDENTIALS_T *credentials = NULL; - const char *password = hash_get(options, "credentials"); - if(password != NULL) { - credentials = credentials_create_password(password); - } - - /* - * Create a session with the Diffusion server. - */ - SESSION_T *session; - DIFFUSION_ERROR_T error = { 0 }; - session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - /* - * Create a remote server, using its builder - */ - DIFFUSION_REMOTE_SERVER_BUILDER_T *builder = - diffusion_remote_server_builder_init(); - - builder = diffusion_remote_server_builder_principal( - builder, - "admin"); - builder = diffusion_remote_server_builder_missing_topic_notification_filter( - builder, - "*/A/B/C/D//"); - builder = diffusion_remote_server_builder_connection_option( - builder, - DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_RECONNECTION_TIMEOUT, - "120000"); // milliseconds - builder = diffusion_remote_server_builder_connection_option( - builder, - DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_RETRY_DELAY, - "2000"); // milliseconds - builder = diffusion_remote_server_builder_connection_option( - builder, - DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_RECOVERY_BUFFER_SIZE, - "5000"); - builder = diffusion_remote_server_builder_connection_option( - builder, - DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_INPUT_BUFFER_SIZE, - "1024"); // kilobytes - builder = diffusion_remote_server_builder_connection_option( - builder, - DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_OUTPUT_BUFFER_SIZE, - "2048"); // kilobytes - builder = diffusion_remote_server_builder_connection_option( - builder, - DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_MAXIMUM_QUEUE_SIZE, - "7500"); - builder = diffusion_remote_server_builder_connection_option( - builder, - DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_CONNECTION_TIMEOUT, - "120000"); // milliseconds - builder = diffusion_remote_server_builder_connection_option( - builder, - DIFFUSION_REMOTE_SERVER_CONNECTION_OPTION_WRITE_TIMEOUT, - "300000"); // milliseconds - - CREDENTIALS_T *remote_server_credentials = credentials_create_password("password"); - builder = diffusion_remote_server_builder_credentials( - builder, - remote_server_credentials); - - DIFFUSION_API_ERROR api_error = { 0 }; - DIFFUSION_REMOTE_SERVER_T *remote_server = - diffusion_remote_server_builder_create( - builder, - "remote server 1", // remote server name - "ws://localhost:9091", // remote server URL - &api_error); // api error in case of invalid parameters - - /* - * Create the remote server definition in the Diffusion server - */ - DIFFUSION_CREATE_REMOTE_SERVER_PARAMS_T create_remote_server_params = { - .remote_server = remote_server, - .on_remote_server_created = on_remote_server_created, - .on_error = on_error - }; - diffusion_create_remote_server(session, create_remote_server_params, NULL); - sleep(2); - - /* - * List all remote servers defined in the Diffusion server - */ - DIFFUSION_LIST_REMOTE_SERVERS_PARAMS_T list_remote_servers_params = { - .on_remote_servers_listed = on_remote_servers_listed, - .on_error = on_error - }; - diffusion_list_remote_servers(session, list_remote_servers_params, NULL); - sleep(2); - - /* - * Check remote server we created. - */ - DIFFUSION_CHECK_REMOTE_SERVER_PARAMS_T check_remote_server_params = { - .name = "remote server 1", - .on_remote_server_checked = on_remote_server_checked, - .on_error = on_error - }; - diffusion_check_remote_server(session, check_remote_server_params, NULL); - sleep(2); - - /* - * Remove remote server we created. - */ - DIFFUSION_REMOVE_REMOTE_SERVER_PARAMS_T remove_remote_server_params = { - .name = "remote server 1", - .on_remote_server_removed = on_remote_server_removed, - .on_error = on_error - }; - diffusion_remove_remote_server(session, remove_remote_server_params, NULL); - sleep(2); - - /* - * Close session and free resources. - */ - session_close(session, NULL); - session_free(session); - - credentials_free(credentials); - credentials_free(remote_server_credentials); - hash_free(options, NULL, free); - diffusion_remote_server_free(remote_server); - diffusion_remote_server_builder_free(builder); - - return EXIT_SUCCESS; -} diff --git a/c/features/security/change-principal.c b/c/features/security/change-principal.c deleted file mode 100644 index 3386645c..00000000 --- a/c/features/security/change-principal.c +++ /dev/null @@ -1,121 +0,0 @@ -/** - * Copyright © 2014, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 5.0 - */ - -/* - * This client shows how the principal (e.g. username) can be changed during - * an active session. - */ - -#include -#include -#ifndef WIN32 -#include -#else -#define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "client"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - END_OF_ARG_OPTS -}; - -/* - * Callback to display that the principal has been successfully - * changed. - */ -static int -on_change_principal(SESSION_T *session, void *context) -{ - printf("Successfully changed the principal.\n"); - return HANDLER_SUCCESS; -} - -/* - * Callback to display an error when attempting to change the - * principal. - */ -static int -on_change_principal_failure(SESSION_T *session, void *context) -{ - printf("Failed to change the principal\n"); - return HANDLER_SUCCESS; -} - -int -main(int argc, char** argv) -{ - /* - * Standard command-line parsing. - */ - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - char *url = hash_get(options, "url"); - - // Create a session with Diffusion, with no principal or credentials. - SESSION_T *session; - DIFFUSION_ERROR_T error = { 0 }; - session = session_create(url, NULL, NULL, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "Failed to create session: %s\n", error.message); - return EXIT_FAILURE; - } - - // Wait for a couple of seconds. - sleep(2); - - puts("Changing credentials"); - - CREDENTIALS_T *credentials = credentials_create_password(hash_get(options, "credentials")); - - // Specify callbacks for the change_principal request. - CHANGE_PRINCIPAL_PARAMS_T params = { - .principal = hash_get(options, "principal"), - .credentials = credentials, - .on_change_principal = on_change_principal, - .on_change_principal_failure = on_change_principal_failure - }; - - // Do the change. - change_principal(session, params); - - // Wait for a couple more seconds. - sleep(2); - - puts("Closing session"); - - // Gracefully close the connection. - session_close(session, NULL); - session_free(session); - - credentials_free(credentials); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/c/features/session_trees/session-trees.c b/c/features/session_trees/session-trees.c deleted file mode 100644 index 5ab5ae8b..00000000 --- a/c/features/session_trees/session-trees.c +++ /dev/null @@ -1,200 +0,0 @@ -/** - * Copyright © 2021 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.7 - */ - -/* - * This example creates branch mapping tables. - */ -#include -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - END_OF_ARG_OPTS -}; - -static int on_branch_mapping_table_set( - void *context) -{ - printf("Branch mapping table has been set.\n"); - return HANDLER_SUCCESS; -} - - -static int on_session_tree_branches_received( - const LIST_T *session_tree_branches, - void *context) -{ - printf("Session tree branches have been received.\n"); - for (int i = 0; i < list_get_size(session_tree_branches); i++) { - char *session_tree_branch = list_get_data_indexed(session_tree_branches, i); - printf("\t%d --> %s\n", i+1, session_tree_branch); - } - return HANDLER_SUCCESS; -} - - -static int on_branch_mapping_table_received( - const DIFFUSION_BRANCH_MAPPING_TABLE_T *table, - void *context) -{ - char *session_tree_branch = - diffusion_branch_mapping_table_get_session_tree_branch( - (DIFFUSION_BRANCH_MAPPING_TABLE_T *) table); - - LIST_T *branch_mappings = - diffusion_branch_mapping_table_get_branch_mappings( - (DIFFUSION_BRANCH_MAPPING_TABLE_T *) table); - - printf("Branch mapping table for '%s'\n", session_tree_branch); - for (int i = 0; i < list_get_size(branch_mappings); i++) { - DIFFUSION_BRANCH_MAPPING_T *mapping = list_get_data_indexed(branch_mappings, i); - char *session_filter = diffusion_branch_mapping_get_session_filter(mapping); - char *topic_tree_branch = diffusion_branch_mapping_get_topic_tree_branch(mapping); - - printf("\t%30s --> %s\n", session_filter, topic_tree_branch); - - free(session_filter); - free(topic_tree_branch); - } - diffusion_branch_mapping_table_free_branch_mappings(branch_mappings); - free(session_tree_branch); - return HANDLER_SUCCESS; -} - - -static int on_error( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("Error: %s\n", error->message); - return HANDLER_SUCCESS; -} - -/* - * Program entry point. - */ -int main(int argc, char** argv) -{ - /* - * Standard command-line parsing. - */ - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - CREDENTIALS_T *credentials = NULL; - const char *password = hash_get(options, "credentials"); - if(password != NULL) { - credentials = credentials_create_password(password); - } - - /* - * Create a session with the Diffusion server. - */ - SESSION_T *session; - DIFFUSION_ERROR_T error = { 0 }; - session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - /* - * Create a branch mapping table. - */ - DIFFUSION_BRANCH_MAPPING_TABLE_BUILDER_T *builder = - diffusion_branch_mapping_table_builder_init(); - - builder = diffusion_branch_mapping_table_builder_add_branch_mapping( - builder, - "$Principal is 'control'", - "target/content/control"); - builder = diffusion_branch_mapping_table_builder_add_branch_mapping( - builder, - "all", - "target/content/other"); - - DIFFUSION_BRANCH_MAPPING_TABLE_T *table = - diffusion_branch_mapping_table_builder_create_table(builder, "public/content"); - - /* - * Put the branch mapping table in the Diffusion server. - */ - DIFFUSION_SESSION_TREES_PUT_BRANCH_MAPPING_TABLE_PARAMS_T put_branch_mapping_table_params = { - .on_table_set = on_branch_mapping_table_set, - .on_error = on_error, - .table = table - }; - diffusion_session_trees_put_branch_mapping_table(session, put_branch_mapping_table_params, NULL); - sleep(2); - - /* - * Retrieve all session tree branches with mappings - */ - DIFFUSION_SESSION_TREES_GET_SESSION_TREE_BRANCHES_PARAMS_T get_session_tree_branches_params = { - .on_session_tree_branches_received = on_session_tree_branches_received, - .on_error = on_error - }; - diffusion_session_trees_get_session_tree_branches(session, get_session_tree_branches_params, NULL); - sleep(2); - - /* - * Retrieve branch mapping table for session tree branch - */ - DIFFUSION_SESSION_TREES_GET_BRANCH_MAPPING_TABLE_PARAMS_T get_table_params = { - .on_table_received = on_branch_mapping_table_received, - .on_error = on_error, - .session_tree_branch = "public/content" - }; - diffusion_session_trees_get_branch_mapping_table(session, get_table_params, NULL); - sleep(2); - - /* - * Close session and free resources. - */ - session_close(session, NULL); - session_free(session); - - credentials_free(credentials); - hash_free(options, NULL, free); - diffusion_branch_mapping_table_free(table); - diffusion_branch_mapping_table_builder_free(builder); - - return EXIT_SUCCESS; -} diff --git a/c/features/subscription_control/subscription-control.c b/c/features/subscription_control/subscription-control.c deleted file mode 100644 index a1c1db33..00000000 --- a/c/features/subscription_control/subscription-control.c +++ /dev/null @@ -1,140 +0,0 @@ -/** - * Copyright © 2014 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 5.7 - */ - -/* - * This example waits to be notified of a client connection, and then - * subscribes that client to a named topic. - */ - -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - {'t', "topic_selector", "Topic selector to subscribe/unsubscribe clients from", ARG_OPTIONAL, ARG_HAS_VALUE, ">foo"}, - END_OF_ARG_OPTS -}; - -HASH_T *options = NULL; - - -// Callback invoked when a client has been successfully subscribed to a topic. -static int on_subscription_complete( - SESSION_T *session, - void *context) -{ - printf("Subscription complete\n"); - return HANDLER_SUCCESS; -} - - -// Callback invoked when a client session has been opened. -static int on_session_open( - SESSION_T *session, - const SESSION_PROPERTIES_EVENT_T *request, - void *context) -{ - if(session_id_cmp(*session->id, request->session_id) == 0) { - // It's our own session, ignore. - return HANDLER_SUCCESS; - } - - char *topic_selector = hash_get(options, "topic_selector"); - - char *sid_str = session_id_to_string(&request->session_id); - printf("Subscribing session %s to topic selector %s\n", sid_str, topic_selector); - free(sid_str); - - // Subscribe the client session to the topic. - SUBSCRIPTION_CONTROL_PARAMS_T subscribe_params = { - .session_id = request->session_id, - .topic_selector = topic_selector, - .on_complete = on_subscription_complete - }; - subscribe_client(session, subscribe_params); - - return HANDLER_SUCCESS; -} - - -int main(int argc, char **argv) -{ - // Standard command-line parsing. - options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - CREDENTIALS_T *credentials = NULL; - const char *password = hash_get(options, "credentials"); - if(password != NULL) { - credentials = credentials_create_password(password); - } - - // Create a session with Diffusion. - DIFFUSION_ERROR_T error = { 0 }; - SESSION_T *session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "Failed to create session: %s\n", error.message); - return EXIT_FAILURE; - } - - /* - * Register a session properties listener, so we are notified - * of new client connections. - * In the callback, we will subscribe the client to topics - * according to the topic_selector argument. - */ - SET_T *required_properties = set_new_string(1); - set_add(required_properties, PROPERTIES_SELECTOR_ALL_FIXED_PROPERTIES); - SESSION_PROPERTIES_REGISTRATION_PARAMS_T params = { - .on_session_open = on_session_open, - .required_properties = required_properties - }; - session_properties_listener_register(session, params); - set_free(required_properties); - - // Pretend to do some work. - sleep(10); - - // Close session and free resources. - session_close(session, NULL); - session_free(session); - - credentials_free(credentials); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/c/features/system_authentication_control/system-auth-control.c b/c/features/system_authentication_control/system-auth-control.c deleted file mode 100644 index b6ee6c32..00000000 --- a/c/features/system_authentication_control/system-auth-control.c +++ /dev/null @@ -1,144 +0,0 @@ -/** - * Copyright © 2014 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 5.5 - */ - -/* - * This examples demonstrates how to interact with the system - * authentication store. - */ - -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "admin"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - END_OF_ARG_OPTS -}; - - -/* - * This callback is invoked when the system authentication store is - * received, and prints the contents of the store. - */ -int on_get_system_authentication_store( - SESSION_T *session, - const SYSTEM_AUTHENTICATION_STORE_T store, - void *context) -{ - puts("Received System Authentication Store"); - - printf("Got %ld principals\n", store.system_principals->size); - - char **names = get_principal_names(store); - for(char **name = names; *name != NULL; name++) { - printf("Principal: %s\n", *name); - - char **roles = get_roles_for_principal(store, *name); - for(char **role = roles; *role != NULL; role++) { - printf(" |- Role: %s\n", *role); - } - free(roles); - } - free(names); - - switch(store.anonymous_connection_action) { - case ANONYMOUS_CONNECTION_ACTION_ALLOW: - puts("Allow anonymous connections"); - break; - case ANONYMOUS_CONNECTION_ACTION_DENY: - puts("Deny anonymous connections"); - break; - case ANONYMOUS_CONNECTION_ACTION_ABSTAIN: - puts("Abstain from making anonymous connection decision"); - break; - } - - puts("Anonymous connection roles:"); - char **roles = get_anonymous_roles(store); - for(char **role = roles; *role != NULL; role++) { - printf(" |- Role: %s\n", *role); - } - free(roles); - - return HANDLER_SUCCESS; -} - - -int main(int argc, char **argv) -{ - // Standard command-line parsing. - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - const char *password = hash_get(options, "credentials"); - - CREDENTIALS_T *credentials = NULL; - if(password != NULL) { - credentials = credentials_create_password(password); - } - - // Create a session with Diffusion. - SESSION_T *session; - DIFFUSION_ERROR_T error = { 0 }; - session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - // Request the system authentication store. - const GET_SYSTEM_AUTHENTICATION_STORE_PARAMS_T params = { - .on_get = on_get_system_authentication_store - }; - - puts("Requesting System Authentication Store"); - get_system_authentication_store(session, params); - - // Sleep for a while - sleep(5); - - // Close the session and free resources. - puts("Closing session"); - session_close(session, NULL); - session_free(session); - - credentials_free(credentials); - - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/c/features/time_series/time-series-append.c b/c/features/time_series/time-series-append.c deleted file mode 100644 index fb30f602..00000000 --- a/c/features/time_series/time-series-append.c +++ /dev/null @@ -1,195 +0,0 @@ -/** - * Copyright © 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.3 - */ - -/* - * This example creates a Time series topic (of String datatype) and periodically appends - * data to it. - */ -#include -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" -#include "conversation.h" - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - {'t', "topic", "Topic name to create and update", ARG_OPTIONAL, ARG_HAS_VALUE, "time-series-append"}, - {'s', "seconds", "Number of seconds to run for before exiting", ARG_OPTIONAL, ARG_HAS_VALUE, "30"}, - END_OF_ARG_OPTS -}; - -/* - * Handlers for add topic feature. - */ -static int on_topic_added_with_specification( - SESSION_T *session, - TOPIC_ADD_RESULT_CODE result_code, - void *context) -{ - printf("Added topic \"%s\"\n", (const char *)context); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_failed_with_specification( - SESSION_T *session, - TOPIC_ADD_FAIL_RESULT_CODE result_code, - const DIFFUSION_ERROR_T *error, - void *context) -{ - printf("Failed to add topic \"%s\" (%d)\n", (const char *)context, result_code); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_discard( - SESSION_T *session, - void *context) -{ - return HANDLER_SUCCESS; -} - - -static ADD_TOPIC_CALLBACK_T create_topic_callback(const char *topic_name) -{ - ADD_TOPIC_CALLBACK_T callback = { - .on_topic_added_with_specification = on_topic_added_with_specification, - .on_topic_add_failed_with_specification = on_topic_add_failed_with_specification, - .on_discard = on_topic_add_discard, - .context = (char *)topic_name - }; - - return callback; -} - - -static int on_append( - const DIFFUSION_TIME_SERIES_EVENT_METADATA_T *event_metadata, - void *context) -{ - printf("time series append success\n"); - return HANDLER_SUCCESS; -} - - -static int on_error( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("time series append error: %s\n", error->message); - return HANDLER_SUCCESS; -} - - -// Program entry point. -int main(int argc, char** argv) -{ - // Standard command-line parsing. - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - const char *password = hash_get(options, "credentials"); - const char *topic_name = hash_get(options, "topic"); - const long seconds = atol(hash_get(options, "seconds")); - - CREDENTIALS_T *credentials = NULL; - if(password != NULL) { - credentials = credentials_create_password(password); - } - - // Create a session with the Diffusion server. - SESSION_T *session; - DIFFUSION_ERROR_T error = { 0 }; - session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - ADD_TOPIC_CALLBACK_T callback = create_topic_callback(topic_name); - - HASH_T *properties = hash_new(2); - hash_add(properties, DIFFUSION_TIME_SERIES_EVENT_VALUE_TYPE, "string"); - - TOPIC_SPECIFICATION_T *spec = topic_specification_init(TOPIC_TYPE_TIME_SERIES); - topic_specification_set_properties(spec, properties); - - add_topic_from_specification(session, topic_name, spec, callback); - - // Sleep for a while - sleep(5); - - topic_specification_free(spec); - hash_free(properties, NULL, NULL); - - time_t end_time = time(NULL) + seconds; - - while(time(NULL) < end_time) { - - // Compose the update content - const time_t time_now = time(NULL); - const char *time_str = ctime(&time_now); - - // Create a BUF_T and write the string datatype value into it. - BUF_T *value = buf_create(); - write_diffusion_string_value(time_str, value); - - DIFFUSION_TIME_SERIES_APPEND_PARAMS_T params = { - .on_append = on_append, - .on_error = on_error, - .topic_path = topic_name, - .datatype = DATATYPE_STRING, - .value = value - }; - - // Append to the time series topic - diffusion_time_series_append(session, params, NULL); - buf_free(value); - - sleep(1); - } - - // Close session and free resources. - session_close(session, NULL); - session_free(session); - - credentials_free(credentials); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/c/features/time_series/time-series-edit.c b/c/features/time_series/time-series-edit.c deleted file mode 100644 index b055b14e..00000000 --- a/c/features/time_series/time-series-edit.c +++ /dev/null @@ -1,244 +0,0 @@ -/** - * Copyright © 2020 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.6 - */ - -/* - * This example creates a Time series topic (of String datatype), appends a sequence of - * values to it and edits the first value. - */ -#include -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" -#include "conversation.h" - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - {'t', "topic", "Topic name to create and update", ARG_OPTIONAL, ARG_HAS_VALUE, "time-series-edit"}, - END_OF_ARG_OPTS -}; - -/* - * Handlers for add topic feature. - */ -static int on_topic_added_with_specification( - SESSION_T *session, - TOPIC_ADD_RESULT_CODE result_code, - void *context) -{ - printf("Added topic \"%s\"\n", (const char *)context); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_failed_with_specification( - SESSION_T *session, - TOPIC_ADD_FAIL_RESULT_CODE result_code, - const DIFFUSION_ERROR_T *error, - void *context) -{ - printf("Failed to add topic \"%s\" (%d)\n", (const char *)context, result_code); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_discard(SESSION_T *session, void *context) -{ - return HANDLER_SUCCESS; -} - - -static ADD_TOPIC_CALLBACK_T create_topic_callback(const char *topic_name) -{ - ADD_TOPIC_CALLBACK_T callback = { - .on_topic_added_with_specification = on_topic_added_with_specification, - .on_topic_add_failed_with_specification = on_topic_add_failed_with_specification, - .on_discard = on_topic_add_discard, - .context = (char *)topic_name - }; - - return callback; -} - - -static int on_append( - const DIFFUSION_TIME_SERIES_EVENT_METADATA_T *event_metadata, - void *context) -{ - printf("time series append success\n"); - return HANDLER_SUCCESS; -} - - -static int on_edit( - const DIFFUSION_TIME_SERIES_EVENT_METADATA_T *event_metadata, - void *context) -{ - printf("time series edit success\n"); - return HANDLER_SUCCESS; -} - - -static int on_error( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("time series append error: %s\n", error->message); - return HANDLER_SUCCESS; -} - - -static int on_error_edit( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("time series edit error: %s\n", error->message); - return HANDLER_SUCCESS; -} - - -static void append_value_to_time_series_topic( - SESSION_T *session, - char *topic_path, - char *value) -{ - BUF_T *buf = buf_create(); - write_diffusion_string_value(value, buf); - - DIFFUSION_TIME_SERIES_APPEND_PARAMS_T params = { - .on_append = on_append, - .on_error = on_error, - .topic_path = topic_path, - .datatype = DATATYPE_STRING, - .value = buf - }; - - /* - * Append to the time series topic - */ - diffusion_time_series_append(session, params, NULL); - - // Sleep for a while - sleep(1); - - buf_free(buf); -} - -/* - * Program entry point. - */ -int main(int argc, char** argv) -{ - /* - * Standard command-line parsing. - */ - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - CREDENTIALS_T *credentials = NULL; - const char *password = hash_get(options, "credentials"); - if(password != NULL) { - credentials = credentials_create_password(password); - } - const char *topic_name = hash_get(options, "topic"); - - /* - * Create a session with the Diffusion server. - */ - SESSION_T *session; - DIFFUSION_ERROR_T error = { 0 }; - session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - ADD_TOPIC_CALLBACK_T callback = create_topic_callback(topic_name); - - HASH_T *properties = hash_new(2); - hash_add(properties, DIFFUSION_TIME_SERIES_EVENT_VALUE_TYPE, "string"); - - TOPIC_SPECIFICATION_T *spec = topic_specification_init(TOPIC_TYPE_TIME_SERIES); - topic_specification_set_properties(spec, properties); - - add_topic_from_specification(session, topic_name, spec, callback); - - // Sleep for a while - sleep(5); - - topic_specification_free(spec); - hash_free(properties, NULL, NULL); - - /* - * Append 3 values to the time series topic - */ - append_value_to_time_series_topic(session, (char *)topic_name, "hello world!"); - append_value_to_time_series_topic(session, (char *)topic_name, "Diffusion"); - append_value_to_time_series_topic(session, (char *)topic_name, "Push Technology"); - - /* - * Edit the first event in the times series topic - */ - BUF_T *buf = buf_create(); - write_diffusion_string_value("edited hello world!", buf); - - DIFFUSION_TIME_SERIES_EDIT_PARAMS_T edit_params = { - .on_edit = on_edit, - .on_error = on_error_edit, - .topic_path = topic_name, - .original_sequence = 0, - .datatype = DATATYPE_STRING, - .value = buf - }; - diffusion_time_series_edit(session, edit_params, NULL); - - // Sleep for a while - sleep(5); - - buf_free(buf); - - /* - * Close session and free resources. - */ - session_close(session, NULL); - session_free(session); - - credentials_free(credentials); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/c/features/time_series/time-series-range-query.c b/c/features/time_series/time-series-range-query.c deleted file mode 100644 index 4ab2ddff..00000000 --- a/c/features/time_series/time-series-range-query.c +++ /dev/null @@ -1,249 +0,0 @@ -/** - * Copyright © 2020 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.6 - */ - -/* - * This example creates a Time series topic (of String datatype), appends a sequence of - * values to it and performs a range query on it. - */ -#include -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" -#include "conversation.h" - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - {'t', "topic", "Topic name to create and update", ARG_OPTIONAL, ARG_HAS_VALUE, "time-series-range-query"}, - END_OF_ARG_OPTS -}; - - -// Handlers for add topic feature. -static int on_topic_added_with_specification( - SESSION_T *session, - TOPIC_ADD_RESULT_CODE result_code, - void *context) -{ - printf("Added topic \"%s\"\n", (const char *)context); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_failed_with_specification( - SESSION_T *session, - TOPIC_ADD_FAIL_RESULT_CODE result_code, - const DIFFUSION_ERROR_T *error, - void *context) -{ - printf("Failed to add topic \"%s\" (%d) (%d - %s)\n", - (const char *)context, result_code, error->code, error->message); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_discard(SESSION_T *session, void *context) -{ - return HANDLER_SUCCESS; -} - - -static ADD_TOPIC_CALLBACK_T create_topic_callback(const char *topic_name) -{ - ADD_TOPIC_CALLBACK_T callback = { - .on_topic_added_with_specification = on_topic_added_with_specification, - .on_topic_add_failed_with_specification = on_topic_add_failed_with_specification, - .on_discard = on_topic_add_discard, - .context = (char *)topic_name - }; - - return callback; -} - - -// Handlers for appending value to time series topics -static int on_append( - const DIFFUSION_TIME_SERIES_EVENT_METADATA_T *event_metadata, - void *context) -{ - printf("time series append success\n"); - return HANDLER_SUCCESS; -} - - -static int on_error( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("time series append error: %s\n", error->message); - return HANDLER_SUCCESS; -} - - -// Handlers for range query of a time series topic -static int on_query_result( - const DIFFUSION_TIME_SERIES_QUERY_RESULT_T *query_result, - void *context) -{ - LIST_T *events = diffusion_time_series_query_result_get_events(query_result); - int size = diffusion_time_series_query_result_get_selected_count(query_result); - printf("Range query: total results = %d\n", size); - - for(int i = 0; i < size; i++) { - DIFFUSION_TIME_SERIES_EVENT_T *event = list_get_data_indexed(events, i); - - char *author = diffusion_time_series_event_get_author(event); - - char *val; - DIFFUSION_VALUE_T *value = diffusion_time_series_event_get_value(event); - read_diffusion_string_value(value, &val, NULL); - - printf("Range query: [%d] --> [%s] appended the value [%s]\n", i, author, val); - - free(author); - diffusion_value_free(value); - free(val); - } - - list_free(events, (void (*)(void *))diffusion_time_series_event_free); - return HANDLER_SUCCESS; -} - - -// Helper function to append a value to a time series topic -static void append_value_to_time_series_topic( - SESSION_T *session, - char *topic_path, - char *value) -{ - BUF_T *buf = buf_create(); - write_diffusion_string_value(value, buf); - - DIFFUSION_TIME_SERIES_APPEND_PARAMS_T params = { - .on_append = on_append, - .on_error = on_error, - .topic_path = topic_path, - .datatype = DATATYPE_STRING, - .value = buf - }; - - // Append to the time series topic - diffusion_time_series_append(session, params, NULL); - - // Sleep for a while - sleep(1); - - buf_free(buf); -} - -// Program entry point. -int main(int argc, char** argv) -{ - // Standard command-line parsing. - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - const char *password = hash_get(options, "credentials"); - const char *topic_name = hash_get(options, "topic"); - - CREDENTIALS_T *credentials = NULL; - if(password != NULL) { - credentials = credentials_create_password(password); - } - - // Create a session with the Diffusion server. - SESSION_T *session; - DIFFUSION_ERROR_T error = { 0 }; - session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - ADD_TOPIC_CALLBACK_T callback = create_topic_callback(topic_name); - - HASH_T *properties = hash_new(2); - hash_add(properties, DIFFUSION_TIME_SERIES_EVENT_VALUE_TYPE, "string"); - // increase the retained range for the topic by up to 50 values, default is 10. - hash_add(properties, DIFFUSION_TIME_SERIES_RETAINED_RANGE, "limit 50"); - - TOPIC_SPECIFICATION_T *spec = topic_specification_init(TOPIC_TYPE_TIME_SERIES); - topic_specification_set_properties(spec, properties); - - add_topic_from_specification(session, topic_name, spec, callback); - - // Sleep for a while - sleep(5); - - topic_specification_free(spec); - hash_free(properties, NULL, NULL); - - // Append an incremental value to the time series topic 20 times - for (int i = 0; i < 20; i++) { - char *value = calloc(20, sizeof(char)); - sprintf(value, "value %0d", i); - append_value_to_time_series_topic(session, (char *)topic_name, value); - free(value); - } - - // Range query from the 6th update for the next 10 updates - // NOTE: the sequence numbers are zero-based. - DIFFUSION_TIME_SERIES_RANGE_QUERY_T *range_query = diffusion_time_series_range_query(); - diffusion_time_series_range_query_from(range_query, 5, NULL); - diffusion_time_series_range_query_next(range_query, 10, NULL); - - DIFFUSION_TIME_SERIES_RANGE_QUERY_PARAMS_T params_range_query = { - .topic_path = topic_name, - .range_query = range_query, - .on_query_result = on_query_result - }; - - diffusion_time_series_select_from(session, params_range_query, NULL); - - // Sleep for a while - sleep(5); - - diffusion_time_series_range_query_free(range_query); - - // Close session and free resources. - session_close(session, NULL); - session_free(session); - - credentials_free(credentials); - hash_free(options, NULL, free); - return EXIT_SUCCESS; -} diff --git a/c/features/time_series/time-series-timestamp-append.c b/c/features/time_series/time-series-timestamp-append.c deleted file mode 100644 index ba4fada0..00000000 --- a/c/features/time_series/time-series-timestamp-append.c +++ /dev/null @@ -1,211 +0,0 @@ -/** - * Copyright © 2020 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.3 - */ - -/* - * This example creates a Time series topic (of String datatype) and periodically appends - * data to it with a user supplied timestamp. - */ -#include -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - - -#include "diffusion.h" -#include "args.h" -#include "conversation.h" - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - {'t', "topic", "Topic name to create and update", ARG_OPTIONAL, ARG_HAS_VALUE, "time-series-timestamp-append"}, - {'s', "seconds", "Number of seconds to run for before exiting", ARG_OPTIONAL, ARG_HAS_VALUE, "30"}, - END_OF_ARG_OPTS -}; - -/* - * Handlers for add topic feature. - */ -static int on_topic_added_with_specification( - SESSION_T *session, - TOPIC_ADD_RESULT_CODE result_code, - void *context) -{ - printf("Added topic \"%s\"\n", (const char *)context); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_failed_with_specification( - SESSION_T *session, - TOPIC_ADD_FAIL_RESULT_CODE result_code, - const DIFFUSION_ERROR_T *error, - void *context) -{ - printf("Failed to add topic \"%s\" (%d)\n", (const char *)context, result_code); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_discard(SESSION_T *session, void *context) -{ - return HANDLER_SUCCESS; -} - - -static ADD_TOPIC_CALLBACK_T create_topic_callback(const char *topic_name) -{ - ADD_TOPIC_CALLBACK_T callback = { - .on_topic_added_with_specification = on_topic_added_with_specification, - .on_topic_add_failed_with_specification = on_topic_add_failed_with_specification, - .on_discard = on_topic_add_discard, - .context = (char *)topic_name - }; - - return callback; -} - - -static int on_append( - const DIFFUSION_TIME_SERIES_EVENT_METADATA_T *event_metadata, - void *context) -{ - printf("time series append success\n"); - return HANDLER_SUCCESS; -} - - -static int on_error(SESSION_T *session, const DIFFUSION_ERROR_T *error) -{ - printf("time series append error: %s\n", error->message); - return HANDLER_SUCCESS; -} - -/* - * Program entry point. - */ -int main(int argc, char** argv) -{ - /* - * Standard command-line parsing. - */ - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - CREDENTIALS_T *credentials = NULL; - const char *password = hash_get(options, "credentials"); - if(password != NULL) { - credentials = credentials_create_password(password); - } - const char *topic_name = hash_get(options, "topic"); - const long seconds = atol(hash_get(options, "seconds")); - - /* - * Create a session with the Diffusion server. - */ - SESSION_T *session; - DIFFUSION_ERROR_T error = { 0 }; - session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - ADD_TOPIC_CALLBACK_T callback = create_topic_callback(topic_name); - - HASH_T *properties = hash_new(2); - hash_add(properties, DIFFUSION_TIME_SERIES_EVENT_VALUE_TYPE, "string"); - - TOPIC_SPECIFICATION_T *spec = topic_specification_init(TOPIC_TYPE_TIME_SERIES); - topic_specification_set_properties(spec, properties); - - add_topic_from_specification(session, topic_name, spec, callback); - - // Sleep for a while - sleep(5); - - topic_specification_free(spec); - hash_free(properties, NULL, NULL); - - time_t end_time = time(NULL) + seconds; - - while(time(NULL) < end_time) { - - /* - * Compose the update content - */ - const time_t time_now = time(NULL); - const char *time_str = ctime(&time_now); - - /* - * Create a BUF_T and write the string datatype value - * into it. - */ - BUF_T *value = buf_create(); - write_diffusion_string_value(time_str, value); - - /* - * Compose the timestamp value in milliseconds for the append - */ - const long time_previous_day_ms = (time_now - (24 * 60 * 60)) * 1000; - - DIFFUSION_TIME_SERIES_TIMESTAMP_APPEND_PARAMS_T params = { - .on_append = on_append, - .on_error = on_error, - .topic_path = topic_name, - .datatype = DATATYPE_STRING, - .value = value, - .timestamp = time_previous_day_ms - }; - - /* - * Append to the time series topic - */ - diffusion_time_series_timestamp_append(session, params, NULL); - buf_free(value); - - sleep(1); - } - - /* - * Close session and free resources. - */ - session_close(session, NULL); - session_free(session); - - credentials_free(credentials); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/c/features/topic_control/add-topics.c b/c/features/topic_control/add-topics.c deleted file mode 100644 index 36b79640..00000000 --- a/c/features/topic_control/add-topics.c +++ /dev/null @@ -1,264 +0,0 @@ -/** - * Copyright © 2014, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 5.0 - */ - -/* - * This example shows how to connect to Diffusion as a control client and - * create various topics on the server. - */ - -#include -#include -#ifndef WIN32 -#include -#else -#define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" -#include "utils.h" - -// Topic selector, selector set delimiter -#define DELIM "////" - -static int default_sleep_time = 3; - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - END_OF_ARG_OPTS -}; - -// Various handlers which are common to all add_topic() functions. -static int -on_topic_added(SESSION_T *session, TOPIC_ADD_RESULT_CODE result_code, void *context) -{ - printf("on_topic_added: %s\n", (const char *)context); - return HANDLER_SUCCESS; -} - -static int -on_topic_add_failed(SESSION_T *session, TOPIC_ADD_FAIL_RESULT_CODE result_code, const DIFFUSION_ERROR_T *error, void *context) -{ - printf("on_topic_add_failed: %s -> %d\n", (const char *)context, result_code); - return HANDLER_SUCCESS; -} - -static int -on_topic_add_discard(SESSION_T *session, void *context) -{ - puts("on_topic_add_discard"); - return HANDLER_SUCCESS; -} - -static int -on_topic_removed(SESSION_T *session, const DIFFUSION_TOPIC_REMOVAL_RESULT_T *response, void *context) -{ - int removed_topic_count = diffusion_topic_removal_result_removed_count(response); - printf("on_topic_removed: removed %d topic(s).\n", removed_topic_count); - return HANDLER_SUCCESS; -} - -static int -on_topic_remove_discard(SESSION_T *session, void *context) -{ - puts("on_topic_remove_discard"); - return HANDLER_SUCCESS; -} - -static int -on_topic_view_created(const DIFFUSION_TOPIC_VIEW_T *topic_view, void *context) -{ - char *view_name = diffusion_topic_view_get_name(topic_view); - char *spec = diffusion_topic_view_get_specification(topic_view); - - printf("Topic view \"%s\" created with specification \"%s\"\n", view_name, spec); - free(view_name); - free(spec); - - return HANDLER_SUCCESS; -} - -static int -on_error(SESSION_T *session, const DIFFUSION_ERROR_T *error) -{ - printf("Error: %s\n", error->message); - - return HANDLER_SUCCESS; -} - -static ADD_TOPIC_CALLBACK_T -create_topic_callback(char *topic_name) -{ - ADD_TOPIC_CALLBACK_T callback = { - .on_topic_added_with_specification = on_topic_added, - .on_topic_add_failed_with_specification = on_topic_add_failed, - .on_discard = on_topic_add_discard, - .context = topic_name - }; - - return callback; -} - -/* - * - */ -int main(int argc, char** argv) -{ - /* - * Standard command-line parsing. - */ - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - CREDENTIALS_T *credentials = NULL; - const char *password = hash_get(options, "credentials"); - if(password != NULL) { - credentials = credentials_create_password(password); - } - - // Setup for session - SESSION_T *session; - DIFFUSION_ERROR_T error = { 0 }; - session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - /* - * Create a JSON topic. - */ - { - char *json_topic_name = "json"; - TOPIC_SPECIFICATION_T *json_specification = topic_specification_init(TOPIC_TYPE_JSON); - - add_topic_from_specification(session, json_topic_name, json_specification, create_topic_callback(json_topic_name)); - sleep(default_sleep_time); - - topic_specification_free(json_specification); - } - - /* - * Create a topic view which is an alias for the "source" - * topic. - */ - { - char *source_topic_name = "source_topic"; - TOPIC_SPECIFICATION_T *string_specification = topic_specification_init(TOPIC_TYPE_STRING); - - add_topic_from_specification(session, source_topic_name, string_specification, create_topic_callback(source_topic_name)); - sleep(default_sleep_time); - - DIFFUSION_CREATE_TOPIC_VIEW_PARAMS_T topic_view_params = { - .view = "view0", - .specification = "map source_topic to topic_view", - .on_topic_view_created = on_topic_view_created, - .on_error = on_error - }; - - diffusion_topic_views_create_topic_view(session, topic_view_params, NULL); - sleep(default_sleep_time); - - topic_specification_free(string_specification); - } - - /* - * This adds a topic with a record containing multiple fields - * of different types. - */ - { - DIFFUSION_RECORDV2_SCHEMA_BUILDER_T *schema_builder = diffusion_recordv2_schema_builder_init(); - diffusion_recordv2_schema_builder_record(schema_builder, "Record1", NULL); - diffusion_recordv2_schema_builder_string(schema_builder, "Field1", NULL); - diffusion_recordv2_schema_builder_integer(schema_builder, "Field2", NULL); - diffusion_recordv2_schema_builder_decimal(schema_builder, "Field3", 2, NULL); - - DIFFUSION_RECORDV2_SCHEMA_T *schema = diffusion_recordv2_schema_builder_build(schema_builder, NULL); - char *schema_string = diffusion_recordv2_schema_as_json_string(schema); - - HASH_T *properties = hash_new(2); - hash_add(properties, DIFFUSION_VALIDATE_VALUES, "true"); - hash_add(properties, DIFFUSION_SCHEMA, schema_string); - - char *recordv2_topic_name = "recordv2"; - TOPIC_SPECIFICATION_T *recordv2_specification = topic_specification_init_with_properties(TOPIC_TYPE_RECORDV2, properties); - - add_topic_from_specification(session, recordv2_topic_name, recordv2_specification, create_topic_callback(recordv2_topic_name)); - sleep(default_sleep_time); - - diffusion_recordv2_schema_builder_free(schema_builder); - diffusion_recordv2_schema_free(schema); - free(schema_string); - - topic_specification_free(recordv2_specification); - hash_free(properties, NULL, NULL); - } - - /* - * Create a binary topic - */ - { - char *binary_topic_name = "binary"; - TOPIC_SPECIFICATION_T *binary_specification = topic_specification_init(TOPIC_TYPE_BINARY); - - add_topic_from_specification(session, binary_topic_name, binary_specification, create_topic_callback(binary_topic_name)); - sleep(default_sleep_time); - - topic_specification_free(binary_specification); - } - - /* - * We can also remove topics. - */ - { - puts("Removing topics in 5 seconds..."); - sleep(5); - - TOPIC_REMOVAL_PARAMS_T remove_params = { - .on_removed = on_topic_removed, - .on_discard = on_topic_remove_discard, - .topic_selector = "#json" DELIM "topic_view" DELIM "recordv2" DELIM "binary" - }; - - topic_removal(session, remove_params); - sleep(default_sleep_time); - } - - /* - * Close our session, and release resources and memory. - */ - session_close(session, NULL); - session_free(session); - - credentials_free(credentials); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/c/features/topic_control/missing-topic-notification.c b/c/features/topic_control/missing-topic-notification.c deleted file mode 100644 index 8d5e2d2d..00000000 --- a/c/features/topic_control/missing-topic-notification.c +++ /dev/null @@ -1,169 +0,0 @@ -/** - * Copyright © 2016 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 5.7 - */ - -/* - * This example shows how to register a missing topic notification handler. - */ -#include -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - {'r', "topic_root", "Topic root to process missing topic notifications on", ARG_OPTIONAL, ARG_HAS_VALUE, "foo"}, - END_OF_ARG_OPTS -}; - - -// Handlers for add_topic_from_specification() function. -static int on_topic_added_with_specification( - SESSION_T *session, - TOPIC_ADD_RESULT_CODE result_code, - void *context) -{ - puts("Topic added"); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_failed_with_specification( - SESSION_T *session, - TOPIC_ADD_FAIL_RESULT_CODE result_code, - const DIFFUSION_ERROR_T *error, - void *context) -{ - puts("Topic add failed"); - printf("Reason code: %d\n", result_code); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_discard( - SESSION_T *session, - void *context) -{ - puts("Topic add discarded"); - return HANDLER_SUCCESS; -} - - -static ADD_TOPIC_CALLBACK_T create_topic_callback() -{ - ADD_TOPIC_CALLBACK_T callback = { - .on_topic_added_with_specification = on_topic_added_with_specification, - .on_topic_add_failed_with_specification = on_topic_add_failed_with_specification, - .on_discard = on_topic_add_discard - }; - - return callback; -} - - -/* - * A request has been made for a topic that doesn't exist. - * This handler will create the missing topic. - */ -static int on_missing_topic( - SESSION_T *session, - const SVC_MISSING_TOPIC_REQUEST_T *request, - void *context) -{ - printf("Missing topic: %s\n", request->topic_selector); - - ADD_TOPIC_CALLBACK_T callback = create_topic_callback(); - TOPIC_SPECIFICATION_T *spec = topic_specification_init(TOPIC_TYPE_JSON); - - add_topic_from_specification(session, request->topic_selector + 1, spec, callback); - topic_specification_free(spec); - - return HANDLER_SUCCESS; -} - - -// Entry point for the example. -int main(int argc, char **argv) -{ - // Standard command-line parsing. - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - const char *topic_root = hash_get(options, "topic_root"); - const char *password = hash_get(options, "credentials"); - - CREDENTIALS_T *credentials = NULL; - if(password != NULL) { - credentials = credentials_create_password(password); - } - - SESSION_T *session; - DIFFUSION_ERROR_T error = { 0 }; - - session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session != NULL) { - char *session_id = session_id_to_string(session->id); - printf("Session created (state=%d, id=%s)\n", - session_state_get(session), session_id); - free(session_id); - } - else { - printf("Failed to create session: %s\n", error.message); - free(error.message); - return EXIT_FAILURE; - } - - // Register the missing topic handler - MISSING_TOPIC_PARAMS_T handler = { - .on_missing_topic = on_missing_topic, - .topic_path = topic_root, - .context = NULL - }; - - missing_topic_register_handler(session, handler); - - // Run for 5 minutes. - sleep(5 * 60); - - // Close session and free resources. - session_close(session, NULL); - session_free(session); - - hash_free(options, NULL, free); - credentials_free(credentials); - - return EXIT_SUCCESS; -} diff --git a/c/features/topic_update/topic-update-add-and-set.c b/c/features/topic_update/topic-update-add-and-set.c deleted file mode 100644 index 8c972b79..00000000 --- a/c/features/topic_update/topic-update-add-and-set.c +++ /dev/null @@ -1,142 +0,0 @@ -/** - * Copyright © 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.2 - */ - -/* - * This example uses the topic update API to add and set a topic. - * The topic is then periodically updated with data. - */ -#include -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" -#include "conversation.h" - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - {'t', "topic", "Topic name to create and update", ARG_OPTIONAL, ARG_HAS_VALUE, "time"}, - {'s', "seconds", "Number of seconds to run for before exiting", ARG_OPTIONAL, ARG_HAS_VALUE, "30"}, - END_OF_ARG_OPTS -}; - - -static int on_topic_update_add_and_set( - DIFFUSION_TOPIC_CREATION_RESULT_T result, - void *context) -{ - if(result == TOPIC_CREATED) { - printf("topic update success: TOPIC_CREATED\n"); - } - else { - printf("topic update success: TOPIC_EXISTS\n"); - } - - return HANDLER_SUCCESS; -} - - -static int on_error( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("topic update error: %s\n", error->message); - return HANDLER_SUCCESS; -} - - -// Program entry point. -int main(int argc, char** argv) -{ - // Standard command-line parsing. - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - CREDENTIALS_T *credentials = NULL; - const char *password = hash_get(options, "credentials"); - if(password != NULL) { - credentials = credentials_create_password(password); - } - const char *topic_name = hash_get(options, "topic"); - const long seconds = atol(hash_get(options, "seconds")); - - // Create a session with the Diffusion server. - SESSION_T *session; - DIFFUSION_ERROR_T error = { 0 }; - session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - TOPIC_SPECIFICATION_T *spec = topic_specification_init(TOPIC_TYPE_STRING); - time_t end_time = time(NULL) + seconds; - - while(time(NULL) < end_time) { - // Compose the update content - const time_t time_now = time(NULL); - const char *time_str = ctime(&time_now); - - // Create a BUF_T and write the string datatype value into it. - BUF_T *update_buf = buf_create(); - write_diffusion_string_value(time_str, update_buf); - - DIFFUSION_TOPIC_UPDATE_ADD_AND_SET_PARAMS_T topic_update_params = { - .topic_path = topic_name, - .specification = spec, - .datatype = DATATYPE_STRING, - .update = update_buf, - .on_topic_update_add_and_set = on_topic_update_add_and_set, - .on_error = on_error - }; - - // Update the topic. - diffusion_topic_update_add_and_set(session, topic_update_params); - buf_free(update_buf); - - sleep(1); - } - - // Close session and free resources. - session_close(session, NULL); - session_free(session); - - credentials_free(credentials); - topic_specification_free(spec); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/c/features/topic_update/topic-update-stream.c b/c/features/topic_update/topic-update-stream.c deleted file mode 100644 index dc0c9ee5..00000000 --- a/c/features/topic_update/topic-update-stream.c +++ /dev/null @@ -1,203 +0,0 @@ -/** - * Copyright © 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.2 - */ - -/* - * This example creates a String topic and periodically updates - * the data it contains. - */ -#include -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" -#include "conversation.h" - - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - {'t', "topic", "Topic name to create and update", ARG_OPTIONAL, ARG_HAS_VALUE, "time"}, - {'s', "seconds", "Number of seconds to run for before exiting", ARG_OPTIONAL, ARG_HAS_VALUE, "30"}, - END_OF_ARG_OPTS -}; - - -// Handlers for add topic feature. -static int on_topic_added_with_specification( - SESSION_T *session, - TOPIC_ADD_RESULT_CODE result_code, - void *context) -{ - printf("Added topic \"%s\"\n", (const char *)context); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_failed_with_specification( - SESSION_T *session, - TOPIC_ADD_FAIL_RESULT_CODE result_code, - const DIFFUSION_ERROR_T *error, - void *context) -{ - printf("Failed to add topic \"%s\" (%d)\n", (const char *)context, result_code); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_discard( - SESSION_T *session, - void *context) -{ - return HANDLER_SUCCESS; -} - - -static ADD_TOPIC_CALLBACK_T create_topic_callback(const char *topic_name) -{ - ADD_TOPIC_CALLBACK_T callback = { - .on_topic_added_with_specification = on_topic_added_with_specification, - .on_topic_add_failed_with_specification = on_topic_add_failed_with_specification, - .on_discard = on_topic_add_discard, - .context = (char *)topic_name - }; - - return callback; -} - - -static int on_topic_creation_result( - DIFFUSION_TOPIC_CREATION_RESULT_T result, - void *context) -{ - printf("topic update success\n"); - return HANDLER_SUCCESS; -} - - -static int on_error( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("topic update error: %s\n", error->message); - return HANDLER_SUCCESS; -} - -// Program entry point. -int main(int argc, char** argv) -{ - // Standard command-line parsing. - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - const char *password = hash_get(options, "credentials"); - const char *topic_name = hash_get(options, "topic"); - const long seconds = atol(hash_get(options, "seconds")); - - CREDENTIALS_T *credentials = NULL; - if(password != NULL) { - credentials = credentials_create_password(password); - } - - // Create a session with the Diffusion server. - SESSION_T *session; - DIFFUSION_ERROR_T error = { 0 }; - session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - ADD_TOPIC_CALLBACK_T callback = create_topic_callback(topic_name); - TOPIC_SPECIFICATION_T *spec = topic_specification_init(TOPIC_TYPE_STRING); - - add_topic_from_specification(session, topic_name, spec, callback); - - // Sleep for a while - sleep(5); - - topic_specification_free(spec); - - // Create a new update stream for the topic. - DIFFUSION_UPDATE_STREAM_BUILDER_T *builder = diffusion_update_stream_builder_init(); - DIFFUSION_API_ERROR api_error = { 0 }; - - DIFFUSION_TOPIC_UPDATE_STREAM_T *update_stream = - diffusion_update_stream_builder_create_update_stream(builder, topic_name, DATATYPE_STRING, &api_error); - - time_t end_time = time(NULL) + seconds; - - while(time(NULL) < end_time) { - // Compose the update content. - const time_t time_now = time(NULL); - const char *time_str = ctime(&time_now); - - // Get the update stream's current value. - DIFFUSION_VALUE_T *current_value = diffusion_topic_update_stream_get(update_stream); - if(current_value != NULL) { - char *value; - read_diffusion_string_value(current_value, &value, NULL); - printf("current topic value: %s", value); - diffusion_value_free(current_value); - free(value); - } - - // Create a BUF_T and write the string datatype value into it. - BUF_T *update_buf = buf_create(); - write_diffusion_string_value(time_str, update_buf); - - DIFFUSION_TOPIC_UPDATE_STREAM_PARAMS_T update_stream_params = { - .on_topic_creation_result = on_topic_creation_result, - .on_error = on_error - }; - - // Update the topic with the update stream. - diffusion_topic_update_stream_set(session, update_stream, update_buf, update_stream_params); - buf_free(update_buf); - - sleep(1); - } - - // Close session and free resources. - session_close(session, NULL); - session_free(session); - - credentials_free(credentials); - diffusion_topic_update_stream_free(update_stream); - diffusion_update_stream_builder_free(builder); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/c/features/topic_update/topic-update-with-constraint.c b/c/features/topic_update/topic-update-with-constraint.c deleted file mode 100644 index b9a7619c..00000000 --- a/c/features/topic_update/topic-update-with-constraint.c +++ /dev/null @@ -1,218 +0,0 @@ -/** - * Copyright © 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.2 - */ - -/* - * This example creates a String topic and periodically updates - * the data it contains. - * - * In order to perform the update, a constraint is evaluated - in this - * example, the constraint is an acquired session lock. - */ -#include -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" -#include "conversation.h" - - -DIFFUSION_SESSION_LOCK_T *g_session_lock = NULL; - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - {'t', "topic", "Topic name to create and update", ARG_OPTIONAL, ARG_HAS_VALUE, "time"}, - {'s', "seconds", "Number of seconds to run for before exiting", ARG_OPTIONAL, ARG_HAS_VALUE, "30"}, - END_OF_ARG_OPTS -}; - -// Handlers for add topic feature. -static int on_topic_added_with_specification( - SESSION_T *session, - TOPIC_ADD_RESULT_CODE result_code, - void *context) -{ - printf("Added topic \"%s\"\n", (const char *)context); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_failed_with_specification( - SESSION_T *session, - TOPIC_ADD_FAIL_RESULT_CODE result_code, - const DIFFUSION_ERROR_T *error, - void *context) -{ - printf("Failed to add topic \"%s\" (%d)\n", (const char *)context, result_code); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_discard(SESSION_T *session, void *context) -{ - return HANDLER_SUCCESS; -} - - -static ADD_TOPIC_CALLBACK_T create_topic_callback(const char *topic_name) -{ - ADD_TOPIC_CALLBACK_T callback = { - .on_topic_added_with_specification = on_topic_added_with_specification, - .on_topic_add_failed_with_specification = on_topic_add_failed_with_specification, - .on_discard = on_topic_add_discard, - .context = (char *)topic_name - }; - - return callback; -} - - -static int on_topic_update(void *context) -{ - printf("topic update success\n"); - return HANDLER_SUCCESS; -} - - -static int on_error( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("topic update error: %s\n", error->message); - return HANDLER_SUCCESS; -} - - -static int on_lock_acquired( - const DIFFUSION_SESSION_LOCK_T *session_lock, - void *context) -{ - char *lock_name = diffusion_session_lock_get_name(session_lock); - printf("session lock acquired: %s\n", lock_name); - free(lock_name); - - g_session_lock = diffusion_session_lock_dup(session_lock); - - return HANDLER_SUCCESS; -} - - -// Program entry point. -int main(int argc, char** argv) -{ - // Standard command-line parsing. - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - CREDENTIALS_T *credentials = NULL; - const char *password = hash_get(options, "credentials"); - if(password != NULL) { - credentials = credentials_create_password(password); - } - const char *topic_name = hash_get(options, "topic"); - const long seconds = atol(hash_get(options, "seconds")); - - // Create a session with the Diffusion server. - SESSION_T *session; - DIFFUSION_ERROR_T error = { 0 }; - session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - ADD_TOPIC_CALLBACK_T callback = create_topic_callback(topic_name); - TOPIC_SPECIFICATION_T *spec = topic_specification_init(TOPIC_TYPE_STRING); - - add_topic_from_specification(session, topic_name, spec, callback); - - // Sleep for a while - sleep(5); - - topic_specification_free(spec); - - DIFFUSION_SESSION_LOCK_PARAMS_T lock_params = { - .on_lock_acquired = on_lock_acquired - }; - - // Acquire the session lock. - diffusion_session_lock(session, "topic-update-lock", lock_params); - - // Sleep for a while - sleep(5); - - // Create the session lock topic update constraint. - DIFFUSION_TOPIC_UPDATE_CONSTRAINT_T *session_lock_constraint = - diffusion_topic_update_constraint_locked(g_session_lock); - - time_t end_time = time(NULL) + seconds; - - while(time(NULL) < end_time) { - // Compose the update content. - const time_t time_now = time(NULL); - const char *time_str = ctime(&time_now); - - // Create a BUF_T and write the string datatype value into it. - BUF_T *update_buf = buf_create(); - write_diffusion_string_value(time_str, update_buf); - - DIFFUSION_TOPIC_UPDATE_SET_PARAMS_T topic_update_params = { - .topic_path = topic_name, - .datatype = DATATYPE_STRING, - .update = update_buf, - .on_topic_update = on_topic_update, - .on_error = on_error - }; - - // Update the topic with the constraint to be evaluated. - diffusion_topic_update_set_with_constraint( - session, - session_lock_constraint, - topic_update_params); - buf_free(update_buf); - - sleep(1); - } - - // Close session and free resources. - session_close(session, NULL); - session_free(session); - - credentials_free(credentials); - diffusion_topic_update_constraint_free(session_lock_constraint); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/c/features/topic_update/topic-update.c b/c/features/topic_update/topic-update.c deleted file mode 100644 index df9198b2..00000000 --- a/c/features/topic_update/topic-update.c +++ /dev/null @@ -1,185 +0,0 @@ -/** - * Copyright © 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.2 - */ - -/* - * This example creates a String topic and periodically updates - * the data it contains. - */ -#include -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" -#include "conversation.h" - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - {'t', "topic", "Topic name to create and update", ARG_OPTIONAL, ARG_HAS_VALUE, "time"}, - {'s', "seconds", "Number of seconds to run for before exiting", ARG_OPTIONAL, ARG_HAS_VALUE, "30"}, - END_OF_ARG_OPTS -}; - - -// Handlers for add topic feature. -static int on_topic_added_with_specification( - SESSION_T *session, - TOPIC_ADD_RESULT_CODE result_code, - void *context) -{ - printf("Added topic \"%s\"\n", (const char *)context); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_failed_with_specification( - SESSION_T *session, - TOPIC_ADD_FAIL_RESULT_CODE result_code, - const DIFFUSION_ERROR_T *error, - void *context) -{ - printf("Failed to add topic \"%s\" (%d)\n", (const char *)context, result_code); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_discard( - SESSION_T *session, - void *context) -{ - return HANDLER_SUCCESS; -} - - -static ADD_TOPIC_CALLBACK_T create_topic_callback(const char *topic_name) -{ - ADD_TOPIC_CALLBACK_T callback = { - .on_topic_added_with_specification = on_topic_added_with_specification, - .on_topic_add_failed_with_specification = on_topic_add_failed_with_specification, - .on_discard = on_topic_add_discard, - .context = (char *)topic_name - }; - - return callback; -} - - -static int on_topic_update(void *context) -{ - printf("topic update success\n"); - return HANDLER_SUCCESS; -} - - -static int on_error( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("topic update error: %s\n", error->message); - return HANDLER_SUCCESS; -} - - -// Program entry point. -int main(int argc, char** argv) -{ - // Standard command-line parsing. - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - const char *password = hash_get(options, "credentials"); - const char *topic_name = hash_get(options, "topic"); - const long seconds = atol(hash_get(options, "seconds")); - - CREDENTIALS_T *credentials = NULL; - if(password != NULL) { - credentials = credentials_create_password(password); - } - - // Create a session with the Diffusion server. - SESSION_T *session; - DIFFUSION_ERROR_T error = { 0 }; - session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - ADD_TOPIC_CALLBACK_T callback = create_topic_callback(topic_name); - TOPIC_SPECIFICATION_T *spec = topic_specification_init(TOPIC_TYPE_STRING); - - add_topic_from_specification(session, topic_name, spec, callback); - - // Sleep for a while - sleep(5); - - topic_specification_free(spec); - - time_t end_time = time(NULL) + seconds; - - while(time(NULL) < end_time) { - // Compose the update content - const time_t time_now = time(NULL); - const char *time_str = ctime(&time_now); - - // Create a BUF_T and write the string datatype value into it. - BUF_T *update_buf = buf_create(); - write_diffusion_string_value(time_str, update_buf); - - DIFFUSION_TOPIC_UPDATE_SET_PARAMS_T topic_update_params = { - .topic_path = topic_name, - .datatype = DATATYPE_STRING, - .update = update_buf, - .on_topic_update = on_topic_update, - .on_error = on_error - }; - - // Update the topic. - diffusion_topic_update_set(session, topic_update_params); - buf_free(update_buf); - - sleep(1); - } - - // Close session and free resources. - session_close(session, NULL); - session_free(session); - - credentials_free(credentials); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/c/features/topic_update/update-record.c b/c/features/topic_update/update-record.c deleted file mode 100644 index db17d6f8..00000000 --- a/c/features/topic_update/update-record.c +++ /dev/null @@ -1,255 +0,0 @@ -/** - * Copyright © 2014 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 5.0 - */ - -/* - * This example creates simple RecordTopicData with a single Record - * containing two Fields, and updates it every second. - * - * When running this example, it's possible to choose whether - * subscribing clients see a entire contents of the topic with every - * update, or just the fields that have changed (ie, a delta). - */ -#include -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" -#include "conversation.h" - - -int active = 0; - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - {'t', "topic", "Topic name to create and update", ARG_OPTIONAL, ARG_HAS_VALUE, "foo"}, - {'s', "seconds", "Number of seconds to run for before exiting", ARG_OPTIONAL, ARG_HAS_VALUE, "30"}, - END_OF_ARG_OPTS -}; - -static const char *EMPTY_FIELD_MARKER = "-EMPTY-"; - -// Handlers for adding topics. -static int on_topic_added( - SESSION_T *session, - TOPIC_ADD_RESULT_CODE result_code, - void *context) -{ - printf("Added topic\n"); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_failed( - SESSION_T *session, - TOPIC_ADD_FAIL_RESULT_CODE result_code, - const DIFFUSION_ERROR_T *error, - void *context) -{ - printf("Failed to add topic (%d)\n", result_code); - return HANDLER_SUCCESS; -} - - -static int on_topic_update(void *context) -{ - printf("topic update success\n"); - return HANDLER_SUCCESS; -} - - -static int on_error( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("topic update error: %s\n", error->message); - return HANDLER_SUCCESS; -} - - -int main(int argc, char** argv) -{ - // Standard command-line parsing. - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - const char *password = hash_get(options, "credentials"); - const char *topic_name = hash_get(options, "topic"); - const long seconds = atol(hash_get(options, "seconds")); - - CREDENTIALS_T *credentials = NULL; - if(password != NULL) { - credentials = credentials_create_password(password); - } - - // Connect to the Diffusion server. - SESSION_T *session; - DIFFUSION_ERROR_T error = { 0 }; - session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - // Add a topic with a simple record topic data structure, containing two fields. - DIFFUSION_RECORDV2_SCHEMA_BUILDER_T *schema_builder = diffusion_recordv2_schema_builder_init(); - diffusion_recordv2_schema_builder_record(schema_builder, "SimpleRecord", NULL); - diffusion_recordv2_schema_builder_string(schema_builder, "first", NULL); - diffusion_recordv2_schema_builder_string(schema_builder, "second", NULL); - - DIFFUSION_RECORDV2_SCHEMA_T *schema = diffusion_recordv2_schema_builder_build(schema_builder, NULL); - char *schema_as_string = diffusion_recordv2_schema_as_json_string(schema); - - HASH_T *properties = hash_new(2); - hash_add(properties, DIFFUSION_VALIDATE_VALUES, "true"); - hash_add(properties, DIFFUSION_SCHEMA, schema_as_string); - - TOPIC_SPECIFICATION_T *recordv2_specification = topic_specification_init_with_properties(TOPIC_TYPE_RECORDV2, properties); - - ADD_TOPIC_CALLBACK_T callback = { - .on_topic_added_with_specification = on_topic_added, - .on_topic_add_failed_with_specification = on_topic_add_failed, - .on_discard = NULL, - .context = (void *)topic_name - }; - - add_topic_from_specification(session, topic_name, recordv2_specification, callback); - - // Sleep for a while - sleep(5); - - diffusion_recordv2_schema_builder_free(schema_builder); - diffusion_recordv2_schema_free(schema); - free(schema_as_string); - - topic_specification_free(recordv2_specification); - hash_free(properties, NULL, NULL); - - // Alternately update one field or both every second. - int count1 = 0; - int count2 = 0; - - DIFFUSION_RECORDV2_BUILDER_T *value_builder = diffusion_recordv2_builder_init(); - char **fields = calloc(3, sizeof(char *)); - time_t end_time = time(NULL) + seconds; - - while(time(NULL) < end_time) { - BUF_T *buf = buf_create(); - - if(count1 % 2 == 0) { - count2++; - } - count1++; - - char *count1_string = NULL; - char *count2_string = NULL; - - if(count1 == 5 || count1 == 6) { - fields[0] = (char *)EMPTY_FIELD_MARKER; - fields[1] = (char *)EMPTY_FIELD_MARKER; - } - else { - count1_string = calloc(20, sizeof(char)); - count2_string = calloc(20, sizeof(char)); - snprintf(count1_string, 20, "%d", count1); - snprintf(count2_string, 20, "%d", count2); - fields[0] = count1_string; - fields[1] = count2_string; - } - - diffusion_recordv2_builder_add_record(value_builder, fields); - void *record_bytes = diffusion_recordv2_builder_build(value_builder); - - if(!write_diffusion_recordv2_value(record_bytes, buf)) { - fprintf(stderr, "Unable to write the recordv2 update\n"); - - // free resources - diffusion_recordv2_builder_free(value_builder); - - free(fields); - - buf_free(buf); - - if (count1_string != NULL) { - free(count1_string); - } - - if (count2_string != NULL) { - free(count2_string); - } - - return EXIT_FAILURE; - } - - DIFFUSION_TOPIC_UPDATE_SET_PARAMS_T topic_update_params = { - .topic_path = topic_name, - .datatype = DATATYPE_RECORDV2, - .update = buf, - .on_topic_update = on_topic_update, - .on_error = on_error - }; - - // Update the topic. - diffusion_topic_update_set(session, topic_update_params); - - // Sleep for a while. - sleep(3); - - diffusion_recordv2_builder_clear(value_builder); - free(record_bytes); - buf_free(buf); - - if (count1_string != NULL) { - free(count1_string); - } - - if (count2_string != NULL) { - free(count2_string); - } - - sleep(1); - } - - diffusion_recordv2_builder_free(value_builder); - free(fields); - - // Close session and free resources. - session_close(session, NULL); - session_free(session); - hash_free(options, NULL, free); - - puts("Done."); - return EXIT_SUCCESS; -} diff --git a/c/features/topic_views/topic-views-get.c b/c/features/topic_views/topic-views-get.c deleted file mode 100644 index 4e1438d6..00000000 --- a/c/features/topic_views/topic-views-get.c +++ /dev/null @@ -1,319 +0,0 @@ -/** - * Copyright © 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.8 - */ - -/* - * This example creates multiple topics and corresponding topic views. - * The topic views are listed and we retrieve a topic view. - */ -#include -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" -#include "conversation.h" - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - {'t', "topic", "Topic name to create and update", ARG_OPTIONAL, ARG_HAS_VALUE, "source"}, - END_OF_ARG_OPTS -}; - -// Forward declaration -static void print_topic_view(DIFFUSION_TOPIC_VIEW_T *topic_view); - - -// Handlers for add topic feature. -static int on_topic_added_with_specification( - SESSION_T *session, - TOPIC_ADD_RESULT_CODE result_code, - void *context) -{ - printf("Added topic \"%s\"\n", (const char *)context); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_failed_with_specification( - SESSION_T *session, - TOPIC_ADD_FAIL_RESULT_CODE result_code, - const DIFFUSION_ERROR_T *error, - void *context) -{ - printf("Failed to add topic \"%s\" (%d)\n", (const char *)context, result_code); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_discard( - SESSION_T *session, - void *context) -{ - printf("Topic add discarded\n"); - return HANDLER_SUCCESS; -} - - -static ADD_TOPIC_CALLBACK_T create_topic_callback(const char *topic_name) -{ - ADD_TOPIC_CALLBACK_T callback = { - .on_topic_added_with_specification = on_topic_added_with_specification, - .on_topic_add_failed_with_specification = on_topic_add_failed_with_specification, - .on_discard = on_topic_add_discard, - .context = (char *)topic_name - }; - - return callback; -} - - -static int on_topic_view_created( - const DIFFUSION_TOPIC_VIEW_T *topic_view, - void *context) -{ - char *view_name = diffusion_topic_view_get_name(topic_view); - char *spec = diffusion_topic_view_get_specification(topic_view); - - printf("Topic view \"%s\" created with specification \"%s\"\n", view_name, spec); - - free(view_name); - free(spec); - - return HANDLER_SUCCESS; -} - - -static int on_error(SESSION_T *session, const DIFFUSION_ERROR_T *error) -{ - printf("Error: %s\n", error->message); - return HANDLER_SUCCESS; -} - - -// Handlers for listing Topic views -static int on_topic_views_list( - const LIST_T *topic_views, - void *context) -{ - int size = list_get_size(topic_views); - - printf("Total topic views: %d\n", size); - for (int i = 0; i < size; i++) { - DIFFUSION_TOPIC_VIEW_T *topic_view = list_get_data_indexed(topic_views, i); - print_topic_view(topic_view); - } - return HANDLER_SUCCESS; -} - - -static int on_error_list( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("An error has occured while listing Topic Views: (%d) %s\n", error->code, error->message); - - return HANDLER_SUCCESS; -} - - -// Handlers for retrieving the topic view information -static int on_topic_view_get (const DIFFUSION_TOPIC_VIEW_T *topic_view, void *context) -{ - printf("Received a topic view.\n"); - print_topic_view((DIFFUSION_TOPIC_VIEW_T *) topic_view); - - return HANDLER_SUCCESS; -} - - -static int on_error_get( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("An error has occured while retrieving a Topic View: (%d) %s\n", error->code, error->message); - - return HANDLER_SUCCESS; -} - - -// Helper functions to create topics and topic views, list, get and print topic views -static void print_topic_view(DIFFUSION_TOPIC_VIEW_T *topic_view) -{ - char *view_name = diffusion_topic_view_get_name(topic_view); - char *view_specification = diffusion_topic_view_get_specification(topic_view); - SET_T *view_roles = diffusion_topic_view_get_roles(topic_view); - - printf("%s: [%s] [", view_name, view_specification); - char **values = (char **) set_values(view_roles); - for(char **value = values; *value != NULL; value++) { - printf("%s ", *value); - } - printf("]\n"); - - free(values); - set_free(view_roles); - free(view_specification); - free(view_name); -} - - -static void create_topic_and_topic_view( - SESSION_T *session, - char *root_topic_path, - char *topic_name, - char *view_name) -{ - char *topic_path = calloc(strlen(root_topic_path) + strlen(topic_name) + 2, sizeof(char)); - sprintf(topic_path, "%s/%s", root_topic_path, topic_name); - - char *topic_view_path = calloc(strlen(view_name) + 7, sizeof(char)); - sprintf(topic_view_path, "views/%s", view_name); - - ADD_TOPIC_CALLBACK_T callback = create_topic_callback(topic_path); - TOPIC_SPECIFICATION_T *spec = topic_specification_init(TOPIC_TYPE_STRING); - - // Create the source topic. - add_topic_from_specification(session, topic_path, spec, callback); - - // Sleep for a while - sleep(5); - - BUF_T *buf = buf_create(); - buf_sprintf(buf, "map %s to %s", topic_path, topic_view_path); - - char *topic_view_spec = buf_as_string(buf); - - DIFFUSION_CREATE_TOPIC_VIEW_PARAMS_T topic_view_params = { - .view = view_name, - .specification = topic_view_spec, - .on_topic_view_created = on_topic_view_created, - .on_error = on_error - }; - - // Send the request to create the topic view. - diffusion_topic_views_create_topic_view(session, topic_view_params, NULL); - - // Sleep for a while - sleep(5); - - // Free resources. - free(topic_view_spec); - buf_free(buf); - topic_specification_free(spec); - free(topic_view_path); - free(topic_path); -} - - -static void list_topic_views(SESSION_T *session) -{ - DIFFUSION_TOPIC_VIEWS_LIST_PARAMS_T params_list = { - .on_topic_views_list = on_topic_views_list, - .on_error = on_error_list - }; - diffusion_topic_views_list_topic_views(session, params_list, NULL); - - // Sleep for a while - sleep(5); -} - - -static void get_topic_view( - SESSION_T *session, - char *view_name) -{ - DIFFUSION_GET_TOPIC_VIEW_PARAMS_T params = { - .name = view_name, - .on_topic_view = on_topic_view_get, - .on_error = on_error_get, - }; - - // Send the request to retrieve the topic view. - diffusion_topic_views_get_topic_view(session, params, NULL); - - // Sleep for a while - sleep(5); -} - - -// Program entry point. -int main(int argc, char** argv) -{ - // Standard command-line parsing. - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - const char *password = hash_get(options, "credentials"); - const char *topic_name = hash_get(options, "topic"); - - CREDENTIALS_T *credentials = NULL; - if(password != NULL) { - credentials = credentials_create_password(password); - } - - // Create a session with the Diffusion server. - SESSION_T *session; - DIFFUSION_ERROR_T error = { 0 }; - session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "Failed to create session\n"); - fprintf(stderr, "%s\n", error.message); - return EXIT_FAILURE; - } - - // Create multiple topics and corresponding topic views - create_topic_and_topic_view(session, (char *) topic_name, "topic_path_example_1", "view_1"); - create_topic_and_topic_view(session, (char *) topic_name, "topic_path_example_2", "view_2"); - create_topic_and_topic_view(session, (char *) topic_name, "topic_path_example_3", "view_3"); - create_topic_and_topic_view(session, (char *) topic_name, "topic_path_example_4", "view_4"); - - // List the topic views before removal - list_topic_views(session); - - // Get topic view details - get_topic_view(session, "view_1"); - get_topic_view(session, "view_2"); - get_topic_view(session, "view_3"); - get_topic_view(session, "view_4"); - - // Close session and free resources. - session_close(session, NULL); - session_free(session); - - credentials_free(credentials); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/c/features/topic_views/topic-views-list.c b/c/features/topic_views/topic-views-list.c deleted file mode 100644 index 71b455a9..00000000 --- a/c/features/topic_views/topic-views-list.c +++ /dev/null @@ -1,260 +0,0 @@ -/** - * Copyright © 2020 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.6 - */ - -/* - * This example creates multiple topics and corresponding topic views. - * The method `diffusion_topic_views_list_topic_views` is used to list all - * available topic views. - */ -#include -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" -#include "conversation.h" - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - {'t', "topic", "Topic name to create and update", ARG_OPTIONAL, ARG_HAS_VALUE, "source"}, - END_OF_ARG_OPTS -}; - - -// Handlers for add topic feature. -static int on_topic_added_with_specification( - SESSION_T *session, - TOPIC_ADD_RESULT_CODE result_code, - void *context) -{ - printf("Added topic \"%s\"\n", (const char *)context); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_failed_with_specification( - SESSION_T *session, - TOPIC_ADD_FAIL_RESULT_CODE result_code, - const DIFFUSION_ERROR_T *error, - void *context) -{ - printf("Failed to add topic \"%s\" (%d)\n", (const char *)context, result_code); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_discard(SESSION_T *session, void *context) -{ - printf("Topic add discarded\n"); - return HANDLER_SUCCESS; -} - - -static ADD_TOPIC_CALLBACK_T create_topic_callback(const char *topic_name) -{ - ADD_TOPIC_CALLBACK_T callback = { - .on_topic_added_with_specification = on_topic_added_with_specification, - .on_topic_add_failed_with_specification = on_topic_add_failed_with_specification, - .on_discard = on_topic_add_discard, - .context = (char *)topic_name - }; - - return callback; -} - - -static int on_topic_view_created(const DIFFUSION_TOPIC_VIEW_T *topic_view, void *context) -{ - char *view_name = diffusion_topic_view_get_name(topic_view); - char *spec = diffusion_topic_view_get_specification(topic_view); - - printf("Topic view \"%s\" created with specification \"%s\"\n", view_name, spec); - - free(view_name); - free(spec); - - return HANDLER_SUCCESS; -} - - -static int on_error( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("Error: %s\n", error->message); - return HANDLER_SUCCESS; -} - - -// Handlers for listing Topic views -static int on_topic_views_list( - const LIST_T *topic_views, - void *context) -{ - int size = list_get_size(topic_views); - - printf("Total topic views: %d\n", size); - for (int i = 0; i < size; i++) { - DIFFUSION_TOPIC_VIEW_T *topic_view = list_get_data_indexed(topic_views, i); - - char *view_name = diffusion_topic_view_get_name(topic_view); - char *view_specification = diffusion_topic_view_get_specification(topic_view); - SET_T *view_roles = diffusion_topic_view_get_roles(topic_view); - - printf("%s: [%s] [", view_name, view_specification); - char **values = (char **) set_values(view_roles); - for(char **value = values; *value != NULL; value++) { - printf("%s ", *value); - } - printf("]\n"); - - free(values); - set_free(view_roles); - free(view_specification); - free(view_name); - } - return HANDLER_SUCCESS; -} - - -static int on_error_list( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("An error has occured while listing Topic Views: (%d) %s\n", error->code, error->message); - return HANDLER_SUCCESS; -} - - -// Helper functions to create topics and topic views -static void create_topic_and_topic_view( - SESSION_T *session, - char *root_topic_path, - char *topic_name, - char *view_name) { - - char *topic_path = calloc(strlen(root_topic_path) + strlen(topic_name) + 2, sizeof(char)); - sprintf(topic_path, "%s/%s", root_topic_path, topic_name); - - char *topic_view_path = calloc(strlen(view_name) + 7, sizeof(char)); - sprintf(topic_view_path, "views/%s", view_name); - - ADD_TOPIC_CALLBACK_T callback = create_topic_callback(topic_path); - TOPIC_SPECIFICATION_T *spec = topic_specification_init(TOPIC_TYPE_STRING); - - // Create the source topic. - add_topic_from_specification(session, topic_path, spec, callback); - - // Sleep for a while - sleep(5); - - // Create the topic view specification string. - // Maps topic to reference topic. - BUF_T *buf = buf_create(); - buf_sprintf(buf, "map %s to %s", topic_path, topic_view_path); - - char *topic_view_spec = buf_as_string(buf); - - DIFFUSION_CREATE_TOPIC_VIEW_PARAMS_T topic_view_params = { - .view = view_name, - .specification = topic_view_spec, - .on_topic_view_created = on_topic_view_created, - .on_error = on_error - }; - - // Send the request to create the topic view. - diffusion_topic_views_create_topic_view(session, topic_view_params, NULL); - - // Sleep for a while - sleep(5); - - // Free resources. - free(topic_view_spec); - buf_free(buf); - topic_specification_free(spec); - free(topic_view_path); - free(topic_path); -} - - -// Program entry point. -int main(int argc, char** argv) -{ - // Standard command-line parsing. - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - CREDENTIALS_T *credentials = NULL; - const char *password = hash_get(options, "credentials"); - if(password != NULL) { - credentials = credentials_create_password(password); - } - const char *topic_name = hash_get(options, "topic"); - - // Create a session with the Diffusion server. - SESSION_T *session; - DIFFUSION_ERROR_T error = { 0 }; - session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - // Create multiple topics and corresponding topic views - create_topic_and_topic_view(session, (char *) topic_name, "topic_path_example_1", "view_1"); - create_topic_and_topic_view(session, (char *) topic_name, "topic_path_example_2", "view_2"); - create_topic_and_topic_view(session, (char *) topic_name, "topic_path_example_3", "view_3"); - create_topic_and_topic_view(session, (char *) topic_name, "topic_path_example_4", "view_4"); - - // List the topic views - DIFFUSION_TOPIC_VIEWS_LIST_PARAMS_T params_list = { - .on_topic_views_list = on_topic_views_list, - .on_error = on_error_list - }; - diffusion_topic_views_list_topic_views(session, params_list, NULL); - - // Sleep for a while - sleep(5); - - // Close session and free resources. - session_close(session, NULL); - session_free(session); - - credentials_free(credentials); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/c/features/topic_views/topic-views-remove.c b/c/features/topic_views/topic-views-remove.c deleted file mode 100644 index f570a826..00000000 --- a/c/features/topic_views/topic-views-remove.c +++ /dev/null @@ -1,295 +0,0 @@ -/** - * Copyright © 2020 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.6 - */ - -/* - * This example creates multiple topics and corresponding topic views. - * The topic views are listed before and after removing a topic view. - */ -#include -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" -#include "conversation.h" - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - {'t', "topic", "Topic name to create and update", ARG_OPTIONAL, ARG_HAS_VALUE, "source"}, - END_OF_ARG_OPTS -}; - - -// Handlers for add topic feature. -static int on_topic_added_with_specification( - SESSION_T *session, - TOPIC_ADD_RESULT_CODE result_code, - void *context) -{ - printf("Added topic \"%s\"\n", (const char *)context); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_failed_with_specification( - SESSION_T *session, - TOPIC_ADD_FAIL_RESULT_CODE result_code, - const DIFFUSION_ERROR_T *error, - void *context) -{ - printf("Failed to add topic \"%s\" (%d)\n", (const char *)context, result_code); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_discard( - SESSION_T *session, - void *context) -{ - printf("Topic add discarded\n"); - return HANDLER_SUCCESS; -} - - -static ADD_TOPIC_CALLBACK_T create_topic_callback(const char *topic_name) -{ - ADD_TOPIC_CALLBACK_T callback = { - .on_topic_added_with_specification = on_topic_added_with_specification, - .on_topic_add_failed_with_specification = on_topic_add_failed_with_specification, - .on_discard = on_topic_add_discard, - .context = (char *)topic_name - }; - - return callback; -} - - -static int on_topic_view_created( - const DIFFUSION_TOPIC_VIEW_T *topic_view, - void *context) -{ - char *view_name = diffusion_topic_view_get_name(topic_view); - char *spec = diffusion_topic_view_get_specification(topic_view); - - printf("Topic view \"%s\" created with specification \"%s\"\n", view_name, spec); - - free(view_name); - free(spec); - - return HANDLER_SUCCESS; -} - - -static int on_error(SESSION_T *session, const DIFFUSION_ERROR_T *error) -{ - printf("Error: %s\n", error->message); - return HANDLER_SUCCESS; -} - - -// Handlers for listing Topic views -static int on_topic_views_list(const LIST_T *topic_views, void *context) -{ - int size = list_get_size(topic_views); - - printf("Total topic views: %d\n", size); - for (int i = 0; i < size; i++) { - DIFFUSION_TOPIC_VIEW_T *topic_view = list_get_data_indexed(topic_views, i); - - char *view_name = diffusion_topic_view_get_name(topic_view); - char *view_specification = diffusion_topic_view_get_specification(topic_view); - SET_T *view_roles = diffusion_topic_view_get_roles(topic_view); - - printf("%s: [%s] [", view_name, view_specification); - char **values = (char **) set_values(view_roles); - for(char **value = values; *value != NULL; value++) { - printf("%s ", *value); - } - printf("]\n"); - - free(values); - set_free(view_roles); - free(view_specification); - free(view_name); - } - return HANDLER_SUCCESS; -} - - -static int on_error_list( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("An error has occured while listing Topic Views: (%d) %s\n", error->code, error->message); - return HANDLER_SUCCESS; -} - - -// Handlers for topic view removal -static int on_topic_view_removed(void *context) -{ - printf("Topic view has been removed.\n"); - return HANDLER_SUCCESS; -} - - -static int on_error_remove( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("An error has occured while removing a topic view: (%d) %s\n", error->code, error->message); - return HANDLER_SUCCESS; -} - - -// Helper functions to create topics and topic views and list topic views -static void create_topic_and_topic_view( - SESSION_T *session, - char *root_topic_path, - char *topic_name, - char *view_name) { - - char *topic_path = calloc(strlen(root_topic_path) + strlen(topic_name) + 2, sizeof(char)); - sprintf(topic_path, "%s/%s", root_topic_path, topic_name); - - char *topic_view_path = calloc(strlen(view_name) + 7, sizeof(char)); - sprintf(topic_view_path, "views/%s", view_name); - - ADD_TOPIC_CALLBACK_T callback = create_topic_callback(topic_path); - TOPIC_SPECIFICATION_T *spec = topic_specification_init(TOPIC_TYPE_STRING); - - // Create the source topic. - add_topic_from_specification(session, topic_path, spec, callback); - - // Sleep for a while - sleep(5); - - BUF_T *buf = buf_create(); - buf_sprintf(buf, "map %s to %s", topic_path, topic_view_path); - - char *topic_view_spec = buf_as_string(buf); - - DIFFUSION_CREATE_TOPIC_VIEW_PARAMS_T topic_view_params = { - .view = view_name, - .specification = topic_view_spec, - .on_topic_view_created = on_topic_view_created, - .on_error = on_error - }; - - // Send the request to create the topic view. - diffusion_topic_views_create_topic_view(session, topic_view_params, NULL); - - // Sleep for a while - sleep(5); - - // Free resources. - free(topic_view_spec); - buf_free(buf); - topic_specification_free(spec); - free(topic_view_path); - free(topic_path); -} - - -static void list_topic_views(SESSION_T *session) -{ - DIFFUSION_TOPIC_VIEWS_LIST_PARAMS_T params_list = { - .on_topic_views_list = on_topic_views_list, - .on_error = on_error_list - }; - - diffusion_topic_views_list_topic_views(session, params_list, NULL); - - // Sleep for a while - sleep(5); -} - -// Program entry point -int main(int argc, char** argv) -{ - // Standard command-line parsing. - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - const char *password = hash_get(options, "credentials"); - const char *topic_name = hash_get(options, "topic"); - - CREDENTIALS_T *credentials = NULL; - if(password != NULL) { - credentials = credentials_create_password(password); - } - - // Create a session with the Diffusion server. - SESSION_T *session; - DIFFUSION_ERROR_T error = { 0 }; - session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - // Create multiple topics and corresponding topic views - create_topic_and_topic_view(session, (char *) topic_name, "topic_path_example_1", "view_1"); - create_topic_and_topic_view(session, (char *) topic_name, "topic_path_example_2", "view_2"); - create_topic_and_topic_view(session, (char *) topic_name, "topic_path_example_3", "view_3"); - create_topic_and_topic_view(session, (char *) topic_name, "topic_path_example_4", "view_4"); - - // List the topic views before removal - list_topic_views(session); - - // Remove topic view - DIFFUSION_REMOVE_TOPIC_VIEW_PARAMS_T params_remove = { - .view = "view_2", - .on_topic_view_removed = on_topic_view_removed, - .on_error = on_error_remove - }; - diffusion_topic_views_remove_topic_view(session, params_remove, NULL); - - // Sleep for a while - sleep(5); - - // List the topic views after removal - list_topic_views(session); - - // Close session and free resources. - session_close(session, NULL); - session_free(session); - - credentials_free(credentials); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/c/features/topic_views/topic-views.c b/c/features/topic_views/topic-views.c deleted file mode 100644 index 127b4b4d..00000000 --- a/c/features/topic_views/topic-views.c +++ /dev/null @@ -1,263 +0,0 @@ -/** - * Copyright © 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.3 - */ - -/* - * This example creates a topic view. - */ -#include -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" -#include "conversation.h" - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - {'t', "topic", "Topic name to create and update", ARG_OPTIONAL, ARG_HAS_VALUE, "source"}, - {'r', "reference-topic", "Reference topic name to be mapped", ARG_OPTIONAL, ARG_HAS_VALUE, "reference"}, - {'s', "seconds", "Number of seconds to run for before exiting", ARG_OPTIONAL, ARG_HAS_VALUE, "30"}, - END_OF_ARG_OPTS -}; - -// Handlers for add topic feature. -static int on_topic_added_with_specification( - SESSION_T *session, - TOPIC_ADD_RESULT_CODE result_code, - void *context) -{ - printf("Added topic \"%s\"\n", (const char *)context); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_failed_with_specification( - SESSION_T *session, - TOPIC_ADD_FAIL_RESULT_CODE result_code, - const DIFFUSION_ERROR_T *error, - void *context) -{ - printf("Failed to add topic \"%s\" (%d)\n", (const char *)context, result_code); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_discard(SESSION_T *session, void *context) -{ - printf("Topic add discarded\n"); - return HANDLER_SUCCESS; -} - - -static ADD_TOPIC_CALLBACK_T create_topic_callback(const char *topic_name) -{ - ADD_TOPIC_CALLBACK_T callback = { - .on_topic_added_with_specification = on_topic_added_with_specification, - .on_topic_add_failed_with_specification = on_topic_add_failed_with_specification, - .on_discard = on_topic_add_discard, - .context = (char *)topic_name - }; - - return callback; -} - - -static int on_topic_view_created( - const DIFFUSION_TOPIC_VIEW_T *topic_view, - void *context) -{ - char *view_name = diffusion_topic_view_get_name(topic_view); - char *spec = diffusion_topic_view_get_specification(topic_view); - - printf("Topic view \"%s\" created with specification \"%s\"\n", view_name, spec); - - free(view_name); - free(spec); - return HANDLER_SUCCESS; -} - - -static int on_topic_update(void *context) -{ - printf("Topic update success\n"); - return HANDLER_SUCCESS; -} - - -static int on_subscription( - const char *const topic_path, - const TOPIC_SPECIFICATION_T *const specification, - void *context) -{ - printf("Subscribed to \"%s\"\n", topic_path); - return HANDLER_SUCCESS; -} - - -static int on_value( - const char *const topic_path, - const TOPIC_SPECIFICATION_T *const specification, - DIFFUSION_DATATYPE datatype, - const DIFFUSION_VALUE_T *const old_value, - const DIFFUSION_VALUE_T *const new_value, - void *context) -{ - char *result; - read_diffusion_string_value(new_value, &result, NULL); - - printf("Value from \"%s\" topic: %s\n", topic_path, result); - - free(result); - return HANDLER_SUCCESS; -} - - -static int on_error( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("Error: %s\n", error->message); - return HANDLER_SUCCESS; -} - - -// Program entry point. -int main(int argc, char** argv) -{ - // Standard command-line parsing. - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - CREDENTIALS_T *credentials = NULL; - const char *password = hash_get(options, "credentials"); - if(password != NULL) { - credentials = credentials_create_password(password); - } - const char *topic_name = hash_get(options, "topic"); - const char *reference_topic_name = hash_get(options, "reference-topic"); - const long seconds = atol(hash_get(options, "seconds")); - - // Create a session with the Diffusion server. - SESSION_T *session; - DIFFUSION_ERROR_T error = { 0 }; - session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - ADD_TOPIC_CALLBACK_T callback = create_topic_callback(topic_name); - TOPIC_SPECIFICATION_T *spec = topic_specification_init(TOPIC_TYPE_STRING); - - // Create the source topic. - add_topic_from_specification(session, topic_name, spec, callback); - - // Sleep for a while - sleep(5); - - topic_specification_free(spec); - - // Create the topic view specification string. - // Maps topic to reference topic. - BUF_T *buf = buf_create(); - buf_sprintf(buf, "map %s to %s", topic_name, reference_topic_name); - - char *topic_view_spec = buf_as_string(buf); - buf_free(buf); - - DIFFUSION_CREATE_TOPIC_VIEW_PARAMS_T topic_view_params = { - .view = "example-view", - .specification = topic_view_spec, - .on_topic_view_created = on_topic_view_created, - .on_error = on_error - }; - - // Send the request to create the topic view. - diffusion_topic_views_create_topic_view(session, topic_view_params, NULL); - free(topic_view_spec); - - VALUE_STREAM_T value_stream = { - .datatype = DATATYPE_STRING, - .on_subscription = on_subscription, - .on_value = on_value - }; - - // Add a value stream for the reference topic to receive update values. - add_stream(session, reference_topic_name, &value_stream); - - SUBSCRIPTION_PARAMS_T subscribe_params = { - .topic_selector = reference_topic_name, - .on_topic_message = NULL - }; - - // Subscribe to the reference topic. - subscribe(session, subscribe_params); - - time_t end_time = time(NULL) + seconds; - - while(time(NULL) < end_time) { - // Compose the update content - const time_t time_now = time(NULL); - const char *time_str = ctime(&time_now); - - // Create a BUF_T and write the string datatype value into it. - BUF_T *value = buf_create(); - write_diffusion_string_value(time_str, value); - - DIFFUSION_TOPIC_UPDATE_SET_PARAMS_T topic_update_params = { - .topic_path = topic_name, - .datatype = DATATYPE_STRING, - .update = value, - .on_topic_update = on_topic_update, - .on_error = on_error - }; - - // Update the source topic. - diffusion_topic_update_set(session, topic_update_params); - buf_free(value); - - sleep(1); - } - - // Close session and free resources. - session_close(session, NULL); - session_free(session); - - credentials_free(credentials); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/c/features/topics/binary-topics.c b/c/features/topics/binary-topics.c deleted file mode 100644 index 5067483e..00000000 --- a/c/features/topics/binary-topics.c +++ /dev/null @@ -1,283 +0,0 @@ -/** - * Copyright © 2018 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.1 - */ - -/** - * This example shows how to add, subscribe and update a Binary topic - */ - -#include -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" -#include "utils.h" - - -static const long sleep_timeout = 1; - -char random_bytes[51]; - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - END_OF_ARG_OPTS -}; - - -// Handlers for add_topic_from_specification() function. -static int on_topic_added_with_specification( - SESSION_T *session, - TOPIC_ADD_RESULT_CODE result_code, - void *context) -{ - return HANDLER_SUCCESS; -} - - -static int on_topic_add_failed_with_specification( - SESSION_T *session, - TOPIC_ADD_FAIL_RESULT_CODE result_code, - const DIFFUSION_ERROR_T *error, - void *context) -{ - fprintf(stderr, "Failed to add topic: %s\n", error->message); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_discard(SESSION_T *session, void *context) -{ - fprintf(stderr, "Topic add discarded."); - return HANDLER_SUCCESS; -} - - -static int on_subscription( - const char *const topic_path, - const TOPIC_SPECIFICATION_T *const specification, - void *context) -{ - printf("Subscribed to topic: %s\n", topic_path); - return HANDLER_SUCCESS; -} - - -static int on_unsubscription( - const char *const topic_path, - const TOPIC_SPECIFICATION_T *const specification, - NOTIFY_UNSUBSCRIPTION_REASON_T reason, - void *context) -{ - printf("Unsubscribed from topic: %s\n", topic_path); - return HANDLER_SUCCESS; -} - - -static int on_value( - const char *const topic_path, - const TOPIC_SPECIFICATION_T *const specification, - DIFFUSION_DATATYPE datatype, - const DIFFUSION_VALUE_T *const old_value, - const DIFFUSION_VALUE_T *const new_value, - void *context) -{ - if(old_value) { - DIFFUSION_API_ERROR old_value_error; - void *old_binary_value; - if(!read_diffusion_binary_value(old_value, &old_binary_value, &old_value_error)) { - fprintf(stderr, "Error parsing binary old value: %s\n", get_diffusion_api_error_description(old_value_error)); - diffusion_api_error_free(old_value_error); - return HANDLER_SUCCESS; - } - - printf("Old binary value: %s\n", (char *)old_binary_value); - free(old_binary_value); - } - - DIFFUSION_API_ERROR new_value_error; - void *new_binary_value; - if(!read_diffusion_binary_value(new_value, &new_binary_value, &new_value_error)) { - fprintf(stderr, "Error parsing binary new value: %s\n", get_diffusion_api_error_description(new_value_error)); - diffusion_api_error_free(new_value_error); - return HANDLER_SUCCESS; - } - - printf("New binary value: %s\n\n", (char *)new_binary_value); - free(new_binary_value); - return HANDLER_SUCCESS; -} - - -static ADD_TOPIC_CALLBACK_T create_topic_callback() -{ - ADD_TOPIC_CALLBACK_T callback = { - .on_topic_added_with_specification = on_topic_added_with_specification, - .on_topic_add_failed_with_specification = on_topic_add_failed_with_specification, - .on_discard = on_topic_add_discard - }; - - return callback; -} - - -static int on_topic_update(void *context) -{ - printf("topic update success\n"); - return HANDLER_SUCCESS; -} - - -static int on_error( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("topic update error: %s\n", error->message); - return HANDLER_SUCCESS; -} - - -static void dispatch_binary_update( - SESSION_T *session, - const char *topic_path) -{ - // Generate 50 bytes of random values - srand(time(NULL)); - for(unsigned long i = 0; i < sizeof(random_bytes) - 1; i++) { - random_bytes[i] = (char)(33 + (rand() % 94)); - } - - random_bytes[50] = '\0'; - - BUF_T *buf = buf_create(); - if(!write_diffusion_binary_value(random_bytes, buf, sizeof(random_bytes))) { - fprintf(stderr, "Unable to write the binary update\n"); - buf_free(buf); - return; - } - - char *topic_path_dup = strdup(topic_path); - - DIFFUSION_TOPIC_UPDATE_SET_PARAMS_T topic_update_params = { - .topic_path = topic_path_dup, - .datatype = DATATYPE_BINARY, - .update = buf, - .on_topic_update = on_topic_update, - .on_error = on_error - }; - - diffusion_topic_update_set(session, topic_update_params); - - // Sleep for a while - sleep(1); - - buf_free(buf); - free(topic_path_dup); -} - - -static void tear_down(SESSION_T *session, TOPIC_SPECIFICATION_T *specification) -{ - session_close(session, NULL); - session_free(session); - - topic_specification_free(specification); -} - - -int main(int argc, char** argv) -{ - // Standard command-line parsing. - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *topic_path = "binary-example"; - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - const char *password = hash_get(options, "credentials"); - - CREDENTIALS_T *credentials = NULL; - if(password != NULL) { - credentials = credentials_create_password(password); - } - - // Setup for session - DIFFUSION_ERROR_T error = { 0 }; - SESSION_T *session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - // Add the binary topic - TOPIC_SPECIFICATION_T *specification = topic_specification_init(TOPIC_TYPE_BINARY); - ADD_TOPIC_CALLBACK_T add_topic_callback = create_topic_callback(); - - add_topic_from_specification(session, topic_path, specification, add_topic_callback); - - // Sleep for a while - sleep(5); - - // Set up and add the value stream to receive binary topic updates - VALUE_STREAM_T value_stream = { - .datatype = DATATYPE_BINARY, - .on_subscription = on_subscription, - .on_unsubscription = on_unsubscription, - .on_value = on_value - }; - - add_stream(session, topic_path, &value_stream); - - // Subscribe to the topic path - SUBSCRIPTION_PARAMS_T params = { - .topic_selector = topic_path, - .on_topic_message = NULL - }; - - subscribe(session, params); - - // Sleep for a while - sleep(5); - - // Dispatch 120 binary topic updates at 1 second intervals. - for(int i = 1; i <= 120; i++) { - dispatch_binary_update(session, topic_path); - sleep(sleep_timeout); - } - - // Close our session, and release resources and memory. - tear_down(session, specification); - credentials_free(credentials); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/c/features/topics/double-topics.c b/c/features/topics/double-topics.c deleted file mode 100644 index bdbdb97c..00000000 --- a/c/features/topics/double-topics.c +++ /dev/null @@ -1,283 +0,0 @@ -/** - * Copyright © 2018 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.1 - */ - -/** - * This example shows how to add, subscribe and update a Double topic - */ - -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" -#include "utils.h" - - -static const long sleep_timeout = 1; - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - END_OF_ARG_OPTS -}; - - -// Handlers for add_topic_from_specification() function. -static int on_topic_added_with_specification( - SESSION_T *session, - TOPIC_ADD_RESULT_CODE result_code, - void *context) -{ - return HANDLER_SUCCESS; -} - - -static int on_topic_add_failed_with_specification( - SESSION_T *session, - TOPIC_ADD_FAIL_RESULT_CODE result_code, - const DIFFUSION_ERROR_T *error, - void *context) -{ - fprintf(stderr, "Failed to add topic: %s\n", error->message); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_discard( - SESSION_T *session, - void *context) -{ - fprintf(stderr, "Topic add discarded."); - return HANDLER_SUCCESS; -} - - -static int on_subscription( - const char *const topic_path, - const TOPIC_SPECIFICATION_T *const specification, - void *context) -{ - printf("Subscribed to topic: %s\n", topic_path); - return HANDLER_SUCCESS; -} - - -static int on_unsubscription( - const char *const topic_path, - const TOPIC_SPECIFICATION_T *const specification, - NOTIFY_UNSUBSCRIPTION_REASON_T reason, - void *context) -{ - printf("Unsubscribed from topic: %s\n", topic_path); - return HANDLER_SUCCESS; -} - - -static int on_value( - const char *const topic_path, - const TOPIC_SPECIFICATION_T *const specification, - DIFFUSION_DATATYPE datatype, - const DIFFUSION_VALUE_T *const old_value, - const DIFFUSION_VALUE_T *const new_value, - void *context) -{ - if(old_value) { - DIFFUSION_API_ERROR old_value_error; - double old_double_value; - if(!read_diffusion_double_value(old_value, &old_double_value, &old_value_error)) { - fprintf( - stderr, - "Error parsing double old value: %s\n", - get_diffusion_api_error_description(old_value_error)); - diffusion_api_error_free(old_value_error); - return HANDLER_SUCCESS; - } - - printf("Old double value: %f\n", old_double_value); - } - - DIFFUSION_API_ERROR new_value_error; - double new_double_value; - if(!read_diffusion_double_value(new_value, &new_double_value, &new_value_error)) { - fprintf( - stderr, - "Error parsing double new value: %s\n", - get_diffusion_api_error_description(new_value_error)); - diffusion_api_error_free(new_value_error); - return HANDLER_SUCCESS; - } - - printf("New double value: %f\n\n", new_double_value); - return HANDLER_SUCCESS; -} - - -static ADD_TOPIC_CALLBACK_T create_topic_callback() -{ - ADD_TOPIC_CALLBACK_T callback = { - .on_topic_added_with_specification = on_topic_added_with_specification, - .on_topic_add_failed_with_specification = on_topic_add_failed_with_specification, - .on_discard = on_topic_add_discard - }; - - return callback; -} - - -static int on_topic_update(void *context) -{ - printf("topic update success\n"); - return HANDLER_SUCCESS; -} - - -static int on_error( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("topic update error: %s\n", error->message); - return HANDLER_SUCCESS; -} - - -static void dispatch_double_update( - SESSION_T *session, - const char *topic_path) -{ - double value = (double)rand()/(double)(RAND_MAX/100); - - BUF_T *buf = buf_create(); - if(!write_diffusion_double_value(value, buf)) { - fprintf(stderr, "Unable to write the double update\n"); - buf_free(buf); - return; - } - - char *topic_path_dup = strdup(topic_path); - - DIFFUSION_TOPIC_UPDATE_SET_PARAMS_T topic_update_params = { - .topic_path = topic_path_dup, - .datatype = DATATYPE_DOUBLE, - .update = buf, - .on_topic_update = on_topic_update, - .on_error = on_error - }; - - diffusion_topic_update_set(session, topic_update_params); - - // Sleep for a while - sleep(1); - - buf_free(buf); - free(topic_path_dup); -} - - -static void tear_down( - SESSION_T *session, - TOPIC_SPECIFICATION_T *specification) -{ - session_close(session, NULL); - session_free(session); - - topic_specification_free(specification); -} - - -int main(int argc, char** argv) -{ - // Standard command-line parsing. - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *topic_path = "double-example"; - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - const char *password = hash_get(options, "credentials"); - - CREDENTIALS_T *credentials = NULL; - if(password != NULL) { - credentials = credentials_create_password(password); - } - - // Setup for session - DIFFUSION_ERROR_T error = { 0 }; - SESSION_T *session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - // Add the double topic - TOPIC_SPECIFICATION_T *specification = topic_specification_init(TOPIC_TYPE_DOUBLE); - ADD_TOPIC_CALLBACK_T add_topic_callback = create_topic_callback(); - - add_topic_from_specification(session, topic_path, specification, add_topic_callback); - - // Sleep for a while - sleep(5); - - // Set up and add the value stream to receive double topic updates - VALUE_STREAM_T value_stream = { - .datatype = DATATYPE_DOUBLE, - .on_subscription = on_subscription, - .on_unsubscription = on_unsubscription, - .on_value = on_value - }; - - add_stream(session, topic_path, &value_stream); - - // Subscribe to the topic path - SUBSCRIPTION_PARAMS_T params = { - .topic_selector = topic_path, - .on_topic_message = NULL - }; - - subscribe(session, params); - - // Sleep for a while - sleep(5); - - // Dispatch 120 double topic updates at 1 second intervals. - for(int i = 1; i <= 120; i++) { - dispatch_double_update(session, topic_path); - sleep(sleep_timeout); - } - - // Close our session, and release resources and memory. - tear_down(session, specification); - - credentials_free(credentials); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/c/features/topics/fetch-request.c b/c/features/topics/fetch-request.c deleted file mode 100644 index da8c9730..00000000 --- a/c/features/topics/fetch-request.c +++ /dev/null @@ -1,209 +0,0 @@ -/** - * Copyright © 2019, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.4 - */ - -/* - * This is a sample client which connects to Diffusion and demonstrates - * the following features: - * - * 1. Connect to Diffusion with a username and password. - * 2. Fetch topic state using a user-specified topic path. - */ - -#include -#ifndef WIN32 -#include -#else -#define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'t', "topic_path", "Topic path", ARG_REQUIRED, ARG_HAS_VALUE, NULL}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "client"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - END_OF_ARG_OPTS -}; - -/* - * This callback is used when the session state changes, e.g. when a session - * moves from a "connecting" to a "connected" state, or from "connected" to - * "closed". - */ -static void -on_session_state_changed(SESSION_T *session, const SESSION_STATE_T old_state, const SESSION_STATE_T new_state) -{ - printf("Session state changed from %s (%d) to %s (%d)\n", - session_state_as_string(old_state), old_state, - session_state_as_string(new_state), new_state); - if(new_state == CONNECTED_ACTIVE) { - char *session_id = session_id_to_string(session->id); - printf("Session ID=%s\n", session_id); - free(session_id); - } -} - -static int -on_fetch_result(const DIFFUSION_FETCH_RESULT_T *fetch_result, void *context) -{ - LIST_T *results = diffusion_fetch_result_get_topic_results(fetch_result); - - DIFFUSION_TOPIC_RESULT_T *topic_result = list_get_data_indexed(results, 0); - DIFFUSION_VALUE_T *value = diffusion_topic_result_get_value(topic_result); - - char *topic_path = diffusion_topic_result_get_path(topic_result); - printf("Fetching value from \"%s\"\n", topic_path); - - if(value != NULL) { - switch(diffusion_topic_result_get_topic_type(topic_result)) { - - char *json_value; - int64_t int64_value; - void *binary_value; - double double_value; - char *string_value; - char *recordv2_value; - - case TOPIC_TYPE_JSON: - to_diffusion_json_string(value, &json_value, NULL); - printf("JSON topic type, fetch value: %s\n", json_value); - free(json_value); - break; - case TOPIC_TYPE_INT64: - read_diffusion_int64_value(value, &int64_value, NULL); - printf("Int64 topic type, fetch value: " "%"PRId64 "\n", int64_value); - break; - case TOPIC_TYPE_BINARY: - read_diffusion_binary_value(value, &binary_value, NULL); - printf("Binary topic type, fetch value: %s\n", (char *)binary_value); - free(binary_value); - break; - case TOPIC_TYPE_DOUBLE: - read_diffusion_double_value(value, &double_value, NULL); - printf("Double topic type, fetch value: %f\n", double_value); - break; - case TOPIC_TYPE_STRING: - read_diffusion_string_value(value, &string_value, NULL); - printf("String topic type, fetch value: %s\n", string_value); - free(string_value); - break; - case TOPIC_TYPE_RECORDV2: - diffusion_recordv2_to_string(value, &recordv2_value, NULL); - printf("RecordV2 topic type, fetch value: %s\n", recordv2_value); - free(recordv2_value); - break; - default: - break; - } - } - else { - printf("No fetch value\n"); - } - - list_free(results, (void (*)(void *))diffusion_topic_result_free); - return HANDLER_SUCCESS; -} - -int -main(int argc, char **argv) -{ - /* - * Standard command-line parsing. - */ - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - char *url = hash_get(options, "url"); - char *topic = hash_get(options, "topic_path"); - const char *principal = hash_get(options, "principal"); - - CREDENTIALS_T *credentials = NULL; - const char *password = hash_get(options, "credentials"); - if(password != NULL) { - credentials = credentials_create_password(password); - } - - /* - * A SESSION_LISTENER_T holds callbacks to inform the client - * about changes to the state. Used here for informational - * purposes only. - */ - SESSION_LISTENER_T session_listener = { - .on_state_changed = &on_session_state_changed - }; - - /* - * Creating a session requires at least a URL. Creating a session - * initiates a connection with Diffusion. - */ - SESSION_T *session; - DIFFUSION_ERROR_T error = { 0 }; - session = session_create(url, principal, credentials, &session_listener, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - /* - * Create the fetch request - */ - DIFFUSION_FETCH_REQUEST_T *fetch_request = diffusion_fetch_request_init(session); - diffusion_fetch_request_with_values(fetch_request, NULL, NULL); - diffusion_fetch_request_from(fetch_request, topic, NULL); - diffusion_fetch_request_to(fetch_request, topic, NULL); - diffusion_fetch_request_first(fetch_request, 1, NULL); - diffusion_fetch_request_maximum_result_size(fetch_request, 1000, NULL); - diffusion_fetch_request_limit_deep_branches(fetch_request, 3 ,3, NULL); // this limits results to a max depth of 3, with each result having maximum 3 results. - - DIFFUSION_FETCH_REQUEST_PARAMS_T params = { - .topic_selector = topic, - .fetch_request = fetch_request, - .on_fetch_result = on_fetch_result - }; - - /* - * Issue the fetch request. - */ - diffusion_fetch_request_fetch(session, params); - - /* - * Wait for 5 seconds for the results to come in. - */ - sleep(5); - - /* - * Clean up. - */ - session_close(session, NULL); - session_free(session); - - credentials_free(credentials); - hash_free(options, NULL, free); - diffusion_fetch_request_free(fetch_request); - - return EXIT_SUCCESS; -} diff --git a/c/features/topics/int64-topics.c b/c/features/topics/int64-topics.c deleted file mode 100644 index 69a36ecb..00000000 --- a/c/features/topics/int64-topics.c +++ /dev/null @@ -1,276 +0,0 @@ -/** - * Copyright © 2018 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.1 - */ - -/** - * This example shows how to add, subscribe and update an Int64 topic - */ - -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" -#include "utils.h" - - -static const long sleep_timeout = 1; - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - END_OF_ARG_OPTS -}; - - -// Handlers for add_topic_from_specification() function. -static int on_topic_added_with_specification( - SESSION_T *session, - TOPIC_ADD_RESULT_CODE result_code, - void *context) -{ - return HANDLER_SUCCESS; -} - - -static int on_topic_add_failed_with_specification( - SESSION_T *session, - TOPIC_ADD_FAIL_RESULT_CODE result_code, - const DIFFUSION_ERROR_T *error, - void *context) -{ - fprintf(stderr, "Failed to add topic: %s\n", error->message); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_discard(SESSION_T *session, void *context) -{ - fprintf(stderr, "Topic add discarded."); - return HANDLER_SUCCESS; -} - - -static int on_subscription( - const char *const topic_path, - const TOPIC_SPECIFICATION_T *const specification, - void *context) -{ - printf("Subscribed to topic: %s\n", topic_path); - return HANDLER_SUCCESS; -} - - -static int on_unsubscription( - const char *const topic_path, - const TOPIC_SPECIFICATION_T *const specification, - NOTIFY_UNSUBSCRIPTION_REASON_T reason, - void *context) -{ - printf("Unsubscribed from topic: %s\n", topic_path); - return HANDLER_SUCCESS; -} - - -static int on_value( - const char *const topic_path, - const TOPIC_SPECIFICATION_T *const specification, - DIFFUSION_DATATYPE datatype, - const DIFFUSION_VALUE_T *const old_value, - const DIFFUSION_VALUE_T *const new_value, - void *context) -{ - if(old_value) { - DIFFUSION_API_ERROR old_value_error; - int64_t old_int64_value; - if(!read_diffusion_int64_value(old_value, &old_int64_value, &old_value_error)) { - fprintf(stderr, "Error parsing int64 old value: %s\n", get_diffusion_api_error_description(old_value_error)); - diffusion_api_error_free(old_value_error); - return HANDLER_SUCCESS; - } - - printf("Old int64 value: " "%"PRId64"" "\n", old_int64_value); - } - - DIFFUSION_API_ERROR new_value_error; - int64_t new_int64_value; - if(!read_diffusion_int64_value(new_value, &new_int64_value, &new_value_error)) { - fprintf(stderr, "Error parsing int64 new value: %s\n", get_diffusion_api_error_description(new_value_error)); - diffusion_api_error_free(new_value_error); - return HANDLER_SUCCESS; - } - - printf("New int64 value: " "%"PRId64"" "\n\n", new_int64_value); - return HANDLER_SUCCESS; -} - - -static ADD_TOPIC_CALLBACK_T create_topic_callback() -{ - ADD_TOPIC_CALLBACK_T callback = { - .on_topic_added_with_specification = on_topic_added_with_specification, - .on_topic_add_failed_with_specification = on_topic_add_failed_with_specification, - .on_discard = on_topic_add_discard - }; - - return callback; -} - - -static int on_topic_update(void *context) -{ - printf("topic update success\n"); - return HANDLER_SUCCESS; -} - - -static int on_error( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("topic update error: %s\n", error->message); - return HANDLER_SUCCESS; -} - - -static void dispatch_int64_update( - SESSION_T *session, - const char *topic_path) -{ - int64_t value = rand(); - - BUF_T *buf = buf_create(); - if(!write_diffusion_int64_value(value, buf)) { - fprintf(stderr, "Unable to write the int64 update\n"); - buf_free(buf); - return; - } - - char *topic_path_dup = strdup(topic_path); - - DIFFUSION_TOPIC_UPDATE_SET_PARAMS_T topic_update_params = { - .topic_path = topic_path_dup, - .datatype = DATATYPE_INT64, - .update = buf, - .on_topic_update = on_topic_update, - .on_error = on_error - }; - - diffusion_topic_update_set(session, topic_update_params); - - // Sleep for a while - sleep(1); - - buf_free(buf); - free(topic_path_dup); -} - - -static void tear_down( - SESSION_T *session, - TOPIC_SPECIFICATION_T *specification) -{ - session_close(session, NULL); - session_free(session); - - topic_specification_free(specification); -} - - -int main(int argc, char** argv) -{ - // Standard command-line parsing. - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *topic_path = "int64-example"; - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - const char *password = hash_get(options, "credentials"); - - CREDENTIALS_T *credentials = NULL; - if(password != NULL) { - credentials = credentials_create_password(password); - } - - // Setup for session - DIFFUSION_ERROR_T error = { 0 }; - SESSION_T *session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - // Add the int64 topic - TOPIC_SPECIFICATION_T *specification = topic_specification_init(TOPIC_TYPE_INT64); - ADD_TOPIC_CALLBACK_T add_topic_callback = create_topic_callback(); - - add_topic_from_specification(session, topic_path, specification, add_topic_callback); - - // Sleep for a while - sleep(5); - - // Set up and add the value stream to receive int64 topic updates - VALUE_STREAM_T value_stream = { - .datatype = DATATYPE_INT64, - .on_subscription = on_subscription, - .on_unsubscription = on_unsubscription, - .on_value = on_value - }; - - add_stream(session, topic_path, &value_stream); - - // Subscribe to the topic path - SUBSCRIPTION_PARAMS_T params = { - .topic_selector = topic_path, - .on_topic_message = NULL - }; - - subscribe(session, params); - - - // Sleep for a while - sleep(5); - - // Dispatch 120 int64 topic updates at 1 second intervals. - for(int i = 1; i <= 120; i++) { - dispatch_int64_update(session, topic_path); - sleep(sleep_timeout); - } - - // Close our session, and release resources and memory. - tear_down(session, specification); - - credentials_free(credentials); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/c/features/topics/recordv2-topics.c b/c/features/topics/recordv2-topics.c deleted file mode 100644 index e8bdf5dd..00000000 --- a/c/features/topics/recordv2-topics.c +++ /dev/null @@ -1,294 +0,0 @@ -/** - * Copyright © 2018 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.1 - */ - -/** - * This example shows how to add, subscribe and update a RecordV2 topic. - */ - -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" -#include "utils.h" - - -static const long sleep_timeout = 1; - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - END_OF_ARG_OPTS -}; - - -// Handlers for add_topic_from_specification() function. -static int on_topic_added_with_specification( - SESSION_T *session, - TOPIC_ADD_RESULT_CODE result_code, - void *context) -{ - return HANDLER_SUCCESS; -} - - -static int on_topic_add_failed_with_specification( - SESSION_T *session, - TOPIC_ADD_FAIL_RESULT_CODE result_code, - const DIFFUSION_ERROR_T *error, - void *context) -{ - fprintf(stderr, "Failed to add topic: %s\n", error->message); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_discard( - SESSION_T *session, - void *context) -{ - fprintf(stderr, "Topic add discarded."); - return HANDLER_SUCCESS; -} - - -static int on_subscription( - const char *const topic_path, - const TOPIC_SPECIFICATION_T *const specification, - void *context) -{ - printf("Subscribed to topic: %s\n", topic_path); - return HANDLER_SUCCESS; -} - - -static int on_unsubscription( - const char *const topic_path, - const TOPIC_SPECIFICATION_T *const specification, - NOTIFY_UNSUBSCRIPTION_REASON_T reason, - void *context) -{ - printf("Unsubscribed from topic: %s\n", topic_path); - return HANDLER_SUCCESS; -} - - -static int on_value( - const char *const topic_path, - const TOPIC_SPECIFICATION_T *const specification, - DIFFUSION_DATATYPE datatype, - const DIFFUSION_VALUE_T *const old_value, - const DIFFUSION_VALUE_T *const new_value, - void *context) -{ - if(old_value) { - DIFFUSION_API_ERROR old_value_error; - char *old_value_string; - if(!diffusion_recordv2_to_string(old_value, &old_value_string, &old_value_error)) { - fprintf(stderr, "Error parsing recordv2 old value to string: %s\n", get_diffusion_api_error_description(old_value_error)); - diffusion_api_error_free(old_value_error); - return HANDLER_SUCCESS; - } - - printf("Old recordv2 value: %s\n", old_value_string); - free(old_value_string); - } - - DIFFUSION_API_ERROR new_value_error; - char *new_value_string; - if(!diffusion_recordv2_to_string(new_value, &new_value_string, &new_value_error)) { - fprintf(stderr, "Error parsing recordv2 new value to string: %s\n", get_diffusion_api_error_description(new_value_error)); - diffusion_api_error_free(new_value_error); - return HANDLER_SUCCESS; - } - - printf("New recordv2 value: %s\n\n", new_value_string); - free(new_value_string); - return HANDLER_SUCCESS; -} - - -static ADD_TOPIC_CALLBACK_T create_topic_callback() -{ - ADD_TOPIC_CALLBACK_T callback = { - .on_topic_added_with_specification = on_topic_added_with_specification, - .on_topic_add_failed_with_specification = on_topic_add_failed_with_specification, - .on_discard = on_topic_add_discard - }; - - return callback; -} - - -static int on_topic_update(void *context) -{ - printf("topic update success\n"); - return HANDLER_SUCCESS; -} - - -static int on_error( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("topic update error: %s\n", error->message); - return HANDLER_SUCCESS; -} - - -static void dispatch_recordv2_update( - SESSION_T *session, - const char *topic_path, - int update_number) -{ - // convert the update number into a string - char update_number_string[20]; - snprintf(update_number_string, 20, "%d", update_number); - - DIFFUSION_RECORDV2_BUILDER_T *value_builder = diffusion_recordv2_builder_init(); - char **fields = calloc(5, sizeof(char *)); - fields[0] = update_number_string; - fields[1] = "foo"; - fields[2] = "bar"; - fields[3] = "baz"; - - diffusion_recordv2_builder_add_record(value_builder, fields); - void *record_bytes = diffusion_recordv2_builder_build(value_builder); - - BUF_T *buf = buf_create(); - if(!write_diffusion_recordv2_value(record_bytes, buf)) { - fprintf(stderr, "Unable to write the recordv2 update\n"); - diffusion_recordv2_builder_free(value_builder); - buf_free(buf); - return; - } - - char *topic_path_dup = strdup(topic_path); - - DIFFUSION_TOPIC_UPDATE_SET_PARAMS_T topic_update_params = { - .topic_path = topic_path_dup, - .datatype = DATATYPE_RECORDV2, - .update = buf, - .on_topic_update = on_topic_update, - .on_error = on_error - }; - - diffusion_topic_update_set(session, topic_update_params); - - // Sleep for a while - sleep(1); - - diffusion_recordv2_builder_free(value_builder); - buf_free(buf); - free(fields); - free(record_bytes); - free(topic_path_dup); -} - - -static void tear_down(SESSION_T *session, TOPIC_SPECIFICATION_T *specification) -{ - session_close(session, NULL); - session_free(session); - - topic_specification_free(specification); -} - - -int main(int argc, char** argv) -{ - // Standard command-line parsing. - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *topic_path = "recordv2-example"; - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - const char *password = hash_get(options, "credentials"); - - CREDENTIALS_T *credentials = NULL; - if(password != NULL) { - credentials = credentials_create_password(password); - } - - // Setup for session - DIFFUSION_ERROR_T error = { 0 }; - SESSION_T *session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - // Add the recordv2 topic - TOPIC_SPECIFICATION_T *specification = topic_specification_init(TOPIC_TYPE_RECORDV2); - ADD_TOPIC_CALLBACK_T add_topic_callback = create_topic_callback(); - - add_topic_from_specification(session, topic_path, specification, add_topic_callback); - - // Sleep for a while - sleep(5); - - // Set up and add the value stream to receive recordv2 topic updates - VALUE_STREAM_T value_stream = { - .datatype = DATATYPE_RECORDV2, - .on_subscription = on_subscription, - .on_unsubscription = on_unsubscription, - .on_value = on_value - }; - - add_stream(session, topic_path, &value_stream); - - // Subscribe to the topic path - SUBSCRIPTION_PARAMS_T params = { - .topic_selector = topic_path, - .on_topic_message = NULL - }; - - subscribe(session, params); - - // Sleep for a while - sleep(5); - - // Dispatch 120 recordv2 topic updates at 1 second intervals. - for(int i = 1; i <= 120; i++) { - dispatch_recordv2_update(session, topic_path, i); - sleep(sleep_timeout); - } - - // Close our session, and release resources and memory. - tear_down(session, specification); - - credentials_free(credentials); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/c/features/topics/string-topics.c b/c/features/topics/string-topics.c deleted file mode 100644 index 78a14255..00000000 --- a/c/features/topics/string-topics.c +++ /dev/null @@ -1,282 +0,0 @@ -/** - * Copyright © 2018 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.1 - */ - -/** - * This example shows how to add, subscribe and update a String topic. - */ - -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" -#include "utils.h" - - -static const long sleep_timeout = 1; - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "control"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - END_OF_ARG_OPTS -}; - - -// Handlers for add_topic_from_specification() function. -static int on_topic_added_with_specification( - SESSION_T *session, - TOPIC_ADD_RESULT_CODE result_code, - void *context) -{ - return HANDLER_SUCCESS; -} - - -static int on_topic_add_failed_with_specification( - SESSION_T *session, - TOPIC_ADD_FAIL_RESULT_CODE result_code, - const DIFFUSION_ERROR_T *error, - void *context) -{ - fprintf(stderr, "Failed to add topic: %s\n", error->message); - return HANDLER_SUCCESS; -} - - -static int on_topic_add_discard( - SESSION_T *session, - void *context) -{ - fprintf(stderr, "Topic add discarded."); - return HANDLER_SUCCESS; -} - - -static int on_subscription( - const char *const topic_path, - const TOPIC_SPECIFICATION_T *const specification, - void *context) -{ - printf("Subscribed to topic: %s\n", topic_path); - return HANDLER_SUCCESS; -} - - -static int on_unsubscription( - const char *const topic_path, - const TOPIC_SPECIFICATION_T *const specification, - NOTIFY_UNSUBSCRIPTION_REASON_T reason, - void *context) -{ - printf("Unsubscribed from topic: %s\n", topic_path); - return HANDLER_SUCCESS; -} - - -static int on_value( - const char *const topic_path, - const TOPIC_SPECIFICATION_T *const specification, - DIFFUSION_DATATYPE datatype, - const DIFFUSION_VALUE_T *const old_value, - const DIFFUSION_VALUE_T *const new_value, - void *context) -{ - if(old_value) { - DIFFUSION_API_ERROR old_value_error; - char *old_value_string; - if(!read_diffusion_string_value(old_value, &old_value_string, &old_value_error)) { - fprintf(stderr, "Error parsing string old value to string: %s\n", get_diffusion_api_error_description(old_value_error)); - diffusion_api_error_free(old_value_error); - return HANDLER_SUCCESS; - } - - printf("Old string value: %s\n", old_value_string); - free(old_value_string); - } - - DIFFUSION_API_ERROR new_value_error; - char *new_value_string; - if(!read_diffusion_string_value(new_value, &new_value_string, &new_value_error)) { - fprintf(stderr, "Error parsing string new value to string: %s\n", get_diffusion_api_error_description(new_value_error)); - diffusion_api_error_free(new_value_error); - return HANDLER_SUCCESS; - } - - printf("New string value: %s\n\n", new_value_string); - free(new_value_string); - return HANDLER_SUCCESS; -} - - -static ADD_TOPIC_CALLBACK_T create_topic_callback() -{ - ADD_TOPIC_CALLBACK_T callback = { - .on_topic_added_with_specification = on_topic_added_with_specification, - .on_topic_add_failed_with_specification = on_topic_add_failed_with_specification, - .on_discard = on_topic_add_discard - }; - - return callback; -} - - -static int on_topic_update(void *context) -{ - printf("topic update success\n"); - return HANDLER_SUCCESS; -} - - -static int on_error( - SESSION_T *session, - const DIFFUSION_ERROR_T *error) -{ - printf("topic update error: %s\n", error->message); - return HANDLER_SUCCESS; -} - - -static void dispatch_string_update( - SESSION_T *session, - const char *topic_path, - int update_number) -{ - // convert the update number into a string - char update_number_string[20]; - snprintf(update_number_string, 20, "%d", update_number); - - BUF_T *buf = buf_create(); - if(!write_diffusion_string_value(update_number_string, buf)) { - fprintf(stderr, "Unable to write the string update\n"); - buf_free(buf); - return; - } - - char *topic_path_dup = strdup(topic_path); - - DIFFUSION_TOPIC_UPDATE_SET_PARAMS_T topic_update_params = { - .topic_path = topic_path_dup, - .datatype = DATATYPE_STRING, - .update = buf, - .on_topic_update = on_topic_update, - .on_error = on_error - }; - - diffusion_topic_update_set(session, topic_update_params); - - // Sleep for a while - sleep(1); - - buf_free(buf); - free(topic_path_dup); -} - - -static void tear_down( - SESSION_T *session, - TOPIC_SPECIFICATION_T *specification) -{ - session_close(session, NULL); - session_free(session); - - topic_specification_free(specification); -} - - -int main(int argc, char** argv) -{ - // Standard command-line parsing. - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *topic_path = "string-example"; - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - const char *password = hash_get(options, "credentials"); - - CREDENTIALS_T *credentials = NULL; - if(password != NULL) { - credentials = credentials_create_password(password); - } - - // Setup for session - DIFFUSION_ERROR_T error = { 0 }; - SESSION_T *session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - // Add the string topic - TOPIC_SPECIFICATION_T *specification = topic_specification_init(TOPIC_TYPE_STRING); - ADD_TOPIC_CALLBACK_T add_topic_callback = create_topic_callback(); - - add_topic_from_specification(session, topic_path, specification, add_topic_callback); - - // Sleep for a while - sleep(5); - - // Set up and add the value stream to receive string topic updates - VALUE_STREAM_T value_stream = { - .datatype = DATATYPE_STRING, - .on_subscription = on_subscription, - .on_unsubscription = on_unsubscription, - .on_value = on_value - }; - - add_stream(session, topic_path, &value_stream); - - // Subscribe to the topic path - SUBSCRIPTION_PARAMS_T params = { - .topic_selector = topic_path, - .on_topic_message = NULL - }; - - subscribe(session, params); - - // Sleep for a while - sleep(5); - - // Dispatch 120 string topic updates at 1 second intervals. - for(int i = 1; i <= 120; i++) { - dispatch_string_update(session, topic_path, i); - sleep(sleep_timeout); - } - - // Close our session, and release resources and memory. - tear_down(session, specification); - - credentials_free(credentials); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/c/features/topics/subscribe-multiple.c b/c/features/topics/subscribe-multiple.c deleted file mode 100644 index 728491f8..00000000 --- a/c/features/topics/subscribe-multiple.c +++ /dev/null @@ -1,142 +0,0 @@ -/** - * Copyright © 2014 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 5.0 - */ - -/* - * This example is similar to that in subscribe.c but subscribes to the - * specified topic twice. This is to show that multiple listeners can be - * registered for a topic, or more likely, overlapping topic selectors cause - * multiple callbacks to be issued. - * - * For clarity, many of the callbacks for handling session state have been - * omitted; see subscribe.c for more detailed examples. - */ - -#include -#ifndef WIN32 -#include -#else -#define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'t', "topic_selector", "Topic selector", ARG_REQUIRED, ARG_HAS_VALUE, NULL}, - END_OF_ARG_OPTS -}; - -/* - * When a subscribed message is received by the first listener, this - * callback is invoked. - */ -static int on_topic_message_1( - SESSION_T *session, - const TOPIC_MESSAGE_T *msg) -{ - printf("First handler: Received message for topic %s\n", msg->name); - printf("Payload: %.*s\n", (int)msg->payload->len, msg->payload->data); - return HANDLER_SUCCESS; -} - -/* - * When a subscribed message is received by the second listener, this - * callback is invoked. - */ -static int -on_topic_message_2(SESSION_T *session, const TOPIC_MESSAGE_T *msg) -{ - printf("Second handler: Received message for topic %s\n", msg->name); - printf("Payload: %.*s\n", (int)msg->payload->len, msg->payload->data); - return HANDLER_SUCCESS; -} - -int -main(int argc, char **argv) -{ - /* - * Standard command-line parsing. - */ - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - char *url = hash_get(options, "url"); - char *topic = hash_get(options, "topic_selector"); - - /* - * Create a session with Diffusion. - */ - DIFFUSION_ERROR_T error = { 0 }; - SESSION_T *session = NULL; - session = session_create(url, NULL, NULL, NULL, NULL, &error); - if(session == NULL) { - fprintf(stderr, "TEST: Failed to create session\n"); - fprintf(stderr, "ERR : %s\n", error.message); - return EXIT_FAILURE; - } - - /* - * When issuing commands to Diffusion (in this case, subscribe to - * a topic), it's typical that more than one message may be - * received in response and a handler can be installed for each - * message type. - */ - SUBSCRIPTION_PARAMS_T sub_params_1 = { - .topic_selector = topic, - .on_topic_message = on_topic_message_1 - }; - - SUBSCRIPTION_PARAMS_T sub_params_2 = { - .topic_selector = topic, - .on_topic_message = on_topic_message_2 - }; - - /* - * Register two subscription handlers for the same topic. The - * first handler is replaced by the second, so we will only - * see on_topic_message_2() invoked. - */ - TOPIC_HANDLER_T old_handlers = NULL; - if((old_handlers = subscribe(session, sub_params_1)) != NULL) { - puts("Replacing existing handlers for topic selector"); - } - if((old_handlers = subscribe(session, sub_params_2)) != NULL) { - puts("Replacing existing handlers for topic selector"); - } - - /* - * Keep receiving messages for 10 seconds. - */ - sleep(10); - - /* - * Politely close the connection. - */ - session_close(session, NULL); - session_free(session); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/c/features/topics/subscribe.c b/c/features/topics/subscribe.c deleted file mode 100644 index da843a09..00000000 --- a/c/features/topics/subscribe.c +++ /dev/null @@ -1,179 +0,0 @@ -/** - * Copyright © 2020, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.1 - */ - -/* - * This example shows how to add a JSON value stream and subscribe to a selector. - */ -#include -#include -#ifndef WIN32 -#include -#else -#define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "client"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - {'t', "topic", "Topic selector to subscribe to", ARG_REQUIRED, ARG_HAS_VALUE, "time"}, - END_OF_ARG_OPTS -}; - -static int on_subscription(const char* topic_path, - const TOPIC_SPECIFICATION_T *specification, - void *context) -{ - printf("Subscribed to topic: %s\n", topic_path); - return HANDLER_SUCCESS; -} - -static int on_unsubscription(const char* topic_path, - const TOPIC_SPECIFICATION_T *specification, - NOTIFY_UNSUBSCRIPTION_REASON_T reason, - void *context) -{ - printf("Unsubscribed from topic: %s\n", topic_path); - return HANDLER_SUCCESS; -} - -static int on_value(const char* topic_path, - const TOPIC_SPECIFICATION_T *const specification, - const DIFFUSION_DATATYPE datatype, - const DIFFUSION_VALUE_T *const old_value, - const DIFFUSION_VALUE_T *const new_value, - void *context) -{ - DIFFUSION_API_ERROR api_error; - char *result; - bool success = to_diffusion_json_string(new_value, &result, &api_error); - - if(success) { - printf("Received value: %s\n", result); - free(result); - return HANDLER_SUCCESS; - } - - printf("Error during diffusion value read: %s\n", - get_diffusion_api_error_description(api_error)); - diffusion_api_error_free(api_error); - return HANDLER_SUCCESS; -} - -static void on_close() -{ - printf("Value stream closed\n"); -} - -/* - * Entry point for the example. - */ -int -main(int argc, char **argv) -{ - /* - * Standard command-line parsing. - */ - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - CREDENTIALS_T *credentials = NULL; - const char *password = hash_get(options, "credentials"); - if(password != NULL) { - credentials = credentials_create_password(password); - } - const char *selector = hash_get(options, "topic"); - - SESSION_T *session; - DIFFUSION_ERROR_T error = { 0 }; - - /* - * Create a session, synchronously. - */ - session = session_create(url, principal, credentials, NULL, NULL, &error); - if(session != NULL) { - char *sid_str = session_id_to_string(session->id); - printf("Session created (state=%d, id=%s)\n", - session_state_get(session), - sid_str); - free(sid_str); - } - else { - printf("Failed to create session: %s\n", error.message); - free(error.message); - credentials_free(credentials); - return EXIT_FAILURE; - } - - /* - * Create a value stream - */ - VALUE_STREAM_T value_stream = { - .datatype = DATATYPE_JSON, - .on_subscription = on_subscription, - .on_unsubscription = on_unsubscription, - .on_value = on_value, - .on_close = on_close - }; - - add_stream(session, selector, &value_stream); - SUBSCRIPTION_PARAMS_T params = { - .topic_selector = selector - }; - - /* - * Subscribe to topics matching the selector - */ - subscribe(session, params); - - UNSUBSCRIPTION_PARAMS_T unsub_params = { - .topic_selector = selector - }; - - /* - * Unsubscribe to topics matching the selector - */ - unsubscribe(session, unsub_params); - - /* - * Sleep for 2 seconds. - */ - sleep(2); - - /* - * Close the session, and release resources and memory. - */ - session_close(session, NULL); - session_free(session); - hash_free(options, NULL, free); - - credentials_free(credentials); - - return EXIT_SUCCESS; -} diff --git a/c/reconnect.c b/c/reconnect.c deleted file mode 100644 index 634ffb43..00000000 --- a/c/reconnect.c +++ /dev/null @@ -1,201 +0,0 @@ -/** - * Copyright © 2014 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 5.0 - */ - -/* - * This example shows how to make a synchronous connection to - * Diffusion, with user-provided reconnection logic. - */ -#include -#include -#include - -#ifndef WIN32 - #include -#else - #define sleep(x) Sleep(1000 * x) -#endif - - -#include "diffusion.h" -#include "args.h" - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, NULL}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, NULL}, - {'s', "sleep", "Time to sleep before disconnecting (in seconds).", ARG_OPTIONAL, ARG_HAS_VALUE, "20" }, - END_OF_ARG_OPTS -}; - -/* - * This callback is used when the session state changes, e.g. when a session - * moves from a "connecting" to a "connected" state, or from "connected" to - * "closed". - */ -static void on_session_state_changed( - SESSION_T *session, - const SESSION_STATE_T old_state, - const SESSION_STATE_T new_state) -{ - printf("Session state changed from %s (%d) to %s (%d)\n", - session_state_as_string(old_state), old_state, - session_state_as_string(new_state), new_state); -} - - -typedef struct { - double current_wait; - double max_wait; -} BACKOFF_STRATEGY_ARGS_T; - - -static RECONNECTION_ATTEMPT_ACTION_T backoff_reconnection_strategy( - SESSION_T *session, - void *args) -{ - BACKOFF_STRATEGY_ARGS_T *backoff_args = args; - - printf("Waiting for %f ms\n", backoff_args->current_wait); - - sleep(backoff_args->current_wait); - - // But only up to some maximum time. - if(backoff_args->current_wait > backoff_args->max_wait) { - backoff_args->current_wait = backoff_args->max_wait; - } - - return RECONNECTION_ATTEMPT_ACTION_START; -} - - -static void backoff_success(SESSION_T *session, void *args) -{ - printf("Reconnection successful\n"); - - BACKOFF_STRATEGY_ARGS_T *backoff_args = args; - backoff_args->current_wait = 0; // Reset wait. -} - - -static void backoff_failure(SESSION_T *session, void *args) -{ - printf("Reconnection failed (%s)\n", session_state_as_string(session->state)); - - BACKOFF_STRATEGY_ARGS_T *backoff_args = args; - - // Exponential backoff. - if(backoff_args->current_wait == 0) { - backoff_args->current_wait = 0.01; - } - else { - backoff_args->current_wait *= 2; - } -} - - -/* - * Entry point for the example. - */ -int main(int argc, char **argv) -{ - /* - * Standard command-line parsing. - */ - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - CREDENTIALS_T *credentials = NULL; - const char *password = hash_get(options, "credentials"); - if(password != NULL) { - credentials = credentials_create_password(password); - } - - const unsigned int sleep_time = atol(hash_get(options, "sleep")); - - SESSION_T *session; - DIFFUSION_ERROR_T error = { 0 }; - - SESSION_LISTENER_T session_listener = { 0 }; - session_listener.on_state_changed = &on_session_state_changed; - - /* - * Set the arguments to our exponential backoff strategy. - */ - BACKOFF_STRATEGY_ARGS_T *backoff_args = calloc(1, sizeof(BACKOFF_STRATEGY_ARGS_T)); - backoff_args->current_wait = 0; - backoff_args->max_wait = 5; - - /* - * Create the backoff strategy. - */ - RECONNECTION_STRATEGY_T *reconnection_strategy = - make_reconnection_strategy_user_function( - backoff_reconnection_strategy, - backoff_args, - backoff_success, - backoff_failure); - - /* - * Only ever retry for 30 seconds. - */ - reconnection_strategy_set_timeout(reconnection_strategy, 30 * 1000); - - /* - * Create a session, synchronously. - */ - session = session_create(url, principal, credentials, &session_listener, reconnection_strategy, &error); - if(session != NULL) { - char *sid_str = session_id_to_string(session->id); - printf("Session created (state=%d, id=%s)\n", session_state_get(session), sid_str); - free(sid_str); - } - else { - printf("Failed to create session: %s\n", error.message); - free(error.message); - } - - // With the exception of backoff_args, the reconnection strategy is - // copied withing session_create() and may be freed now. - free(reconnection_strategy); - - /* - * Sleep for a while. - */ - sleep(sleep_time); - - /* - * Close the session, and release resources and memory. - */ - session_close(session, NULL); - session_free(session); - - free(backoff_args); - - credentials_free(credentials); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/c/resources/DiffusionData_CA.crt b/c/resources/DiffusionData_CA.crt new file mode 100644 index 00000000..7fe687ec --- /dev/null +++ b/c/resources/DiffusionData_CA.crt @@ -0,0 +1,34 @@ +-----BEGIN CERTIFICATE----- +MIIF3TCCA8WgAwIBAgIUDAeTQb/Qm7CTyew//1n2jAG0KwEwDQYJKoZIhvcNAQEL +BQAwfjELMAkGA1UEBhMCVUsxDTALBgNVBAgMBEtlbnQxEjAQBgNVBAcMCU1haWRz +dG9uZTEWMBQGA1UECgwNRGlmZnVzaW9uRGF0YTEUMBIGA1UECwwLRW5naW5lZXJp +bmcxHjAcBgNVBAMMFXd3dy5kaWZmdXNpb25kYXRhLmNvbTAeFw0yNDA4MTUxMTQ4 +MDRaFw0yOTA4MTUxMTQ4MDRaMH4xCzAJBgNVBAYTAlVLMQ0wCwYDVQQIDARLZW50 +MRIwEAYDVQQHDAlNYWlkc3RvbmUxFjAUBgNVBAoMDURpZmZ1c2lvbkRhdGExFDAS +BgNVBAsMC0VuZ2luZWVyaW5nMR4wHAYDVQQDDBV3d3cuZGlmZnVzaW9uZGF0YS5j +b20wggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCxuvNkYmQUJQwPGWj0 +4csBsBISv1Q3I3zHtgC1UpPvWyhiNvcKPzoo8Gasrn7XUEAdbLU2Qe7SoOkdcjGg +I0SOwhpQNwagMRnhws7RPJ0hFBa5qgUZErmR6sOiKHZh9QHe3twPUtJkWslGgOFT +oxBddkOVqJgMn5yIVaP75WSHE0DNhHtB3OVUkSJhKPk+yY2kW4UikyNd13tC0dX4 +lDHRqg/GufZ4iBD1YX/sU8vYPdr8b0sZevCMGIbLBsFU3D8GjRl2c1hXkR98dhk1 +CC9sfpUiXtR2ONSJU+s2V9FGVVOCe8HXlMt1d26Y6Xr3n5Z9Wf3LUboGg706ST95 +Ni8XHkqGoY6Yi2QhPqaQirw5FDfNNGz77PU34bc+/hU6/xxvtocNZr5jUez7iX8e +YyYCiDcTaQfY7rcG9a3tlBn7Xp5pQC3B6EcS9Bpwv12q0puQ61JWdrT72xbYMzBk +6jWlYWTarT6MQ865aNRQpree+6UyDhLgehRCqqGqOGxwgwxe4hKk2+QPHK9lP0dO +V7ruhyPz8lYEow2V6s0nPtPg9+3nnf5Ib7O4FP/76kNB2OgWudc0MKrvS4gGOSvP +U56f3SNVzfrpmkH3qkvskX6Mh9f3qlXbwn8gF0X9bUWM5uBlRfFYtw4EZ+FoWCeD +WYVn6mtsX63bYz4IHF+5oGlxVwIDAQABo1MwUTAdBgNVHQ4EFgQU44C00ICWw7sE +9j0TE9pkwuREFb8wHwYDVR0jBBgwFoAU44C00ICWw7sE9j0TE9pkwuREFb8wDwYD +VR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAgEAREQy2phzMPjElTp/EgrJ +9FSqWQPTii3mAaz2TuTPMMH/gUvo5Rb6lfxD0fAkDVEFZ2yIxXG37Vg5ANoH0j0x +aBBTz2ggNCghPvSWix8Lmni9qNjBM+7yUhYXyMWQoKZDx9t1MZyVd0sRiyQR17SF +LkypPFeiGRpXLii+ybWJgqrf9gGVnrl/6bWu/6vK7OBRvMn6VfSOAxULvIlVEtSI +ei3zYvQge2c5CUP512DbyN4ELf+MoUeyCpZgrS2nKFJJvH8Suo0keuM/OroIwEUF +7fJm6XZYqwYnIJyGiN7A8w0RAOWyQ0gjlhEU/6WwwzNfOjBJXIX4yZHoUz0Z6BwI +u2AbYbdRlPNeLvnCzXyrr1fVRfHXP5zhJFCn0Bgmh6YwC7+BvQ+VeZMQ2Kk8se8s +L/c+MF5ojoQB35mBxYll5lPRXz1Q8vcHzi7c365f5Yl9vnzSPRjoS6c0/Yrnbazu +XGbRzp8UziYKhyG6sG5dsVANBnZL2B9R7OpspPzruRh1y4pRbOZdCXZOVMtws+mZ +NtABVJoOh4o3QxXBs11E852lJ53n7khiEKbzVO9Pnvgph/lTP5RizHMJQUVvaZcW +BCKjIIfaLGjqvM7KAzO9Zm+/hhliftzWc1d6PS7NE44AxfSQ5jWMAhUb39S+1kgy +IL8b5higv90PE/26D2troKE= +-----END CERTIFICATE----- diff --git a/c/session-factory.c b/c/session-factory.c deleted file mode 100644 index 7df98e81..00000000 --- a/c/session-factory.c +++ /dev/null @@ -1,116 +0,0 @@ -/** - * Copyright © 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * This example is written in C99. Please use an appropriate C99 capable compiler - * - * @author DiffusionData Limited - * @since 6.9 - */ - -/* - * This examples shows how to connect to Diffusion via a session factory. - */ -#include -#include -#include -#ifndef WIN32 -#include -#else -#define sleep(x) Sleep(1000 * x) -#endif - -#include "diffusion.h" -#include "args.h" - - -ARG_OPTS_T arg_opts[] = { - ARG_OPTS_HELP, - {'u', "url", "Diffusion server URL", ARG_OPTIONAL, ARG_HAS_VALUE, "ws://localhost:8080"}, - {'p', "principal", "Principal (username) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "client"}, - {'c', "credentials", "Credentials (password) for the connection", ARG_OPTIONAL, ARG_HAS_VALUE, "password"}, - {'a', "attempts", "Total attempts for initial session establishment", ARG_OPTIONAL, ARG_HAS_VALUE, "10"}, - {'i', "interval", "Interval in milliseconds between attempts for initial session establishment", ARG_OPTIONAL, ARG_HAS_VALUE, "1000"}, - {'s', "sleep", "Time to sleep before disconnecting (in seconds).", ARG_OPTIONAL, ARG_HAS_VALUE, "5" }, - END_OF_ARG_OPTS -}; - - -/* - * Entry point for the example. - */ -int main(int argc, char **argv) -{ - /* - * Standard command-line parsing. - */ - HASH_T *options = parse_cmdline(argc, argv, arg_opts); - if(options == NULL || hash_get(options, "help") != NULL) { - show_usage(argc, argv, arg_opts); - return EXIT_FAILURE; - } - - const char *url = hash_get(options, "url"); - const char *principal = hash_get(options, "principal"); - CREDENTIALS_T *credentials = NULL; - const char *password = hash_get(options, "credentials"); - if(password != NULL) { - credentials = credentials_create_password(password); - } - - uint32_t attempts = atol(hash_get(options, "attempts")); - uint32_t interval = atol(hash_get(options, "interval")); - - const unsigned int sleep_time = atol(hash_get(options, "sleep")); - - DIFFUSION_SESSION_FACTORY_T *session_factory = diffusion_session_factory_init(); - diffusion_session_factory_principal(session_factory, principal); - diffusion_session_factory_credentials(session_factory, credentials); - - DIFFUSION_RETRY_STRATEGY_T *retry_strategy = diffusion_retry_strategy_create(interval, attempts, NULL); - diffusion_session_factory_initial_retry_strategy(session_factory, retry_strategy); - - /* - * Create a session, synchronously. - */ - SESSION_T *session = session_create_with_session_factory(session_factory, url); - if(session != NULL) { - char *sid_str = session_id_to_string(session->id); - printf("Session created (state=%d, id=%s)\n", - session_state_get(session), - sid_str); - free(sid_str); - } - else { - printf("Failed to create session\n"); - } - - /* - * Sleep for a while. - */ - sleep(sleep_time); - - /* - * Close the session, and release resources and memory. - */ - session_close(session, NULL); - session_free(session); - - diffusion_retry_strategy_free(retry_strategy); - diffusion_session_factory_free(session_factory); - - credentials_free(credentials); - hash_free(options, NULL, free); - - return EXIT_SUCCESS; -} diff --git a/dotnet/README.md b/dotnet/README.md index f859b391..2c2c33bc 100644 --- a/dotnet/README.md +++ b/dotnet/README.md @@ -2,17 +2,37 @@ This directory contains examples showing the use of the Diffusion .NET Client Library. -The `getting-started` directory contains a simple publishing and -subscribing client. The `examples` directory contains more in-depth -examples that can be run via the `Runner.csproj` project. - ## Client libraries -In order for all examples to work you have to pull in -`Diffusion.Client` via NuGet: `dotnet add package Diffusion.Client`. +In order for all examples to work you have to add the .NET `Diffusion.Client` via NuGet: + +* using NuGet Package Manager in Visual Studio, or, + +* on the command line with: `dotnet add package Diffusion.Client`. + +Also, + +* Download the client from our website (https://www.diffusiondata.com/diffusion-cloud/#dotnet). + +* The client library is available in the `clients` directory of the Diffusion server installation. + +## Running Examples + +PLEASE READ THIS FIRST +Before running the examples back up the `persistence` directory of the Diffusion server installation. +This is necessary as some examples, such as those for Topic Views, will leave the persistence store changed when finished running. +In this situation stop the Diffusion server and restore the backup before continuing. + +1. Uncomment the example in Program.cs. + +2. Start the diffusion server using diffusion.bat or diffusion.sh in the `bin` directory of the Diffusion server installation. + +3. Run the example: + +* in Visual Studio: F5 or Ctrl+F5. -You can also download the client library from the following locations: +* on the command line: `dotnet run`. -* Download from [our website](http://download.pushtechnology.com/cloud/latest/sdks.html#dotnet) +## Documentation -* The client library is also available in the `clients` directory of the Diffusion server installation. +For further information see our documentation at https://docs.diffusiondata.com/docs/latest/manual/html/. \ No newline at end of file diff --git a/dotnet/client-examples.sln b/dotnet/client-examples.sln deleted file mode 100644 index 0f694c37..00000000 --- a/dotnet/client-examples.sln +++ /dev/null @@ -1,89 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.4.33205.214 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Examples", "Examples", "{1F4E79D7-6CBD-4E2C-8001-56C6DD086FB9}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Getting Started", "Getting Started", "{37D0C7B4-D0DD-46CB-BAAF-8CB5B43E4227}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Source", "Source", "{A7A3F917-51B9-409E-910A-F1B728E71373}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Publishing", "source\getting-started\Publishing\Publishing.csproj", "{67EA612D-71CC-4353-9A47-CEF86B911917}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Subscribing", "source\getting-started\Subscribing\Subscribing.csproj", "{9109F6B4-3AF3-4699-8757-B03ADE15ADD3}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Runner", "source\examples\Runner\Runner.csproj", "{1EFBF419-9BEE-4E12-9C91-FB2C7738B524}" -EndProject -Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Publishing", "source\examples\Publishing\Publishing.shproj", "{960603FE-DE40-42FE-A1E7-1284E3AF1A15}" -EndProject -Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Consuming", "source\examples\Consuming\Consuming.shproj", "{6E978DC0-D636-4883-B0D8-4BA93667865C}" -EndProject -Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Features", "source\examples\Features\Features.shproj", "{CBF43C7F-76A7-4476-8F01-AB2F4C89F90E}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{7C879BE2-668F-4149-876F-F891E8E0E448}" - ProjectSection(SolutionItems) = preProject - README.md = README.md - EndProjectSection -EndProject -Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Website", "source\examples\Website\Website.shproj", "{E306DE7D-C209-4230-8533-94134903B03A}" -EndProject -Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Manual", "source\examples\Manual\Manual.shproj", "{AA2EF359-4F0C-44C5-9047-2E7D2EFA048D}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CodeSnippets", "source\examples\CodeSnippets\CodeSnippets.csproj", "{4D25893B-C0D9-435B-9F64-658FE31AE2B4}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {67EA612D-71CC-4353-9A47-CEF86B911917}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {67EA612D-71CC-4353-9A47-CEF86B911917}.Debug|Any CPU.Build.0 = Debug|Any CPU - {67EA612D-71CC-4353-9A47-CEF86B911917}.Release|Any CPU.ActiveCfg = Release|Any CPU - {67EA612D-71CC-4353-9A47-CEF86B911917}.Release|Any CPU.Build.0 = Release|Any CPU - {9109F6B4-3AF3-4699-8757-B03ADE15ADD3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9109F6B4-3AF3-4699-8757-B03ADE15ADD3}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9109F6B4-3AF3-4699-8757-B03ADE15ADD3}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9109F6B4-3AF3-4699-8757-B03ADE15ADD3}.Release|Any CPU.Build.0 = Release|Any CPU - {1EFBF419-9BEE-4E12-9C91-FB2C7738B524}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1EFBF419-9BEE-4E12-9C91-FB2C7738B524}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1EFBF419-9BEE-4E12-9C91-FB2C7738B524}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1EFBF419-9BEE-4E12-9C91-FB2C7738B524}.Release|Any CPU.Build.0 = Release|Any CPU - {4D25893B-C0D9-435B-9F64-658FE31AE2B4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {4D25893B-C0D9-435B-9F64-658FE31AE2B4}.Debug|Any CPU.Build.0 = Debug|Any CPU - {4D25893B-C0D9-435B-9F64-658FE31AE2B4}.Release|Any CPU.ActiveCfg = Release|Any CPU - {4D25893B-C0D9-435B-9F64-658FE31AE2B4}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {1F4E79D7-6CBD-4E2C-8001-56C6DD086FB9} = {A7A3F917-51B9-409E-910A-F1B728E71373} - {37D0C7B4-D0DD-46CB-BAAF-8CB5B43E4227} = {A7A3F917-51B9-409E-910A-F1B728E71373} - {67EA612D-71CC-4353-9A47-CEF86B911917} = {37D0C7B4-D0DD-46CB-BAAF-8CB5B43E4227} - {9109F6B4-3AF3-4699-8757-B03ADE15ADD3} = {37D0C7B4-D0DD-46CB-BAAF-8CB5B43E4227} - {1EFBF419-9BEE-4E12-9C91-FB2C7738B524} = {1F4E79D7-6CBD-4E2C-8001-56C6DD086FB9} - {960603FE-DE40-42FE-A1E7-1284E3AF1A15} = {1F4E79D7-6CBD-4E2C-8001-56C6DD086FB9} - {6E978DC0-D636-4883-B0D8-4BA93667865C} = {1F4E79D7-6CBD-4E2C-8001-56C6DD086FB9} - {CBF43C7F-76A7-4476-8F01-AB2F4C89F90E} = {1F4E79D7-6CBD-4E2C-8001-56C6DD086FB9} - {E306DE7D-C209-4230-8533-94134903B03A} = {1F4E79D7-6CBD-4E2C-8001-56C6DD086FB9} - {AA2EF359-4F0C-44C5-9047-2E7D2EFA048D} = {1F4E79D7-6CBD-4E2C-8001-56C6DD086FB9} - {4D25893B-C0D9-435B-9F64-658FE31AE2B4} = {1F4E79D7-6CBD-4E2C-8001-56C6DD086FB9} - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {5978CBA1-E70C-47D3-AE8E-057A43482B63} - EndGlobalSection - GlobalSection(SharedMSBuildProjectFiles) = preSolution - source\examples\Consuming\Consuming.projitems*{1efbf419-9bee-4e12-9c91-fb2c7738b524}*SharedItemsImports = 5 - source\examples\Features\Features.projitems*{1efbf419-9bee-4e12-9c91-fb2c7738b524}*SharedItemsImports = 5 - source\examples\Publishing\Publishing.projitems*{1efbf419-9bee-4e12-9c91-fb2c7738b524}*SharedItemsImports = 5 - source\examples\Manual\Manual.projitems*{4d25893b-c0d9-435b-9f64-658fe31ae2b4}*SharedItemsImports = 5 - source\examples\Website\Website.projitems*{4d25893b-c0d9-435b-9f64-658fe31ae2b4}*SharedItemsImports = 5 - source\examples\Consuming\Consuming.projitems*{6e978dc0-d636-4883-b0d8-4ba93667865c}*SharedItemsImports = 13 - source\examples\Publishing\Publishing.projitems*{960603fe-de40-42fe-a1e7-1284e3af1a15}*SharedItemsImports = 13 - source\examples\Manual\Manual.projitems*{aa2ef359-4f0c-44c5-9047-2e7d2efa048d}*SharedItemsImports = 13 - source\examples\Features\Features.projitems*{cbf43c7f-76a7-4476-8f01-ab2f4c89f90e}*SharedItemsImports = 13 - source\examples\Website\Website.projitems*{e306de7d-c209-4230-8533-94134903b03a}*SharedItemsImports = 13 - EndGlobalSection -EndGlobal diff --git a/dotnet/examples/Connection/Establishment/ConnectAsynchronously.cs b/dotnet/examples/Connection/Establishment/ConnectAsynchronously.cs new file mode 100644 index 00000000..b90649be --- /dev/null +++ b/dotnet/examples/Connection/Establishment/ConnectAsynchronously.cs @@ -0,0 +1,43 @@ +/** + * Copyright © 2025 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Session; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.Connection.Establishment +{ + public sealed class ConnectAsynchronously: Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = await Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .OpenAsync(serverUrl); + + WriteLine($"Connected. Session Identifier: {session.SessionId}."); + + // Insert work here... + + session.Close(); + } + } +} diff --git a/dotnet/examples/Connection/Establishment/ConnectAsynchronouslyWithoutURL.cs b/dotnet/examples/Connection/Establishment/ConnectAsynchronouslyWithoutURL.cs new file mode 100644 index 00000000..9f9ed09c --- /dev/null +++ b/dotnet/examples/Connection/Establishment/ConnectAsynchronouslyWithoutURL.cs @@ -0,0 +1,47 @@ +/** + * Copyright © 2025 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Session; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.Connection.Establishment +{ + public sealed class ConnectAsynchronouslyWithoutURL : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = await Diffusion.Sessions + .Credentials(Diffusion.Credentials.Password("password")) + .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) + .ServerHost("localhost") + .ServerPort(8080) + .RequestPath("/foo/bar/diffusion") + .SecureTransport(true) + .OpenAsync(); + + WriteLine($"Connected. Session Identifier: {session.SessionId}."); + + // Insert work here... + + session.Close(); + } + } +} diff --git a/dotnet/examples/Connection/Establishment/ConnectSecurelyAcceptingAllServerCertificates.cs b/dotnet/examples/Connection/Establishment/ConnectSecurelyAcceptingAllServerCertificates.cs new file mode 100644 index 00000000..978f92fd --- /dev/null +++ b/dotnet/examples/Connection/Establishment/ConnectSecurelyAcceptingAllServerCertificates.cs @@ -0,0 +1,46 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Session; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.Connection.Establishment +{ + public sealed class ConnectSecurelyAcceptingAllServerCertificates : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + // Connect to the server + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) + .Open(serverUrl); + + WriteLine($"Connected securely. Session Identifier: {session.SessionId}."); + + // Insert work here... + + session.Close(); + } + } +} diff --git a/dotnet/examples/Connection/Establishment/ConnectSynchronously.cs b/dotnet/examples/Connection/Establishment/ConnectSynchronously.cs new file mode 100644 index 00000000..16dc6166 --- /dev/null +++ b/dotnet/examples/Connection/Establishment/ConnectSynchronously.cs @@ -0,0 +1,44 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Session; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.Connection.Establishment +{ + public sealed class ConnectSynchronously: Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + WriteLine($"Connected. Session Identifier: {session.SessionId}."); + + // Insert work here... + + session.Close(); + } + } +} diff --git a/dotnet/examples/Connection/Establishment/ConnectSynchronouslyWithoutURL.cs b/dotnet/examples/Connection/Establishment/ConnectSynchronouslyWithoutURL.cs new file mode 100644 index 00000000..d7254d96 --- /dev/null +++ b/dotnet/examples/Connection/Establishment/ConnectSynchronouslyWithoutURL.cs @@ -0,0 +1,47 @@ +/** + * Copyright © 2025 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Session; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.Connection.Establishment +{ + public sealed class ConnectSynchronouslyWithoutURL: Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions.Principal("client") + .Credentials(Diffusion.Credentials.Password("password")) + .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) + .ServerHost("localhost") + .ServerPort(8080) + .RequestPath("/foo/bar/diffusion") + .SecureTransport(true) + .Open(); + + WriteLine($"Connected. Session Identifier: {session.SessionId}."); + + // Insert work here... + + session.Close(); + } + } +} diff --git a/dotnet/examples/Connection/Establishment/ConnectUsingASessionFactory.cs b/dotnet/examples/Connection/Establishment/ConnectUsingASessionFactory.cs new file mode 100644 index 00000000..b94ef418 --- /dev/null +++ b/dotnet/examples/Connection/Establishment/ConnectUsingASessionFactory.cs @@ -0,0 +1,44 @@ +/** + * Copyright © 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.Connection.Establishment +{ + public sealed class ConnectUsingASessionFactory : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var sessionFactory = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")); + + var session = sessionFactory.Open(serverUrl); + + WriteLine($"Connected. Session Identifier: {session.SessionId}."); + + // Insert work here... + + session.Close(); + } + } +} diff --git a/dotnet/examples/Connection/Establishment/SessionStateListener.cs b/dotnet/examples/Connection/Establishment/SessionStateListener.cs new file mode 100644 index 00000000..02c27be6 --- /dev/null +++ b/dotnet/examples/Connection/Establishment/SessionStateListener.cs @@ -0,0 +1,50 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Session; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.Connection.Establishment +{ + public sealed class SessionStateListener: Example + { + private void OnSessionStateChanged(object sender, SessionListenerEventArgs e) + { + WriteLine($"State changed from {e.OldState} to {e.NewState}."); + } + + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .SessionStateChangedHandler(OnSessionStateChanged) + .Open(serverUrl); + + WriteLine($"Connected. Session Identifier: {session.SessionId}."); + + // Insert work here... + + session.Close(); + } + } +} diff --git a/dotnet/examples/Connection/Resilience/InitialSessionEstablishmentRetryMechanism.cs b/dotnet/examples/Connection/Resilience/InitialSessionEstablishmentRetryMechanism.cs new file mode 100644 index 00000000..bbcb3ea9 --- /dev/null +++ b/dotnet/examples/Connection/Resilience/InitialSessionEstablishmentRetryMechanism.cs @@ -0,0 +1,49 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Session; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.Connection.Resilience +{ + public sealed class InitialSessionEstablishmentRetryMechanism: Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + // Create an initial session establishment retry strategy. + // It will attempt 5 times to connect to the Diffusion server, + // with 250 milliseconds interval between attempts. + var retryStrategy = new RetryStrategy(250, 5); + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .InitialRetryStrategy(retryStrategy) + .Open(serverUrl); + + WriteLine($"Connected. Session Identifier: {session.SessionId}."); + + // Insert work here... + + session.Close(); + } + } +} diff --git a/dotnet/examples/Connection/Resilience/ReconnectionStrategy.cs b/dotnet/examples/Connection/Resilience/ReconnectionStrategy.cs new file mode 100644 index 00000000..54975c0a --- /dev/null +++ b/dotnet/examples/Connection/Resilience/ReconnectionStrategy.cs @@ -0,0 +1,80 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Session; +using PushTechnology.ClientInterface.Client.Session.Reconnection; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.Connection.Resilience +{ + public sealed class ReconnectionStrategy : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + // Set the maximum amount of time the client will try and reconnect for to 10 minutes. + int maximumTimeoutDuration = 1000 * 60 * 10; + var reconnectionStrategy = new SessionReconnectionStrategy(); + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .ReconnectionTimeout(maximumTimeoutDuration) + .ReconnectionStrategy(reconnectionStrategy) + .Open(serverUrl); + + WriteLine($"Connected. Session Identifier: {session.SessionId}."); + + // Insert work here... + + session.Close(); + } + + /// + /// This class is used to reconnect to the server when the session is disconnected unexpectedly. + /// + private class SessionReconnectionStrategy : IReconnectionStrategy + { + public int Retries { get; set; } + + public SessionReconnectionStrategy() => Retries = 0; + + public async Task PerformReconnection(IReconnectionAttempt reconnection) + { + if (Retries > 10) + { + // Abort after 10 attempts. + throw new Exception(); + } + else + { + Retries++; + + // Retry after 3 seconds. + await Task.Delay(TimeSpan.FromMilliseconds(3000)); + + WriteLine("Attempting to reconnect..."); + + reconnection.Start(); + } + } + } + } +} diff --git a/dotnet/examples/Messaging/MessageToMessagePath.cs b/dotnet/examples/Messaging/MessageToMessagePath.cs new file mode 100644 index 00000000..784a6678 --- /dev/null +++ b/dotnet/examples/Messaging/MessageToMessagePath.cs @@ -0,0 +1,68 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.Messaging +{ + public sealed class MessageToMessagePath : Example { + public override async Task Run( CancellationToken cancellationToken, string[] args ) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string path = "my/message/path"; + + var requestHandler = new SimpleRequestHandler(); + var registration = await session.Messaging.AddRequestHandlerAsync( + path, requestHandler, cancellationToken); + + var session2 = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string response = await session2.Messaging.SendRequestAsync( + path, "Hello", cancellationToken); + WriteLine($"Received response: {response}."); + + session.Close(); + session2.Close(); + } + + private class SimpleRequestHandler : IRequestHandler { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnRequest( string request, IRequestContext context, IResponder responder ) { + WriteLine( $"Received message: {request}." ); + + responder.Respond( "Goodbye" ); + } + } + } +} diff --git a/dotnet/examples/Messaging/MessageToSessionFilter.cs b/dotnet/examples/Messaging/MessageToSessionFilter.cs new file mode 100644 index 00000000..d9de4d66 --- /dev/null +++ b/dotnet/examples/Messaging/MessageToSessionFilter.cs @@ -0,0 +1,107 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Session; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.Messaging +{ + public sealed class MessageToSessionFilter : Example { + public override async Task Run( CancellationToken cancellationToken, string[] args ) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string path = "my/message/path"; + + var requestStream = new SimpleRequestStream(); + session.Messaging.SetRequestStream(path, requestStream); + + var session2 = Diffusion.Sessions + .Principal("control") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var requestStream2 = new AnotherRequestStream(); + session2.Messaging.SetRequestStream(path, requestStream2); + + var session3 = Diffusion.Sessions + .Principal("control") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var requestCallback = new RequestCallback(); + + int requestsSent = await session3.Messaging.SendRequestToFilterAsync( + "$Principal EQ 'admin'", + path, + "Hello", + requestCallback, + cancellationToken); + + session.Close(); + session2.Close(); + session3.Close(); + } + + private class SimpleRequestStream : IRequestStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnRequest( string path, string request, IResponder responder ) { + WriteLine( $"Received message: {request}." ); + + responder.Respond( "Goodbye" ); + } + } + + private class AnotherRequestStream : IRequestStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnRequest(string path, string request, IResponder responder) + { + WriteLine($"Received message: {request}."); + + responder.Respond("I'm not supposed to receive a message."); + } + } + + private class RequestCallback : IFilteredRequestCallback + { + public void OnResponse(ISessionId sessionId, string response) + { + WriteLine($"Received response: {response}."); + } + + public void OnResponseError(ISessionId sessionId, Exception exception) {} + } + } +} diff --git a/dotnet/examples/Messaging/MessageToSessionID.cs b/dotnet/examples/Messaging/MessageToSessionID.cs new file mode 100644 index 00000000..a800a2c5 --- /dev/null +++ b/dotnet/examples/Messaging/MessageToSessionID.cs @@ -0,0 +1,91 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.Messaging +{ + public sealed class MessageToSessionID : Example { + public override async Task Run( CancellationToken cancellationToken, string[] args ) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string path = "my/message/path"; + + var requestStream = new SimpleRequestStream(); + session.Messaging.SetRequestStream(path, requestStream); + + var session2 = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var requestStream2 = new AnotherRequestStream(); + session2.Messaging.SetRequestStream(path, requestStream2); + + var session3 = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string response = await session3.Messaging.SendRequestAsync( + session.SessionId, path, "Hello", cancellationToken); + WriteLine($"Received response: {response}."); + + session.Close(); + session2.Close(); + session3.Close(); + } + + private class SimpleRequestStream : IRequestStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnRequest( string path, string request, IResponder responder ) { + WriteLine( $"Received message: {request}." ); + + responder.Respond( "Goodbye" ); + } + } + + private class AnotherRequestStream : IRequestStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnRequest(string path, string request, IResponder responder) + { + WriteLine($"Received message: {request}."); + + responder.Respond("I'm not supposed to receive a message."); + } + } + } +} diff --git a/dotnet/examples/Monitoring/MissingTopicNotifications.cs b/dotnet/examples/Monitoring/MissingTopicNotifications.cs new file mode 100644 index 00000000..19b3a360 --- /dev/null +++ b/dotnet/examples/Monitoring/MissingTopicNotifications.cs @@ -0,0 +1,106 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using System.Collections.Generic; +using static System.Console; +using System.Linq; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Session; +using PushTechnology.ClientInterface.Client.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using static PushTechnology.ClientInterface.Examples.Program; +using NUnit.Framework; + +namespace PushTechnology.ClientInterface.Examples.Monitoring +{ + public sealed class MissingTopicNotifications : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + IRegistration registration = null; + string topicPath = "my/topic/path"; + string topicSelector = "?my/topic/path//"; + + var missingTopicNotificationStream = new MissingTopicNotificationStream(session); + registration = await session.TopicControl.AddMissingTopicHandlerAsync(topicPath, missingTopicNotificationStream, cancellationToken); + + var session2 = Diffusion.Sessions + .Principal("client") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var stringStream = new StringStream(); + session2.Topics.AddStream(topicSelector, stringStream); + + await session2.Topics.SubscribeAsync("my/topic/path/does/not/exist/yet", cancellationToken); + + session.Close(); + session2.Close(); + } + + private sealed class MissingTopicNotificationStream : IMissingTopicNotificationStream + { + private ISession session; + public MissingTopicNotificationStream(ISession session) => this.session = session; + + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnMissingTopic(IMissingTopicNotification notification) + { + WriteLine($"Topic '{notification.TopicPath}' does not exist."); + + session.TopicControl.AddTopicAsync(notification.TopicPath, Diffusion.NewSpecification(TopicType.STRING)); + } + } + + private sealed class StringStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, string oldValue, string newValue) + { + WriteLine($"{topicPath} changed from {oldValue ?? "NULL"} to {newValue}."); + } + } + } +} diff --git a/dotnet/examples/Monitoring/SessionEventListener.cs b/dotnet/examples/Monitoring/SessionEventListener.cs new file mode 100644 index 00000000..83f0adcb --- /dev/null +++ b/dotnet/examples/Monitoring/SessionEventListener.cs @@ -0,0 +1,98 @@ +/** + * Copyright © 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features.Control.Clients; +using PushTechnology.ClientInterface.Client.Session; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.Monitoring +{ + public sealed class SessionEventListener : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session1 = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var session2 = Diffusion.Sessions + .Principal("client") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var clientControl = session1.ClientControl; + + // We specify the session properties to be returned and we + // exclude sessions with the 'admin' principal + var parameters = Diffusion.NewSessionEventParametersBuilder() + .Properties(SessionProperty.ALL_FIXED_PROPERTIES) + .Filter("$Principal NE 'admin'") + .Build(); + + var myEventStream = new MyEventStream(); + var registration = await clientControl.AddSessionEventListenerAsync(myEventStream, parameters); + + await clientControl.SetSessionPropertiesAsync(session2.SessionId, + new Dictionary { { "$Country", "CA" } }); + + session2.Close(); + session1.Close(); + } + + private class MyEventStream : ISessionEventStream + { + public void OnClose() + { + WriteLine("Stream closed"); + } + + public void OnError(ErrorReason errorReason) => WriteLine($"An error occured:{errorReason}"); + + public void OnSessionEvent(ISessionEventStreamEvent sessionEventStreamEvent) + { + if (sessionEventStreamEvent.IsOpenEvent) + { + WriteLine($"New session: id={sessionEventStreamEvent.SessionId}"); + return; + } + + if (sessionEventStreamEvent.SessionEventStreamEventType == SessionEventStreamEventType.STATE) + { + WriteLine($"Session state changed: id={sessionEventStreamEvent.SessionId}, state={sessionEventStreamEvent.SessionEventStreamEventState}"); + } + else + { + WriteLine($"Session properties changed: id={sessionEventStreamEvent.SessionId}, properties: "); + var properties = sessionEventStreamEvent.Properties; + foreach (var changedProperty in sessionEventStreamEvent.ChangedProperties) + { + string line = $"{changedProperty.Key} changed from '{changedProperty.Value}' to '{properties[changedProperty.Key]}'"; + WriteLine(line); + } + } + } + } + } +} diff --git a/dotnet/examples/Monitoring/TopicNotifications.cs b/dotnet/examples/Monitoring/TopicNotifications.cs new file mode 100644 index 00000000..8ad930fa --- /dev/null +++ b/dotnet/examples/Monitoring/TopicNotifications.cs @@ -0,0 +1,104 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using System.Collections.Generic; +using System.Linq; +using static System.Console; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; +using PushTechnology.ClientInterface.Client.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using static PushTechnology.ClientInterface.Examples.Program; +using NUnit.Framework; + +namespace PushTechnology.ClientInterface.Examples.Monitoring +{ + public sealed class TopicNotifications : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var topicNotificationListener = new TopicNotificationListener(); + var registration = await session.TopicNotifications.AddListenerAsync(topicNotificationListener, cancellationToken); + await registration.SelectAsync(">my/topic/path", cancellationToken); + + var specification = Diffusion.NewSpecification(TopicType.STRING); + + await session.TopicUpdate.AddAndSetAsync("my/topic/path", specification, "Good morning", cancellationToken); + await session.TopicUpdate.AddAndSetAsync("my/topic/path/descendant", specification, "Good afternoon", cancellationToken); + await session.TopicUpdate.AddAndSetAsync("other/path/of/the/topic/tree", specification, "This will not generate a notification", cancellationToken); + await session.TopicControl.RemoveTopicsAsync("my/topic/path/descendant", cancellationToken); + + session.Close(); + } + + private sealed class TopicNotificationListener : ITopicNotificationListener + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnDescendantNotification(string topicPath, NotificationType type) + { + if (type == NotificationType.ADDED) + { + WriteLine($"Descendant Topic {topicPath} has been added."); + } + if (type == NotificationType.SELECTED) + { + WriteLine($"Descendant Topic {topicPath} has been selected."); + } + if (type == NotificationType.DESELECTED) + { + WriteLine($"Descendant Topic {topicPath} has been deselected."); + } + if (type == NotificationType.REMOVED) + { + WriteLine($"Descendant Topic {topicPath} has been removed."); + } + } + + public void OnTopicNotification(string topicPath, ITopicSpecification specification, NotificationType type) + { + if (type == NotificationType.ADDED) + { + WriteLine($"Topic {topicPath} has been added."); + } + if (type == NotificationType.SELECTED) + { + WriteLine($"Topic {topicPath} has been selected."); + } + if (type == NotificationType.DESELECTED) + { + WriteLine($"Topic {topicPath} has been deselected."); + } + if (type == NotificationType.REMOVED) + { + WriteLine($"Topic {topicPath} has been removed."); + } + } + } + } +} diff --git a/dotnet/examples/Ping/PingServer.cs b/dotnet/examples/Ping/PingServer.cs new file mode 100644 index 00000000..36da2dfa --- /dev/null +++ b/dotnet/examples/Ping/PingServer.cs @@ -0,0 +1,42 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.Ping +{ + public sealed class PingServer: Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var pingDetails = await session.Ping.PingServerAsync(cancellationToken); + WriteLine($"Server Ping: {pingDetails.RoundTripTimeSpan}ms."); + + session.Close(); + } + } +} diff --git a/dotnet/examples/Program.cs b/dotnet/examples/Program.cs new file mode 100644 index 00000000..992a14fa --- /dev/null +++ b/dotnet/examples/Program.cs @@ -0,0 +1,564 @@ +/** +* Copyright © 2023 - 2025 Diffusion Data Ltd. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using System.Threading; + +using PushTechnology.ClientInterface.Examples.Connection.Establishment; +using PushTechnology.ClientInterface.Examples.Connection.Resilience; +using PushTechnology.ClientInterface.Examples.Wrangling.TopicViews.API; +using PushTechnology.ClientInterface.Examples.Wrangling.SessionTrees; +using PushTechnology.ClientInterface.Examples.Messaging; +using PushTechnology.ClientInterface.Examples.Monitoring; +using PushTechnology.ClientInterface.Examples.Ping; +using PushTechnology.ClientInterface.Examples.PubSub.FetchTopics; +using PushTechnology.ClientInterface.Examples.PubSub.PublishingTopics; +using PushTechnology.ClientInterface.Examples.PubSub.PublishingTopicsWithConstraint; +using PushTechnology.ClientInterface.Examples.PubSub.RemovingTopics; +using PushTechnology.ClientInterface.Examples.PubSub.SubscribingToTopics; +using PushTechnology.ClientInterface.Examples.PubSub.JSONPatch; +using PushTechnology.ClientInterface.Examples.TimeSeries; +using PushTechnology.ClientInterface.Examples.Security; +using PushTechnology.ClientInterface.Examples.ServerConfiguration.Metrics; +using PushTechnology.ClientInterface.Examples.ServerConfiguration.Metrics.MetricAlerts; +using PushTechnology.ClientInterface.Examples.ServerConfiguration.Metrics.SessionMetricCollector; +using PushTechnology.ClientInterface.Examples.ServerConfiguration.Metrics.TopicMetricCollector; +using PushTechnology.ClientInterface.Examples.ServerConfiguration.RemoteServers; +using PushTechnology.ClientInterface.Examples.ServerConfiguration.SystemAuthenticationControl; +using PushTechnology.ClientInterface.Examples.ServerConfiguration.SecurityControl; +using PushTechnology.ClientInterface.Examples.SessionManagement; +using PushTechnology.ClientInterface.Examples.SessionManagement.ClientControl; +using PushTechnology.ClientInterface.Examples.Wrangling.TopicViews.DSL; + +namespace PushTechnology.ClientInterface.Examples +{ + /// + /// This is used to run the examples. + /// + public static class Program + { + + /// + /// To run an example, uncomment the corresponding block of code. + /// + /// The program arguments. + public static void Main(string[] args) + { + var url = "ws://localhost:8080"; + var secureUrl = "wss://localhost:8080"; + + using (var runner = new ExampleRunner()) + { + // Start the connect synchronously example + //runner.Start(new ConnectSynchronously(), url); + + // Start the connect synchronously without URL example + //runner.Start(new ConnectSynchronouslyWithoutURL(), url); + + // Start the connect asynchronously example + //runner.Start(new ConnectAsynchronously(), url); + + // Start the connect asynchronously without URL example + //runner.Start(new ConnectAsynchronouslyWithoutURL(), url); + + // Start the connect using a session factory example + //runner.Start(new ConnectUsingASessionFactory(), url); + + // Start the connect securely example + //runner.Start(new ConnectSecurelyAcceptingAllServerCertificates(), secureUrl); + + // Start the session state listener example + //runner.Start(new SessionStateListener(), url); + + // Start the reconnection strategy example + //runner.Start(new ReconnectionStrategy(), url); + + // Start the initial session establishment retry mechanism example + //runner.Start(new InitialSessionEstablishmentRetryMechanism(), url); + + // Start the ping server example + //runner.Start(new PingServer(), url); + + // Start the reauthenticate example + //runner.Start(new Reauthenticate(), url); + + // Start the get global permissions example + //runner.Start(new GetGlobalPermissions(), url); + + // Start the get path permissions example + //runner.Start(new GetPathPermissions(), url); + + // Start the add topic example + //runner.Start(new AddTopic(), url); + + // Start the add topic with custom topic properties example + //runner.Start(new AddTopicWithCustomTopicProperties(), url); + + // Start the add and set topic example + //runner.Start(new AddAndSetTopic(), url); + + // Start the set topic example + //runner.Start(new SetTopic(), url); + + // Start the add and set topic using update stream example + //runner.Start(new AddAndSetTopicUsingUpdateStream(), url); + + // Start the set topic using update stream example + //runner.Start(new SetTopicUsingUpdateStream(), url); + + // Start the add and set topic with no topic constraint example + //runner.Start(new AddAndSetTopicNoTopic(), url); + + // Start the add and set topic with session lock constraint example + //runner.Start(new AddAndSetTopicSessionLock(), url); + + // Start the add and set topic with value constraint example + //runner.Start(new AddAndSetTopicValue(), url); + + // Start the add and set topic with JSON value with constraint example + //runner.Start(new AddAndSetTopicJSONValueWith(), url); + + // Start the add and set topic with JSON value without constraint example + //runner.Start(new AddAndSetTopicJSONValueWithout(), url); + + // Start the set topic with no value constraint example + //runner.Start(new SetTopicNoValue(), url); + + // Start the set topic with session lock constraint example + //runner.Start(new SetTopicSessionLock(), url); + + // Start the set topic with value constraint example + //runner.Start(new SetTopicValue(), url); + + // Start the set topic with JSON value with constraint example + //runner.Start(new SetTopicJSONValueWith(), url); + + // Start the set topic with JSON value without constraint example + //runner.Start(new SetTopicJSONValueWithout(), url); + + // Start the add and set topic with and constraint example + //runner.Start(new AddAndSetTopicAnd(), url); + + // Start the add and set topic with or constraint example + //runner.Start(new AddAndSetTopicOr(), url); + + // Start the subscribe to single topic using topic path example + //runner.Start(new SubscribeToSingleTopicUsingTopicPath(), url); + + // Start the subscribe to multiple topics using topic selector example + //runner.Start(new SubscribeToMultipleTopicsUsingTopicSelector(), url); + + // Start the subscribe using fallback streams example + //runner.Start(new SubscribeUsingFallbackStreams(), url); + + // Start the subscribe with cross compatible value stream example + //runner.Start(new SubscribeWithCrossCompatibleValueStream(), url); + + // Start the subscribe using selection scopes example + //runner.Start(new SubscribeUsingSelectionScopes(), url); + + // Start the removing a single topic using topic path example + //runner.Start(new RemovingASingleTopicUsingTopicPath(), url); + + // Start the removing multiple topics using a topic selector example + //runner.Start(new RemovingMultipleTopicsUsingATopicSelector(), url); + + // Start the removing topics with automatic topic removal example + //runner.Start(new RemovingTopicsWithAutomaticTopicRemoval(), url); + + // Start the fetch topic properties example + //runner.Start(new FetchTopicProperties(), url); + + // Start the fetch multiple topics by iterating through paging example + //runner.Start(new FetchMultipleTopicsByIteratingThroughPaging(), url); + + // Start the json patch add example + //runner.Start(new JSONPatchAdd(), url); + + // Start the json patch copy example + //runner.Start(new JSONPatchCopy(), url); + + // Start the json patch move example + //runner.Start(new JSONPatchMove(), url); + + // Start the json patch remove example + //runner.Start(new JSONPatchRemove(), url); + + // Start the json patch replace example + //runner.Start(new JSONPatchReplace(), url); + + // Start the json patch test example + //runner.Start(new JSONPatchTest(), url); + + // Start the create timeSeries topic example + //runner.Start(new CreateTimeSeriesTopic(), url); + + // Start the append to timeSeries topic example + //runner.Start(new AppendToTimeSeriesTopic(), url); + + // Start the subscribe to timeSeries topics example + //runner.Start(new SubscribeToTimeSeriesTopics(), url); + + // Start the append to timeSeries topic with user supplied timestamp example + //runner.Start(new AppendToTimeSeriesTopicWithUserSuppliedTimestamp(), url); + + // Start the append to timeSeries topic via update stream example + //runner.Start(new AppendToTimeSeriesTopicViaUpdateStream(), url); + + // Start the edit timeSeries topic example + //runner.Start(new EditTimeSeriesTopic(), url); + + // Start the range query a timeSeries topic example + //runner.Start(new RangeQueryATimeSeriesTopic(), url); + + // Start the timeSeries cross compatible datatypes example + //runner.Start(new TimeSeriesCrossCompatibleDatatypes(), url); + + // Start the message to messagePath example + //runner.Start(new MessageToMessagePath(), url); + + // Start the message to session ID example + //runner.Start(new MessageToSessionID(), url); + + // Start the message to session filter example + //runner.Start(new MessageToSessionFilter(), url); + + // Start the add topic view example + //runner.Start(new AddTopicView(), url); + + // Start the list topic views example + //runner.Start(new ListTopicViews(), url); + + // Start the remove topic views example + //runner.Start(new RemoveTopicViews(), url); + + // Start the source path directive example + //runner.Start(new SourcePathDirective(), url); + + // Start the remote topic views example + //runner.Start(new RemoteTopicViews(), url); + + // Start the scalar directive example + //runner.Start(new ScalarDirective(), url); + + // Start the expand value example + //runner.Start(new ExpandValue(), url); + + // Start the process transformations set example + //runner.Start(new ProcessTransformationsSet(), url); + + // Start the process transformations remove example + //runner.Start(new ProcessTransformationsRemove(), url); + + // Start the process transformations continue example + //runner.Start(new ProcessTransformationsContinue(), url); + + // Start the patch transformations add example + //runner.Start(new PatchTransformationsAdd(), url); + + // Start the patch transformations remove example + //runner.Start(new PatchTransformationsRemove(), url); + + // Start the patch transformations replace example + //runner.Start(new PatchTransformationsReplace(), url); + + // Start the patch transformations move example + //runner.Start(new PatchTransformationsMove(), url); + + // Start the patch transformations copy example + //runner.Start(new PatchTransformationsCopy(), url); + + // Start the patch transformations test example + //runner.Start(new PatchTransformationsTest(), url); + + // Start the insert transformations example + //runner.Start(new InsertTransformations(), url); + + // Start the options topic property mapping example + //runner.Start(new OptionsTopicPropertyMapping(), url); + + // Start the options topic value example + //runner.Start(new OptionsTopicValue(), url); + + // Start the options throttle example + //runner.Start(new OptionsThrottle(), url); + + // Start the options delay example + //runner.Start(new OptionsDelay(), url); + + // Start the options separator example + //runner.Start(new OptionsSeparator(), url); + + // Start the options preserve topics example + //runner.Start(new OptionsPreserveTopics(), url); + + // Start the options topic type example + //runner.Start(new OptionsTopicType(), url); + + // Start the put branch mapping table example + //runner.Start(new PutBranchMappingTable(), url); + + // Start the list session tree branches with mappings example + //runner.Start(new ListSessionTreeBranchesWithMappings(), url); + + // Start the get branch mapping table example + //runner.Start(new GetBranchMappingTable(), url); + + // Start the session trees use case example + //runner.Start(new UseCase(), url); + + // Start the put and remove branch mapping table example + //runner.Start(new PutAndRemoveBranchMappingTable(), url); + + // Start the missing topic notifications example + //runner.Start(new MissingTopicNotifications(), url); + + // Start the topic notifications example + //runner.Start(new TopicNotifications(), url); + + // Start the session event listener example + //runner.Start(new SessionEventListener(), url); + + // Start the subscription control example + //runner.Start(new SubscriptionControl(), url); + + // Start the authentication control example + //runner.Start(new AuthenticationControl(), url); + + // Start the get session properties via session ID example + //runner.Start(new GetSessionPropertiesViaSessionID(), url); + + // Start the set session properties via session ID example + //runner.Start(new SetSessionPropertiesViaSessionID(), url); + + // Start the set session properties via session filter example + //runner.Start(new SetSessionPropertiesViaSessionFilter(), url); + + // Start the close client via session ID example + //runner.Start(new CloseClientViaSessionID(), url); + + // Start the close client via session filter example + //runner.Start(new CloseClientViaSessionFilter(), url); + + // Start the change roles via session ID example + //runner.Start(new ChangeRolesViaSessionID(), url); + + // Start the change roles via session filter example + //runner.Start(new ChangeRolesViaSessionFilter(), url); + + // Start the control client queue conflation via session ID example + //runner.Start(new ControlClientQueueConflationViaSessionID(), url); + + // Start the control client queue conflation via session filter example + //runner.Start(new ControlClientQueueConflationViaSessionFilter(), url); + + // Start the put session metric collector example + //runner.Start(new PutSessionMetricCollector(), url); + + // Start the list session metric collectors example + //runner.Start(new ListSessionMetricCollectors(), url); + + // Start the remove session metric collector example + //runner.Start(new RemoveSessionMetricCollector(), url); + + // Start the put topic metric collector example + //runner.Start(new PutTopicMetricCollector(), url); + + // Start the list topic metric collectors example + //runner.Start(new ListTopicMetricCollectors(), url); + + // Start the remove topic metric collector example + //runner.Start(new RemoveTopicMetricCollector(), url); + + // Start the get outbound bytes example + //runner.Start(new GetOutboundBytes(), url); + + // Start the get metrics console example + //runner.Start(new GetMetricsConsole(), url); + + // Start the set metric alert example + //runner.Start(new SetMetricAlert(), url); + + // Start the list metric alerts example + //runner.Start(new ListMetricAlerts(), url); + + // Start the remove metric alert example + //runner.Start(new RemoveMetricAlert(), url); + + // Start the isolate path example + //runner.Start(new IsolatePath(), url); + + // Start the deisolate path example + //runner.Start(new DeisolatePath(), url); + + // Start the set path permissions example + //runner.Start(new SetPathPermissions(), url); + + // Start the remove path permissions example + //runner.Start(new RemovePathPermissions(), url); + + // Start the set default path permissions example + //runner.Start(new SetDefaultPathPermissions(), url); + + // Start the set global permissions example + //runner.Start(new SetGlobalPermissions(), url); + + // Start the define roles hierarchy example + //runner.Start(new DefineRolesHierarchy(), url); + + // Start the restrict role edit permissions example + //runner.Start(new RestrictRoleEditPermissions(), url); + + // Start the set default roles for anonymous sessions example + //runner.Start(new SetDefaultRolesForAnonymousSessions(), url); + + // Start the set default roles for named sessions example + //runner.Start(new SetDefaultRolesForNamedSessions(), url); + + // Start the deny anonymous connections example + //runner.Start(new DenyAnonymousConnections(), url); + + // Start the abstain anonymous connections example + //runner.Start(new AbstainAnonymousConnections(), url); + + // Start the allow anonymous connections example + //runner.Start(new AllowAnonymousConnections(), url); + + // Start the add principal example + //runner.Start(new AddPrincipal(), url); + + // Start the add locked principal example + //runner.Start(new AddLockedPrincipal(), url); + + // Start the remove principal example + //runner.Start(new RemovePrincipal(), url); + + // Start the assign roles example + //runner.Start(new AssignRoles(), url); + + // Start the change principal's password example + //runner.Start(new ChangePrincipalPassword(), url); + + // Start the verify principal's password example + //runner.Start(new VerifyPrincipalPassword(), url); + + // Start the trust client proposed property value from allowed value example + //runner.Start(new TrustClientProposedPropertyIn(), url); + + // Start the trust client proposed property value that matches regular expression example + //runner.Start(new TrustClientProposedPropertyMatches(), url); + + // Start the ignore client proposed property example + //runner.Start(new IgnoreClientProposedProperty(), url); + + // Start the create primary initiator remote server example + //runner.Start(new CreatePrimaryInitiatorRemoteServer(), url); + + // Start the create secondary initiator remote server example + //runner.Start(new CreateSecondaryInitiatorRemoteServer(), url); + + // Start the create secondary acceptor remote server example + //runner.Start(new CreateSecondaryAcceptorRemoteServer(), url); + + // Start the list remote servers example + //runner.Start(new ListRemoteServers(), url); + + // Start the check remote servers example + //runner.Start(new CheckRemoteServers(), url); + + // Start the remove remote servers example + //runner.Start(new RemoveRemoteServers(), url); + } + } + + /// + /// Interface to be used by all examples. + /// + public interface IExample + { + /// + /// Runs the current example. + /// + /// + /// This acts as the main method for examples. + /// + /// The cancellation token to cancel the current example run. + /// The optional example arguments. + Task Run(CancellationToken cancel, string[] args); + + Task RunWrapper(CancellationToken cancel, string[] args); + AutoResetEvent CompletedEvent { get; set; } + } + + public abstract class Example : IExample + { + + public virtual AutoResetEvent CompletedEvent { get; set; } + + public async Task RunWrapper(CancellationToken cancel, string[] args) + { + await Run(cancel, args); + CompletedEvent.Set(); + } + + public abstract Task Run(CancellationToken cancel, string[] args); + + public Example() => CompletedEvent = new AutoResetEvent(false); + } + + /// + /// Class used by the Main method in to start a new cancelable task + /// for each implementation. + /// + private sealed class ExampleRunner : IDisposable + { + private readonly List runningExamples = new List(); + private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + + /// + /// Starts a new task for an implementation. + /// + /// The example to run. + /// An array of arguments. Depending on what is necessary for an example, + /// it may contain multiple variables, such as serverUrl, topic paths etc. Check the example class + /// for the description of what is required for this array. + public void Start(IExample example, params string[] args) + { + var task = Task.Run(async () => { + var run = example?.RunWrapper(cancellationTokenSource.Token, args); + if (run != null) + { + await run; + } + }); + runningExamples.Add(task); + + Assert.IsTrue(example.CompletedEvent.WaitOne(50000)); + } + + /// + /// Method used to wait for examples to be canceled by the user. + /// + public void Dispose() + { + cancellationTokenSource.Cancel(); + Task.WaitAll(runningExamples.ToArray()); + } + } + } +} + diff --git a/dotnet/examples/PubSub/FetchTopics/FetchMultipleTopicsByIteratingThroughPaging.cs b/dotnet/examples/PubSub/FetchTopics/FetchMultipleTopicsByIteratingThroughPaging.cs new file mode 100644 index 00000000..6c09c931 --- /dev/null +++ b/dotnet/examples/PubSub/FetchTopics/FetchMultipleTopicsByIteratingThroughPaging.cs @@ -0,0 +1,78 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +using System.Threading; +using System.Threading.Tasks; +using static System.Console; +using System.Linq; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Topics; + +namespace PushTechnology.ClientInterface.Examples.PubSub.FetchTopics +{ + public sealed class FetchMultipleTopicsByIteratingThroughPaging : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var topics = session.Topics; + + var topicSpecification = Diffusion.NewSpecification(TopicType.STRING); + + for (int i = 1; i <= 25; i++) + { + string stringValue = string.Format("diffusion data #{0}", i); + await session.TopicUpdate.AddAndSetAsync("my/topic/path/" + i, topicSpecification, stringValue, cancellationToken); + } + + IFetchResult fetchResult = null; + + string topicSelector = "?my/topic/path//"; + + fetchResult = await topics.FetchRequest.WithValues().First(10).FetchAsync(topicSelector, cancellationToken); + + while (true) + { + foreach (var topic in fetchResult.Results) + { + WriteLine($"{topic.Path}: {topic.Value}"); + } + + if (fetchResult.HasMore) + { + // Fetch the next 10 values. + string path = fetchResult.Results.ElementAt(fetchResult.Results.Count - 1).Path; + fetchResult = await topics.FetchRequest.After(path).WithValues().First(10).FetchAsync(topicSelector, cancellationToken); + WriteLine("Loading next page."); + } + else + { + WriteLine("Done."); + break; + } + } + + session.Close(); + } + } +} + diff --git a/dotnet/examples/PubSub/FetchTopics/FetchTopicProperties.cs b/dotnet/examples/PubSub/FetchTopics/FetchTopicProperties.cs new file mode 100644 index 00000000..266919c9 --- /dev/null +++ b/dotnet/examples/PubSub/FetchTopics/FetchTopicProperties.cs @@ -0,0 +1,96 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +using System.Threading; +using System.Threading.Tasks; +using System.Linq; +using System.Collections.Generic; +using static PushTechnology.ClientInterface.Examples.Program; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; + +namespace PushTechnology.ClientInterface.Examples.PubSub.FetchTopics +{ + public sealed class FetchTopicProperties : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var topics = session.Topics; + + var topicProperties = new Dictionary { + { TopicSpecificationProperty.DontRetainValue, "true" }, + { TopicSpecificationProperty.Persistent, "false" }, + { TopicSpecificationProperty.PublishValuesOnly, "true" } + }; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON) + .WithProperties(topicProperties); + + for (int i = 1; i <= 5; i++) + { + string jsonValue = string.Format("\"diffusion\":\"data #{0}\"", i); + await session.TopicUpdate.AddAndSetAsync("my/topic/path/with/properties/" + i, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString("{" + jsonValue + "}"), cancellationToken); + } + + topicSpecification = Diffusion.NewSpecification(TopicType.STRING) + .WithProperties(topicProperties); + + for (int i = 1; i <= 5; i++) + { + string stringValue = string.Format("diffusion data #{0}", i); + await session.TopicUpdate.AddAndSetAsync("my/topic/path/with/default/properties/" + i, topicSpecification, stringValue, cancellationToken); + } + + var topicTypes = new[] { TopicType.JSON }; + var fetchResult = await topics.FetchRequest.TopicTypes(topicTypes).WithProperties().FetchAsync("?my/topic/path//", cancellationToken); + + foreach (var topic in fetchResult.Results) + { + WriteLine($"{topic.Path} properties:"); + + foreach (var property in topic.Specification.Properties) + { + WriteLine($"{property.Key}: {property.Value}"); + } + } + + topicTypes = new[] { TopicType.STRING }; + + // Fetch the topic properties for the topic path selector my/topic/path/. + fetchResult = await topics.FetchRequest.TopicTypes(topicTypes).WithProperties().FetchAsync("?my/topic/path//", cancellationToken); + + foreach (var topic in fetchResult.Results) + { + WriteLine($"{topic.Path} properties:"); + + foreach (var property in topic.Specification.Properties) + { + WriteLine($"{property.Key}: {property.Value}"); + } + } + + session.Close(); + } + } +} + diff --git a/dotnet/examples/PubSub/JSONPatch/JSONPatchAdd.cs b/dotnet/examples/PubSub/JSONPatch/JSONPatchAdd.cs new file mode 100644 index 00000000..25b76aee --- /dev/null +++ b/dotnet/examples/PubSub/JSONPatch/JSONPatchAdd.cs @@ -0,0 +1,82 @@ +/** + * Copyright © 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Data.JSON; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; + +namespace PushTechnology.ClientInterface.Examples.PubSub.JSONPatch +{ + public sealed class JSONPatchAdd : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var topic = "my/topic/path"; + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + string json = "{\"Fred\":\"Flintstone\",\"Barney\":\"Rubble\"}"; + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topic, jsonStream); + + await session.Topics.SubscribeAsync(topic, cancellationToken); + + var result = await session.TopicUpdate.ApplyJSONPatchAsync(topic, "[{\"op\":\"add\", \"path\": \"/George\", \"value\": \"Jetson\"}]", cancellationToken); + + WriteLine($"JSON patch add has been successfully applied."); + + session.Close(); + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() { } + + public void OnError(ErrorReason errorReason) { } + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} diff --git a/dotnet/examples/PubSub/JSONPatch/JSONPatchCopy.cs b/dotnet/examples/PubSub/JSONPatch/JSONPatchCopy.cs new file mode 100644 index 00000000..0f7744fe --- /dev/null +++ b/dotnet/examples/PubSub/JSONPatch/JSONPatchCopy.cs @@ -0,0 +1,82 @@ +/** + * Copyright © 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Data.JSON; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; + +namespace PushTechnology.ClientInterface.Examples.PubSub.JSONPatch +{ + public sealed class JSONPatchCopy : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var topic = "my/topic/path"; + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + string json = "{ \"Meet the Flintstones\": {\"Fred\":\"Flintstone\",\"Barney\":\"Rubble\"}, \"The Jetsons\": {\"George\":\"Jetson\"}}"; + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topic, jsonStream); + + await session.Topics.SubscribeAsync(topic, cancellationToken); + + var result = await session.TopicUpdate.ApplyJSONPatchAsync(topic, "[{\"op\":\"copy\", \"from\": \"/Meet the Flintstones/Fred\", \"path\": \"/The Jetsons/George\"}]", cancellationToken); + + WriteLine($"JSON patch copy has been successfully applied."); + + session.Close(); + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() { } + + public void OnError(ErrorReason errorReason) { } + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} diff --git a/dotnet/examples/PubSub/JSONPatch/JSONPatchMove.cs b/dotnet/examples/PubSub/JSONPatch/JSONPatchMove.cs new file mode 100644 index 00000000..027d36d1 --- /dev/null +++ b/dotnet/examples/PubSub/JSONPatch/JSONPatchMove.cs @@ -0,0 +1,82 @@ +/** + * Copyright © 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Data.JSON; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; + +namespace PushTechnology.ClientInterface.Examples.PubSub.JSONPatch +{ + public sealed class JSONPatchMove : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var topic = "my/topic/path"; + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + string json = "{\"Fred\":\"Flintstone\",\"Barney\":\"Rubble\",\"George\":\"Jetson\"}"; + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topic, jsonStream); + + await session.Topics.SubscribeAsync(topic, cancellationToken); + + var result = await session.TopicUpdate.ApplyJSONPatchAsync(topic, "[{\"op\":\"move\", \"from\": \"/Fred\", \"path\": \"/Meet The Flintstones~1Fred\"}]", cancellationToken); + + WriteLine($"JSON patch move has been successfully applied."); + + session.Close(); + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() { } + + public void OnError(ErrorReason errorReason) { } + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} diff --git a/dotnet/examples/PubSub/JSONPatch/JSONPatchRemove.cs b/dotnet/examples/PubSub/JSONPatch/JSONPatchRemove.cs new file mode 100644 index 00000000..efcdd481 --- /dev/null +++ b/dotnet/examples/PubSub/JSONPatch/JSONPatchRemove.cs @@ -0,0 +1,82 @@ +/** + * Copyright © 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Data.JSON; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; + +namespace PushTechnology.ClientInterface.Examples.PubSub.JSONPatch +{ + public sealed class JSONPatchRemove : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var topic = "my/topic/path"; + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + string json = "{\"Fred\":\"Flintstone\",\"Barney\":\"Rubble\",\"George\":\"Jetson\"}"; + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topic, jsonStream); + + await session.Topics.SubscribeAsync(topic, cancellationToken); + + var result = await session.TopicUpdate.ApplyJSONPatchAsync(topic, "[{\"op\":\"remove\", \"path\": \"/George\"}]", cancellationToken); + + WriteLine($"JSON patch remove has been successfully applied."); + + session.Close(); + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() { } + + public void OnError(ErrorReason errorReason) { } + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} diff --git a/dotnet/examples/PubSub/JSONPatch/JSONPatchReplace.cs b/dotnet/examples/PubSub/JSONPatch/JSONPatchReplace.cs new file mode 100644 index 00000000..fd355e58 --- /dev/null +++ b/dotnet/examples/PubSub/JSONPatch/JSONPatchReplace.cs @@ -0,0 +1,82 @@ +/** + * Copyright © 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Data.JSON; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; + +namespace PushTechnology.ClientInterface.Examples.PubSub.JSONPatch +{ + public sealed class JSONPatchReplace : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var topic = "my/topic/path"; + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + string json = "{\"Fred\":\"Flintstone\",\"Barney\":\"Rubble\",\"George\":\"Jetson\"}"; + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topic, jsonStream); + + await session.Topics.SubscribeAsync(topic, cancellationToken); + + var result = await session.TopicUpdate.ApplyJSONPatchAsync(topic, "[{\"op\":\"replace\", \"path\": \"/George\", \"value\": \"Bedrock\"}]", cancellationToken); + + WriteLine($"JSON patch replace has been successfully applied."); + + session.Close(); + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() { } + + public void OnError(ErrorReason errorReason) { } + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} diff --git a/dotnet/examples/PubSub/JSONPatch/JSONPatchTest.cs b/dotnet/examples/PubSub/JSONPatch/JSONPatchTest.cs new file mode 100644 index 00000000..e18bcbc4 --- /dev/null +++ b/dotnet/examples/PubSub/JSONPatch/JSONPatchTest.cs @@ -0,0 +1,82 @@ +/** + * Copyright © 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Data.JSON; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; + +namespace PushTechnology.ClientInterface.Examples.PubSub.JSONPatch +{ + public sealed class JSONPatchTest : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var topic = "my/topic/path"; + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + string json = "{\"Fred\":\"Flintstone\",\"Barney\":\"Rubble\",\"George\":\"Jetson\"}"; + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topic, jsonStream); + + await session.Topics.SubscribeAsync(topic, cancellationToken); + + var result = await session.TopicUpdate.ApplyJSONPatchAsync(topic, "[{\"op\":\"test\", \"path\": \"/Fred\", \"value\": \"Flintstone\"}]", cancellationToken); + + WriteLine($"JSON patch test has been successfully applied."); + + session.Close(); + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() { } + + public void OnError(ErrorReason errorReason) { } + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} diff --git a/dotnet/examples/PubSub/PublishingTopics/AddAndSetTopic.cs b/dotnet/examples/PubSub/PublishingTopics/AddAndSetTopic.cs new file mode 100644 index 00000000..0e4750b7 --- /dev/null +++ b/dotnet/examples/PubSub/PublishingTopics/AddAndSetTopic.cs @@ -0,0 +1,56 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Topics; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Features; + +namespace PushTechnology.ClientInterface.Examples.PubSub.PublishingTopics +{ + public sealed class AddAndSetTopic : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + + string json = "{\"diffusion\":\"data\"}"; + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + var result = await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + if (result == TopicCreationResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + + session.Close(); + } + } +} diff --git a/dotnet/examples/PubSub/PublishingTopics/AddAndSetTopicUsingUpdateStream.cs b/dotnet/examples/PubSub/PublishingTopics/AddAndSetTopicUsingUpdateStream.cs new file mode 100644 index 00000000..303a4d96 --- /dev/null +++ b/dotnet/examples/PubSub/PublishingTopics/AddAndSetTopicUsingUpdateStream.cs @@ -0,0 +1,61 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Topics; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Data.JSON; + +namespace PushTechnology.ClientInterface.Examples.PubSub.PublishingTopics +{ + public sealed class AddAndSetTopicUsingUpdateStream : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var topic = "my/topic/path/with/update/stream"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + var updateStream = session.TopicUpdate.NewUpdateStreamBuilder() + .Specification(topicSpecification) + .Build(topic); + + var result = await updateStream.SetAsync(Diffusion.DataTypes.JSON.FromJSONString("{\"diffusion\":\"data\"}"), cancellationToken); + + if (result == TopicCreationResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + + session.Close(); + } + } +} diff --git a/dotnet/examples/PubSub/PublishingTopics/AddTopic.cs b/dotnet/examples/PubSub/PublishingTopics/AddTopic.cs new file mode 100644 index 00000000..f8d56ba0 --- /dev/null +++ b/dotnet/examples/PubSub/PublishingTopics/AddTopic.cs @@ -0,0 +1,56 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; +using PushTechnology.ClientInterface.Client.Topics; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.PubSub.PublishingTopics +{ + public sealed class AddTopic : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + var result = await session.TopicControl.AddTopicAsync(topic, topicSpecification, cancellationToken); + + if (result == AddTopicResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + + session.Close(); + } + } +} diff --git a/dotnet/examples/PubSub/PublishingTopics/AddTopicWithCustomTopicProperties.cs b/dotnet/examples/PubSub/PublishingTopics/AddTopicWithCustomTopicProperties.cs new file mode 100644 index 00000000..38b7f64f --- /dev/null +++ b/dotnet/examples/PubSub/PublishingTopics/AddTopicWithCustomTopicProperties.cs @@ -0,0 +1,66 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Client.Topics; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; +using System.Collections.Generic; +using PushTechnology.ClientInterface.Client.Features; + +namespace PushTechnology.ClientInterface.Examples.PubSub.PublishingTopics +{ + public sealed class AddTopicWithCustomTopicProperties : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path/with/properties"; + + var topicProperties = new Dictionary { + { TopicSpecificationProperty.DontRetainValue, "true" }, + { TopicSpecificationProperty.Persistent, "false" }, + { TopicSpecificationProperty.PublishValuesOnly, "true" } + }; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON) + .WithProperties(topicProperties); + + var result = await session.TopicControl.AddTopicAsync(topic, topicSpecification, cancellationToken); + + if (result == AddTopicResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + + session.Close(); + } + } +} diff --git a/dotnet/examples/PubSub/PublishingTopics/SetTopic.cs b/dotnet/examples/PubSub/PublishingTopics/SetTopic.cs new file mode 100644 index 00000000..e3f5bf85 --- /dev/null +++ b/dotnet/examples/PubSub/PublishingTopics/SetTopic.cs @@ -0,0 +1,63 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; +using PushTechnology.ClientInterface.Client.Topics; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Data.JSON; +using PushTechnology.ClientInterface.Client.Features; + +namespace PushTechnology.ClientInterface.Examples.PubSub.PublishingTopics +{ + public sealed class SetTopic : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + var result = await session.TopicControl.AddTopicAsync(topic, topicSpecification, cancellationToken); + + if (result == AddTopicResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + + string json = "{\"diffusion\":[\"data\", \"more data\"]}"; + await session.TopicUpdate.SetAsync(topic, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + WriteLine("Topic value has been set."); + + session.Close(); + } + } +} diff --git a/dotnet/examples/PubSub/PublishingTopics/SetTopicUsingUpdateStream.cs b/dotnet/examples/PubSub/PublishingTopics/SetTopicUsingUpdateStream.cs new file mode 100644 index 00000000..a880b391 --- /dev/null +++ b/dotnet/examples/PubSub/PublishingTopics/SetTopicUsingUpdateStream.cs @@ -0,0 +1,66 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Data.JSON; +using NUnit.Framework; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; +using PushTechnology.ClientInterface.Client.Topics; + +namespace PushTechnology.ClientInterface.Examples.PubSub.PublishingTopics +{ + public sealed class SetTopicUsingUpdateStream : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path/with/update/stream"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + var result = await session.TopicControl.AddTopicAsync(topic, topicSpecification, cancellationToken); + + if (result == AddTopicResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + + var updateStream = session.TopicUpdate.NewUpdateStreamBuilder() + .Build(topic); + + await updateStream.SetAsync(Diffusion.DataTypes.JSON.FromJSONString("{\"diffusion\":[\"data\", \"more data\"]}"), cancellationToken); + + WriteLine("Topic value has been set."); + + session.Close(); + } + } +} diff --git a/dotnet/examples/PubSub/PublishingTopicsWithConstraint/AddAndSetTopicAnd.cs b/dotnet/examples/PubSub/PublishingTopicsWithConstraint/AddAndSetTopicAnd.cs new file mode 100644 index 00000000..d340acd9 --- /dev/null +++ b/dotnet/examples/PubSub/PublishingTopicsWithConstraint/AddAndSetTopicAnd.cs @@ -0,0 +1,74 @@ +/** + * Copyright © 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Topics; +using PushTechnology.ClientInterface.Client.Features; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.PubSub.PublishingTopicsWithConstraint +{ + public sealed class AddAndSetTopicAnd : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + + string json = "{\"diffusion\":\"data\"}"; + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + var withoutConstraint = Diffusion.UpdateConstraints.JSONValue.Without("/bar"); + var withConstraint = Diffusion.UpdateConstraints.JSONValue.With("/diffusion", "data"); + var constraint = withoutConstraint.And(withConstraint); + + var result = await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + if (result == TopicCreationResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + throw new Exception("Topic failed to be created."); + } + + string json2 = "{\"diffusion\":\"baz\"}"; + + result = await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json2), constraint, cancellationToken); + + if (result == TopicCreationResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + + session.Close(); + } + } +} diff --git a/dotnet/examples/PubSub/PublishingTopicsWithConstraint/AddAndSetTopicJSONValueWith.cs b/dotnet/examples/PubSub/PublishingTopicsWithConstraint/AddAndSetTopicJSONValueWith.cs new file mode 100644 index 00000000..f60f1cfc --- /dev/null +++ b/dotnet/examples/PubSub/PublishingTopicsWithConstraint/AddAndSetTopicJSONValueWith.cs @@ -0,0 +1,69 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Topics; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Features; + +namespace PushTechnology.ClientInterface.Examples.PubSub.PublishingTopicsWithConstraint +{ + public sealed class AddAndSetTopicJSONValueWith : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + + string json = "{\"diffusion\":\"bar\"}"; + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + var constraint = Diffusion.UpdateConstraints.JSONValue.With("/diffusion", "bar"); + var result = await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + if (result == TopicCreationResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + throw new Exception("Topic failed to be created."); + } + + string json2 = "{\"diffusion\":\"baz\"}"; + result = await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json2), constraint, cancellationToken); + + if (result == TopicCreationResult.EXISTS) + { + WriteLine("Topic already exists."); + } + else + { + throw new Exception("Topic should exist already."); + } + + session.Close(); + } + } +} diff --git a/dotnet/examples/PubSub/PublishingTopicsWithConstraint/AddAndSetTopicJSONValueWithout.cs b/dotnet/examples/PubSub/PublishingTopicsWithConstraint/AddAndSetTopicJSONValueWithout.cs new file mode 100644 index 00000000..2a39b865 --- /dev/null +++ b/dotnet/examples/PubSub/PublishingTopicsWithConstraint/AddAndSetTopicJSONValueWithout.cs @@ -0,0 +1,69 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Topics; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Features; + +namespace PushTechnology.ClientInterface.Examples.PubSub.PublishingTopicsWithConstraint +{ + public sealed class AddAndSetTopicJSONValueWithout : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + + string json = "{\"diffusion\":\"data\"}"; + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + var constraint = Diffusion.UpdateConstraints.JSONValue.Without("/bar"); + var result = await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + if (result == TopicCreationResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + throw new Exception("Topic failed to be created."); + } + + string json2 = "{\"diffusion\":\"baz\"}"; + result = await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json2), constraint, cancellationToken); + + if (result == TopicCreationResult.EXISTS) + { + WriteLine("Topic already exists."); + } + else + { + throw new Exception("Topic should exist already."); + } + + session.Close(); + } + } +} diff --git a/dotnet/examples/PubSub/PublishingTopicsWithConstraint/AddAndSetTopicNoTopic.cs b/dotnet/examples/PubSub/PublishingTopicsWithConstraint/AddAndSetTopicNoTopic.cs new file mode 100644 index 00000000..cd22b39c --- /dev/null +++ b/dotnet/examples/PubSub/PublishingTopicsWithConstraint/AddAndSetTopicNoTopic.cs @@ -0,0 +1,57 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Topics; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Features; + +namespace PushTechnology.ClientInterface.Examples.PubSub.PublishingTopicsWithConstraint +{ + public sealed class AddAndSetTopicNoTopic : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + + string json = "{\"diffusion\":\"data\"}"; + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + var constraint = Diffusion.UpdateConstraints.NoTopic; + var result = await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), constraint, cancellationToken); + + if (result == TopicCreationResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + + session.Close(); + } + } +} diff --git a/dotnet/examples/PubSub/PublishingTopicsWithConstraint/AddAndSetTopicOr.cs b/dotnet/examples/PubSub/PublishingTopicsWithConstraint/AddAndSetTopicOr.cs new file mode 100644 index 00000000..1d71677c --- /dev/null +++ b/dotnet/examples/PubSub/PublishingTopicsWithConstraint/AddAndSetTopicOr.cs @@ -0,0 +1,73 @@ +/** + * Copyright © 2025 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Topics; +using PushTechnology.ClientInterface.Client.Features; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.PubSub.PublishingTopicsWithConstraint +{ + public sealed class AddAndSetTopicOr : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + string topic = "my/topic/path"; + + var value = Diffusion.DataTypes.JSON.FromJSONString("{\"diffusion\":\"data\"}"); + var differentValue = Diffusion.DataTypes.JSON.FromJSONString("{\"diffusion\":\"data2\"}"); + + var constraint = Diffusion.UpdateConstraints.Value(value).Or(Diffusion.UpdateConstraints.NoTopic); + + // Update the topic, this works as we satisfy the no topic constraint + var result = await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, value, constraint, cancellationToken); + + if (result == TopicCreationResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + throw new Exception("Topic failed to be created."); + } + + // Update the topic again, this works as we satisfy the value constraint + result = await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, differentValue, constraint, cancellationToken); + + if (result == TopicCreationResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + hasUpdateFailed = true; + Assert.IsTrue(hasUpdateFailed); + var removeResult = await session.TopicControl.RemoveTopicsAsync(topic, cancellationToken); + WriteLine($"Or: {removeResult.ToString()}"); diff --git a/dotnet/examples/PubSub/PublishingTopicsWithConstraint/AddAndSetTopicSessionLock.cs b/dotnet/examples/PubSub/PublishingTopicsWithConstraint/AddAndSetTopicSessionLock.cs new file mode 100644 index 00000000..251f063d --- /dev/null +++ b/dotnet/examples/PubSub/PublishingTopicsWithConstraint/AddAndSetTopicSessionLock.cs @@ -0,0 +1,67 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Topics; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Features; + +namespace PushTechnology.ClientInterface.Examples.PubSub.PublishingTopicsWithConstraint +{ + public sealed class AddAndSetTopicSessionLock : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + try + { + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + + string json = "{\"diffusion\":\"data\"}"; + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + var sessionLock = await session.LockAsync(topic, cancellationToken); + var constraint = Diffusion.UpdateConstraints.Locked(sessionLock); + var result = await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), constraint, cancellationToken); + + if (result == TopicCreationResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + + session.Close(); + } + catch (Exception ex) + { + WriteLine($"An error occurred when running the example : {ex}."); + throw; + } + } + } +} diff --git a/dotnet/examples/PubSub/PublishingTopicsWithConstraint/AddAndSetTopicValue.cs b/dotnet/examples/PubSub/PublishingTopicsWithConstraint/AddAndSetTopicValue.cs new file mode 100644 index 00000000..1f68bdea --- /dev/null +++ b/dotnet/examples/PubSub/PublishingTopicsWithConstraint/AddAndSetTopicValue.cs @@ -0,0 +1,69 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Topics; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Features; + +namespace PushTechnology.ClientInterface.Examples.PubSub.PublishingTopicsWithConstraint +{ + public sealed class AddAndSetTopicValue : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + + string json = "{\"diffusion\":\"data\"}"; + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + var constraint = Diffusion.UpdateConstraints.Value(Diffusion.DataTypes.JSON.FromJSONString(json)); + var result = await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + if (result == TopicCreationResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + throw new Exception("Topic failed to be created."); + } + + string json2 = "{\"diffusion\":\"data2\"}"; + result = await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json2), constraint, cancellationToken); + + if (result == TopicCreationResult.EXISTS) + { + WriteLine("Topic already exists."); + } + else + { + throw new Exception("Topic should exist already."); + } + + session.Close(); + } + } +} diff --git a/dotnet/examples/PubSub/PublishingTopicsWithConstraint/SetTopicJSONValueWith.cs b/dotnet/examples/PubSub/PublishingTopicsWithConstraint/SetTopicJSONValueWith.cs new file mode 100644 index 00000000..98476deb --- /dev/null +++ b/dotnet/examples/PubSub/PublishingTopicsWithConstraint/SetTopicJSONValueWith.cs @@ -0,0 +1,67 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; +using PushTechnology.ClientInterface.Client.Topics; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Data.JSON; +using PushTechnology.ClientInterface.Client.Features; + +namespace PushTechnology.ClientInterface.Examples.PubSub.PublishingTopicsWithConstraint +{ + public sealed class SetTopicJSONValueWith : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + var result = await session.TopicControl.AddTopicAsync(topic, topicSpecification, cancellationToken); + + if (result == AddTopicResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + + string json = "{\"diffusion\":\"bar\"}"; + var constraint = Diffusion.UpdateConstraints.JSONValue.With("/diffusion", "bar"); + await session.TopicUpdate.SetAsync(topic, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + string json2 = "{\"diffusion\":\"baz\"}"; + await session.TopicUpdate.SetAsync(topic, Diffusion.DataTypes.JSON.FromJSONString(json2), constraint, cancellationToken); + + WriteLine("Topic value has been set."); + + session.Close(); + } + } +} diff --git a/dotnet/examples/PubSub/PublishingTopicsWithConstraint/SetTopicJSONValueWithout.cs b/dotnet/examples/PubSub/PublishingTopicsWithConstraint/SetTopicJSONValueWithout.cs new file mode 100644 index 00000000..3dad53ff --- /dev/null +++ b/dotnet/examples/PubSub/PublishingTopicsWithConstraint/SetTopicJSONValueWithout.cs @@ -0,0 +1,67 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; +using PushTechnology.ClientInterface.Client.Topics; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Data.JSON; +using PushTechnology.ClientInterface.Client.Features; + +namespace PushTechnology.ClientInterface.Examples.PubSub.PublishingTopicsWithConstraint +{ + public sealed class SetTopicJSONValueWithout : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + var result = await session.TopicControl.AddTopicAsync(topic, topicSpecification, cancellationToken); + + if (result == AddTopicResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + + string json = "{\"diffusion\": null}"; + var constraint = Diffusion.UpdateConstraints.JSONValue.Without("/bar"); + await session.TopicUpdate.SetAsync(topic, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + string json2 = "{\"diffusion\":\"baz\"}"; + await session.TopicUpdate.SetAsync(topic, Diffusion.DataTypes.JSON.FromJSONString(json2), constraint, cancellationToken); + + WriteLine("Topic value has been set."); + + session.Close(); + } + } +} diff --git a/dotnet/examples/PubSub/PublishingTopicsWithConstraint/SetTopicNoValue.cs b/dotnet/examples/PubSub/PublishingTopicsWithConstraint/SetTopicNoValue.cs new file mode 100644 index 00000000..fa8b72dd --- /dev/null +++ b/dotnet/examples/PubSub/PublishingTopicsWithConstraint/SetTopicNoValue.cs @@ -0,0 +1,64 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; +using PushTechnology.ClientInterface.Client.Topics; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Data.JSON; +using PushTechnology.ClientInterface.Client.Features; + +namespace PushTechnology.ClientInterface.Examples.PubSub.PublishingTopicsWithConstraint +{ + public sealed class SetTopicNoValue : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + var result = await session.TopicControl.AddTopicAsync(topic, topicSpecification, cancellationToken); + + if (result == AddTopicResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + + string json = "{\"diffusion\":[\"data\", \"more data\"]}"; + var constraint = Diffusion.UpdateConstraints.NoValue; + await session.TopicUpdate.SetAsync(topic, Diffusion.DataTypes.JSON.FromJSONString(json), constraint, cancellationToken); + + WriteLine("Topic value has been set."); + + session.Close(); + } + } +} diff --git a/dotnet/examples/PubSub/PublishingTopicsWithConstraint/SetTopicSessionLock.cs b/dotnet/examples/PubSub/PublishingTopicsWithConstraint/SetTopicSessionLock.cs new file mode 100644 index 00000000..1f9fa5ce --- /dev/null +++ b/dotnet/examples/PubSub/PublishingTopicsWithConstraint/SetTopicSessionLock.cs @@ -0,0 +1,73 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; +using PushTechnology.ClientInterface.Client.Topics; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Data.JSON; + +namespace PushTechnology.ClientInterface.Examples.PubSub.PublishingTopicsWithConstraint +{ + public sealed class SetTopicSessionLock : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + try + { + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + var result = await session.TopicControl.AddTopicAsync(topic, topicSpecification, cancellationToken); + + if (result == AddTopicResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + + string json = "{\"diffusion\":[\"data\", \"more data\"]}"; + + var sessionLock = await session.LockAsync("SessionLock1", cancellationToken); + var constraint = Diffusion.UpdateConstraints.Locked(sessionLock); + await session.TopicUpdate.SetAsync(topic, Diffusion.DataTypes.JSON.FromJSONString(json), constraint, cancellationToken); + + WriteLine("Topic value has been set."); + + session.Close(); + } + catch (Exception ex) + { + WriteLine($"An error occurred when running the example : {ex}."); + throw; + } + } + } +} diff --git a/dotnet/examples/PubSub/PublishingTopicsWithConstraint/SetTopicValue.cs b/dotnet/examples/PubSub/PublishingTopicsWithConstraint/SetTopicValue.cs new file mode 100644 index 00000000..ecc40829 --- /dev/null +++ b/dotnet/examples/PubSub/PublishingTopicsWithConstraint/SetTopicValue.cs @@ -0,0 +1,66 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; +using PushTechnology.ClientInterface.Client.Topics; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Data.JSON; + +namespace PushTechnology.ClientInterface.Examples.PubSub.PublishingTopicsWithConstraint +{ + public sealed class SetTopicValue : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + var result = await session.TopicControl.AddTopicAsync(topic, topicSpecification, cancellationToken); + + if (result == AddTopicResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + + string json = "{\"diffusion\":[\"data\", \"more data\"]}"; + var constraint = Diffusion.UpdateConstraints.Value(Diffusion.DataTypes.JSON.FromJSONString(json)); + await session.TopicUpdate.SetAsync(topic, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + string json2 = "{\"diffusion\":[\"data\", \"more data\", \"yet more data\"]}"; + await session.TopicUpdate.SetAsync(topic, Diffusion.DataTypes.JSON.FromJSONString(json2), constraint, cancellationToken); + + WriteLine("Topic value has been set."); + + session.Close(); + } + } +} diff --git a/dotnet/examples/PubSub/RemovingTopics/RemovingASingleTopicUsingTopicPath.cs b/dotnet/examples/PubSub/RemovingTopics/RemovingASingleTopicUsingTopicPath.cs new file mode 100644 index 00000000..b1287542 --- /dev/null +++ b/dotnet/examples/PubSub/RemovingTopics/RemovingASingleTopicUsingTopicPath.cs @@ -0,0 +1,72 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; +using PushTechnology.ClientInterface.Client.Session; +using PushTechnology.ClientInterface.Client.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Data.JSON; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.PubSub.RemovingTopics +{ + public sealed class RemovingASingleTopicUsingTopicPath: Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path/to/be/removed"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + await AddAndSetTopic(session, topic, topicSpecification, "{\"diffusion\":[\"data\", \"more data\"]}", cancellationToken); + await AddAndSetTopic(session, "my/topic/path/will/not/be/removed", topicSpecification, "{\"diffusion\":[\"no data\"]}", cancellationToken); + await AddAndSetTopic(session, "my/topic/path/will/not/be/removed/either", topicSpecification, "{\"diffusion\":[\"no data either\"]}", cancellationToken); + + await session.TopicControl.RemoveTopicsAsync(topic, cancellationToken); + + WriteLine("Topic has been removed."); + + session.Close(); + } + + private async Task AddAndSetTopic(ISession session, string topic, ITopicSpecification topicSpecification, string json, CancellationToken cancellationToken) + { + var result = await session.TopicControl.AddTopicAsync(topic, topicSpecification, cancellationToken); + + if (result == AddTopicResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + + await session.TopicUpdate.SetAsync(topic, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + } + } +} diff --git a/dotnet/examples/PubSub/RemovingTopics/RemovingMultipleTopicsUsingATopicSelector.cs b/dotnet/examples/PubSub/RemovingTopics/RemovingMultipleTopicsUsingATopicSelector.cs new file mode 100644 index 00000000..589cf662 --- /dev/null +++ b/dotnet/examples/PubSub/RemovingTopics/RemovingMultipleTopicsUsingATopicSelector.cs @@ -0,0 +1,71 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; +using PushTechnology.ClientInterface.Client.Session; +using PushTechnology.ClientInterface.Client.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Data.JSON; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.PubSub.RemovingTopics +{ + public sealed class RemovingMultipleTopicsUsingATopicSelector : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + await AddAndSetTopic(session, "my/topic/path/to/be/removed", topicSpecification, "{\"diffusion\":[\"data\", \"more data\"]}", cancellationToken); + await AddAndSetTopic(session, "my/topic/path/to/be/also/removed", topicSpecification, "{\"diffusion\":[\"data\", \"also more data\"]}", cancellationToken); + await AddAndSetTopic(session, "my/topic/path/will/not/be/removed", topicSpecification, "{\"diffusion\":[\"no data\"]}", cancellationToken); + await AddAndSetTopic(session, "my/topic/path/will/not/be/removed/either", topicSpecification, "{\"diffusion\":[\"no data either\"]}", cancellationToken); + + var result = await session.TopicControl.RemoveTopicsAsync("?my/topic/path/to/be//", cancellationToken); + + WriteLine($"{result.RemovedCount} topics have been removed."); + + session.Close(); + } + + private async Task AddAndSetTopic(ISession session, string topic, ITopicSpecification topicSpecification, string json, CancellationToken cancellationToken) + { + var result = await session.TopicControl.AddTopicAsync(topic, topicSpecification, cancellationToken); + + if (result == AddTopicResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + + await session.TopicUpdate.SetAsync(topic, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + } + } +} diff --git a/dotnet/examples/PubSub/RemovingTopics/RemovingTopicsWithAutomaticTopicRemoval.cs b/dotnet/examples/PubSub/RemovingTopics/RemovingTopicsWithAutomaticTopicRemoval.cs new file mode 100644 index 00000000..f1fed9e5 --- /dev/null +++ b/dotnet/examples/PubSub/RemovingTopics/RemovingTopicsWithAutomaticTopicRemoval.cs @@ -0,0 +1,70 @@ +/** + * Copyright © 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; +using PushTechnology.ClientInterface.Client.Session; +using PushTechnology.ClientInterface.Client.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.PubSub.RemovingTopics +{ + public sealed class RemovingTopicsWithAutomaticTopicRemoval : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + await AddTopic(session, "my/topic/path/to/be/removed/time/after", "when time after 'Tue, 4 May 2077 11:05:30 GMT'", cancellationToken); + await AddTopic(session, "my/topic/path/to/be/removed/subscriptions", "when subscriptions < 1 for 10m", cancellationToken); + await AddTopic(session, "my/topic/path/to/be/removed/local/subscriptions", "when local subscriptions < 1 for 10m", cancellationToken); + + await AddTopic(session, "my/topic/path/to/be/removed/no/updates", "when no updates for 10m", cancellationToken); + await AddTopic(session, "my/topic/path/to/be/removed/no/session", "when no session has '$Principal is \"client\"' for 1h", cancellationToken); + await AddTopic(session, "my/topic/path/to/be/removed/no/local/session", "when no local session has 'Department is \"Accounts\"' for 1h after 1d", cancellationToken); + + await AddTopic(session, "my/topic/path/to/be/removed/subcriptions/or/updates", "when subscriptions < 1 for 10m or no updates for 20m", cancellationToken); + await AddTopic(session, "my/topic/path/to/be/removed/subcriptions/and/updates", "when subscriptions < 1 for 10m and no updates for 20m", cancellationToken); + + session.Close(); + } + + private async Task AddTopic(ISession session, string topic, string removalValue, CancellationToken cancellationToken) + { + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON).WithProperty(TopicSpecificationProperty.Removal, removalValue); + + var result = await session.TopicControl.AddTopicAsync(topic, topicSpecification, cancellationToken); + + if (result == AddTopicResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + } + } +} diff --git a/dotnet/examples/PubSub/SubscribingToTopics/SubscribeToMultipleTopicsUsingTopicSelector.cs b/dotnet/examples/PubSub/SubscribingToTopics/SubscribeToMultipleTopicsUsingTopicSelector.cs new file mode 100644 index 00000000..e454adce --- /dev/null +++ b/dotnet/examples/PubSub/SubscribingToTopics/SubscribeToMultipleTopicsUsingTopicSelector.cs @@ -0,0 +1,101 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using System.Collections.Generic; +using System.Linq; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Session; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Data.JSON; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; + +namespace PushTechnology.ClientInterface.Examples.PubSub.SubscribingToTopics +{ + public sealed class SubscribeToMultipleTopicsUsingTopicSelector : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + await AddTopic(session, "my/topic/path", topicSpecification, cancellationToken); + await AddTopic(session, "my/other/topic/path", topicSpecification, cancellationToken); + + string topicSelector = "?my//"; + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topicSelector, jsonStream); + + await session.Topics.SubscribeAsync(topicSelector, cancellationToken); + + WriteLine("Creating my/additional/topic/path"); + + await AddTopic(session, "my/additional/topic/path", topicSpecification, cancellationToken); + + session.Close(); + } + + private async Task AddTopic(ISession session, string topic, ITopicSpecification topicSpecification, CancellationToken cancellationToken) + { + var result = await session.TopicControl.AddTopicAsync(topic, topicSpecification, cancellationToken); + + if (result == AddTopicResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} diff --git a/dotnet/examples/PubSub/SubscribingToTopics/SubscribeToSingleTopicUsingTopicPath.cs b/dotnet/examples/PubSub/SubscribingToTopics/SubscribeToSingleTopicUsingTopicPath.cs new file mode 100644 index 00000000..6df9247f --- /dev/null +++ b/dotnet/examples/PubSub/SubscribingToTopics/SubscribeToSingleTopicUsingTopicPath.cs @@ -0,0 +1,104 @@ +/** + * Copyright © 2023 - 2025 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using System.Collections.Generic; +using System.Linq; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Data.JSON; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; + +namespace PushTechnology.ClientInterface.Examples.PubSub.SubscribingToTopics +{ + public sealed class SubscribeToSingleTopicUsingTopicPath : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + string topicSelector = ">my/topic/path"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + var result = await session.TopicControl.AddTopicAsync(topic, topicSpecification, cancellationToken); + + if (result == AddTopicResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topicSelector, jsonStream); + + await Task.Delay(2000); + + await session.Topics.SubscribeAsync(topicSelector, cancellationToken); + + await Task.Delay(1000); + + string json = "{\"diffusion\":\"data\"}"; + await session.TopicUpdate.SetAsync(topic, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + await Task.Delay(1000); + + string json2 = "{\"diffusion\":\"more data\"}"; + await session.TopicUpdate.SetAsync(topic, Diffusion.DataTypes.JSON.FromJSONString(json2), cancellationToken); + + await Task.Delay(2000); + + session.Close(); + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} diff --git a/dotnet/examples/PubSub/SubscribingToTopics/SubscribeUsingFallbackStreams.cs b/dotnet/examples/PubSub/SubscribingToTopics/SubscribeUsingFallbackStreams.cs new file mode 100644 index 00000000..4cb18ce7 --- /dev/null +++ b/dotnet/examples/PubSub/SubscribingToTopics/SubscribeUsingFallbackStreams.cs @@ -0,0 +1,105 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using System.Collections.Generic; +using System.Linq; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Data.JSON; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; +using PushTechnology.ClientInterface.Client.Session; + +namespace PushTechnology.ClientInterface.Examples.PubSub.SubscribingToTopics +{ + public sealed class SubscribeUsingFallbackStreams : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + await AddTopic(session, "my/topic/path", topicSpecification, cancellationToken); + await AddTopic(session, "my/other/topic/path", topicSpecification, cancellationToken); + + var fallbackStream = new FallbackStream(); + session.Topics.AddFallbackStream(fallbackStream); + + string topicSelector = "?my//"; + + await session.Topics.SubscribeAsync(topicSelector, cancellationToken); + + WriteLine("Creating my/additional/topic/path"); + + await AddTopic(session, "my/additional/topic/path", topicSpecification, cancellationToken); + + WriteLine("Creating this/topic/path/will/not/be/picked/up"); + + await AddTopic(session, "this/topic/path/will/not/be/picked/up", topicSpecification, cancellationToken); + + session.Close(); + } + + private async Task AddTopic(ISession session, string topic, ITopicSpecification topicSpecification, CancellationToken cancellationToken) + { + var result = await session.TopicControl.AddTopicAsync(topic, topicSpecification, cancellationToken); + + if (result == AddTopicResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + } + + private sealed class FallbackStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} diff --git a/dotnet/examples/PubSub/SubscribingToTopics/SubscribeUsingSelectionScopes.cs b/dotnet/examples/PubSub/SubscribingToTopics/SubscribeUsingSelectionScopes.cs new file mode 100644 index 00000000..b6afa538 --- /dev/null +++ b/dotnet/examples/PubSub/SubscribingToTopics/SubscribeUsingSelectionScopes.cs @@ -0,0 +1,142 @@ +/** + * Copyright © 2025 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using System.Collections.Generic; +using System.Linq; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Session; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; + +namespace PushTechnology.ClientInterface.Examples.PubSub.SubscribingToTopics +{ + public sealed class SubscribeUsingSelectionScopes : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var topicPath = "my/topic/path"; + var myOtherPath = "my/other/path"; + + var topicControl = session.TopicControl; + var subscriptionControl = session.SubscriptionControl; + + await AddTopic(session, topicPath, TopicType.STRING, cancellationToken); + await AddTopic(session, myOtherPath, TopicType.STRING, cancellationToken); + + var componentA = session.Topics; + var componentB = session.Topics; + + var streamA = new MyStream("componentA"); + var streamB = new MyStream("componentB"); + + // Each component registers a stream for the topics they are interested in + // and subscribe to the topics with their own scope + componentA.AddStream(topicPath, streamA); + componentB.AddStream("?my//", streamB); + + await componentA.SubscribeAsync(topicPath, "scopeA", cancellationToken); + await componentB.SubscribeAsync(topicPath, "scopeB", cancellationToken); + await componentB.SubscribeAsync(myOtherPath, "scopeB", cancellationToken); + + var topicSelections = await session.SubscriptionControl.GetTopicSelectionsAsync(session.SessionId); + + foreach (var topicSelection in topicSelections) + { + WriteLine($"{topicSelection.Key} scopes"); + } + + // ComponentB unsubscribes from topicPath, scopeA is unaffected + await componentB.UnsubscribeAsync(topicPath, "scopeB", cancellationToken); + + topicSelections = await session.SubscriptionControl.GetTopicSelectionsAsync(session.SessionId); + + foreach (var topicSelection in topicSelections) + { + WriteLine($"{topicSelection.Key} scopes"); + } + + // ComponentA unsubscribes from all topics, scopeB is unaffected + // topicPath is no longer in any scopes and is unsubscribed for the session + await componentA.UnsubscribeAsync("?.*//", "scopeA", cancellationToken); + + // ComponentA removes its stream and will no longer receive updates + componentA.RemoveStream(streamA); + + // A control client unsubscribes all remaining scopes for myOtherPath which + // is now unsubscribed for the session + await session.SubscriptionControl.UnsubscribeAllScopesAsync(session.SessionId, myOtherPath); + + componentB.RemoveStream(streamB); + } + + private async Task AddTopic(ISession session, string topic, TopicType type, CancellationToken cancellationToken) + { + var result = await session.TopicControl.AddTopicAsync(topic, type, cancellationToken); + + if (result == AddTopicResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + } + + private sealed class MyStream : IValueStream + { + private string scopeName; + + public MyStream(string scopeName) => this.scopeName = scopeName; + + public void OnClose() { + WriteLine($"{scopeName}: stream closed."); + } + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"{scopeName}: Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"{scopeName}: Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, string oldValue, string newValue) + { + WriteLine($"{scopeName}: {topicPath} changed from {(oldValue ?? "NULL")} to {newValue}."); + } + } + } +} diff --git a/dotnet/examples/PubSub/SubscribingToTopics/SubscribeWithCrossCompatibleValueStream.cs b/dotnet/examples/PubSub/SubscribingToTopics/SubscribeWithCrossCompatibleValueStream.cs new file mode 100644 index 00000000..48d0a1f1 --- /dev/null +++ b/dotnet/examples/PubSub/SubscribingToTopics/SubscribeWithCrossCompatibleValueStream.cs @@ -0,0 +1,115 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using System.Collections.Generic; +using System.Linq; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Data.JSON; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; + +namespace PushTechnology.ClientInterface.Examples.PubSub.SubscribingToTopics +{ + public sealed class SubscribeWithCrossCompatibleValueStream : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/int/topic/path"; + string topicSelector = ">my/int/topic/path"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.INT64); + var result = await session.TopicControl.AddTopicAsync(topic, topicSpecification, cancellationToken); + + if (result == AddTopicResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topicSelector, jsonStream); + + var stringStream = new StringStream(); + session.Topics.AddStream(topicSelector, stringStream); + + await session.Topics.SubscribeAsync(topicSelector, cancellationToken); + + session.Close(); + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"JSON stream subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"JSON stream unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"JSON stream {topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + + private sealed class StringStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"String stream subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"String stream unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, string oldValue, string newValue) + { + WriteLine($"String stream {topicPath} changed from {oldValue ?? "NULL"} to {newValue}."); + } + } + } +} diff --git a/dotnet/examples/Security/ChangePrincipal.cs b/dotnet/examples/Security/ChangePrincipal.cs new file mode 100644 index 00000000..3251590c --- /dev/null +++ b/dotnet/examples/Security/ChangePrincipal.cs @@ -0,0 +1,50 @@ +/** + * Copyright © 2023 -2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.Security +{ + public sealed class ChangePrincipal : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + bool result = await session.Security.ChangePrincipalAsync("control", Diffusion.Credentials.Password("password"), cancellationToken); + + if (result) + { + WriteLine("Principal has been changed to control."); + } + else + { + throw new Exception("Authentication failed."); + } + + session.Close(); + } + } +} diff --git a/dotnet/examples/Security/GetGlobalPermissions.cs b/dotnet/examples/Security/GetGlobalPermissions.cs new file mode 100644 index 00000000..1f3de6af --- /dev/null +++ b/dotnet/examples/Security/GetGlobalPermissions.cs @@ -0,0 +1,49 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.Security +{ + public sealed class GetGlobalPermissions : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + // Get the permissions assigned to the session. + var globalPermissions = await session.Security.GetGlobalPermissionsAsync(cancellationToken); + + WriteLine("Permissions for the Administrator session are:"); + + foreach (var permission in globalPermissions) + { + WriteLine($"{permission}"); + } + + session.Close(); + } + } +} diff --git a/dotnet/examples/Security/GetPathPermissions.cs b/dotnet/examples/Security/GetPathPermissions.cs new file mode 100644 index 00000000..5cc0216a --- /dev/null +++ b/dotnet/examples/Security/GetPathPermissions.cs @@ -0,0 +1,49 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.Security +{ + public sealed class GetPathPermissions : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + // Get the path permissions assigned to the session on a specific path. + var pathPermissions = await session.Security.GetPermissionsForPathAsync(".*//", cancellationToken); + + WriteLine("Path permissions for the Administrator session on '.*//' are:"); + + foreach (var permission in pathPermissions) + { + WriteLine($"{permission}"); + } + + session.Close(); + } + } +} diff --git a/dotnet/examples/Security/Reauthenticate.cs b/dotnet/examples/Security/Reauthenticate.cs new file mode 100644 index 00000000..be5f01fe --- /dev/null +++ b/dotnet/examples/Security/Reauthenticate.cs @@ -0,0 +1,51 @@ +/** + * Copyright © 2025 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using System.Collections.Generic; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.Security +{ + public sealed class Reauthenticate: Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + bool result = await session.Security.ReauthenticateAsync("control", Diffusion.Credentials.Password("password"), new Dictionary(), cancellationToken); + + if (result) + { + WriteLine("Session reauthenticated for principal control."); + } + else + { + throw new Exception("Authentication failed."); + } + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/Metrics/GetMetricsConsole.cs b/dotnet/examples/ServerConfiguration/Metrics/GetMetricsConsole.cs new file mode 100644 index 00000000..f2fd7ed7 --- /dev/null +++ b/dotnet/examples/ServerConfiguration/Metrics/GetMetricsConsole.cs @@ -0,0 +1,77 @@ +/** + * Copyright © 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using System.Collections.Generic; +using System.Linq; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.Metrics +{ + public sealed class GetMetricsConsole : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var requiredMetrics = new HashSet + { + "diffusion_server_time_zone", + "diffusion_server_user_directory", + "diffusion_server_license_expiry_date", + "diffusion_server_uptime_millis", + "diffusion_license", + "diffusion_server_free_memory_bytes", + "diffusion_server_max_memory_bytes", + "diffusion_server_total_memory_bytes", + "diffusion_release", + "diffusion_server_start_date", + "diffusion_server_start_date_millis", + "diffusion_server_used_swap_space_size_bytes", + "diffusion_server_used_physical_memory_size_bytes", + "diffusion_server_number_of_topics", + "diffusion_server_session_locks", + "diffusion_server_user_name", + "diffusion_server_uptime", + "diffusion_multiplexer_manager_number_of_multiplexers" + }; + + var result = await session.Metrics.MetricsRequest().Filter(requiredMetrics).FetchAsync(); + + string serverName = result.ServerNames.First(); + + var collections = result.GetMetrics(serverName); + + foreach (var collection in collections) + { + foreach (var sample in collection.Samples) + { + WriteLine($"{collection.Name}: {sample.Name} {collection.Unit} ({collection.Type})"); + } + } + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/Metrics/GetOutboundBytes.cs b/dotnet/examples/ServerConfiguration/Metrics/GetOutboundBytes.cs new file mode 100644 index 00000000..dcc3e906 --- /dev/null +++ b/dotnet/examples/ServerConfiguration/Metrics/GetOutboundBytes.cs @@ -0,0 +1,51 @@ +/** + * Copyright © 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using System.Collections.Generic; +using System.Linq; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.Metrics +{ + public sealed class GetOutboundBytes : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var result = await session.Metrics.MetricsRequest().CurrentServer.Filter(new HashSet { "diffusion_network_outbound_bytes" }).FetchAsync(); + + string serverName = result.ServerNames.First(); + + var collection = result.GetMetrics(serverName); + + var sample = collection[0].Samples.First(); + + WriteLine($"{collection[0].Name}: {sample.Name} {collection[0].Unit} ({collection[0].Type})"); + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/Metrics/MetricAlerts/ListMetricAlerts.cs b/dotnet/examples/ServerConfiguration/Metrics/MetricAlerts/ListMetricAlerts.cs new file mode 100644 index 00000000..cbb21525 --- /dev/null +++ b/dotnet/examples/ServerConfiguration/Metrics/MetricAlerts/ListMetricAlerts.cs @@ -0,0 +1,57 @@ +/** + * Copyright © 2025 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.Metrics.MetricAlerts +{ + public sealed class ListMetricAlerts : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + for (int i = 0; i < 5; i++) + { + string alertName = "alert" + i; + string topic = "my/topic/path/" + i; + await session.Metrics.SetMetricAlertAsync(alertName, "select os_system_cpu_load into topic " + topic); + } + + WriteLine("Alerts created"); + + await Task.Delay(3000); + + var alerts = await session.Metrics.ListMetricAlertsAsync(); + + foreach (var alert in alerts){ + WriteLine(alert.Name); + } + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/Metrics/MetricAlerts/RemoveMetricAlert.cs b/dotnet/examples/ServerConfiguration/Metrics/MetricAlerts/RemoveMetricAlert.cs new file mode 100644 index 00000000..ed955dcd --- /dev/null +++ b/dotnet/examples/ServerConfiguration/Metrics/MetricAlerts/RemoveMetricAlert.cs @@ -0,0 +1,48 @@ +/** + * Copyright © 2025 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System.Threading; +using System.Threading.Tasks; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.Metrics.MetricAlerts +{ + public sealed class RemoveMetricAlert : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + await session.Metrics.SetMetricAlertAsync("myAlert", "select os_system_cpu_load into topic my/topic/path"); + + WriteLine("Alert created"); + + await Task.Delay(3000); + + await session.Metrics.RemoveMetricAlertAsync("myAlert"); + + WriteLine($"Alert removed"); + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/Metrics/MetricAlerts/SetMetricAlert.cs b/dotnet/examples/ServerConfiguration/Metrics/MetricAlerts/SetMetricAlert.cs new file mode 100644 index 00000000..8273074a --- /dev/null +++ b/dotnet/examples/ServerConfiguration/Metrics/MetricAlerts/SetMetricAlert.cs @@ -0,0 +1,52 @@ +/** + * Copyright © 2025 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Data.JSON; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.Metrics.MetricAlerts +{ + public sealed class SetMetricAlert : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + await session.Metrics.SetMetricAlertAsync("myAlert", "select os_system_cpu_load into topic my/topic/path"); + + WriteLine("Alert created"); + + await Task.Delay(5000); + + var fetchResult = await session.Topics.FetchRequest.WithValues().FetchAsync("my/topic/path", cancellationToken); + + string topicValue = fetchResult.Results.First().Value.ToJSONString(); + + WriteLine($"Topic value: {topicValue}"); + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/Metrics/SessionMetricCollector/ListSessionMetricCollectors.cs b/dotnet/examples/ServerConfiguration/Metrics/SessionMetricCollector/ListSessionMetricCollectors.cs new file mode 100644 index 00000000..ae53ac36 --- /dev/null +++ b/dotnet/examples/ServerConfiguration/Metrics/SessionMetricCollector/ListSessionMetricCollectors.cs @@ -0,0 +1,76 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using static System.Console; +using System.Linq; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features.Metrics; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.Metrics.SessionMetricCollector +{ + public sealed class ListSessionMetricCollectors : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string sessionFilter = "$Principal is 'control'"; + + var builder = Diffusion.NewSessionMetricCollectorBuilder(); + builder = (ISessionMetricCollectorBuilder)builder.ExportsToPrometheus(false); + builder = builder.GroupByProperties(new List { "$Location" }); + builder = builder.RemoveMetricsWithNoMatches(true); + builder = (ISessionMetricCollectorBuilder)builder.MaximumGroups(10); + var collector = builder.Create("Session Metric Collector 1", sessionFilter); + + await session.Metrics.PutSessionMetricCollectorAsync(collector, cancellationToken); + + builder = Diffusion.NewSessionMetricCollectorBuilder(); + builder = (ISessionMetricCollectorBuilder)builder.ExportsToPrometheus(true); + builder = builder.GroupByProperties(new List { "$Location" }); + builder = builder.RemoveMetricsWithNoMatches(true); + builder = (ISessionMetricCollectorBuilder)builder.MaximumGroups(250); + collector = builder.Create("Session Metric Collector 2", sessionFilter); + + await session.Metrics.PutSessionMetricCollectorAsync(collector, cancellationToken); + + var listSessionMetricCollectors = await session.Metrics.ListSessionMetricCollectorsAsync(cancellationToken); + + foreach (var sessionMetricCollector in listSessionMetricCollectors) + { + WriteLine($"{sessionMetricCollector.Name}: " + + $"{sessionMetricCollector.SessionFilter} " + + $"({sessionMetricCollector.MaximumGroups}, " + + $"{GetAnswer(sessionMetricCollector.ExportsToPrometheus)}, " + + $"{GetAnswer(sessionMetricCollector.RemovesMetricsWithNoMatches)}, " + + $"{string.Join(",", sessionMetricCollector.GroupByProperties)})"); + } + + session.Close(); + } + + private string GetAnswer(bool result) => result ? "Yes" : "No"; + } +} diff --git a/dotnet/examples/ServerConfiguration/Metrics/SessionMetricCollector/PutSessionMetricCollector.cs b/dotnet/examples/ServerConfiguration/Metrics/SessionMetricCollector/PutSessionMetricCollector.cs new file mode 100644 index 00000000..1820bc89 --- /dev/null +++ b/dotnet/examples/ServerConfiguration/Metrics/SessionMetricCollector/PutSessionMetricCollector.cs @@ -0,0 +1,54 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features.Metrics; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.Metrics.SessionMetricCollector +{ + public sealed class PutSessionMetricCollector : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string sessionFilter = "$Principal is 'control'"; + + var builder = Diffusion.NewSessionMetricCollectorBuilder(); + builder = (ISessionMetricCollectorBuilder)builder.ExportsToPrometheus(false); + builder = builder.GroupByProperties(new List { "$Location" }); + builder = builder.RemoveMetricsWithNoMatches(true); + builder = (ISessionMetricCollectorBuilder)builder.MaximumGroups(10); + var collector = builder.Create("Session Metric Collector 1", sessionFilter); + + await session.Metrics.PutSessionMetricCollectorAsync(collector, cancellationToken); + + WriteLine($"Session metric collector '{collector.Name}' added."); + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/Metrics/SessionMetricCollector/RemoveSessionMetricCollector.cs b/dotnet/examples/ServerConfiguration/Metrics/SessionMetricCollector/RemoveSessionMetricCollector.cs new file mode 100644 index 00000000..39bf23d1 --- /dev/null +++ b/dotnet/examples/ServerConfiguration/Metrics/SessionMetricCollector/RemoveSessionMetricCollector.cs @@ -0,0 +1,57 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features.Metrics; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.Metrics.SessionMetricCollector +{ + public sealed class RemoveSessionMetricCollector : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + ISessionMetricCollector collector = null; + string sessionFilter = "$Principal is 'control'"; + + var builder = Diffusion.NewSessionMetricCollectorBuilder(); + builder = (ISessionMetricCollectorBuilder)builder.ExportsToPrometheus(false); + builder = builder.GroupByProperties(new List { "$Location" }); + builder = builder.RemoveMetricsWithNoMatches(true); + builder = (ISessionMetricCollectorBuilder)builder.MaximumGroups(10); + collector = builder.Create("Session Metric Collector 1", sessionFilter); + + await session.Metrics.PutSessionMetricCollectorAsync(collector, cancellationToken); + + await session.Metrics.RemoveSessionMetricCollectorAsync(collector.Name, cancellationToken); + + WriteLine($"{collector.Name} has been removed."); + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/Metrics/TopicMetricCollector/ListTopicMetricCollectors.cs b/dotnet/examples/ServerConfiguration/Metrics/TopicMetricCollector/ListTopicMetricCollectors.cs new file mode 100644 index 00000000..9f166921 --- /dev/null +++ b/dotnet/examples/ServerConfiguration/Metrics/TopicMetricCollector/ListTopicMetricCollectors.cs @@ -0,0 +1,79 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using static System.Console; +using System.Linq; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features.Metrics; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.Metrics.TopicMetricCollector +{ + public sealed class ListTopicMetricCollectors : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + ITopicMetricCollector collector = null; + string topicSelector = "?my/topic//"; + + var builder = Diffusion.NewTopicMetricCollectorBuilder(); + builder = (ITopicMetricCollectorBuilder)builder.ExportsToPrometheus(false); + builder = builder.GroupByTopicType(true); + builder = builder.GroupByTopicView(true); + builder = builder.GroupByPathPrefixParts(15); + builder = (ITopicMetricCollectorBuilder)builder.MaximumGroups(10); + collector = builder.Create("Topic Metric Collector 1", topicSelector); + + await session.Metrics.PutTopicMetricCollectorAsync(collector, cancellationToken); + + builder = Diffusion.NewTopicMetricCollectorBuilder(); + builder = (ITopicMetricCollectorBuilder)builder.ExportsToPrometheus(true); + builder = builder.GroupByTopicType(false); + builder = builder.GroupByTopicView(true); + builder = builder.GroupByPathPrefixParts(15); + builder = (ITopicMetricCollectorBuilder)builder.MaximumGroups(250); + collector = builder.Create("Topic Metric Collector 2", topicSelector); + + await session.Metrics.PutTopicMetricCollectorAsync(collector, cancellationToken); + + var listTopicMetricCollectors = await session.Metrics.ListTopicMetricCollectorsAsync(cancellationToken); + + foreach (var topicMetricCollector in listTopicMetricCollectors) + { + WriteLine($"{topicMetricCollector.Name}: " + + $"{topicMetricCollector.TopicSelector} " + + $"({topicMetricCollector.MaximumGroups}, " + + $"{GetAnswer(topicMetricCollector.ExportsToPrometheus)}, " + + $"{GetAnswer(topicMetricCollector.GroupsByTopicType)}, " + + $"{GetAnswer(topicMetricCollector.GroupsByTopicView)}, " + + $"{topicMetricCollector.GroupByPathPrefixParts})"); + } + + session.Close(); + } + + private string GetAnswer(bool result) => result ? "Yes" : "No"; + } +} diff --git a/dotnet/examples/ServerConfiguration/Metrics/TopicMetricCollector/PutTopicMetricCollector.cs b/dotnet/examples/ServerConfiguration/Metrics/TopicMetricCollector/PutTopicMetricCollector.cs new file mode 100644 index 00000000..b451909c --- /dev/null +++ b/dotnet/examples/ServerConfiguration/Metrics/TopicMetricCollector/PutTopicMetricCollector.cs @@ -0,0 +1,54 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features.Metrics; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.Metrics.TopicMetricCollector +{ + public sealed class PutTopicMetricCollector : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topicSelector = "?my/topic//"; + + var builder = Diffusion.NewTopicMetricCollectorBuilder(); + builder = (ITopicMetricCollectorBuilder)builder.ExportsToPrometheus(false); + builder = builder.GroupByTopicType(true); + builder = builder.GroupByTopicView(true); + builder = builder.GroupByPathPrefixParts(15); + builder = (ITopicMetricCollectorBuilder)builder.MaximumGroups(10); + var collector = builder.Create("Topic Metric Collector 1", topicSelector); + + await session.Metrics.PutTopicMetricCollectorAsync(collector, cancellationToken); + + WriteLine($"Topic metric collector '{collector.Name}' added."); + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/Metrics/TopicMetricCollector/RemoveTopicMetricCollector.cs b/dotnet/examples/ServerConfiguration/Metrics/TopicMetricCollector/RemoveTopicMetricCollector.cs new file mode 100644 index 00000000..b02d4d3d --- /dev/null +++ b/dotnet/examples/ServerConfiguration/Metrics/TopicMetricCollector/RemoveTopicMetricCollector.cs @@ -0,0 +1,57 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features.Metrics; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.Metrics.TopicMetricCollector +{ + public sealed class RemoveTopicMetricCollector : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + ITopicMetricCollector collector = null; + string topicSelector = "?my/topic//"; + + var builder = Diffusion.NewTopicMetricCollectorBuilder(); + builder = (ITopicMetricCollectorBuilder)builder.ExportsToPrometheus(false); + builder = builder.GroupByTopicType(true); + builder = builder.GroupByTopicView(true); + builder = builder.GroupByPathPrefixParts(15); + builder = (ITopicMetricCollectorBuilder)builder.MaximumGroups(10); + collector = builder.Create("Topic Metric Collector 1", topicSelector); + + await session.Metrics.PutTopicMetricCollectorAsync(collector, cancellationToken); + + await session.Metrics.RemoveTopicMetricCollectorAsync(collector.Name, cancellationToken); + + WriteLine($"{collector.Name} has been removed."); + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/RemoteServers/CheckRemoteServers.cs b/dotnet/examples/ServerConfiguration/RemoteServers/CheckRemoteServers.cs new file mode 100644 index 00000000..02c25839 --- /dev/null +++ b/dotnet/examples/ServerConfiguration/RemoteServers/CheckRemoteServers.cs @@ -0,0 +1,82 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Features.Control.Clients; +using System.Collections.Generic; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.RemoteServers +{ + public sealed class CheckRemoteServers : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + IRemoteServer server = null, server2 = null; + + var builder = (ISecondaryInitiatorBuilder)Diffusion.NewRemoteServerBuilder(RemoteServerType.SECONDARY_INITIATOR); + + var initiator = builder + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .ConnectionOptions(new Dictionary() + { + { RemoteServerConnectionOption.RECONNECTION_TIMEOUT, "120000" }, + { RemoteServerConnectionOption.CONNECTION_TIMEOUT, "15000" }, + { RemoteServerConnectionOption.MAXIMUM_QUEUE_SIZE, "1000" } + }) + .Build("Remote Server 1", "ws://new.server.url.com"); + + server = await session.RemoteServers.CreateRemoteServerAsync(initiator, cancellationToken); + + builder = builder.Reset(); + + initiator = builder + .Principal("control") + .Credentials(Diffusion.Credentials.Password("password")) + .ConnectionOptions(new Dictionary() + { + { RemoteServerConnectionOption.RECONNECTION_TIMEOUT, "60000" }, + { RemoteServerConnectionOption.CONNECTION_TIMEOUT, "5000" }, + { RemoteServerConnectionOption.MAXIMUM_QUEUE_SIZE, "10000" } + }) + .Build("Remote Server 2", "ws://another.server.url.com"); + + server2 = await session.RemoteServers.CreateRemoteServerAsync(initiator, cancellationToken); + + var listServers = await session.RemoteServers.ListRemoteServersAsync(cancellationToken); + + foreach (var remoteServer in listServers) + { + var result = await session.RemoteServers.CheckRemoteServerAsync(remoteServer.Name, cancellationToken); + + WriteLine($"{remoteServer.Name} ({remoteServer.ServerUrl}): {result.ConnectionState} ({result.FailureMessage})"); + } + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/RemoteServers/CreatePrimaryInitiatorRemoteServer.cs b/dotnet/examples/ServerConfiguration/RemoteServers/CreatePrimaryInitiatorRemoteServer.cs new file mode 100644 index 00000000..bd7be57c --- /dev/null +++ b/dotnet/examples/ServerConfiguration/RemoteServers/CreatePrimaryInitiatorRemoteServer.cs @@ -0,0 +1,53 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Features.Control.Clients; +using System.Collections.Generic; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.RemoteServers +{ + public sealed class CreatePrimaryInitiatorRemoteServer : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + IRemoteServer server = null; + + var builder = (IPrimaryInitiatorBuilder)Diffusion.NewRemoteServerBuilder(RemoteServerType.PRIMARY_INITIATOR); + + var initiator = builder + .RetryDelay(2500) + .Build("Remote Server 1", new List { "ws://new.server.url.com:8080", "ws://new.server.url.com:8081", "ws://new.server.url.com:8082" }, "High Volume Connector"); + + server = await session.RemoteServers.CreateRemoteServerAsync(initiator, cancellationToken); + + WriteLine($"Remote server '{server.Name}' was created."); + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/RemoteServers/CreateSecondaryAcceptorRemoteServer.cs b/dotnet/examples/ServerConfiguration/RemoteServers/CreateSecondaryAcceptorRemoteServer.cs new file mode 100644 index 00000000..099db94b --- /dev/null +++ b/dotnet/examples/ServerConfiguration/RemoteServers/CreateSecondaryAcceptorRemoteServer.cs @@ -0,0 +1,59 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Features.Control.Clients; +using System.Collections.Generic; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.RemoteServers +{ + public sealed class CreateSecondaryAcceptorRemoteServer : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + IRemoteServer server = null; + + var builder = (ISecondaryAcceptorBuilder)Diffusion.NewRemoteServerBuilder(RemoteServerType.SECONDARY_ACCEPTOR); + + var initiator = builder + .ConnectionOptions(new Dictionary() + { + { RemoteServerConnectionOption.WRITE_TIMEOUT, "2000" }, + { RemoteServerConnectionOption.CONNECTION_TIMEOUT, "15000" }, + { RemoteServerConnectionOption.MAXIMUM_QUEUE_SIZE, "1000" } + }) + .MissingTopicNotificationFilter("?abc") + .Build("Remote Server 1", "ws://new.server.url.com"); + + server = await session.RemoteServers.CreateRemoteServerAsync(initiator, cancellationToken); + + WriteLine($"Remote server '{server.Name}' was created."); + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/RemoteServers/CreateSecondaryInitiatorRemoteServer.cs b/dotnet/examples/ServerConfiguration/RemoteServers/CreateSecondaryInitiatorRemoteServer.cs new file mode 100644 index 00000000..bff6778e --- /dev/null +++ b/dotnet/examples/ServerConfiguration/RemoteServers/CreateSecondaryInitiatorRemoteServer.cs @@ -0,0 +1,61 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Features.Control.Clients; +using System.Collections.Generic; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.RemoteServers +{ + public sealed class CreateSecondaryInitiatorRemoteServer : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + IRemoteServer server = null; + + var builder = (ISecondaryInitiatorBuilder)Diffusion.NewRemoteServerBuilder(RemoteServerType.SECONDARY_INITIATOR); + + var initiator = builder + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .ConnectionOptions(new Dictionary() + { + { RemoteServerConnectionOption.RECONNECTION_TIMEOUT, "120000" }, + { RemoteServerConnectionOption.CONNECTION_TIMEOUT, "15000" }, + { RemoteServerConnectionOption.MAXIMUM_QUEUE_SIZE, "1000" } + }) + .MissingTopicNotificationFilter("?abc") + .Build("Remote Server 1", "ws://new.server.url.com"); + + server = await session.RemoteServers.CreateRemoteServerAsync(initiator, cancellationToken); + + WriteLine($"Remote server '{server.Name}' was created."); + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/RemoteServers/ListRemoteServers.cs b/dotnet/examples/ServerConfiguration/RemoteServers/ListRemoteServers.cs new file mode 100644 index 00000000..65f87567 --- /dev/null +++ b/dotnet/examples/ServerConfiguration/RemoteServers/ListRemoteServers.cs @@ -0,0 +1,81 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using System.Linq; +using System.Collections.Generic; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Features.Control.Clients; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.RemoteServers +{ + public sealed class ListRemoteServers : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + IRemoteServer server = null, server2 = null; + + var builder = (ISecondaryInitiatorBuilder)Diffusion.NewRemoteServerBuilder(RemoteServerType.SECONDARY_INITIATOR); + + var initiator = builder + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .ConnectionOptions(new Dictionary() + { + { RemoteServerConnectionOption.RECONNECTION_TIMEOUT, "120000" }, + { RemoteServerConnectionOption.CONNECTION_TIMEOUT, "15000" }, + { RemoteServerConnectionOption.MAXIMUM_QUEUE_SIZE, "1000" } + }) + .Build("Remote Server 1", "ws://new.server.url.com"); + + server = await session.RemoteServers.CreateRemoteServerAsync(initiator, cancellationToken); + + builder = builder.Reset(); + + initiator = builder + .Principal("control") + .Credentials(Diffusion.Credentials.Password("password")) + .ConnectionOptions(new Dictionary() + { + { RemoteServerConnectionOption.RECONNECTION_TIMEOUT, "6000" }, + { RemoteServerConnectionOption.CONNECTION_TIMEOUT, "5000" }, + { RemoteServerConnectionOption.MAXIMUM_QUEUE_SIZE, "10000" } + }) + .Build("Remote Server 2", "ws://another.server.url.com"); + + server2 = await session.RemoteServers.CreateRemoteServerAsync(initiator, cancellationToken); + + var listServers = await session.RemoteServers.ListRemoteServersAsync(cancellationToken); + + foreach (var remoteServer in listServers) + { + WriteLine($"{remoteServer.Name} ({remoteServer.ServerUrl})"); + } + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/RemoteServers/RemoveRemoteServers.cs b/dotnet/examples/ServerConfiguration/RemoteServers/RemoveRemoteServers.cs new file mode 100644 index 00000000..c75c0b1a --- /dev/null +++ b/dotnet/examples/ServerConfiguration/RemoteServers/RemoveRemoteServers.cs @@ -0,0 +1,62 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Features.Control.Clients; +using System.Collections.Generic; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.RemoteServers +{ + public sealed class RemoveRemoteServers : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + IRemoteServer server = null; + + var builder = (ISecondaryInitiatorBuilder)Diffusion.NewRemoteServerBuilder(RemoteServerType.SECONDARY_INITIATOR); + + var initiator = builder + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .ConnectionOptions(new Dictionary() + { + { RemoteServerConnectionOption.RECONNECTION_TIMEOUT, "120000" }, + { RemoteServerConnectionOption.CONNECTION_TIMEOUT, "15000" }, + { RemoteServerConnectionOption.MAXIMUM_QUEUE_SIZE, "1000" } + }) + .Build("Remote Server 1", "ws://new.server.url.com"); + + server = await session.RemoteServers.CreateRemoteServerAsync(initiator, cancellationToken); + + await session.RemoteServers.RemoveRemoteServerAsync(server.Name, cancellationToken); + + WriteLine($"Remote Server 1 has been removed."); + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/SecurityControl/DefineRolesHierarchy.cs b/dotnet/examples/ServerConfiguration/SecurityControl/DefineRolesHierarchy.cs new file mode 100644 index 00000000..f2a8d2ba --- /dev/null +++ b/dotnet/examples/ServerConfiguration/SecurityControl/DefineRolesHierarchy.cs @@ -0,0 +1,47 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.SecurityControl +{ + public sealed class DefineRolesHierarchy : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + WriteLine($"OPERATOR now includes CLIENT and CLIENT_CONTROL roles."); + + string script = session.SecurityControl.Script.SetRoleIncludes("OPERATOR", new[] { "CLIENT", "CLIENT_CONTROL" }).ToScript(); + + WriteLine($"{script}"); + + await session.SecurityControl.UpdateStoreAsync(script, cancellationToken); + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/SecurityControl/DeisolatePath.cs b/dotnet/examples/ServerConfiguration/SecurityControl/DeisolatePath.cs new file mode 100644 index 00000000..dc9aea7e --- /dev/null +++ b/dotnet/examples/ServerConfiguration/SecurityControl/DeisolatePath.cs @@ -0,0 +1,55 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.SecurityControl +{ + public sealed class DeisolatePath : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + WriteLine($"Isolating my/topic/path permissions from parent and default path permissions."); + + string script = session.SecurityControl.Script.IsolatePath("my/topic/path").ToScript(); + + WriteLine($"{script}"); + + await session.SecurityControl.UpdateStoreAsync(script, cancellationToken); + + script = session.SecurityControl.Script.DeisolatePath("my/topic/path").ToScript(); + + WriteLine($"Removing my/topic/path permission isolation."); + + WriteLine($"{script}"); + + await session.SecurityControl.UpdateStoreAsync(script, cancellationToken); + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/SecurityControl/IsolatePath.cs b/dotnet/examples/ServerConfiguration/SecurityControl/IsolatePath.cs new file mode 100644 index 00000000..9bbaaa6d --- /dev/null +++ b/dotnet/examples/ServerConfiguration/SecurityControl/IsolatePath.cs @@ -0,0 +1,47 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.SecurityControl +{ + public sealed class IsolatePath : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + WriteLine($"Isolating my/topic/path permissions from parent and default path permissions."); + + string script = session.SecurityControl.Script.IsolatePath("my/topic/path").ToScript(); + + WriteLine($"{script}"); + + await session.SecurityControl.UpdateStoreAsync(script, cancellationToken); + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/SecurityControl/RemovePathPermissions.cs b/dotnet/examples/ServerConfiguration/SecurityControl/RemovePathPermissions.cs new file mode 100644 index 00000000..69910073 --- /dev/null +++ b/dotnet/examples/ServerConfiguration/SecurityControl/RemovePathPermissions.cs @@ -0,0 +1,58 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Types; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.SecurityControl +{ + public sealed class RemovePathPermissions : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + WriteLine($"Allowing Role CLIENT to update and modify my/topic/path."); + + var permissions = new[] { PathPermission.UPDATE_TOPIC, PathPermission.MODIFY_TOPIC }; + + string script = session.SecurityControl.Script.SetPathPermissions("CLIENT", "my/topic/path", permissions).ToScript(); + + WriteLine($"{script}"); + + await session.SecurityControl.UpdateStoreAsync(script, cancellationToken); + + WriteLine($"Removing path permissions for Role CLIENT at my/topic/path."); + + script = session.SecurityControl.Script.RemovePathPermissions("CLIENT", "my/topic/path").ToScript(); + + WriteLine($"{script}"); + + await session.SecurityControl.UpdateStoreAsync(script, cancellationToken); + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/SecurityControl/RestrictRoleEditPermissions.cs b/dotnet/examples/ServerConfiguration/SecurityControl/RestrictRoleEditPermissions.cs new file mode 100644 index 00000000..c38a20e4 --- /dev/null +++ b/dotnet/examples/ServerConfiguration/SecurityControl/RestrictRoleEditPermissions.cs @@ -0,0 +1,48 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.SecurityControl +{ + public sealed class RestrictRoleEditPermissions : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + WriteLine($"EXAMPLE role has been locked by admin principal."); + + string script = session.SecurityControl.Script.SetRoleLockedByPrincipal("EXAMPLE", "admin").ToScript(); + + WriteLine($"{script}"); + + await session.SecurityControl.UpdateStoreAsync(script, cancellationToken); + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/SecurityControl/SetDefaultPathPermissions.cs b/dotnet/examples/ServerConfiguration/SecurityControl/SetDefaultPathPermissions.cs new file mode 100644 index 00000000..6a715172 --- /dev/null +++ b/dotnet/examples/ServerConfiguration/SecurityControl/SetDefaultPathPermissions.cs @@ -0,0 +1,60 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Types; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.SecurityControl +{ + public sealed class SetDefaultPathPermissions : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var defaultPathPermissions = new List(); + + var securityConfig = await session.SecurityControl.GetSecurityAsync(cancellationToken); + + var clientRole = securityConfig.Roles.Where(x => x.Name == "CLIENT").FirstOrDefault(); + defaultPathPermissions = clientRole.DefaultPathPermissions.ToList(); + + WriteLine($"Adding the following permissions to the default path permisions of Role CLIENT: MODIFY_TOPIC and UPDATE_TOPIC."); + + var permissions = new List { PathPermission.UPDATE_TOPIC, PathPermission.MODIFY_TOPIC }; + permissions.AddRange(defaultPathPermissions); + + string script = session.SecurityControl.Script.SetDefaultPathPermissions("CLIENT", permissions).ToScript(); + + WriteLine($"{script}"); + + await session.SecurityControl.UpdateStoreAsync(script, cancellationToken); + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/SecurityControl/SetDefaultRolesForAnonymousSessions.cs b/dotnet/examples/ServerConfiguration/SecurityControl/SetDefaultRolesForAnonymousSessions.cs new file mode 100644 index 00000000..faebf4c8 --- /dev/null +++ b/dotnet/examples/ServerConfiguration/SecurityControl/SetDefaultRolesForAnonymousSessions.cs @@ -0,0 +1,47 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.SecurityControl +{ + public sealed class SetDefaultRolesForAnonymousSessions : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + WriteLine($"All anonymous sessions now have AUTHENTICATION_HANDLER privileges."); + + string script = session.SecurityControl.Script.SetRolesForAnonymousSessions(new[] { "AUTHENTICATION_HANDLER" }).ToScript(); + + WriteLine($"{script}"); + + await session.SecurityControl.UpdateStoreAsync(script, cancellationToken); + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/SecurityControl/SetDefaultRolesForNamedSessions.cs b/dotnet/examples/ServerConfiguration/SecurityControl/SetDefaultRolesForNamedSessions.cs new file mode 100644 index 00000000..6be22513 --- /dev/null +++ b/dotnet/examples/ServerConfiguration/SecurityControl/SetDefaultRolesForNamedSessions.cs @@ -0,0 +1,47 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.SecurityControl +{ + public sealed class SetDefaultRolesForNamedSessions : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + WriteLine($"All named sessions now have ADMINISTRATOR privileges."); + + string script = session.SecurityControl.Script.SetRolesForNamedSessions(new[] { "ADMINISTRATOR" }).ToScript(); + + WriteLine($"{script}"); + + await session.SecurityControl.UpdateStoreAsync(script, cancellationToken); + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/SecurityControl/SetGlobalPermissions.cs b/dotnet/examples/ServerConfiguration/SecurityControl/SetGlobalPermissions.cs new file mode 100644 index 00000000..24c0c86f --- /dev/null +++ b/dotnet/examples/ServerConfiguration/SecurityControl/SetGlobalPermissions.cs @@ -0,0 +1,60 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Types; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.SecurityControl +{ + public sealed class SetGlobalPermissions : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var defaultGlobalPermissions = new List(); + + var securityConfig = await session.SecurityControl.GetSecurityAsync(cancellationToken); + + var clientRole = securityConfig.Roles.Where(x => x.Name == "CLIENT").FirstOrDefault(); + defaultGlobalPermissions = clientRole.GlobalPermissions.ToList(); + + WriteLine($"Adding the following permissions to the global permissions of Role CLIENT: VIEW_SERVER and VIEW_SESSION."); + + var permissions = new List { GlobalPermission.VIEW_SERVER, GlobalPermission.VIEW_SESSION }; + permissions.AddRange(defaultGlobalPermissions); + + string script = session.SecurityControl.Script.SetGlobalPermissions("CLIENT", permissions).ToScript(); + + WriteLine($"{script}"); + + await session.SecurityControl.UpdateStoreAsync(script, cancellationToken); + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/SecurityControl/SetPathPermissions.cs b/dotnet/examples/ServerConfiguration/SecurityControl/SetPathPermissions.cs new file mode 100644 index 00000000..1ec17fd5 --- /dev/null +++ b/dotnet/examples/ServerConfiguration/SecurityControl/SetPathPermissions.cs @@ -0,0 +1,50 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Types; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.SecurityControl +{ + public sealed class SetPathPermissions : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + WriteLine($"Allowing Role CLIENT to update and modify my/topic/path."); + + var permissions = new[] { PathPermission.UPDATE_TOPIC, PathPermission.MODIFY_TOPIC }; + + string script = session.SecurityControl.Script.SetPathPermissions("CLIENT", "my/topic/path", permissions).ToScript(); + + WriteLine($"{script}"); + + await session.SecurityControl.UpdateStoreAsync(script, cancellationToken); + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/AbstainAnonymousConnections.cs b/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/AbstainAnonymousConnections.cs new file mode 100644 index 00000000..1a512476 --- /dev/null +++ b/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/AbstainAnonymousConnections.cs @@ -0,0 +1,92 @@ +/** + * Copyright © 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Session; +using PushTechnology.ClientInterface.Client.Features.Control.Clients; +using PushTechnology.ClientInterface.Client.Security.Authentication; +using PushTechnology.DiffusionCore.Client.Types; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.SystemAuthenticationControl +{ + public sealed class AbstainAnonymousConnections : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions.Principal("admin").Password("password") + .Open(serverUrl); + + WriteLine($"Abstain anonymous connections."); + + string updateScript = session.SystemAuthenticationControl.Script + .AbstainAnonymousConnections() + .ToScript(); + + await session.SystemAuthenticationControl.UpdateStoreAsync(updateScript, cancellationToken); + + + var session2 = Diffusion.Sessions.Principal("control").Password("password") + .Open(serverUrl); + + var authenticator = new Authenticator(); + + var registration = await session2.AuthenticationControl.SetAuthenticationHandlerAsync("after-system-handler", authenticator, cancellationToken); + + try + { + var session3 = Diffusion.Sessions.Open(serverUrl); + } + catch (Exception ex) + { + WriteLine($"{ex.Message}"); + } + + session2.Close(); + session.Close(); + } + + private sealed class Authenticator : IControlAuthenticator + { + + public void Authenticate( + string principal, + ICredentials credentials, + IReadOnlyDictionary sessionProperties, + IReadOnlyDictionary proposedProperties, + IAuthenticatorCallback callback) + { + if (string.IsNullOrEmpty(principal)) + { + WriteLine("Anonymous connection attempt detected. Session establishment Rejected."); + + callback.Deny(); + } + } + + public void OnClose() { } + + public void OnError(ErrorReason errorReason) { } + } + } +} diff --git a/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/AddLockedPrincipal.cs b/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/AddLockedPrincipal.cs new file mode 100644 index 00000000..556de9d6 --- /dev/null +++ b/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/AddLockedPrincipal.cs @@ -0,0 +1,45 @@ +/** + * Copyright © 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.SystemAuthenticationControl +{ + public sealed class AddLockedPrincipal : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions.Principal("admin").Password("password") + .Open(serverUrl); + + WriteLine($"Add locked principal."); + + string updateScript = session.SystemAuthenticationControl.Script + .AddPrincipal("super_user", "password12345", new List() { "ADMINISTRATOR " }, "admin") + .ToScript(); + + await session.SystemAuthenticationControl.UpdateStoreAsync(updateScript, cancellationToken); + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/AddPrincipal.cs b/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/AddPrincipal.cs new file mode 100644 index 00000000..916244ee --- /dev/null +++ b/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/AddPrincipal.cs @@ -0,0 +1,46 @@ +/** + * Copyright © 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.SystemAuthenticationControl +{ + public sealed class AddPrincipal : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions.Principal("admin").Password("password") + .Open(serverUrl); + + WriteLine($"Add principal."); + + string updateScript = session.SystemAuthenticationControl.Script + .AddPrincipal("super_user", "password12345", new List() { "ADMINISTRATOR " }) + .ToScript(); + + await session.SystemAuthenticationControl.UpdateStoreAsync(updateScript, cancellationToken); + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/AllowAnonymousConnections.cs b/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/AllowAnonymousConnections.cs new file mode 100644 index 00000000..d49a0722 --- /dev/null +++ b/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/AllowAnonymousConnections.cs @@ -0,0 +1,51 @@ +/** + * Copyright © 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.SystemAuthenticationControl +{ + public sealed class AllowAnonymousConnections : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions.Principal("admin").Password("password") + .Open(serverUrl); + + WriteLine($"Allow anonymous connections."); + + string updateScript = session.SystemAuthenticationControl.Script + .AllowAnonymousConnections(new List()) + .ToScript(); + + await session.SystemAuthenticationControl.UpdateStoreAsync(updateScript, cancellationToken); + + var session2 = Diffusion.Sessions.Open(serverUrl); + + WriteLine($"Session has been established for an anonymous principal."); + + session2.Close(); + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/AssignRoles.cs b/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/AssignRoles.cs new file mode 100644 index 00000000..3be18e5b --- /dev/null +++ b/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/AssignRoles.cs @@ -0,0 +1,50 @@ +/** + * Copyright © 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.SystemAuthenticationControl +{ + public sealed class AssignRoles : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions.Principal("admin").Password("password") + .Open(serverUrl); + + string updateScript = session.SystemAuthenticationControl.Script + .AddPrincipal("super_user", "password12345", new List() { "CLIENT " }) + .ToScript(); + + await session.SystemAuthenticationControl.UpdateStoreAsync(updateScript, cancellationToken); + + WriteLine($"Adding ADMINISTRATOR role to super_user principal."); + + updateScript = session.SystemAuthenticationControl.Script + .AssignRoles("super_user", new[] { "ADMINISTRATOR" }).ToScript(); + + await session.SystemAuthenticationControl.UpdateStoreAsync(updateScript, cancellationToken); + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/ChangePrincipalPassword.cs b/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/ChangePrincipalPassword.cs new file mode 100644 index 00000000..8c25af3e --- /dev/null +++ b/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/ChangePrincipalPassword.cs @@ -0,0 +1,51 @@ +/** + * Copyright © 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.SystemAuthenticationControl +{ + public sealed class ChangePrincipalPassword : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions.Principal("admin").Password("password") + .Open(serverUrl); + + string updateScript = session.SystemAuthenticationControl.Script + .AddPrincipal("super_user", "password12345", new List() { "CLIENT " }) + .ToScript(); + + await session.SystemAuthenticationControl.UpdateStoreAsync(updateScript, cancellationToken); + + WriteLine($"Change principal password."); + + updateScript = session.SystemAuthenticationControl.Script + .SetPassword("super_user", "hunter2") + .ToScript(); + + await session.SystemAuthenticationControl.UpdateStoreAsync(updateScript, cancellationToken); + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/DenyAnonymousConnections.cs b/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/DenyAnonymousConnections.cs new file mode 100644 index 00000000..67eb6ac8 --- /dev/null +++ b/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/DenyAnonymousConnections.cs @@ -0,0 +1,56 @@ +/** + * Copyright © 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Session; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.SystemAuthenticationControl +{ + public sealed class DenyAnonymousConnections : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions.Principal("admin").Password("password") + .Open(serverUrl); + + WriteLine($"Deny anonymous connections."); + + string updateScript = session.SystemAuthenticationControl.Script + .DenyAnonymousConnections() + .ToScript(); + + await session.SystemAuthenticationControl.UpdateStoreAsync(updateScript, cancellationToken); + + try + { + var session2 = Diffusion.Sessions.Open(serverUrl); + } + catch (Exception ex) + { + WriteLine($"{ex.Message}"); + } + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/IgnoreClientProposedProperty.cs b/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/IgnoreClientProposedProperty.cs new file mode 100644 index 00000000..2ee7a499 --- /dev/null +++ b/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/IgnoreClientProposedProperty.cs @@ -0,0 +1,74 @@ +/** + * Copyright © 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Session; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.SystemAuthenticationControl +{ + public sealed class IgnoreClientProposedProperty : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session1 = Diffusion.Sessions.Principal("admin").Password("password") + .Open(serverUrl); + + WriteLine($"Ignore client proposed property."); + + string updateScript = session1.SystemAuthenticationControl.Script + .IgnoreClientProposedProperty("Rubble") + .TrustClientProposedPropertyMatches("Flintstone", ".*_Flintstone") + .ToScript(); + + await session1.SystemAuthenticationControl.UpdateStoreAsync(updateScript, cancellationToken); + + var session2 = Diffusion.Sessions.Principal("control").Password("password") + .Property("Rubble", "Barney_Rubble") + .Open(serverUrl); + + var requiredProperties = new List { SessionProperty.ALL_FIXED_PROPERTIES }; + + var properties = await session1.ClientControl.GetSessionPropertiesAsync(session2.SessionId, requiredProperties); + + foreach (var property in properties) + { + WriteLine($"{property.Key}: {property.Value}"); + } + + var session3 = Diffusion.Sessions.Principal("control").Password("password") + .Property("Flintstone", "Fred_Flintstone") + .Open(serverUrl); + + properties = await session1.ClientControl.GetSessionPropertiesAsync(session3.SessionId, requiredProperties); + + foreach (var property in properties) + { + WriteLine($"{property.Key}: {property.Value}"); + } + + session3.Close(); + session2.Close(); + session1.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/RemovePrincipal.cs b/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/RemovePrincipal.cs new file mode 100644 index 00000000..65ade800 --- /dev/null +++ b/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/RemovePrincipal.cs @@ -0,0 +1,52 @@ +/** + * Copyright © 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.SystemAuthenticationControl +{ + public sealed class RemovePrincipal : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions.Principal("admin").Password("password") + .Open(serverUrl); + + string updateScript = session.SystemAuthenticationControl.Script + .AddPrincipal("super_user", "password12345", new List() { "ADMINISTRATOR " }) + .ToScript(); + + await session.SystemAuthenticationControl.UpdateStoreAsync(updateScript, cancellationToken); + + WriteLine($"Remove principal."); + + updateScript = session.SystemAuthenticationControl.Script + .RemovePrincipal("super_user") + .ToScript(); + + await session.SystemAuthenticationControl.UpdateStoreAsync(updateScript, cancellationToken); + + session.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/TrustClientProposedPropertyIn.cs b/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/TrustClientProposedPropertyIn.cs new file mode 100644 index 00000000..7bed3a63 --- /dev/null +++ b/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/TrustClientProposedPropertyIn.cs @@ -0,0 +1,73 @@ +/** + * Copyright © 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Session; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.SystemAuthenticationControl +{ + public sealed class TrustClientProposedPropertyIn : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session1 = Diffusion.Sessions.Principal("admin").Password("password") + .Open(serverUrl); + + WriteLine($"Trust client proposed property in."); + + string updateScript = session1.SystemAuthenticationControl.Script + .TrustClientProposedPropertyIn("Flintstone", new List { "Fred", "Wilma", "Pebbles" }) + .ToScript(); + + await session1.SystemAuthenticationControl.UpdateStoreAsync(updateScript, cancellationToken); + + var session2 = Diffusion.Sessions.Principal("control").Password("password") + .Property("Flintstone", "Barney") + .Open(serverUrl); + + var requiredProperties = new List { SessionProperty.ALL_FIXED_PROPERTIES }; + + var properties = await session1.ClientControl.GetSessionPropertiesAsync(session2.SessionId, requiredProperties); + + foreach (var property in properties) + { + WriteLine($"{property.Key}: {property.Value}"); + } + + var session3 = Diffusion.Sessions.Principal("control").Password("password") + .Property("Flintstone", "Fred") + .Open(serverUrl); + + properties = await session1.ClientControl.GetSessionPropertiesAsync(session3.SessionId, requiredProperties); + + foreach (var property in properties) + { + WriteLine($"{property.Key}: {property.Value}"); + } + + session3.Close(); + session2.Close(); + session1.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/TrustClientProposedPropertyMatches.cs b/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/TrustClientProposedPropertyMatches.cs new file mode 100644 index 00000000..5f714c13 --- /dev/null +++ b/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/TrustClientProposedPropertyMatches.cs @@ -0,0 +1,73 @@ +/** + * Copyright © 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Session; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.SystemAuthenticationControl +{ + public sealed class TrustClientProposedPropertyMatches : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session1 = Diffusion.Sessions.Principal("admin").Password("password") + .Open(serverUrl); + + WriteLine($"Trust client proposed property matches."); + + string updateScript = session1.SystemAuthenticationControl.Script + .TrustClientProposedPropertyMatches("Flintstone", ".*_Flintstone") + .ToScript(); + + await session1.SystemAuthenticationControl.UpdateStoreAsync(updateScript, cancellationToken); + + var session2 = Diffusion.Sessions.Principal("control").Password("password") + .Property("Flintstone", "Barney_Rubble") + .Open(serverUrl); + + var requiredProperties = new List { SessionProperty.ALL_FIXED_PROPERTIES }; + + var properties = await session1.ClientControl.GetSessionPropertiesAsync(session2.SessionId, requiredProperties); + + foreach (var property in properties) + { + WriteLine($"{property.Key}: {property.Value}"); + } + + var session3 = Diffusion.Sessions.Principal("control").Password("password") + .Property("Flintstone", "Fred_Flintstone") + .Open(serverUrl); + + properties = await session1.ClientControl.GetSessionPropertiesAsync(session3.SessionId, requiredProperties); + + foreach (var property in properties) + { + WriteLine($"{property.Key}: {property.Value}"); + } + + session3.Close(); + session2.Close(); + session1.Close(); + } + } +} diff --git a/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/VerifyPrincipalPassword.cs b/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/VerifyPrincipalPassword.cs new file mode 100644 index 00000000..1dbe0023 --- /dev/null +++ b/dotnet/examples/ServerConfiguration/SystemAuthenticationControl/VerifyPrincipalPassword.cs @@ -0,0 +1,78 @@ +/** + * Copyright © 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Session; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.ServerConfiguration.SystemAuthenticationControl +{ + public sealed class VerifyPrincipalPassword : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session1 = Diffusion.Sessions.Principal("admin").Password("password") + .Open(serverUrl); + + WriteLine($"Verify principal password."); + + string updateScript = session1.SystemAuthenticationControl.Script + .VerifyPassword("control", "password") + .SetPassword("control", "12345") + .ToScript(); + + await session1.SystemAuthenticationControl.UpdateStoreAsync(updateScript, cancellationToken); + + var session2 = Diffusion.Sessions.Principal("control").Password("12345") + .Open(serverUrl); + + session2.Close(); + + try + { + updateScript = session1.SystemAuthenticationControl.Script + .VerifyPassword("control", "this_is_not_the_right_password") + .SetPassword("control", "new_password") + .ToScript(); + + + await session1.SystemAuthenticationControl.UpdateStoreAsync(updateScript, cancellationToken); + } + catch (Exception ex) + { + WriteLine(ex.Message); + } + + try + { + var session3 = Diffusion.Sessions.Principal("control").Password("new_password") + .Open(serverUrl); + } + catch (Exception ex) + { + WriteLine(ex.Message); + } + + session1.Close(); + } + } +} diff --git a/dotnet/examples/SessionManagement/AuthenticationControl.cs b/dotnet/examples/SessionManagement/AuthenticationControl.cs new file mode 100644 index 00000000..498c08e2 --- /dev/null +++ b/dotnet/examples/SessionManagement/AuthenticationControl.cs @@ -0,0 +1,141 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using System.Linq; +using static System.Console; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features.Control.Clients; +using PushTechnology.ClientInterface.Client.Security.Authentication; +using PushTechnology.ClientInterface.Client.Session; +using PushTechnology.DiffusionCore.Client.Types; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.SessionManagement +{ + public sealed class AuthenticationControl : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + ISession session1 = null, session2 = null, session3 = null, session4 = null; + IRegistration registration = null; + + var authenticator = new Authenticator(); + + try + { + session1 = Diffusion.Sessions + .Principal("control") + .Password("password") + .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) + .Open(serverUrl); + + registration = await session1.AuthenticationControl.SetAuthenticationHandlerAsync("before-system-handler", authenticator, cancellationToken); + + await Task.Delay(5000); + } + catch (Exception ex) + { + WriteLine($"An error occurred when running the example : {ex}."); + } + + try + { + session2 = Diffusion.Sessions.Open(serverUrl); + + await Task.Delay(5000); + } + catch(Exception ex) + { + WriteLine($"Session creation failed due to authentication denied : {ex}."); + } + + try + { + session3 = Diffusion.Sessions.Principal("control") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + await Task.Delay(5000); + } + catch (Exception ex) + { + WriteLine($"Session creation failed due to authentication denied : {ex}."); + } + + try + { + session4 = Diffusion.Sessions.Principal("diffusion_control") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + await Task.Delay(5000); + } + catch (Exception ex) + { + WriteLine($"An error occurred when running the example : {ex}."); + } + + await registration.CloseAsync(); + + session4?.Close(); + session3?.Close(); + session2?.Close(); + session1.Close(); + } + + private sealed class Authenticator : IControlAuthenticator + { + + public void Authenticate( + string principal, + ICredentials credentials, + IReadOnlyDictionary sessionProperties, + IReadOnlyDictionary proposedProperties, + IAuthenticatorCallback callback) + { + if (principal.StartsWith("diffusion_")) + { + WriteLine("Principal begins with diffusion_ prefix. Session establishment Accepted."); + + callback.Allow(); + } + else + { + if (string.IsNullOrEmpty(principal)) + { + WriteLine("Anonymous connection attempt detected. Session establishment Rejected."); + } + else + { + WriteLine("Principal does not begins with diffusion_ prefix. Session establishment Rejected."); + } + + callback.Deny(); + } + } + + public void OnClose() { } + + public void OnError(ErrorReason errorReason) { } + } + } +} \ No newline at end of file diff --git a/dotnet/examples/SessionManagement/ClientControl/ChangeRolesViaSessionFilter.cs b/dotnet/examples/SessionManagement/ClientControl/ChangeRolesViaSessionFilter.cs new file mode 100644 index 00000000..9636fbee --- /dev/null +++ b/dotnet/examples/SessionManagement/ClientControl/ChangeRolesViaSessionFilter.cs @@ -0,0 +1,60 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Collections.ObjectModel; +using System.Threading; +using System.Threading.Tasks; +using System.Collections.Generic; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Session; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.SessionManagement.ClientControl +{ + public sealed class ChangeRolesViaSessionFilter : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var session2 = Diffusion.Sessions + .Principal("client") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var requiredProperties = new List { SessionProperty.ALL_FIXED_PROPERTIES }; + + var properties = await session.ClientControl.GetSessionPropertiesAsync(session2.SessionId, requiredProperties, cancellationToken); + + WriteLine($"Original value {properties["$Roles"]}"); + + await session.ClientControl.ChangeRolesAsync("$Principal is 'client'", new Collection(), new Collection() { "TOPIC_CONTROL" }, cancellationToken); + + properties = await session.ClientControl.GetSessionPropertiesAsync(session2.SessionId, requiredProperties, cancellationToken); + + WriteLine($"Changed value {properties["$Roles"]}"); + + session2.Close(); + session.Close(); + } + } +} diff --git a/dotnet/examples/SessionManagement/ClientControl/ChangeRolesViaSessionID.cs b/dotnet/examples/SessionManagement/ClientControl/ChangeRolesViaSessionID.cs new file mode 100644 index 00000000..8b433764 --- /dev/null +++ b/dotnet/examples/SessionManagement/ClientControl/ChangeRolesViaSessionID.cs @@ -0,0 +1,60 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Session; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.SessionManagement.ClientControl +{ + public sealed class ChangeRolesViaSessionID : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var session2 = Diffusion.Sessions + .Principal("client") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var requiredProperties = new List { SessionProperty.ALL_FIXED_PROPERTIES }; + + var properties = await session.ClientControl.GetSessionPropertiesAsync(session2.SessionId, requiredProperties, cancellationToken); + + WriteLine($"Original value {properties["$Roles"]}"); + + await session.ClientControl.ChangeRolesAsync(session2.SessionId, new Collection(), new Collection() { "TOPIC_CONTROL" }, cancellationToken); + + properties = await session.ClientControl.GetSessionPropertiesAsync(session2.SessionId, requiredProperties, cancellationToken); + + WriteLine($"Changed value {properties["$Roles"]}"); + + session2.Close(); + session.Close(); + } + } +} diff --git a/dotnet/examples/SessionManagement/ClientControl/CloseClientViaSessionFilter.cs b/dotnet/examples/SessionManagement/ClientControl/CloseClientViaSessionFilter.cs new file mode 100644 index 00000000..0f154be0 --- /dev/null +++ b/dotnet/examples/SessionManagement/ClientControl/CloseClientViaSessionFilter.cs @@ -0,0 +1,54 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Session; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.SessionManagement.ClientControl +{ + public sealed class CloseClientViaSessionFilter : Example + { + private void OnSessionStateChanged(object sender, SessionListenerEventArgs e) + { + WriteLine($"State changed from {e.OldState} to {e.NewState}."); + } + + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var session2 = Diffusion.Sessions + .Principal("client") + .Credentials(Diffusion.Credentials.Password("password")) + .SessionStateChangedHandler(OnSessionStateChanged) + .Open(serverUrl); + + int result = await session.ClientControl.CloseAsync("$Principal is 'client'", cancellationToken); + WriteLine($"Number of sessions closed: {result}."); + + session.Close(); + } + } +} diff --git a/dotnet/examples/SessionManagement/ClientControl/CloseClientViaSessionID.cs b/dotnet/examples/SessionManagement/ClientControl/CloseClientViaSessionID.cs new file mode 100644 index 00000000..81e616c1 --- /dev/null +++ b/dotnet/examples/SessionManagement/ClientControl/CloseClientViaSessionID.cs @@ -0,0 +1,53 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Session; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.SessionManagement.ClientControl +{ + public sealed class CloseClientViaSessionID : Example + { + private void OnSessionStateChanged(object sender, SessionListenerEventArgs e) + { + WriteLine($"State changed from {e.OldState} to {e.NewState}."); + } + + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var session2 = Diffusion.Sessions + .Principal("client") + .Credentials(Diffusion.Credentials.Password("password")) + .SessionStateChangedHandler(OnSessionStateChanged) + .Open(serverUrl); + + await session.ClientControl.CloseAsync(session2.SessionId, cancellationToken); + + session.Close(); + } + } +} diff --git a/dotnet/examples/SessionManagement/ClientControl/ControlClientQueueConflationViaSessionFilter.cs b/dotnet/examples/SessionManagement/ClientControl/ControlClientQueueConflationViaSessionFilter.cs new file mode 100644 index 00000000..af99c253 --- /dev/null +++ b/dotnet/examples/SessionManagement/ClientControl/ControlClientQueueConflationViaSessionFilter.cs @@ -0,0 +1,48 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.SessionManagement.ClientControl +{ + public sealed class ControlClientQueueConflationViaSessionFilter : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var session2 = Diffusion.Sessions + .Principal("client") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + int matchedSessions = await session.ClientControl.SetConflatedAsync("$Principal is 'client'", false, cancellationToken); + WriteLine($"Total clients with queue conflation disabled by session filter: {matchedSessions}."); + + session2.Close(); + session.Close(); + } + } +} diff --git a/dotnet/examples/SessionManagement/ClientControl/ControlClientQueueConflationViaSessionID.cs b/dotnet/examples/SessionManagement/ClientControl/ControlClientQueueConflationViaSessionID.cs new file mode 100644 index 00000000..e3c00a9a --- /dev/null +++ b/dotnet/examples/SessionManagement/ClientControl/ControlClientQueueConflationViaSessionID.cs @@ -0,0 +1,48 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.SessionManagement.ClientControl +{ + public sealed class ControlClientQueueConflationViaSessionID : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var session2 = Diffusion.Sessions + .Principal("client") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + await session.ClientControl.SetConflatedAsync(session2.SessionId, false, cancellationToken); + WriteLine("Conflation policy was disabled."); + + session2.Close(); + session.Close(); + } + } +} diff --git a/dotnet/examples/SessionManagement/ClientControl/GetSessionPropertiesViaSessionID.cs b/dotnet/examples/SessionManagement/ClientControl/GetSessionPropertiesViaSessionID.cs new file mode 100644 index 00000000..f0f23a86 --- /dev/null +++ b/dotnet/examples/SessionManagement/ClientControl/GetSessionPropertiesViaSessionID.cs @@ -0,0 +1,58 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Session; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.SessionManagement.ClientControl +{ + public sealed class GetSessionPropertiesViaSessionID : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var session2 = Diffusion.Sessions + .Principal("client") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var requiredProperties = new List { SessionProperty.ALL_FIXED_PROPERTIES }; + + var properties = await session.ClientControl.GetSessionPropertiesAsync(session2.SessionId, requiredProperties, cancellationToken); + + WriteLine("Received the following session properties:"); + + foreach (var property in properties) + { + WriteLine($"{property.Key}: {property.Value}"); + } + + session2.Close(); + session.Close(); + } + } +} diff --git a/dotnet/examples/SessionManagement/ClientControl/SetSessionPropertiesViaSessionFilter.cs b/dotnet/examples/SessionManagement/ClientControl/SetSessionPropertiesViaSessionFilter.cs new file mode 100644 index 00000000..9d128dac --- /dev/null +++ b/dotnet/examples/SessionManagement/ClientControl/SetSessionPropertiesViaSessionFilter.cs @@ -0,0 +1,69 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Session; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.SessionManagement.ClientControl +{ + public sealed class SetSessionPropertiesViaSessionFilter : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var session2 = Diffusion.Sessions + .Principal("client") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var requiredProperties = new List { SessionProperty.ALL_FIXED_PROPERTIES }; + + var properties = await session.ClientControl.GetSessionPropertiesAsync(session2.SessionId, requiredProperties, cancellationToken); + + WriteLine("Original session properties:"); + + foreach (var property in properties) + { + WriteLine($"{property.Key}: {property.Value}"); + } + + await session.ClientControl.SetSessionPropertiesAsync("$Principal is 'client'", new Dictionary { { "$Language", "en-gb" } }, cancellationToken); + + properties = await session.ClientControl.GetSessionPropertiesAsync(session2.SessionId, requiredProperties, cancellationToken); + + WriteLine("Changed session properties:"); + + foreach (var property in properties) + { + WriteLine($"{property.Key}: {property.Value}"); + } + + session2.Close(); + session.Close(); + } + } +} diff --git a/dotnet/examples/SessionManagement/ClientControl/SetSessionPropertiesViaSessionID.cs b/dotnet/examples/SessionManagement/ClientControl/SetSessionPropertiesViaSessionID.cs new file mode 100644 index 00000000..b3d088af --- /dev/null +++ b/dotnet/examples/SessionManagement/ClientControl/SetSessionPropertiesViaSessionID.cs @@ -0,0 +1,71 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Session; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + + +namespace PushTechnology.ClientInterface.Examples.SessionManagement.ClientControl +{ + public sealed class SetSessionPropertiesViaSessionID : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var session2 = Diffusion.Sessions + .Principal("client") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var requiredProperties = new List { SessionProperty.ALL_FIXED_PROPERTIES }; + + var properties = await session.ClientControl.GetSessionPropertiesAsync(session2.SessionId, requiredProperties, cancellationToken); + + WriteLine("Original session properties:"); + + foreach (var property in properties) + { + WriteLine($"{property.Key}: {property.Value}"); + } + + await session.ClientControl.SetSessionPropertiesAsync(session2.SessionId, new Dictionary { { "$Language", "en-gb" } }, cancellationToken); + + properties = await session.ClientControl.GetSessionPropertiesAsync(session2.SessionId, requiredProperties, cancellationToken); + + WriteLine("Changed session properties:"); + + foreach (var property in properties) + { + WriteLine($"{property.Key}: {property.Value}"); + } + + session2.Close(); + session.Close(); + } + } +} diff --git a/dotnet/examples/SessionManagement/SubscriptionControl.cs b/dotnet/examples/SessionManagement/SubscriptionControl.cs new file mode 100644 index 00000000..2684e437 --- /dev/null +++ b/dotnet/examples/SessionManagement/SubscriptionControl.cs @@ -0,0 +1,122 @@ +/** + * Copyright © 2023 - 2025 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using System.Linq; +using static System.Console; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Features.Control.Clients; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Session; +using PushTechnology.ClientInterface.Client.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.SessionManagement +{ + public sealed class SubscriptionControl : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path/hello"; + string topicSelector = "?my/topic/path//"; + + var specification = Diffusion.NewSpecification(TopicType.STRING); + + await session.TopicUpdate.AddAndSetAsync(topic, specification, "Hello World!", cancellationToken); + + var parameters = Diffusion.NewSessionEventParametersBuilder() + .Properties(SessionProperty.ALL_FIXED_PROPERTIES) + .Build(); + + var myEventStream = new MyEventStream(session); + var registration = await session.ClientControl.AddSessionEventListenerAsync(myEventStream, parameters); + + var session2 = Diffusion.Sessions + .Principal("client") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var valueStream = new ValueStream(); + session2.Topics.AddStream(topicSelector, valueStream); + + session2.Close(); + session.Close(); + } + + private class MyEventStream : ISessionEventStream + { + private readonly ISession session; + + public MyEventStream(ISession session) => this.session = session; + + public void OnClose() { } + + public void OnError(ErrorReason errorReason) { } + + public void OnSessionEvent(ISessionEventStreamEvent sessionEventStreamEvent) + { + if (sessionEventStreamEvent.IsOpenEvent) + { + if (session.SessionId.ToString() != sessionEventStreamEvent.SessionId.ToString()) + { + Thread.Sleep(2000); + + session.SubscriptionControl.SubscribeAsync(sessionEventStreamEvent.SessionId, "?my/topic/path//"); + + Thread.Sleep(2000); + + session.SubscriptionControl.UnsubscribeAsync(sessionEventStreamEvent.SessionId, "?my/topic/path//"); + } + } + } + } + + private sealed class ValueStream : IValueStream + { + + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, string oldValue, string newValue) + { + WriteLine($"{topicPath}: {newValue}."); + } + } + } +} diff --git a/dotnet/examples/TimeSeries/AppendToTimeSeriesTopic.cs b/dotnet/examples/TimeSeries/AppendToTimeSeriesTopic.cs new file mode 100644 index 00000000..4e7ec2c8 --- /dev/null +++ b/dotnet/examples/TimeSeries/AppendToTimeSeriesTopic.cs @@ -0,0 +1,78 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; +using PushTechnology.ClientInterface.Client.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + + +namespace PushTechnology.ClientInterface.Examples.TimeSeries +{ + public sealed class AppendToTimeSeriesTopic : Example + { + public override async Task Run( CancellationToken cancellationToken, string[] args ) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string typeName = Diffusion.DataTypes.Get().TypeName; + + var topicProperties = new Dictionary { + { TopicSpecificationProperty.TimeSeriesEventValueType, typeName }, + { TopicSpecificationProperty.TimeSeriesRetainedRange, "limit 15 last 10s" }, + { TopicSpecificationProperty.TimeSeriesSubscriptionRange, "limit 3" } + }; + + var specification = Diffusion.NewSpecification(TopicType.TIME_SERIES) + .WithProperties(topicProperties); + + string topic = "my/time/series/topic/path"; + + var result = await session.TopicControl.AddTopicAsync(topic, specification, cancellationToken); + + if (result == AddTopicResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + + var random = new Random(); + + for (int i = 0; i < 25; i++) + { + double newValue = random.NextDouble(); + + await session.TimeSeries.AppendAsync(topic, newValue, cancellationToken); + } + + session.Close(); + } + } +} diff --git a/dotnet/examples/TimeSeries/AppendToTimeSeriesTopicViaUpdateStream.cs b/dotnet/examples/TimeSeries/AppendToTimeSeriesTopicViaUpdateStream.cs new file mode 100644 index 00000000..1408b309 --- /dev/null +++ b/dotnet/examples/TimeSeries/AppendToTimeSeriesTopicViaUpdateStream.cs @@ -0,0 +1,80 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; +using PushTechnology.ClientInterface.Client.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + + +namespace PushTechnology.ClientInterface.Examples.TimeSeries +{ + public sealed class AppendToTimeSeriesTopicViaUpdateStream : Example + { + public override async Task Run( CancellationToken cancellationToken, string[] args ) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string typeName = Diffusion.DataTypes.Get().TypeName; + + var topicProperties = new Dictionary { + { TopicSpecificationProperty.TimeSeriesEventValueType, typeName }, + { TopicSpecificationProperty.TimeSeriesRetainedRange, "limit 15 last 10s" }, + { TopicSpecificationProperty.TimeSeriesSubscriptionRange, "limit 3" } + }; + + var specification = Diffusion.NewSpecification(TopicType.TIME_SERIES) + .WithProperties(topicProperties); + + string topic = "my/time/series/topic/path"; + + var result = await session.TopicControl.AddTopicAsync(topic, specification, cancellationToken); + + if (result == AddTopicResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + + var builder = session.TopicUpdate.NewUpdateStreamBuilder(); + var stream = builder.Build(topic); + + var random = new Random(); + + for (int i = 0; i < 25; i++) + { + double newValue = random.NextDouble(); + + await stream.SetAsync(newValue, cancellationToken); + } + + session.Close(); + } + } +} diff --git a/dotnet/examples/TimeSeries/AppendToTimeSeriesTopicWithUserSuppliedTimestamp.cs b/dotnet/examples/TimeSeries/AppendToTimeSeriesTopicWithUserSuppliedTimestamp.cs new file mode 100644 index 00000000..a44277a5 --- /dev/null +++ b/dotnet/examples/TimeSeries/AppendToTimeSeriesTopicWithUserSuppliedTimestamp.cs @@ -0,0 +1,78 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; +using PushTechnology.ClientInterface.Client.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + + +namespace PushTechnology.ClientInterface.Examples.TimeSeries +{ + public sealed class AppendToTimeSeriesTopicWithUserSuppliedTimestamp : Example + { + public override async Task Run( CancellationToken cancellationToken, string[] args ) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string typeName = Diffusion.DataTypes.Get().TypeName; + + var topicProperties = new Dictionary { + { TopicSpecificationProperty.TimeSeriesEventValueType, typeName }, + { TopicSpecificationProperty.TimeSeriesRetainedRange, "limit 15 last 10s" }, + { TopicSpecificationProperty.TimeSeriesSubscriptionRange, "limit 3" } + }; + + var specification = Diffusion.NewSpecification(TopicType.TIME_SERIES) + .WithProperties(topicProperties); + + string topic = "my/time/series/topic/path/user/supplied"; + + var result = await session.TopicControl.AddTopicAsync(topic, specification, cancellationToken); + + if (result == AddTopicResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + + int millis = 1000000; + var random = new Random(); + + for (int i = 0; i < 25; i++) + { + double newValue = random.NextDouble(); + + await session.TimeSeries.AppendAsync(topic, newValue, DateTimeOffset.FromUnixTimeMilliseconds(++millis), cancellationToken); + } + + session.Close(); + } + } +} diff --git a/dotnet/examples/TimeSeries/CreateTimeSeriesTopic.cs b/dotnet/examples/TimeSeries/CreateTimeSeriesTopic.cs new file mode 100644 index 00000000..de847a08 --- /dev/null +++ b/dotnet/examples/TimeSeries/CreateTimeSeriesTopic.cs @@ -0,0 +1,68 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; +using PushTechnology.ClientInterface.Client.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + + +namespace PushTechnology.ClientInterface.Examples.TimeSeries +{ + public sealed class CreateTimeSeriesTopic : Example + { + public override async Task Run( CancellationToken cancellationToken, string[] args ) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string typeName = Diffusion.DataTypes.Get().TypeName; + + var topicProperties = new Dictionary { + { TopicSpecificationProperty.TimeSeriesEventValueType, typeName }, + { TopicSpecificationProperty.TimeSeriesRetainedRange, "limit 15 last 10s" }, + { TopicSpecificationProperty.TimeSeriesSubscriptionRange, "limit 3" } + }; + + var specification = Diffusion.NewSpecification(TopicType.TIME_SERIES) + .WithProperties(topicProperties); + + string topic = "my/time/series/topic/path"; + + var result = await session.TopicControl.AddTopicAsync(topic, specification, cancellationToken); + + if (result == AddTopicResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + + session.Close(); + } + } +} diff --git a/dotnet/examples/TimeSeries/EditTimeSeriesTopic.cs b/dotnet/examples/TimeSeries/EditTimeSeriesTopic.cs new file mode 100644 index 00000000..31452c8f --- /dev/null +++ b/dotnet/examples/TimeSeries/EditTimeSeriesTopic.cs @@ -0,0 +1,79 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; +using PushTechnology.ClientInterface.Client.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + + +namespace PushTechnology.ClientInterface.Examples.TimeSeries +{ + public sealed class EditTimeSeriesTopic : Example + { + public override async Task Run( CancellationToken cancellationToken, string[] args ) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string typeName = Diffusion.DataTypes.Get().TypeName; + + var topicProperties = new Dictionary { + { TopicSpecificationProperty.TimeSeriesEventValueType, typeName }, + { TopicSpecificationProperty.TimeSeriesRetainedRange, "limit 15 last 10s" }, + { TopicSpecificationProperty.TimeSeriesSubscriptionRange, "limit 3" } + }; + + var specification = Diffusion.NewSpecification(TopicType.TIME_SERIES) + .WithProperties(topicProperties); + + string topic = "my/time/series/topic/path"; + + var result = await session.TopicControl.AddTopicAsync(topic, specification, cancellationToken); + + if (result == AddTopicResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + + var random = new Random(); + + for (int i = 0; i < 25; i++) + { + double newValue = random.NextDouble(); + + await session.TimeSeries.AppendAsync(topic, newValue, cancellationToken); + } + + await session.TimeSeries.EditAsync(topic, 20, 3.14, cancellationToken); + + session.Close(); + } + } +} diff --git a/dotnet/examples/TimeSeries/RangeQueryATimeSeriesTopic.cs b/dotnet/examples/TimeSeries/RangeQueryATimeSeriesTopic.cs new file mode 100644 index 00000000..509fe361 --- /dev/null +++ b/dotnet/examples/TimeSeries/RangeQueryATimeSeriesTopic.cs @@ -0,0 +1,94 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; +using PushTechnology.ClientInterface.Client.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.TimeSeries +{ + public sealed class RangeQueryATimeSeriesTopic : Example + { + public override async Task Run( CancellationToken cancellationToken, string[] args ) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string typeName = Diffusion.DataTypes.Get().TypeName; + + var topicProperties = new Dictionary { + { TopicSpecificationProperty.TimeSeriesEventValueType, typeName }, + { TopicSpecificationProperty.TimeSeriesRetainedRange, "limit 50 last 120s" }, + { TopicSpecificationProperty.TimeSeriesSubscriptionRange, "limit 3" } + }; + + var specification = Diffusion.NewSpecification(TopicType.TIME_SERIES) + .WithProperties(topicProperties); + + string topic = "my/time/series/topic/path"; + + var result = await session.TopicControl.AddTopicAsync(topic, specification, cancellationToken); + + if (result == AddTopicResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + + var random = new Random(); + + for (int i = 0; i < 25; i++) + { + double newValue = random.NextDouble(); + + await session.TimeSeries.AppendAsync(topic, newValue, cancellationToken); + } + + await session.TimeSeries.EditAsync(topic, 10, 3.14, cancellationToken); + + // Create a time series range query from values 5 to 15. + var rangeQuery = session.TimeSeries.RangeQuery.As(); + + var queryResult = await rangeQuery + .From(5) + .To(15) + .SelectFromAsync(topic, cancellationToken); + + var eventResults = queryResult.Events.ToList(); + + foreach (var eventResult in eventResults) + { + WriteLine($"{eventResult.Metadata.Sequence} ({eventResult.Metadata.Timestamp}): {eventResult.Value}"); + } + + session.Close(); + } + } +} diff --git a/dotnet/examples/TimeSeries/SubscribeToTimeSeriesTopics.cs b/dotnet/examples/TimeSeries/SubscribeToTimeSeriesTopics.cs new file mode 100644 index 00000000..67930ccb --- /dev/null +++ b/dotnet/examples/TimeSeries/SubscribeToTimeSeriesTopics.cs @@ -0,0 +1,107 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using static System.Console; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.TimeSeries +{ + public sealed class SubscribeToTimeSeriesTopics : Example + { + public override async Task Run( CancellationToken cancellationToken, string[] args ) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string typeName = Diffusion.DataTypes.Get().TypeName; + + var topicProperties = new Dictionary { + { TopicSpecificationProperty.TimeSeriesEventValueType, typeName }, + { TopicSpecificationProperty.TimeSeriesRetainedRange, "limit 15 last 10s" }, + { TopicSpecificationProperty.TimeSeriesSubscriptionRange, "limit 3" } + }; + + var specification = Diffusion.NewSpecification(TopicType.TIME_SERIES) + .WithProperties(topicProperties); + + string topic = "my/time/series/topic/path"; + string topicSelector = "?my/time/series//"; + + var result = await session.TopicControl.AddTopicAsync(topic, specification, cancellationToken); + + if (result == AddTopicResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + + var random = new Random(); + + for (int i = 0; i < 25; i++) + { + double newValue = random.NextDouble(); + + await session.TimeSeries.AppendAsync(topic, newValue, cancellationToken); + } + + var valueStream = new ValueStream(); + session.Topics.AddStream(topicSelector, valueStream); + + await session.Topics.SubscribeAsync(topicSelector, cancellationToken); + + session.Close(); + } + + private sealed class ValueStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, double? oldValue, double? newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToString())} to {newValue}."); + } + } + } +} diff --git a/dotnet/examples/TimeSeries/TimeSeriesCrossCompatibleDatatypes.cs b/dotnet/examples/TimeSeries/TimeSeriesCrossCompatibleDatatypes.cs new file mode 100644 index 00000000..ae6f291d --- /dev/null +++ b/dotnet/examples/TimeSeries/TimeSeriesCrossCompatibleDatatypes.cs @@ -0,0 +1,109 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Features.Control.Topics; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Data.JSON; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + + +namespace PushTechnology.ClientInterface.Examples.TimeSeries +{ + public sealed class TimeSeriesCrossCompatibleDatatypes : Example + { + public override async Task Run( CancellationToken cancellationToken, string[] args ) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string typeName = Diffusion.DataTypes.Get().TypeName; + + var topicProperties = new Dictionary { + { TopicSpecificationProperty.TimeSeriesEventValueType, typeName }, + { TopicSpecificationProperty.TimeSeriesRetainedRange, "limit 15 last 10s" }, + { TopicSpecificationProperty.TimeSeriesSubscriptionRange, "limit 3" } + }; + + var specification = Diffusion.NewSpecification(TopicType.TIME_SERIES) + .WithProperties(topicProperties); + + string topic = "my/time/series/topic/path"; + string topicSelector = "?my/time/series//"; + + var result = await session.TopicControl.AddTopicAsync(topic, specification, cancellationToken); + + if (result == AddTopicResult.CREATED) + { + WriteLine("Topic has been created."); + } + else + { + WriteLine("Topic already exists."); + } + + var random = new Random(); + + for (int i = 0; i < 25; i++) + { + double newValue = random.NextDouble(); + + await session.TimeSeries.AppendAsync(topic, newValue, cancellationToken); + } + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topicSelector, jsonStream); + + await session.Topics.SubscribeAsync(topicSelector, cancellationToken); + + session.Close(); + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} diff --git a/dotnet/examples/Wrangling/SessionTrees/GetBranchMappingTable.cs b/dotnet/examples/Wrangling/SessionTrees/GetBranchMappingTable.cs new file mode 100644 index 00000000..61f58ef8 --- /dev/null +++ b/dotnet/examples/Wrangling/SessionTrees/GetBranchMappingTable.cs @@ -0,0 +1,70 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.SessionTrees +{ + public sealed class GetBranchMappingTable : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var table = Diffusion.NewBranchMappingTableBuilder() + .AddBranchMapping("$Principal is 'admin'", "my/topic/path/for/admin") + .AddBranchMapping("$Principal is 'control'", "my/topic/path/for/control") + .AddBranchMapping("$Principal is ''", "my/topic/path/for/anonymous") + .Create("my/personal/path"); + + await session.SessionTrees.PutBranchMappingTableAsync(table, cancellationToken); + + var table2 = Diffusion.NewBranchMappingTableBuilder() + .AddBranchMapping("$Transport is 'WEBSOCKET'", "my/alternate/path/for/websocket") + .AddBranchMapping("$Transport is 'HTTP_LONG_POLL'", "my/alternate/path/for/http") + .AddBranchMapping("$Transport is 'TCP'", "my/alternate/path/for/tcp") + .Create("my/alternate/path"); + + await session.SessionTrees.PutBranchMappingTableAsync(table2, cancellationToken); + + var listSessionTreeBranches = await session.SessionTrees.GetSessionTreeBranchesWithMappingsAsync(cancellationToken); + + foreach (string sessionTreeBranch in listSessionTreeBranches) + { + WriteLine($"{sessionTreeBranch}:"); + + var branchMappingTable = await session.SessionTrees.GetBranchMappingTableAsync(sessionTreeBranch, cancellationToken); + + foreach (var branchMapping in branchMappingTable.BranchMappings) + { + WriteLine($"{branchMapping.SessionFilter}: {branchMapping.TopicTreeBranch}"); + } + } + + session.Close(); + } + } +} diff --git a/dotnet/examples/Wrangling/SessionTrees/ListSessionTreeBranchesWithMappings.cs b/dotnet/examples/Wrangling/SessionTrees/ListSessionTreeBranchesWithMappings.cs new file mode 100644 index 00000000..bb578fc2 --- /dev/null +++ b/dotnet/examples/Wrangling/SessionTrees/ListSessionTreeBranchesWithMappings.cs @@ -0,0 +1,63 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.SessionTrees +{ + public sealed class ListSessionTreeBranchesWithMappings : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var table = Diffusion.NewBranchMappingTableBuilder() + .AddBranchMapping("$Principal is 'admin'", "my/topic/path/for/admin") + .AddBranchMapping("$Principal is 'control'", "my/topic/path/for/control") + .AddBranchMapping("$Principal is ''", "my/topic/path/for/anonymous") + .Create("my/personal/path"); + + await session.SessionTrees.PutBranchMappingTableAsync(table, cancellationToken); + + var table2 = Diffusion.NewBranchMappingTableBuilder() + .AddBranchMapping("$Transport is 'WEBSOCKET'", "my/alternate/path/for/websocket") + .AddBranchMapping("$Transport is 'HTTP_LONG_POLL'", "my/alternate/path/for/http") + .AddBranchMapping("$Transport is 'TCP'", "my/alternate/path/for/tcp") + .Create("my/alternate/path"); + + await session.SessionTrees.PutBranchMappingTableAsync(table2, cancellationToken); + + var listSessionTreeBranches = await session.SessionTrees.GetSessionTreeBranchesWithMappingsAsync(cancellationToken); + + foreach (string sessionTreeBranch in listSessionTreeBranches) + { + WriteLine($"{sessionTreeBranch}"); + } + + session.Close(); + } + } +} diff --git a/dotnet/examples/Wrangling/SessionTrees/PutAndRemoveBranchMappingTable.cs b/dotnet/examples/Wrangling/SessionTrees/PutAndRemoveBranchMappingTable.cs new file mode 100644 index 00000000..72350506 --- /dev/null +++ b/dotnet/examples/Wrangling/SessionTrees/PutAndRemoveBranchMappingTable.cs @@ -0,0 +1,53 @@ +/** + * Copyright © 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.SessionTrees +{ + public sealed class PutAndRemoveBranchMappingTable : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var table = Diffusion.NewBranchMappingTableBuilder() + .AddBranchMapping("$Principal is 'admin'", "my/topic/path/for/admin") + .AddBranchMapping("$Principal is 'control'", "my/topic/path/for/control") + .AddBranchMapping("$Principal is ''", "my/topic/path/for/anonymous") + .Create("my/personal/path"); + + await session.SessionTrees.PutBranchMappingTableAsync(table, cancellationToken); + + WriteLine($"Session tree mappings added."); + + await session.SessionTrees.PutBranchMappingTableAsync(Diffusion.NewBranchMappingTableBuilder().Create("my/personal/path"), cancellationToken); + + WriteLine($"Session tree mapping table and mappings removed."); + + session.Close(); + } + } +} diff --git a/dotnet/examples/Wrangling/SessionTrees/PutBranchMappingTable.cs b/dotnet/examples/Wrangling/SessionTrees/PutBranchMappingTable.cs new file mode 100644 index 00000000..4c729376 --- /dev/null +++ b/dotnet/examples/Wrangling/SessionTrees/PutBranchMappingTable.cs @@ -0,0 +1,49 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.SessionTrees +{ + public sealed class PutBranchMappingTable : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var table = Diffusion.NewBranchMappingTableBuilder() + .AddBranchMapping("$Principal is 'admin'", "my/topic/path/for/admin") + .AddBranchMapping("$Principal is 'control'", "my/topic/path/for/control") + .AddBranchMapping("$Principal is ''", "my/topic/path/for/anonymous") + .Create("my/personal/path"); + + await session.SessionTrees.PutBranchMappingTableAsync(table, cancellationToken); + + WriteLine($"Branch mapping table created for session tree branch '{table.SessionTreeBranch}'."); + + session.Close(); + } + } +} diff --git a/dotnet/examples/Wrangling/SessionTrees/UseCase.cs b/dotnet/examples/Wrangling/SessionTrees/UseCase.cs new file mode 100644 index 00000000..3760bf37 --- /dev/null +++ b/dotnet/examples/Wrangling/SessionTrees/UseCase.cs @@ -0,0 +1,116 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.SessionTrees +{ + public sealed class UseCase : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + var topicSpecification = Diffusion.NewSpecification(TopicType.STRING); + await session.TopicUpdate.AddAndSetAsync("my/topic/path/for/admin", topicSpecification, "Good morning Administrator", cancellationToken); + await session.TopicUpdate.AddAndSetAsync("my/topic/path/for/control", topicSpecification, "Good afternoon Control Client", cancellationToken); + await session.TopicUpdate.AddAndSetAsync("my/topic/path/for/anonymous", topicSpecification, "Good night Anonymous", cancellationToken); + + var table = Diffusion.NewBranchMappingTableBuilder() + .AddBranchMapping("$Principal is 'admin'", "my/topic/path/for/admin") + .AddBranchMapping("$Principal is 'control'", "my/topic/path/for/control") + .AddBranchMapping("$Principal is ''", "my/topic/path/for/anonymous") + .Create("my/personal/path"); + + await session.SessionTrees.PutBranchMappingTableAsync(table, cancellationToken); + + string topicSelector = ">my/personal/path"; + var stringStream = new StringStream(); + session.Topics.AddStream(topicSelector, stringStream); + + await session.Topics.SubscribeAsync(topicSelector, cancellationToken); + + var session2 = Diffusion.Sessions.Open(serverUrl); + + var anotherStringStream = new AnotherStringStream(); + session2.Topics.AddStream(topicSelector, anotherStringStream); + + await session2.Topics.SubscribeAsync(topicSelector, cancellationToken); + + session.Close(); + session2.Close(); + } + + private sealed class StringStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, string oldValue, string newValue) + { + WriteLine($"{topicPath} changed from {oldValue ?? "NULL"} to {newValue}."); + } + } + + private sealed class AnotherStringStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, string oldValue, string newValue) + { + WriteLine($"{topicPath} changed from {oldValue ?? "NULL"} to {newValue}."); + } + } + } +} diff --git a/dotnet/examples/Wrangling/TopicViews/API/AddTopicView.cs b/dotnet/examples/Wrangling/TopicViews/API/AddTopicView.cs new file mode 100644 index 00000000..0b94e80f --- /dev/null +++ b/dotnet/examples/Wrangling/TopicViews/API/AddTopicView.cs @@ -0,0 +1,49 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Topics; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.TopicViews.API +{ + public sealed class AddTopicView : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + + string json = "{\"diffusion\":\"data\"}"; + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + var view1 = await session.TopicViews.CreateTopicViewAsync("topic_view_1", "map my/topic/path to views/", cancellationToken); + + WriteLine($"Topic View {view1.Name} has been created."); + session.Close(); + } + } +} diff --git a/dotnet/examples/Wrangling/TopicViews/API/ListTopicViews.cs b/dotnet/examples/Wrangling/TopicViews/API/ListTopicViews.cs new file mode 100644 index 00000000..bf32e2c9 --- /dev/null +++ b/dotnet/examples/Wrangling/TopicViews/API/ListTopicViews.cs @@ -0,0 +1,61 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using System.Linq; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Topics; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.TopicViews.API +{ + public sealed class ListTopicViews : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + string topic2 = "my/topic/path/array"; + + string json = "{\"diffusion\":\"data\"}"; + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + await session.TopicUpdate.AddAndSetAsync(topic2, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + var view1 = await session.TopicViews.CreateTopicViewAsync("topic_view_1", "map my/topic/path to views/", cancellationToken); + WriteLine($"Topic View '{view1.Name}' has been created."); + + var view2 = await session.TopicViews.CreateTopicViewAsync("topic_view_2", "map my/topic/path/array to views/", cancellationToken); + WriteLine($"Topic View '{view2.Name}' has been created."); + + var topicViews = await session.TopicViews.ListTopicViewsAsync(cancellationToken); + + foreach (var topicView in topicViews) + { + WriteLine($"Topic View {topicView.Name}: {topicView.Specification} ({string.Join(",", topicView.Roles.ToList())})"); + } + session.Close(); + } + } +} diff --git a/dotnet/examples/Wrangling/TopicViews/API/RemoveTopicViews.cs b/dotnet/examples/Wrangling/TopicViews/API/RemoveTopicViews.cs new file mode 100644 index 00000000..a9117090 --- /dev/null +++ b/dotnet/examples/Wrangling/TopicViews/API/RemoveTopicViews.cs @@ -0,0 +1,70 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using System.Linq; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Topics; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.TopicViews.API +{ + public sealed class RemoveTopicViews : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + string topic2 = "my/topic/path/array"; + + string json = "{\"diffusion\":\"data\"}"; + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + await session.TopicUpdate.AddAndSetAsync(topic2, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + var view1 = await session.TopicViews.CreateTopicViewAsync("topic_view_1", "map my/topic/path to views/", cancellationToken); + WriteLine($"Topic View '{view1.Name}' has been created."); + + var view2 = await session.TopicViews.CreateTopicViewAsync("topic_view_2", "map my/topic/path/array to views/", cancellationToken); + WriteLine($"Topic View '{view2.Name}' has been created."); + + var topicViews = await session.TopicViews.ListTopicViewsAsync(cancellationToken); + + foreach (var topicView in topicViews) + { + WriteLine($"Topic View {topicView.Name}: {topicView.Specification} ({string.Join(",", topicView.Roles.ToList())})"); + } + + await session.TopicViews.RemoveTopicViewAsync("topic_view_1", cancellationToken); + + topicViews = await session.TopicViews.ListTopicViewsAsync(cancellationToken); + + foreach (var topicView in topicViews) + { + WriteLine($"Topic View {topicView.Name}: {topicView.Specification} ({string.Join(",", topicView.Roles.ToList())})"); + } + session.Close(); + } + } +} diff --git a/dotnet/examples/Wrangling/TopicViews/DSL/ExpandValue.cs b/dotnet/examples/Wrangling/TopicViews/DSL/ExpandValue.cs new file mode 100644 index 00000000..3a07009b --- /dev/null +++ b/dotnet/examples/Wrangling/TopicViews/DSL/ExpandValue.cs @@ -0,0 +1,84 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using System.Collections.Generic; +using System.Linq; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Topics; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Data.JSON; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.TopicViews.DSL +{ + public sealed class ExpandValue : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + string topicSelector = "?views//"; + + string json = "{\"currencies\":[\"USD\", \"GBP\", \"EUR\", \"CHF\"]}"; + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topicSelector, jsonStream); + + await session.Topics.SubscribeAsync(topicSelector, cancellationToken); + + var view1 = await session.TopicViews.CreateTopicViewAsync("topic_view_1", "map my/topic/path to views/currency", cancellationToken); + WriteLine($"Topic View {view1.Name} has been created."); + + session.Close(); + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} diff --git a/dotnet/examples/Wrangling/TopicViews/DSL/InsertTransformations.cs b/dotnet/examples/Wrangling/TopicViews/DSL/InsertTransformations.cs new file mode 100644 index 00000000..3b169f16 --- /dev/null +++ b/dotnet/examples/Wrangling/TopicViews/DSL/InsertTransformations.cs @@ -0,0 +1,98 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using System.Collections.Generic; +using System.Linq; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Topics; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Data.JSON; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.TopicViews.DSL +{ + public sealed class InsertTransformations : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path/original_cast"; + string topic2 = "my/topic/path/additional_cast"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + string json = "[" + + " \"Fred Flintstone\", " + + " \"Wilma Flintstone\", " + + " \"Barney Rubble\", " + + " \"Betty Rubble\" " + + "]"; + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + string json2 = "[" + + " \"Pebbles Flintstone\", " + + " \"Bamm-Bamm Rubble\" " + + "]"; + await session.TopicUpdate.AddAndSetAsync(topic2, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json2), cancellationToken); + + string topicSelector = "?views//"; + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topicSelector, jsonStream); + + await session.Topics.SubscribeAsync(topicSelector, cancellationToken); + + var view1 = await session.TopicViews.CreateTopicViewAsync("topic_view_1", "map my/topic/path/original_cast to views/the_flintstones insert my/topic/path/additional_cast at /-", cancellationToken); + WriteLine($"Topic View {view1.Name} has been created."); + + session.Close(); + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} \ No newline at end of file diff --git a/dotnet/examples/Wrangling/TopicViews/DSL/OptionsDelay.cs b/dotnet/examples/Wrangling/TopicViews/DSL/OptionsDelay.cs new file mode 100644 index 00000000..a2112c7a --- /dev/null +++ b/dotnet/examples/Wrangling/TopicViews/DSL/OptionsDelay.cs @@ -0,0 +1,88 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using System.Collections.Generic; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.TopicViews.DSL +{ + public sealed class OptionsDelay : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + string topicSelector = "?.*//"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.INT64); + + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, 0, cancellationToken); + + var valueStream = new ValueStream(); + session.Topics.AddStream(topicSelector, valueStream); + + await session.Topics.SubscribeAsync(topicSelector, cancellationToken); + + var view1 = await session.TopicViews.CreateTopicViewAsync("topic_view_1", "map my/topic/path to views/ delay by 5 seconds", cancellationToken); + WriteLine($"Topic View {view1.Name} has been created."); + + for (int i = 0; i < 15; i++) + { + await session.TopicUpdate.SetAsync(topic, DateTimeOffset.Now.ToUnixTimeMilliseconds(), cancellationToken); + await Task.Delay(1000); + } + + session.Close(); + } + + private sealed class ValueStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, long? oldValue, long? newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToString())} to {(newValue == null ? "NULL" : newValue.ToString())}."); + } + } + } +} diff --git a/dotnet/examples/Wrangling/TopicViews/DSL/OptionsPreserveTopics.cs b/dotnet/examples/Wrangling/TopicViews/DSL/OptionsPreserveTopics.cs new file mode 100644 index 00000000..81451605 --- /dev/null +++ b/dotnet/examples/Wrangling/TopicViews/DSL/OptionsPreserveTopics.cs @@ -0,0 +1,100 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using System.Collections.Generic; +using System.Linq; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Data.JSON; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.TopicViews.DSL +{ + public sealed class OptionsPreserveTopics : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + string topicSelector = "?views//"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + string json = "{\"name\":\"Fred Flintstone\"}"; + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topicSelector, jsonStream); + + await session.Topics.SubscribeAsync(topicSelector, cancellationToken); + + var view1 = await session.TopicViews.CreateTopicViewAsync("topic_view_1", "map my/topic/path to views/preserved/ preserve topics", cancellationToken); + WriteLine($"Topic View {view1.Name} has been created."); + + var view2 = await session.TopicViews.CreateTopicViewAsync("topic_view_2", "map my/topic/path to views/not_preserved/", cancellationToken); + WriteLine($"Topic View {view2.Name} has been created."); + + await Task.Delay(2000); + + string json2 = "{\"name\":\"Wilma Flintstone\"}"; + await session.TopicUpdate.SetAsync(topic, Diffusion.DataTypes.JSON.FromJSONString(json2), cancellationToken); + + await Task.Delay(2000); + + string json3 = "{\"name\":\"Pebbles Flintstone\"}"; + await session.TopicUpdate.SetAsync(topic, Diffusion.DataTypes.JSON.FromJSONString(json3), cancellationToken); + + await Task.Delay(2000); + + session.Close(); + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} diff --git a/dotnet/examples/Wrangling/TopicViews/DSL/OptionsSeparator.cs b/dotnet/examples/Wrangling/TopicViews/DSL/OptionsSeparator.cs new file mode 100644 index 00000000..1ae6d363 --- /dev/null +++ b/dotnet/examples/Wrangling/TopicViews/DSL/OptionsSeparator.cs @@ -0,0 +1,89 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using System.Collections.Generic; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Data.JSON; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.TopicViews.DSL +{ + public sealed class OptionsSeparator : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topicSelector = "?views//"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + string json = "{\"name\":\"Fred/Flintstone\"}"; + await session.TopicUpdate.AddAndSetAsync("my/topic/path/1", topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + string json2 = "{\"name\":\"Wilma/Flintstone\"}"; + await session.TopicUpdate.AddAndSetAsync("my/topic/path/2", topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + string json3 = "{\"name\":\"Pebbles/Flintstone\"}"; + await session.TopicUpdate.AddAndSetAsync("my/topic/path/3", topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topicSelector, jsonStream); + + await session.Topics.SubscribeAsync(topicSelector, cancellationToken); + + var view1 = await session.TopicViews.CreateTopicViewAsync("topic_view_1", "map ?my/topic/path// to views/ separator '_'", cancellationToken); + WriteLine($"Topic View {view1.Name} has been created."); + + session.Close(); + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} diff --git a/dotnet/examples/Wrangling/TopicViews/DSL/OptionsThrottle.cs b/dotnet/examples/Wrangling/TopicViews/DSL/OptionsThrottle.cs new file mode 100644 index 00000000..b15fb9ca --- /dev/null +++ b/dotnet/examples/Wrangling/TopicViews/DSL/OptionsThrottle.cs @@ -0,0 +1,88 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using System.Collections.Generic; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.TopicViews.DSL +{ + public sealed class OptionsThrottle : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + string topicSelector = "?.*//"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.INT64); + + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, 0, cancellationToken); + + var valueStream = new ValueStream(); + session.Topics.AddStream(topicSelector, valueStream); + + await session.Topics.SubscribeAsync(topicSelector, cancellationToken); + + var view1 = await session.TopicViews.CreateTopicViewAsync("topic_view_1", "map my/topic/path to views/ throttle to 1 update every 3 seconds", cancellationToken); + WriteLine($"Topic View {view1.Name} has been created."); + + for (int i = 0; i < 15; i++) + { + await session.TopicUpdate.SetAsync(topic, DateTimeOffset.Now.ToUnixTimeMilliseconds(), cancellationToken); + await Task.Delay(1000); + } + + session.Close(); + } + + private sealed class ValueStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, long? oldValue, long? newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToString())} to {(newValue == null ? "NULL" : newValue.ToString())}."); + } + } + } +} diff --git a/dotnet/examples/Wrangling/TopicViews/DSL/OptionsTopicPropertyMapping.cs b/dotnet/examples/Wrangling/TopicViews/DSL/OptionsTopicPropertyMapping.cs new file mode 100644 index 00000000..baf97030 --- /dev/null +++ b/dotnet/examples/Wrangling/TopicViews/DSL/OptionsTopicPropertyMapping.cs @@ -0,0 +1,90 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using System.Collections.Generic; +using System.Linq; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Data.JSON; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.TopicViews.DSL +{ + public sealed class OptionsTopicPropertyMapping : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + string topicSelector = "?views//"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + string json = "[" + + " \"Fred Flintstone\", " + + " \"Wilma Flintstone\", " + + " \"Barney Rubble\", " + + " \"Betty Rubble\" " + + "]"; + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topicSelector, jsonStream); + + await session.Topics.SubscribeAsync(topicSelector, cancellationToken); + + var view1 = await session.TopicViews.CreateTopicViewAsync("topic_view_1", "map ?my/topic/path// to views/ with properties 'CONFLATION':'off', 'COMPRESSION':'false', 'DONT_RETAIN_VALUE':'true'", cancellationToken); + WriteLine($"Topic View {view1.Name} has been created."); + + session.Close(); + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} diff --git a/dotnet/examples/Wrangling/TopicViews/DSL/OptionsTopicType.cs b/dotnet/examples/Wrangling/TopicViews/DSL/OptionsTopicType.cs new file mode 100644 index 00000000..c50a4763 --- /dev/null +++ b/dotnet/examples/Wrangling/TopicViews/DSL/OptionsTopicType.cs @@ -0,0 +1,69 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Topics; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; +using System.Linq; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.TopicViews.DSL +{ + public sealed class OptionsTopicType : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.INT64); + + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, 0, cancellationToken); + + var view1 = await session.TopicViews.CreateTopicViewAsync("topic_view_1", "map my/topic/path to views/archive/ type TIME_SERIES", cancellationToken); + WriteLine($"Topic View {view1.Name} has been created."); + + for (int i = 0; i < 15; i++) + { + await session.TopicUpdate.SetAsync(topic, DateTimeOffset.Now.ToUnixTimeMilliseconds(), cancellationToken); + await Task.Delay(1000); + } + + var rangeQuery = session.TimeSeries.RangeQuery.As(); + + var queryResult = await rangeQuery + .From(0) + .SelectFromAsync("views/archive/my/topic/path", cancellationToken); + + var results = queryResult.Events.ToList(); + + foreach (var result in results) + { + WriteLine($"{result.Metadata.Sequence} ({result.Metadata.Timestamp}): {result.Value}"); + } + + session.Close(); + } + } +} diff --git a/dotnet/examples/Wrangling/TopicViews/DSL/OptionsTopicValue.cs b/dotnet/examples/Wrangling/TopicViews/DSL/OptionsTopicValue.cs new file mode 100644 index 00000000..e251ead1 --- /dev/null +++ b/dotnet/examples/Wrangling/TopicViews/DSL/OptionsTopicValue.cs @@ -0,0 +1,85 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using System.Collections.Generic; +using System.Linq; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Data.JSON; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.TopicViews.DSL +{ + public sealed class OptionsTopicValue : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + string topicSelector = "?views//"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + string json = "{\"account\":\"1234\",\"balance\":{\"amount\":12.57,\"currency\":\"USD\"}}"; + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topicSelector, jsonStream); + + await session.Topics.SubscribeAsync(topicSelector, cancellationToken); + + var view1 = await session.TopicViews.CreateTopicViewAsync("topic_view_1", "map my/topic/path to views/ as ", cancellationToken); + WriteLine($"Topic View {view1.Name} has been created."); + + session.Close(); + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} diff --git a/dotnet/examples/Wrangling/TopicViews/DSL/PatchTransformationsAdd.cs b/dotnet/examples/Wrangling/TopicViews/DSL/PatchTransformationsAdd.cs new file mode 100644 index 00000000..cca01d8b --- /dev/null +++ b/dotnet/examples/Wrangling/TopicViews/DSL/PatchTransformationsAdd.cs @@ -0,0 +1,90 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using System.Collections.Generic; +using System.Linq; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Data.JSON; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.TopicViews.DSL +{ + public sealed class PatchTransformationsAdd : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + string topicSelector = "?views//"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + string json = "{\"Fred\":\"Flintstone\",\"Barney\":\"Rubble\"}"; + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topicSelector, jsonStream); + + await session.Topics.SubscribeAsync(topicSelector, cancellationToken); + + var view1 = await session.TopicViews.CreateTopicViewAsync("topic_view_1", + "map ?my/topic/path// to views/ patch '[" + + "{\"op\": \"add\", \"path\": \"/George\", \"value\": \"Jetson\"}" + + "]'", + cancellationToken); + + WriteLine($"Topic View {view1.Name} has been created."); + + session.Close(); + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} diff --git a/dotnet/examples/Wrangling/TopicViews/DSL/PatchTransformationsCopy.cs b/dotnet/examples/Wrangling/TopicViews/DSL/PatchTransformationsCopy.cs new file mode 100644 index 00000000..3ff55c2a --- /dev/null +++ b/dotnet/examples/Wrangling/TopicViews/DSL/PatchTransformationsCopy.cs @@ -0,0 +1,85 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using System.Collections.Generic; +using System.Linq; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Data.JSON; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.TopicViews.DSL +{ + public sealed class PatchTransformationsCopy : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + string topicSelector = "?views//"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + string json = "{ \"Meet the Flintstones\": {\"Fred\":\"Flintstone\",\"Barney\":\"Rubble\"}, \"The Jetsons\": {\"George\":\"Jetson\"}}"; + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topicSelector, jsonStream); + + await session.Topics.SubscribeAsync(topicSelector, cancellationToken); + + var view1 = await session.TopicViews.CreateTopicViewAsync("topic_view_1", "map ?my/topic/path// to views/ patch '[ {\"op\": \"copy\", \"from\": \"/Meet the Flintstones/Fred\", \"path\": \"/The Jetsons/Fred\" }]'", cancellationToken); + WriteLine($"Topic View {view1.Name} has been created."); + + session.Close(); + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} diff --git a/dotnet/examples/Wrangling/TopicViews/DSL/PatchTransformationsMove.cs b/dotnet/examples/Wrangling/TopicViews/DSL/PatchTransformationsMove.cs new file mode 100644 index 00000000..71164c3b --- /dev/null +++ b/dotnet/examples/Wrangling/TopicViews/DSL/PatchTransformationsMove.cs @@ -0,0 +1,90 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using System.Collections.Generic; +using System.Linq; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Data.JSON; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.TopicViews.DSL +{ + public sealed class PatchTransformationsMove : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + string topicSelector = "?views//"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + string json = "{\"Fred\":\"Flintstone\",\"Barney\":\"Rubble\",\"George\":\"Jetson\"}"; + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topicSelector, jsonStream); + + await session.Topics.SubscribeAsync(topicSelector, cancellationToken); + + var view1 = await session.TopicViews.CreateTopicViewAsync("topic_view_1", + "map ?my/topic/path// to views/ patch '[ " + + "{\"op\": \"move\", \"from\": \"/Fred\", \"path\": \"/Meet The Flintstones~1Fred\" }, " + + "{\"op\": \"move\", \"from\": \"/Barney\", \"path\": \"/Meet The Flintstones~1Barney\" }, " + + "{\"op\": \"move\", \"from\": \"/George\", \"path\": \"/The Jetsons~1George\" }]'", cancellationToken); + + WriteLine($"Topic View {view1.Name} has been created."); + + session.Close(); + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} diff --git a/dotnet/examples/Wrangling/TopicViews/DSL/PatchTransformationsRemove.cs b/dotnet/examples/Wrangling/TopicViews/DSL/PatchTransformationsRemove.cs new file mode 100644 index 00000000..9804ac1b --- /dev/null +++ b/dotnet/examples/Wrangling/TopicViews/DSL/PatchTransformationsRemove.cs @@ -0,0 +1,85 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using System.Collections.Generic; +using System.Linq; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Data.JSON; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.TopicViews.DSL +{ + public sealed class PatchTransformationsRemove : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + string topicSelector = "?views//"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + string json = "{\"Fred\":\"Flintstone\",\"Barney\":\"Rubble\",\"George\":\"Jetson\"}"; + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topicSelector, jsonStream); + + await session.Topics.SubscribeAsync(topicSelector, cancellationToken); + + var view1 = await session.TopicViews.CreateTopicViewAsync("topic_view_1", "map ?my/topic/path// to views/ patch '[{\"op\": \"remove\", \"path\": \"/George\"}]'", cancellationToken); + WriteLine($"Topic View {view1.Name} has been created."); + + session.Close(); + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} diff --git a/dotnet/examples/Wrangling/TopicViews/DSL/PatchTransformationsReplace.cs b/dotnet/examples/Wrangling/TopicViews/DSL/PatchTransformationsReplace.cs new file mode 100644 index 00000000..db558c2d --- /dev/null +++ b/dotnet/examples/Wrangling/TopicViews/DSL/PatchTransformationsReplace.cs @@ -0,0 +1,85 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using System.Collections.Generic; +using System.Linq; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Data.JSON; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.TopicViews.DSL +{ + public sealed class PatchTransformationsReplace : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + string topicSelector = "?views//"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + string json = "{\"Fred\":\"Flintstone\",\"Barney\":\"Rubble\",\"George\":\"Jetson\"}"; + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topicSelector, jsonStream); + + await session.Topics.SubscribeAsync(topicSelector, cancellationToken); + + var view1 = await session.TopicViews.CreateTopicViewAsync("topic_view_1", "map ?my/topic/path// to views/ patch '[{\"op\": \"replace\", \"path\": \"/George\", \"value\": \"Bedrock\"}]'", cancellationToken); + WriteLine($"Topic View {view1.Name} has been created."); + + session.Close(); + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} diff --git a/dotnet/examples/Wrangling/TopicViews/DSL/PatchTransformationsTest.cs b/dotnet/examples/Wrangling/TopicViews/DSL/PatchTransformationsTest.cs new file mode 100644 index 00000000..4006dd24 --- /dev/null +++ b/dotnet/examples/Wrangling/TopicViews/DSL/PatchTransformationsTest.cs @@ -0,0 +1,85 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using System.Collections.Generic; +using System.Linq; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Data.JSON; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.TopicViews.DSL +{ + public sealed class PatchTransformationsTest : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + string topicSelector = "?views//"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + string json = "{\"Fred\":\"Flintstone\",\"Wilma\":\"Flintstone\",\"Barney\":\"Rubble\",\"Betty\":\"Rubble\"}"; + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topicSelector, jsonStream); + + await session.Topics.SubscribeAsync(topicSelector, cancellationToken); + + var view1 = await session.TopicViews.CreateTopicViewAsync("topic_view_1", "map ?my/topic/path// to views/ patch '[{\"op\": \"test\", \"path\": \"/Fred\", \"value\": \"Flintstone\" }]'", cancellationToken); + WriteLine($"Topic View {view1.Name} has been created."); + + session.Close(); + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} diff --git a/dotnet/examples/Wrangling/TopicViews/DSL/ProcessTransformationsContinue.cs b/dotnet/examples/Wrangling/TopicViews/DSL/ProcessTransformationsContinue.cs new file mode 100644 index 00000000..57c33024 --- /dev/null +++ b/dotnet/examples/Wrangling/TopicViews/DSL/ProcessTransformationsContinue.cs @@ -0,0 +1,89 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using System.Collections.Generic; +using System.Linq; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Data.JSON; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.TopicViews.DSL +{ + public sealed class ProcessTransformationsContinue : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path/1"; + string topic2 = "my/topic/path/2"; + string topicSelector = "?views//"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + string json = "{\"name\":\"APPL\",\"quantity\":100,\"price_per_share\":12.34}"; + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + string json2 = "{\"name\":\"AMZN\",\"quantity\":256,\"price_per_share\":87.65}"; + await session.TopicUpdate.AddAndSetAsync(topic2, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json2), cancellationToken); + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topicSelector, jsonStream); + + await session.Topics.SubscribeAsync(topicSelector, cancellationToken); + + var view1 = await session.TopicViews.CreateTopicViewAsync("topic_view_1", "map ?my/topic/path// to views/ process {if '/price_per_share > 20' continue}", cancellationToken); + WriteLine($"Topic View {view1.Name} has been created."); + + session.Close(); + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} diff --git a/dotnet/examples/Wrangling/TopicViews/DSL/ProcessTransformationsRemove.cs b/dotnet/examples/Wrangling/TopicViews/DSL/ProcessTransformationsRemove.cs new file mode 100644 index 00000000..9ead23ea --- /dev/null +++ b/dotnet/examples/Wrangling/TopicViews/DSL/ProcessTransformationsRemove.cs @@ -0,0 +1,89 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using System.Collections.Generic; +using System.Linq; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Data.JSON; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.TopicViews.DSL +{ + public sealed class ProcessTransformationsRemove : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path/1"; + string topic2 = "my/topic/path/2"; + string topicSelector = "?views//"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + string json = "{\"name\":\"APPL\",\"quantity\":100,\"price_per_share\":12.34}"; + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + string json2 = "{\"name\":\"AMZN\",\"quantity\":256,\"price_per_share\":87.65}"; + await session.TopicUpdate.AddAndSetAsync(topic2, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json2), cancellationToken); + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topicSelector, jsonStream); + + await session.Topics.SubscribeAsync(topicSelector, cancellationToken); + + var view1 = await session.TopicViews.CreateTopicViewAsync("topic_view_1", "map ?my/topic/path// to views/ process {set(/total, calc '/quantity * /price_per_share'); remove(/quantity); remove(/price_per_share)}", cancellationToken); + WriteLine($"Topic View {view1.Name} has been created."); + + session.Close(); + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} diff --git a/dotnet/examples/Wrangling/TopicViews/DSL/ProcessTransformationsSet.cs b/dotnet/examples/Wrangling/TopicViews/DSL/ProcessTransformationsSet.cs new file mode 100644 index 00000000..5244e7a5 --- /dev/null +++ b/dotnet/examples/Wrangling/TopicViews/DSL/ProcessTransformationsSet.cs @@ -0,0 +1,89 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using System.Collections.Generic; +using System.Linq; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Data.JSON; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.TopicViews.DSL +{ + public sealed class ProcessTransformationsSet : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path/1"; + string topic2 = "my/topic/path/2"; + string topicSelector = "?views//"; + + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + + string json = "{\"account\":\"1234\",\"balance\":{\"amount\":12.57,\"currency\":\"USD\"}}"; + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + string json2 = "{\"account\":\"5678\",\"balance\":{\"amount\":98.76,\"currency\":\"USD\"}}"; + await session.TopicUpdate.AddAndSetAsync(topic2, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json2), cancellationToken); + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topicSelector, jsonStream); + + await session.Topics.SubscribeAsync(topicSelector, cancellationToken); + + var view1 = await session.TopicViews.CreateTopicViewAsync("topic_view_1", "map ?my/topic/path// to views/ process {if '/balance/amount > 20' set(/tier, 1) else set(/tier, 2)} process {set(/balance/amount_in_cents, calc '/balance/amount * 100')}", cancellationToken); + WriteLine($"Topic View {view1.Name} has been created."); + + session.Close(); + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} diff --git a/dotnet/examples/Wrangling/TopicViews/DSL/RemoteTopicViews.cs b/dotnet/examples/Wrangling/TopicViews/DSL/RemoteTopicViews.cs new file mode 100644 index 00000000..a3062e29 --- /dev/null +++ b/dotnet/examples/Wrangling/TopicViews/DSL/RemoteTopicViews.cs @@ -0,0 +1,61 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using PushTechnology.ClientInterface.Client.Factories; +using static System.Console; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Features.Control.Clients; +using System.Collections.Generic; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.TopicViews.DSL +{ + public sealed class RemoteTopicViews : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + IRemoteServer server = null; + + var builder = (ISecondaryInitiatorBuilder)Diffusion.NewRemoteServerBuilder(RemoteServerType.SECONDARY_INITIATOR); + var secondaryInitiator = builder + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .ConnectionOptions(new Dictionary() + { + { RemoteServerConnectionOption.RECONNECTION_TIMEOUT, "120000" }, + { RemoteServerConnectionOption.MAXIMUM_QUEUE_SIZE, "1000" }, + { RemoteServerConnectionOption.CONNECTION_TIMEOUT, "15000" } + }) + .Build("Remote Server 1", "ws://new.server.url.com"); + + server = await session.RemoteServers.CreateRemoteServerAsync(secondaryInitiator, cancellationToken); + WriteLine($"Remote server {server.Name} has been created."); + + var view1 = await session.TopicViews.CreateTopicViewAsync("topic_view_1", "map my/topic/path from 'Remote Server 1' to views/remote/", cancellationToken); + WriteLine($"Remote Topic View {view1.Name} has been created."); + + session.Close(); + } + } +} diff --git a/dotnet/examples/Wrangling/TopicViews/DSL/ScalarDirective.cs b/dotnet/examples/Wrangling/TopicViews/DSL/ScalarDirective.cs new file mode 100644 index 00000000..76e64dc4 --- /dev/null +++ b/dotnet/examples/Wrangling/TopicViews/DSL/ScalarDirective.cs @@ -0,0 +1,84 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using static System.Console; +using System.Collections.Generic; +using System.Linq; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Data.JSON; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.TopicViews.DSL +{ + public sealed class ScalarDirective : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "my/topic/path"; + string topicSelector = "?views//"; + + string json = "{\"account\":\"1234\",\"balance\":{\"amount\":12.57,\"currency\":\"USD\"}}"; + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topicSelector, jsonStream); + + await session.Topics.SubscribeAsync(topicSelector, cancellationToken); + + var view1 = await session.TopicViews.CreateTopicViewAsync("topic_view_1", "map my/topic/path to views/currency//account/", cancellationToken); + WriteLine($"Topic View {view1.Name} has been created."); + + session.Close(); + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} diff --git a/dotnet/examples/Wrangling/TopicViews/DSL/SourcePathDirective.cs b/dotnet/examples/Wrangling/TopicViews/DSL/SourcePathDirective.cs new file mode 100644 index 00000000..d034fbd3 --- /dev/null +++ b/dotnet/examples/Wrangling/TopicViews/DSL/SourcePathDirective.cs @@ -0,0 +1,90 @@ +/** + * Copyright © 2023 - 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; +using System.Collections.Generic; +using System.Linq; +using static System.Console; +using PushTechnology.ClientInterface.Client.Factories; +using PushTechnology.ClientInterface.Client.Features; +using PushTechnology.ClientInterface.Client.Topics; +using static PushTechnology.ClientInterface.Examples.Program; +using PushTechnology.ClientInterface.Client.Callbacks; +using PushTechnology.ClientInterface.Client.Features.Topics; +using PushTechnology.ClientInterface.Client.Topics.Details; +using PushTechnology.ClientInterface.Data.JSON; + +namespace PushTechnology.ClientInterface.Examples.Wrangling.TopicViews.DSL +{ + public sealed class SourcePathDirective : Example + { + public override async Task Run(CancellationToken cancellationToken, string[] args) + { + string serverUrl = args[0]; + + var session = Diffusion.Sessions + .Principal("admin") + .Credentials(Diffusion.Credentials.Password("password")) + .Open(serverUrl); + + string topic = "a/b/c/d/e/f/g"; + string topicSelector = "?views//"; + + string json = "{\"account\":\"1234\",\"balance\":{\"amount\":12.57,\"currency\":\"USD\"}}"; + var topicSpecification = Diffusion.NewSpecification(TopicType.JSON); + await session.TopicUpdate.AddAndSetAsync(topic, topicSpecification, Diffusion.DataTypes.JSON.FromJSONString(json), cancellationToken); + + var jsonStream = new JSONStream(); + session.Topics.AddStream(topicSelector, jsonStream); + + await session.Topics.SubscribeAsync(topicSelector, cancellationToken); + + var view1 = await session.TopicViews.CreateTopicViewAsync("topic_view_1", "map a/b/c/d/e/f/g to views/", cancellationToken); + WriteLine($"Topic View {view1.Name} has been created."); + + var view2 = await session.TopicViews.CreateTopicViewAsync("topic_view_2", "map a/b/c/d/e/f/g to views/", cancellationToken); + WriteLine($"Topic View {view2.Name} has been created."); + + var view3 = await session.TopicViews.CreateTopicViewAsync("topic_view_3", "map a/b/c/d/e/f/g to views/", cancellationToken); + WriteLine($"Topic View {view3.Name} has been created."); + + session.Close(); + } + + private sealed class JSONStream : IValueStream + { + public void OnClose() {} + + public void OnError(ErrorReason errorReason) {} + + public void OnSubscription(string topicPath, ITopicSpecification specification) + { + WriteLine($"Subscribed to {topicPath}."); + } + + public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) + { + WriteLine($"Unsubscribed from {topicPath}: {reason}."); + } + + public void OnValue(string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue) + { + WriteLine($"{topicPath} changed from {(oldValue == null ? "NULL" : oldValue.ToJSONString())} to {newValue.ToJSONString()}."); + } + } + } +} diff --git a/dotnet/examples/sdk-examples.csproj b/dotnet/examples/sdk-examples.csproj new file mode 100644 index 00000000..4f2cd429 --- /dev/null +++ b/dotnet/examples/sdk-examples.csproj @@ -0,0 +1,33 @@ + + + Exe + net8.0 + false + PushTechnology.ClientInterface.Example + + + + ..\ + 7.2 + + + + ..\ + 7.2 + + + + + + + + + + + + + ..\Diffusion.Client.dll + + + + diff --git a/dotnet/sdk-examples.sln b/dotnet/sdk-examples.sln new file mode 100644 index 00000000..3edaa604 --- /dev/null +++ b/dotnet/sdk-examples.sln @@ -0,0 +1,38 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.5.33530.505 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{763F9EE6-7FFE-4C70-B60E-D43BC722DBAA}" + ProjectSection(SolutionItems) = preProject + ..\..\README.md = ..\..\README.md + EndProjectSection +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "sdk-examples", "examples\sdk-examples.csproj", "{CBF74249-5CA0-4D0D-90EE-587287C73A98}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Source", "Source", "{DBFCDCF9-51BB-4439-989F-E02002FE0C46}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Examples", "Examples", "{E40E1A3D-ABCA-4A38-B18C-A0B613AE31A8}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {CBF74249-5CA0-4D0D-90EE-587287C73A98}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CBF74249-5CA0-4D0D-90EE-587287C73A98}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CBF74249-5CA0-4D0D-90EE-587287C73A98}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CBF74249-5CA0-4D0D-90EE-587287C73A98}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {CBF74249-5CA0-4D0D-90EE-587287C73A98} = {E40E1A3D-ABCA-4A38-B18C-A0B613AE31A8} + {E40E1A3D-ABCA-4A38-B18C-A0B613AE31A8} = {DBFCDCF9-51BB-4439-989F-E02002FE0C46} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {F1ADC674-176F-48A6-BF05-36E4DADDB58F} + EndGlobalSection +EndGlobal diff --git a/dotnet/source/examples/Consuming/BinaryTopics.cs b/dotnet/source/examples/Consuming/BinaryTopics.cs deleted file mode 100644 index cdf312b1..00000000 --- a/dotnet/source/examples/Consuming/BinaryTopics.cs +++ /dev/null @@ -1,118 +0,0 @@ -/** - * Copyright © 2018, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features; -using PushTechnology.ClientInterface.Client.Features.Topics; -using PushTechnology.ClientInterface.Client.Topics.Details; -using PushTechnology.ClientInterface.Data.Binary; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Consuming { - /// - /// Implementation of a client which subscribes to a binary topic and consumes the data it receives. - /// - public sealed class ConsumingBinaryTopics : IExample { - /// - /// Runs the binary topic consuming client example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string serverUrl = args[ 0 ]; - - // Connect anonymously - var session = Diffusion.Sessions.Open( serverUrl ); - - // Get the Topics feature to subscribe to topics - var topics = session.Topics; - string topic = "random/Binary"; - - // Add a topic stream for 'random/Binary' - var binaryStream = new BinaryStream(); - topics.AddStream( topic, binaryStream ); - - try { - // Subscribe to 'random/Binary' topic - await topics.SubscribeAsync( topic, cancellationToken ); - - // Run until user requests ending of example - await Task.Delay( Timeout.Infinite, cancellationToken ); - } catch ( TaskCanceledException ) { - //Task was canceled; close stream and unsubscribe - topics.RemoveStream( binaryStream ); - await topics.UnsubscribeAsync( topic ); - } finally { - // Note that closing the session, will automatically unsubscribe from all topics the client is - // subscribed to. - session.Close(); - } - } - - /// - /// Basic implementation of the IValueStream for binary topics. - /// - private sealed class BinaryStream : IValueStream { - /// - /// Notification of stream being closed normally. - /// - public void OnClose() - => WriteLine( "The subscrption stream is now closed." ); - - /// - /// Notification of a contextual error related to this callback. - /// - /// - /// Situations in which OnError is called include the session being closed, a communication - /// timeout, or a problem with the provided parameters. No further calls will be made to this callback. - /// - /// Error reason. - public void OnError( ErrorReason errorReason ) - => WriteLine( $"An error has occured : {errorReason}." ); - - /// - /// Notification of a successful subscription. - /// - /// Topic path. - /// Topic specification. - public void OnSubscription( string topicPath, ITopicSpecification specification ) - => WriteLine( $"Client subscribed to topic '{topicPath}'." ); - - /// - /// Notification of a successful unsubscription. - /// - /// Topic path. - /// Topic specification. - /// Error reason. - public void OnUnsubscription( string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason ) - => WriteLine( $"Client unsubscribed from topic '{topicPath}' with reason '{reason}'." ); - - /// - /// Topic update received. - /// - /// Topic path. - /// Topic specification. - /// Value prior to update. - /// Value after update. - public void OnValue( string topicPath, ITopicSpecification specification, IBinary oldValue, IBinary newValue ) - => WriteLine( $"New value of topic '{topicPath}' is {Encoding.UTF8.GetString( newValue.ToByteArray() )}." ); - } - } -} diff --git a/dotnet/source/examples/Consuming/Consuming.projitems b/dotnet/source/examples/Consuming/Consuming.projitems deleted file mode 100644 index 092af5a8..00000000 --- a/dotnet/source/examples/Consuming/Consuming.projitems +++ /dev/null @@ -1,23 +0,0 @@ - - - - $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - true - 6e978dc0-d636-4883-b0d8-4ba93667865c - - - PushTechnology.ClientInterface.Example.Consuming - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dotnet/source/examples/Consuming/Consuming.shproj b/dotnet/source/examples/Consuming/Consuming.shproj deleted file mode 100644 index c76700a3..00000000 --- a/dotnet/source/examples/Consuming/Consuming.shproj +++ /dev/null @@ -1,13 +0,0 @@ - - - - 6e978dc0-d636-4883-b0d8-4ba93667865c - 14.0 - - - - - - - - diff --git a/dotnet/source/examples/Consuming/DoubleTopics.cs b/dotnet/source/examples/Consuming/DoubleTopics.cs deleted file mode 100644 index b78b6894..00000000 --- a/dotnet/source/examples/Consuming/DoubleTopics.cs +++ /dev/null @@ -1,116 +0,0 @@ -/** - * Copyright © 2018, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features; -using PushTechnology.ClientInterface.Client.Features.Topics; -using PushTechnology.ClientInterface.Client.Topics.Details; -using static PushTechnology.ClientInterface.Examples.Runner.Program; -using static System.Console; - -namespace PushTechnology.ClientInterface.Example.Consuming { - /// - /// Implementation of a client which subscribes to a double topic and consumes the data it receives. - /// - public sealed class ConsumingDoubleTopics : IExample { - /// - /// Runs the double topic client example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string serverUrl = args[ 0 ]; - - // Connect anonymously - var session = Diffusion.Sessions.Open( serverUrl ); - - // Get the Topics feature to subscribe to topics - var topics = session.Topics; - string topic = "random/Double"; - - // Add a topic stream for 'random/Double' - var doubleStream = new DoubleStream(); - topics.AddStream( topic, doubleStream ); - - try { - // Subscribe to 'random/Double' topic - await topics.SubscribeAsync( topic, cancellationToken ); - - // Run until user requests ending of example - await Task.Delay( Timeout.Infinite, cancellationToken ); - } catch ( TaskCanceledException ) { - //Task was canceled; close stream and unsubscribe - topics.RemoveStream( doubleStream ); - await topics.UnsubscribeAsync( topic ); - } finally { - // Note that closing the session, will automatically unsubscribe from all topics the client is - // subscribed to. - session.Close(); - } - } - - /// - /// Basic implementation of the IValueStream for Double topics. - /// - private sealed class DoubleStream : IValueStream { - /// - /// Notification of stream being closed normally. - /// - public void OnClose() - => WriteLine( "The subscrption stream is now closed." ); - - /// - /// Notification of a contextual error related to this callback. - /// - /// - /// Situations in which OnError is called include the session being closed, a communication - /// timeout, or a problem with the provided parameters. No further calls will be made to this callback. - /// - /// Error reason. - public void OnError( ErrorReason errorReason ) - => WriteLine( $"An error has occured : {errorReason}." ); - - /// - /// Notification of a successful subscription. - /// - /// Topic path. - /// Topic specification. - public void OnSubscription( string topicPath, ITopicSpecification specification ) - => WriteLine( $"Client subscribed to topic '{topicPath}'." ); - - /// - /// Notification of a successful unsubscription. - /// - /// Topic path. - /// Topic specification. - /// Error reason. - public void OnUnsubscription( string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason ) - => WriteLine( $"Client unsubscribed from topic '{topicPath}' with reason '{reason}'." ); - - /// - /// Topic update received. - /// - /// Topic path. - /// Topic specification. - /// Value prior to update. - /// Value after update. - public void OnValue( string topicPath, ITopicSpecification specification, double? oldValue, double? newValue ) - => WriteLine( $"New value of topic '{topicPath}' is {newValue}." ); - } - } -} diff --git a/dotnet/source/examples/Consuming/FilterRequestMessages.cs b/dotnet/source/examples/Consuming/FilterRequestMessages.cs deleted file mode 100644 index 4f10a15e..00000000 --- a/dotnet/source/examples/Consuming/FilterRequestMessages.cs +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Copyright © 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Consuming { - /// - /// Client implementation that listens for messages on a topic path. - /// - public sealed class ReceivingFilterRequestMessages : IExample { - /// - /// Runs the client receiving messages example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - var serverUrl = args[ 0 ]; - var session = Diffusion.Sessions.Principal( "client" ).Password( "password" ).Open( serverUrl ); - var messaging = session.Messaging; - var messagingPath = ">random/requestResponse"; - - var requestStream = new SimpleRequestStream(); - messaging.SetRequestStream( messagingPath, requestStream ); - - try { - await Task.Delay( Timeout.InfiniteTimeSpan, cancellationToken ); - } finally { - // Close session - messaging.RemoveRequestStream( messagingPath ); - session.Close(); - } - } - - /// - /// A simple IRequestStream implementation that prints confirmation of the actions completed. - /// - private class SimpleRequestStream : IRequestStream { - /// - /// Indicates that the request stream was closed. - /// - public void OnClose() - => WriteLine( "A request handler was closed." ); - - /// - /// Indicates that the request stream has received error. - /// - public void OnError( ErrorReason errorReason ) - => WriteLine( $"A request handler has received error: {errorReason}." ); - - /// - /// Indicates that a request was received and responds to it. - /// - /// On invalid request you would call: . - public void OnRequest( string path, string request, IResponder responder ) { - WriteLine( $"Received request: '{request}'." ); - responder.Respond( DateTime.UtcNow.ToLongTimeString() ); - } - } - } -} diff --git a/dotnet/source/examples/Consuming/IntegerTopics.cs b/dotnet/source/examples/Consuming/IntegerTopics.cs deleted file mode 100644 index a42ca419..00000000 --- a/dotnet/source/examples/Consuming/IntegerTopics.cs +++ /dev/null @@ -1,116 +0,0 @@ -/** - * Copyright © 2018, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features; -using PushTechnology.ClientInterface.Client.Features.Topics; -using PushTechnology.ClientInterface.Client.Topics.Details; -using static PushTechnology.ClientInterface.Examples.Runner.Program; -using static System.Console; - -namespace PushTechnology.ClientInterface.Example.Consuming { - /// - /// Implementation of a client which subscribes to a integer topic and consumes the data it receives. - /// - public sealed class ConsumingIntegerTopics : IExample { - /// - /// Runs the integer topic client example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string serverUrl = args[ 0 ]; - - // Connect anonymously - var session = Diffusion.Sessions.Open( serverUrl ); - - // Get the Topics feature to subscribe to topics - var topics = session.Topics; - string topic = "random/Integer"; - - // Add a topic stream for 'random/Integer' - var integerStream = new IntegerStream(); - topics.AddStream( topic, integerStream ); - - try { - // Subscribe to 'random/Integer' topic - await topics.SubscribeAsync( topic, cancellationToken ); - - // Run until user requests ending of example - await Task.Delay( Timeout.Infinite, cancellationToken ); - } catch ( TaskCanceledException ) { - //Task was canceled; close stream and unsubscribe - topics.RemoveStream( integerStream ); - await topics.UnsubscribeAsync( topic ); - } finally { - // Note that closing the session, will automatically unsubscribe from all topics the client is - // subscribed to. - session.Close(); - } - } - - /// - /// Basic implementation of the IValueStream for Integer topics. - /// - private sealed class IntegerStream : IValueStream { - /// - /// Notification of stream being closed normally. - /// - public void OnClose() - => WriteLine( "The subscrption stream is now closed." ); - - /// - /// Notification of a contextual error related to this callback. - /// - /// - /// Situations in which OnError is called include the session being closed, a communication - /// timeout, or a problem with the provided parameters. No further calls will be made to this callback. - /// - /// Error reason. - public void OnError( ErrorReason errorReason ) - => WriteLine( $"An error has occured : {errorReason}." ); - - /// - /// Notification of a successful subscription. - /// - /// Topic path. - /// Topic specification. - public void OnSubscription( string topicPath, ITopicSpecification specification ) - => WriteLine( $"Client subscribed to topic '{topicPath}'." ); - - /// - /// Notification of a successful unsubscription. - /// - /// Topic path. - /// Topic specification. - /// Error reason. - public void OnUnsubscription( string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason ) - => WriteLine( $"Client unsubscribed from topic '{topicPath}' with reason '{reason}'." ); - - /// - /// Topic update received. - /// - /// Topic path. - /// Topic specification. - /// Value prior to update. - /// Value after update. - public void OnValue( string topicPath, ITopicSpecification specification, long? oldValue, long? newValue ) - => WriteLine( $"New value of topic '{topicPath}' is {newValue}." ); - } - } -} diff --git a/dotnet/source/examples/Consuming/JSONTopics.cs b/dotnet/source/examples/Consuming/JSONTopics.cs deleted file mode 100644 index 6550c01b..00000000 --- a/dotnet/source/examples/Consuming/JSONTopics.cs +++ /dev/null @@ -1,118 +0,0 @@ -/** - * Copyright © 2016, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features; -using PushTechnology.ClientInterface.Client.Features.Topics; -using PushTechnology.ClientInterface.Client.Topics.Details; -using PushTechnology.ClientInterface.Data.JSON; -using static PushTechnology.ClientInterface.Examples.Runner.Program; -using static System.Console; - -namespace PushTechnology.ClientInterface.Example.Consuming { - /// - /// Implementation of a client which subscribes to a JSON topic and consumes the data it receives. - /// - public sealed class ConsumingJSONTopics : IExample { - /// - /// Runs the JSON topic client example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string serverUrl = args[ 0 ]; - - // Connect anonymously - var session = Diffusion.Sessions.Open( serverUrl ); - - // Get the Topics feature to subscribe to topics - var topics = session.Topics; - string topic = "random/JSON"; - - // Add a topic stream for 'random/JSON' - var jsonStream = new JSONStream(); - topics.AddStream( topic, jsonStream ); - - try { - // Subscribe to 'random/JSON' topic - await topics.SubscribeAsync( topic, cancellationToken ); - - // Run until user requests ending of example - await Task.Delay( Timeout.Infinite, cancellationToken ); - } catch ( TaskCanceledException ) { - //Task was canceled; close stream and unsubscribe - topics.RemoveStream( jsonStream ); - await topics.UnsubscribeAsync( topic ); - - } finally { - // Note that closing the session, will automatically unsubscribe from all topics the client is - // subscribed to. - session.Close(); - } - } - - /// - /// Basic implementation of the IValueStream for JSON topics. - /// - private sealed class JSONStream : IValueStream { - /// - /// Notification of stream being closed normally. - /// - public void OnClose() - => WriteLine( "The subscrption stream is now closed." ); - - /// - /// Notification of a contextual error related to this callback. - /// - /// - /// Situations in which OnError is called include the session being closed, a communication - /// timeout, or a problem with the provided parameters. No further calls will be made to this callback. - /// - /// Error reason. - public void OnError( ErrorReason errorReason ) - => WriteLine( $"An error has occured : {errorReason}." ); - - /// - /// Notification of a successful subscription. - /// - /// Topic path. - /// Topic specification. - public void OnSubscription( string topicPath, ITopicSpecification specification ) - => WriteLine( $"Client subscribed to topic '{topicPath}'." ); - - /// - /// Notification of a successful unsubscription. - /// - /// Topic path. - /// Topic specification. - /// Error reason. - public void OnUnsubscription( string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason ) - => WriteLine( $"Client unsubscribed from topic '{topicPath}' with reason '{reason}'." ); - - /// - /// Topic update received. - /// - /// Topic path. - /// Topic specification. - /// Value prior to update. - /// Value after update. - public void OnValue( string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue ) - => WriteLine( $"New value of topic '{topicPath}' is {newValue.ToJSONString()}." ); - } - } -} diff --git a/dotnet/source/examples/Consuming/PathRequestMessages.cs b/dotnet/source/examples/Consuming/PathRequestMessages.cs deleted file mode 100644 index 9ac960f9..00000000 --- a/dotnet/source/examples/Consuming/PathRequestMessages.cs +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright © 2018, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features; -using PushTechnology.ClientInterface.Client.Features.Control.Topics; -using PushTechnology.ClientInterface.Client.Session; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Consuming { - /// - /// Client implementation that listens for messages on a topic path. - /// - public sealed class ReceivingPathRequestMessages : IExample { - /// - /// Runs the client receiving messages example. - /// - /// A token used to end the client example. - /// A single string should be used for the server URL. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string serverUrl = args[ 0 ]; - var session = Diffusion.Sessions.Principal( "control" ).Password( "password" ) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - var messaging = session.Messaging; - string messagingPath = ">random/requestResponse"; - - var requestHandler = new SimpleRequestHandler(); - var requestHandlerRegistration = await messaging.AddRequestHandlerAsync( - messagingPath, requestHandler, cancellationToken ); - - try { - await Task.Delay( Timeout.InfiniteTimeSpan, cancellationToken ); - } finally { - // Close session - await requestHandlerRegistration.CloseAsync(); - session.Close(); - } - } - - /// - /// A simple IRequestHandler implementation that prints confirmation of the actions completed. - /// - private class SimpleRequestHandler : IRequestHandler { - /// - /// Indicates that the request handler was closed. - /// - public void OnClose() - => WriteLine( "A request handler was closed." ); - - /// - /// Indicates that the request handler has received error. - /// - public void OnError( ErrorReason errorReason ) - => WriteLine( $"A request handler has received error: '{errorReason}'." ); - - /// - /// Indicates that a request was received and responds to it. - /// - /// On invalid request you would call: . - public void OnRequest( string request, IRequestContext context, IResponder responder ) { - WriteLine( $"Received request: '{request}'." ); - responder.Respond( DateTime.UtcNow.ToLongTimeString() ); - } - } - } -} diff --git a/dotnet/source/examples/Consuming/RecordV2Topics.cs b/dotnet/source/examples/Consuming/RecordV2Topics.cs deleted file mode 100644 index 76f24138..00000000 --- a/dotnet/source/examples/Consuming/RecordV2Topics.cs +++ /dev/null @@ -1,117 +0,0 @@ -/** - * Copyright © 2018, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features; -using PushTechnology.ClientInterface.Client.Features.Topics; -using PushTechnology.ClientInterface.Client.Topics.Details; -using PushTechnology.ClientInterface.Data.Record; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Consuming { - /// - /// Implementation of a client which subscribes to a RecordV2 topic and consumes the data it receives. - /// - public sealed class ConsumingRecordV2Topics : IExample { - /// - /// Runs the RecordV2 topic consuming client example. - /// - /// A token used to end the client example. - /// A single string should be used for the server URL. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string serverUrl = args[ 0 ]; - - // Connect anonymously - var session = Diffusion.Sessions.Open( serverUrl ); - - // Get the Topics feature to subscribe to topics - var topics = session.Topics; - string topic = "random/RecordV2"; - - // Add a topic stream for 'random/RecordV2' - var recordV2Stream = new RecordV2Stream(); - topics.AddStream( topic, recordV2Stream ); - - try { - // Subscribe to 'random/RecordV2' topic - await topics.SubscribeAsync( topic, cancellationToken ); - - // Run until user requests ending of example - await Task.Delay( Timeout.Infinite, cancellationToken ); - } catch ( TaskCanceledException ) { - //Task was canceled; close stream and unsubscribe - topics.RemoveStream( recordV2Stream ); - await topics.UnsubscribeAsync( topic ); - } finally { - // Note that closing the session, will automatically unsubscribe from all topics the client is - // subscribed to. - session.Close(); - } - } - - /// - /// Basic implementation of the IValueStream for RecordV2 topics. - /// - private sealed class RecordV2Stream : IValueStream { - /// - /// Notification of stream being closed normally. - /// - public void OnClose() - => WriteLine( "The subscription stream is now closed." ); - - /// - /// Notification of a contextual error related to this callback. - /// - /// - /// Situations in which OnError is called include the session being closed, a communication - /// timeout, or a problem with the provided parameters. No further calls will be made to this callback. - /// - /// Error reason. - public void OnError( ErrorReason errorReason ) - => WriteLine( $"An error has occurred : {errorReason}." ); - - /// - /// Notification of a successful subscription. - /// - /// Topic path. - /// Topic specification. - public void OnSubscription( string topicPath, ITopicSpecification specification ) - => WriteLine( $"Client subscribed to topic '{topicPath}'." ); - - /// - /// Notification of a successful unsubscription. - /// - /// Topic path. - /// Topic specification. - /// Error reason. - public void OnUnsubscription( string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason ) - => WriteLine( $"Client unsubscribed from topic '{topicPath}' with reason '{reason}'." ); - - /// - /// Topic update received. - /// - /// Topic path. - /// Topic specification. - /// Value prior to update. - /// Value after update. - public void OnValue( string topicPath, ITopicSpecification specification, IRecordV2 oldValue, IRecordV2 newValue ) - => WriteLine( $"New value of topic '{topicPath}' is [{string.Join( ", ", newValue.AsFields() )}]." ); - } - } -} diff --git a/dotnet/source/examples/Consuming/SessionRequestMessages.cs b/dotnet/source/examples/Consuming/SessionRequestMessages.cs deleted file mode 100644 index ca95ac8b..00000000 --- a/dotnet/source/examples/Consuming/SessionRequestMessages.cs +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Copyright © 2018, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Consuming { - /// - /// Client implementation that listens for messages on a topic path. - /// - public sealed class ReceivingSessionRequestMessages : IExample { - /// - /// Runs the client receiving messages example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string serverUrl = args[ 0 ]; - var session = Diffusion.Sessions.Principal( "client" ).Password( "password" ).Open( serverUrl ); - var messaging = session.Messaging; - string messagingPath = ">random/requestResponse"; - - var requestStream = new SimpleRequestStream(); - messaging.SetRequestStream( messagingPath, requestStream ); - - try { - await Task.Delay( Timeout.InfiniteTimeSpan, cancellationToken ); - } finally { - // Close session - messaging.RemoveRequestStream( messagingPath ); - session.Close(); - } - } - - /// - /// A simple IRequestStream implementation that prints confirmation of the actions completed. - /// - private class SimpleRequestStream : IRequestStream { - /// - /// Indicates that the request stream was closed. - /// - public void OnClose() - => WriteLine( "A request handler was closed." ); - - /// - /// Indicates that the request stream has received error. - /// - public void OnError( ErrorReason errorReason ) - => WriteLine( $"A request handler has received error: {errorReason}." ); - - /// - /// Indicates that a request was received and responds to it. - /// - /// On invalid request you would call: . - public void OnRequest( string path, string request, IResponder responder ) { - if ( request == "Hello?" ) { // message to the filter to obtain the session ID - responder.Respond( "Yes" ); - } else { - WriteLine( $"Received request: '{request}'." ); - responder.Respond( DateTime.UtcNow.ToLongTimeString() ); - } - } - } - } -} diff --git a/dotnet/source/examples/Consuming/StringTopics.cs b/dotnet/source/examples/Consuming/StringTopics.cs deleted file mode 100644 index 75c32069..00000000 --- a/dotnet/source/examples/Consuming/StringTopics.cs +++ /dev/null @@ -1,116 +0,0 @@ -/** - * Copyright © 2018, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features; -using PushTechnology.ClientInterface.Client.Features.Topics; -using PushTechnology.ClientInterface.Client.Topics.Details; -using static PushTechnology.ClientInterface.Examples.Runner.Program; -using static System.Console; - -namespace PushTechnology.ClientInterface.Example.Consuming { - /// - /// Implementation of a client which subscribes to a string topic and consumes the data it receives. - /// - public sealed class ConsumingStringTopics : IExample { - /// - /// Runs the string topic client example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string serverUrl = args[ 0 ]; - - // Connect anonymously - var session = Diffusion.Sessions.Open( serverUrl ); - - // Get the Topics feature to subscribe to topics - var topics = session.Topics; - string topic = "random/String"; - - // Add a topic stream for 'random/String' - var stringStream = new StringStream(); - topics.AddStream( topic, stringStream ); - - try { - // Subscribe to 'random/String' topic - await topics.SubscribeAsync( topic, cancellationToken ); - - // Run until user requests ending of example - await Task.Delay( Timeout.Infinite, cancellationToken ); - } catch(TaskCanceledException) { - //Task was canceled; close stream and unsubscribe - topics.RemoveStream( stringStream ); - await topics.UnsubscribeAsync( topic ); - } finally { - // Note that closing the session, will automatically unsubscribe from all topics the client is - // subscribed to. - session.Close(); - } - } - - /// - /// Basic implementation of the IValueStream for String topics. - /// - private sealed class StringStream : IValueStream { - /// - /// Notification of stream being closed normally. - /// - public void OnClose() - => WriteLine( "The subscrption stream is now closed." ); - - /// - /// Notification of a contextual error related to this callback. - /// - /// - /// Situations in which OnError is called include the session being closed, a communication - /// timeout, or a problem with the provided parameters. No further calls will be made to this callback. - /// - /// Error reason. - public void OnError( ErrorReason errorReason ) - => WriteLine( $"An error has occured : {errorReason}." ); - - /// - /// Notification of a successful subscription. - /// - /// Topic path. - /// Topic specification. - public void OnSubscription( string topicPath, ITopicSpecification specification ) - => WriteLine( $"Client subscribed to topic '{topicPath}'." ); - - /// - /// Notification of a successful unsubscription. - /// - /// Topic path. - /// Topic specification. - /// Error reason. - public void OnUnsubscription( string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason ) - => WriteLine( $"Client unsubscribed from topic '{topicPath}' with reason '{reason}'." ); - - /// - /// Topic update received. - /// - /// Topic path. - /// Topic specification. - /// Value prior to update. - /// Value after update. - public void OnValue( string topicPath, ITopicSpecification specification, string oldValue, string newValue ) - => WriteLine( $"New value of topic '{topicPath}' is '{newValue}'." ); - } - } -} diff --git a/dotnet/source/examples/Consuming/TimeseriesTopics.cs b/dotnet/source/examples/Consuming/TimeseriesTopics.cs deleted file mode 100644 index 91bf2cc1..00000000 --- a/dotnet/source/examples/Consuming/TimeseriesTopics.cs +++ /dev/null @@ -1,119 +0,0 @@ -/** - * Copyright © 2020 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features; -using PushTechnology.ClientInterface.Client.Features.Topics; -using PushTechnology.ClientInterface.Client.Topics.Details; -using static PushTechnology.ClientInterface.Examples.Runner.Program; -using static System.Console; -using System; -using PushTechnology.ClientInterface.Client.Features.TimeSeries; - -namespace PushTechnology.ClientInterface.Example.Consuming { - /// - /// Implementation of a client which subscribes to a string time series topic and consumes the data it receives. - /// - public sealed class ConsumingTimeSeriesTopics : IExample { - /// - /// Runs the string time series topic client example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string TOPIC_PREFIX = "time-series"; - - var serverUrl = args[ 0 ]; - - var session = Diffusion.Sessions.Principal("client").Password("password").Open(serverUrl); - - var typeName = Diffusion.DataTypes.Get().TypeName; - var topic = $"?{TOPIC_PREFIX}/{typeName}//"; - - // Add a value stream - var stringStream = new StringStream(); - session.Topics.AddTimeSeriesStream(topic, stringStream); - - try - { - // Subscribe to the topic - await session.Topics.SubscribeAsync( topic, cancellationToken ); - - // Run until the ending of the example - await Task.Delay( Timeout.Infinite, cancellationToken ); - } catch(TaskCanceledException) { - //Task was canceled; close stream and unsubscribe - session.Topics.RemoveStream( stringStream ); - await session.Topics.UnsubscribeAsync( topic ); - } finally { - // Note that closing the session, will automatically unsubscribe from all topics the client is - // subscribed to. - session.Close(); - } - } - - /// - /// Basic implementation of the IValueStream for time series string topics. - /// - private sealed class StringStream : IValueStream> { - /// - /// Notification of the stream being closed normally. - /// - public void OnClose() - => WriteLine( "The subscrption stream is now closed." ); - - /// - /// Notification of a contextual error related to this callback. - /// - /// - /// Situations in which OnError is called include the session being closed, a communication - /// timeout, or a problem with the provided parameters. No further calls will be made to this callback. - /// - /// Error reason. - public void OnError( ErrorReason errorReason ) - => WriteLine( $"An error has occured : {errorReason}." ); - - /// - /// Notification of a successful subscription. - /// - /// Topic path. - /// Topic specification. - public void OnSubscription( string topicPath, ITopicSpecification specification ) - => WriteLine( $"Client subscribed to {topicPath}." ); - - /// - /// Notification of a successful unsubscription. - /// - /// Topic path. - /// Topic specification. - /// Error reason. - public void OnUnsubscription( string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason ) - => WriteLine( $"Client unsubscribed from {topicPath} : {reason}." ); - - /// - /// Topic update received. - /// - /// Topic path. - /// Topic specification. - /// Value prior to update. - /// Value after update. - public void OnValue( string topicPath, ITopicSpecification specification, IEvent oldValue, IEvent newValue ) - => WriteLine( $"New value of {topicPath} is {newValue}." ); - } - } -} diff --git a/dotnet/source/examples/Features/AuthenticationControl.cs b/dotnet/source/examples/Features/AuthenticationControl.cs deleted file mode 100644 index 0a11d3fc..00000000 --- a/dotnet/source/examples/Features/AuthenticationControl.cs +++ /dev/null @@ -1,143 +0,0 @@ -/** - * Copyright © 2019, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features.Control.Clients; -using PushTechnology.ClientInterface.Client.Security.Authentication; -using PushTechnology.DiffusionCore.Client.Types; -using static PushTechnology.ClientInterface.Examples.Runner.Program; -using static System.Console; -using PushTechnology.ClientInterface.Client.Session; -using System; - -namespace PushTechnology.ClientInterface.Example.Features { - /// - /// Implementation of a client which authenticates other sessions. - /// - public sealed class AuthenticationControl : IExample { - /// - /// Runs the authenticator client example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string serverUrl = args[ 0 ]; - - // Connect as a control session - var session = Diffusion.Sessions.Principal( "control" ).Password( "password" ) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - WriteLine("Opening control session."); - - IRegistration registration = null; - - try - { - registration = await session.AuthenticationControl.SetAuthenticationHandlerAsync( - "before-system-handler", new Authenticator(), cancellationToken ); - - WriteLine("Authentication handler registered. Authenticator created."); - - Diffusion.Sessions.Principal("client") - .Credentials(Diffusion.Credentials.Password("password")) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl, new SessionOpenCallback()); - - await Task.Delay(TimeSpan.FromMilliseconds(2000), cancellationToken ); - } catch ( TaskCanceledException ) { - //Task was cancelled; - } finally { - WriteLine("Closing control session."); - - await registration.CloseAsync(); - session.Close(); - } - } - - private sealed class SessionOpenCallback : ISessionOpenCallback - { - public void OnError(ErrorReason errorReason) => WriteLine($"An error occurred: {errorReason}"); - - public void OnOpened(ISession session) - { - WriteLine("Other session opened."); - - session.Close(); - - WriteLine("Other session closed."); - } - } - - /// - /// Basic implementation of . - /// - private sealed class Authenticator : IControlAuthenticator { - /// - /// Method which decides whether a connection attempt should be allowed, denied or - /// if another authenticator should evaluate this request. - /// - /// The session principal. - /// The credentials. - /// The session properties. - /// The client proposed properties. - /// The callback. - public void Authenticate( - string principal, - ICredentials credentials, - IReadOnlyDictionary sessionProperties, - IReadOnlyDictionary proposedProperties, - IAuthenticatorCallback callback ) { - - switch ( principal ) { - case "admin": { - WriteLine( "Authenticator allowing connection with proposed properties properties." ); - callback.Allow( proposedProperties ); - break; - } - case "client": { - WriteLine( "Authenticator allowing connection with no properties." ); - callback.Allow(); - break; - } - case "block": { - WriteLine( "Authenticator denying connection." ); - callback.Deny(); - break; - } - default: { - WriteLine( "Authenticator abstaining." ); - callback.Abstain(); - break; - } - } - } - /// - /// Notification of authenticator closure. - /// - public void OnClose() => WriteLine( "Authenticator closed." ); - - /// - /// Notification of error. - /// - /// Error reason. - public void OnError( ErrorReason errorReason ) => WriteLine( $"Authenticator received an error: {errorReason}" ); - } - } -} diff --git a/dotnet/source/examples/Features/AutomaticRemoval.cs b/dotnet/source/examples/Features/AutomaticRemoval.cs deleted file mode 100644 index 8e7e32cb..00000000 --- a/dotnet/source/examples/Features/AutomaticRemoval.cs +++ /dev/null @@ -1,153 +0,0 @@ -/** - * Copyright © 2018, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Topics; -using PushTechnology.ClientInterface.Client.Topics.Details; -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using static PushTechnology.ClientInterface.Examples.Runner.Program; -using static System.Console; - -namespace PushTechnology.ClientInterface.Example.Features { - public class Removal : IExample { - /// Client implementation that removes topics based on different topic specifications. - /// The cancellation token to cancel the current example run. - /// A single string which should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - var serverUrl = args[ 0 ]; - // Connect with control principal. - var session = Diffusion.Sessions.Principal( "control" ).Password( "password" ) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - var topicControl = session.TopicControl; - ITopicSpecification topicSpecification; - - // Topic to be removed after a set time has passed. - var topicPath = "removal/RemovalOnTime"; - - try { - // Get the time 30 seconds from now as a RFC1123 String. - var time = DateTime - .UtcNow - .AddSeconds( 30 ) - .ToString( DateTimeFormatInfo.InvariantInfo.RFC1123Pattern ); - - // Creating a topic specification with the required topic type and property. - topicSpecification = topicControl - .NewSpecification( TopicType.INT64 ) - .WithProperty( TopicSpecificationProperty.Removal, $"when time after \"{time}\"" ); - - // After adding this topic, the removal property will see to its deletion after the set time and date - // have passed. - await topicControl.AddTopicAsync( topicPath, topicSpecification, cancellationToken ); - WriteLine( "Topic \"{0}\" with the specification \"{1} : {2}\" has been added.", - topicPath, - TopicSpecificationProperty.Removal, - topicSpecification.Properties[ TopicSpecificationProperty.Removal ] ); - } catch ( Exception ex ) { - WriteLine( "Failed to add topic {0} : {1}.", topicPath, ex ); - } - - // Topic to be removed after the session that created it is closed. - topicPath = "removal/RemovalOnSessionClosure"; - - try { - // Creating a topic specification with the required topic type and property. - topicSpecification = topicControl - .NewSpecification( TopicType.INT64 ) - .WithProperty( TopicSpecificationProperty.Removal, "when this session closes" ); - - // After adding this topic, the removal property will see to its deletion after the session closes. - await topicControl.AddTopicAsync( topicPath, topicSpecification, cancellationToken ); - WriteLine( "Topic \"{0}\" with the specification \"{1} : {2}\" has been added.", - topicPath, - TopicSpecificationProperty.Removal, - topicSpecification.Properties[ TopicSpecificationProperty.Removal ] ); - } catch ( Exception ex ) { - WriteLine( "Failed to add topic {0} : {1}.", topicPath, ex ); - } - - // Topic to be removed after a set time has passed without any updates. - topicPath = "removal/RemovalOnNoUpdates"; - - try { - // Creating a topic specification with the required topic type and property. - topicSpecification = topicControl - .NewSpecification( TopicType.INT64 ) - .WithProperty( TopicSpecificationProperty.Removal, "when no updates for 10s" ); - - // After adding this topic, the removal property will see to its deletion when there have been - // no updates for 10 seconds. - await topicControl.AddTopicAsync( topicPath, topicSpecification, cancellationToken ); - WriteLine( "Topic \"{0}\" with the specification \"{1} : {2}\" has been added.", - topicPath, - TopicSpecificationProperty.Removal, - topicSpecification.Properties[ TopicSpecificationProperty.Removal ] ); - } catch ( Exception ex ) { - WriteLine( "Failed to add topic {0} : {1}.", topicPath, ex ); - } - - // Topic to be removed if specified criteria is met. - topicPath = "removal/RemovalOnCriteria"; - - try { - // Creating a topic specification with the required topic type and property. - topicSpecification = topicControl - .NewSpecification( TopicType.INT64 ) - .WithProperty( TopicSpecificationProperty.Removal, - "when no session has \"$Principal is 'yourprincipal'\" after 5s" ); - - // After adding this topic, the removal property will see to its deletion when the criteria are met. - // In this case, it means that the 'yourprincipal' principal is not authenticated with any session. - await topicControl.AddTopicAsync( - topicPath, - topicSpecification, - cancellationToken ); - WriteLine( "Topic \"{0}\" with the specification \"{1} : {2}\" has been added.", - topicPath, - TopicSpecificationProperty.Removal, - topicSpecification.Properties[ TopicSpecificationProperty.Removal ] ); - } catch ( Exception ex ) { - WriteLine( "Failed to add topic {0} : {1}.", topicPath, ex ); - } - - // Topic to be removed when the number of subscriptions falls below a specified value. - topicPath = "removal/RemovalOnLessSubscriptions"; - - try { - // Creating a topic specification with the required topic type and property. - topicSpecification = topicControl - .NewSpecification( TopicType.INT64 ) - .WithProperty( TopicSpecificationProperty.Removal, "when subscriptions < 1 for 10s" ); - - // After adding this topic, the removal property will see to its deletion when there are no subscribers. - await topicControl.AddTopicAsync( topicPath, topicSpecification, cancellationToken ); - WriteLine( "Topic \"{0}\" with the specification \"{1} : {2}\" has been added.", - topicPath, - TopicSpecificationProperty.Removal, - topicSpecification.Properties[ TopicSpecificationProperty.Removal ] ); - } catch ( Exception ex ) { - WriteLine( "Failed to add topic {0} : {1}.", topicPath, ex ); - } - - session.Close(); - } - } -} diff --git a/dotnet/source/examples/Features/ChangePrincipal.cs b/dotnet/source/examples/Features/ChangePrincipal.cs deleted file mode 100644 index a9186edc..00000000 --- a/dotnet/source/examples/Features/ChangePrincipal.cs +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright © 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Collections.ObjectModel; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Session; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Features { - /// - /// Client implementation that changes the principal of a session. - /// - public sealed class ChangePrincipal : IExample { - /// - /// Runs the client control example that changes the principal of a session. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string serverUrl = args[ 0 ]; - - var session = Diffusion.Sessions.Principal("admin") - .Credentials(Diffusion.Credentials.Password("password")) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - var security = session.Security; - - try - { - WriteLine($"Changing the security principal of the session to 'control'."); - - bool result = await security.ChangePrincipalAsync("control", Diffusion.Credentials.Password("password")); - - string stringResult = result ? "succeeded" : "failed"; - - WriteLine($"Principal change {stringResult}."); - } - catch(Exception ex) - { - WriteLine($"An error occurred while trying to change principal : {ex}."); - } - finally - { - session.Close(); - } - } - } -} diff --git a/dotnet/source/examples/Features/ClientControlChangeRoles.cs b/dotnet/source/examples/Features/ClientControlChangeRoles.cs deleted file mode 100644 index 8c7d02a2..00000000 --- a/dotnet/source/examples/Features/ClientControlChangeRoles.cs +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Copyright © 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Collections.ObjectModel; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Session; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Features { - /// - /// Client implementation that changes the assigned roles of a session using the session id. - /// - public sealed class ClientControlChangeRoles : IExample { - /// - /// Runs the client control example that changes the assigned roles of a session using the session id. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - var serverUrl = args[ 0 ]; - var session = Diffusion.Sessions.Principal("control").Password( "password" ) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open( serverUrl ); - - ISession adminSession = Diffusion.Sessions.Principal("admin") - .Credentials(Diffusion.Credentials.Password("password")) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - var adminSecurity = adminSession.Security; - - var clientControl = session.ClientControl; - - try - { - //Get the permissions assigned to the session - var result = await adminSecurity.GetGlobalPermissionsAsync(); - - WriteLine("Permissions for the Administrator session are:"); - - foreach (var permission in result) - { - WriteLine($"{permission}"); - } - } - catch(Exception ex) - { - WriteLine($"Failed to get global permissions : {ex}."); - adminSession.Close(); - session.Close(); - return; - } - - try - { - WriteLine("Removing the Administrator role for the session."); - - await clientControl.ChangeRolesAsync(adminSession.SessionId, new Collection() { "ADMINISTRATOR" }, new Collection()); - } - catch (Exception ex) - { - WriteLine($"Failed to change roles : {ex}."); - adminSession.Close(); - session.Close(); - return; - } - - try - { - var result = await adminSecurity.GetGlobalPermissionsAsync(); - - WriteLine($"Session now has {result.Count} permissions."); - } - catch(Exception ex) - { - WriteLine($"Failed to get global permissions : {ex}."); - } - - // Close the sessions - adminSession.Close(); - session.Close(); - } - } -} diff --git a/dotnet/source/examples/Features/ClientControlChangeRolesFilter.cs b/dotnet/source/examples/Features/ClientControlChangeRolesFilter.cs deleted file mode 100644 index ac719446..00000000 --- a/dotnet/source/examples/Features/ClientControlChangeRolesFilter.cs +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Copyright © 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Collections.ObjectModel; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Session; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Features { - /// - /// Client implementation that changes the assigned roles of a session using a filter. - /// - public sealed class ClientControlChangeRolesFilter : IExample { - /// - /// Runs the client control example that changes the assigned roles of a session using a filter. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - var serverUrl = args[ 0 ]; - var session = Diffusion.Sessions.Principal("control").Password( "password" ) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open( serverUrl ); - - ISession adminSession = Diffusion.Sessions.Principal("admin") - .Credentials(Diffusion.Credentials.Password("password")) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - var adminSecurity = adminSession.Security; - - var clientControl = session.ClientControl; - - try - { - //Get the permissions assigned to the session - var result = await adminSecurity.GetGlobalPermissionsAsync(); - - WriteLine("Permissions for the Administrator session are:"); - - foreach (var permission in result) - { - WriteLine($"{permission}"); - } - } - catch (Exception ex) - { - WriteLine($"Failed to get global permissions : {ex}."); - adminSession.Close(); - session.Close(); - return; - } - - try - { - WriteLine("Removing the Administrator role for the session with a filter."); - - await clientControl.ChangeRolesAsync("$SessionId is \"" + adminSession.SessionId + "\"", new Collection() { "ADMINISTRATOR" }, new Collection()); - } - catch (Exception ex) - { - WriteLine($"Failed to change roles : {ex}."); - adminSession.Close(); - session.Close(); - return; - } - - try - { - var result = await adminSecurity.GetGlobalPermissionsAsync(); - - WriteLine($"Session now has {result.Count} permissions."); - } - catch (Exception ex) - { - WriteLine($"Failed to get global permissions : {ex}."); - } - - // Close the sessions - adminSession.Close(); - session.Close(); - } - } -} diff --git a/dotnet/source/examples/Features/ClientControlCloseSession.cs b/dotnet/source/examples/Features/ClientControlCloseSession.cs deleted file mode 100644 index 04473920..00000000 --- a/dotnet/source/examples/Features/ClientControlCloseSession.cs +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Copyright © 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features.Control.Clients; -using PushTechnology.ClientInterface.Client.Session; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Features { - /// - /// Client implementation that closes a session with its id. - /// - public sealed class ClientControlCloseSession : IExample { - /// - /// Runs the client control example that closes a session with its id. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - var serverUrl = args[ 0 ]; - var session = Diffusion.Sessions.Principal("control").Password( "password" ) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open( serverUrl ); - - var clientControl = session.ClientControl; - - ISession clientSession = Diffusion.Sessions.Principal("client") - .Credentials(Diffusion.Credentials.Password("password")) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .NoReconnection() - .Open(serverUrl); - - WriteLine($"Session with id '{clientSession.SessionId}' created."); - - try - { - WriteLine($"Closing session with id '{clientSession.SessionId}'"); - - clientControl.Close(clientSession.SessionId, new ClientCallback()); - } - catch (Exception ex) - { - WriteLine($"Failed to close session with id '{clientSession.SessionId}' : {ex}."); - } - - // Close the session - session.Close(); - } - - /// - /// The callback for close operations. - /// - private class ClientCallback : IClientCallback - { - /// - /// Indicates that the session was closed. - /// - public void OnDiscard() - { - WriteLine("The session was closed."); - } - - /// - /// Indicates that a requested operation has been handled by the server. - /// - public void OnComplete() - { - WriteLine($"Operation handled."); - } - } - } -} diff --git a/dotnet/source/examples/Features/ClientControlCloseSessionFilter.cs b/dotnet/source/examples/Features/ClientControlCloseSessionFilter.cs deleted file mode 100644 index d8d5b298..00000000 --- a/dotnet/source/examples/Features/ClientControlCloseSessionFilter.cs +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Copyright © 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Session; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Features { - /// - /// Client implementation that closes a session using a filter. - /// - public sealed class ClientControlCloseSessionFilter : IExample { - /// - /// Runs the client control example that closes a session with a filter. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - var serverUrl = args[ 0 ]; - var session = Diffusion.Sessions.Principal("control").Password( "password" ) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open( serverUrl ); - - var clientControl = session.ClientControl; - - ISession clientSession = Diffusion.Sessions.Principal("client") - .Credentials(Diffusion.Credentials.Password("password")) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .NoReconnection() - .Open(serverUrl); - - WriteLine($"Session with id '{clientSession.SessionId}' created."); - - try - { - WriteLine($"Closing session with id '{clientSession.SessionId}'"); - - var result = await clientControl.CloseAsync("$SessionId is \"" + clientSession.SessionId + "\""); - - WriteLine($"Number of sessions closed: {result}"); - } - catch (Exception ex) - { - WriteLine($"Failed to close session with id '{clientSession.SessionId}' : {ex}."); - } - - // Close the session - session.Close(); - } - } -} diff --git a/dotnet/source/examples/Features/ClientControlGetSessionProperties.cs b/dotnet/source/examples/Features/ClientControlGetSessionProperties.cs deleted file mode 100644 index 553ce665..00000000 --- a/dotnet/source/examples/Features/ClientControlGetSessionProperties.cs +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Copyright © 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features.Control; -using PushTechnology.ClientInterface.Client.Session; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Features { - /// - /// Client implementation that gets the property values of a session. - /// - public sealed class ClientControlGetSessionProperties : IExample - { - /// - /// Runs the client control example that gets the property values of a session. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run(CancellationToken cancellationToken, string[] args) - { - var serverUrl = args[0]; - var controlSession = Diffusion.Sessions.Principal("control").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - var clientControl = controlSession.ClientControl; - - ISession session = Diffusion.Sessions.Principal("client") - .Credentials(Diffusion.Credentials.Password("password")) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .NoReconnection() - .Open(serverUrl); - - WriteLine($"Session with id '{session.SessionId}' created."); - - List requiredProperties = new List { SessionProperty.ALL_FIXED_PROPERTIES, SessionProperty.ALL_USER_PROPERTIES }; - - try - { - clientControl.GetSessionProperties(session.SessionId, requiredProperties, new SessionPropertiesCallback()); - } - catch (Exception ex) - { - WriteLine($"Failed to get properties of session with id '{session.SessionId}' : {ex}."); - } - - // Close the sessions - session.Close(); - controlSession.Close(); - } - - /// - /// The callback for retrieving session properties. - /// - private class SessionPropertiesCallback : ISessionPropertiesCallback - { - /// - /// Notification of a contextual error related to this callback. - /// - /// - public void OnError(ErrorReason errorReason) - { - WriteLine($"An error has occured : {errorReason}."); - } - - /// - /// Indicates that the session is not known by the server. - /// - public void OnUnknownSession(ISessionId sessionId) - { - WriteLine($"Session with id {sessionId} is not known."); - } - - /// - /// Called to return requested session properties. - /// - public void OnReply(ISessionId sessionId, Dictionary properties) - { - WriteLine($"Session properties are:"); - - foreach (var property in properties) - { - WriteLine($"{property.Key}: {property.Value}"); - } - } - } - } -} diff --git a/dotnet/source/examples/Features/ClientControlSetConflated.cs b/dotnet/source/examples/Features/ClientControlSetConflated.cs deleted file mode 100644 index ad63425c..00000000 --- a/dotnet/source/examples/Features/ClientControlSetConflated.cs +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Copyright © 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features.Control.Clients; -using PushTechnology.ClientInterface.Client.Session; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Features { - /// - /// Client implementation that sets the queue conflation of a session. - /// - public sealed class ClientControlSetConflated : IExample - { - /// - /// Runs the client control example that sets the queue conflation of a session. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run(CancellationToken cancellationToken, string[] args) - { - var serverUrl = args[0]; - var controlSession = Diffusion.Sessions.Principal("control").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - var clientControl = controlSession.ClientControl; - - ISession session = Diffusion.Sessions.Principal("client") - .Credentials(Diffusion.Credentials.Password("password")) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .NoReconnection() - .Open(serverUrl); - - WriteLine($"Session with id '{session.SessionId}' created."); - - try - { - clientControl.SetConflated(session.SessionId, true, new ClientCallback()); - - WriteLine($"Queue conflation enabled for session with id '{session.SessionId}'."); - } - catch (Exception ex) - { - WriteLine($"Failed to set the queue conflation for session with id '{session.SessionId}' : {ex}."); - } - - // Close the sessions - session.Close(); - controlSession.Close(); - } - - /// - /// The callback for close operations. - /// - private class ClientCallback : IClientCallback - { - /// - /// Indicates that the session was closed. - /// - public void OnDiscard() - { - WriteLine("The session was closed."); - } - - /// - /// Indicates that a requested operation has been handled by the server. - /// - public void OnComplete() - { - WriteLine("Operation handled."); - } - } - } -} diff --git a/dotnet/source/examples/Features/ClientControlSetConflatedFilter.cs b/dotnet/source/examples/Features/ClientControlSetConflatedFilter.cs deleted file mode 100644 index 64c32685..00000000 --- a/dotnet/source/examples/Features/ClientControlSetConflatedFilter.cs +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Copyright © 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features.Control.Clients; -using PushTechnology.ClientInterface.Client.Session; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Features { - /// - /// Client implementation that sets the queue conflation of a session using a filter. - /// - public sealed class ClientControlSetConflatedFilter : IExample - { - /// - /// Runs the client control example that sets the queue conflation of a session using a filter. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run(CancellationToken cancellationToken, string[] args) - { - var serverUrl = args[0]; - var controlSession = Diffusion.Sessions.Principal("control").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - var clientControl = controlSession.ClientControl; - - ISession session = Diffusion.Sessions.Principal("client") - .Credentials(Diffusion.Credentials.Password("password")) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .NoReconnection() - .Open(serverUrl); - - WriteLine($"Session with id '{session.SessionId}' created."); - - ISession session2 = Diffusion.Sessions.Principal("client") - .Credentials(Diffusion.Credentials.Password("password")) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .NoReconnection() - .Open(serverUrl); - - WriteLine($"Session with id '{session2.SessionId}' created."); - - try - { - await clientControl.SetSessionPropertiesAsync(session.SessionId, new Dictionary { { "$Country", "UK" } }); - - await clientControl.SetSessionPropertiesAsync(session2.SessionId, new Dictionary { { "$Country", "US" } }); - } - catch (Exception ex) - { - WriteLine($"Failed to set the properties of a session : {ex}."); - session.Close(); - session2.Close(); - controlSession.Close(); - return; - } - - try - { - var matchedSessions = await clientControl.SetConflatedAsync("$Country is 'UK'", true); - - WriteLine($"Total clients with queue conflation enabled by session filter: {matchedSessions}."); - } - catch (Exception ex) - { - WriteLine($"Failed to set queue conflation by filter : {ex}."); - } - - // Close the sessions - session.Close(); - session2.Close(); - controlSession.Close(); - } - } -} diff --git a/dotnet/source/examples/Features/ClientControlSetSessionProperties.cs b/dotnet/source/examples/Features/ClientControlSetSessionProperties.cs deleted file mode 100644 index 4a06f990..00000000 --- a/dotnet/source/examples/Features/ClientControlSetSessionProperties.cs +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright © 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features.Control; -using PushTechnology.ClientInterface.Client.Session; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Features { - /// - /// Client implementation that sets the property values of a session. - /// - public sealed class ClientControlSetSessionProperties : IExample - { - /// - /// Runs the client control example that sets the property values of a session. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run(CancellationToken cancellationToken, string[] args) - { - var serverUrl = args[0]; - var controlSession = Diffusion.Sessions.Principal("control").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - var clientControl = controlSession.ClientControl; - - ISession session = Diffusion.Sessions.Principal("client") - .Credentials(Diffusion.Credentials.Password("password")) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .NoReconnection() - .Open(serverUrl); - - WriteLine($"Session with id '{session.SessionId}' created."); - - Dictionary properties = new Dictionary { { "$Latitude", "51.509865" } }; - - try - { - var changedProperties = await clientControl.SetSessionPropertiesAsync(session.SessionId, properties); - - foreach (var changedProperty in changedProperties) - { - var value = string.IsNullOrEmpty(changedProperty.Value) ? "[not set]" : $"'{changedProperty.Value}'"; - WriteLine($"Session property {changedProperty.Key} changed from {value} to '{properties[changedProperty.Key]}'"); - } - } - catch (Exception ex) - { - WriteLine($"Failed to set properties of session with id '{session.SessionId}' : {ex}."); - } - - // Close the sessions - session.Close(); - controlSession.Close(); - } - } -} diff --git a/dotnet/source/examples/Features/ClientControlSetSessionPropertiesFilter.cs b/dotnet/source/examples/Features/ClientControlSetSessionPropertiesFilter.cs deleted file mode 100644 index 1f85a1f2..00000000 --- a/dotnet/source/examples/Features/ClientControlSetSessionPropertiesFilter.cs +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Copyright © 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features.Control; -using PushTechnology.ClientInterface.Client.Session; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Features { - /// - /// Client implementation that sets the property values of a session using a filter. - /// - public sealed class ClientControlSetSessionPropertiesFilter : IExample - { - /// - /// Runs the client control example that sets the property values of a session using a filter. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run(CancellationToken cancellationToken, string[] args) - { - var serverUrl = args[0]; - var controlSession = Diffusion.Sessions.Principal("control").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - var clientControl = controlSession.ClientControl; - - ISession session = Diffusion.Sessions.Principal("client") - .Credentials(Diffusion.Credentials.Password("password")) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .NoReconnection() - .Open(serverUrl); - - try - { - Dictionary properties = new Dictionary { { "$Latitude", "51.509865" } }; - - await clientControl.SetSessionPropertiesAsync(session.SessionId, properties); - } - catch (Exception ex) - { - WriteLine($"Failed to set properties of session with id '{session.SessionId}' : {ex}."); - session.Close(); - controlSession.Close(); - return; - } - - try - { - Dictionary properties = new Dictionary { { "$Latitude", "-51.509865" } }; - - WriteLine($"Changing session property $Latitude to '-51.509865'."); - - var numberOfChangedProperties = await clientControl.SetSessionPropertiesAsync("$Latitude is '51.509865'", properties); - WriteLine($"Number of session properties changed: {numberOfChangedProperties}."); - } - catch (Exception ex) - { - WriteLine($"Failed to set properties with filter : {ex}."); - } - - // Close the sessions - session.Close(); - controlSession.Close(); - } - } -} diff --git a/dotnet/source/examples/Features/ClientControlSetSessionPropertiesListener.cs b/dotnet/source/examples/Features/ClientControlSetSessionPropertiesListener.cs deleted file mode 100644 index b55597a8..00000000 --- a/dotnet/source/examples/Features/ClientControlSetSessionPropertiesListener.cs +++ /dev/null @@ -1,161 +0,0 @@ -/** - * Copyright © 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features.Control; -using PushTechnology.ClientInterface.Client.Features.Control.Clients; -using PushTechnology.ClientInterface.Client.Features.Impl; -using PushTechnology.ClientInterface.Client.Security.Authentication; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.DiffusionCore.Client.Types; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Features -{ - /// - /// Client implementation that sets the property values of a session using a listener for notifications. - /// - public sealed class ClientControlSetSessionPropertiesListener : IExample - { - /// - /// Runs the client control example that sets the property values of a session using a listener for notifications. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run(CancellationToken cancellationToken, string[] args) - { - var serverUrl = args[0]; - var controlSession = Diffusion.Sessions.Principal("control").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - var clientControl = controlSession.ClientControl; - - try - { - List requiredProperties = new List { SessionProperty.ALL_FIXED_PROPERTIES, SessionProperty.ALL_USER_PROPERTIES }; - - clientControl.SetSessionPropertiesListener(new SessionPropertiesListener(), requiredProperties.ToArray()); - } - catch (Exception ex) - { - WriteLine($"Failed to register listener : {ex}."); - controlSession.Close(); - return; - } - - ISession session = Diffusion.Sessions.Principal("client") - .Credentials(Diffusion.Credentials.Password("password")) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .NoReconnection() - .Open(serverUrl); - - try - { - Dictionary properties = new Dictionary { { "$Latitude", "51.509865" } }; - - var changedProperties = await clientControl.SetSessionPropertiesAsync(session.SessionId, properties); - - foreach (var changedProperty in changedProperties) - { - var value = string.IsNullOrEmpty(changedProperty.Value) ? "[not set]" : $"'{changedProperty.Value}'"; - WriteLine($"Session property {changedProperty.Key} changed from {value} to '{properties[changedProperty.Key]}'"); - } - } - catch (Exception ex) - { - WriteLine($"Failed to set properties of session with id '{session.SessionId}' : {ex}."); - } - - // Close the sessions - session.Close(); - controlSession.Close(); - } - - /// - /// The handler for session properties listener notifications. - /// - private class SessionPropertiesListener : ISessionPropertiesListener - { - /// - /// Called if the handler is closed. - /// - public void OnClose() - { - WriteLine($"The listener was closed."); - } - - /// - /// Notification of a contextual error related to this handler. - /// - /// - public void OnError(ErrorReason errorReason) - { - WriteLine($"An error has occured : {errorReason}."); - } - - /// - /// Called when the handler has been successfully registered with the server. - /// - /// - public void OnRegistered(IRegistration registration) - { - WriteLine($"The listener has been registered."); - } - - /// - /// Notification that a client session has closed. - /// - /// - /// - /// - public void OnSessionClose(ISessionId sessionId, IDictionary properties, CloseReason closeReason) - { - WriteLine($"Session with id '{sessionId}' has been closed."); - } - - /// - /// Notification of a session event that can result in a change of properties. - /// - /// - /// - /// - /// - public void OnSessionEvent(ISessionId sessionId, SessionPropertiesListenerEventType? eventType, IDictionary properties, IDictionary previousValues) - { - if (eventType.HasValue) - { - WriteLine($"Session with id '{sessionId}' was {eventType.Value}."); - } - } - - /// - /// Notification that a new client session has been opened. - /// - /// - /// - public void OnSessionOpen(ISessionId sessionId, IDictionary properties) - { - WriteLine($"Session with id '{sessionId}' has been opened."); - } - } - } -} diff --git a/dotnet/source/examples/Features/Features.projitems b/dotnet/source/examples/Features/Features.projitems deleted file mode 100644 index b6bdd8df..00000000 --- a/dotnet/source/examples/Features/Features.projitems +++ /dev/null @@ -1,41 +0,0 @@ - - - - $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - true - cbf43c7f-76a7-4476-8f01-ab2f4c89f90e - - - PushTechnology.ClientInterface.Example.Features - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dotnet/source/examples/Features/Features.shproj b/dotnet/source/examples/Features/Features.shproj deleted file mode 100644 index 58d0757b..00000000 --- a/dotnet/source/examples/Features/Features.shproj +++ /dev/null @@ -1,13 +0,0 @@ - - - - cbf43c7f-76a7-4476-8f01-ab2f4c89f90e - 14.0 - - - - - - - - diff --git a/dotnet/source/examples/Features/PingServer.cs b/dotnet/source/examples/Features/PingServer.cs deleted file mode 100644 index 7d3f80a3..00000000 --- a/dotnet/source/examples/Features/PingServer.cs +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright © 2016, 2017 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Session; - -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Features { - /// - /// This example shows how a client session is able to ping the server. - /// - public sealed class PingServer : IExample { - /// - /// Runs the server ping example. - /// - /// The cancellation token to cancel the current example run. - /// The optional example arguments. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - var serverUrl = args[ 0 ]; - - // Connect anonymously - var session = Diffusion.Sessions.Open( serverUrl ); - - // Access the pings feature - var pings = session.Ping; - - // Loop until cancelled - while ( !cancellationToken.IsCancellationRequested ) { - // Ping server roughly every second - await Task.Delay( TimeSpan.FromSeconds( 1 ) ); - - try { - // Ping the server. A overload without a cancellation token is available. - var details = await pings.PingServerAsync( cancellationToken ); - - // Print out details - WriteLine( $"Pinged server at {details.Timestamp}. Received answer after {details.RoundTripTimeSpan}." ); - - } catch ( SessionClosedException ) { - WriteLine( "Ping failed due to a closed session." ); - - } catch ( SessionException ) { - WriteLine( "Ping failed due to a communication failure." ); - - } catch ( TaskCanceledException ) { - WriteLine( "Ping failed due to a manual cancellation." ); - } - } - - session.Close(); - } - } -} diff --git a/dotnet/source/examples/Features/RemoteServers.cs b/dotnet/source/examples/Features/RemoteServers.cs deleted file mode 100644 index 209231e8..00000000 --- a/dotnet/source/examples/Features/RemoteServers.cs +++ /dev/null @@ -1,128 +0,0 @@ -/** - * Copyright © 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features.Control.Clients; -using PushTechnology.ClientInterface.Client.Session; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Features -{ - /// - /// Client implementation that manages remote servers. - /// - public sealed class RemoteServers : IExample - { - /// - /// Runs the remote servers example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run(CancellationToken cancellationToken, string[] args) - { - var serverUrl = args[0]; - var session = Diffusion.Sessions.Principal("admin").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - IRemoteServer server = null; - - var builder = Diffusion.NewRemoteServerBuilder(); - var remoteServer1 = builder - .Principal("principal") - .Credentials(Diffusion.Credentials.Password("password")) - .ConnectionOptions(new Dictionary() - { - { RemoteServerConnectionOption.RECONNECTION_TIMEOUT, "50000" }, - { RemoteServerConnectionOption.CONNECTION_TIMEOUT, "2500" }, - { RemoteServerConnectionOption.WRITE_TIMEOUT, "2000" } - }) - .MissingTopicNotificationFilter("filter") - .Create("Server1", "ws://host:8080"); - - try - { - server = await session.RemoteServers.CreateRemoteServerAsync(remoteServer1); - - WriteLine($"Remote server '{server.Name}' was created."); - } - catch (Exception ex) - { - WriteLine($"Failed to create remote server : {ex}."); - session.Close(); - return; - } - - try - { - var listServers = await session.RemoteServers.ListRemoteServersAsync(); - - WriteLine($"The following remote servers exist:"); - - foreach (var remoteServer in listServers) - { - WriteLine($"Name: '{remoteServer.Name}', Url: '{remoteServer.ServerUrl}', Principal: '{remoteServer.Principal}', Missing Topic Notification Filter: '{remoteServer.MissingTopicNotificationFilter}'"); - - foreach(var connectionOption in remoteServer.ConnectionOptions) - { - WriteLine($"Connection Option: '{connectionOption.Key}', Value: '{connectionOption.Value}'"); - } - } - } - catch (Exception ex) - { - WriteLine($"Failed to list remote servers : {ex}."); - session.Close(); - return; - } - - try - { - var result = await session.RemoteServers.CheckRemoteServerAsync(server.Name); - - WriteLine($"Checking '{server.Name}':"); - - WriteLine($"Connection state: '{result.ConnectionState}'"); - WriteLine($"Failure message: '{result.FailureMessage}'"); - } - catch (Exception ex) - { - WriteLine($"Failed to check remote server '{server.Name}' : {ex}."); - session.Close(); - return; - } - - try - { - await session.RemoteServers.RemoveRemoteServerAsync(server.Name); - - WriteLine($"Remote server '{server.Name}' has been removed."); - } - catch (Exception ex) - { - WriteLine($"Failed to remove remote server '{server.Name}' : {ex}."); - session.Close(); - return; - } - - // Close the session - session.Close(); - } - } -} \ No newline at end of file diff --git a/dotnet/source/examples/Features/SecurityControl.cs b/dotnet/source/examples/Features/SecurityControl.cs deleted file mode 100644 index b3bbaa51..00000000 --- a/dotnet/source/examples/Features/SecurityControl.cs +++ /dev/null @@ -1,244 +0,0 @@ -/** - * Copyright © 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features.Control.Clients.SecurityControl; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Types; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Features -{ - /// - /// Client implementation that uses the security control. - /// - public sealed class SecurityControl : IExample - { - /// - /// Runs the security control example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run(CancellationToken cancel, string[] args) - { - string serverUrl = args[0]; - - // Connect as a control session - var session = Diffusion.Sessions.Principal("admin").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - string role = "ADMINISTRATOR"; - - IReadOnlyCollection defaultPermissions = null; - ISecurityConfiguration securityConfig = null; - - try - { - //Get the default global permissions for the Admin role - securityConfig = await session.SecurityControl.GetSecurityAsync(); - - var adminRole = securityConfig.Roles.Where(x => x.Name == role).FirstOrDefault(); - defaultPermissions = adminRole.GlobalPermissions; - - WriteLine($"The Administrator role has the following global permissions by default:"); - - foreach (var permission in defaultPermissions) - { - WriteLine($"'{permission}'"); - } - } - catch (Exception ex) - { - WriteLine($"Failed to get global permissions : {ex}."); - } - - try - { - //Add the following global permissions for the Admin role - var permissions = new List(defaultPermissions); - permissions.AddRange(new[] { GlobalPermission.REGISTER_HANDLER, GlobalPermission.VIEW_SESSION }); - - WriteLine($"Adding further permissions..."); - - string script = session.SecurityControl.Script.SetGlobalPermissions(role, permissions).ToScript(); - - await session.SecurityControl.UpdateStoreAsync(script); - } - catch (Exception ex) - { - WriteLine($"Failed to set global permissions : {ex}."); - } - - try - { - //Get the current global permissions for the Admin role - securityConfig = await session.SecurityControl.GetSecurityAsync(); - - var adminRole = securityConfig.Roles.Where(x => x.Name == role).FirstOrDefault(); - - WriteLine($"The Administrator role now has the following global permissions:"); - - foreach (var permission in adminRole.GlobalPermissions) - { - WriteLine($"'{permission}'"); - } - } - catch (Exception ex) - { - WriteLine($"Failed to get global permissions : {ex}."); - } - - try - { - WriteLine($"Reseting to the original state."); - - string script = session.SecurityControl.Script.SetGlobalPermissions(role, defaultPermissions).ToScript(); - - await session.SecurityControl.UpdateStoreAsync(script); - } - catch (Exception ex) - { - WriteLine($"Failed to set global permissions : {ex}."); - } - - // Create a new role - - string testRole = "TestRole"; - - try - { - var defaultPermission = new[] { GlobalPermission.REGISTER_HANDLER }; - - WriteLine($"Creating role '{testRole}'."); - - string storeScript = session.SecurityControl.Script - .SetGlobalPermissions(testRole, defaultPermission) - .ToScript(); - - await session.SecurityControl.UpdateStoreAsync(storeScript); - } - catch (Exception ex) - { - WriteLine($"Failed to create role : {ex}."); - } - - //Get the current global permissions for the new role - - try - { - securityConfig = await session.SecurityControl.GetSecurityAsync(); - - var newRole = securityConfig.Roles.Where(x => x.Name == testRole).FirstOrDefault(); - - WriteLine($"'{testRole}' has been created with the following global permissions:"); - - foreach (var permission in newRole.GlobalPermissions) - { - WriteLine($"'{permission}'"); - } - } - catch (Exception ex) - { - WriteLine($"Failed to get global permissions : {ex}."); - } - - // Create a new principal - - string testPrincipal = "TestPrincipal"; - - try - { - WriteLine($"Creating principal '{testPrincipal}'."); - - string storeScript = session.SystemAuthenticationControl.Script - .AddPrincipal(testPrincipal, "password", new List()) - .TrustClientProposedPropertyIn("Foo", new List { "value1", "value2" }) - .TrustClientProposedPropertyMatches("Bar", "regex1") - .ToScript(); - - await session.SystemAuthenticationControl.UpdateStoreAsync(storeScript); - - WriteLine($"'{testPrincipal}' has been created."); - } - catch (Exception ex) - { - WriteLine($"Failed to create principal : {ex}."); - } - - //Assign roles to the principal - - try - { - WriteLine($"Adding the roles of Administrator, Modify Session and TestRole to '{testPrincipal}'."); - - string script1 = session.SystemAuthenticationControl.Script - .AssignRoles(testPrincipal, new[] { "ADMINISTRATOR", "MODIFY_SESSION", testRole }) - .ToScript(); - - await session.SystemAuthenticationControl.UpdateStoreAsync(script1); - - var sysAuth = await session.SystemAuthenticationControl.GetSystemAuthenticationAsync(); - - var principals = sysAuth.Principals.AsEnumerable(); - - WriteLine($"The following principals now exist:"); - - foreach (var principal in principals) - { - WriteLine($"'{principal.Name}' has the following roles:"); - - foreach (string assignedRole in principal.AssignedRoles) - { - WriteLine($"'{assignedRole}'"); - } - } - } - catch (Exception ex) - { - WriteLine($"Failed to assign roles : {ex}."); - } - - // Remove the new principal - - try - { - WriteLine($"Removing '{testPrincipal}'."); - - string storeScript = session.SystemAuthenticationControl.Script - .RemovePrincipal(testPrincipal) - .ToScript(); - - await session.SystemAuthenticationControl.UpdateStoreAsync(storeScript); - - WriteLine($"'{testPrincipal}' has been removed."); - } - catch (Exception ex) - { - WriteLine($"Failed to remove principal : {ex}."); - } - finally - { - session.Close(); - session = null; - } - } - } -} \ No newline at end of file diff --git a/dotnet/source/examples/Features/SessionLocks.cs b/dotnet/source/examples/Features/SessionLocks.cs deleted file mode 100644 index 3320809a..00000000 --- a/dotnet/source/examples/Features/SessionLocks.cs +++ /dev/null @@ -1,147 +0,0 @@ -/** - * Copyright © 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features; -using PushTechnology.ClientInterface.Client.Features.Topics; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Topics; -using PushTechnology.ClientInterface.Client.Topics.Details; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Features -{ - /// - /// Client implementation that demonstrates session locks. - /// - public sealed class SessionLocks : IExample - { - private ISession session1, session2; - private ISessionLock sessionLock1, sessionLock2; - - private static string LOCK_NAME = "lockA"; - - /// - /// Runs the session locks example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run(CancellationToken cancellationToken, string[] args) - { - string serverUrl = args[0]; - session1 = Diffusion.Sessions.Principal("control").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - session2 = Diffusion.Sessions.Principal("control").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - WriteLine("Sessions 1 and 2 have been created."); - - AcquireLockSession1(); - } - - private async void AcquireLockSession1() - { - try - { - WriteLine("Requesting lock 1..."); - - sessionLock1 = await session1.LockAsync(LOCK_NAME, SessionLockScope.UNLOCK_ON_CONNECTION_LOSS); - - WriteLine("Lock 1 has been acquired."); - - AcquireLockSession2(); - - Thread.Sleep(1000); - - ReleaseLock1(); - } - catch (Exception ex) - { - WriteLine($"Failed to get lock 1 : {ex}."); - session1.Close(); - session2.Close(); - } - } - - private async void AcquireLockSession2() - { - try - { - WriteLine("Requesting lock 2..."); - - sessionLock2 = await session2.LockAsync(LOCK_NAME, SessionLockScope.UNLOCK_ON_CONNECTION_LOSS); - - WriteLine("Lock 2 has been acquired."); - - Thread.Sleep(1000); - - ReleaseLock2(); - } - catch (Exception ex) - { - WriteLine($"Failed to get lock 2 : {ex}."); - session1.Close(); - session2.Close(); - } - } - - private async void ReleaseLock1() - { - try - { - WriteLine("Requesting lock 1 release..."); - - await sessionLock1.UnlockAsync(); - - WriteLine("Lock 1 has been released."); - } - catch (Exception ex) - { - WriteLine($"Failed to release lock 1 : {ex}."); - session1.Close(); - session2.Close(); - } - } - - private async void ReleaseLock2() - { - try - { - WriteLine("Requesting lock 2 release..."); - - await sessionLock2.UnlockAsync(); - - WriteLine("Lock 2 has been released."); - } - catch (Exception ex) - { - WriteLine($"Failed to release lock 2 : {ex}."); - } - finally - { - session1.Close(); - session2.Close(); - } - } - } -} \ No newline at end of file diff --git a/dotnet/source/examples/Features/SessionMetricCollector.cs b/dotnet/source/examples/Features/SessionMetricCollector.cs deleted file mode 100644 index 465ccf67..00000000 --- a/dotnet/source/examples/Features/SessionMetricCollector.cs +++ /dev/null @@ -1,113 +0,0 @@ -/** - * Copyright © 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features.Metrics; -using PushTechnology.ClientInterface.Client.Session; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Features -{ - /// - /// Client implementation that demonstrates the session metric collector. - /// - public sealed class SessionMetricCollector : IExample - { - /// - /// Runs the session metric collector example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run(CancellationToken cancellationToken, string[] args) - { - string serverUrl = args[0]; - var session = Diffusion.Sessions.Principal("admin").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - var metrics = session.Metrics; - ISessionMetricCollector collector = null; - string sessionFilter = "x is 'y'"; - - try - { - WriteLine($"Adding the session metric collector 'Test' with session filter '{sessionFilter}'."); - - var builder = Diffusion.NewSessionMetricCollectorBuilder(); - builder = (ISessionMetricCollectorBuilder)builder.ExportsToPrometheus(true); - builder = (ISessionMetricCollectorBuilder)builder.GroupByProperties(new List { "$Location" }); - builder = (ISessionMetricCollectorBuilder)builder.RemoveMetricsWithNoMatches(true); - builder = (ISessionMetricCollectorBuilder)builder.MaximumGroups(10); - collector = builder.Create("Test", sessionFilter); - - await metrics.PutSessionMetricCollectorAsync(collector); - - WriteLine($"Session metric collector '{collector.Name}' added."); - } - catch (Exception ex) - { - WriteLine($"Failed to add session metric collector : {ex}."); - session.Close(); - return; - } - - try - { - WriteLine($"The following session metric collectors exist:"); - - var listSessionMetricCollectors = await metrics.ListSessionMetricCollectorsAsync(); - - foreach (var sessionMetricCollector in listSessionMetricCollectors) - { - WriteLine($"Name: '{sessionMetricCollector.Name}', Session filter: '{sessionMetricCollector.SessionFilter}', " + - $"Exports to Prometheus: '{GetAnswer(sessionMetricCollector.ExportsToPrometheus)}', " + - $"Maximum Groups: {sessionMetricCollector.MaximumGroups}, " + - $"Removes metrics with no matches: '{GetAnswer(sessionMetricCollector.RemovesMetricsWithNoMatches)}'"); - - foreach (string property in sessionMetricCollector.GroupByProperties) - { - WriteLine($"Group by: '{property}' property"); - } - } - } - catch (Exception ex) - { - WriteLine($"Failed to list session metric collectors : {ex}."); - session.Close(); - return; - } - - try - { - await metrics.RemoveSessionMetricCollectorAsync(collector.Name); - - WriteLine($"Collector '{collector.Name}' removed."); - } - catch (Exception ex) - { - WriteLine($"Failed to remove session metric collector : {ex}."); - } - - // Close the session - session.Close(); - } - - private string GetAnswer(bool result) => result ? "Yes" : "No"; - } -} \ No newline at end of file diff --git a/dotnet/source/examples/Features/SessionReconnection.cs b/dotnet/source/examples/Features/SessionReconnection.cs deleted file mode 100644 index dfea56f8..00000000 --- a/dotnet/source/examples/Features/SessionReconnection.cs +++ /dev/null @@ -1,135 +0,0 @@ -/** - * Copyright © 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Session.Reconnection; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Features -{ - /// - /// Client implementation that demonstrates session reconnection strategy. - /// - public sealed class SessionReconnection : IExample - { - private int maximumTimeoutDuration = 1000 * 60 * 10; - - private ReconnectionStrategy reconnectionStrategy = new ReconnectionStrategy(); - /// - /// Runs the session reconnection example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run(CancellationToken cancellationToken, string[] args) - { - string serverUrl = args[0]; - - var factory = Diffusion.Sessions; - - var session = Connect(serverUrl, factory); - - if (session != null) - { - WriteLine("The session has been created."); - } - - Thread.Sleep(60000); - - session.Close(); - } - - public ISession Connect(string url, ISessionFactory initialFactory) - { - try - { - string principal = "control"; - string password = "password"; - - var factory = initialFactory - .Principal(principal) - .Credentials(Diffusion.Credentials.Password(password)) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .ReconnectionTimeout(maximumTimeoutDuration) - .ReconnectionStrategy(reconnectionStrategy) - .SessionStateChangedHandler(OnSessionStateChanged); - - return factory.Open(url); - } - catch (Exception ex) - { - WriteLine($"Session connection error : {ex}."); - } - - return null; - } - - private void OnSessionStateChanged(object sender, SessionListenerEventArgs e) - { - if (e.NewState == SessionState.RECOVERING_RECONNECT) - { - // The session has been disconnected, and has entered - // recovery state. It is during this state that - // the reconnect strategy will be called - WriteLine("The session has been disconnected."); - } - - if (e.NewState == SessionState.CONNECTED_ACTIVE) - { - // The session has connected for the first time, or it has - // been reconnected. - reconnectionStrategy.Retries = 0; - - WriteLine("The session has connected."); - } - - if (e.OldState == SessionState.RECOVERING_RECONNECT) - { - // The session has left recovery state. It may either be - // attempting to reconnect, or the attempt has been aborted; - // this will be reflected in the newState. - } - - if (e.NewState == SessionState.CLOSED_BY_CLIENT) - { - WriteLine("The session has been closed."); - } - } - - private class ReconnectionStrategy : IReconnectionStrategy - { - public int Retries { get; set; } - - // Set the maximum interval between reconnect attempts to 60 seconds. - private long maximumAttemptInterval = 1000 * 60; - - public ReconnectionStrategy() => Retries = 0; - - public async Task PerformReconnection(IReconnectionAttempt reconnection) - { - long wait = Math.Min((long)Math.Pow(2, Retries++) * 100L, maximumAttemptInterval); - - Thread.Sleep((int)wait); - - WriteLine("Attempting to reconnect..."); - - reconnection.Start(); - } - } - } -} \ No newline at end of file diff --git a/dotnet/source/examples/Features/SessionRetry.cs b/dotnet/source/examples/Features/SessionRetry.cs deleted file mode 100644 index d66caf27..00000000 --- a/dotnet/source/examples/Features/SessionRetry.cs +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Copyright © 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Session; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Features -{ - /// - /// Client implementation that demonstrates establishing a session with a session retry strategy. - /// - public sealed class SessionRetry : IExample - { - public async Task Run(CancellationToken cancellationToken, string[] args) - { - var serverUrl = args[0]; - - ISession session = null; - - //Create an initial session establishment retry strategy. - //It will attempt 5 times to connect to the Diffusion server, - //with 100 milliseconds interval between attempts. - var retryStrategy = new RetryStrategy(100, 5); - - try - { - session = Diffusion.Sessions - .Principal("admin") - .Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .InitialRetryStrategy(retryStrategy) - .Open(serverUrl); - WriteLine($"Session established with session id {session.SessionId}."); - } - catch (SessionEstablishmentException ex) - { - WriteLine($"Failed to open the session : {ex}."); - } - finally - { - session.Close(); - } - } - } -} \ No newline at end of file diff --git a/dotnet/source/examples/Features/SessionTrees.cs b/dotnet/source/examples/Features/SessionTrees.cs deleted file mode 100644 index 579c8d2c..00000000 --- a/dotnet/source/examples/Features/SessionTrees.cs +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Copyright © 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Session; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Features -{ - /// - /// Client implementation that demonstrates session trees. - /// - public sealed class SessionTrees : IExample - { - /// - /// Runs the session trees example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run(CancellationToken cancellationToken, string[] args) - { - string serverUrl = args[0]; - var session = Diffusion.Sessions.Principal("control").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - try - { - var table = Diffusion.NewBranchMappingTableBuilder() - .AddBranchMapping("$Principal is 'control'", "target/1") - .AddBranchMapping("all", "target/2") - .Create("source/path"); - - await session.SessionTrees.PutBranchMappingTableAsync(table); - - WriteLine($"Branch mapping table created for session tree branch '{table.SessionTreeBranch}'."); - } - catch (Exception ex) - { - WriteLine($"Failed to create branch mapping table : {ex}."); - session.Close(); - return; - } - - IReadOnlyCollection listSessionTreeBranches = null; - - try - { - WriteLine($"Retrieving session tree branches."); - - listSessionTreeBranches = await session.SessionTrees.GetSessionTreeBranchesWithMappingsAsync(); - } - catch (Exception ex) - { - WriteLine($"Failed to retrieve session tree branches : {ex}."); - session.Close(); - return; - } - - try - { - WriteLine($"Retrieving branch mapping table:"); - - foreach (string sessionTreeBranch in listSessionTreeBranches) - { - var branchMappingTable = await session.SessionTrees.GetBranchMappingTableAsync(sessionTreeBranch); - - foreach (var branchMapping in branchMappingTable.BranchMappings) - { - WriteLine($"Session tree branch: '{sessionTreeBranch}', Session filter: '{branchMapping.SessionFilter}', Topic tree branch: '{branchMapping.TopicTreeBranch}'"); - } - } - } - catch(Exception ex) - { - WriteLine($"Failed to retrieve a branch mapping : {ex}."); - } - - // Close the session - session.Close(); - } - } -} \ No newline at end of file diff --git a/dotnet/source/examples/Features/SubscriptionControlRoutingHandler.cs b/dotnet/source/examples/Features/SubscriptionControlRoutingHandler.cs deleted file mode 100644 index 3f08e731..00000000 --- a/dotnet/source/examples/Features/SubscriptionControlRoutingHandler.cs +++ /dev/null @@ -1,183 +0,0 @@ -/** - * Copyright © 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features; -using PushTechnology.ClientInterface.Client.Features.Control.Clients; -using PushTechnology.ClientInterface.Client.Features.Control.Topics; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Topics; -using PushTechnology.ClientInterface.Client.Topics.Details; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Features { - /// - /// Client implementation that routes subscriptions. - /// - public sealed class SubscriptionControlRoutingHandler : IExample - { - /// - /// Runs the control client example that routes subscriptions. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run(CancellationToken cancellationToken, string[] args) - { - var topic = "branch/routingTopic"; - - var serverUrl = args[0]; - var controlSession = Diffusion.Sessions.Principal("control").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - var subscriptionControl = controlSession.SubscriptionControl; - - try - { - await controlSession.TopicControl.AddTopicAsync(topic, controlSession.TopicControl.NewSpecification(TopicType.ROUTING), cancellationToken); - - await controlSession.TopicControl.AddTopicAsync("branch/someTopic", TopicType.STRING, cancellationToken); - } - catch (Exception ex) - { - WriteLine($"Failed to add topic '{topic}' : {ex}."); - controlSession.Close(); - return; - } - - try - { - // Sets up a handler so that all subscriptions to topic 'branch' are routed. - subscriptionControl.AddRoutingSubscriptionHandler("branch", new RoutingSubscriptionRequestHandler()); - - WriteLine($"Routing handler added for topic 'branch'."); - } - catch (Exception ex) - { - WriteLine($"Failed to add routing handler for topic 'branch' : {ex}."); - } - - ISession session = Diffusion.Sessions.Principal("client") - .Credentials(Diffusion.Credentials.Password("password")) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .NoReconnection() - .Open(serverUrl); - - WriteLine($"Session with id '{session.SessionId}' created."); - - try - { - await session.Topics.SubscribeAsync("?branch/", cancellationToken); - - WriteLine($"Session with id '{session.SessionId}' is subscribed to '?branch/'."); - - await Task.Delay(TimeSpan.FromMilliseconds(300)); - } - catch (Exception ex) - { - WriteLine($"Failed to subscribe to '?branch/' : {ex}."); - session.Close(); - controlSession.Close(); - return; - } - - try - { - WriteLine($"Removing topics for path '?branch/'."); - - var result = await session.TopicControl.RemoveTopicsAsync("?branch/", cancellationToken); - - WriteLine($"{result.RemovedCount} topics successfully removed."); - } - catch (Exception ex) - { - WriteLine($"Failed to remove topics for path '?branch/' : {ex}."); - } - - // Close the sessions - controlSession.Close(); - } - - /// - /// The handler for routing subscription requests. - /// - private class RoutingSubscriptionRequestHandler : IRoutingSubscriptionRequestHandler - { - /// - /// Called when the handler has been registered at the server and is now active. - /// - /// Path to topic. - /// Reference to a registered handler. - public void OnActive(string topicPath, IRegisteredHandler registeredHandler) - { - WriteLine($"Handler registered for '{topicPath}'."); - } - - /// - /// Called if the handler is closed. - /// - /// Path to topic. - public void OnClose(string topicPath) - { - WriteLine($"Handler closed for '{topicPath}'."); - } - - /// - /// A request to subscribe to a specific routing topic. - /// - /// The request to subscribe to a routing topic. - public void OnSubscriptionRequest(IRoutingSubscriptionRequest request) - { - var topic = "branch/someTopic"; - - try - { - WriteLine($"Routing subscription to '{topic}'."); - request.Route(topic, new SubscriptionCallback()); - } - catch(Exception ex) - { - WriteLine($"Subscription routing failed: {ex}."); - } - } - } - - /// - /// The callback for subscription operations. - /// - private class SubscriptionCallback : ISubscriptionCallback - { - /// - /// Indicates that the session was closed. - /// - public void OnDiscard() - { - WriteLine("The session was closed."); - } - - /// - /// Indicates that a requested operation has been handled by the server. - /// - public void OnComplete() - { - WriteLine("Subscription complete."); - } - } - } -} diff --git a/dotnet/source/examples/Features/SubscriptionControlSubscribe.cs b/dotnet/source/examples/Features/SubscriptionControlSubscribe.cs deleted file mode 100644 index 70c43f6d..00000000 --- a/dotnet/source/examples/Features/SubscriptionControlSubscribe.cs +++ /dev/null @@ -1,124 +0,0 @@ -/** - * Copyright © 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features.Control.Clients; -using PushTechnology.ClientInterface.Client.Features.Control.Topics; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Topics; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Features { - /// - /// Client implementation that subscribes to topics. - /// - public sealed class SubscriptionControlSubscribe : IExample - { - /// - /// Runs the control client example that subscribes to topics. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run(CancellationToken cancellationToken, string[] args) - { - var topic = $"topic/example"; - - var serverUrl = args[0]; - var controlSession = Diffusion.Sessions.Principal("control").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - var subscriptionControl = controlSession.SubscriptionControl; - - try - { - await controlSession.TopicControl.AddTopicAsync(topic, TopicType.STRING, cancellationToken); - } - catch (Exception ex) - { - WriteLine($"Failed to add topic '{topic}' : {ex}."); - controlSession.Close(); - return; - } - - ISession session = Diffusion.Sessions.Principal("client") - .Credentials(Diffusion.Credentials.Password("password")) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .NoReconnection() - .Open(serverUrl); - - WriteLine($"Session with id '{session.SessionId}' created."); - - var subscriptionCallback = new SubscriptionCallback(); - - var topicSelector = "?topic//"; - - try - { - subscriptionControl.Subscribe(session.SessionId, topicSelector, subscriptionCallback); - - WriteLine($"Session with id '{session.SessionId}' is subscribed to '{topicSelector}'."); - } - catch (Exception ex) - { - WriteLine($"Failed to subscribe to '{topicSelector}' : {ex}."); - session.Close(); - controlSession.Close(); - return; - } - - try - { - subscriptionControl.Unsubscribe(session.SessionId, topicSelector, subscriptionCallback); - - WriteLine($"Session with id '{session.SessionId}' is unsubscribed to '{topicSelector}'."); - } - catch (Exception ex) - { - WriteLine($"Failed to unsubscribe to '{topicSelector}' : {ex}."); - } - - // Close the sessions - session.Close(); - controlSession.Close(); - } - - /// - /// The callback for subscription operations. - /// - private class SubscriptionCallback : ISubscriptionCallback - { - /// - /// Indicates that the session was closed. - /// - public void OnDiscard() - { - WriteLine("The session was closed."); - } - - /// - /// Indicates that a requested operation has been handled by the server. - /// - public void OnComplete() - { - WriteLine("Subscription complete."); - } - } - } -} diff --git a/dotnet/source/examples/Features/SubscriptionControlSubscribeFilter.cs b/dotnet/source/examples/Features/SubscriptionControlSubscribeFilter.cs deleted file mode 100644 index 4a8c6c7b..00000000 --- a/dotnet/source/examples/Features/SubscriptionControlSubscribeFilter.cs +++ /dev/null @@ -1,127 +0,0 @@ -/** - * Copyright © 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features.Control.Clients; -using PushTechnology.ClientInterface.Client.Features.Control.Topics; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Types; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Features { - /// - /// Client implementation that subscribes to topics with a filter. - /// - public sealed class SubscriptionControlSubscribeFilter : IExample - { - /// - /// Runs the control client example that subscribes to topics with a filter. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run(CancellationToken cancellationToken, string[] args) - { - var topic = $"?topic-example//"; - - var serverUrl = args[0]; - var controlSession = Diffusion.Sessions.Principal("control").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - WriteLine($"Session with id '{controlSession.SessionId}' created."); - - var filter = "$SessionId is \"" + controlSession.SessionId + "\""; - - var subscriptionControl = controlSession.SubscriptionControl; - - var filterCallback = new SubscriptionByFilterCallback(); - - try - { - subscriptionControl.SubscribeByFilter(filter, topic, filterCallback); - - WriteLine($"Sessions satisfying filter '{filter}' are subscribed to '{topic}'."); - - await Task.Delay(TimeSpan.FromMilliseconds(300)); - } - catch (Exception ex) - { - WriteLine($"Failed to subscribe by filter '{filter}' : {ex}."); - controlSession.Close(); - return; - } - - try - { - subscriptionControl.UnsubscribeByFilter(filter, topic, filterCallback); - - WriteLine($"Sessions satisfying filter '{filter}' are unsubscribed to '{topic}'."); - - await Task.Delay(TimeSpan.FromMilliseconds(300)); - } - catch (Exception ex) - { - WriteLine($"Failed to unsubscribe by filter '{filter}' : {ex}."); - } - - controlSession.Close(); - } - - /// - /// The callback for filtered subscriptions and unsubscriptions. - /// - private class SubscriptionByFilterCallback : ISubscriptionByFilterCallback - { - /// - /// Indicates successful processing of the request at the server. - /// - /// Indicates the number of sessions that satisfied the filter and which qualified - /// for subscription/unsubscription. - public void OnComplete(int numberSelected) - { - WriteLine($"The number of sessions that qualified for subscription/unsubscription is: {numberSelected}."); - } - - /// - /// The filter was rejected. No sessions were subscribed/unsubscribed. - /// - /// Errors found. - public void OnRejected(ICollection errors) - { - WriteLine($"The following errors occured:"); - - foreach(var error in errors) - { - WriteLine($"{error}."); - } - } - - /// - /// Notification of a contextual error related to this callback. - /// - /// Error reason provided. - public void OnError(ErrorReason errorReason) - { - WriteLine($"An error has occured : {errorReason}."); - } - } - } -} diff --git a/dotnet/source/examples/Features/SystemAuthenticationControl.cs b/dotnet/source/examples/Features/SystemAuthenticationControl.cs deleted file mode 100644 index bc6af5ed..00000000 --- a/dotnet/source/examples/Features/SystemAuthenticationControl.cs +++ /dev/null @@ -1,116 +0,0 @@ -/** - * Copyright © 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features.Control.Clients; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; -using PushTechnology.ClientInterface.Client.Session; - -namespace PushTechnology.ClientInterface.Example.Features -{ - /// - /// An example of altering the system authentication configuration. - /// - public sealed class SystemAuthenticationControl : IExample - { - private ISystemAuthenticationControl sysAuthCtrl; - private IScriptBuilder emptyScript; - - public async Task Run(CancellationToken cancel, string[] args) { - string serverUrl = args[0]; - - // Connect as an admin session - var session = Diffusion.Sessions.Principal("admin").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - sysAuthCtrl = session.SystemAuthenticationControl; - emptyScript = sysAuthCtrl.Script; - - IEnumerable filteredPrincipals = null; - - try - { - var sysAuth = await sysAuthCtrl.GetSystemAuthenticationAsync(); - - var principals = sysAuth.Principals.AsEnumerable(); - - // For each principal that has the CLIENT assigned role - filteredPrincipals = principals.Where(p => p.AssignedRoles.Contains("CLIENT")); - - WriteLine($"The following principals have the CLIENT role:"); - - foreach (var principal in filteredPrincipals) - { - WriteLine($"'{principal.Name}'."); - } - } - catch(Exception ex) - { - WriteLine($"Failed to get principals : {ex}."); - } - - try - { - string newPrincipalsScript = filteredPrincipals.Select(p => - { - var newRoles = new HashSet(); - - foreach (string r in p.AssignedRoles) - { - newRoles.Add(r); - } - - newRoles.Add("OPERATOR"); - - return emptyScript.AssignRoles(p.Name, newRoles); - }).Aggregate(emptyScript, (sb1, sb2) => sb2.Append(sb1)).ToScript(); - - await sysAuthCtrl.UpdateStoreAsync(newPrincipalsScript); - - WriteLine($"Adding the OPERATOR role to these principals..."); - - var sysAuth = await sysAuthCtrl.GetSystemAuthenticationAsync(); - - var principals = sysAuth.Principals.AsEnumerable(); - - WriteLine($"The following principals now exist:"); - - foreach (var principal in principals) - { - WriteLine($"'{principal.Name}' has the following roles:"); - - foreach (string assignedRole in principal.AssignedRoles) - { - WriteLine($"'{assignedRole}'"); - } - } - } - catch(Exception ex) - { - WriteLine($"Failed to add roles : {ex}."); - } - finally - { - session.Close(); - } - } - } -} diff --git a/dotnet/source/examples/Features/TopicFetch.cs b/dotnet/source/examples/Features/TopicFetch.cs deleted file mode 100644 index 3f6171fd..00000000 --- a/dotnet/source/examples/Features/TopicFetch.cs +++ /dev/null @@ -1,148 +0,0 @@ - -/******************************************************************************* - * Copyright (C) 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features; -using PushTechnology.ClientInterface.Data.JSON; -using static PushTechnology.ClientInterface.Examples.Runner.Program; -using System; -using PushTechnology.ClientInterface.Data; -using PushTechnology.ClientInterface.Client.Topics; -using PushTechnology.ClientInterface.Client.Session; -using System.Linq; - -namespace PushTechnology.ClientInterface.Example.Features { - /// - /// Client implementation that fetches topic values and/or specifications. - /// - public sealed class TopicFetch : IExample - { - /// - /// Runs the fetch example that retrieves values and/or topic specifications for a set of topics without subscribing. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run(CancellationToken cancellationToken, string[] args) - { - var serverUrl = args[ 0 ]; - - ISession session = Diffusion.Sessions - .Principal( "control" ) - .Password( "password" ) - .CertificateValidation((cert, chain, errors) - => CertificateValidationResult.ACCEPT) - .Open( serverUrl ); - - ITopics topics = session.Topics; - - for (char a = 'a'; a <= 'z'; ++a) - { - try - { - if (a % 2 == 0) - { - await session.TopicControl.AddTopicAsync("a/" + a, TopicType.JSON); - } - else if (a % 3 == 0) - { - await session.TopicControl.AddTopicAsync("a/" + a, TopicType.STRING); - } - } - catch(Exception ex) - { - Console.WriteLine("Failed to add topic {0} : {1}.", "a/" + a, ex); - } - } - - //Fetch all topics - only topic path and type are returned in each result. - var res = topics.FetchRequest.FetchAsync("*.*").Result; - Console.WriteLine( "All results:" ); - foreach (var topic in res.Results) { - Console.WriteLine(topic.Path); - } - - // Fetch all string topics that satisfy a specified topic selector with values. - res = topics.FetchRequest.WithValues().FetchAsync("*.*").Result; - Console.WriteLine( "All string results:" ); - foreach ( var topic in res.Results ) { - Console.WriteLine( topic.Path ); - } - - // Fetch a single string topic with value and properties. - var resSingle = topics.FetchRequest.WithValues().WithProperties().FetchAsync("?a/c").Result.Results.ElementAt(0); - Console.WriteLine($"Topic 'a/c' has path: {resSingle.Path}, type: {resSingle.Type}, value: '{resSingle.Value}', specification: '{resSingle.Specification}'"); - - // Fetch all JSON topics that match a specified selector, with values. - var resJSON = topics.FetchRequest.WithValues().TopicTypes(new[] { TopicType.JSON }).FetchAsync("*.*").Result; - Console.WriteLine("All JSON results:"); - foreach (var topic in resJSON.Results) - { - Console.WriteLine(topic.Path); - } - - // Obtain an inclusive range of topics, using topic paths for the start and end points. - string from = "a/b"; - string to = "a/d"; - var resBytes = topics.FetchRequest.From(from).To(to).FetchAsync("*.*").Result; - Console.WriteLine("All topics between 'a/b' and 'a/d' inclusive are:"); - foreach (var topic in resBytes.Results) - { - Console.WriteLine(topic.Path); - } - - // Obtain the next group of topics, with values, from a specified start point 'after' limiting the number of topics to fetch with 'limit'. - // This demonstrates paging and could be used repeatedly specifying the after value as the path of the last topic retrieved - // from the previous call of the next method. The FetchResult.HasMore() method on the result can be used to - // determine whether there may be more results. - string after = "a/b"; - int limit = 2; - var resNext = topics.FetchRequest.After(after).WithValues().First(limit).FetchAsync("*.*").Result; - Console.WriteLine("The 2 next lexographic topics after 'a/b' are:"); - foreach (var topic in resNext.Results) - { - Console.WriteLine(topic.Path); - } - - // Obtain the prior group of topics, with values, from a specified end point 'before' limiting the number of topics to fetch with 'limit'. - // This demonstrates paging and could be used to retrieve the set of topics prior to the first topic from a previous call of prior or next. - string before = "a/e"; - limit = 3; - var resPrior = topics.FetchRequest.Before(before).WithValues().Last(limit).FetchAsync("*.*").Result; - Console.WriteLine("The 3 prior lexographic topics before 'a/e' are:"); - foreach (var topic in resPrior.Results) - { - Console.WriteLine(topic.Path); - } - - // Limit on the number of results returned for each deep branch with 'deepBranchDepth' the number of parts in the root path of a branch - // for it to be considered deep, and 'deepBranchLimit' the maximum number of results to return for each deep branch. - // This demonstrates a method that could be particularly useful for incrementally exploring a topic tree from the root, - // allowing a breadth-first search strategy. - int deepBranchDepth = 1; - int deepBranchLimit = 1; - var resLimit = topics.FetchRequest.LimitDeepBranches(deepBranchDepth, deepBranchLimit).WithValues().FetchAsync("*.*").Result; - Console.WriteLine("The results that are at most 1 part deep, with a maximum of 1 result per deep branch are:"); - foreach (var topic in resLimit.Results) - { - Console.WriteLine(topic.Path); - } - } - - } - -} - diff --git a/dotnet/source/examples/Features/TopicMetricCollector.cs b/dotnet/source/examples/Features/TopicMetricCollector.cs deleted file mode 100644 index 3fb19103..00000000 --- a/dotnet/source/examples/Features/TopicMetricCollector.cs +++ /dev/null @@ -1,110 +0,0 @@ -/** - * Copyright © 2021 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features.Metrics; -using PushTechnology.ClientInterface.Client.Session; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Features -{ - /// - /// Client implementation that demonstrates the topic metric collector. - /// - public sealed class TopicMetricCollector : IExample - { - /// - /// Runs the topic metric collector example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run(CancellationToken cancellationToken, string[] args) - { - string serverUrl = args[0]; - var session = Diffusion.Sessions.Principal("admin").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - var metrics = session.Metrics; - ITopicMetricCollector collector = null; - string topicSelector = "selector"; - - try - { - WriteLine($"Adding the topic metric collector 'Test' with topic selector '{topicSelector}'."); - - var builder = Diffusion.NewTopicMetricCollectorBuilder(); - builder = (ITopicMetricCollectorBuilder)builder.ExportsToPrometheus(true); - builder = (ITopicMetricCollectorBuilder)builder.GroupByTopicType(true); - builder = (ITopicMetricCollectorBuilder)builder.GroupByTopicView(true); - builder = (ITopicMetricCollectorBuilder)builder.MaximumGroups(10); - builder = (ITopicMetricCollectorBuilder)builder.GroupByPathPrefixParts(1); - collector = builder.Create("Test", topicSelector); - - await metrics.PutTopicMetricCollectorAsync(collector); - - WriteLine($"Topic metric collector '{collector.Name}' added."); - } - catch (Exception ex) - { - WriteLine($"Failed to add topic metric collector : {ex}."); - session.Close(); - return; - } - - try - { - WriteLine($"The following topic metric collectors exist:"); - - var listTopicMetricCollectors = await metrics.ListTopicMetricCollectorsAsync(); - - foreach (var topicMetricCollector in listTopicMetricCollectors) - { - WriteLine($"Name: '{topicMetricCollector.Name}', Topic selector: '{topicMetricCollector.TopicSelector}', " + - $"Maximum Groups: {topicMetricCollector.MaximumGroups}, " + - $"Exports to Prometheus: '{GetAnswer(topicMetricCollector.ExportsToPrometheus)}', " + - $"Group By Path Prefix Parts: {topicMetricCollector.GroupByPathPrefixParts}, " + - $"Groups by topic type: '{GetAnswer(topicMetricCollector.GroupsByTopicType)}', " + - $"Groups by topic view: '{GetAnswer(topicMetricCollector.GroupsByTopicView)}'"); - } - } - catch (Exception ex) - { - WriteLine($"Failed to list topic metric collectors : {ex}."); - session.Close(); - return; - } - - try - { - await metrics.RemoveTopicMetricCollectorAsync(collector.Name); - - WriteLine($"Collector '{collector.Name}' removed."); - } - catch (Exception ex) - { - WriteLine($"Failed to remove topic metric collector : {ex}."); - } - - // Close the session - session.Close(); - } - - private string GetAnswer(bool result) => result ? "Yes" : "No"; - } -} \ No newline at end of file diff --git a/dotnet/source/examples/Features/TopicViews.cs b/dotnet/source/examples/Features/TopicViews.cs deleted file mode 100644 index 9181b7a9..00000000 --- a/dotnet/source/examples/Features/TopicViews.cs +++ /dev/null @@ -1,128 +0,0 @@ -/** - * Copyright © 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using System.Threading; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features; -using PushTechnology.ClientInterface.Client.Topics; -using PushTechnology.ClientInterface.Client.Session; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; -using System.Linq; - -namespace PushTechnology.ClientInterface.Example.Features { - /// - /// Client implementation that creates and manages topic views. - /// - public sealed class TopicViews : IExample - { - /// - /// Runs the topic views example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run(CancellationToken cancellationToken, string[] args) - { - var serverUrl = args[0]; - var session = Diffusion.Sessions.Principal("control").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - // Create a topic - var topic = "a/path/0"; - - try - { - await session.TopicControl.AddTopicAsync(topic, TopicType.JSON, cancellationToken); - } - catch (Exception ex) - { - WriteLine($"Failed to add topic '{topic}' : {ex}."); - session.Close(); - return; - } - - try - { - var specification = "map ?a/path/ to prefix/"; - - ITopicView view1 = await session.TopicViews.CreateTopicViewAsync("View1", specification, CancellationToken.None); - WriteLine($"Topic view '{view1.Name}' was created."); - - ITopicView view2 = await session.TopicViews.CreateTopicViewAsync("View2", specification, CancellationToken.None); - WriteLine($"Topic view '{view2.Name}' was created."); - } - catch (Exception ex) - { - WriteLine($"Topic view could not be created : {ex}."); - session.Close(); - return; - } - - try - { - var listTask = await session.TopicViews.ListTopicViewsAsync(CancellationToken.None); - List views = listTask.ToList(); - - WriteLine($"Listing topic views - {views.Count} views were found:"); - - foreach (var view in views) - { - WriteLine($"Topic view '{view.Name}'"); - } - } - catch (Exception ex) - { - WriteLine($"Topic views could not be listed : {ex}."); - } - - try - { - ITopicView view1 = await session.TopicViews.GetTopicViewAsync("View1", CancellationToken.None); - WriteLine($"Topic view '{view1.Name}' was retrieved with specification '{view1.Specification}' and roles:"); - - foreach (var role in view1.Roles) - { - WriteLine($"'{role}'"); - } - } - catch (Exception ex) - { - WriteLine($"Topic view 'View1' could not be retrieved : {ex}."); - session.Close(); - return; - } - - try - { - await session.TopicViews.RemoveTopicViewAsync("View1", CancellationToken.None); - WriteLine($"Topic view 'View1' was removed."); - await session.TopicViews.RemoveTopicViewAsync("View2", CancellationToken.None); - WriteLine($"Topic view 'View2' was removed."); - } - catch (Exception ex) - { - WriteLine($"Topic view could not be removed : {ex}."); - } - - // Close the session - session.Close(); - } - } -} diff --git a/dotnet/source/examples/Publishing/AddAndSetTopic.cs b/dotnet/source/examples/Publishing/AddAndSetTopic.cs deleted file mode 100644 index c7fef5af..00000000 --- a/dotnet/source/examples/Publishing/AddAndSetTopic.cs +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Copyright © 2020, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Topics; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - - -namespace PushTechnology.ClientInterface.Example.Publishing { - /// - /// Control client implementation that adds a topic if it doesn't exist, or updates the same topic if it does exist. - /// - public sealed class AddAndSetTopic : IExample { - /// - /// Runs the AddAndSet topic update client example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancel, string[] args ) { - string serverUrl = args[ 0 ]; - var session = Diffusion.Sessions.Principal( "control" ).Password( "password" ) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - var topicUpdate = session.TopicUpdate; - - try { - // Attempt to add a topic, set its value to 0, and await the response from the server. - // If there was no topic previously bound to "test/topic", the method will return and create the topic and set its value to 0. - // If there is an existing INT64 topic with default topic properties bound to "test/topic" the method will set its value to 1. - // If an incompatible topic is bound to "test/topic", the method will throw ExistingTopicException. - var state = await topicUpdate.AddAndSetAsync( "test/topic", session.TopicControl.NewSpecification( TopicType.INT64 ), 0L ); - - WriteLine($"Topic 'test/topic' {state} with value: 0." ); - - state = await topicUpdate.AddAndSetAsync( "test/topic", session.TopicControl.NewSpecification( TopicType.INT64 ), 1L ); - - WriteLine($"Topic 'test/topic' {state} with value: 1."); - } - catch ( Exception ex ) { - WriteLine( $"Failed to add and set topic 'test/topic': {ex}." ); - session.Close(); - - return; - } - - try - { - await session.TopicControl.RemoveTopicsAsync("test/topic"); - - WriteLine($"Removed topic 'test/topic'."); - } - catch (Exception ex) - { - WriteLine($"Failed to remove topic 'test/topic': {ex}."); - } - finally - { - session.Close(); - } - } - } -} - - diff --git a/dotnet/source/examples/Publishing/AddAndSetTopicWithConstraint.cs b/dotnet/source/examples/Publishing/AddAndSetTopicWithConstraint.cs deleted file mode 100644 index 08bbeb73..00000000 --- a/dotnet/source/examples/Publishing/AddAndSetTopicWithConstraint.cs +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Copyright © 2020 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Topics; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Publishing { - /// - /// Control client implementation that adds a string topic with constraint then updates the topic with constraint. - /// - public sealed class AddAndSetTopicWithConstraint : IExample { - /// - /// Runs the add and set topic with constraint control client example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string TOPIC_PREFIX = "test-topics"; - - var serverUrl = args[0]; - var session = Diffusion.Sessions.Principal("control").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - var topicControl = session.TopicControl; - var topicUpdate = session.TopicUpdate; - - // Create a string topic - var topicPath = $"{TOPIC_PREFIX}/String"; - - var updateConstraint = Diffusion.UpdateConstraints.NoTopic; - - // Add and set the topic with constraint and expect success - try - { - await topicUpdate.AddAndSetAsync(topicPath, topicControl.NewSpecification(TopicType.STRING), "Value1", updateConstraint); - - WriteLine($"Topic '{topicPath}' successfully added as the topic did not originally exist - with it's value set to 'Value1'."); - } - catch (Exception ex) - { - WriteLine($"Failed to add/set topic '{topicPath}' : {ex}."); - session.Close(); - return; - } - - var updateConstraint2 = Diffusion.UpdateConstraints.Value("Value1"); - - // Set the topic value with constraint and expect success - try - { - await topicUpdate.AddAndSetAsync(topicPath, topicControl.NewSpecification(TopicType.STRING), "Value2", updateConstraint2); - - WriteLine($"Topic value set successfully with 'Value2' as topic value was previously 'Value1'."); - } - catch (Exception ex) - { - WriteLine($"Failed to update topic '{topicPath}' : {ex}."); - session.Close(); - return; - } - - // Close the session - session.Close(); - } - } -} diff --git a/dotnet/source/examples/Publishing/AddFallbackStream.cs b/dotnet/source/examples/Publishing/AddFallbackStream.cs deleted file mode 100644 index 8702dfd2..00000000 --- a/dotnet/source/examples/Publishing/AddFallbackStream.cs +++ /dev/null @@ -1,256 +0,0 @@ -/** - * Copyright © 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features; -using PushTechnology.ClientInterface.Client.Features.Topics; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Topics; -using PushTechnology.ClientInterface.Client.Topics.Details; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Publishing -{ - /// - /// Control client implementation of a fallback stream for topics. - /// - public sealed class AddFallbackStream : IExample - { - private const string TOPIC_PREFIX = "topic"; - - /// - /// Runs the client topic fallback stream example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run(CancellationToken cancellationToken, string[] args) - { - var selector = $"?{TOPIC_PREFIX}//"; - - var serverUrl = args[0]; - var session = Diffusion.Sessions.Principal("control").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - var clientSession = Diffusion.Sessions.Principal("client").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - try// Add topics and set their values - { - await session.TopicUpdate.AddAndSetAsync("topic/foo", session.TopicControl.NewSpecification(TopicType.STRING), "foo-string"); - - await session.TopicUpdate.AddAndSetAsync("topic/bar", session.TopicControl.NewSpecification(TopicType.STRING), "bar-string"); - - await session.TopicUpdate.AddAndSetAsync("topic/baz", session.TopicControl.NewSpecification(TopicType.STRING), "baz-string"); - } - catch (Exception ex) - { - WriteLine($"Failed to add topic and set its value : {ex}."); - - clientSession.Close(); - session.Close(); - return; - } - - IValueStream stringStream = null; - IValueStream fallbackStringStream = null; - - try - { - // Add a topic stream for 'topic/foo' - stringStream = new StringStream(); - clientSession.Topics.AddStream("topic/foo", stringStream); - } - catch (Exception ex) - { - WriteLine($"Failed to add value stream : {ex}."); - - await session.TopicControl.RemoveTopicsAsync(selector); - - clientSession.Close(); - session.Close(); - return; - } - - try - { - // Add a fallback stream for the other topics - fallbackStringStream = new FallbackStringStream(); - clientSession.Topics.AddFallbackStream(fallbackStringStream); - } - catch (Exception ex) - { - WriteLine($"Failed to add fallback stream : {ex}."); - - await session.TopicControl.RemoveTopicsAsync(selector); - - clientSession.Topics.RemoveStream(stringStream); - - clientSession.Close(); - session.Close(); - return; - } - - try - { - WriteLine($"Subscribing to topics."); - - await clientSession.Topics.SubscribeAsync(selector, cancellationToken); - - await Task.Delay(TimeSpan.FromSeconds(1)); - } - catch (Exception ex) - { - WriteLine($"Subscribing to topics failed : {ex}."); - - await session.TopicControl.RemoveTopicsAsync(selector); - - clientSession.Topics.RemoveStream(fallbackStringStream); - clientSession.Topics.RemoveStream(stringStream); - - clientSession.Close(); - session.Close(); - return; - } - - try//Clear up - { - await session.TopicControl.RemoveTopicsAsync(selector); - - WriteLine($"Topics removed."); - - clientSession.Topics.RemoveStream(fallbackStringStream); - clientSession.Topics.RemoveStream(stringStream); - - await clientSession.Topics.UnsubscribeAsync(selector, cancellationToken); - - WriteLine($"Unsubscribed to topics."); - } - catch (Exception ex) - { - WriteLine($"Clear up failed : {ex}."); - } - - clientSession.Close(); - session.Close(); - } - - /// - /// Basic implementation of the IValueStream for string topics. - /// - private sealed class StringStream : IValueStream - { - /// - /// Notification of stream being closed normally. - /// - public void OnClose() - => WriteLine("The subscription stream is now closed."); - - /// - /// Notification of a contextual error related to this callback. - /// - /// - /// Situations in which OnError is called include the session being closed, a communication - /// timeout, or a problem with the provided parameters. No further calls will be made to this callback. - /// - /// Error reason. - public void OnError(ErrorReason errorReason) - => WriteLine($"An error has occured : {errorReason}."); - - /// - /// Notification of a successful subscription. - /// - /// Topic path. - /// Topic specification. - public void OnSubscription(string topicPath, ITopicSpecification specification) - => WriteLine($"Client subscribed to '{topicPath}'."); - - /// - /// Notification of a successful unsubscription. - /// - /// Topic path. - /// Topic specification. - /// Error reason. - public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) - => WriteLine($"Client unsubscribed from '{topicPath}' : {reason}."); - - /// - /// Topic update received. - /// - /// Topic path. - /// Topic specification. - /// Value prior to update. - /// Value after update. - public void OnValue(string topicPath, ITopicSpecification specification, string oldValue, string newValue) - => WriteLine($"New value of '{topicPath}' is '{newValue}'."); - } - - /// - /// Basic implementation of the IValueStream for string topics as a fallback stream - /// - private sealed class FallbackStringStream : IValueStream - { - /// - /// Notification of stream being closed normally. - /// - public void OnClose() - => WriteLine("The fallback stream is now closed."); - - /// - /// Notification of a contextual error related to this callback. - /// - /// - /// Situations in which OnError is called include the session being closed, a communication - /// timeout, or a problem with the provided parameters. No further calls will be made to this callback. - /// - /// Error reason. - public void OnError(ErrorReason errorReason) - => WriteLine($"An error has occured : {errorReason}."); - - /// - /// Notification of a successful subscription. - /// - /// Topic path. - /// Topic specification. - public void OnSubscription(string topicPath, ITopicSpecification specification) - => WriteLine($"Client subscribed to '{topicPath}' using fallback stream."); - - /// - /// Notification of a successful unsubscription. - /// - /// Topic path. - /// Topic specification. - /// Error reason. - public void OnUnsubscription(string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason) - => WriteLine($"Client unsubscribed from '{topicPath}' : {reason}."); - - /// - /// Topic update received. - /// - /// Topic path. - /// Topic specification. - /// Value prior to update. - /// Value after update. - public void OnValue(string topicPath, ITopicSpecification specification, string oldValue, string newValue) - => WriteLine($"New value of '{topicPath}' is '{newValue}'."); - } - } -} diff --git a/dotnet/source/examples/Publishing/AddMissingTopicHandler.cs b/dotnet/source/examples/Publishing/AddMissingTopicHandler.cs deleted file mode 100644 index a08c1f23..00000000 --- a/dotnet/source/examples/Publishing/AddMissingTopicHandler.cs +++ /dev/null @@ -1,196 +0,0 @@ -/** - * Copyright © 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features.Control.Topics; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Topics; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Publishing -{ - /// - /// Control client implementation of a missing topic handler. - /// - public sealed class AddMissingTopicHandler : IExample - { - private const string TOPIC_PREFIX = "Example"; - private ISession session; - - /// - /// Runs the client missing topic handler example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run(CancellationToken cancellationToken, string[] args) - { - var selector = $"?{TOPIC_PREFIX}//"; - var topicPath = $"{TOPIC_PREFIX}"; - - var serverUrl = args[0]; - session = Diffusion.Sessions.Principal("control").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - var clientSession = Diffusion.Sessions.Principal("client").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - IRegistration registration = null; - - try - { - WriteLine($"Adding missing topic handler for topic '{topicPath}'."); - - registration = await session.TopicControl.AddMissingTopicHandlerAsync(topicPath, new MissingTopicNotificationStream(session)); - } - catch (Exception ex) - { - WriteLine($"Failed to add missing topic handler : {ex}."); - - clientSession.Close(); - session.Close(); - return; - } - - try - { - WriteLine($"Subscribing to topic '{topicPath}'."); - - await clientSession.Topics.SubscribeAsync(selector, cancellationToken); - - await Task.Delay(TimeSpan.FromSeconds(1)); - } - catch (Exception ex) - { - WriteLine($"Subscribing to topic '{topicPath}' failed : {ex}."); - - await registration.CloseAsync(); - - clientSession.Close(); - session.Close(); - return; - } - - try//Clear up - { - await session.TopicControl.RemoveTopicsAsync(topicPath); - - WriteLine($"Topic '{topicPath}' removed."); - - await clientSession.Topics.UnsubscribeAsync(selector, cancellationToken); - - WriteLine($"Unsubscribing to topic '{topicPath}'."); - - await registration.CloseAsync(); - } - catch(Exception ex) - { - WriteLine($"Clear up failed : {ex}."); - } - - clientSession.Close(); - session.Close(); - } - - /// - /// Basic implementation of the stream that will be called when a session subscribes using a topic selector - /// that matches no topics. - /// - private sealed class MissingTopicNotificationStream : IMissingTopicNotificationStream - { - private ISession session; - - public MissingTopicNotificationStream(ISession session) - { - this.session = session; - } - - /// - /// Notification of stream being closed normally. - /// - public void OnClose() - => WriteLine("Handler is removed."); - - /// - /// Notification of a contextual error related to this callback. - /// - /// - /// Situations in which OnError is called include the session being closed, a communication - /// timeout, or a problem with the provided parameters. No further calls will be made to this callback. - /// - /// Error reason. - public void OnError(ErrorReason errorReason) - => WriteLine($"An error has occured : {errorReason}."); - - /// - /// Called when a session requests a topic that does not exist, and the topic path - /// belongs to part of the topic tree for which this stream was registered. - /// - /// - public void OnMissingTopic(IMissingTopicNotification notification) - { - WriteLine($"Topic '{notification.TopicPath}' does not exist."); - - session.TopicControl.AddTopic(notification.TopicPath, session.TopicControl.NewSpecification(TopicType.STRING), new TopicControlAddCallback(notification)); - } - } - - /// - /// Implementation of a callback interface for adding topics. - /// - private sealed class TopicControlAddCallback : ITopicControlAddCallback - { - IMissingTopicNotification notification; - - public TopicControlAddCallback(IMissingTopicNotification notification) - { - this.notification = notification; - } - - /// - /// Called to notify that the session is closed. - /// - public void OnDiscard() - { - WriteLine("The stream is now closed."); - } - - /// - /// Called to indicate that the topic has been successfully added. - /// - /// - public void OnTopicAdded(string topicPath) - { - WriteLine($"Topic '{topicPath}' added."); - } - - /// - /// Called to indicate that an attempt to add a topic has failed. - /// - /// - /// - public void OnTopicAddFailed(string topicPath, TopicAddFailReason reason) - { - WriteLine($"The topic could not be added with reason: {reason}."); - } - } - } -} diff --git a/dotnet/source/examples/Publishing/ApplyJSONPatch.cs b/dotnet/source/examples/Publishing/ApplyJSONPatch.cs deleted file mode 100644 index b18754dc..00000000 --- a/dotnet/source/examples/Publishing/ApplyJSONPatch.cs +++ /dev/null @@ -1,124 +0,0 @@ -/** - * Copyright © 2020 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Topics; -using PushTechnology.ClientInterface.Data.JSON; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Publishing { - /// - /// Control client implementation that partially updates a JSON topic by applying a JSON patch. - /// - public sealed class ApplyJSONPatch : IExample { - /// - /// Runs the apply JSON patch control client example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string TOPIC_PREFIX = "test-topics"; - - var serverUrl = args[0]; - var session = Diffusion.Sessions.Principal("control").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - var topicControl = session.TopicControl; - var topicUpdate = session.TopicUpdate; - - var topicPath = $"{TOPIC_PREFIX}/{Guid.NewGuid()}"; - string json = "{\"foo\":\"bar\"}"; - - // Add and set the JSON topic - try - { - await topicUpdate.AddAndSetAsync(topicPath, topicControl.NewSpecification(TopicType.JSON), Diffusion.DataTypes.JSON.FromJSONString(json)); - - var result = await session.Topics.FetchRequest.First(1).TopicTypes(new[] { TopicType.JSON }).WithValues().FetchAsync(topicPath); - - WriteLine($"Topic '{topicPath}' successfully added with value '{result.Results.First().Value.ToJSONString()}'."); - } - catch (Exception ex) - { - WriteLine($"Failed to add/set topic '{topicPath}' : {ex}."); - session.Close(); - return; - } - - try - { - //1) Add new array value - string patch = "[{\"op\":\"add\",\"path\":\"/a\",\"value\":[\"c\",\"d\"]}]"; - - await topicUpdate.ApplyJSONPatchAsync(topicPath, patch); - - var result = await session.Topics.FetchRequest.First(1).TopicTypes(new[] { TopicType.JSON }).WithValues().FetchAsync(topicPath); - - WriteLine($"Applying json patch '{patch}' gives '{result.Results.First().Value.ToJSONString()}'."); - - //2) Add new array item at start - patch = "[{\"op\":\"add\",\"path\":\"/a/0\",\"value\":\"qux\"}]"; - - await topicUpdate.ApplyJSONPatchAsync(topicPath, patch); - - result = await session.Topics.FetchRequest.First(1).TopicTypes(new[] { TopicType.JSON }).WithValues().FetchAsync(topicPath); - - WriteLine($"Applying json patch '{patch}' gives '{result.Results.First().Value.ToJSONString()}'."); - - //3) Replace foo's value - patch = "[{\"op\":\"replace\",\"path\":\"/foo\",\"value\":[1,2,3]}]"; - - await topicUpdate.ApplyJSONPatchAsync(topicPath, patch); - - result = await session.Topics.FetchRequest.First(1).TopicTypes(new[] { TopicType.JSON }).WithValues().FetchAsync(topicPath); - - WriteLine($"Applying json patch '{patch}' gives '{result.Results.First().Value.ToJSONString()}'."); - - //4) Replace foo's array item at start - patch = "[{\"op\":\"replace\",\"path\":\"/foo/0\",\"value\":\"qux\"}]"; - - await topicUpdate.ApplyJSONPatchAsync(topicPath, patch); - - result = await session.Topics.FetchRequest.First(1).TopicTypes(new[] { TopicType.JSON }).WithValues().FetchAsync(topicPath); - - WriteLine($"Applying json patch '{patch}' gives '{result.Results.First().Value.ToJSONString()}'."); - - //5) Remove foo's array item at start - patch = "[{\"op\":\"remove\",\"path\":\"/foo/0\"}]"; - - await topicUpdate.ApplyJSONPatchAsync(topicPath, patch); - - result = await session.Topics.FetchRequest.First(1).TopicTypes(new[] { TopicType.JSON }).WithValues().FetchAsync(topicPath); - - WriteLine($"Applying json patch '{patch}' gives '{result.Results.First().Value.ToJSONString()}'."); - } - catch (Exception ex) - { - WriteLine($"Failed to apply patch: {ex}."); - session.Close(); - return; - } - - // Close the session - session.Close(); - } - } -} diff --git a/dotnet/source/examples/Publishing/BinaryTopics.cs b/dotnet/source/examples/Publishing/BinaryTopics.cs deleted file mode 100644 index 8f5c40ba..00000000 --- a/dotnet/source/examples/Publishing/BinaryTopics.cs +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Copyright © 2018, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Topics; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Publishing { - /// - /// Control client implementation that adds and updates a binary topic. - /// - public sealed class PublishingBinaryTopics : IExample { - /// - /// Runs the binary topic control client example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string serverUrl = args[ 0 ]; - var session = Diffusion.Sessions.Principal( "control" ).Password( "password" ) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - var topicControl = session.TopicControl; - var topicUpdate = session.TopicUpdate; - - var random = new Random(); - - // Create a binary topic 'random/Binary' - string topic = "random/Binary"; - - try { - await topicControl.AddTopicAsync( topic, TopicType.BINARY, cancellationToken ); - - WriteLine($"Topic '{topic}' added successfully."); - } - catch ( Exception ex ) { - WriteLine( $"Failed to add topic '{topic}' : {ex}." ); - session.Close(); - return; - } - - WriteLine($"Updating topic '{topic}' with new values:"); - - // Update topic every 300 ms until user requests cancellation of example - while ( !cancellationToken.IsCancellationRequested ) { - var newValue = Diffusion.DataTypes.Binary.ReadValue( - Encoding.UTF8.GetBytes( DateTime.Now.ToLongTimeString() ) ); - - try { - await topicUpdate.SetAsync( topic, newValue, cancellationToken ); - - await Task.Delay( TimeSpan.FromMilliseconds( 300 ) ); - } catch ( Exception ex ) { - WriteLine( $"Topic {topic} could not be updated : {ex}." ); - } - } - - // Remove the binary topic 'random/Binary' - try { - await topicControl.RemoveTopicsAsync( topic, cancellationToken ); - } catch ( Exception ex ) { - WriteLine( $"Failed to remove topic '{topic}' : {ex}." ); - } - - // Close the session - session.Close(); - } - } -} diff --git a/dotnet/source/examples/Publishing/DoubleTopics.cs b/dotnet/source/examples/Publishing/DoubleTopics.cs deleted file mode 100644 index cb05fdef..00000000 --- a/dotnet/source/examples/Publishing/DoubleTopics.cs +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Copyright © 2018, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Topics; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Publishing { - /// - /// Control client implementation that adds and updates a double topic. - /// - public sealed class PublishingDoubleTopics : IExample { - /// - /// Runs the double topic control client example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string serverUrl = args[ 0 ]; - var session = Diffusion.Sessions.Principal( "control" ).Password( "password" ) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - var topicControl = session.TopicControl; - var topicUpdate = session.TopicUpdate; - - var random = new Random(); - - // Create a double topic 'random/Double' - string topic = "random/Double"; - - try { - await topicControl.AddTopicAsync( topic, TopicType.DOUBLE, cancellationToken ); - - WriteLine($"Topic '{topic}' added successfully."); - } - catch ( Exception ex ) { - WriteLine( $"Failed to add topic '{topic}' : {ex}." ); - session.Close(); - return; - } - - WriteLine($"Updating topic '{topic}' with new values:"); - - // Update topic every 300 ms until user requests cancellation of example - while ( !cancellationToken.IsCancellationRequested ) { - double newValue = random.NextDouble(); - - try { - await topicUpdate.SetAsync( topic, newValue, cancellationToken ); - - await Task.Delay( TimeSpan.FromMilliseconds( 300 ) ); - } catch ( Exception ex ) { - WriteLine( $"Topic {topic} could not be updated : {ex}." ); - } - } - - // Remove the double topic 'random/Double' - try { - await topicControl.RemoveTopicsAsync( topic, cancellationToken ); - } catch ( Exception ex ) { - WriteLine( $"Failed to remove topic '{topic}' : {ex}." ); - } - - // Close the session - session.Close(); - } - } -} diff --git a/dotnet/source/examples/Publishing/FilterRequestMessages.cs b/dotnet/source/examples/Publishing/FilterRequestMessages.cs deleted file mode 100644 index 99662bf7..00000000 --- a/dotnet/source/examples/Publishing/FilterRequestMessages.cs +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright © 2018 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features; -using PushTechnology.ClientInterface.Client.Session; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Publishing { - /// - /// Control client implementation that sends request messages to a filter and if it gets response displays it on the - /// system console, and sends another request directly to the session. - /// - public sealed class SendingFilterRequestMessages : IExample { - private readonly string messagingPath = ">random/requestResponse"; - - /// - /// Runs the client sending request/response messages example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string serverUrl = args[ 0 ]; - var session = Diffusion.Sessions.Principal( "control" ).Password( "password" ) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - var messaging = session.Messaging; - var requestCallback = new RequestCallback(); - - while ( !cancellationToken.IsCancellationRequested ) { - int requestsSent = await messaging.SendRequestToFilterAsync( - "$Principal EQ 'client'", - messagingPath, - "Time", - requestCallback, - cancellationToken ); - WriteLine( $"Sent request to {requestsSent} session(s) matching the filter." ); - - await Task.Delay( TimeSpan.FromMilliseconds( 1000 ) ); - } - - // Close the session - session.Close(); - } - - /// - /// A simple IFilteredRequestCallback implementation that prints confirmation of the actions completed. - /// - private class RequestCallback : IFilteredRequestCallback { - /// - /// Indicates that a response message was received. - /// - public void OnResponse( ISessionId sessionId, string response ) - => WriteLine( $"Received response: '{response}'." ); - - /// - /// Indicates that a error response message was received. - /// - public void OnResponseError( ISessionId sessionId, Exception exception ) - => WriteLine( $"Response error received from session {sessionId}: '{exception}'." ); - } - } -} diff --git a/dotnet/source/examples/Publishing/IntegerTopics.cs b/dotnet/source/examples/Publishing/IntegerTopics.cs deleted file mode 100644 index 7ce1b27c..00000000 --- a/dotnet/source/examples/Publishing/IntegerTopics.cs +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Copyright © 2018, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Topics; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Publishing { - /// - /// Control client implementation that adds and updates an integer topic. - /// - public sealed class PublishingIntegerTopics : IExample { - /// - /// Runs the integer topic control client example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string serverUrl = args[ 0 ]; - var session = Diffusion.Sessions.Principal( "control" ).Password( "password" ) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - var topicControl = session.TopicControl; - var topicUpdate = session.TopicUpdate; - - var random = new Random(); - - // Create a Integer topic 'random/Integer' - string topic = "random/Integer"; - - try { - await topicControl.AddTopicAsync( topic, TopicType.INT64, cancellationToken ); - - WriteLine($"Topic '{topic}' added successfully."); - } - catch ( Exception ex ) { - WriteLine( $"Failed to add topic '{topic}' : {ex}." ); - session.Close(); - return; - } - - WriteLine($"Updating topic '{topic}' with new values:"); - - // Update topic every 300 ms until user requests cancellation of example - while ( !cancellationToken.IsCancellationRequested ) { - long newValue = (long) random.Next(); - - try { - await topicUpdate.SetAsync( topic, newValue, cancellationToken ); - - await Task.Delay( TimeSpan.FromMilliseconds( 300 ) ); - } catch ( Exception ex ) { - WriteLine( $"Topic {topic} could not be updated : {ex}." ); - } - } - - // Remove the Integer topic 'random/Integer' - try { - await topicControl.RemoveTopicsAsync( topic, cancellationToken ); - } catch ( Exception ex ) { - WriteLine( $"Failed to remove topic '{topic}' : {ex}." ); - } - - // Close the session - session.Close(); - } - } -} diff --git a/dotnet/source/examples/Publishing/JSONTopics.cs b/dotnet/source/examples/Publishing/JSONTopics.cs deleted file mode 100644 index 047c7b36..00000000 --- a/dotnet/source/examples/Publishing/JSONTopics.cs +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright © 2016, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Topics; - -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Publishing -{ - /// - /// Control client implementation that adds and updates a JSON topic. - /// - public sealed class PublishingJSONTopics : IExample { - /// - /// Runs the JSON topic control client example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string serverUrl = args[ 0 ]; - var session = Diffusion.Sessions.Principal( "control" ).Password( "password" ) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open( serverUrl ); - - var topicControl = session.TopicControl; - var topicUpdate = session.TopicUpdate; - - // Create a JSON topic 'random/JSON' - string topic = "random/JSON"; - - try { - await topicControl.AddTopicAsync( topic, TopicType.JSON, cancellationToken ); - WriteLine($"Topic '{topic}' added successfully."); - } - catch ( Exception ex ) { - WriteLine( $"Failed to add topic '{topic}' : {ex}." ); - session.Close(); - return; - } - - WriteLine($"Updating topic '{topic}' with new values:"); - - // Update topic every 300 ms until user requests cancellation of example - while ( !cancellationToken.IsCancellationRequested ) { - var newValue = Diffusion.DataTypes.JSON.FromJSONString( - "{\"date\":\"" + DateTime.Today.Date.ToString( "D" ) + "\"," + - "\"time\":\"" + DateTime.Now.TimeOfDay.ToString( "g" ) + "\"}" ); - - try { - await topicUpdate.SetAsync( topic, newValue, cancellationToken ); - - await Task.Delay( TimeSpan.FromMilliseconds( 300 ) ); - } catch ( Exception ex ) { - WriteLine( $"Topic {topic} could not be updated : {ex}." ); - } - } - - // Remove the JSON topic 'random/JSON' - try { - await topicControl.RemoveTopicsAsync( topic, cancellationToken ); - } catch ( Exception ex ) { - WriteLine( $"Failed to remove topic '{topic}' : {ex}." ); - } - - // Close the session - session.Close(); - } - } -} diff --git a/dotnet/source/examples/Publishing/PathRequestMessages.cs b/dotnet/source/examples/Publishing/PathRequestMessages.cs deleted file mode 100644 index 530f9831..00000000 --- a/dotnet/source/examples/Publishing/PathRequestMessages.cs +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Copyright © 2018, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Session; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Publishing { - /// - /// Control client implementation that sends request messages to a path and if it gets a response it displays it on the - /// system console. - /// - public sealed class SendingPathRequestMessages : IExample { - /// - /// Runs the client sending request/response messages example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string serverUrl = args[ 0 ]; - var session = Diffusion.Sessions.Principal("control").Password( "password" ) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - var messaging = session.Messaging; - string messagingPath = ">random/requestResponse"; - - while ( !cancellationToken.IsCancellationRequested ) { - try { - string response = await messaging.SendRequestAsync( - messagingPath, "Time", cancellationToken ); - WriteLine( $"Received response: '{response}'." ); - } catch ( Exception e ) { - WriteLine( $"Got exception: '{e.Message}'." ); - } - - await Task.Delay( TimeSpan.FromMilliseconds( 1000 ) ); - } - - // Close the session - session.Close(); - } - } -} diff --git a/dotnet/source/examples/Publishing/Publishing.projitems b/dotnet/source/examples/Publishing/Publishing.projitems deleted file mode 100644 index 39fcc56c..00000000 --- a/dotnet/source/examples/Publishing/Publishing.projitems +++ /dev/null @@ -1,36 +0,0 @@ - - - - $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - true - 960603fe-de40-42fe-a1e7-1284e3af1a15 - - - PushTechnology.ClientInterface.Example.Publishing - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dotnet/source/examples/Publishing/Publishing.shproj b/dotnet/source/examples/Publishing/Publishing.shproj deleted file mode 100644 index f70c49f0..00000000 --- a/dotnet/source/examples/Publishing/Publishing.shproj +++ /dev/null @@ -1,13 +0,0 @@ - - - - 960603fe-de40-42fe-a1e7-1284e3af1a15 - 14.0 - - - - - - - - diff --git a/dotnet/source/examples/Publishing/RecordV2Topics.cs b/dotnet/source/examples/Publishing/RecordV2Topics.cs deleted file mode 100644 index f433142c..00000000 --- a/dotnet/source/examples/Publishing/RecordV2Topics.cs +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Copyright © 2018, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Topics; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Publishing { - /// - /// Control client implementation that adds and updates a RecordV2 topic. - /// - public sealed class PublishingRecordV2Topics : IExample { - /// - /// Runs the RecordV2 topic control client example. - /// - /// A token used to end the client example. - /// A single string should be used for the server URL. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string serverUrl = args[ 0 ]; - var session = Diffusion.Sessions.Principal( "control" ).Password( "password" ) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - var topicControl = session.TopicControl; - var topicUpdate = session.TopicUpdate; - - var random = new Random(); - - // Create a RecordV2 topic 'random/RecordV2' - string topic = "random/RecordV2"; - - try { - await topicControl.AddTopicAsync( topic, TopicType.RECORD_V2, cancellationToken ); - - WriteLine($"Topic '{topic}' added successfully."); - } - catch ( Exception ex ) { - WriteLine( $"Failed to add topic '{topic}' : {ex}." ); - session.Close(); - return; - } - - WriteLine($"Updating topic '{topic}' with new values:"); - - // Update topic every 300 ms until user requests cancellation of example - while ( !cancellationToken.IsCancellationRequested ) { - var builder = Diffusion.DataTypes.RecordV2.CreateValueBuilder(); - var fields = new List() { DateTime.Now.ToLongTimeString(), "this", "is", "an", "example" }; - builder.AddFields( fields ); - var newValue = builder.Build(); - - try { - await topicUpdate.SetAsync( topic, newValue, cancellationToken ); - - await Task.Delay( TimeSpan.FromMilliseconds( 300 ) ); - } catch ( Exception ex ) { - WriteLine( $"Topic {topic} could not be updated : {ex}." ); - } - } - - // Remove the RecordV2 topic 'random/RecordV2' - try { - await topicControl.RemoveTopicsAsync( topic, cancellationToken ); - } catch ( Exception ex ) { - WriteLine( $"Failed to remove topic '{topic}' : {ex}." ); - } - - // Close the session - session.Close(); - } - } -} diff --git a/dotnet/source/examples/Publishing/RemoveTopics.cs b/dotnet/source/examples/Publishing/RemoveTopics.cs deleted file mode 100644 index e320330c..00000000 --- a/dotnet/source/examples/Publishing/RemoveTopics.cs +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Copyright © 2020, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Topics; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Publishing { - /// - /// Control client implementation that adds then removes a string topic. - /// - public sealed class RemoveTopics : IExample { - /// - /// Runs the remove topic control client example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string TOPIC_PREFIX = "test-topics"; - - var serverUrl = args[ 0 ]; - var session = Diffusion.Sessions.Principal("control").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - var topicControl = session.TopicControl; - - // Create a string topic - var topicPath = $"{TOPIC_PREFIX}/String"; - - // Add topic - try - { - await topicControl.AddTopicAsync(topicPath, TopicType.STRING, cancellationToken ); - - WriteLine($"Topic '{topicPath}' successfully added."); - } - catch (Exception ex) { - WriteLine( $"Failed to add topic '{topicPath}' : {ex}." ); - session.Close(); - return; - } - - // Add again but this will fail as the topic already exists - try - { - var addTopicResult = await topicControl.AddTopicAsync(topicPath, TopicType.STRING, cancellationToken); - - var result = (addTopicResult == Client.Features.Control.Topics.AddTopicResult.EXISTS) ? "already exists so could not be added": "does not exist so was added"; - WriteLine($"Topic '{topicPath}' {result}."); - } - catch (Exception ex) - { - WriteLine($"Failed to add topic '{topicPath}' : {ex}."); - session.Close(); - return; - } - - // Remove the string topic - try - { - WriteLine($"Removing topic '{topicPath}'."); - - var result = await topicControl.RemoveTopicsAsync($"?{TOPIC_PREFIX}/", cancellationToken ); - - WriteLine($"{result.RemovedCount} topic successfully removed."); - } - catch (Exception ex) { - WriteLine( $"Failed to remove topic '{topicPath}' : {ex}." ); - } - - // Add again but this time there is success - try - { - var addTopicResult = await topicControl.AddTopicAsync(topicPath, TopicType.STRING, cancellationToken); - - var result = (addTopicResult == Client.Features.Control.Topics.AddTopicResult.EXISTS) ? "already exists so could not be added" : "does not exist so was added"; - WriteLine($"Topic '{topicPath}' {result}."); - } - catch (Exception ex) - { - WriteLine($"Failed to add topic '{topicPath}' : {ex}."); - session.Close(); - return; - } - - // Close the session - session.Close(); - } - } -} diff --git a/dotnet/source/examples/Publishing/SessionRequestMessages.cs b/dotnet/source/examples/Publishing/SessionRequestMessages.cs deleted file mode 100644 index 98665bf9..00000000 --- a/dotnet/source/examples/Publishing/SessionRequestMessages.cs +++ /dev/null @@ -1,89 +0,0 @@ -/** - * Copyright © 2018 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features; -using PushTechnology.ClientInterface.Client.Session; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Publishing { - /// - /// Control client implementation that sends request messages to a filter and if it gets response displays it on the - /// system console, and sends another request directly to the session. - /// - public sealed class SendingSessionRequestMessages : IExample { - private readonly string messagingPath = ">random/requestResponse"; - - /// - /// Runs the client sending request/response messages example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string serverUrl = args[ 0 ]; - var session = Diffusion.Sessions.Principal( "control" ).Password( "password" ) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - var messaging = session.Messaging; - var requestCallback = new RequestCallback(); - - // Filter messaging is used to get the session ID for this example - int requestsSent = await messaging.SendRequestToFilterAsync( - "$Principal EQ 'client'", - messagingPath, - "Hello?", - requestCallback, - cancellationToken); - - await Task.Delay(TimeSpan.FromMilliseconds(1000)); - - while ( !cancellationToken.IsCancellationRequested ) { - // Send message to a session using obtained session ID - string response = await messaging.SendRequestAsync( - requestCallback.SessionId, messagingPath, "Time", cancellationToken); - WriteLine($"Received response: '{response}'."); - - await Task.Delay( TimeSpan.FromMilliseconds( 1000 ) ); - } - - // Close the session - session.Close(); - } - - /// - /// A simple IFilteredRequestCallback implementation that prints confirmation of the actions completed. - /// - private class RequestCallback : IFilteredRequestCallback { - public ISessionId SessionId { get; private set; } - - /// - /// Indicates that a response message was received. - /// - public void OnResponse(ISessionId sessionId, string response) => SessionId = sessionId; - - /// - /// Indicates that a error response message was received. - /// - public void OnResponseError( ISessionId sessionId, Exception exception ) - => WriteLine( $"Response error received from session {sessionId}: '{exception}'." ); - } - } -} diff --git a/dotnet/source/examples/Publishing/SetTopicWithConstraint.cs b/dotnet/source/examples/Publishing/SetTopicWithConstraint.cs deleted file mode 100644 index 3f974b4a..00000000 --- a/dotnet/source/examples/Publishing/SetTopicWithConstraint.cs +++ /dev/null @@ -1,97 +0,0 @@ -/** - * Copyright © 2020 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Topics; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Publishing { - /// - /// Control client implementation that adds and updates a string topic with constraint. - /// - public sealed class SetTopicWithConstraint : IExample { - /// - /// Runs the set topic with constraint control client example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string TOPIC_PREFIX = "test-topics"; - - var serverUrl = args[0]; - var session = Diffusion.Sessions.Principal("control").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - var topicControl = session.TopicControl; - var topicUpdate = session.TopicUpdate; - - // Create a string topic - var topicPath = $"{TOPIC_PREFIX}/String"; - - // Add topic - try - { - await topicControl.AddTopicAsync(topicPath, TopicType.STRING, cancellationToken); - - WriteLine($"Topic '{topicPath}' successfully added."); - } - catch (Exception ex) - { - WriteLine($"Failed to add topic '{topicPath}' : {ex}."); - session.Close(); - return; - } - - var updateConstraint = Diffusion.UpdateConstraints.NoValue; - - // Set the topic value with constraint and expect success - try - { - await topicUpdate.SetAsync(topicPath, "Value1", updateConstraint); - - WriteLine($"Topic value set successfully with 'Value1' as topic had no value originally."); - } - catch (Exception ex) - { - WriteLine($"Failed to update topic '{topicPath}' : {ex}."); - session.Close(); - return; - } - - var updateConstraint2 = Diffusion.UpdateConstraints.Value("Value1"); - - // Set the topic value with constraint and expect success - try - { - await topicUpdate.SetAsync(topicPath, "Value2", updateConstraint2); - WriteLine($"Topic value set successfully with 'Value2' as topic value was previously 'Value1'."); - } - catch (Exception ex) - { - WriteLine($"Failed to update topic '{topicPath}' : {ex}."); - session.Close(); - return; - } - - // Close the session - session.Close(); - } - } -} diff --git a/dotnet/source/examples/Publishing/StringTopics.cs b/dotnet/source/examples/Publishing/StringTopics.cs deleted file mode 100644 index 59975aae..00000000 --- a/dotnet/source/examples/Publishing/StringTopics.cs +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright © 2018, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Topics; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Publishing { - /// - /// Control client implementation that adds and updates a string topic. - /// - public sealed class PublishingStringTopics : IExample { - /// - /// Runs the string topic control client example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string serverUrl = args[ 0 ]; - var session = Diffusion.Sessions.Principal( "control" ).Password( "password" ) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - - var topicControl = session.TopicControl; - var topicUpdate = session.TopicUpdate; - - // Create a string topic 'random/String' - string topic = "random/String"; - - try { - await topicControl.AddTopicAsync( topic, TopicType.STRING, cancellationToken ); - - WriteLine($"Topic '{topic}' added successfully."); - } - catch (Exception ex) { - WriteLine( $"Failed to add topic '{topic}' : {ex}." ); - session.Close(); - return; - } - - WriteLine($"Updating topic '{topic}' with new values:"); - - // Update topic every 300 ms until user requests cancellation of example - while (!cancellationToken.IsCancellationRequested) { - string newValue = DateTime.Today.Date.ToString( "D" ) + " " + - DateTime.Now.TimeOfDay.ToString( "g" ); - - try { - await topicUpdate.SetAsync( topic, newValue, cancellationToken ); - - await Task.Delay( TimeSpan.FromMilliseconds( 300 ) ); - } catch ( Exception ex ) { - WriteLine( $"Topic {topic} could not be updated : {ex}." ); - } - } - - // Remove the string topic 'random/String' - try { - await topicControl.RemoveTopicsAsync( topic, cancellationToken ); - } catch(Exception ex) { - WriteLine( $"Failed to remove topic '{topic}' : {ex}." ); - } - - // Close the session - session.Close(); - } - } -} diff --git a/dotnet/source/examples/Publishing/TimeSeriesAddTopics.cs b/dotnet/source/examples/Publishing/TimeSeriesAddTopics.cs deleted file mode 100644 index 0008fe53..00000000 --- a/dotnet/source/examples/Publishing/TimeSeriesAddTopics.cs +++ /dev/null @@ -1,89 +0,0 @@ -/** - * Copyright © 2020 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features.Control.Topics; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Topics; -using PushTechnology.ClientInterface.Client.Topics.Details; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Publishing { - /// - /// Control client implementation that adds a time series topic. - /// - public sealed class PublishingTimeSeriesAddTopics : IExample { - /// - /// Runs the time series add topics control client example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string TOPIC_PREFIX = "time-series"; - - var serverUrl = args[ 0 ]; - var session = Diffusion.Sessions.Principal( "control" ).Password( "password" ) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open( serverUrl ); - - // Create a string topic - var typeName = Diffusion.DataTypes.Get().TypeName; - var topic = $"{TOPIC_PREFIX}/{typeName}/{DateTime.Now.ToFileTimeUtc()}"; - var specification = session.TopicControl.NewSpecification(TopicType.TIME_SERIES) - .WithProperty(TopicSpecificationProperty.TimeSeriesEventValueType, typeName); - - try - { - await session.TopicControl.AddTopicAsync(topic, specification, cancellationToken); - - var newValue = DateTime.Today.Date.ToString("D") + " " + - DateTime.Now.TimeOfDay.ToString("g"); - - try - { - await session.TopicUpdate.SetAsync(topic, newValue, cancellationToken); - - await Task.Delay(TimeSpan.FromMilliseconds(300)); - } - catch (Exception ex) - { - Console.WriteLine($"Topic {topic} could not be updated : {ex}."); - } - } - catch (Exception ex) - { - WriteLine($"Failed to add topic '{topic}' : {ex}."); - session.Close(); - return; - } - - // Remove the string topic - try - { - await session.TopicControl.RemoveTopicsAsync( topic, cancellationToken ); - } catch(Exception ex) { - WriteLine( $"Failed to remove topic '{topic}' : {ex}." ); - } - - // Close the session - session.Close(); - } - } -} diff --git a/dotnet/source/examples/Publishing/TimeSeriesAppend.cs b/dotnet/source/examples/Publishing/TimeSeriesAppend.cs deleted file mode 100644 index 80936023..00000000 --- a/dotnet/source/examples/Publishing/TimeSeriesAppend.cs +++ /dev/null @@ -1,89 +0,0 @@ -/** - * Copyright © 2020 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features.Control.Topics; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Topics; -using PushTechnology.ClientInterface.Client.Topics.Details; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Publishing { - /// - /// Control client implementation that appends values to a time series topic. - /// - public sealed class PublishingTimeSeriesAppend : IExample { - /// - /// Runs the time series topic append control client example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string TOPIC_PREFIX = "time-series"; - - var serverUrl = args[ 0 ]; - var session = Diffusion.Sessions.Principal( "control" ).Password( "password" ) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open( serverUrl ); - - // Create a string topic - var typeName = Diffusion.DataTypes.Get().TypeName; - var topicPath = $"{TOPIC_PREFIX}/{typeName}/{DateTime.Now.ToFileTimeUtc()}"; - var specification = session.TopicControl.NewSpecification(TopicType.TIME_SERIES) - .WithProperty(TopicSpecificationProperty.TimeSeriesEventValueType, typeName); - - try - { - await session.TopicControl.AddTopicAsync(topicPath, specification, cancellationToken); - } - catch (Exception ex) - { - WriteLine($"Failed to add topic '{topicPath}' : {ex}."); - session.Close(); - return; - } - - try - { - await session.TimeSeries.AppendAsync(topicPath, "Value 1", cancellationToken); - await session.TimeSeries.AppendAsync(topicPath, "Value 2", cancellationToken); - await session.TimeSeries.AppendAsync(topicPath, "Value 3", cancellationToken); - await session.TimeSeries.AppendAsync(topicPath, "Value 4", cancellationToken); - - await Task.Delay(TimeSpan.FromMilliseconds(300)); - } - catch (Exception ex) - { - WriteLine($"Topic {topicPath} value could not be appended : {ex}."); - } - - // Remove the string topic - try - { - await session.TopicControl.RemoveTopicsAsync( topicPath, cancellationToken ); - } catch(Exception ex) { - WriteLine( $"Failed to remove topic '{topicPath}' : {ex}." ); - } - - // Close the session - session.Close(); - } - } -} diff --git a/dotnet/source/examples/Publishing/TimeSeriesAppendWithTimestamp.cs b/dotnet/source/examples/Publishing/TimeSeriesAppendWithTimestamp.cs deleted file mode 100644 index 339d382d..00000000 --- a/dotnet/source/examples/Publishing/TimeSeriesAppendWithTimestamp.cs +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Copyright © 2020 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features.Control.Topics; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Topics; -using PushTechnology.ClientInterface.Client.Topics.Details; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Publishing { - /// - /// Control client implementation that appends values with a user supplied timestamp to a time series topic. - /// - public sealed class PublishingTimeSeriesAppendWithTimestamp : IExample { - /// - /// Runs the time series topic append (with timestamp) control client example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string TOPIC_PREFIX = "time-series"; - - var serverUrl = args[ 0 ]; - var session = Diffusion.Sessions.Principal( "control" ).Password( "password" ) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open( serverUrl ); - - // Create a string topic - var typeName = Diffusion.DataTypes.Get().TypeName; - var topicPath = $"{TOPIC_PREFIX}/{typeName}/{DateTime.Now.ToFileTimeUtc()}"; - var specification = session.TopicControl.NewSpecification(TopicType.TIME_SERIES) - .WithProperty(TopicSpecificationProperty.TimeSeriesEventValueType, typeName); - - try - { - await session.TopicControl.AddTopicAsync(topicPath, specification, cancellationToken); - } - catch (Exception ex) - { - WriteLine($"Failed to add topic '{topicPath}' : {ex}."); - session.Close(); - return; - } - - try - { - await session.TimeSeries.AppendAsync(topicPath, "Value1", DateTimeOffset.FromUnixTimeMilliseconds(322), cancellationToken); - await session.TimeSeries.AppendAsync(topicPath, "Value1", DateTimeOffset.FromUnixTimeMilliseconds(323), cancellationToken); - await session.TimeSeries.AppendAsync(topicPath, "Value1", DateTimeOffset.FromUnixTimeMilliseconds(323), cancellationToken); - await session.TimeSeries.AppendAsync(topicPath, "Value1", DateTimeOffset.FromUnixTimeMilliseconds(324), cancellationToken); - await session.TimeSeries.AppendAsync(topicPath, "Value1", DateTimeOffset.FromUnixTimeMilliseconds(325), cancellationToken); - - await Task.Delay(TimeSpan.FromMilliseconds(300)); - } - catch (Exception ex) - { - WriteLine($"Topic {topicPath} value could not be appended : {ex}."); - } - - // Remove the string topic - try - { - await session.TopicControl.RemoveTopicsAsync( topicPath, cancellationToken ); - } catch(Exception ex) { - WriteLine( $"Failed to remove topic '{topicPath}' : {ex}." ); - } - - // Close the session - session.Close(); - } - } -} diff --git a/dotnet/source/examples/Publishing/TimeSeriesEdit.cs b/dotnet/source/examples/Publishing/TimeSeriesEdit.cs deleted file mode 100644 index 38cb57d3..00000000 --- a/dotnet/source/examples/Publishing/TimeSeriesEdit.cs +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Copyright © 2020 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features.Control.Topics; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Topics; -using PushTechnology.ClientInterface.Client.Topics.Details; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Publishing { - /// - /// Control client implementation that edits values of a time series topic. - /// - public sealed class PublishingTimeSeriesEdit : IExample { - /// - /// Runs the time series topic edit control client example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string TOPIC_PREFIX = "time-series"; - - var serverUrl = args[ 0 ]; - var session = Diffusion.Sessions.Principal( "control" ).Password( "password" ) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open( serverUrl ); - - // Create a string topic - var typeName = Diffusion.DataTypes.Get().TypeName; - var topicPath = $"{TOPIC_PREFIX}/{typeName}/{DateTime.Now.ToFileTimeUtc()}"; - var specification = session.TopicControl.NewSpecification(TopicType.TIME_SERIES) - .WithProperty(TopicSpecificationProperty.TimeSeriesEventValueType, typeName); - - try - { - await session.TopicControl.AddTopicAsync(topicPath, specification, cancellationToken); - } - catch (Exception ex) - { - WriteLine($"Failed to add topic '{topicPath}' : {ex}."); - session.Close(); - return; - } - - try - { - await session.TimeSeries.AppendAsync(topicPath, "Value 1", cancellationToken); - } - catch (Exception ex) - { - WriteLine($"Topic {topicPath} value could not be appended : {ex}."); - } - - try - { - await session.TimeSeries.EditAsync(topicPath, 0, "Value 1a", cancellationToken); - await session.TimeSeries.EditAsync(topicPath, 0, "Value 1b", cancellationToken); - await session.TimeSeries.EditAsync(topicPath, 0, "Value 1c", cancellationToken); - await session.TimeSeries.EditAsync(topicPath, 0, "Value 1d", cancellationToken); - } - catch (Exception ex) - { - WriteLine($"Topic {topicPath} value could not be edited : {ex}."); - } - - // Remove the string topic - try - { - await session.TopicControl.RemoveTopicsAsync( topicPath, cancellationToken ); - } catch(Exception ex) { - WriteLine( $"Failed to remove topic '{topicPath}' : {ex}." ); - } - - // Close the session - session.Close(); - } - } -} diff --git a/dotnet/source/examples/Publishing/TimeSeriesRangeQuery.cs b/dotnet/source/examples/Publishing/TimeSeriesRangeQuery.cs deleted file mode 100644 index c28fb512..00000000 --- a/dotnet/source/examples/Publishing/TimeSeriesRangeQuery.cs +++ /dev/null @@ -1,119 +0,0 @@ -/** - * Copyright © 2020 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features.Control.Topics; -using PushTechnology.ClientInterface.Client.Features.TimeSeries; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Topics; -using PushTechnology.ClientInterface.Client.Topics.Details; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Publishing { - /// - /// Control client implementation that performs a range query of a time series. - /// - public sealed class PublishingTimeSeriesRangeQuery : IExample { - /// - /// Runs the time series range query control client example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - string TOPIC_PREFIX = "time-series"; - - var serverUrl = args[ 0 ]; - var session = Diffusion.Sessions.Principal( "control" ).Password( "password" ) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open( serverUrl ); - - // Create a string topic - var typeName = Diffusion.DataTypes.Get().TypeName; - var topicPath = $"{TOPIC_PREFIX}/{typeName}/{DateTime.Now.ToFileTimeUtc()}"; - var specification = session.TopicControl.NewSpecification(TopicType.TIME_SERIES) - .WithProperty(TopicSpecificationProperty.TimeSeriesEventValueType, typeName); - - try - { - await session.TopicControl.AddTopicAsync(topicPath, specification, cancellationToken); - } - catch (Exception ex) - { - WriteLine($"Failed to add topic '{topicPath}' : {ex}."); - session.Close(); - return; - } - - try - { - await session.TimeSeries.AppendAsync(topicPath, "Value1", DateTimeOffset.FromUnixTimeMilliseconds(200), cancellationToken); - await session.TimeSeries.AppendAsync(topicPath, "Value2", DateTimeOffset.FromUnixTimeMilliseconds(301), cancellationToken); - await session.TimeSeries.AppendAsync(topicPath, "Value3", DateTimeOffset.FromUnixTimeMilliseconds(301), cancellationToken); - await session.TimeSeries.AppendAsync(topicPath, "Value4", DateTimeOffset.FromUnixTimeMilliseconds(301), cancellationToken); - await session.TimeSeries.AppendAsync(topicPath, "Value5", DateTimeOffset.FromUnixTimeMilliseconds(324), cancellationToken); - await session.TimeSeries.AppendAsync(topicPath, "Value6", DateTimeOffset.FromUnixTimeMilliseconds(501), cancellationToken); - await session.TimeSeries.AppendAsync(topicPath, "Value7", DateTimeOffset.FromUnixTimeMilliseconds(501), cancellationToken); - await session.TimeSeries.AppendAsync(topicPath, "Value8", DateTimeOffset.FromUnixTimeMilliseconds(501), cancellationToken); - - await Task.Delay(TimeSpan.FromMilliseconds(300)); - } - catch (Exception ex) - { - WriteLine($"Topic {topicPath} value could not be appended : {ex}."); - } - - try - { - IRangeQuery rangeQuery = session.TimeSeries.RangeQuery.As(); - - var taskRange = rangeQuery - .From(DateTimeOffset.FromUnixTimeMilliseconds(301L)) - .To(DateTimeOffset.FromUnixTimeMilliseconds(501L)) - .SelectFromAsync(topicPath); - - taskRange.Wait(TimeSpan.FromSeconds(20)); - - var results = taskRange.Result.Events.ToList(); - WriteLine($"{results.Count} results obtained from range query (301 to 501):"); - - foreach(var result in results) - { - WriteLine($"Sequence number: {result.Metadata.Sequence}, Value: {result.Value} with Timestamp: {result.Metadata.Timestamp}"); - } - } - catch (Exception ex) - { - WriteLine($"Range query failed for topic {topicPath} : {ex}."); - } - - // Remove the string topic - try - { - await session.TopicControl.RemoveTopicsAsync( topicPath, cancellationToken ); - } catch(Exception ex) { - WriteLine( $"Failed to remove topic '{topicPath}' : {ex}." ); - } - - // Close the session - session.Close(); - } - } -} diff --git a/dotnet/source/examples/Publishing/TopicNotificationListener.cs b/dotnet/source/examples/Publishing/TopicNotificationListener.cs deleted file mode 100644 index aeb8fee8..00000000 --- a/dotnet/source/examples/Publishing/TopicNotificationListener.cs +++ /dev/null @@ -1,168 +0,0 @@ -/** - * Copyright © 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features; -using PushTechnology.ClientInterface.Client.Features.Control.Topics; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Topics; -using PushTechnology.ClientInterface.Client.Topics.Details; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Publishing { - /// - /// Control client implementation of a listener for topic notifications. - /// - public sealed class TopicNotificationListener : IExample { - private const string TOPIC_PREFIX = "topic-notifications"; - - /// - /// Runs the client topic notification listener example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run( CancellationToken cancellationToken, string[] args ) { - var selector = $"?{TOPIC_PREFIX}//"; - - var serverUrl = args[ 0 ]; - var session = Diffusion.Sessions.Principal( "control" ).Password( "password" ) - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open( serverUrl ); - - var notifications = session.TopicNotifications; - - INotificationRegistration registration = null; - string path = string.Empty; - - try - { - //Register a listener to receive topic notifications - registration = await notifications.AddListenerAsync(new Listener()); - } - catch(Exception ex) - { - WriteLine($"Failed to add listener : {ex}."); - session.Close(); - return; - } - - try - { - //Start receiving notifications - await registration.SelectAsync(selector); - } - catch (Exception ex) - { - WriteLine($"Selector '{selector}' registration failed : {ex}."); - session.Close(); - return; - } - - try - { - //Add topic - path = $"{TOPIC_PREFIX}/{DateTime.Now.ToFileTimeUtc()}"; - var specification = session.TopicControl.NewSpecification(TopicType.STRING); - - await session.TopicControl.AddTopicAsync(path, specification); - } - catch (Exception ex) - { - WriteLine($"Failed to add topic '{path}' : {ex}."); - session.Close(); - return; - } - - try - { - //Remove topic - await session.TopicControl.RemoveTopicsAsync(path); - } - catch (Exception ex) - { - WriteLine($"Failed to remove topic '{path}' : {ex}."); - session.Close(); - return; - } - - try - { - //Stop receiving notifications - await registration.DeselectAsync(selector); - } - catch (Exception ex) - { - WriteLine($"Deselection failed for selector '{selector}' : {ex}."); - session.Close(); - return; - } - - try - { - //Unregister the listener - await registration.CloseAsync(); - } - catch (Exception ex) - { - WriteLine($"Failed to unregister the listener : {ex}."); - } - - // Close the session - session.Close(); - } - - /// - /// The listener for topic notifications. - /// - private class Listener : ITopicNotificationListener { - /// - /// Indicates that the stream was closed. - /// - public void OnClose() - { - WriteLine("The listener was closed."); - } - - /// - /// Notification for an immediate descendant of a selected topic path. - /// - public void OnDescendantNotification(string topicPath, NotificationType type) - { - WriteLine($"Descendant topic '{topicPath}' has been {type}."); - } - - /// - /// Indicates an error received by the callback. - /// - public void OnError(ErrorReason errorReason) - { - WriteLine($"The listener received the error: '{errorReason}'."); - } - - /// - /// Notification for a selected topic. - /// - public void OnTopicNotification(string topicPath, ITopicSpecification specification, NotificationType type) - { - WriteLine($"Topic '{topicPath}' has been {type}."); - } - } - } -} diff --git a/dotnet/source/examples/Publishing/UpdateStreamBuilder.cs b/dotnet/source/examples/Publishing/UpdateStreamBuilder.cs deleted file mode 100644 index 0f762749..00000000 --- a/dotnet/source/examples/Publishing/UpdateStreamBuilder.cs +++ /dev/null @@ -1,102 +0,0 @@ -/** - * Copyright © 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Session; -using PushTechnology.ClientInterface.Client.Topics; -using static System.Console; -using static PushTechnology.ClientInterface.Examples.Runner.Program; - -namespace PushTechnology.ClientInterface.Example.Publishing { - /// - /// Control client implementation that creates an update stream with a builder. - /// - public sealed class UpdateStreamBuilder : IExample { - /// - /// Runs the create update stream with builder control client example. - /// - /// A token used to end the client example. - /// A single string should be used for the server url. - public async Task Run(CancellationToken cancellationToken, string[] args) - { - string TOPIC_PREFIX = "test-topics"; - - var serverUrl = args[0]; - var session = Diffusion.Sessions.Principal("control").Password("password") - .CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT) - .Open(serverUrl); - var topicControl = session.TopicControl; - var topicUpdate = session.TopicUpdate; - - // Create a string topic - var topicPath = $"{TOPIC_PREFIX}/String"; - - // Add topic - try - { - await topicControl.AddTopicAsync(topicPath, TopicType.STRING, cancellationToken); - - WriteLine($"Topic '{topicPath}' successfully added."); - } - catch (Exception ex) - { - WriteLine($"Failed to add topic '{topicPath}' : {ex}."); - session.Close(); - return; - } - - var specification = session.TopicControl.NewSpecification(TopicType.STRING); - var builder = session.TopicUpdate.NewUpdateStreamBuilder(); - builder = builder.Specification(specification); - var stream = builder.Build(topicPath); - - // Set the topic value - try - { - await stream.SetAsync("Value1"); - WriteLine($"Topic value set successfully with 'Value1'."); - } - catch (Exception ex) - { - WriteLine($"Failed to update topic '{topicPath}' : {ex}."); - session.Close(); - return; - } - - var updateConstraint = Diffusion.UpdateConstraints.Value("Value1"); - builder = builder.Constraint(updateConstraint); - var stream2 = builder.Build(topicPath); - - // Set the topic value with constraint and expect success - try - { - await stream2.SetAsync("Value2"); - WriteLine($"Topic value set successfully with 'Value2' as topic value was previously 'Value1'."); - } - catch (Exception ex) - { - WriteLine($"Failed to update topic '{topicPath}' : {ex}."); - session.Close(); - return; - } - - // Close the session - session.Close(); - } - } -} diff --git a/dotnet/source/examples/Runner/Program.cs b/dotnet/source/examples/Runner/Program.cs deleted file mode 100644 index ab0d3479..00000000 --- a/dotnet/source/examples/Runner/Program.cs +++ /dev/null @@ -1,262 +0,0 @@ -/** - * Copyright © 2016 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using PushTechnology.ClientInterface.Example.Consuming; -using PushTechnology.ClientInterface.Example.Features; -using PushTechnology.ClientInterface.Example.Publishing; - - -namespace PushTechnology.ClientInterface.Examples.Runner { - /// - /// This is used to run the examples. - /// - public static class Program { - /// - /// To run an example set, uncomment the corresponding block of code. - /// - /// The program arguments. - public static void Main( string[] args ) { - var url = "ws://localhost:8080"; - var secureUrl = "wss://localhost:8080"; - - using ( var runner = new ExampleRunner() ) { - /// Start JSON topic examples - //runner.Start( new PublishingJSONTopics(), secureUrl ); - //runner.Start( new ConsumingJSONTopics(), url ); - - /// Start string topic examples - //runner.Start( new PublishingStringTopics(), secureUrl ); - //runner.Start( new ConsumingStringTopics(), url ); - - /// Start integer topic examples - //runner.Start( new PublishingIntegerTopics(), secureUrl ); - //runner.Start( new ConsumingIntegerTopics(), url ); - - /// Start double topic examples - //runner.Start( new PublishingDoubleTopics(), secureUrl ); - //runner.Start( new ConsumingDoubleTopics(), url ); - - /// Start binary topic examples - //runner.Start( new PublishingBinaryTopics(), secureUrl ); - //runner.Start( new ConsumingBinaryTopics(), url ); - - /// Start RecordV2 topic examples - //runner.Start( new PublishingRecordV2Topics(), secureUrl ); - //runner.Start( new ConsumingRecordV2Topics(), url ); - - /// Start Request/Response to path examples - //runner.Start( new ReceivingPathRequestMessages(), secureUrl ); - //runner.Start( new SendingPathRequestMessages(), secureUrl ); - - /// Start Request/Response to session filter examples - //runner.Start( new ReceivingFilterRequestMessages(), url ); - //runner.Start( new SendingFilterRequestMessages(), secureUrl ); - - /// Start Request/Response to specified session examples - //runner.Start( new ReceivingSessionRequestMessages(), url ); - //runner.Start( new SendingSessionRequestMessages(), secureUrl ); - - /// Start ping example - //runner.Start( new PingServer(), url); - - /// Start automatic topic removal - //runner.Start( new Removal(), secureUrl ); - - /// Start authentication example - //runner.Start( new AuthenticationControl(), secureUrl ); - - /// Start AddAndSet example - //runner.Start( new AddAndSetTopic(), secureUrl ); - - /// Start time series add topics example - //runner.Start(new PublishingTimeSeriesAddTopics(), secureUrl); - //runner.Start(new ConsumingTimeSeriesTopics(), url); - - /// Start time series topic append example - //runner.Start(new PublishingTimeSeriesAppend(), secureUrl); - //runner.Start(new ConsumingTimeSeriesTopics(), url); - - /// Start time series topic append with timestamp example - //runner.Start(new PublishingTimeSeriesAppendWithTimestamp(), secureUrl); - //runner.Start(new ConsumingTimeSeriesTopics(), url); - - /// Start time series topic edit example - //runner.Start(new PublishingTimeSeriesEdit(), secureUrl); - //runner.Start(new ConsumingTimeSeriesTopics(), url); - - /// Start time series range query example - //runner.Start(new PublishingTimeSeriesRangeQuery(), secureUrl); - //runner.Start(new ConsumingTimeSeriesTopics(), url); - - /// Start topic view example - //runner.Start(new TopicViews(), secureUrl); - - /// Start remove topics example - //runner.Start(new RemoveTopics(), secureUrl); - - /// Start set topic with constraint example - //runner.Start(new SetTopicWithConstraint(), secureUrl); - - /// Start add and set topic with constraint example - //runner.Start(new AddAndSetTopicWithConstraint(), secureUrl); - - /// Start apply JSON patch example - //runner.Start(new ApplyJSONPatch(), secureUrl); - - /// Start System Authentication Control example - //runner.Start(new SystemAuthenticationControl(), secureUrl); - - /// Start add fallback stream example - //runner.Start(new AddFallbackStream(), secureUrl); - - /// Start add missing topic handler example - //runner.Start(new AddMissingTopicHandler(), secureUrl); - - /// Start topic notification listener example - //runner.Start(new TopicNotificationListener(), secureUrl); - - /// Start client control change roles example - //runner.Start(new ClientControlChangeRoles(), secureUrl); - - /// Start client control change roles filter example - //runner.Start(new ClientControlChangeRolesFilter(), secureUrl); - - /// Start client control close session example - //runner.Start(new ClientControlCloseSession(), secureUrl); - - /// Start client control close session filter example - //runner.Start(new ClientControlCloseSessionFilter(), secureUrl); - - /// Start client control get session properties example - //runner.Start(new ClientControlGetSessionProperties(), secureUrl); - - /// Start client control set conflated example - //runner.Start(new ClientControlSetConflated(), secureUrl); - - /// Start client control set conflated filter example - //runner.Start(new ClientControlSetConflatedFilter(), secureUrl); - - /// Start client control set session properties example - //runner.Start(new ClientControlSetSessionProperties(), secureUrl); - - /// Start client control set session properties filter example - //runner.Start(new ClientControlSetSessionPropertiesFilter(), secureUrl); - - /// Start client control set session properties listener example - //runner.Start(new ClientControlSetSessionPropertiesListener(), secureUrl); - - /// Start subscription control routing handler example - //runner.Start(new SubscriptionControlRoutingHandler(), secureUrl); - - /// Start subscription control subscribe example - //runner.Start(new SubscriptionControlSubscribe(), secureUrl); - - /// Start subscription control subscribe with a filter example - //runner.Start(new SubscriptionControlSubscribeFilter(), secureUrl); - - /// Start Remote Servers example - //runner.Start(new RemoteServers(), secureUrl); - - /// Start Security Control example - //runner.Start(new SecurityControl(), secureUrl); - - /// Start Session Trees example - //runner.Start(new SessionTrees(), secureUrl); - - /// Start Change Principal example - //runner.Start(new ChangePrincipal(), secureUrl); - - /// Start Session Locks example - //runner.Start(new SessionLocks(), secureUrl); - - /// Start Session Reconnection example - //runner.Start(new SessionReconnection(), secureUrl); - - /// Start Session Metric Collector example - //runner.Start(new SessionMetricCollector(), secureUrl); - - /// Start Topic Metric Collector example - //runner.Start(new TopicMetricCollector(), secureUrl); - - /// Start Session Retry example - //runner.Start(new SessionRetry(), secureUrl); - - /// Start Update Stream Builder example - //runner.Start(new UpdateStreamBuilder(), secureUrl); - - /// Start Topic Fetch example - //runner.Start(new TopicFetch(), secureUrl); - } - } - - /// - /// Interface to be used by all examples. - /// - public interface IExample { - /// - /// Runs the current example. - /// - /// - /// This acts as the main method for examples. - /// - /// The cancellation token to cancel the current example run. - /// The optional example arguments. - Task Run( CancellationToken cancel, string[] args ); - } - - /// - /// Class used by the Main method in to start a new cancelable task - /// for each implementation. - /// - private sealed class ExampleRunner : IDisposable { - private readonly List runningExamples = new List(); - private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - - /// - /// Starts a new task for an implementation. - /// - /// The example to run. - /// An array of arguments. Depending on what is necessary for an example, - /// it may contain multiple variables, such as serverUrl, topic paths etc. Check the example class - /// for the description of what is required for this array. - public void Start( IExample example, params string[] args ) { - var task = Task.Run( async () => { - var run = example?.Run( cancellationTokenSource.Token, args ); - if ( run != null ) { - await run; - } - } ); - runningExamples.Add( task ); - } - - /// - /// Method used to wait for examples to be canceled by the user. - /// - /// - /// Pressing any key will stop the examples. - /// - public void Dispose() { - // Wait for key press to cancel - Console.ReadKey( true ); - cancellationTokenSource.Cancel(); - Task.WaitAll( runningExamples.ToArray() ); - } - } - } -} diff --git a/dotnet/source/examples/Runner/Runner.csproj b/dotnet/source/examples/Runner/Runner.csproj deleted file mode 100644 index 7cab0114..00000000 --- a/dotnet/source/examples/Runner/Runner.csproj +++ /dev/null @@ -1,31 +0,0 @@ - - - Exe - net461;netcoreapp2.0 - PushTechnology.ClientInterface.Example - - - - ..\..\..\target - 7.2 - - - - ..\..\..\target - 7.2 - - - - - ..\..\..\target\Diffusion.Client.dll - - - - - - - - - - - diff --git a/dotnet/source/getting-started/Publishing/Program.cs b/dotnet/source/getting-started/Publishing/Program.cs deleted file mode 100644 index b87c0806..00000000 --- a/dotnet/source/getting-started/Publishing/Program.cs +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Copyright © 2016, 2020 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features.Control.Topics; -using PushTechnology.ClientInterface.Client.Topics; -using PushTechnology.ClientInterface.Data.JSON; - -namespace PushTechnology.ClientInterface.Example { - /// - /// A client that publishes an incrementing count to the JSON topic "foo/counter". - /// - class Program { - static void Main( string[] args ) { - // Connect using a principal with 'modify_topic' and 'update_topic' permissions - var session = Diffusion.Sessions.Principal( "control" ).Password( "password" ).Open( "ws://localhost:8080" ); - - // Get the TopicControl and TopicUpdate features - var topicControl = session.TopicControl; - var topicUpdate = session.TopicUpdate; - - // Create a JSON topic 'foo/counter' - var topic = "foo/counter"; - try { - topicControl.AddTopicAsync( topic, TopicType.JSON ).Wait(); - } catch ( Exception ex ) { - Console.WriteLine( $"Failed to add topic {topic} : {ex}." ); - session.Close(); - return; - } - - // Update topic every 300 ms for 30 minutes - for ( var i = 0; i < 3600; ++i ) { - var newValue = Diffusion.DataTypes.JSON.FromJSONString( - "{\"date\":\"" + DateTime.Today.Date.ToString( "D" ) + "\"," + - "\"time\":\"" + DateTime.Now.TimeOfDay.ToString( "g" ) + "\"}" ); - topicUpdate.SetAsync( topic, newValue ); - - Thread.Sleep( 300 ); - } - - // Close session - session.Close(); - } - } -} diff --git a/dotnet/source/getting-started/Publishing/Publishing.csproj b/dotnet/source/getting-started/Publishing/Publishing.csproj deleted file mode 100644 index 9050b600..00000000 --- a/dotnet/source/getting-started/Publishing/Publishing.csproj +++ /dev/null @@ -1,24 +0,0 @@ - - - Exe - net461;netcoreapp2.0 - PushTechnology.ClientInterface.Example - - - - ..\..\..\target - 7.2 - - - - ..\..\..\target - 7.2 - - - - - ..\..\..\target\Diffusion.Client.dll - - - - diff --git a/dotnet/source/getting-started/Subscribing/Program.cs b/dotnet/source/getting-started/Subscribing/Program.cs deleted file mode 100644 index d09b1dd2..00000000 --- a/dotnet/source/getting-started/Subscribing/Program.cs +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Copyright © 2016, 2017 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Threading; -using PushTechnology.ClientInterface.Client.Callbacks; -using PushTechnology.ClientInterface.Client.Factories; -using PushTechnology.ClientInterface.Client.Features; -using PushTechnology.ClientInterface.Client.Features.Topics; -using PushTechnology.ClientInterface.Client.Topics.Details; -using PushTechnology.ClientInterface.Data.JSON; - -namespace PushTechnology.ClientInterface.Example { - class Program { - static void Main( string[] args ) { - // Connect anonymously - var session = Diffusion.Sessions.Open( "ws://localhost:8080" ); - - // Get the Topics feature to subscribe to topics - var topics = session.Topics; - var topic = ">foo/counter"; - - // Add a topic stream for 'random/JSON' and request subscription - var jsonStream = new JSONStream(); - topics.AddStream( topic, jsonStream ); - topics.SubscribeAsync( topic ).Wait(); - - //Stay connected for 10 minutes - Thread.Sleep( TimeSpan.FromMinutes( 10 ) ); - - session.Close(); - } - - /// - /// Basic implementation of the IValueStream for JSON topics. - /// - internal sealed class JSONStream : IValueStream { - /// - /// Notification of stream being closed normally. - /// - public void OnClose() - => Console.WriteLine( "The subscription stream is now closed." ); - - /// - /// Notification of a contextual error related to this callback. - /// - /// - /// Situations in which OnError is called include the session being closed, a communication - /// timeout, or a problem with the provided parameters. No further calls will be made to this callback. - /// - /// Error reason. - public void OnError( ErrorReason errorReason ) - => Console.WriteLine( $"An error has occured : {errorReason}" ); - - /// - /// Notification of a successful subscription. - /// - /// Topic path. - /// Topic specification. - public void OnSubscription( string topicPath, ITopicSpecification specification ) - => Console.WriteLine( $"Client subscribed to {topicPath}" ); - - /// - /// Notification of a successful unsubscription. - /// - /// Topic path. - /// Topic specification. - /// Error reason. - public void OnUnsubscription( string topicPath, ITopicSpecification specification, TopicUnsubscribeReason reason ) - => Console.WriteLine( $"Client unsubscribed from {topicPath} : {reason}" ); - - /// - /// Topic update received. - /// - /// Topic path. - /// Topic specification. - /// Value prior to update. - /// Value after update. - public void OnValue( string topicPath, ITopicSpecification specification, IJSON oldValue, IJSON newValue ) - => Console.WriteLine( $"New value of {topicPath} is {newValue.ToJSONString()}" ); - } - } -} diff --git a/dotnet/source/getting-started/Subscribing/Subscribing.csproj b/dotnet/source/getting-started/Subscribing/Subscribing.csproj deleted file mode 100644 index 9050b600..00000000 --- a/dotnet/source/getting-started/Subscribing/Subscribing.csproj +++ /dev/null @@ -1,24 +0,0 @@ - - - Exe - net461;netcoreapp2.0 - PushTechnology.ClientInterface.Example - - - - ..\..\..\target - 7.2 - - - - ..\..\..\target - 7.2 - - - - - ..\..\..\target\Diffusion.Client.dll - - - - diff --git a/java/README.md b/java/README.md deleted file mode 100644 index 716e789e..00000000 --- a/java/README.md +++ /dev/null @@ -1,23 +0,0 @@ -# Java examples for the Diffusion APIs - -This directory contains examples showing the use of the Java API -for Diffusion and Diffusion Cloud. These examples can also be used with the Android API. - -The examples can be built using Apache Maven. - -The Maven POM file is also configured to launch the PublishingClient -example. To use, edit `PublishingClient.java` to set an appropriate URL for -your Diffusion server or Diffusion Cloud service. Then start the example using Maven: - - `mvn clean compile exec:java` - - -## Client libraries - -The Java client library is available from the [Push Technology Maven repository](https://download.pushtechnology.com/maven/). - -You can also download the Java client library from the following locations: - -* Download from [our website](http://download.pushtechnology.com/cloud/latest/sdks.html#java) - -* The client library is also available in the `clients` directory of the Diffusion installation. diff --git a/java/com/pushtechnology/client/sdk/example/connection/establishment/ConnectAcceptingAllCertificatesExample.java b/java/com/pushtechnology/client/sdk/example/connection/establishment/ConnectAcceptingAllCertificatesExample.java new file mode 100644 index 00000000..2ad4a7f7 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/connection/establishment/ConnectAcceptingAllCertificatesExample.java @@ -0,0 +1,78 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.connection.establishment; + +import java.security.cert.X509Certificate; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to establish a secure connection + * to a Diffusion server that accepts all SSL certificates. + *

+ * The example creates a custom SSLContext that bypasses certificate validation, + * allowing connections to servers with any certificate. + *

+ * Note: Accepting all certificates is insecure and should only be used for testing or development purposes. + * + * @author DiffusionData Limited + */ +public class ConnectAcceptingAllCertificatesExample { + + private static final Logger LOG = + LoggerFactory.getLogger(ConnectAcceptingAllCertificatesExample.class); + + public static void main(String[] args) throws Exception { + + final SSLContext sslContext = SSLContext.getInstance("TLS"); + + sslContext.init( + null, + new TrustManager[] { + new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] certs, String authType) { } + @Override + public void checkServerTrusted(X509Certificate[] certs, String authType) { } + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + } + }, + null); + + final Session session = Diffusion.sessions() + .secureTransport(true) + .sslContext(sslContext) + .principal("admin") + .password("password") + .open("wss://localhost:8080"); + + LOG.info("Connected, session identifier: '{}'.", session.getSessionId()); + + // Insert work here + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/connection/establishment/ConnectAcceptingSpecificCertificateExample.java b/java/com/pushtechnology/client/sdk/example/connection/establishment/ConnectAcceptingSpecificCertificateExample.java new file mode 100644 index 00000000..b6bfa98c --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/connection/establishment/ConnectAcceptingSpecificCertificateExample.java @@ -0,0 +1,77 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.connection.establishment; + +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to establish a secure connection while accepting a specific certificate. + *

+ * A custom trust manager is implemented to inspect and trust server certificates. + * An SSL context is created and configured with the trust manager before opening a secure session. + * + * @author DiffusionData Limited + */ +public class ConnectAcceptingSpecificCertificateExample { + + private static final Logger LOG = + LoggerFactory.getLogger(ConnectAcceptingSpecificCertificateExample.class); + + public static void main(String[] args) throws Exception { + + + final TrustManager trustManager = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, + String authType) throws CertificateException { } + + @Override + public void checkServerTrusted(X509Certificate[] chain, + String authType) throws CertificateException { } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + }; + + final SSLContext context = SSLContext.getInstance("TLS"); + context.init(null, new TrustManager[] { trustManager }, null); + + final Session session = Diffusion.sessions() + .secureTransport(true) + .sslContext(context) + .principal("admin") + .password("password") + .open("wss://localhost:8080"); + + LOG.info("Connected, session identifier: '{}'.", session.getSessionId()); + + // Insert work here + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/connection/establishment/ConnectAsyncExample.java b/java/com/pushtechnology/client/sdk/example/connection/establishment/ConnectAsyncExample.java new file mode 100644 index 00000000..df249e94 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/connection/establishment/ConnectAsyncExample.java @@ -0,0 +1,48 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.connection.establishment; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to establish an asynchronous connection + * to a Diffusion server. + * + * @author DiffusionData Limited + */ +public class ConnectAsyncExample { + + private static final Logger LOG = + LoggerFactory.getLogger(ConnectAsyncExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .openAsync("ws://localhost:8080") + .join(); + + LOG.info("Connected, session identifier: '{}'.", session.getSessionId()); + + // Insert work here + + session.close(); + } +} \ No newline at end of file diff --git a/java/com/pushtechnology/client/sdk/example/connection/establishment/ConnectSyncExample.java b/java/com/pushtechnology/client/sdk/example/connection/establishment/ConnectSyncExample.java new file mode 100644 index 00000000..f5398965 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/connection/establishment/ConnectSyncExample.java @@ -0,0 +1,49 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.connection.establishment; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to establish a synchronous connection + * to a Diffusion server. + * + * @author DiffusionData Limited + */ +public class ConnectSyncExample { + + private static final Logger LOG = + LoggerFactory.getLogger(ConnectSyncExample.class); + + public static void main(String[] args) { + + final String serverUrl = args.length == 1 ? args[0] : "ws://localhost:8080"; + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open(serverUrl); + + LOG.info("Connected, session identifier: '{}'.", session.getSessionId()); + + // Insert work here + + session.close(); + } +} \ No newline at end of file diff --git a/java/com/pushtechnology/client/sdk/example/connection/establishment/ConnectSyncTryWithResourcesExample.java b/java/com/pushtechnology/client/sdk/example/connection/establishment/ConnectSyncTryWithResourcesExample.java new file mode 100644 index 00000000..1e7a1358 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/connection/establishment/ConnectSyncTryWithResourcesExample.java @@ -0,0 +1,54 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.connection.establishment; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.session.SessionException; + +/** + * This example demonstrates how to establish a synchronous connection + * to a Diffusion server using a try-with-resources statement. + *

+ * The use of try-with-resources ensures that the session is automatically closed. + * + * @author DiffusionData Limited + */ +public class ConnectSyncTryWithResourcesExample { + + private static final Logger LOG = + LoggerFactory.getLogger(ConnectSyncTryWithResourcesExample.class); + + public static void main(String[] args) { + + final String serverUrl = args.length == 1 ? args[0] : "ws://localhost:8080"; + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open(serverUrl)) { + + LOG.info("Connected, session identifier: '{}'.", session.getSessionId()); + + // Insert work here + } + catch (SessionException e) { + LOG.error("An exception occurred attempting to open or close a session.", e); + } + } +} \ No newline at end of file diff --git a/java/com/pushtechnology/client/sdk/example/connection/establishment/ConnectViaSessionFactoryExample.java b/java/com/pushtechnology/client/sdk/example/connection/establishment/ConnectViaSessionFactoryExample.java new file mode 100644 index 00000000..4401f9f9 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/connection/establishment/ConnectViaSessionFactoryExample.java @@ -0,0 +1,54 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.connection.establishment; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.session.SessionFactory; + +/** + * This example demonstrates how to establish multiple connections + * to a Diffusion server using a shared SessionFactory. + * + * @author DiffusionData Limited + */ +public class ConnectViaSessionFactoryExample { + + private static final Logger LOG = + LoggerFactory.getLogger(ConnectViaSessionFactoryExample.class); + + public static void main(String[] args) { + + final SessionFactory sessionFactory = Diffusion.sessions(); + + sessionFactory + .principal("admin") + .password("password"); + + final Session session = sessionFactory.open("ws://localhost:8080"); + final Session anotherSession = sessionFactory.open("ws://localhost:8080"); + + LOG.info("Connected, session identifier: '{}'.", session.getSessionId()); + LOG.info("Connected, session identifier: '{}'.", anotherSession.getSessionId()); + + // Insert work here + + session.close(); + anotherSession.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/connection/establishment/SessionStateListenerExample.java b/java/com/pushtechnology/client/sdk/example/connection/establishment/SessionStateListenerExample.java new file mode 100644 index 00000000..b3e6524f --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/connection/establishment/SessionStateListenerExample.java @@ -0,0 +1,58 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.connection.establishment; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.session.Session.Listener; +import com.pushtechnology.diffusion.client.session.Session.State; + +/** + * This example demonstrates how to use a session state listener to monitor + * changes in the state of a Diffusion session. + *

+ * The example registers a custom session listener that logs state transitions + * of the session. + * + * @author DiffusionData Limited + */ +public class SessionStateListenerExample { + + private static final Logger LOG = LoggerFactory + .getLogger(SessionStateListenerExample.class); + + public static void main(String[] args) { + + final Listener mySessionListener = new Listener() { + @Override + public void onSessionStateChanged(Session session, State oldState, State newState) { + LOG.info("State changed from {} to {}", oldState, newState); + } + }; + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .listener(mySessionListener) + .open("ws://localhost:8080"); + + // Insert work here + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/connection/resilience/InitialSessionEstablishmentRetryExample.java b/java/com/pushtechnology/client/sdk/example/connection/resilience/InitialSessionEstablishmentRetryExample.java new file mode 100644 index 00000000..3a3839f0 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/connection/resilience/InitialSessionEstablishmentRetryExample.java @@ -0,0 +1,52 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.connection.resilience; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.session.retry.RetryStrategy; + +/** + * This example demonstrates how to configure an initial retry strategy for + * session establishment. + *

+ * The example sets up a retry strategy with specified delay and retry count + * for reconnect attempts when establishing a session. + * + * @author DiffusionData Limited + */ +public class InitialSessionEstablishmentRetryExample { + + private static final Logger LOG = + LoggerFactory.getLogger(InitialSessionEstablishmentRetryExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .initialRetryStrategy(new RetryStrategy(250, 10)) + .open("ws://localhost:8080"); + + LOG.info("Connected, session identifier: '{}'.", session.getSessionId()); + + // Insert work here + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/connection/resilience/ReconnectionStrategyExample.java b/java/com/pushtechnology/client/sdk/example/connection/resilience/ReconnectionStrategyExample.java new file mode 100644 index 00000000..e9da291b --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/connection/resilience/ReconnectionStrategyExample.java @@ -0,0 +1,73 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.connection.resilience; + +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.session.reconnect.ReconnectionStrategy; + +/** + * This example demonstrates how to implement a custom reconnection strategy + * for a Diffusion session. + *

+ * The example defines a custom ReconnectionStrategy that limits the number of + * reconnection attempts and schedules each attempt with a fixed delay. + * + * @author DiffusionData Limited + */ +public class ReconnectionStrategyExample { + + private static final Logger LOG = + LoggerFactory.getLogger(ReconnectionStrategyExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .reconnectionStrategy(new MyReconnectionStrategy()) + .open("ws://localhost:8080"); + + LOG.info("Connected, session identifier: '{}'.", session.getSessionId()); + + // Insert work here + + session.close(); + } + + static class MyReconnectionStrategy implements ReconnectionStrategy { + + private int retries = 0; + private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); + + @Override + public void performReconnection(ReconnectionAttempt reconnectionAttempt) { + if (retries < 10) { + retries++; + scheduler.schedule(reconnectionAttempt::start, 3000, TimeUnit.MILLISECONDS); + } + else { + reconnectionAttempt.abort(); + } + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/messaging/MessagingSendToPathExample.java b/java/com/pushtechnology/client/sdk/example/messaging/MessagingSendToPathExample.java new file mode 100644 index 00000000..1eca3c2d --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/messaging/MessagingSendToPathExample.java @@ -0,0 +1,99 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.messaging; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.callbacks.Registration; +import com.pushtechnology.diffusion.client.features.Messaging; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to send and receive messages to and from a + * specific path using the Diffusion messaging feature. + *

+ * The example registers a request handler for a specified path and processes incoming messages. + * Another session sends a request to this path and receives a response. + * + * @author DiffusionData Limited + */ +public class MessagingSendToPathExample { + + private static final Logger LOG = + LoggerFactory.getLogger(MessagingSendToPathExample.class); + + public static void main(String[] args) throws Exception { + + final String serverUrl = "ws://localhost:8080"; + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open(serverUrl)) { + + final String path = "my/message/path"; + + final Registration registration = session.feature(Messaging.class) + .addRequestHandler(path, String.class, String.class, new MyRequestHandler()) + .join(); + + final Session session2 = Diffusion.sessions() + .principal("admin").password("password").open(serverUrl); + + final String result = session2.feature(Messaging.class) + .sendRequest(path, "Hello", String.class, String.class) + .join(); + + LOG.info("Response: '{}'.", result); + + SECONDS.sleep(2); + + registration.close() + .join(); + + session2.close(); + } + } + + public static class MyRequestHandler implements Messaging.RequestHandler { + private static final Logger LOG = LoggerFactory.getLogger(MyRequestHandler.class); + + @Override + public void onRequest( + String request, + RequestContext requestContext, + Responder responder) { + + LOG.info("Received message: '{}'.", request); + + responder.respond("Goodbye."); + } + + @Override + public void onClose() { + LOG.info("On close."); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.info("On error: {}.", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/messaging/MessagingSendToSessionFilterExample.java b/java/com/pushtechnology/client/sdk/example/messaging/MessagingSendToSessionFilterExample.java new file mode 100644 index 00000000..ba283d8f --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/messaging/MessagingSendToSessionFilterExample.java @@ -0,0 +1,149 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.messaging; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.Messaging; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.session.SessionId; + +/** + * This example demonstrates how to send messages to sessions matching a filter + * using the Diffusion messaging feature. + *

+ * The example sets up request streams for specific paths and uses a + * session filter to target sessions based on principal values. + * Matching sessions process the message and send responses back to the sender. + * + * @author DiffusionData Limited + */ +public class MessagingSendToSessionFilterExample { + + private static final Logger LOG = + LoggerFactory.getLogger(MessagingSendToSessionFilterExample.class); + + public static void main(String[] args) throws Exception { + + final String serverUrl = "ws://localhost:8080"; + + try (Session session1 = Diffusion.sessions() + .principal("admin").password("password").open(serverUrl)) { + + final String path = "my/message/path"; + + session1.feature(Messaging.class).setRequestStream(path, String.class, String.class, + new MyRequestStream1()); + + final Session session2 = Diffusion.sessions() + .principal("control").password("password").open(serverUrl); + + session2.feature(Messaging.class).setRequestStream(path, String.class, String.class, + new MyRequestStream2()); + + final Session session3 = Diffusion.sessions() + .principal("control").password("password").open(serverUrl); + + final int result = session3.feature(Messaging.class) + .sendRequestToFilter("$Principal is 'admin'", path, "Hello", String.class, String.class, + new MyFilteredRequestCallback()) + .join(); + + LOG.info("Message received by {} session(s).", result); + + SECONDS.sleep(2); + + session2.feature(Messaging.class).removeRequestStream(path); + session1.feature(Messaging.class).removeRequestStream(path); + session3.close(); + session2.close(); + } + } + + public static class MyRequestStream1 implements Messaging.RequestStream { + private static final Logger LOG = LoggerFactory.getLogger(MyRequestStream1.class); + + @Override + public void onRequest( + String path, + String request, + Responder responder) { + + LOG.info("Received message: '{}'.", request); + + responder.respond("Goodbye."); + } + + @Override + public void onClose() { + LOG.info("On close."); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.info("On error: {}.", errorReason); + } + } + + public static class MyRequestStream2 implements Messaging.RequestStream { + private static final Logger LOG = LoggerFactory.getLogger(MyRequestStream2.class); + + @Override + public void onRequest( + String path, + String request, + Responder responder) { + + LOG.error("Received message: '{}' - this was not expected!!", request); + + responder.respond("I'm not supposed to receive a message."); + } + + @Override + public void onClose() { + LOG.info("On close."); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.info("On error: {}.", errorReason); + } + } + + public static class MyFilteredRequestCallback implements Messaging.FilteredRequestCallback { + private static final Logger LOG = LoggerFactory.getLogger(MyFilteredRequestCallback.class); + + @Override + public void onResponse( + SessionId sessionId, + String response) { + + LOG.info("Session: {} responded with: '{}'.", sessionId, response); + } + + @Override + public void onResponseError( + SessionId sessionId, + Throwable throwable) { + + LOG.error("Session: {} had response error: {}", sessionId, throwable.getMessage()); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/messaging/MessagingSendToSessionIdExample.java b/java/com/pushtechnology/client/sdk/example/messaging/MessagingSendToSessionIdExample.java new file mode 100644 index 00000000..f67b2954 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/messaging/MessagingSendToSessionIdExample.java @@ -0,0 +1,129 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.messaging; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.Messaging; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to send messages to a specific session using + * its session ID with the Diffusion messaging feature. + *

+ * The example sets up request streams for specific paths and uses a session ID + * to directly target a session for messaging. + * The targeted session processes the message and sends a response back to the sender. + * + * @author DiffusionData Limited + */ +public class MessagingSendToSessionIdExample { + + private static final Logger LOG = + LoggerFactory.getLogger(MessagingSendToSessionIdExample.class); + + public static void main(String[] args) throws Exception { + + final String serverUrl = "ws://localhost:8080"; + + try (Session session1 = Diffusion.sessions() + .principal("admin") + .password("password") + .open(serverUrl)) { + + final String path = "my/message/path"; + + session1.feature(Messaging.class).setRequestStream(path, String.class, String.class, + new MyRequestStream1()); + + final Session session2 = Diffusion.sessions() + .principal("admin").password("password").open(serverUrl); + + session2.feature(Messaging.class).setRequestStream(path, String.class, String.class, + new MyRequestStream2()); + + final Session session3 = Diffusion.sessions() + .principal("admin").password("password").open(serverUrl); + + final String result = session3.feature(Messaging.class) + .sendRequest(session1.getSessionId(), path, "Hello", String.class, String.class) + .join(); + + LOG.info("Response: '{}'.", result); + + SECONDS.sleep(2); + + session2.feature(Messaging.class).removeRequestStream(path); + session1.feature(Messaging.class).removeRequestStream(path); + session3.close(); + session2.close(); + } + } + + public static class MyRequestStream1 implements Messaging.RequestStream { + private static final Logger LOG = LoggerFactory.getLogger(MyRequestStream1.class); + + @Override + public void onRequest( + String path, + String request, + Responder responder) { + + LOG.info("Received message: '{}'.", request); + + responder.respond("Goodbye."); + } + + @Override + public void onClose() { + LOG.info("On close."); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.info("On error: {}.", errorReason); + } + } + + public static class MyRequestStream2 implements Messaging.RequestStream { + private static final Logger LOG = LoggerFactory.getLogger(MyRequestStream2.class); + + @Override + public void onRequest( + String path, + String request, + Responder responder) { + + LOG.error("Received message: '{}' - this was not expected!!", request); + + responder.respond("I'm not supposed to receive a message."); + } + + @Override + public void onClose() { + LOG.info("On close."); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.info("On error: {}.", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/monitoring/MonitoringMissingTopicNotificationsExample.java b/java/com/pushtechnology/client/sdk/example/monitoring/MonitoringMissingTopicNotificationsExample.java new file mode 100644 index 00000000..29b389f7 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/monitoring/MonitoringMissingTopicNotificationsExample.java @@ -0,0 +1,162 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.monitoring; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.callbacks.Registration; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; + +/** + * This example demonstrates how to monitor and handle missing topic notifications + * in Diffusion. + *

+ * The example registers a missing topic handler that creates a topic when a + * subscription request is made to a nonexistent topic. + * A value stream is used to observe changes to the newly created topic. + * + * @author DiffusionData Limited + */ +public class MonitoringMissingTopicNotificationsExample { + + private static final Logger LOG = + LoggerFactory.getLogger(MonitoringMissingTopicNotificationsExample.class); + + public static void main(String[] args) throws Exception { + + final String serverUrl = "ws://localhost:8080"; + + try (Session session1 = Diffusion.sessions() + .principal("admin") + .password("password") + .open(serverUrl)) { + + final String topicPath = "my/topic/path"; + + final Registration registration = + session1.feature(TopicControl.class).addMissingTopicHandler(topicPath, + new MyMissingTopicStream(session1)) + .join(); + + final Session session2 = Diffusion.sessions() + .principal("client").password("password").open(serverUrl); + + final Topics session2Topics = session2.feature(Topics.class); + + final MyLoggingStringStream myLoggingStringStream = new MyLoggingStringStream(); + + session2Topics.addStream("?my/topic/path", String.class, myLoggingStringStream); + session2Topics.subscribe("my/topic/path/does/not/exist/yet") + .join(); + + LOG.info("Missing topic will have been created."); + + session2Topics.removeStream(myLoggingStringStream); + + SECONDS.sleep(2); + + registration.close() + .join(); + + session2.close(); + } + } + + public static class MyMissingTopicStream implements TopicControl.MissingTopicNotificationStream { + private static final Logger LOG = LoggerFactory.getLogger(MyMissingTopicStream.class); + + private final Session session; + + public MyMissingTopicStream(Session session) { + this.session = session; + } + + @Override + public void onMissingTopic(TopicControl.MissingTopicNotification missingTopicNotification) { + final String topicPath = missingTopicNotification.getTopicPath(); + + LOG.info("On missing topic: '{}'.", topicPath); + + session.feature(TopicControl.class).addTopic(topicPath, TopicType.STRING) + .whenComplete((addTopicResult, throwable) -> { + if (throwable == null) { + LOG.info("Topic created: '{}'.", topicPath); + } + }); + } + + @Override + public void onClose() { + LOG.info("On close."); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.info("On error: {}.", errorReason); + } + } + + public static class MyLoggingStringStream implements Topics.ValueStream { + private static final Logger LOG = LoggerFactory.getLogger(MyLoggingStringStream.class); + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + String oldValue, + String newValue) { + + LOG.info("'{}' changed from '{}' to '{}}'.", + topicPath, oldValue, newValue); + } + + @Override + public void onSubscription( + String topicPath, + TopicSpecification topicSpecification) { + + LOG.info("Subscribed to: '{}'.", topicPath); + } + + @Override + public void onUnsubscription( + String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + + LOG.info("Unsubscribed from: '{}', reason: {}.", + topicPath, unsubscribeReason); + } + + @Override + public void onClose() { + LOG.info("On close."); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("On error: {}.", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/monitoring/MonitoringTopicNotificationsExample.java b/java/com/pushtechnology/client/sdk/example/monitoring/MonitoringTopicNotificationsExample.java new file mode 100644 index 00000000..b1ea66b5 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/monitoring/MonitoringTopicNotificationsExample.java @@ -0,0 +1,109 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.monitoring; + +import java.util.HashMap; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.TopicUpdate; +import com.pushtechnology.diffusion.client.features.control.topics.TopicNotifications; +import com.pushtechnology.diffusion.client.features.control.topics.TopicNotifications.TopicNotificationListener; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; + +/** + * This example demonstrates how to monitor topic notifications in Diffusion. + *

+ * The example registers a topic notification listener to observe changes to topics + * and their descendants within a selected topic tree. + * + * @author DiffusionData Limited + */ +public class MonitoringTopicNotificationsExample { + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final TopicUpdate topicUpdate = session.feature(TopicUpdate.class); + final TopicNotifications notifications = session.feature(TopicNotifications.class); + final TopicSpecification myTopicSpec = Diffusion.newTopicSpecification( + TopicType.STRING); + + final TopicNotifications.NotificationRegistration registration = + notifications.addListener(new MyTopicListener()).join(); + + registration.select(">my"); + + final Map myTopicData = new HashMap<>(); + myTopicData.put("my/topic/path", "Good morning"); + myTopicData.put("my/other/topic/path", "Good afternoon"); + myTopicData.put("other/path/of/the/topic/tree", "This will not generate a notification"); + + myTopicData.forEach((path, value) -> + topicUpdate.addAndSet( + path, + myTopicSpec, + String.class, + value) + .join()); + + registration.close().join(); + session.close(); + } + + static final class MyTopicListener implements TopicNotificationListener { + + private static final Logger LOG = + LoggerFactory.getLogger(MyTopicListener.class); + + @Override + public void onTopicNotification(String topicPath, + TopicSpecification topicSpecification, + NotificationType notificationType) { + + LOG.info("Topic {} has been {}", + topicPath, notificationType.name().toLowerCase()); + } + + @Override + public void onDescendantNotification(String topicPath, + NotificationType notificationType) { + + LOG.info("Descendant Topic {} has been {}", + topicPath, notificationType.name().toLowerCase()); + + } + + @Override + public void onClose() { + LOG.info("closed"); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("Error: {}", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/monitoring/SessionEventListenerExample.java b/java/com/pushtechnology/client/sdk/example/monitoring/SessionEventListenerExample.java new file mode 100644 index 00000000..b1e6bd52 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/monitoring/SessionEventListenerExample.java @@ -0,0 +1,114 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.monitoring; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import java.util.Collections; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.callbacks.Registration; +import com.pushtechnology.diffusion.client.features.control.clients.ClientControl; +import com.pushtechnology.diffusion.client.features.control.clients.ClientControl.SessionEventParameters; +import com.pushtechnology.diffusion.client.features.control.clients.ClientControl.SessionEventStream.Event.Type; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to monitor session events in Diffusion. + *

+ * The example registers a session event listener to observe session lifecycle + * events and property changes for sessions matching a specified filter. + * + * @author DiffusionData Limited + */ +public class SessionEventListenerExample { + + public static void main(String[] args) throws Exception { + + final Session session1 = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Session session2 = Diffusion.sessions() + .principal("client") + .password("password") + .open("ws://localhost:8080"); + + final ClientControl clientControl = session1.feature(ClientControl.class); + + final SessionEventParameters parameters = + Diffusion.newSessionEventParametersBuilder() + .properties(Session.ALL_FIXED_PROPERTIES) + .filter("$Principal NE 'admin'") + .build(); + + final Registration registration = clientControl.addSessionEventListener( + new MyEventStream(), parameters).join(); + + clientControl.setSessionProperties(session2.getSessionId(), + Collections.singletonMap("$Country", "CA")).join(); + + session2.close(); + registration.close(); + + SECONDS.sleep(2); + + session1.close(); + } + + /** + * Define an implementation of SessionEventSteam with our desired behaviour. + */ + static class MyEventStream implements ClientControl.SessionEventStream { + + private static final Logger LOG = + LoggerFactory.getLogger(MyEventStream.class); + + @Override + public void onSessionEvent(Event event) { + + if (event.isOpenEvent()) { + LOG.info("New session: {}", event.sessionId()); + return; + } + + if (event.type() == Type.STATE) { + LOG.info("Session state changed {}", event.state()); + + } + else { + event.changedProperties().forEach((property, value) -> { + LOG.info("Session property changed: {}={}", property, value); + }); + } + } + + @Override + public void onClose() { + LOG.info("Stream closed"); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("An error occured: {}", + errorReason.getDescription()); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/ping/PingServerExample.java b/java/com/pushtechnology/client/sdk/example/ping/PingServerExample.java new file mode 100644 index 00000000..efb5d410 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/ping/PingServerExample.java @@ -0,0 +1,48 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.ping; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.Pings; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to send a ping to the Diffusion server + * and receive a response. + * + * @author DiffusionData Limited + */ +public class PingServerExample { + + private static final Logger LOG = + LoggerFactory.getLogger(PingServerExample.class); + + public static void main(String[] args) { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final Pings.PingDetails result = session.feature(Pings.class).pingServer() + .join(); + + LOG.info("Received Ping response: {}.", result); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/fetch/FetchTopicPropertiesExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/fetch/FetchTopicPropertiesExample.java new file mode 100644 index 00000000..aa283f1a --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/fetch/FetchTopicPropertiesExample.java @@ -0,0 +1,116 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.fetch; + +import java.util.Collections; +import java.util.concurrent.CompletionException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to fetch the properties of topics in Diffusion. + *

+ * The example creates a set of JSON and STRING topics with specific properties, + * and uses the fetch request feature to retrieve the properties of topics that + * match a given selector. + * + * @author DiffusionData Limited + */ +public class FetchTopicPropertiesExample { + + private static final Logger LOG = + LoggerFactory.getLogger(FetchTopicPropertiesExample.class); + + public static void main(String[] args) { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final Topics topics = session.feature(Topics.class); + + final TopicSpecification specialisedJsonTopicSpecification = Diffusion.newTopicSpecification(TopicType.JSON) + .withProperty(TopicSpecification.DONT_RETAIN_VALUE, Boolean.TRUE.toString()) + .withProperty(TopicSpecification.PERSISTENT, Boolean.FALSE.toString()) + .withProperty(TopicSpecification.PUBLISH_VALUES_ONLY, Boolean.TRUE.toString()); + + for (int i = 1; i <= 5; i++) { + final String topicPath = "my/topic/path/with/properties/" + i; + + final String jsonAsString = String.format("{ \"diffusion\": \"data #%d\" }", i); + final JSON jsonValue = Diffusion.dataTypes().json().fromJsonString(jsonAsString); + + topics.addAndSet(topicPath, specialisedJsonTopicSpecification, JSON.class, jsonValue) + .join(); + } + + final TopicSpecification simpleStringTopicSpecification = Diffusion.newTopicSpecification(TopicType.STRING); + + for (int i = 1; i <= 5; i++) { + final String topicPath = "my/topic/path/with/default/properties/" + i; + final String value = "diffusion data #" + i; + + topics.addAndSet(topicPath, simpleStringTopicSpecification, String.class, value) + .join(); + } + + final String topicSelectorString = "?my/topic/path//"; + + final Topics.FetchResult jsonTopicsFetchResult = topics.fetchRequest() + .topicTypes(Collections.singleton(TopicType.JSON)) + .withProperties() + .fetch(topicSelectorString) + .join(); + + jsonTopicsFetchResult.results().forEach(topicResult -> { + LOG.info("{} properties:", topicResult.path()); + + topicResult.specification().getProperties().forEach((key, value) -> { + LOG.info("* {}: {}.", key, value); + } + ); + } + ); + + final Topics.FetchResult stringFetchResult = topics.fetchRequest() + .topicTypes(Collections.singleton(TopicType.STRING)) + .withProperties() + .fetch(topicSelectorString) + .join(); + + stringFetchResult.results().forEach(topicResult -> { + LOG.info("{} properties:", topicResult.path()); + + topicResult.specification().getProperties().forEach((key, value) -> { + LOG.info("* {}: {}.", key, value); + } + ); + } + ); + } + catch (CompletionException e) { + LOG.error("Failed to run example to completion.", e); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/fetch/FetchTopicViaPagingExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/fetch/FetchTopicViaPagingExample.java new file mode 100644 index 00000000..eea5e77c --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/fetch/FetchTopicViaPagingExample.java @@ -0,0 +1,92 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.fetch; + +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.Topics.FetchResult.TopicResult; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; + +/** + * This example demonstrates how to fetch topics in Diffusion using paging. + *

+ * The example creates a set of STRING topics, then uses the fetch request feature + * with paging to retrieve the topics in batches, allowing efficient handling of + * large topic trees. + * + * @author DiffusionData Limited + */ +public class FetchTopicViaPagingExample { + + private static final Logger LOG = + LoggerFactory.getLogger(FetchTopicViaPagingExample.class); + + public static void main(String[] args) { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final Topics topics = session.feature(Topics.class); + final String topicSelectorString = "?my/topic/path//"; + + final TopicSpecification topicSpecification = + Diffusion.newTopicSpecification(TopicType.STRING); + + for (int i = 1; i <= 25; i++) { + final String topicPath = "my/topic/path/" + i; + final String value = "diffusion data #" + i; + + topics.addAndSet(topicPath, topicSpecification, String.class, value) + .join(); + } + + final List> topicResults = new ArrayList<>(); + + final Topics.FetchRequest request = topics.fetchRequest() + .withValues(String.class) + .first(10); + + Topics.FetchResult pagedFetch = request + .fetch(topicSelectorString) + .join(); + + topicResults.addAll(pagedFetch.results()); + + while (pagedFetch.hasMore()) { + + LOG.info("Loading next page."); + + final String lastTopic = topicResults.get(topicResults.size() - 1).path(); + + pagedFetch = request.after(lastTopic).fetch(topicSelectorString).join(); + + topicResults.addAll(pagedFetch.results()); + } + + topicResults.forEach(topicResult -> + LOG.info("{}: {}.", topicResult.path(), topicResult.value())); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/jsonpatch/JSONPatchAddExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/jsonpatch/JSONPatchAddExample.java new file mode 100644 index 00000000..4cb20e9d --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/jsonpatch/JSONPatchAddExample.java @@ -0,0 +1,115 @@ +/******************************************************************************* + * Copyright (C) 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.jsonpatch; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.TopicUpdate; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to apply a JSON Patch to add a value to a JSON + * topic in Diffusion. + *

+ * The example creates a JSON topic, sets its initial value, and applies a JSON + * Patch to add a new field to the JSON object. + * + * @author DiffusionData Limited + */ +public class JSONPatchAddExample { + + private static final Logger LOG = + LoggerFactory.getLogger(JSONPatchAddExample.class); + + public static void main(String[] args) { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final Topics topics = session.feature(Topics.class); + final TopicUpdate topicUpdate = session.feature(TopicUpdate.class); + final TopicSpecification spec = Diffusion.newTopicSpecification(TopicType.JSON); + final JSON jsonValue = Diffusion.dataTypes().json() + .fromJsonString("{ \"Fred\": \"Flintstone\", \"Barney\": \"Rubble\" }"); + + topicUpdate.addAndSet( + "my/topic/path", + spec, + JSON.class, + jsonValue + ).join(); + + final Topics.ValueStream myStream = new MyStream(LOG); + topics.addFallbackStream(JSON.class, myStream); + topics.subscribe("my/topic/path").join(); + + topicUpdate.applyJsonPatch( + "my/topic/path", + "[{\"op\":\"add\", \"path\": \"/George\", \"value\": \"Jetson\"}]" + ).join(); + + topics.removeStream(myStream); + } + } + + static class MyStream implements Topics.ValueStream { + + private Logger logger; + + MyStream(Logger logger) { + this.logger = logger; + } + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + logger.info("{} new value {}", + topicPath, newValue); + } + + @Override + public void onSubscription(String topicPath, TopicSpecification topicSpecification) { + logger.info("Subscribed to: {}", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + logger.info("Unsubscribed from: {}, reason: {}", + topicPath, unsubscribeReason); + } + + @Override + public void onClose() { + logger.info("On close"); + } + + @Override + public void onError(ErrorReason errorReason) { + logger.error("On error: {}", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/jsonpatch/JSONPatchCopyExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/jsonpatch/JSONPatchCopyExample.java new file mode 100644 index 00000000..ed5a05f6 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/jsonpatch/JSONPatchCopyExample.java @@ -0,0 +1,120 @@ +/******************************************************************************* + * Copyright (C) 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.jsonpatch; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.TopicUpdate; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to apply a JSON Patch to copy a value within a + * JSON topic in Diffusion. + *

+ * The example creates a JSON topic, sets its initial value, and applies a JSON + * Patch to copy a field's value from one location to another within the JSON object. + * + * @author DiffusionData Limited + */ +public class JSONPatchCopyExample { + + private static final Logger LOG = + LoggerFactory.getLogger(JSONPatchCopyExample.class); + + public static void main(String[] args) { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final Topics topics = session.feature(Topics.class); + final TopicUpdate topicUpdate = session.feature(TopicUpdate.class); + final TopicSpecification spec = Diffusion.newTopicSpecification(TopicType.JSON); + final JSON jsonValue = Diffusion.dataTypes().json() + .fromJsonString( + "{\"Meet the Flintstones\": {" + + "\"Fred\": \"Flintstone\"," + + "\"Barney\": \"Rubble\"}," + + "\"The Jetsons\": {" + + "\"George\" : \"Jetson\"}}"); + + topicUpdate.addAndSet( + "my/topic/path", + spec, + JSON.class, + jsonValue + ).join(); + + final Topics.ValueStream myStream = new MyStream(LOG); + topics.addFallbackStream(JSON.class, myStream); + topics.subscribe("my/topic/path").join(); + + topicUpdate.applyJsonPatch( + "my/topic/path", + "[{\"op\":\"copy\", \"from\": \"/Meet the Flintstones/Fred\", \"path\": \"/The Jetsons/George\"}]" + ).join(); + + topics.removeStream(myStream); + } + } + + static class MyStream implements Topics.ValueStream { + + private Logger logger; + + MyStream(Logger logger) { + this.logger = logger; + } + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + logger.info("{} new value {}", + topicPath, newValue); + } + + @Override + public void onSubscription(String topicPath, TopicSpecification topicSpecification) { + logger.info("Subscribed to: {}", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + logger.info("Unsubscribed from: {}, reason: {}", + topicPath, unsubscribeReason); + } + + @Override + public void onClose() { + logger.info("On close"); + } + + @Override + public void onError(ErrorReason errorReason) { + logger.error("On error: {}", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/jsonpatch/JSONPatchMoveExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/jsonpatch/JSONPatchMoveExample.java new file mode 100644 index 00000000..b5ecf68f --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/jsonpatch/JSONPatchMoveExample.java @@ -0,0 +1,118 @@ +/******************************************************************************* + * Copyright (C) 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.jsonpatch; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.TopicUpdate; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to apply a JSON Patch to move a value within a + * JSON topic in Diffusion. + *

+ * The example creates a JSON topic, sets its initial value, and applies a JSON + * Patch to move a field's value from one location to another within the JSON object. + * + * @author DiffusionData Limited + */ +public class JSONPatchMoveExample { + + private static final Logger LOG = + LoggerFactory.getLogger(JSONPatchMoveExample.class); + + public static void main(String[] args) { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final Topics topics = session.feature(Topics.class); + final TopicUpdate topicUpdate = session.feature(TopicUpdate.class); + final TopicSpecification spec = Diffusion.newTopicSpecification(TopicType.JSON); + final JSON jsonValue = Diffusion.dataTypes().json() + .fromJsonString("{ " + + "\"Fred\": \"Flintstone\", " + + "\"Barney\": \"Rubble\", " + + "\"George\": \"Jetson\" }"); + + topicUpdate.addAndSet( + "my/topic/path", + spec, + JSON.class, + jsonValue + ).join(); + + final Topics.ValueStream myStream = new MyStream(LOG); + topics.addFallbackStream(JSON.class, myStream); + topics.subscribe("my/topic/path").join(); + + topicUpdate.applyJsonPatch( + "my/topic/path", + "[{\"op\":\"move\", \"from\": \"/Fred\", \"path\": \"/Meet The Flintstones~1Fred\"}]" + ).join(); + + topics.removeStream(myStream); + } + } + + static class MyStream implements Topics.ValueStream { + + private Logger logger; + + MyStream(Logger logger) { + this.logger = logger; + } + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + logger.info("{} new value {}", + topicPath, newValue); + } + + @Override + public void onSubscription(String topicPath, TopicSpecification topicSpecification) { + logger.info("Subscribed to: {}", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + logger.info("Unsubscribed from: {}, reason: {}", + topicPath, unsubscribeReason); + } + + @Override + public void onClose() { + logger.info("On close"); + } + + @Override + public void onError(ErrorReason errorReason) { + logger.error("On error: {}", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/jsonpatch/JSONPatchRemoveExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/jsonpatch/JSONPatchRemoveExample.java new file mode 100644 index 00000000..8e599c52 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/jsonpatch/JSONPatchRemoveExample.java @@ -0,0 +1,118 @@ +/******************************************************************************* + * Copyright (C) 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.jsonpatch; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.TopicUpdate; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to apply a JSON Patch to remove a value from a + * JSON topic in Diffusion. + *

+ * The example creates a JSON topic, sets its initial value, and applies a JSON + * Patch to remove a specified field from the JSON object. + * + * @author DiffusionData Limited + */ +public class JSONPatchRemoveExample { + + private static final Logger LOG = + LoggerFactory.getLogger(JSONPatchRemoveExample.class); + + public static void main(String[] args) { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final Topics topics = session.feature(Topics.class); + final TopicUpdate topicUpdate = session.feature(TopicUpdate.class); + final TopicSpecification spec = Diffusion.newTopicSpecification(TopicType.JSON); + final JSON jsonValue = Diffusion.dataTypes().json() + .fromJsonString("{ " + + "\"Fred\": \"Flintstone\", " + + "\"Barney\": \"Rubble\", " + + "\"George\": \"Jetson\" }"); + + topicUpdate.addAndSet( + "my/topic/path", + spec, + JSON.class, + jsonValue + ).join(); + + final Topics.ValueStream myStream = new MyStream(LOG); + topics.addFallbackStream(JSON.class, myStream); + topics.subscribe("my/topic/path").join(); + + topicUpdate.applyJsonPatch( + "my/topic/path", + "[{\"op\":\"remove\", \"path\": \"/George\"}]" + ).join(); + + topics.removeStream(myStream); + } + } + + static class MyStream implements Topics.ValueStream { + + private Logger logger; + + MyStream(Logger logger) { + this.logger = logger; + } + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + logger.info("{} new value {}", + topicPath, newValue); + } + + @Override + public void onSubscription(String topicPath, TopicSpecification topicSpecification) { + logger.info("Subscribed to: {}", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + logger.info("Unsubscribed from: {}, reason: {}", + topicPath, unsubscribeReason); + } + + @Override + public void onClose() { + logger.info("On close"); + } + + @Override + public void onError(ErrorReason errorReason) { + logger.error("On error: {}", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/jsonpatch/JSONPatchReplaceExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/jsonpatch/JSONPatchReplaceExample.java new file mode 100644 index 00000000..0ad37b9a --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/jsonpatch/JSONPatchReplaceExample.java @@ -0,0 +1,118 @@ +/******************************************************************************* + * Copyright (C) 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.jsonpatch; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.TopicUpdate; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to apply a JSON Patch to replace a value in a + * JSON topic in Diffusion. + *

+ * The example creates a JSON topic, sets its initial value, and applies a JSON + * Patch to replace the value of a specified field within the JSON object. + * + * @author DiffusionData Limited + */ +public class JSONPatchReplaceExample { + + private static final Logger LOG = + LoggerFactory.getLogger(JSONPatchReplaceExample.class); + + public static void main(String[] args) { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final Topics topics = session.feature(Topics.class); + final TopicUpdate topicUpdate = session.feature(TopicUpdate.class); + final TopicSpecification spec = Diffusion.newTopicSpecification(TopicType.JSON); + final JSON jsonValue = Diffusion.dataTypes().json() + .fromJsonString("{ " + + "\"Fred\": \"Flintstone\", " + + "\"Barney\": \"Rubble\", " + + "\"George\": \"Jetson\" }"); + + topicUpdate.addAndSet( + "my/topic/path", + spec, + JSON.class, + jsonValue + ).join(); + + final Topics.ValueStream myStream = new MyStream(LOG); + topics.addFallbackStream(JSON.class, myStream); + topics.subscribe("my/topic/path").join(); + + topicUpdate.applyJsonPatch( + "my/topic/path", + "[{\"op\":\"replace\", \"path\": \"/George\", \"value\": \"Bedrock\"}]" + ).join(); + + topics.removeStream(myStream); + } + } + + static class MyStream implements Topics.ValueStream { + + private Logger logger; + + MyStream(Logger logger) { + this.logger = logger; + } + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + logger.info("{} new value {}", + topicPath, newValue); + } + + @Override + public void onSubscription(String topicPath, TopicSpecification topicSpecification) { + logger.info("Subscribed to: {}", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + logger.info("Unsubscribed from: {}, reason: {}", + topicPath, unsubscribeReason); + } + + @Override + public void onClose() { + logger.info("On close"); + } + + @Override + public void onError(ErrorReason errorReason) { + logger.error("On error: {}", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/jsonpatch/JSONPatchTestExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/jsonpatch/JSONPatchTestExample.java new file mode 100644 index 00000000..4320c844 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/jsonpatch/JSONPatchTestExample.java @@ -0,0 +1,129 @@ +/******************************************************************************* + * Copyright (C) 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.jsonpatch; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.TopicUpdate; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to apply a JSON Patch test operation on a JSON + * topic in Diffusion. + *

+ * The example creates a JSON topic, sets its initial value, and applies JSON + * Patch test operations to validate specific values at given paths in the JSON object. + * + * @author DiffusionData Limited + */ +public class JSONPatchTestExample { + + private static final Logger LOG = + LoggerFactory.getLogger(JSONPatchTestExample.class); + + public static void main(String[] args) { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final Topics topics = session.feature(Topics.class); + final TopicUpdate topicUpdate = session.feature(TopicUpdate.class); + final TopicSpecification spec = Diffusion.newTopicSpecification(TopicType.JSON); + final JSON jsonValue = Diffusion.dataTypes().json() + .fromJsonString("{ " + + "\"Fred\": \"Flintstone\", " + + "\"Barney\": \"Rubble\", " + + "\"George\": \"Jetson\" }"); + + topicUpdate.addAndSet( + "my/topic/path", + spec, + JSON.class, + jsonValue + ).join(); + + final Topics.ValueStream myStream = new MyStream(LOG); + topics.addFallbackStream(JSON.class, myStream); + topics.subscribe("my/topic/path").join(); + + // this patch succeeds + TopicUpdate.JsonPatchResult result = topicUpdate.applyJsonPatch( + "my/topic/path", + "[{\"op\":\"test\", \"path\": \"/Fred\", \"value\": \"Flintstone\"}]" + ).join(); + + LOG.info(result.toString()); + + // this patch fails + result = topicUpdate.applyJsonPatch( + "my/topic/path", + "[{\"op\":\"test\", \"path\": \"/Fred\", \"value\": \"Jetson\"}]" + ).join(); + + LOG.info(result.toString()); + + topics.removeStream(myStream); + } + } + + static class MyStream implements Topics.ValueStream { + + private Logger logger; + + MyStream(Logger logger) { + this.logger = logger; + } + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + logger.info("{} new value {}", + topicPath, newValue); + } + + @Override + public void onSubscription(String topicPath, TopicSpecification topicSpecification) { + logger.info("Subscribed to: {}", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + logger.info("Unsubscribed from: {}, reason: {}", + topicPath, unsubscribeReason); + } + + @Override + public void onClose() { + logger.info("On close"); + } + + @Override + public void onError(ErrorReason errorReason) { + logger.error("On error: {}", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/publish/AddAndSetTopicExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/publish/AddAndSetTopicExample.java new file mode 100644 index 00000000..574c5fca --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/publish/AddAndSetTopicExample.java @@ -0,0 +1,61 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.publish; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.TopicCreationResult; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to create a new topic and set its initial value + * in Diffusion. + *

+ * The example uses the `addAndSet` method to create a JSON topic at a specified + * path and set its initial value. + * + * @author DiffusionData Limited + */ +public class AddAndSetTopicExample { + + private static final Logger LOG = + LoggerFactory.getLogger(AddAndSetTopicExample.class); + + public static void main(String[] args) { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final JSON data = Diffusion.dataTypes().json() + .fromJsonString("{ \"diffusion\": \"data\" }"); + + final TopicCreationResult result = session.feature(Topics.class) + .addAndSet("my/topic/path", + Diffusion.newTopicSpecification(TopicType.JSON), + JSON.class, + data) + .join(); + + LOG.info("Topic: {}.", result); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/publish/AddAndSetTopicViaUpdateStreamExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/publish/AddAndSetTopicViaUpdateStreamExample.java new file mode 100644 index 00000000..dcace21c --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/publish/AddAndSetTopicViaUpdateStreamExample.java @@ -0,0 +1,78 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.publish; + +import java.util.concurrent.CompletionException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.TopicCreationResult; +import com.pushtechnology.diffusion.client.features.TopicUpdate; +import com.pushtechnology.diffusion.client.features.UpdateStream; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to add and set a topic using an update stream + * in Diffusion. + *

+ * The example creates a JSON topic using an update stream and sets its initial value. + * + * @author DiffusionData Limited + */ +public class AddAndSetTopicViaUpdateStreamExample { + + private static final Logger LOG = + LoggerFactory.getLogger(AddAndSetTopicViaUpdateStreamExample.class); + + public static void main(String[] args) throws Throwable { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final TopicUpdate topicUpdate = session.feature(TopicUpdate.class); + final TopicSpecification spec = Diffusion.newTopicSpecification(TopicType.JSON); + + final UpdateStream updateStream = topicUpdate.newUpdateStreamBuilder() + .specification(spec) + .build("my/topic/path/with/update/stream", JSON.class); + + final JSON jsonValue = Diffusion.dataTypes().json() + .fromJsonString("{ \"diffusion\": \"data\" }"); + + final TopicCreationResult result = + updateStream.set(jsonValue) + .join(); + + if (result == TopicCreationResult.CREATED) { + LOG.info("Topic has been created."); + } + else { + LOG.info("Topic already exists."); + } + } + catch (CompletionException e) { + LOG.error("Failed to add topic.", e); + + throw e.getCause(); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/publish/AddTopicCustomPropertiesExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/publish/AddTopicCustomPropertiesExample.java new file mode 100644 index 00000000..608adb11 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/publish/AddTopicCustomPropertiesExample.java @@ -0,0 +1,75 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.publish; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.CompletionException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; + +/** + * This example demonstrates how to create a topic with custom properties in Diffusion. + *

+ * The example uses the `addTopic` method to create a JSON topic with specified + * custom properties. + * + * @author DiffusionData Limited + */ +public class AddTopicCustomPropertiesExample { + + private static final Logger LOG = + LoggerFactory.getLogger(AddTopicCustomPropertiesExample.class); + + public static void main(String[] args) throws Throwable { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final Map topicProperties = new HashMap<>(); + topicProperties.put(TopicSpecification.DONT_RETAIN_VALUE, Boolean.TRUE.toString()); + topicProperties.put(TopicSpecification.PERSISTENT, Boolean.FALSE.toString()); + topicProperties.put(TopicSpecification.PUBLISH_VALUES_ONLY, Boolean.TRUE.toString()); + + final TopicControl topicControl = session.feature(TopicControl.class); + + final TopicControl.AddTopicResult result = topicControl + .addTopic("my/topic/path/with/properties", Diffusion.newTopicSpecification(TopicType.JSON) + .withProperties(topicProperties)) + .join(); + + if (result == TopicControl.AddTopicResult.CREATED) { + LOG.info("Topic has been created."); + } + else { + LOG.info("Topic already exists."); + } + } + catch (CompletionException e) { + LOG.error("Failed to add topic.", e); + + throw e.getCause(); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/publish/AddTopicExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/publish/AddTopicExample.java new file mode 100644 index 00000000..30a91371 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/publish/AddTopicExample.java @@ -0,0 +1,66 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.publish; + +import java.util.concurrent.CompletionException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicType; + +/** + * This example demonstrates how to create a topic in Diffusion. + *

+ * The example uses the `addTopic` method to create a JSON topic at a specified path. + * + * @author DiffusionData Limited + */ +public class AddTopicExample { + + private static final Logger LOG = + LoggerFactory.getLogger(AddTopicExample.class); + + public static void main(String[] args) throws Throwable { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final TopicControl topicControl = session.feature(TopicControl.class); + + final TopicControl.AddTopicResult result = + topicControl.addTopic( + "my/topic/path", Diffusion.newTopicSpecification(TopicType.JSON)) + .join(); + + if (result == TopicControl.AddTopicResult.CREATED) { + LOG.info("Topic has been created."); + } + else { + LOG.info("Topic already exists."); + } + } + catch (CompletionException e) { + LOG.error("Failed to add topic.", e); + + throw e.getCause(); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/publish/SetTopicExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/publish/SetTopicExample.java new file mode 100644 index 00000000..4055f63a --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/publish/SetTopicExample.java @@ -0,0 +1,64 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.publish; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to set the value of a topic in Diffusion. + *

+ * The example creates a JSON topic at a specified path and sets its value. + * + * @author DiffusionData Limited + */ +public class SetTopicExample { + + private static final Logger LOG = + LoggerFactory.getLogger(SetTopicExample.class); + + public static void main(String[] args) { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final String topicPath = "my/topic/path"; + + final JSON data = Diffusion.dataTypes().json() + .fromJsonString("{ \"diffusion\": [\"data\", \"more data\"] }"); + + final TopicControl.AddTopicResult addTopicResult = + session.feature(TopicControl.class) + .addTopic(topicPath, Diffusion.newTopicSpecification(TopicType.JSON)) + .join(); + + LOG.info("Topic: {}.", addTopicResult); + + session.feature(Topics.class).set(topicPath, JSON.class, data) + .join(); + + LOG.info("Value set."); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/publish/SetTopicViaUpdateStreamExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/publish/SetTopicViaUpdateStreamExample.java new file mode 100644 index 00000000..198e648f --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/publish/SetTopicViaUpdateStreamExample.java @@ -0,0 +1,82 @@ +/******************************************************************************* + * Copyright (C) 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.publish; + +import java.util.concurrent.CompletionException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.TopicCreationResult; +import com.pushtechnology.diffusion.client.features.TopicUpdate; +import com.pushtechnology.diffusion.client.features.UpdateStream; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to set the value of a topic using an update + * stream in Diffusion. + *

+ * The example creates a JSON topic at a specified path and sets its value using + * an update stream. + * + * @author DiffusionData Limited + */ +public class SetTopicViaUpdateStreamExample { + + private static final Logger LOG = + LoggerFactory.getLogger(SetTopicViaUpdateStreamExample.class); + + public static void main(String[] args) { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final TopicUpdate topicUpdate = session.feature(TopicUpdate.class); + final TopicSpecification spec = Diffusion.newTopicSpecification(TopicType.JSON); + + session.feature(TopicControl.class) + .addTopic("my/topic/path/with/update/stream", spec) + .join(); + + final UpdateStream updateStream = topicUpdate.newUpdateStreamBuilder() + .specification(spec) + .build("my/topic/path/with/update/stream", JSON.class); + + final JSON jsonValue = Diffusion.dataTypes().json() + .fromJsonString("{ \"diffusion\": [\"data\", \"more data\"] }"); + + final TopicCreationResult result = + updateStream.set(jsonValue) + .join(); + + if (result == TopicCreationResult.CREATED) { + LOG.info("Topic has been created."); + } + else { + LOG.info("Topic already exists."); + } + } + catch (CompletionException e) { + LOG.error("Failed to add topic.", e); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/AddAndSetJSONValueWithConstraintExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/AddAndSetJSONValueWithConstraintExample.java new file mode 100644 index 00000000..a8979a6e --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/AddAndSetJSONValueWithConstraintExample.java @@ -0,0 +1,86 @@ +/******************************************************************************* + * Copyright (C) 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.publish.constraints; + +import java.util.concurrent.CompletionException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.TopicUpdate; +import com.pushtechnology.diffusion.client.features.UpdateConstraint; +import com.pushtechnology.diffusion.client.features.UpdateConstraint.Operator; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to update a JSON topic in Diffusion with a constraint. + *

+ * The example creates a JSON topic and uses an update constraint to allow updates + * only when the current value matches a specified condition. + * + * @author DiffusionData Limited + */ +public class AddAndSetJSONValueWithConstraintExample { + + private static final Logger LOG = + LoggerFactory.getLogger(AddAndSetJSONValueWithConstraintExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final TopicSpecification specification = Diffusion.newTopicSpecification(TopicType.JSON); + + final JSON value = Diffusion.dataTypes().json() + .fromJsonString("{ \"diffusion\": \"data\" }"); + + final JSON differentValue = Diffusion.dataTypes().json() + .fromJsonString("{ \"diffusion\": \"data2\" }"); + + // create a topic with a json value + session.feature(TopicUpdate.class) + .addAndSet("my/topic/path", specification, JSON.class, value) + .join(); + LOG.info("Topic updated"); + + // only allow updates if the value at the given json pointer matches the value supplied + final UpdateConstraint constraint = Diffusion.updateConstraints() + .jsonValue().with("/diffusion", Operator.IS, "data"); + + // update the topic with the constraint, this works as the initial value has not yet changed + session.feature(TopicUpdate.class) + .addAndSet("my/topic/path", specification, JSON.class, differentValue, constraint).join(); + LOG.info("Topic updated"); + + try { + // attempt another constrained update, this will fail as the json + // value no longer matches the initial value + session.feature(TopicUpdate.class) + .addAndSet("my/topic/path", specification, JSON.class, value, constraint).join(); + } + catch (CompletionException e) { + LOG.info("Update failed: {}", e.getCause().getMessage()); + } + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/AddAndSetJSONValueWithoutConstraintExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/AddAndSetJSONValueWithoutConstraintExample.java new file mode 100644 index 00000000..16a29490 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/AddAndSetJSONValueWithoutConstraintExample.java @@ -0,0 +1,77 @@ +/******************************************************************************* + * Copyright (C) 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.publish.constraints; + +import java.util.concurrent.CompletionException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.TopicUpdate; +import com.pushtechnology.diffusion.client.features.UpdateConstraint; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to update a JSON topic in Diffusion using the + * 'without' constraint. + *

+ * The example creates a JSON topic and uses an update constraint to restrict updates + * if a specific JSON path is already present. + * + * @author DiffusionData Limited + */ +public class AddAndSetJSONValueWithoutConstraintExample { + + private static final Logger LOG = + LoggerFactory.getLogger(AddAndSetJSONValueWithoutConstraintExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final TopicSpecification specification = Diffusion.newTopicSpecification(TopicType.JSON); + + final JSON value = Diffusion.dataTypes().json() + .fromJsonString("{ \"diffusion\": \"data\" }"); + + // create a topic with a json value + session.feature(TopicUpdate.class) + .addAndSet("my/topic/path", specification, JSON.class, value).join(); + LOG.info("Topic updated"); + + // only allow updates if the specified position in the json object does not exist + final UpdateConstraint constraint = Diffusion.updateConstraints() + .jsonValue().without("/diffusion"); + + try { + // attempt a constrained update, this will fail as the json + // value exists + session.feature(TopicUpdate.class) + .addAndSet("my/topic/path", specification, JSON.class, value, constraint).join(); + } + catch (CompletionException e) { + LOG.info("Update failed: {}", e.getCause().getMessage()); + } + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/AddAndSetNoTopicConstraintExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/AddAndSetNoTopicConstraintExample.java new file mode 100644 index 00000000..2f650eb5 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/AddAndSetNoTopicConstraintExample.java @@ -0,0 +1,74 @@ +/******************************************************************************* + * Copyright (C) 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.publish.constraints; + +import java.util.concurrent.CompletionException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.TopicUpdate; +import com.pushtechnology.diffusion.client.features.UpdateConstraint; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to update a topic in Diffusion using the + * 'noTopic' constraint. + *

+ * The example creates a topic and uses an update constraint to ensure updates + * are only allowed if no topic exists at the specified path. + * + * @author DiffusionData Limited + */ +public class AddAndSetNoTopicConstraintExample { + + private static final Logger LOG = + LoggerFactory.getLogger(AddAndSetNoTopicConstraintExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final TopicSpecification specification = Diffusion.newTopicSpecification(TopicType.JSON); + final JSON value = Diffusion.dataTypes().json() + .fromJsonString("{ \"diffusion\": \"data\" }"); + + // create a topic with a value + session.feature(TopicUpdate.class) + .addAndSet("my/topic/path", specification, JSON.class, value).join(); + LOG.info("Topic updated"); + + // only allow updates if there is no topic at the given path + final UpdateConstraint constraint = Diffusion.updateConstraints().noTopic(); + + try { + // attempt to update the topic with the constraint, this will fail + session.feature(TopicUpdate.class) + .addAndSet("my/topic/path", specification, JSON.class, value, constraint).join(); + } + catch (CompletionException e) { + LOG.info("Update failed: {}", e.getCause().getMessage()); + } + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/AddAndSetSessionLockConstraintExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/AddAndSetSessionLockConstraintExample.java new file mode 100644 index 00000000..7516e653 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/AddAndSetSessionLockConstraintExample.java @@ -0,0 +1,80 @@ +/******************************************************************************* + * Copyright (C) 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.publish.constraints; + +import java.util.concurrent.CompletionException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.TopicUpdate; +import com.pushtechnology.diffusion.client.features.UpdateConstraint; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.session.Session.SessionLock; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to use addAndSet with the 'locked' constraint. + *

+ * The example uses an update constraint to ensure that addAndSet is only allowed + * when the session holds a lock on the topic path. + * + * @author DiffusionData Limited + */ +public class AddAndSetSessionLockConstraintExample { + + private static final Logger LOG = + LoggerFactory.getLogger(AddAndSetSessionLockConstraintExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final TopicSpecification specification = Diffusion.newTopicSpecification(TopicType.JSON); + + final JSON value = Diffusion.dataTypes().json() + .fromJsonString("{ \"diffusion\": \"data\" }"); + + // lock the path and create a constraint that requires the lock + final SessionLock lock = session.lock("my/topic/path").join(); + final UpdateConstraint constraint = Diffusion.updateConstraints().locked(lock); + + // add and set the topic with the constraint, this works as we have the lock + session.feature(TopicUpdate.class) + .addAndSet("my/topic/path", specification, JSON.class, value, constraint).join(); + LOG.info("Topic updated"); + + //release the lock + lock.unlock().join(); + + try { + // attempt another constrained update, this will fail as we no + // longer have the lock + session.feature(TopicUpdate.class) + .addAndSet("my/topic/path", specification, JSON.class, value, constraint).join(); + } + catch (CompletionException e) { + LOG.info("Update failed: {}", e.getCause().getMessage()); + } + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/AddAndSetValueConstraintExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/AddAndSetValueConstraintExample.java new file mode 100644 index 00000000..4b6f5d4f --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/AddAndSetValueConstraintExample.java @@ -0,0 +1,84 @@ +/******************************************************************************* + * Copyright (C) 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.publish.constraints; + +import java.util.concurrent.CompletionException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.TopicUpdate; +import com.pushtechnology.diffusion.client.features.UpdateConstraint; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to update a topic in Diffusion using the + * 'value' constraint. + *

+ * The example creates a JSON topic and uses an update constraint to ensure + * updates are only allowed if the current value matches a specified value. + * + * @author DiffusionData Limited + */ +public class AddAndSetValueConstraintExample { + + private static final Logger LOG = + LoggerFactory.getLogger(AddAndSetValueConstraintExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final TopicSpecification specification = Diffusion.newTopicSpecification(TopicType.JSON); + + final JSON initialValue = Diffusion.dataTypes().json() + .fromJsonString("{ \"diffusion\": \"data\" }"); + + final JSON differentValue = Diffusion.dataTypes().json() + .fromJsonString("{ \"diffusion\": \"data2\" }"); + + // create a topic with the initial value + session.feature(TopicUpdate.class) + .addAndSet("my/topic/path", specification, JSON.class, initialValue).join(); + LOG.info("Topic updated"); + + // only allow updates if the current value of the topic matches the initial value + final UpdateConstraint constraint = Diffusion.updateConstraints().value(initialValue); + + // update the topic with the constraint, this works as the initial value has not yet changed + session.feature(TopicUpdate.class) + .addAndSet("my/topic/path", specification, JSON.class, differentValue, constraint).join(); + LOG.info("Topic updated"); + + try { + // attempt another constrained update, this will fail as the topic + // value no longer matches the initial value + session.feature(TopicUpdate.class) + .addAndSet("my/topic/path", specification, JSON.class, differentValue, constraint).join(); + } + catch (CompletionException e) { + LOG.info("Update failed: {}", e.getCause().getMessage()); + } + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/SetTopicJSONValueWithConstraintExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/SetTopicJSONValueWithConstraintExample.java new file mode 100644 index 00000000..867a2d19 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/SetTopicJSONValueWithConstraintExample.java @@ -0,0 +1,83 @@ +/******************************************************************************* + * Copyright (C) 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.publish.constraints; + +import java.util.concurrent.CompletionException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.TopicUpdate; +import com.pushtechnology.diffusion.client.features.UpdateConstraint; +import com.pushtechnology.diffusion.client.features.UpdateConstraint.Operator; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to update a JSON topic in Diffusion using the + * 'with' constraint. + *

+ * The example creates a JSON topic and uses an update constraint to ensure updates + * are only allowed if a specific JSON path matches a given value. + * + * @author DiffusionData Limited + */ +public class SetTopicJSONValueWithConstraintExample { + + private static final Logger LOG = + LoggerFactory.getLogger(SetTopicJSONValueWithConstraintExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final JSON value = Diffusion.dataTypes().json() + .fromJsonString("{ \"diffusion\": \"data\" }"); + + final JSON differentValue = Diffusion.dataTypes().json() + .fromJsonString("{ \"diffusdion\": \"data2\" }"); + + session.feature(TopicControl.class).addTopic("my/topic/path", TopicType.JSON).join(); + session.feature(TopicUpdate.class).set("my/topic/path", JSON.class, value).join(); + LOG.info("Topic updated"); + + // only allow updates if the value at the given json pointer matches the value supplied + final UpdateConstraint constraint = Diffusion.updateConstraints() + .jsonValue().with("/diffusion", Operator.IS, "data"); + + // update the topic with the constraint, this works as the initial value has not yet changed + session.feature(TopicUpdate.class) + .set("my/topic/path", JSON.class, differentValue, constraint).join(); + LOG.info("Topic updated"); + + try { + // attempt another constrained update, this will fail as the json + // value no longer matches the initial value + session.feature(TopicUpdate.class) + .set("my/topic/path", JSON.class, value, constraint).join(); + } + catch (CompletionException e) { + LOG.info("Update failed: {}", e.getCause().getMessage()); + } + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/SetTopicJSONValueWithoutConstraintExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/SetTopicJSONValueWithoutConstraintExample.java new file mode 100644 index 00000000..b905e39d --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/SetTopicJSONValueWithoutConstraintExample.java @@ -0,0 +1,75 @@ +/******************************************************************************* + * Copyright (C) 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.publish.constraints; + +import java.util.concurrent.CompletionException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.TopicUpdate; +import com.pushtechnology.diffusion.client.features.UpdateConstraint; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to update a JSON topic in Diffusion using the + * 'without' constraint. + *

+ * The example creates a JSON topic and uses an update constraint to restrict + * updates if a specific JSON path is already present. + * + * @author DiffusionData Limited + */ +public class SetTopicJSONValueWithoutConstraintExample { + + private static final Logger LOG = + LoggerFactory.getLogger(SetTopicJSONValueWithoutConstraintExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final JSON value = Diffusion.dataTypes().json() + .fromJsonString("{ \"diffusion\": \"data\" }"); + + session.feature(TopicControl.class).addTopic("my/topic/path", TopicType.JSON).join(); + session.feature(TopicUpdate.class).set("my/topic/path", JSON.class, value).join(); + + LOG.info("Topic updated"); + + // only allow updates if the specified position in the json object does not exist + final UpdateConstraint constraint = Diffusion.updateConstraints() + .jsonValue().without("/diffusion"); + + try { + // attempt a constrained update, this will fail as the json + // value exists + session.feature(TopicUpdate.class) + .set("my/topic/path", JSON.class, value, constraint).join(); + } + catch (CompletionException e) { + LOG.info("Update failed: {}", e.getCause().getMessage()); + } + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/SetTopicNoValueConstraintExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/SetTopicNoValueConstraintExample.java new file mode 100644 index 00000000..9b4acc98 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/SetTopicNoValueConstraintExample.java @@ -0,0 +1,76 @@ +/******************************************************************************* + * Copyright (C) 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.publish.constraints; + +import java.util.concurrent.CompletionException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.TopicUpdate; +import com.pushtechnology.diffusion.client.features.UpdateConstraint; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to update a topic in Diffusion using the + * 'noValue' constraint. + *

+ * The example creates a topic and uses an update constraint to ensure updates + * are only allowed if the topic currently has no value. + * + * @author DiffusionData Limited + */ + +public class SetTopicNoValueConstraintExample { + + private static final Logger LOG = + LoggerFactory.getLogger(SetTopicNoValueConstraintExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final JSON value = Diffusion.dataTypes().json() + .fromJsonString("{ \"diffusion\": \"data\" }"); + + session.feature(TopicControl.class).addTopic("my/topic/path", TopicType.JSON).join(); + + // only allow updates if the topic has no value + final UpdateConstraint constraint = Diffusion.updateConstraints().noValue(); + + // set with constraint, this works as the topic has no value yet + session.feature(TopicUpdate.class) + .set("my/topic/path", JSON.class, value, constraint).join(); + LOG.info("Topic updated"); + + try { + // attempt another constrained update, this will fail as the topic + // now has a value + session.feature(TopicUpdate.class).set("my/topic/path", JSON.class, value, constraint).join(); + } + catch (CompletionException e) { + LOG.info("Update failed: {}", e.getCause().getMessage()); + } + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/SetTopicSessionLockConstraintExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/SetTopicSessionLockConstraintExample.java new file mode 100644 index 00000000..fa5fa200 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/SetTopicSessionLockConstraintExample.java @@ -0,0 +1,81 @@ +/******************************************************************************* + * Copyright (C) 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.publish.constraints; + +import java.util.concurrent.CompletionException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.TopicUpdate; +import com.pushtechnology.diffusion.client.features.UpdateConstraint; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.session.Session.SessionLock; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to set a topic in Diffusion using the + * 'locked' constraint. + *

+ * The example creates a topic and uses an update constraint to ensure updates + * are only allowed when the session holds a lock on the topic path. + * + * @author DiffusionData Limited + */ +public class SetTopicSessionLockConstraintExample { + + private static final Logger LOG = + LoggerFactory.getLogger(SetTopicSessionLockConstraintExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final JSON value = Diffusion.dataTypes().json() + .fromJsonString("{ \"diffusion\": \"data\" }"); + + session.feature(TopicControl.class).addTopic("my/topic/path", TopicType.JSON).join(); + + final SessionLock lock = session.lock("my/topic/path").join(); + + // only allow updates if the caller has the given lock + final UpdateConstraint constraint = Diffusion.updateConstraints().locked(lock); + + // update the topic with the constraint, this works as we have the lock + session.feature(TopicUpdate.class) + .set("my/topic/path", JSON.class, value, constraint).join(); + LOG.info("Topic updated"); + + lock.unlock().join(); + + try { + // attempt another constrained update, this will fail as we have + // released the lock. + session.feature(TopicUpdate.class) + .set("my/topic/path", JSON.class, value, constraint).join(); + } + catch (CompletionException e) { + LOG.info("Update failed: {}", e.getCause().getMessage()); + } + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/SetTopicValueConstraintExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/SetTopicValueConstraintExample.java new file mode 100644 index 00000000..14c98dbc --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/SetTopicValueConstraintExample.java @@ -0,0 +1,76 @@ +/******************************************************************************* + * Copyright (C) 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.publish.constraints; + +import java.util.concurrent.CompletionException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.TopicUpdate; +import com.pushtechnology.diffusion.client.features.UpdateConstraint; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to update a topic in Diffusion using the + * 'value' constraint. + *

+ * The example creates a topic and uses an update constraint to ensure updates + * are only allowed if the current value matches a specified value. + * + * @author DiffusionData Limited + */ +public class SetTopicValueConstraintExample { + + private static final Logger LOG = + LoggerFactory.getLogger(SetTopicValueConstraintExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final JSON value = Diffusion.dataTypes().json() + .fromJsonString("{ \"diffusion\": \"data\" }"); + + final JSON differentValue = Diffusion.dataTypes().json() + .fromJsonString("{ \"diffusion\": \"data2\" }"); + + session.feature(TopicControl.class).addTopic("my/topic/path", TopicType.JSON).join(); + session.feature(TopicUpdate.class).set("my/topic/path", JSON.class, value).join(); + LOG.info("Topic updated"); + + // only allow updates if the current value of the topic matches the given value + final UpdateConstraint constraint = Diffusion.updateConstraints().value(differentValue); + + try { + // attempt a constrained update, this will fail as the topic + // value does not match the different value specified by the constraint + session.feature(TopicUpdate.class) + .set("my/topic/path", JSON.class, value, constraint).join(); + } + catch (CompletionException e) { + LOG.info("Update failed: {}", e.getCause().getMessage()); + } + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/UpdateConstraintAndOperatorExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/UpdateConstraintAndOperatorExample.java new file mode 100644 index 00000000..aa9d8995 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/UpdateConstraintAndOperatorExample.java @@ -0,0 +1,86 @@ +/******************************************************************************* + * Copyright (C) 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.publish.constraints; + +import java.util.concurrent.CompletionException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.TopicUpdate; +import com.pushtechnology.diffusion.client.features.UpdateConstraint; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.session.Session.SessionLock; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to use the logical 'and' operator to combine multiple + * constraints when updating a topic in Diffusion. + *

+ * The example creates a topic and uses combined constraints to ensure updates + * are only allowed if the session holds a lock and no topic exists at the specified path. + * + * @author DiffusionData Limited + */ + +public class UpdateConstraintAndOperatorExample { + + private static final Logger LOG = + LoggerFactory.getLogger(UpdateConstraintAndOperatorExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final TopicSpecification specification = Diffusion.newTopicSpecification(TopicType.JSON); + + final JSON value = Diffusion.dataTypes().json() + .fromJsonString("{ \"diffusion\": \"data\" }"); + + final SessionLock lock = session.lock("my/topic/path").join(); + + // use the AND method to specify two constraints + // we require a session lock and for no topic to exist + final UpdateConstraint constraint = Diffusion.updateConstraints().locked(lock) + .and(Diffusion.updateConstraints().noTopic()); + + // update the topic with the constraint, this works as we have the lock + // and the topic does not exist yet + session.feature(TopicUpdate.class) + .addAndSet("my/topic/path", specification, JSON.class, value, constraint).join(); + + LOG.info("Topic updated"); + + try { + // attempt another constrained update, this will fail as we still + // have the lock, but the topic now exists + session.feature(TopicUpdate.class) + .addAndSet("my/topic/path", specification, JSON.class, value, constraint).join(); + } + catch (CompletionException e) { + LOG.info("Update failed: {}", e.getCause().getMessage()); + } + + lock.unlock().join(); + session.close(); + + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/UpdateConstraintOrOperatorExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/UpdateConstraintOrOperatorExample.java new file mode 100644 index 00000000..bd96614e --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/publish/constraints/UpdateConstraintOrOperatorExample.java @@ -0,0 +1,86 @@ +/******************************************************************************* + * Copyright (C) 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.publish.constraints; + +import java.util.concurrent.CompletionException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.TopicUpdate; +import com.pushtechnology.diffusion.client.features.UpdateConstraint; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to use the logical 'or' operator to combine multiple + * constraints when updating a topic in Diffusion. + *

+ * The example creates a topic and uses combined constraints to ensure updates are + * allowed if either the topic has no value or its current value matches a specified value. + * + * @author DiffusionData Limited + */ +public class UpdateConstraintOrOperatorExample { + + private static final Logger LOG = + LoggerFactory.getLogger(UpdateConstraintOrOperatorExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final TopicSpecification specification = Diffusion.newTopicSpecification(TopicType.JSON); + + final JSON value = Diffusion.dataTypes().json() + .fromJsonString("{ \"diffusion\": \"data\" }"); + + final JSON differentValue = Diffusion.dataTypes().json() + .fromJsonString("{ \"diffusion\": \"data2\" }"); + + // use the OR method to specify multiple constraints, the current + // value of the topic must match the given value or there should be no topic + final UpdateConstraint constraint = Diffusion.updateConstraints().value(value) + .or(Diffusion.updateConstraints().noTopic()); + + // update the topic, this works as we satisfy the no topic constraint + session.feature(TopicUpdate.class) + .addAndSet("my/topic/path", specification, JSON.class, value, constraint).join(); + LOG.info("Topic updated"); + + // update the topic again, this works as we satisfy the value constraint + session.feature(TopicUpdate.class) + .addAndSet("my/topic/path", specification, JSON.class, differentValue, constraint).join(); + LOG.info("Topic updated"); + + try { + // attempt another constrained update, this fails both the no topic + // and value constraints + session.feature(TopicUpdate.class) + .addAndSet("my/topic/path", specification, JSON.class, value, constraint).join(); + } + catch (CompletionException e) { + LOG.info("Update failed: {}", e.getCause().getMessage()); + } + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/remove/RemoveMultipleTopicsViaSelectorExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/remove/RemoveMultipleTopicsViaSelectorExample.java new file mode 100644 index 00000000..84644d78 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/remove/RemoveMultipleTopicsViaSelectorExample.java @@ -0,0 +1,109 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.remove; + +import static java.lang.String.format; + +import java.util.concurrent.CompletionException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; + +/** + * This example demonstrates how to remove multiple topics in Diffusion using a + * topic selector. + *

+ * The example creates a set of topics and then uses a selector to remove topics + * that match the specified path pattern. + * + * @author DiffusionData Limited + */ +public class RemoveMultipleTopicsViaSelectorExample { + + private static final Logger LOG = + LoggerFactory.getLogger(RemoveMultipleTopicsViaSelectorExample.class); + + public static void main(String[] args) throws Throwable { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final TopicControl topicControl = session.feature(TopicControl.class); + + final TopicSpecification topicSpecification = Diffusion.newTopicSpecification(TopicType.JSON); + + topicControl.addTopic("this/topic1", topicSpecification) + .join(); + + topicControl.addTopic("this/topic2", topicSpecification) + .join(); + + final TopicControl.AddTopicResult addResult1 = + topicControl.addTopic( + "my/topic/path/to/be/removed", topicSpecification) + .join(); + + if (addResult1 == TopicControl.AddTopicResult.CREATED) { + LOG.info("Topic has been created."); + } + else { + LOG.info("Topic already exists."); + } + + final TopicControl.AddTopicResult addResult2 = + topicControl.addTopic( + "my/topic/path/to/be/also/removed", topicSpecification) + .join(); + + if (addResult2 == TopicControl.AddTopicResult.CREATED) { + LOG.info("Second topic has been created."); + } + else { + LOG.info("Second topic already exists."); + } + + final TopicControl.TopicRemovalResult removeResult = + topicControl.removeTopics("?my/topic/path/to/be//") + .join(); + + final int removedCount = removeResult.getRemovedCount(); + + if (removedCount == 2) { + LOG.info("Topics have been removed."); + } + else { + final String message = format( + "Topics expected to be removed, but %d topics were removed.", + removedCount); + + LOG.error(message); + throw new IllegalStateException(message); + } + } + catch (CompletionException e) { + LOG.error("Failed to add or remove topic.", e); + + throw e.getCause(); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/remove/RemoveSingleTopicViaPathExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/remove/RemoveSingleTopicViaPathExample.java new file mode 100644 index 00000000..5cc67cfd --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/remove/RemoveSingleTopicViaPathExample.java @@ -0,0 +1,96 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.remove; + +import static java.lang.String.format; + +import java.util.concurrent.CompletionException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; + +/** + * This example demonstrates how to remove a single topic in Diffusion using the + * topic's path. + * + * @author DiffusionData Limited + */ +public class RemoveSingleTopicViaPathExample { + + private static final Logger LOG = + LoggerFactory.getLogger(RemoveSingleTopicViaPathExample.class); + + public static void main(String[] args) throws Throwable { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final TopicControl topicControl = session.feature(TopicControl.class); + + final TopicSpecification topicSpecification = Diffusion.newTopicSpecification(TopicType.JSON); + + topicControl.addTopic("this/topic1", topicSpecification) + .join(); + + topicControl.addTopic("this/topic2", topicSpecification) + .join(); + + final String topicPath = "my/topic/path/to/be/removed"; + + final TopicControl.AddTopicResult addResult = + topicControl.addTopic( + topicPath, topicSpecification) + .join(); + + if (addResult == TopicControl.AddTopicResult.CREATED) { + LOG.info("Topic has been created."); + } + else { + LOG.info("Topic already exists."); + } + + final TopicControl.TopicRemovalResult removeResult = + topicControl.removeTopics(topicPath) + .join(); + + final int removedCount = removeResult.getRemovedCount(); + + if (removedCount == 1) { + LOG.info("Topic has been removed."); + } + else { + final String message = format( + "Topic: '%s' was expected to be removed, but %d topics were removed.", + topicPath, removedCount); + + LOG.error(message); + throw new IllegalStateException(message); + } + } + catch (CompletionException e) { + LOG.error("Failed to add or remove topic.", e); + + throw e.getCause(); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/remove/RemoveTopicsWithAutomaticTopicRemovalExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/remove/RemoveTopicsWithAutomaticTopicRemovalExample.java new file mode 100644 index 00000000..19f78882 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/remove/RemoveTopicsWithAutomaticTopicRemovalExample.java @@ -0,0 +1,88 @@ +package com.pushtechnology.client.sdk.example.pubsub.remove; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl.AddTopicResult; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; + +/** + * This example demonstrates how to configure automatic topic removal in Diffusion. + *

+ * The example creates multiple topics with different removal criteria, such as + * time-based removal, removal based on subscription or update conditions, and + * session-based removal rules. + * + * @author DiffusionData Limited + */ +public class RemoveTopicsWithAutomaticTopicRemovalExample { + + private static final Logger LOG = + LoggerFactory.getLogger(RemoveTopicsWithAutomaticTopicRemovalExample.class); + + public static void main(String[] args) { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final TopicControl topicControl = session.feature(TopicControl.class); + final TopicSpecification specification = + Diffusion.newTopicSpecification(TopicType.JSON); + AddTopicResult result; + + result = topicControl.addTopic("my/topic/path/to/be/removed/time/after", + specification.withProperty(TopicSpecification.REMOVAL, + "when time after 'Tue, 4 May 2077 11:05:30 GMT'")).join(); + + LOG.info(result.toString()); + + result = topicControl.addTopic("my/topic/path/to/be/removed/subscriptions", + specification.withProperty(TopicSpecification.REMOVAL, + "when subscriptions < 1 for 10m")).join(); + + LOG.info(result.toString()); + + result = topicControl.addTopic("my/topic/path/to/be/removed/local/subscriptions", + specification.withProperty(TopicSpecification.REMOVAL, + "when local subscriptions < 1 for 10m")).join(); + + LOG.info(result.toString()); + + result = topicControl.addTopic("my/topic/path/to/be/removed/no/updates", + specification.withProperty(TopicSpecification.REMOVAL, + "when no updates for 10m")).join(); + + LOG.info(result.toString()); + + result = topicControl.addTopic("my/topic/path/to/be/removed/no/session", + specification.withProperty(TopicSpecification.REMOVAL, + "when no session has '$Principal is \"client\"' for 1h")).join(); + + LOG.info(result.toString()); + + result = topicControl.addTopic("my/topic/path/to/be/removed/no/local/session", + specification.withProperty(TopicSpecification.REMOVAL, + "when no local session has 'Department is \"Accounts\"' for 1h after 1d")).join(); + + LOG.info(result.toString()); + + result = topicControl.addTopic("my/topic/path/to/be/removed/subcriptions/or/updates", + specification.withProperty(TopicSpecification.REMOVAL, + "when subscriptions < 1 for 10m or no updates for 20m")).join(); + + LOG.info(result.toString()); + + result = topicControl.addTopic("my/topic/path/to/be/removed/subcriptions/and/updates", + specification.withProperty(TopicSpecification.REMOVAL, + "when subscriptions < 1 for 10m and no updates for 20m")).join(); + + LOG.info(result.toString()); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/subscribe/SubscribeCrossCompatibleExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/subscribe/SubscribeCrossCompatibleExample.java new file mode 100644 index 00000000..64ce575f --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/subscribe/SubscribeCrossCompatibleExample.java @@ -0,0 +1,170 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.subscribe; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.TopicUpdate; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates subscribing to a topic in Diffusion and observing its + * values across compatible data types. + *

+ * The example creates an INT64 topic, subscribes to it using a topic selector, + * and sets up value streams of type JSON and String. + *

+ * In accordance with the Diffusion type hierarchy, the JSON stream is able to receive + * data from the INT64 topic while the String stream is not. + * + * @author DiffusionData Limited + */ +public class SubscribeCrossCompatibleExample { + + private static final Logger LOG = + LoggerFactory.getLogger(SubscribeCrossCompatibleExample.class); + + public static void main(String[] args) + throws Exception { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final String topicPath = "my/int/topic/path"; + + session.feature(TopicUpdate.class).addAndSet( + topicPath, Diffusion.newTopicSpecification(TopicType.INT64), Long.class, 123L + ); + + final Topics topics = session.feature(Topics.class); + + final String topicSelectorExpression = ">my/int/topic/path"; + + final MyLoggingJsonStream jsonValueStream = new MyLoggingJsonStream(); + topics.addStream(topicSelectorExpression, JSON.class, jsonValueStream); + + final MyLoggingStringStream stringValueStream = new MyLoggingStringStream(); + topics.addStream(topicSelectorExpression, String.class, stringValueStream); + + topics.subscribe(topicSelectorExpression) + .join(); + + LOG.info("Subscribed."); + + topics.unsubscribe(topicSelectorExpression) + .join(); + + topics.removeStream(jsonValueStream); + topics.removeStream(stringValueStream); + + SECONDS.sleep(2); + } + } + + public static class MyLoggingJsonStream implements Topics.ValueStream { + private static final Logger LOG = LoggerFactory.getLogger(MyLoggingJsonStream.class); + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + + LOG.info("JSON value '{}'.", newValue.toJsonString()); + } + + @Override + public void onSubscription( + String topicPath, + TopicSpecification topicSpecification) { + + LOG.info("JSON subscribed to: '{}'.", topicPath); + } + + @Override + public void onUnsubscription( + String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + + LOG.info("JSON unsubscribed from: '{}', reason: {}.", + topicPath, unsubscribeReason); + } + + @Override + public void onClose() { + LOG.info("JSON on close."); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("JSON on error: {}.", errorReason); + } + } + + public static class MyLoggingStringStream implements Topics.ValueStream { + private static final Logger LOG = LoggerFactory.getLogger(MyLoggingStringStream.class); + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + String oldValue, + String newValue) { + + LOG.info("String value '{}'.", newValue); + } + + @Override + public void onSubscription( + String topicPath, + TopicSpecification topicSpecification) { + + LOG.info("String subscribed to: '{}'.", topicPath); + } + + @Override + public void onUnsubscription( + String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + + LOG.info("String unsubscribed from: '{}', reason: {}.", + topicPath, unsubscribeReason); + } + + @Override + public void onClose() { + LOG.info("String on close."); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("String on error: {}.", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/subscribe/SubscribeFallbackStreamExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/subscribe/SubscribeFallbackStreamExample.java new file mode 100644 index 00000000..6f62bc92 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/subscribe/SubscribeFallbackStreamExample.java @@ -0,0 +1,191 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.subscribe; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates subscribing to multiple JSON topics in Diffusion + * using both specific and fallback value streams. + *

+ * The example shows how to set up a specific value stream for selected topics and a fallback + * stream to handle any other matching topics. + * + * @author DiffusionData Limited + */ +public class SubscribeFallbackStreamExample { + + private static final Logger LOG = + LoggerFactory.getLogger(SubscribeFallbackStreamExample.class); + + public static void main(String[] args) throws Exception { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final TopicSpecification topicSpecification = Diffusion.newTopicSpecification(TopicType.JSON); + final TopicControl topicControl = session.feature(TopicControl.class); + + topicControl.addTopic("my/topic/path", topicSpecification) + .join(); + + topicControl.addTopic("my/other/topic/path", topicSpecification) + .join(); + + final Topics topics = session.feature(Topics.class); + final MyLoggingJsonStream valueStream = new MyLoggingJsonStream(); + + final String specificTopicSelectorExpression = ">my/topic/path"; + + topics.addStream(specificTopicSelectorExpression, JSON.class, valueStream); + topics.subscribe(specificTopicSelectorExpression) + .join(); + + final String topicSelectorExpression = "?my//"; + final MyLoggingJsonFallbackStream fallbackStream = new MyLoggingJsonFallbackStream(); + + topics.addFallbackStream(JSON.class, fallbackStream); + topics.subscribe(topicSelectorExpression) + .join(); + + final String thirdTopicPath = "my/additional/topic/path"; + + final TopicControl.AddTopicResult result1 = + topicControl.addTopic(thirdTopicPath, topicSpecification) + .join(); + + LOG.info("{} {}.", thirdTopicPath, result1); + + final String forthTopicPath = "this/topic/path/will/not/be/picked/up"; + + final TopicControl.AddTopicResult result2 = + topicControl.addTopic(forthTopicPath, topicSpecification) + .join(); + + LOG.info("{} {}.", forthTopicPath, result2); + + topics.unsubscribe(topicSelectorExpression) + .join(); + + topics.unsubscribe(specificTopicSelectorExpression) + .join(); + + topics.removeStream(valueStream); + topics.removeStream(fallbackStream); + + SECONDS.sleep(2); // Wait long enough for logging to be output + } + } + + public static class MyLoggingJsonStream implements Topics.ValueStream { + private static final Logger LOG = LoggerFactory.getLogger(MyLoggingJsonStream.class); + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + + LOG.info("'{}' changed from '{}' to '{}}'.", + topicPath, oldValue, newValue); + } + + @Override + public void onSubscription( + String topicPath, + TopicSpecification topicSpecification) { + + LOG.info("Subscribed to: '{}'.", topicPath); + } + + @Override + public void onUnsubscription( + String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + + LOG.info("Unsubscribed from: '{}', reason: {}.", + topicPath, unsubscribeReason); + } + + @Override + public void onClose() { + LOG.info("On close."); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("On error: {}.", errorReason); + } + } + + public static class MyLoggingJsonFallbackStream implements Topics.ValueStream { + private static final Logger LOG = LoggerFactory.getLogger(MyLoggingJsonFallbackStream.class); + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + + LOG.info("FB - '{}' changed from '{}' to '{}'.", + topicPath, oldValue, newValue); + } + + @Override + public void onSubscription( + String topicPath, + TopicSpecification topicSpecification) { + + LOG.info("FB - Subscribed to: '{}'.", topicPath); + } + + @Override + public void onUnsubscription( + String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + + LOG.info("FB - Unsubscribed from: '{}', reason: {}.", + topicPath, unsubscribeReason); + } + + @Override + public void onClose() { + LOG.info("FB - On close."); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("FB - On error: {}.", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/subscribe/SubscribeMultipleTopicsViaSelectorExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/subscribe/SubscribeMultipleTopicsViaSelectorExample.java new file mode 100644 index 00000000..0ca23bf2 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/subscribe/SubscribeMultipleTopicsViaSelectorExample.java @@ -0,0 +1,126 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.subscribe; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates subscribing to multiple topics in Diffusion + * using a topic selector. + * + * @author DiffusionData Limited + */ +public class SubscribeMultipleTopicsViaSelectorExample { + + private static final Logger LOG = + LoggerFactory.getLogger(SubscribeMultipleTopicsViaSelectorExample.class); + + public static void main(String[] args) throws Exception { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final TopicSpecification topicSpecification = + Diffusion.newTopicSpecification(TopicType.JSON); + + final TopicControl topicControl = session.feature(TopicControl.class); + + topicControl.addTopic("my/topic/path", topicSpecification) + .join(); + + topicControl.addTopic("my/other/topic/path", topicSpecification) + .join(); + + final Topics topics = session.feature(Topics.class); + final MyLoggingJsonStream valueStream = new MyLoggingJsonStream(); + + final String topicSelectorExpression = "?my//"; + + topics.addStream(topicSelectorExpression, JSON.class, valueStream); + topics.subscribe(topicSelectorExpression) + .join(); + + final TopicControl.AddTopicResult result = + topicControl.addTopic("my/additional/topic/path", topicSpecification) + .join(); + + LOG.info("Third topic: {}.", result); + + topics.unsubscribe(topicSelectorExpression) + .join(); + + topics.removeStream(valueStream); + + SECONDS.sleep(2); + } + } + + public static class MyLoggingJsonStream implements Topics.ValueStream { + private static final Logger LOG = LoggerFactory.getLogger(MyLoggingJsonStream.class); + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + + LOG.info("'{}' changed from '{}' to '{}'.", + topicPath, oldValue, newValue); + } + + @Override + public void onSubscription( + String topicPath, + TopicSpecification topicSpecification) { + + LOG.info("Subscribed to: '{}'.", topicPath); + } + + @Override + public void onUnsubscription( + String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + + LOG.info("Unsubscribed from: '{}', reason: {}.", + topicPath, unsubscribeReason); + } + + @Override + public void onClose() { + LOG.info("On close."); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("On error: {}.", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/subscribe/SubscribeSingleTopicViaPathExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/subscribe/SubscribeSingleTopicViaPathExample.java new file mode 100644 index 00000000..63820adc --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/subscribe/SubscribeSingleTopicViaPathExample.java @@ -0,0 +1,121 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.subscribe; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates subscribing to a single topic in Diffusion using + * its topic path, and receiving value updates. + * + * @author DiffusionData Limited + */ +public class SubscribeSingleTopicViaPathExample { + + private static final Logger LOG = + LoggerFactory.getLogger(SubscribeSingleTopicViaPathExample.class); + + public static void main(String[] args) throws Exception { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final String topicPath = "my/topic/path"; + final String topicSelectorExpression = ">my/topic/path"; + + session.feature(TopicControl.class).addTopic( + topicPath, Diffusion.newTopicSpecification(TopicType.JSON)).join(); + + final Topics topics = session.feature(Topics.class); + final MyLoggingJsonStream valueStream = new MyLoggingJsonStream(); + + topics.addStream(topicSelectorExpression, JSON.class, valueStream); + topics.subscribe(topicSelectorExpression) + .join(); + + LOG.info("Subscribed."); + + topics.set(topicPath, JSON.class, + Diffusion.dataTypes().json().fromJsonString("{ \"diffusion\": \"data\" }")).join(); + + topics.set(topicPath, JSON.class, + Diffusion.dataTypes().json().fromJsonString("{ \"diffusion\": \"more data\" }")).join(); + + topics.unsubscribe(topicSelectorExpression) + .join(); + + topics.removeStream(valueStream); + + SECONDS.sleep(2); // Wait long enough for logging to be output + } + } + + public static class MyLoggingJsonStream implements Topics.ValueStream { + private static final Logger LOG = LoggerFactory.getLogger(MyLoggingJsonStream.class); + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + + LOG.info("'{}' changed from '{}' to '{}'.", + topicPath, oldValue, newValue); + } + + @Override + public void onSubscription( + String topicPath, + TopicSpecification topicSpecification) { + + LOG.info("Subscribed to: '{}'.", topicPath); + } + + @Override + public void onUnsubscription( + String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + + LOG.info("Unsubscribed from: '{}', reason: {}.", + topicPath, unsubscribeReason); + } + + @Override + public void onClose() { + LOG.info("On close."); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("On error: {}.", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/pubsub/subscribe/SubscribeUsingSelectionScopesExample.java b/java/com/pushtechnology/client/sdk/example/pubsub/subscribe/SubscribeUsingSelectionScopesExample.java new file mode 100644 index 00000000..e3cff395 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/pubsub/subscribe/SubscribeUsingSelectionScopesExample.java @@ -0,0 +1,155 @@ +/******************************************************************************* + * Copyright (C) 2025 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.pubsub.subscribe; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.SubscriptionControl; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; + +/** + * This example demonstrates subscribing to a topic in Diffusion using + * selections scopes. + *

+ * Multiple application components can use the same session to subscribe and unsubscribe + * to topics using unique selection scopes which prevent unsubscriptions from + * one component affecting the other. + * + * @author DiffusionData Limited + */ +public class SubscribeUsingSelectionScopesExample { + + private static final Logger LOG = + LoggerFactory.getLogger(SubscribeUsingSelectionScopesExample.class); + + public static void main(String[] args) throws Exception { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final String topicPath = "my/topic/path"; + final String myOtherPath = "my/other/path"; + + final TopicControl topicControl = session.feature(TopicControl.class); + final SubscriptionControl subscriptionControl = session.feature(SubscriptionControl.class); + + topicControl.addTopic(topicPath, TopicType.STRING).join(); + topicControl.addTopic(myOtherPath, TopicType.STRING).join(); + + final Topics componentA = session.feature(Topics.class); + final Topics componentB = session.feature(Topics.class); + + final MyStream streamA = new MyStream("componentA"); + final MyStream streamB = new MyStream("componentB"); + + // each component registers a stream for the topics they are interested in + // and subscribe to the topics with their own scope + + componentA.addStream(topicPath, String.class, streamA); + componentB.addStream("?my//", String.class, streamB); + + componentA.subscribe(topicPath, "scopeA").join(); + componentB.subscribe(topicPath, "scopeB").join(); + componentB.subscribe(myOtherPath, "scopeB").join(); + + showSelectionScopes(session); + + // componentB unsubscribes from topicPath, scopeA is unaffected + componentB.unsubscribe(topicPath, "scopeB").join(); + + showSelectionScopes(session); + + // componentA unsubscribes from all topics, scopeB is unaffected + // topicPath is no longer in any scopes and is unsubscribed for the session + componentA.unsubscribe("?.*//", "scopeA").join(); + + // componentA removes its stream and will no longer receive updates + componentA.removeStream(streamA); + + // a control client unsubscribes all remaining scopes for myOtherPath which + // is now unsubscribed for the session + subscriptionControl.unsubscribeAllScopes(session.getSessionId(), myOtherPath).join(); + + componentB.removeStream(streamB); + } + } + + public static class MyStream implements Topics.ValueStream { + + private final String scopeName; + + public MyStream(String scopeName) { + this.scopeName = scopeName; + } + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + String oldValue, + String newValue) { + + LOG.info("{}: '{}' changed from '{}' to '{}'.", + scopeName, topicPath, oldValue, newValue); + } + + @Override + public void onSubscription( + String topicPath, + TopicSpecification topicSpecification) { + + LOG.info("{}: Subscribed to: '{}'.", scopeName, topicPath); + } + + @Override + public void onUnsubscription( + String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + + LOG.info("{}: Unsubscribed from: '{}', reason: {}.", + scopeName, topicPath, unsubscribeReason); + } + + @Override + public void onClose() { + LOG.info("{}: stream closed.", scopeName); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("{}: On error: {}.", scopeName, errorReason); + } + } + + /** + * Fetch and log selection scopes for the given session. + */ + private static void showSelectionScopes(Session session) { + session.feature(SubscriptionControl.class) + .getTopicSelections(session.getSessionId()).join() + .forEach((scopeName, selections) + -> LOG.info("{} scopes:{}", scopeName, selections)); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/remoteservers/CheckRemoteServersExample.java b/java/com/pushtechnology/client/sdk/example/remoteservers/CheckRemoteServersExample.java new file mode 100644 index 00000000..2adc7b00 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/remoteservers/CheckRemoteServersExample.java @@ -0,0 +1,103 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.remoteservers; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.RemoteServers; +import com.pushtechnology.diffusion.client.features.control.RemoteServers.CheckRemoteServerResult; +import com.pushtechnology.diffusion.client.features.control.RemoteServers.RemoteServer.ConnectionOption; +import com.pushtechnology.diffusion.client.features.control.RemoteServers.SecondaryInitiator.SecondaryInitiatorBuilder; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to check the state of remote servers in Diffusion. + * + * @author DiffusionData Limited + */ +public class CheckRemoteServersExample { + + private static final Logger LOG = LoggerFactory.getLogger( + CheckRemoteServersExample.class); + + public static void main(String[] args) throws Exception { + final Session adminSession = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final RemoteServers remoteServersControl = + adminSession.feature(RemoteServers.class); + + final SecondaryInitiatorBuilder builder = + Diffusion.newRemoteServerBuilder(SecondaryInitiatorBuilder.class); + + final Map myConnectionOptions = new HashMap<>(); + myConnectionOptions.put(ConnectionOption.RECONNECTION_TIMEOUT, "120000"); + myConnectionOptions.put(ConnectionOption.MAXIMUM_QUEUE_SIZE, "1000"); + myConnectionOptions.put(ConnectionOption.CONNECTION_TIMEOUT, "15000"); + + remoteServersControl.createRemoteServer( + builder + .principal("admin") + .credentials(Diffusion.credentials().password("password")) + .connectionOptions(myConnectionOptions) + .build("Remote Server 1", "ws://new.server.url.com") + ).join(); + + builder.reset(); + + final Map myOtherConnectionOptions = + new HashMap(); + myOtherConnectionOptions.put(ConnectionOption.RECONNECTION_TIMEOUT, "6000"); + myOtherConnectionOptions.put(ConnectionOption.MAXIMUM_QUEUE_SIZE, "10000"); + myOtherConnectionOptions.put(ConnectionOption.CONNECTION_TIMEOUT, "5000"); + + remoteServersControl.createRemoteServer( + builder + .principal("control") + .credentials(Diffusion.credentials().password("password")) + .connectionOptions(myOtherConnectionOptions) + .build("Remote Server 2", "ws://another.server.url.com") + ).join(); + + final List servers = remoteServersControl + .listRemoteServers() + .join(); + + servers.forEach(server -> { + final String name = server.getName(); + final CheckRemoteServerResult result = + remoteServersControl.checkRemoteServer(name).join(); + + final String status = result.getConnectionState().name(); + final String failureMessage = result.getFailureMessage(); + + LOG.info( + "<{}>: <{}> ({})\n", name, status, failureMessage); + }); + + remoteServersControl.removeRemoteServer("Remote Server 1").join(); + remoteServersControl.removeRemoteServer("Remote Server 2").join(); + + adminSession.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/remoteservers/CreatePrimaryInitiatorExample.java b/java/com/pushtechnology/client/sdk/example/remoteservers/CreatePrimaryInitiatorExample.java new file mode 100644 index 00000000..1f4af8ec --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/remoteservers/CreatePrimaryInitiatorExample.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.remoteservers; + +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.RemoteServers; +import com.pushtechnology.diffusion.client.features.control.RemoteServers.PrimaryInitiator.PrimaryInitiatorBuilder; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to create a primary initiator remote server in Diffusion. + * + * @author DiffusionData Limited + */ +public class CreatePrimaryInitiatorExample { + + private static final Logger LOG = LoggerFactory.getLogger( + CreatePrimaryInitiatorExample.class); + + public static void main(String[] args) { + + final Session adminSession = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final RemoteServers remoteServersControl = + adminSession.feature(RemoteServers.class); + + final RemoteServers.PrimaryInitiator.PrimaryInitiatorBuilder builder = + Diffusion.newRemoteServerBuilder(PrimaryInitiatorBuilder.class); + + final List urls = new ArrayList<>(); + urls.add("ws://new.server.url.com:8080"); + urls.add("ws://new.server.url.com:8081"); + urls.add("ws://new.server.url.com:8082"); + + remoteServersControl.createRemoteServer( + builder + .retryDelay(2500) + .build("Remote Server 1", urls, "High Volume Connector") + ).join(); + + remoteServersControl.removeRemoteServer("Remote Server 1").join(); + adminSession.close(); + + LOG.info("created remote server"); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/remoteservers/CreateSecondaryAcceptorExample.java b/java/com/pushtechnology/client/sdk/example/remoteservers/CreateSecondaryAcceptorExample.java new file mode 100644 index 00000000..0a5d8400 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/remoteservers/CreateSecondaryAcceptorExample.java @@ -0,0 +1,70 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.remoteservers; + +import java.util.HashMap; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.RemoteServers; +import com.pushtechnology.diffusion.client.features.control.RemoteServers.SecondaryAcceptor.SecondaryAcceptorBuilder; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to create a secondary acceptor remote server in Diffusion. + * + * @author DiffusionData Limited + */ +public class CreateSecondaryAcceptorExample { + + private static final Logger LOG = LoggerFactory.getLogger( + CreateSecondaryAcceptorExample.class); + + public static void main(String[] args) { + + final Session adminSession = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final RemoteServers remoteServersControl = + adminSession.feature(RemoteServers.class); + + final RemoteServers.SecondaryAcceptor.SecondaryAcceptorBuilder builder = + Diffusion.newRemoteServerBuilder(SecondaryAcceptorBuilder.class); + + final Map + myConnectionOptions = new HashMap<>(); + myConnectionOptions.put(RemoteServers.RemoteServer.ConnectionOption.WRITE_TIMEOUT, "2000"); + myConnectionOptions.put(RemoteServers.RemoteServer.ConnectionOption.MAXIMUM_QUEUE_SIZE, "1000"); + myConnectionOptions.put(RemoteServers.RemoteServer.ConnectionOption.CONNECTION_TIMEOUT, "15000"); + + remoteServersControl.createRemoteServer( + builder + .principal("") + .connectionOptions(myConnectionOptions) + .missingTopicNotificationFilter("?abc") + .build("Remote Server 1", "ws://new.server.url.com") + ).join(); + + remoteServersControl.removeRemoteServer("Remote Server 1").join(); + adminSession.close(); + + LOG.info("created secondary acceptor"); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/remoteservers/CreateSecondaryInitiatorExample.java b/java/com/pushtechnology/client/sdk/example/remoteservers/CreateSecondaryInitiatorExample.java new file mode 100644 index 00000000..2e332d2b --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/remoteservers/CreateSecondaryInitiatorExample.java @@ -0,0 +1,71 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.remoteservers; + +import java.util.HashMap; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.RemoteServers; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to create a secondary initiator remote server in Diffusion. + * + * @author DiffusionData Limited + */ +public class CreateSecondaryInitiatorExample { + + private static final Logger LOG = LoggerFactory.getLogger( + CreateSecondaryInitiatorExample.class); + + public static void main(String[] args) { + + final Session adminSession = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final RemoteServers remoteServersControl = + adminSession.feature(RemoteServers.class); + + final RemoteServers.SecondaryInitiator.SecondaryInitiatorBuilder builder = + Diffusion.newRemoteServerBuilder( + RemoteServers.SecondaryInitiator.SecondaryInitiatorBuilder.class); + + final Map + myConnectionOptions = new HashMap<>(); + myConnectionOptions.put(RemoteServers.RemoteServer.ConnectionOption.RECONNECTION_TIMEOUT, "120000"); + myConnectionOptions.put(RemoteServers.RemoteServer.ConnectionOption.MAXIMUM_QUEUE_SIZE, "1000"); + myConnectionOptions.put(RemoteServers.RemoteServer.ConnectionOption.CONNECTION_TIMEOUT, "15000"); + + remoteServersControl.createRemoteServer( + builder + .principal("admin") + .credentials(Diffusion.credentials().password("password")) + .connectionOptions(myConnectionOptions) + .missingTopicNotificationFilter("?abc") + .build("Remote Server 1", "ws://new.server.url.com") + ).join(); + + remoteServersControl.removeRemoteServer("Remote Server 1").join(); + adminSession.close(); + + LOG.info("created secondary initiator"); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/remoteservers/ListRemoteServersExample.java b/java/com/pushtechnology/client/sdk/example/remoteservers/ListRemoteServersExample.java new file mode 100644 index 00000000..88976d90 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/remoteservers/ListRemoteServersExample.java @@ -0,0 +1,96 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.remoteservers; + + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.RemoteServers; +import com.pushtechnology.diffusion.client.features.control.RemoteServers.RemoteServer; +import com.pushtechnology.diffusion.client.features.control.RemoteServers.RemoteServer.ConnectionOption; +import com.pushtechnology.diffusion.client.features.control.RemoteServers.SecondaryInitiator.SecondaryInitiatorBuilder; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to list remote servers in Diffusion. + * + * @author DiffusionData Limited + */ +public class ListRemoteServersExample { + + private static final Logger LOG = LoggerFactory.getLogger( + ListRemoteServersExample.class); + + public static void main(String[] args) throws Exception { + + final Session adminSession = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final RemoteServers remoteServersControl = + adminSession.feature(RemoteServers.class); + + final SecondaryInitiatorBuilder builder = + Diffusion.newRemoteServerBuilder(SecondaryInitiatorBuilder.class); + + final Map myConnectionOptions = new HashMap<>(); + myConnectionOptions.put(ConnectionOption.RECONNECTION_TIMEOUT, "120000"); + myConnectionOptions.put(ConnectionOption.MAXIMUM_QUEUE_SIZE, "1000"); + myConnectionOptions.put(ConnectionOption.CONNECTION_TIMEOUT, "15000"); + + remoteServersControl.createRemoteServer( + builder + .principal("admin") + .credentials(Diffusion.credentials().password("password")) + .connectionOptions(myConnectionOptions) + .build("Remote Server 1", "ws://new.server.url.com") + ).join(); + + builder.reset(); + + final Map myOtherConnectionOptions = new HashMap<>(); + myOtherConnectionOptions.put(ConnectionOption.RECONNECTION_TIMEOUT, "6000"); + myOtherConnectionOptions.put(ConnectionOption.MAXIMUM_QUEUE_SIZE, "10000"); + myOtherConnectionOptions.put(ConnectionOption.CONNECTION_TIMEOUT, "5000"); + + remoteServersControl.createRemoteServer( + builder + .principal("control") + .credentials(Diffusion.credentials().password("password")) + .connectionOptions(myOtherConnectionOptions) + .build("Remote Server 2", "ws://another.server.url.com") + ).join(); + + final List servers = remoteServersControl + .listRemoteServers() + .join(); + + servers.forEach(server -> System.out.printf("<%s>\n", server.getName())); + + remoteServersControl.removeRemoteServer("Remote Server 1").join(); + remoteServersControl.removeRemoteServer("Remote Server 2").join(); + + adminSession.close(); + + LOG.info("remote servers created: {}", servers.size()); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/remoteservers/RemoveRemoteServersExample.java b/java/com/pushtechnology/client/sdk/example/remoteservers/RemoveRemoteServersExample.java new file mode 100644 index 00000000..34798fb1 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/remoteservers/RemoveRemoteServersExample.java @@ -0,0 +1,72 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.remoteservers; + +import java.util.HashMap; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.RemoteServers; +import com.pushtechnology.diffusion.client.features.control.RemoteServers.RemoteServer.ConnectionOption; +import com.pushtechnology.diffusion.client.features.control.RemoteServers.SecondaryInitiator.SecondaryInitiatorBuilder; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to remove remote servers in Diffusion. + * + * @author DiffusionData Limited + */ +public class RemoveRemoteServersExample { + + private static final Logger LOG = LoggerFactory.getLogger( + RemoveRemoteServersExample.class); + + public static void main(String[] args) throws Exception { + + final Session adminSession = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final RemoteServers remoteServersControl = + adminSession.feature(RemoteServers.class); + + final SecondaryInitiatorBuilder builder = + Diffusion.newRemoteServerBuilder(SecondaryInitiatorBuilder.class); + + final Map myConnectionOptions = new HashMap<>(); + myConnectionOptions.put(ConnectionOption.RECONNECTION_TIMEOUT, "120000"); + myConnectionOptions.put(ConnectionOption.MAXIMUM_QUEUE_SIZE, "1000"); + myConnectionOptions.put(ConnectionOption.CONNECTION_TIMEOUT, "15000"); + + remoteServersControl.createRemoteServer( + builder + .principal("admin") + .credentials(Diffusion.credentials().password("password")) + .connectionOptions(myConnectionOptions) + .build("Remote Server 1", "ws://new.server.url.com") + ).join(); + + remoteServersControl.removeRemoteServer("Remote Server 1").join(); + System.out.println("Remote Server 1 has been removed"); + + adminSession.close(); + + LOG.info("Remote Server 1 has been removed"); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/security/GetGlobalPermissionsExample.java b/java/com/pushtechnology/client/sdk/example/security/GetGlobalPermissionsExample.java new file mode 100644 index 00000000..29a44f67 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/security/GetGlobalPermissionsExample.java @@ -0,0 +1,55 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.security; + +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.Security; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.types.GlobalPermission; + +/** + * This example demonstrates how to retrieve the global permissions using the + * Security feature. + * + * @author DiffusionData Limited + */ +public class GetGlobalPermissionsExample { + + private static final Logger LOG = LoggerFactory.getLogger( + GetGlobalPermissionsExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Set globalPermissions = session.feature(Security.class) + .getGlobalPermissions() + .join(); + + for (GlobalPermission permission : globalPermissions) { + LOG.info(permission.name()); + } + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/security/GetPathPermissionsExample.java b/java/com/pushtechnology/client/sdk/example/security/GetPathPermissionsExample.java new file mode 100644 index 00000000..39c248e3 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/security/GetPathPermissionsExample.java @@ -0,0 +1,55 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.security; + +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.Security; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.types.PathPermission; + +/** + * This example demonstrates how to retrieve path permissions using the + * Security feature. + * + * @author DiffusionData Limited + */ +public class GetPathPermissionsExample { + + private static final Logger LOG = LoggerFactory.getLogger( + GetPathPermissionsExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Set pathPermissions = session.feature(Security.class) + .getPermissionsForPath(".*//") + .join(); + + for (PathPermission permission : pathPermissions) { + LOG.info(permission.name()); + } + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/security/ReauthenticateExample.java b/java/com/pushtechnology/client/sdk/example/security/ReauthenticateExample.java new file mode 100644 index 00000000..841df8d8 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/security/ReauthenticateExample.java @@ -0,0 +1,54 @@ +/******************************************************************************* + * Copyright (C) 2025 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.security; + +import java.util.Collections; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.Security; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.types.Credentials; + +/** + * This example demonstrates how to re-authenticate a Diffusion session. + * + * @author DiffusionData Limited + */ +public class ReauthenticateExample { + + private static final Logger LOG = LoggerFactory.getLogger( + ReauthenticateExample.class); + + public static void main(String[] args) throws Exception { + + final Credentials credentials = Diffusion.credentials().password("password"); + + final Session session = Diffusion.sessions() + .principal("admin") + .credentials(credentials) + .open("ws://localhost:8080"); + + session.feature(Security.class) + .reauthenticate("control", credentials, Collections.emptyMap()) + .join(); + + LOG.info("Session reauthenticated for principal {}", session.getPrincipal()); + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/metricalerts/ListMetricAlertsExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/metricalerts/ListMetricAlertsExample.java new file mode 100644 index 00000000..1349dfc7 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/metricalerts/ListMetricAlertsExample.java @@ -0,0 +1,58 @@ +/******************************************************************************* + * Copyright (C) 2025 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.serverconfiguration.metrics.metricalerts; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.Metrics; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to list metric alerts in Diffusion. + * + * @author DiffusionData Limited + */ +public class ListMetricAlertsExample { + + private static final Logger LOG = LoggerFactory.getLogger( + ListMetricAlertsExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Metrics metrics = session.feature(Metrics.class); + + for (int i = 0; i < 5; i++) { + final String alertName = "alert" + i; + final String topic = "my/topic/path/" + i; + + metrics.setMetricAlert(alertName, + "select os_system_cpu_load into topic " + topic).join(); + } + + final List alerts = metrics.listMetricAlerts().join(); + alerts.forEach(alert -> LOG.info(alert.getName())); + + session.close(); + } +} \ No newline at end of file diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/metricalerts/RemoveMetricAlertExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/metricalerts/RemoveMetricAlertExample.java new file mode 100644 index 00000000..290e2c52 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/metricalerts/RemoveMetricAlertExample.java @@ -0,0 +1,51 @@ +/******************************************************************************* + * Copyright (C) 2025 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.serverconfiguration.metrics.metricalerts; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.Metrics; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to remove metric alerts in Diffusion. + * + * @author DiffusionData Limited + */ +public class RemoveMetricAlertExample { + + private static final Logger LOG = LoggerFactory.getLogger( + RemoveMetricAlertExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Metrics metrics = session.feature(Metrics.class); + + metrics.setMetricAlert("myAlert", + "select os_system_cpu_load into topic my/topic/path").join(); + + metrics.removeMetricAlert("myAlert").join(); + + LOG.info("alert removed"); + session.close(); + } +} \ No newline at end of file diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/metricalerts/SetMetricAlertExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/metricalerts/SetMetricAlertExample.java new file mode 100644 index 00000000..3841f2f7 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/metricalerts/SetMetricAlertExample.java @@ -0,0 +1,58 @@ +/******************************************************************************* + * Copyright (C) 2025 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.serverconfiguration.metrics.metricalerts; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.Metrics; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to set metric alerts in Diffusion. + * + * @author DiffusionData Limited + */ +public class SetMetricAlertExample { + + private static final Logger LOG = LoggerFactory.getLogger( + SetMetricAlertExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Metrics metrics = session.feature(Metrics.class); + + metrics.setMetricAlert("myAlert", "select os_system_cpu_load into topic my/topic/path").join(); + + LOG.info("alert created"); + Thread.sleep(5000); + + final Topics.FetchResult result = session.feature(Topics.class) + .fetchRequest().withValues(JSON.class).fetch("my/topic/path").join(); + + final String topicValue = result.results().get(0).value().toJsonString(); + + LOG.info("Topic value: {}", topicValue); + session.close(); + } +} \ No newline at end of file diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/sessionmetriccollector/ListSessionMetricCollectorsExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/sessionmetriccollector/ListSessionMetricCollectorsExample.java new file mode 100644 index 00000000..bc3dc6f6 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/sessionmetriccollector/ListSessionMetricCollectorsExample.java @@ -0,0 +1,85 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.serverconfiguration.metrics.sessionmetriccollector; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.Metrics; +import com.pushtechnology.diffusion.client.features.control.Metrics.SessionMetricCollector; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to list session metric collectors using the + * Metrics feature. + * + * @author DiffusionData Limited + */ +public class ListSessionMetricCollectorsExample { + + private static final Logger LOG = LoggerFactory.getLogger( + ListSessionMetricCollectorsExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Metrics metricsControl = session.feature(Metrics.class); + final SessionMetricCollector.Builder builder = Diffusion.newSessionMetricCollectorBuilder(); + + metricsControl.putSessionMetricCollector(builder + .exportToPrometheus(false) + .maximumGroups(10) + .removeMetricsWithNoMatches(true) + .groupByProperty("$Location") + .create("Session Metric Collector 1", "$Principal is 'control'")); + + builder.reset(); + + metricsControl.putSessionMetricCollector(builder + .exportToPrometheus(true) + .maximumGroups(250) + .removeMetricsWithNoMatches(true) + .groupByProperty("$Location") + .create("Session Metric Collector 2", "$Principal is 'control'")); + + final List collectors = metricsControl + .listSessionMetricCollectors() + .join(); + + collectors.forEach(c -> + System.out.printf("<%s>: <%s> (<%d>, <%b>,<%b>,<%s>)\n", + c.getName(), + c.getSessionFilter(), + c.maximumGroups(), + c.exportsToPrometheus(), + c.removesMetricsWithNoMatches(), + c.getGroupByProperties()) + ); + + SECONDS.sleep(5); + session.close(); + + LOG.info("Listed {} collectors", collectors.size()); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/sessionmetriccollector/PutSessionMetricCollectorExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/sessionmetriccollector/PutSessionMetricCollectorExample.java new file mode 100644 index 00000000..64e53ee1 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/sessionmetriccollector/PutSessionMetricCollectorExample.java @@ -0,0 +1,62 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.serverconfiguration.metrics.sessionmetriccollector; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.Metrics; +import com.pushtechnology.diffusion.client.features.control.Metrics.SessionMetricCollector; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to add a session metric collector using the + * Metrics feature. + * + * @author DiffusionData Limited + */ +public class PutSessionMetricCollectorExample { + + private static final Logger LOG = LoggerFactory.getLogger( + PutSessionMetricCollectorExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Metrics metricsControl = session.feature(Metrics.class); + + final SessionMetricCollector sessionMetricCollector = + Diffusion.newSessionMetricCollectorBuilder() + .exportToPrometheus(false) + .maximumGroups(10) + .removeMetricsWithNoMatches(true) + .groupByProperty("$Location") + .create("Session Metric Collector 1", "$Principal is 'control'"); + + metricsControl.putSessionMetricCollector(sessionMetricCollector); + SECONDS.sleep(5); + + session.close(); + + LOG.info("Created {}", sessionMetricCollector.getName()); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/sessionmetriccollector/RemoveSessionMetricCollectorExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/sessionmetriccollector/RemoveSessionMetricCollectorExample.java new file mode 100644 index 00000000..52ce296b --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/sessionmetriccollector/RemoveSessionMetricCollectorExample.java @@ -0,0 +1,64 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.serverconfiguration.metrics.sessionmetriccollector; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.Metrics; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to remove a session metric collector using the + * Metrics feature. + * + * @author DiffusionData Limited + */ +public class RemoveSessionMetricCollectorExample { + + private static final Logger LOG = LoggerFactory.getLogger( + RemoveSessionMetricCollectorExample.class); + + public static void main(String[] args) throws Exception { + + final Session adminSession = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Metrics metricsControl = adminSession.feature(Metrics.class); + + final Metrics.SessionMetricCollector sessionMetricCollector = + Diffusion.newSessionMetricCollectorBuilder() + .exportToPrometheus(false) + .maximumGroups(10) + .removeMetricsWithNoMatches(true) + .groupByProperty("$Location") + .create("Session Metric Collector 1", "$Principal is 'control'"); + + metricsControl.putSessionMetricCollector(sessionMetricCollector); + SECONDS.sleep(5); + + metricsControl.removeSessionMetricCollector(sessionMetricCollector.getName()); + System.out.printf("%s has been removed", sessionMetricCollector.getName()); + + adminSession.close(); + + LOG.info("{} has been removed", sessionMetricCollector.getName()); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/topicmetriccollector/GetMetricsConsoleExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/topicmetriccollector/GetMetricsConsoleExample.java new file mode 100644 index 00000000..b2dd1ce0 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/topicmetriccollector/GetMetricsConsoleExample.java @@ -0,0 +1,98 @@ +/******************************************************************************* + * Copyright (C) 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.serverconfiguration.metrics.topicmetriccollector; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.Metrics; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to retrieve server metrics using the Metrics + * feature in Diffusion. + * + * @author DiffusionData Limited + */ +public class GetMetricsConsoleExample { + + private static final Logger LOG = LoggerFactory.getLogger( + GetMetricsConsoleExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Metrics metricsControl = session.feature(Metrics.class); + + final Set requiredMetrics = new HashSet<>( + Arrays.asList( + "diffusion_server_time_zone", + "diffusion_server_user_directory", + "diffusion_server_license_expiry_date", + "diffusion_server_uptime_millis", + "diffusion_license", + "diffusion_server_free_memory_bytes", + "diffusion_server_max_memory_bytes", + "diffusion_server_total_memory_bytes", + "diffusion_release", + "diffusion_server_start_date", + "diffusion_server_start_date_millis", + "diffusion_server_used_swap_space_size_bytes", + "diffusion_server_used_physical_memory_size_bytes", + "diffusion_server_number_of_topics", + "diffusion_server_session_locks", + "diffusion_server_user_name", + "diffusion_server_uptime", + "diffusion_multiplexer_manager_number_of_multiplexers" + ) + ); + + final Metrics.MetricsResult result = metricsControl.metricsRequest() + .filter(requiredMetrics) + .fetch().join(); + + final String serverName = result.getServerNames().iterator().next(); + + final List collections = + result.getMetrics(serverName); + + collections.forEach(collection -> { + collection.getSamples().forEach(metricSample -> { + + final String name = metricSample.getName(); + final String type = collection.getType().name(); + final String unit = collection.getUnit(); + + final String value = "GAUGE".equals(type) ? + String.valueOf(metricSample.getValue()) : + metricSample.getLabelValues().toString(); + + LOG.info("{}: {} {} ({})", name, value, unit, type); + }); + }); + + session.close(); + } +} \ No newline at end of file diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/topicmetriccollector/GetMetricsOutboundBytesExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/topicmetriccollector/GetMetricsOutboundBytesExample.java new file mode 100644 index 00000000..9ccb1f1d --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/topicmetriccollector/GetMetricsOutboundBytesExample.java @@ -0,0 +1,66 @@ +/******************************************************************************* + * Copyright (C) 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.serverconfiguration.metrics.topicmetriccollector; + +import java.util.Collections; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.Metrics; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to retrieve server metrics for network outbound + * bytes using the Metrics feature in Diffusion. + * + * @author DiffusionData Limited + */ +public class GetMetricsOutboundBytesExample { + + private static final Logger LOG = LoggerFactory.getLogger( + GetMetricsOutboundBytesExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Metrics metricsControl = session.feature(Metrics.class); + + final Metrics.MetricsResult result = metricsControl.metricsRequest() + .currentServer() + .filter(Collections.singleton("diffusion_network_outbound_bytes")) + .fetch().join(); + + final String serverName = result.getServerNames().iterator().next(); + + final Metrics.MetricSampleCollection collection = + result.getMetrics(serverName).get(0); + + final Metrics.MetricSample sample = collection.getSamples().get(0); + + LOG.info("{}: {} {} ({})", + collection.getName(), + sample.getValue(), + collection.getUnit(), + collection.getType()); + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/topicmetriccollector/ListTopicMetricCollectorsExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/topicmetriccollector/ListTopicMetricCollectorsExample.java new file mode 100644 index 00000000..d4ff9598 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/topicmetriccollector/ListTopicMetricCollectorsExample.java @@ -0,0 +1,86 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.serverconfiguration.metrics.topicmetriccollector; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.Metrics; +import com.pushtechnology.diffusion.client.features.control.Metrics.TopicMetricCollector; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to list metric collectors using the Metrics + * feature in Diffusion. + * + * @author DiffusionData Limited + */ +public class ListTopicMetricCollectorsExample { + + private static final Logger LOG = LoggerFactory.getLogger( + ListTopicMetricCollectorsExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Metrics metricsControl = session.feature(Metrics.class); + final TopicMetricCollector.Builder builder = + Diffusion.newTopicMetricCollectorBuilder(); + + builder + .exportToPrometheus(false) + .maximumGroups(10) + .groupByTopicType(true); + + metricsControl.putTopicMetricCollector( + builder.create("Topic Metric Collector 1", "?/my/topic//")).join(); + + builder.reset(); + + builder + .exportToPrometheus(true) + .maximumGroups(250) + .groupByTopicType(false); + + metricsControl.putTopicMetricCollector( + builder.create("Topic Metric Collector 2", "?/my/topic//")).join(); + + final List metricCollectorList = + metricsControl.listTopicMetricCollectors().join(); + + metricCollectorList.forEach(collector -> { + System.out.printf("%s: %s (%d, %s, %s)\n", + collector.getName(), + collector.getTopicSelector(), + collector.maximumGroups(), + collector.exportsToPrometheus(), + collector.groupsByTopicType() + ); + + metricsControl.removeTopicMetricCollector(collector.getName()).join(); + }); + + session.close(); + + LOG.info("Collectors listed {}", metricCollectorList.size()); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/topicmetriccollector/PutTopicMetricCollectorExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/topicmetriccollector/PutTopicMetricCollectorExample.java new file mode 100644 index 00000000..81c56de5 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/topicmetriccollector/PutTopicMetricCollectorExample.java @@ -0,0 +1,60 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.serverconfiguration.metrics.topicmetriccollector; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.Metrics; +import com.pushtechnology.diffusion.client.features.control.Metrics.TopicMetricCollector; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to add metric collectors using the Metrics + * feature in Diffusion. + * + * @author DiffusionData Limited + */ +public class PutTopicMetricCollectorExample { + + private static final Logger LOG = LoggerFactory.getLogger( + PutTopicMetricCollectorExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Metrics metricsControl = session.feature(Metrics.class); + + final TopicMetricCollector topicMetricCollector = + Diffusion.newTopicMetricCollectorBuilder() + .exportToPrometheus(false) + .maximumGroups(10) + .groupByTopicType(true) + .groupByTopicView(false) + .create("Topic Metric Collector 1", "?/my/topic//"); + + metricsControl.putTopicMetricCollector(topicMetricCollector).join(); + + System.out.printf("Created %s\n", topicMetricCollector.getName()); + session.close(); + + LOG.info("Created {}", topicMetricCollector.getName()); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/topicmetriccollector/RemoveTopicMetricCollectorExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/topicmetriccollector/RemoveTopicMetricCollectorExample.java new file mode 100644 index 00000000..868a7fcf --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/metrics/topicmetriccollector/RemoveTopicMetricCollectorExample.java @@ -0,0 +1,63 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.serverconfiguration.metrics.topicmetriccollector; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.Metrics; +import com.pushtechnology.diffusion.client.features.control.Metrics.TopicMetricCollector; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to remove metric collectors using the Metrics + * feature in Diffusion. + * + * @author DiffusionData Limited + */ +public class RemoveTopicMetricCollectorExample { + + private static final Logger LOG = LoggerFactory.getLogger( + RemoveTopicMetricCollectorExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Metrics metricsControl = session.feature(Metrics.class); + + final TopicMetricCollector topicMetricCollector = + Diffusion.newTopicMetricCollectorBuilder() + .exportToPrometheus(false) + .maximumGroups(10) + .groupByTopicType(true) + .groupByTopicView(false) + .create("Topic Metric Collector 1", "?/my/topic//"); + + final String collectorName = topicMetricCollector.getName(); + + metricsControl.putTopicMetricCollector(topicMetricCollector).join(); + metricsControl.removeTopicMetricCollector(collectorName).join(); + + System.out.printf("%s has been removed", collectorName); + session.close(); + + LOG.info("Removed {}", collectorName); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/DefineRolesHierarchyExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/DefineRolesHierarchyExample.java new file mode 100644 index 00000000..b8d3fcf7 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/DefineRolesHierarchyExample.java @@ -0,0 +1,62 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.serverconfiguration.securitycontrol; + +import java.util.HashSet; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.SecurityControl; +import com.pushtechnology.diffusion.client.features.control.clients.SecurityControl.ScriptBuilder; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to define a roles hierarchy using the security + * control feature in Diffusion. + *

+ * The example assigns a set of roles to an existing role by updating the security store. + * + * @author DiffusionData Limited + */ +public class DefineRolesHierarchyExample { + + private static final Logger LOG = LoggerFactory.getLogger( + DefineRolesHierarchyExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final SecurityControl securityControl = session.feature(SecurityControl.class); + final ScriptBuilder builder = securityControl.scriptBuilder(); + + final Set myRoles = new HashSet<>(); + myRoles.add("CLIENT"); + myRoles.add("CLIENT_CONTROL"); + + builder.setRoleIncludes("OPERATOR", myRoles); + + securityControl.updateStore(builder.script()).whenComplete((r, ex) -> + LOG.info("OPERATOR now includes CLIENT and CLIENT_CONTROL roles")); + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/DeisolatePathExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/DeisolatePathExample.java new file mode 100644 index 00000000..b41f097c --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/DeisolatePathExample.java @@ -0,0 +1,63 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.serverconfiguration.securitycontrol; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.SecurityControl; +import com.pushtechnology.diffusion.client.features.control.clients.SecurityControl.ScriptBuilder; +import com.pushtechnology.diffusion.client.session.Session; + +public class DeisolatePathExample { + + /** + * This example demonstrates how to deisolate a topic path using the security + * control feature in Diffusion. + * + * @author DiffusionData Limited + */ + private static final Logger LOG = LoggerFactory.getLogger( + DeisolatePathExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final SecurityControl securityControl = session.feature(SecurityControl.class); + final ScriptBuilder builder = securityControl.scriptBuilder(); + + builder.isolatePath("my/topic/path"); + final String script = builder.script(); + + LOG.info("Isolating my/topic/path permissions from parent and default path permissions"); + + securityControl.updateStore(script) + .whenComplete((r, ex) -> LOG.info(script)); + + builder.deisolatePath("my/topic/path"); + + LOG.info("Desolating my/topic/path"); + + securityControl.updateStore(script) + .whenComplete((r, ex) -> LOG.info(builder.script())); + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/IsolatePathExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/IsolatePathExample.java new file mode 100644 index 00000000..cd76ed6a --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/IsolatePathExample.java @@ -0,0 +1,56 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.serverconfiguration.securitycontrol; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.SecurityControl; +import com.pushtechnology.diffusion.client.features.control.clients.SecurityControl.ScriptBuilder; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to isolate a topic path using the security + * control feature in Diffusion. + * + * @author DiffusionData Limited + */ +public class IsolatePathExample { + + private static final Logger LOG = LoggerFactory.getLogger( + IsolatePathExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final SecurityControl securityControl = session.feature(SecurityControl.class); + final ScriptBuilder builder = securityControl.scriptBuilder(); + + builder.isolatePath("my/topic/path"); + final String script = builder.script(); + + LOG.info("Isolating my/topic/path permissions from parent and default path permissions"); + + securityControl.updateStore(script) + .whenComplete((r, ex) -> LOG.info(script)); + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/RemovePathPermissionsExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/RemovePathPermissionsExample.java new file mode 100644 index 00000000..befcba9a --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/RemovePathPermissionsExample.java @@ -0,0 +1,74 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.serverconfiguration.securitycontrol; + +import java.util.HashSet; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.SecurityControl; +import com.pushtechnology.diffusion.client.features.control.clients.SecurityControl.ScriptBuilder; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.types.PathPermission; + +/** + * This example demonstrates how remove path permissions for a role using the + * security control feature in Diffusion. + *

+ * The example first assigns the `UPDATE_TOPIC` and `MODIFY_TOPIC` permissions + * to the `CLIENT` role for a specified topic path, and then removes these permissions. + * + * @author DiffusionData Limited + */ +public class RemovePathPermissionsExample { + + private static final Logger LOG = LoggerFactory.getLogger( + RemovePathPermissionsExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final SecurityControl securityControl = session.feature(SecurityControl.class); + final ScriptBuilder builder = securityControl.scriptBuilder(); + + final Set myPermissions = new HashSet<>(); + myPermissions.add(PathPermission.UPDATE_TOPIC); + myPermissions.add(PathPermission.MODIFY_TOPIC); + + builder.setPathPermissions("CLIENT", "my/topic/path", myPermissions); + final String script = builder.script(); + + LOG.info("Allowing Role CLIENT to update and modify my/topic/path"); + + securityControl.updateStore(script) + .whenComplete((r, ex) -> LOG.info(script)); + + builder.removePathPermissions("CLIENT", "my/topic/path"); + + LOG.info("Removing path permissions for Role CLIENT at my/topic/path"); + + securityControl.updateStore(builder.script()) + .whenComplete((r, ex) -> LOG.info(builder.script())); + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/RestrictRoleEditPermissionsExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/RestrictRoleEditPermissionsExample.java new file mode 100644 index 00000000..af89a30b --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/RestrictRoleEditPermissionsExample.java @@ -0,0 +1,57 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.serverconfiguration.securitycontrol; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.SecurityControl; +import com.pushtechnology.diffusion.client.features.control.clients.SecurityControl.ScriptBuilder; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to restrict edit permissions for a role using + * the security control feature in Diffusion. + *

+ * The example locks the `EXAMPLE` role, making it editable only by the specified + * `admin` principal. + * + * @author DiffusionData Limited + */ +public class RestrictRoleEditPermissionsExample { + + private static final Logger LOG = LoggerFactory.getLogger( + RestrictRoleEditPermissionsExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final SecurityControl securityControl = session.feature(SecurityControl.class); + final ScriptBuilder builder = securityControl.scriptBuilder(); + + builder.setRoleLockedByPrincipal("EXAMPLE", "admin"); + + + securityControl.updateStore(builder.script()) + .whenComplete((r, ex) -> LOG.info("EXAMPLE role has been locked by admin principal")); + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/SetDefaultPathPermissionsExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/SetDefaultPathPermissionsExample.java new file mode 100644 index 00000000..ce03940f --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/SetDefaultPathPermissionsExample.java @@ -0,0 +1,66 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.serverconfiguration.securitycontrol; + +import java.util.HashSet; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.SecurityControl; +import com.pushtechnology.diffusion.client.features.control.clients.SecurityControl.ScriptBuilder; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.types.PathPermission; + +/** + * This example demonstrates how to set default path permissions for a role using + * the security control feature in Diffusion. + *

+ * The example assigns `UPDATE_TOPIC` and `MODIFY_TOPIC` permissions to the + * `CLIENT` role as default path permissions. + * + * @author DiffusionData Limited + */ +public class SetDefaultPathPermissionsExample { + + private static final Logger LOG = LoggerFactory.getLogger( + SetDefaultPathPermissionsExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final SecurityControl securityControl = session.feature(SecurityControl.class); + final ScriptBuilder builder = securityControl.scriptBuilder(); + + final Set myPermissions = new HashSet<>(); + myPermissions.add(PathPermission.UPDATE_TOPIC); + myPermissions.add(PathPermission.MODIFY_TOPIC); + + builder.setDefaultPathPermissions("CLIENT", myPermissions); + final String script = builder.script(); + + LOG.info("Updating default permissions"); + securityControl.updateStore(script) + .whenComplete((r, ex) -> LOG.info(script)); + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/SetDefaultRolesForAnonymousSessionsExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/SetDefaultRolesForAnonymousSessionsExample.java new file mode 100644 index 00000000..f1c78c34 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/SetDefaultRolesForAnonymousSessionsExample.java @@ -0,0 +1,57 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.serverconfiguration.securitycontrol; + +import java.util.Collections; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.SecurityControl; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to set default roles for anonymous sessions using + * the security control feature in Diffusion. + *

+ * The example assigns the `AUTHENTICATION_HANDLER` role to all anonymous sessions. + * + * @author DiffusionData Limited + */ +public class SetDefaultRolesForAnonymousSessionsExample { + + private static final Logger LOG = LoggerFactory.getLogger( + SetDefaultRolesForAnonymousSessionsExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final SecurityControl securityControl = session.feature(SecurityControl.class); + final SecurityControl.ScriptBuilder builder = securityControl.scriptBuilder(); + + builder.setRolesForAnonymousSessions(Collections.singleton("AUTHENTICATION_HANDLER")); + + securityControl.updateStore(builder.script()) + .whenComplete((r, ex) -> + LOG.info("All anonymous sessions now have AUTHENTICATION_HANDLER privileges.")); + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/SetDefaultRolesForNamedSessionsExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/SetDefaultRolesForNamedSessionsExample.java new file mode 100644 index 00000000..94c9ba85 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/SetDefaultRolesForNamedSessionsExample.java @@ -0,0 +1,57 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.serverconfiguration.securitycontrol; + +import java.util.Collections; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.SecurityControl; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to set default roles for named sessions using the + * security control feature in Diffusion. + *

+ * The example assigns the `ADMINISTRATOR` role to all named sessions. + * + * @author DiffusionData Limited + */ +public class SetDefaultRolesForNamedSessionsExample { + + private static final Logger LOG = LoggerFactory.getLogger( + SetDefaultRolesForNamedSessionsExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final SecurityControl securityControl = session.feature(SecurityControl.class); + final SecurityControl.ScriptBuilder builder = securityControl.scriptBuilder(); + + builder.setRolesForNamedSessions(Collections.singleton("ADMINISTRATOR")); + + securityControl.updateStore(builder.script()) + .whenComplete((r, ex) -> + LOG.info("All named sessions now have ADMINISTRATOR privileges.")); + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/SetGlobalPermissionsExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/SetGlobalPermissionsExample.java new file mode 100644 index 00000000..617befab --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/SetGlobalPermissionsExample.java @@ -0,0 +1,68 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.serverconfiguration.securitycontrol; + +import java.util.HashSet; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.SecurityControl; +import com.pushtechnology.diffusion.client.features.control.clients.SecurityControl.ScriptBuilder; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.types.GlobalPermission; + +/** + * This example demonstrates how to set global permissions for a role using the + * security control feature in Diffusion. + *

+ * The example assigns the `VIEW_SERVER` and `VIEW_SESSION` global permissions + * to the `CLIENT` role. + * + * @author DiffusionData Limited + */ +public class SetGlobalPermissionsExample { + + private static final Logger LOG = LoggerFactory.getLogger( + SetGlobalPermissionsExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final SecurityControl securityControl = session.feature(SecurityControl.class); + final ScriptBuilder builder = securityControl.scriptBuilder(); + + final Set myPermissions = new HashSet<>(); + myPermissions.add(GlobalPermission.VIEW_SERVER); + myPermissions.add(GlobalPermission.VIEW_SESSION); + + builder.setGlobalPermissions("CLIENT", myPermissions); + final String script = builder.script(); + + LOG.info("Adding the following permissions to the global permissions " + + "of Role CLIENT: VIEW_SERVER and VIEW_SESSION"); + + securityControl.updateStore(script) + .whenComplete((r, ex) -> LOG.info(script)); + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/SetPathPermissionsExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/SetPathPermissionsExample.java new file mode 100644 index 00000000..09f1cff0 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/securitycontrol/SetPathPermissionsExample.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.serverconfiguration.securitycontrol; + +import java.util.HashSet; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.SecurityControl; +import com.pushtechnology.diffusion.client.features.control.clients.SecurityControl.ScriptBuilder; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.types.PathPermission; + +/** + * This example demonstrates how to set path-specific permissions for a role using + * the security control feature in Diffusion. + *

+ * The example grants the `CLIENT` role the `UPDATE_TOPIC` and `MODIFY_TOPIC` + * permissions for the given path. + * + * @author DiffusionData Limited + */ +public class SetPathPermissionsExample { + + private static final Logger LOG = LoggerFactory.getLogger( + SetPathPermissionsExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final SecurityControl securityControl = session.feature(SecurityControl.class); + final ScriptBuilder builder = securityControl.scriptBuilder(); + + final Set myPermissions = new HashSet<>(); + myPermissions.add(PathPermission.UPDATE_TOPIC); + myPermissions.add(PathPermission.MODIFY_TOPIC); + + builder.setPathPermissions("CLIENT", "my/topic/path", myPermissions); + final String script = builder.script(); + + LOG.info("Allowing Role CLIENT to update and modify my/topic/path"); + + securityControl.updateStore(script) + .whenComplete((r, ex) -> LOG.info(script)); + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/AbstainAnonymousConnectionsExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/AbstainAnonymousConnectionsExample.java new file mode 100644 index 00000000..c5b49ccb --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/AbstainAnonymousConnectionsExample.java @@ -0,0 +1,99 @@ +package com.pushtechnology.client.sdk.example.serverconfiguration.systemauthenticationcontrol; + +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.control.clients.AuthenticationControl; +import com.pushtechnology.diffusion.client.features.control.clients.SystemAuthenticationControl; +import com.pushtechnology.diffusion.client.session.AuthenticationException; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.types.Credentials; + +/** + * This example demonstrates how to configure a Diffusion server to abstain from + * handling anonymous connections. + *

+ * The system handler is configured to abstain, allowing a custom authentication + * handler to decide whether to permit anonymous connections. + * + * @author DiffusionData Limited + */ +public class AbstainAnonymousConnectionsExample { + + private static final Logger LOG = + LoggerFactory.getLogger(AbstainAnonymousConnectionsExample.class); + + public static void main(String[] args) { + + final Session adminSession = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final SystemAuthenticationControl adminControl = + adminSession.feature(SystemAuthenticationControl.class); + + final SystemAuthenticationControl.ScriptBuilder builder = + adminControl.scriptBuilder(); + + adminControl.updateStore( + builder + .abstainAnonymousConnections() + .script()) + .join(); + + adminSession.close(); + + final Session controlSession = Diffusion.sessions() + .principal("control") + .password("password") + .open("ws://localhost:8080"); + + controlSession.feature(AuthenticationControl.class) + .setAuthenticationHandler("after-system-handler", new MyAuthenticator(LOG)).join(); + + try { + Diffusion.sessions().open("ws://localhost:8080"); + } + catch (AuthenticationException e) { + LOG.info("Anonymous connection denied: {}", e.getMessage()); + } + + controlSession.close(); + } + + static class MyAuthenticator implements AuthenticationControl.ControlAuthenticator { + + private Logger logger; + + MyAuthenticator(Logger logger) { + this.logger = logger; + } + + + @Override + public void authenticate(String principal, Credentials credentials, + Map sessionProperties, + Map proposedProperties, + Callback callback) { + + if ("".equals(principal)) { + logger.info("denying anonymous connection"); + callback.deny(); + + return; + } + callback.allow(); + } + + @Override + public void onClose() { } + + @Override + public void onError(ErrorReason errorReason) { } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/AddLockedPrincipalExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/AddLockedPrincipalExample.java new file mode 100644 index 00000000..1ddd1a3b --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/AddLockedPrincipalExample.java @@ -0,0 +1,55 @@ +package com.pushtechnology.client.sdk.example.serverconfiguration.systemauthenticationcontrol; + +import java.util.Collections; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.SystemAuthenticationControl; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to add a principal that is locked by another principal. + *

+ * Upon creation the 'super_user' principal is locked by the 'admin' principal. + * + * @author DiffusionData Limited + */ +public class AddLockedPrincipalExample { + + private static final Logger LOG = + LoggerFactory.getLogger(AddLockedPrincipalExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final SystemAuthenticationControl authenticationControl = + session.feature(SystemAuthenticationControl.class); + + final SystemAuthenticationControl.ScriptBuilder builder = + authenticationControl.scriptBuilder(); + + builder.addPrincipal( + "super_user", + "password12345", + Collections.singleton("ADMINISTRATOR"), + "admin"); + + authenticationControl.updateStore(builder.script()).join(); + + final Session superSession = Diffusion.sessions() + .principal("super_user") + .password("password12345") + .open("ws://localhost:8080"); + + LOG.info("connected as {}", superSession.getPrincipal()); + + superSession.close(); + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/AddPrincipalExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/AddPrincipalExample.java new file mode 100644 index 00000000..7b54e599 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/AddPrincipalExample.java @@ -0,0 +1,53 @@ +package com.pushtechnology.client.sdk.example.serverconfiguration.systemauthenticationcontrol; + +import java.util.Collections; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.SystemAuthenticationControl; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to add a principal using the system + * authentication control feature. + * + * @author DiffusionData Limited + */ +public class AddPrincipalExample { + + private static final Logger LOG = + LoggerFactory.getLogger(AddPrincipalExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final SystemAuthenticationControl authenticationControl = + session.feature(SystemAuthenticationControl.class); + + final SystemAuthenticationControl.ScriptBuilder builder = + authenticationControl.scriptBuilder(); + + builder.addPrincipal( + "super_user", + "password12345", + Collections.singleton("ADMINISTRATOR")); + + authenticationControl.updateStore(builder.script()).join(); + + final Session superSession = Diffusion.sessions() + .principal("super_user") + .password("password12345") + .open("ws://localhost:8080"); + + LOG.info("connected as {}", superSession.getPrincipal()); + + superSession.close(); + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/AllowAnonymousConnectionsExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/AllowAnonymousConnectionsExample.java new file mode 100644 index 00000000..8b1f5a4a --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/AllowAnonymousConnectionsExample.java @@ -0,0 +1,50 @@ +package com.pushtechnology.client.sdk.example.serverconfiguration.systemauthenticationcontrol; + +import java.util.Collections; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.SystemAuthenticationControl; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to allow anonymous connections. + *

+ * Anonymous connections are permitted with the 'CLIENT' role. + * + * @author DiffusionData Limited + */ +public class AllowAnonymousConnectionsExample { + + private static final Logger LOG = + LoggerFactory.getLogger(AllowAnonymousConnectionsExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final SystemAuthenticationControl authenticationControl = + session.feature(SystemAuthenticationControl.class); + + final SystemAuthenticationControl.ScriptBuilder builder = + authenticationControl.scriptBuilder(); + + authenticationControl.updateStore( + builder + .allowAnonymousConnections(Collections.singleton("CLIENT")) + .script()) + .join(); + + final Session anonSession = Diffusion.sessions().open("ws://localhost:8080"); + + LOG.info("Anon session state: {}", anonSession.getState()); + + anonSession.close(); + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/AssignRolesExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/AssignRolesExample.java new file mode 100644 index 00000000..3711bf8e --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/AssignRolesExample.java @@ -0,0 +1,60 @@ +package com.pushtechnology.client.sdk.example.serverconfiguration.systemauthenticationcontrol; + +import java.util.Collections; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.SystemAuthenticationControl; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to assign roles to a principal using the system + * authentication control feature. + *

+ * The 'super_user' principal is assigned the 'ADMINISTRATOR' role. + * + * @author DiffusionData Limited + */ +public class AssignRolesExample { + + private static final Logger LOG = + LoggerFactory.getLogger(AssignRolesExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final SystemAuthenticationControl authenticationControl = + session.feature(SystemAuthenticationControl.class); + + String updateScript = authenticationControl.scriptBuilder() + .addPrincipal( + "super_user", + "password12345", + Collections.singleton("CLIENT")) + .script(); + + authenticationControl.updateStore(updateScript).join(); + + updateScript = authenticationControl.scriptBuilder() + .assignRoles("super_user", Collections.singleton("ADMINISTRATOR")) + .script(); + + authenticationControl.updateStore(updateScript).join(); + + final Session superSession = Diffusion.sessions() + .principal("super_user") + .password("password12345") + .open("ws://localhost:8080"); + + LOG.info("connected as {}", superSession.getPrincipal()); + + superSession.close(); + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/ChangePrincipalPasswordExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/ChangePrincipalPasswordExample.java new file mode 100644 index 00000000..1621b2c1 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/ChangePrincipalPasswordExample.java @@ -0,0 +1,58 @@ +package com.pushtechnology.client.sdk.example.serverconfiguration.systemauthenticationcontrol; + +import java.util.Collections; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.SystemAuthenticationControl; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to change the password of a principal using the system + * authentication control feature. + * + * @author DiffusionData Limited + */ +public class ChangePrincipalPasswordExample { + + private static final Logger LOG = + LoggerFactory.getLogger(ChangePrincipalPasswordExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final SystemAuthenticationControl authenticationControl = + session.feature(SystemAuthenticationControl.class); + + String updateScript = authenticationControl.scriptBuilder() + .addPrincipal( + "super_user", + "password12345", + Collections.singleton("CLIENT")) + .script(); + + authenticationControl.updateStore(updateScript).join(); + + updateScript = authenticationControl.scriptBuilder() + .setPassword("super_user", "myNewPassword") + .script(); + + authenticationControl.updateStore(updateScript).join(); + + final Session superSession = Diffusion.sessions() + .principal("super_user") + .password("myNewPassword") + .open("ws://localhost:8080"); + + LOG.info("connected as {}", superSession.getPrincipal()); + + superSession.close(); + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/DenyAnonymousConnectionsExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/DenyAnonymousConnectionsExample.java new file mode 100644 index 00000000..b444ff6c --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/DenyAnonymousConnectionsExample.java @@ -0,0 +1,50 @@ +package com.pushtechnology.client.sdk.example.serverconfiguration.systemauthenticationcontrol; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.SystemAuthenticationControl; +import com.pushtechnology.diffusion.client.session.AuthenticationException; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to deny anonymous connections using the system + * authentication control feature. + * + * @author DiffusionData Limited + */ +public class DenyAnonymousConnectionsExample { + + private static final Logger LOG = + LoggerFactory.getLogger(DenyAnonymousConnectionsExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final SystemAuthenticationControl authenticationControl = + session.feature(SystemAuthenticationControl.class); + + final SystemAuthenticationControl.ScriptBuilder builder = + authenticationControl.scriptBuilder(); + + authenticationControl.updateStore( + builder + .denyAnonymousConnections() + .script()) + .join(); + + try { + Diffusion.sessions().open("ws://localhost:8080"); + } + catch (AuthenticationException e) { + LOG.info("Anonymous connections denied: {}", e.getMessage()); + } + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/IgnoreClientProposedPropertyExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/IgnoreClientProposedPropertyExample.java new file mode 100644 index 00000000..ceeb53db --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/IgnoreClientProposedPropertyExample.java @@ -0,0 +1,74 @@ +package com.pushtechnology.client.sdk.example.serverconfiguration.systemauthenticationcontrol; + +import java.util.Collections; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.ClientControl; +import com.pushtechnology.diffusion.client.features.control.clients.SystemAuthenticationControl; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to configure Diffusion to ignore specified session + * properties proposed by clients. + * + * @author DiffusionData Limited + */ +public class IgnoreClientProposedPropertyExample { + + private static final Logger LOG = + LoggerFactory.getLogger(IgnoreClientProposedPropertyExample.class); + + public static void main(String[] args) { + + final Session adminSession = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final SystemAuthenticationControl authenticationControl = + adminSession.feature(SystemAuthenticationControl.class); + + final String updateScript = authenticationControl.scriptBuilder() + .ignoreClientProposedProperty("Rubble") + .trustClientProposedPropertyMatches("Flintstone", ".*_Flintstone") + .script(); + + authenticationControl.updateStore(updateScript).join(); + + final Session sessionWithAllowedProp = + Diffusion.sessions() + .property("Flintstone", "Fred_Flintstone") + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + Map properties; + + properties = adminSession.feature(ClientControl.class) + .getSessionProperties(sessionWithAllowedProp.getSessionId(), + Collections.singleton("Flintstone")).join(); + + LOG.info("Session properties: {}", properties); + + final Session sessionWithNotAllowedProp = + Diffusion.sessions() + .property("Rubble", "Barney_Rubble") + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + properties = adminSession.feature(ClientControl.class) + .getSessionProperties(sessionWithNotAllowedProp.getSessionId(), + Collections.singleton("Flintstone")).join(); + + LOG.info("Empty properties: {}", properties); + + sessionWithNotAllowedProp.close(); + sessionWithAllowedProp.close(); + adminSession.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/RemovePrincipalExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/RemovePrincipalExample.java new file mode 100644 index 00000000..5e4f12fb --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/RemovePrincipalExample.java @@ -0,0 +1,72 @@ +package com.pushtechnology.client.sdk.example.serverconfiguration.systemauthenticationcontrol; + +import java.util.Collections; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.SystemAuthenticationControl; +import com.pushtechnology.diffusion.client.session.AuthenticationException; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to remove a principal using the system + * authentication control feature. + * + * @author DiffusionData Limited + */ +public class RemovePrincipalExample { + + private static final Logger LOG = + LoggerFactory.getLogger(RemovePrincipalExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final SystemAuthenticationControl authenticationControl = + session.feature(SystemAuthenticationControl.class); + + final SystemAuthenticationControl.ScriptBuilder builder = + authenticationControl.scriptBuilder(); + + builder.addPrincipal( + "super_user", + "password12345", + Collections.singleton("ADMINISTRATOR")); + + authenticationControl.updateStore(builder.script()).join(); + + final Session superSession = Diffusion.sessions() + .principal("super_user") + .password("password12345") + .open("ws://localhost:8080"); + + LOG.info("connected as {}", superSession.getPrincipal()); + + superSession.close(); + + final SystemAuthenticationControl.ScriptBuilder newBuilder = + authenticationControl.scriptBuilder(); + + newBuilder.removePrincipal("super_user"); + + authenticationControl.updateStore(newBuilder.script()).join(); + + try { + Diffusion.sessions() + .principal("super_user") + .password("password12345") + .open("ws://localhost:8080"); + } + catch (AuthenticationException e) { + LOG.info("connection failed: {}", e.getMessage()); + } + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/TrustClientProposedPropertyInExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/TrustClientProposedPropertyInExample.java new file mode 100644 index 00000000..5f1f1f72 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/TrustClientProposedPropertyInExample.java @@ -0,0 +1,80 @@ +package com.pushtechnology.client.sdk.example.serverconfiguration.systemauthenticationcontrol; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.ClientControl; +import com.pushtechnology.diffusion.client.features.control.clients.SystemAuthenticationControl; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to allow a proposed session property only if + * its value matches a set of allowed values. + * + * @author DiffusionData Limited + */ +public class TrustClientProposedPropertyInExample { + + private static final Logger LOG = + LoggerFactory.getLogger(TrustClientProposedPropertyInExample.class); + + public static void main(String[] args) { + + final Session adminSession = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final SystemAuthenticationControl authenticationControl = + adminSession.feature(SystemAuthenticationControl.class); + + final Set allowedValues = new HashSet<>(); + allowedValues.add("Fred"); + allowedValues.add("Wilma"); + allowedValues.add("Pebbles"); + + final String updateScript = authenticationControl.scriptBuilder() + .trustClientProposedPropertyIn("Flintstone", allowedValues) + .script(); + + authenticationControl.updateStore(updateScript).join(); + + final Session sessionWithAllowedProp = + Diffusion.sessions() + .property("Flintstone", "Fred") + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + Map properties; + + properties = adminSession.feature(ClientControl.class) + .getSessionProperties(sessionWithAllowedProp.getSessionId(), + Collections.singleton("Flintstone")).join(); + + LOG.info("Session properties: {}", properties); + + final Session sessionWithNotAllowedProp = + Diffusion.sessions() + .property("Flintstone", "Barney") + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + properties = adminSession.feature(ClientControl.class) + .getSessionProperties(sessionWithNotAllowedProp.getSessionId(), + Collections.singleton("Flintstone")).join(); + + LOG.info("Empty properties: {}", properties); + + sessionWithNotAllowedProp.close(); + sessionWithAllowedProp.close(); + adminSession.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/TrustClientProposedPropertyMatchesExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/TrustClientProposedPropertyMatchesExample.java new file mode 100644 index 00000000..a02ac565 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/TrustClientProposedPropertyMatchesExample.java @@ -0,0 +1,73 @@ +package com.pushtechnology.client.sdk.example.serverconfiguration.systemauthenticationcontrol; + +import java.util.Collections; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.ClientControl; +import com.pushtechnology.diffusion.client.features.control.clients.SystemAuthenticationControl; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to trust a proposed session property only if + * its value matches a specified regular expression. + * + * @author DiffusionData Limited + */ +public class TrustClientProposedPropertyMatchesExample { + + private static final Logger LOG = + LoggerFactory.getLogger(TrustClientProposedPropertyMatchesExample.class); + + public static void main(String[] args) { + + final Session adminSession = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final SystemAuthenticationControl authenticationControl = + adminSession.feature(SystemAuthenticationControl.class); + + final String updateScript = authenticationControl.scriptBuilder() + .trustClientProposedPropertyMatches("name", ".*_Flintstone") + .script(); + + authenticationControl.updateStore(updateScript).join(); + + final Session sessionWithAllowedProp = + Diffusion.sessions() + .property("name", "Fred_Flintstone") + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + Map properties; + + properties = adminSession.feature(ClientControl.class) + .getSessionProperties(sessionWithAllowedProp.getSessionId(), + Collections.singleton("name")).join(); + + LOG.info("Session properties: {}", properties); + + final Session sessionWithNotAllowedProp = + Diffusion.sessions() + .property("name", "Barney_Rubble") + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + properties = adminSession.feature(ClientControl.class) + .getSessionProperties(sessionWithNotAllowedProp.getSessionId(), + Collections.singleton("name")).join(); + + LOG.info("Empty properties: {}", properties); + + sessionWithNotAllowedProp.close(); + sessionWithAllowedProp.close(); + adminSession.close(); + } +} \ No newline at end of file diff --git a/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/VerifyPrincipalPasswordExample.java b/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/VerifyPrincipalPasswordExample.java new file mode 100644 index 00000000..d83c58d5 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/serverconfiguration/systemauthenticationcontrol/VerifyPrincipalPasswordExample.java @@ -0,0 +1,73 @@ +package com.pushtechnology.client.sdk.example.serverconfiguration.systemauthenticationcontrol; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.SystemAuthenticationControl; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to verify the password for a principal. + *

+ * The `verifyPassword` method is used to ensure the current password for the + * principal is correct before updating it. + * + * @author DiffusionData Limited + */ +public class VerifyPrincipalPasswordExample { + + private static final Logger LOG = + LoggerFactory.getLogger(VerifyPrincipalPasswordExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final SystemAuthenticationControl authenticationControl = + session.feature(SystemAuthenticationControl.class); + + String updateScript = authenticationControl.scriptBuilder() + .verifyPassword("control", "password") + .setPassword("control", "12345") + .script(); + + authenticationControl.updateStore(updateScript).join(); + + final Session controlSession = Diffusion.sessions() + .principal("control") + .password("12345") + .open("ws://localhost:8080"); + + LOG.info("connected as {}", controlSession.getPrincipal()); + + controlSession.close(); + + updateScript = authenticationControl.scriptBuilder() + .verifyPassword("control", "this_is_not_the_right_password") + .setPassword("control", "new_password") + .script(); + + try { + authenticationControl.updateStore(updateScript).join(); + } + catch (Exception e) { + LOG.info("Password was not updated: {}", e.getMessage()); + } + + try { + Diffusion.sessions() + .principal("control") + .password("new_password") + .open("ws://localhost:8080"); + } + catch (Exception e) { + LOG.info("Authentication failed: {}", e.getMessage()); + } + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/sessionmanagement/authenticationcontrol/AuthenticationControlExample.java b/java/com/pushtechnology/client/sdk/example/sessionmanagement/authenticationcontrol/AuthenticationControlExample.java new file mode 100644 index 00000000..147aaa50 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/sessionmanagement/authenticationcontrol/AuthenticationControlExample.java @@ -0,0 +1,119 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.sessionmanagement.authenticationcontrol; + +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.control.clients.AuthenticationControl; +import com.pushtechnology.diffusion.client.features.control.clients.AuthenticationControl.ControlAuthenticator; +import com.pushtechnology.diffusion.client.session.AuthenticationException; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.session.SessionFactory; +import com.pushtechnology.diffusion.client.types.Credentials; + +/** + * This example demonstrates how to implement and use a custom authentication handler. + *

+ * The custom authenticator defines rules for accepting or rejecting session + * establishment based on the principal. + *

+ * Anonymous connections and connections with principals not starting with a + * specific prefix are rejected, while others are allowed. + * + * @author DiffusionData Limited + */ +public class AuthenticationControlExample { + + private static final Logger LOG = + LoggerFactory.getLogger(AuthenticationControlExample.class); + + public static void main(String[] args) { + + final SessionFactory sessions = Diffusion.sessions(); + + final Session controlSession = sessions + .principal("control") + .password("password") + .open("ws://localhost:8080"); + + controlSession.feature(AuthenticationControl.class) + .setAuthenticationHandler("before-system-handler", new MyAuthenticator()).join(); + + try { + sessions.principal("").open("ws://localhost:8080"); + } + catch (AuthenticationException e) { + System.out.println("This should fail"); + LOG.info(e.getMessage()); + } + + try { + sessions.principal("client").password("password") + .open("ws://localhost:8080"); + } + catch (AuthenticationException e) { + System.out.println("This should also fail"); + LOG.info(e.getMessage()); + } + + final Session session = sessions + .principal("diffusion_client") + .password("password") + .open("ws://localhost:8080"); + + System.out.println("Connected as: " + session.getPrincipal()); + + session.close(); + controlSession.close(); + + LOG.info(session.getState().toString()); + } + + private static final class MyAuthenticator implements ControlAuthenticator { + + @Override + public void authenticate(String principal, Credentials credentials, + Map sessionProperties, + Map proposedProperties, + Callback callback) { + + if ("".equals(principal)) { + System.out.println("Anonymous connection attempt detected. Session establishment Rejected."); + callback.deny(); + return; + } + + if (!principal.startsWith("diffusion_")) { + System.out.println("Principal does not begin with diffusion_ prefix. Session establishment Rejected."); + callback.deny(); + return; + } + + System.out.println("Principal begins with diffusion_ prefix. Session establishment Accepted."); + callback.allow(); + } + + @Override + public void onClose() { } + + @Override + public void onError(ErrorReason errorReason) { } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/ChangeRolesViaSessionFilterExample.java b/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/ChangeRolesViaSessionFilterExample.java new file mode 100644 index 00000000..50d9cb58 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/ChangeRolesViaSessionFilterExample.java @@ -0,0 +1,85 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.sessionmanagement.clientcontrol; + +import java.util.Collections; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.ClientControl; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to change the roles of multiple sessions + * using a session filter. + *

+ * The example uses the filter "$Principal is 'client'" to ensure the change + * only applies to 'client' sessions. + * + * @author DiffusionData Limited + */ +public class ChangeRolesViaSessionFilterExample { + + private static final Logger LOG = + LoggerFactory.getLogger(ChangeRolesViaSessionFilterExample.class); + + public static void main(String[] args) { + + final Session adminSession = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Session clientSession1 = Diffusion.sessions() + .principal("client") + .password("password") + .open("ws://localhost:8080"); + + final Session clientSession2 = Diffusion.sessions() + .principal("client") + .password("password") + .open("ws://localhost:8080"); + + final ClientControl clientControl = adminSession.feature(ClientControl.class); + + Map sessionProperties = clientControl.getSessionProperties( + clientSession1.getSessionId(), + Collections.singletonList(Session.ROLES)).join(); + + LOG.info("roles: {}", sessionProperties.get(Session.ROLES)); + + final Integer result = clientControl + .changeRoles( + "$Principal is 'client'", + Collections.emptySet(), + Collections.singleton("TOPIC_CONTROL")) + .join(); + + LOG.info("Updated {} session(s)\n", result); + + sessionProperties = clientControl.getSessionProperties( + clientSession1.getSessionId(), + Collections.singletonList(Session.ROLES)).join(); + + LOG.info("roles: {}", sessionProperties.get(Session.ROLES)); + + adminSession.close(); + clientSession1.close(); + clientSession2.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/ChangeRolesViaSessionIdExample.java b/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/ChangeRolesViaSessionIdExample.java new file mode 100644 index 00000000..4d34713e --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/ChangeRolesViaSessionIdExample.java @@ -0,0 +1,74 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.sessionmanagement.clientcontrol; + +import java.util.Collections; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.ClientControl; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to change the roles of a session + * using its ID. + * + * @author DiffusionData Limited + */ +public class ChangeRolesViaSessionIdExample { + + private static final Logger LOG = + LoggerFactory.getLogger(ChangeRolesViaSessionIdExample.class); + + public static void main(String[] args) throws Exception { + + final Session adminSession = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Session clientSession = Diffusion.sessions() + .principal("client") + .password("password") + .open("ws://localhost:8080"); + + final ClientControl clientControl = adminSession.feature(ClientControl.class); + + Map sessionProperties = clientControl.getSessionProperties( + clientSession.getSessionId(), + Collections.singletonList(Session.ROLES)).join(); + + LOG.info("roles: {}", sessionProperties.get(Session.ROLES)); + + adminSession.feature(ClientControl.class) + .changeRoles( + clientSession.getSessionId(), + Collections.emptySet(), + Collections.singleton("TOPIC_CONTROL")).join(); + + + sessionProperties = clientControl.getSessionProperties( + clientSession.getSessionId(), + Collections.singletonList(Session.ROLES)).join(); + + LOG.info("roles: {}", sessionProperties.get(Session.ROLES)); + + adminSession.close(); + clientSession.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/CloseClientViaSessionFilterExample.java b/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/CloseClientViaSessionFilterExample.java new file mode 100644 index 00000000..54b9247f --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/CloseClientViaSessionFilterExample.java @@ -0,0 +1,68 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.sessionmanagement.clientcontrol; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.ClientControl; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to close multiple sessions using a session + * filter. + *

+ * The example uses the filter "$Principal is 'client'" to ensure the operation + * only applies to 'client' sessions. + * + * @author DiffusionData Limited + */ +public class CloseClientViaSessionFilterExample { + + private static final Logger LOG = + LoggerFactory.getLogger(CloseClientViaSessionFilterExample.class); + + public static void main(String[] args) throws Exception { + + final Session adminSession = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Session clientSession1 = Diffusion.sessions() + .principal("client") + .password("password") + .open("ws://localhost:8080"); + + final Session clientSession2 = Diffusion.sessions() + .principal("client") + .password("password") + .open("ws://localhost:8080"); + + final ClientControl clientControl = adminSession.feature(ClientControl.class); + + clientControl.close("$Principal is 'client'").join(); + + SECONDS.sleep(1); + + LOG.info("Client session 1 state: {}", clientSession1.getState()); + LOG.info("Client session 2 state: {}", clientSession2.getState()); + + adminSession.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/CloseClientViaSessionIdExample.java b/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/CloseClientViaSessionIdExample.java new file mode 100644 index 00000000..0912f187 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/CloseClientViaSessionIdExample.java @@ -0,0 +1,55 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.sessionmanagement.clientcontrol; + +import static java.util.concurrent.TimeUnit.MILLISECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.ClientControl; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to close a session using its ID. + * + * @author DiffusionData Limited + */ +public class CloseClientViaSessionIdExample { + + private static final Logger LOG = LoggerFactory.getLogger( + CloseClientViaSessionIdExample.class); + + public static void main(String[] args) throws Exception { + + final Session adminSession = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Session clientSession = Diffusion.sessions() + .principal("client") + .password("password") + .open("ws://localhost:8080"); + + final ClientControl clientControl = adminSession.feature(ClientControl.class); + clientControl.close(clientSession.getSessionId()).join(); + MILLISECONDS.sleep(500); + + LOG.info("Client session state: {}", clientSession.getState()); + adminSession.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/GetSessionPropertiesViaSessionIdExample.java b/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/GetSessionPropertiesViaSessionIdExample.java new file mode 100644 index 00000000..883be9c6 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/GetSessionPropertiesViaSessionIdExample.java @@ -0,0 +1,65 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.sessionmanagement.clientcontrol; + +import java.util.Collection; +import java.util.Collections; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.ClientControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.session.SessionId; + +/** + * This example demonstrates how to get a sessions properties using its ID. + * + * @author DiffusionData Limited + */ +public class GetSessionPropertiesViaSessionIdExample { + + private static final Logger LOG = LoggerFactory.getLogger( + GetSessionPropertiesViaSessionIdExample.class); + + public static void main(String[] args) throws Exception { + + final Session adminSession = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Session clientSession = Diffusion.sessions() + .principal("client") + .password("password") + .open("ws://localhost:8080"); + + final SessionId clientSessionID = clientSession.getSessionId(); + final Collection requiredProperties = Collections.singleton(Session.ALL_FIXED_PROPERTIES); + final ClientControl clientControl = adminSession.feature(ClientControl.class); + + final Map sessionProperties = clientControl + .getSessionProperties(clientSessionID, requiredProperties).join(); + + sessionProperties.forEach((key, value) -> System.out.printf(" <%s> : <%s>\n", key, value)); + + adminSession.close(); + clientSession.close(); + + LOG.info("Received session properties for {}.", clientSessionID); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/QueueConflationViaSessionFilterExample.java b/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/QueueConflationViaSessionFilterExample.java new file mode 100644 index 00000000..c3389af3 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/QueueConflationViaSessionFilterExample.java @@ -0,0 +1,59 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.sessionmanagement.clientcontrol; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.ClientControl; +import com.pushtechnology.diffusion.client.features.control.clients.ClientControl.SessionFilterOperationResult; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to set queue conflation for multiple sessions + * using a session filter. + *

+ * The example uses the filter "$Principal is 'client'" to ensure the change + * only applies to 'client' sessions. + * + * @author DiffusionData Limited + */ +public class QueueConflationViaSessionFilterExample { + + private static final Logger LOG = LoggerFactory.getLogger( + QueueConflationViaSessionFilterExample.class); + + public static void main(String[] args) throws Exception { + + final Session adminSession = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Session clientSession = Diffusion.sessions() + .principal("client") + .password("password") + .open("ws://localhost:8080"); + + final SessionFilterOperationResult result = adminSession.feature(ClientControl.class) + .setConflated("$Principal is 'client'", false).join(); + + LOG.info("Sessions updated: {}", result.selected()); + + adminSession.close(); + clientSession.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/QueueConflationViaSessionIdExample.java b/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/QueueConflationViaSessionIdExample.java new file mode 100644 index 00000000..15e78673 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/QueueConflationViaSessionIdExample.java @@ -0,0 +1,58 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.sessionmanagement.clientcontrol; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.ClientControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.session.SessionId; + +/** + * This example demonstrates how to set queue conflation for a session + * using its ID. + * + * @author DiffusionData Limited + */ +public class QueueConflationViaSessionIdExample { + + private static final Logger LOG = LoggerFactory.getLogger( + QueueConflationViaSessionIdExample.class); + + public static void main(String[] args) throws Exception { + + final Session adminSession = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Session clientSession = Diffusion.sessions() + .principal("client") + .password("password") + .open("ws://localhost:8080"); + + final SessionId clientSessionID = clientSession.getSessionId(); + + final ClientControl clientControl = adminSession.feature(ClientControl.class); + clientControl.setConflated(clientSessionID, false).join(); + + LOG.info("Queue conflation configured for session {}.", clientSessionID); + + adminSession.close(); + clientSession.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/SetSessionPropertiesViaFilterExample.java b/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/SetSessionPropertiesViaFilterExample.java new file mode 100644 index 00000000..eaceaa93 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/SetSessionPropertiesViaFilterExample.java @@ -0,0 +1,80 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.sessionmanagement.clientcontrol; + +import java.util.Collections; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.ClientControl; +import com.pushtechnology.diffusion.client.features.control.clients.ClientControl.SessionFilterOperationResult; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to set session properties for multiple sessions + * using a session filter. + *

+ * The example uses the filter "$Principal is 'client'" to ensure the change + * only applies to 'client' sessions. + * + * @author DiffusionData Limited + */ +public class SetSessionPropertiesViaFilterExample { + private static final Logger LOG = LoggerFactory.getLogger( + SetSessionPropertiesViaFilterExample.class); + + public static void main(String[] args) throws Exception { + + final Session adminSession = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Session clientSession = Diffusion.sessions() + .principal("client") + .password("password") + .open("ws://localhost:8080"); + + final ClientControl clientControl = adminSession.feature(ClientControl.class); + + Map sessionProperties = clientControl + .getSessionProperties(clientSession.getSessionId(), + Collections.singleton(Session.ALL_FIXED_PROPERTIES)).join(); + + sessionProperties.forEach((key, value) -> System.out.printf(" <%s> : <%s>\n", key, value)); + + final Map myProperties = Collections.singletonMap("$Country", "CA"); + + final SessionFilterOperationResult result = clientControl + .setSessionProperties("$Principal is 'client'", myProperties) + .join(); + + System.out.printf("Updated %s session(s)\n", result.selected()); + + sessionProperties = clientControl + .getSessionProperties(clientSession.getSessionId(), + Collections.singleton(Session.ALL_FIXED_PROPERTIES)).join(); + + sessionProperties.forEach((key, value) -> System.out.printf(" <%s> : <%s>\n", key, value)); + + adminSession.close(); + clientSession.close(); + + LOG.info("Updated {} session(s)", result.selected()); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/SetSessionPropertiesViaSessionIdExample.java b/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/SetSessionPropertiesViaSessionIdExample.java new file mode 100644 index 00000000..cb791921 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/sessionmanagement/clientcontrol/SetSessionPropertiesViaSessionIdExample.java @@ -0,0 +1,75 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.sessionmanagement.clientcontrol; + +import java.util.Collections; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.clients.ClientControl; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to set a sessions properties using its ID. + * + * @author DiffusionData Limited + */ +public class SetSessionPropertiesViaSessionIdExample { + + private static final Logger LOG = LoggerFactory.getLogger( + SetSessionPropertiesViaSessionIdExample.class); + + public static void main(String[] args) { + + final Session adminSession = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Session clientSession = Diffusion.sessions() + .principal("client") + .password("password") + .open("ws://localhost:8080"); + + final ClientControl clientControl = adminSession.feature(ClientControl.class); + + Map sessionProperties = clientControl + .getSessionProperties(clientSession.getSessionId(), + Collections.singleton(Session.ALL_FIXED_PROPERTIES)).join(); + + sessionProperties.forEach((key, value) -> System.out.printf(" <%s> : <%s>\n", key, value)); + + final Map myProperties = Collections.singletonMap("$Country", "CA"); + + final Map result = clientControl + .setSessionProperties(clientSession.getSessionId(), myProperties).join(); + + System.out.printf("Properties changed: %d", result.size()); + + sessionProperties = clientControl + .getSessionProperties(clientSession.getSessionId(), + Collections.singleton(Session.ALL_FIXED_PROPERTIES)).join(); + + sessionProperties.forEach((key, value) -> System.out.printf(" <%s> : <%s>\n", key, value)); + + adminSession.close(); + clientSession.close(); + + LOG.info("Properties changed: {}", result.size()); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/sessionmanagement/subscriptioncontrol/SubscriptionControlExample.java b/java/com/pushtechnology/client/sdk/example/sessionmanagement/subscriptioncontrol/SubscriptionControlExample.java new file mode 100644 index 00000000..f2f576f6 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/sessionmanagement/subscriptioncontrol/SubscriptionControlExample.java @@ -0,0 +1,148 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.sessionmanagement.subscriptioncontrol; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.TopicUpdate; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.clients.ClientControl; +import com.pushtechnology.diffusion.client.features.control.clients.ClientControl.SessionEventParameters; +import com.pushtechnology.diffusion.client.features.control.topics.SubscriptionControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.session.SessionId; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; + +/** + * This example demonstrates how to manage subscriptions for client sessions. + *

+ * The example listens for new client sessions, subscribes them to a topic upon connection, + * and unsubscribes them after a delay. + * + * @author DiffusionData Limited + */ +public class SubscriptionControlExample { + + private static final Logger LOG = + LoggerFactory.getLogger(SubscriptionControlExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final ClientControl clientControl = session.feature(ClientControl.class); + final TopicUpdate topicUpdate = session.feature(TopicUpdate.class); + + topicUpdate.addAndSet( + "my/topic/path/hello", + Diffusion.newTopicSpecification(TopicType.STRING), + String.class, + "Hello World!"); + + clientControl.addSessionEventListener(new MyEventStream(session), + SessionEventParameters.DEFAULT); + + final Session clientSession = Diffusion.sessions() + .principal("client") + .password("password") + .open("ws://localhost:8080"); + + clientSession.feature(Topics.class) + .addFallbackStream(String.class, new MyFallbackStream()); + + session.close(); + clientSession.close(); + + LOG.info("created client subscription"); + } + + static class MyEventStream implements ClientControl.SessionEventStream { + + private final Session controlSession; + private final SessionId callerId; + + MyEventStream(Session controlSession) { + this.controlSession = controlSession; + callerId = controlSession.getSessionId(); + } + + @Override + public void onSessionEvent(Event event) { + if (event.isOpenEvent()) { + final SessionId sessionId = event.sessionId(); + + // if this is not the calling session, subscribe and unsubscribe it + if (!callerId.equals(sessionId)) { + controlSession.feature(SubscriptionControl.class) + .subscribe(sessionId, "?my/topic/path//"); + + try { + Thread.sleep(5000); + } + catch (InterruptedException ex) { + ex.printStackTrace(); + } + controlSession.feature(SubscriptionControl.class) + .unsubscribe(sessionId, "?my/topic/path//"); + } + } + } + + @Override + public void onClose() { + System.out.println("Stream closed"); + } + + @Override + public void onError(ErrorReason errorReason) { + System.out.println("On error: " + errorReason.toString()); + } + } + + private static final class MyFallbackStream implements Topics.ValueStream { + + @Override + public void onValue(String topicPath, + TopicSpecification topicSpecification, String oldValue, String newValue) { + System.out.printf("%s : %s\n", topicPath, newValue); + } + + @Override + public void onSubscription(String topicPath, + TopicSpecification topicSpecification) { + System.out.printf("Subscribed to %s\n", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + System.out.printf("Unsubscribed to %s: %s\n", topicPath, unsubscribeReason); + } + + @Override + public void onClose() { } + + @Override + public void onError(ErrorReason errorReason) { } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/sessiontrees/SessionTreesGetBranchMappingTableExample.java b/java/com/pushtechnology/client/sdk/example/sessiontrees/SessionTreesGetBranchMappingTableExample.java new file mode 100644 index 00000000..de6ba882 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/sessiontrees/SessionTreesGetBranchMappingTableExample.java @@ -0,0 +1,78 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.sessiontrees; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.topics.SessionTrees; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to retrieve session tree branch mapping tables in Diffusion. + *

+ * The example first creates and applies two branch mapping tables, then lists all session tree + * branches with mappings and retrieves the corresponding mapping tables. + * + * @author DiffusionData Limited + */ +public class SessionTreesGetBranchMappingTableExample { + + private static final Logger LOG = + LoggerFactory.getLogger(SessionTreesGetBranchMappingTableExample.class); + + public static void main(String[] args) { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final SessionTrees.BranchMappingTable branchMappingTable1 = Diffusion.newBranchMappingTableBuilder() + .addBranchMapping("$Principal is 'admin'", "my/topic/path/for/admin") + .addBranchMapping("$Principal is 'control'", "my/topic/path/for/control") + .addBranchMapping("$Principal is ''", "my/topic/path/for/anonymous") + .create("my/personal/path"); + + final SessionTrees sessionTrees = session.feature(SessionTrees.class); + + sessionTrees.putBranchMappingTable(branchMappingTable1) + .join(); + + final SessionTrees.BranchMappingTable branchMappingTable2 = Diffusion.newBranchMappingTableBuilder() + .addBranchMapping("$Transport is 'WEBSOCKET'", "my/alternate/path/for/websocket") + .addBranchMapping("$Transport is 'HTTP_LONG_POLL'", "my/alternate/path/for/http") + .addBranchMapping("$Transport is 'TCP'", "my/alternate/path/for/tcp") + .create("my/alternate/path"); + + sessionTrees.putBranchMappingTable(branchMappingTable2) + .join(); + + LOG.info("Session tree mappings added."); + + sessionTrees.listSessionTreeBranchesWithMappings() + .join() + .forEach(sessionTreeBranch -> { + LOG.info("{}:", sessionTreeBranch); + + sessionTrees.getBranchMappingTable(sessionTreeBranch) + .join().getBranchMappings() + .forEach(branchMapping -> LOG.info(" {}: {}", + branchMapping.getSessionFilter(), branchMapping.getTopicTreeBranch())); + }); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/sessiontrees/SessionTreesListSessionTreeBranchesWithMappingsExample.java b/java/com/pushtechnology/client/sdk/example/sessiontrees/SessionTreesListSessionTreeBranchesWithMappingsExample.java new file mode 100644 index 00000000..1589a3e2 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/sessiontrees/SessionTreesListSessionTreeBranchesWithMappingsExample.java @@ -0,0 +1,68 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.sessiontrees; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.topics.SessionTrees; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to list session tree branches with mappings in Diffusion. + * + * @author DiffusionData Limited + */ +public class SessionTreesListSessionTreeBranchesWithMappingsExample { + + private static final Logger LOG = + LoggerFactory.getLogger(SessionTreesListSessionTreeBranchesWithMappingsExample.class); + + public static void main(String[] args) { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final SessionTrees sessionTrees = session.feature(SessionTrees.class); + + final SessionTrees.BranchMappingTable branchMappingTable = Diffusion.newBranchMappingTableBuilder() + .addBranchMapping("$Principal is 'admin'", "my/topic/path/for/admin") + .addBranchMapping("$Principal is 'control'", "my/topic/path/for/control") + .addBranchMapping("$Principal is ''", "my/topic/path/for/anonymous") + .create("my/personal/path"); + + sessionTrees.putBranchMappingTable(branchMappingTable) + .join(); + + final SessionTrees.BranchMappingTable branchMappingTable2 = Diffusion.newBranchMappingTableBuilder() + .addBranchMapping("$Transport is 'WEBSOCKET'", "my/alternate/path/for/websocket") + .addBranchMapping("$Transport is 'HTTP_LONG_POLL'", "my/alternate/path/for/http") + .addBranchMapping("$Transport is 'TCP'", "my/alternate/path/for/tcp") + .create("my/alternate/path"); + + sessionTrees.putBranchMappingTable(branchMappingTable2) + .join(); + + LOG.info("Session tree mappings added."); + + sessionTrees.listSessionTreeBranchesWithMappings() + .join() + .forEach(sessionTreeBranch -> LOG.info("{}:", sessionTreeBranch)); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/sessiontrees/SessionTreesPutAndRemoveBranchMappingTableExample.java b/java/com/pushtechnology/client/sdk/example/sessiontrees/SessionTreesPutAndRemoveBranchMappingTableExample.java new file mode 100644 index 00000000..69ec6144 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/sessiontrees/SessionTreesPutAndRemoveBranchMappingTableExample.java @@ -0,0 +1,66 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.sessiontrees; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.topics.SessionTrees; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to add and remove a session tree branch mapping table in Diffusion. + *

+ * The branch mapping table is first created and applied, then later replaced with an empty table + * to remove all mappings. + * + * @author DiffusionData Limited + */ +public class SessionTreesPutAndRemoveBranchMappingTableExample { + + private static final Logger LOG = + LoggerFactory.getLogger(SessionTreesPutAndRemoveBranchMappingTableExample.class); + + public static void main(String[] args) { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final String s = "my/personal/path"; + + final SessionTrees.BranchMappingTable branchMappingTable = Diffusion.newBranchMappingTableBuilder() + .addBranchMapping("$Principal is 'admin'", "my/topic/path/for/admin") + .addBranchMapping("$Principal is 'control'", "my/topic/path/for/control") + .addBranchMapping("$Principal is ''", "my/topic/path/for/anonymous") + .create(s); + + final SessionTrees sessionTrees = session.feature(SessionTrees.class); + + sessionTrees.putBranchMappingTable(branchMappingTable) + .join(); + + LOG.info("Session tree mappings added."); + + sessionTrees.putBranchMappingTable(Diffusion.newBranchMappingTableBuilder() + .create(s)) + .join(); + + LOG.info("Session tree mappings removed."); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/sessiontrees/SessionTreesPutBranchMappingTableExample.java b/java/com/pushtechnology/client/sdk/example/sessiontrees/SessionTreesPutBranchMappingTableExample.java new file mode 100644 index 00000000..230343d7 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/sessiontrees/SessionTreesPutBranchMappingTableExample.java @@ -0,0 +1,55 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.sessiontrees; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.topics.SessionTrees; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to define and create a session tree branch mapping table in Diffusion. + *

+ * The branch mapping table routes clients to different topic paths based on their session principal. + * + * @author DiffusionData Limited + */ +public class SessionTreesPutBranchMappingTableExample { + + private static final Logger LOG = + LoggerFactory.getLogger(SessionTreesPutBranchMappingTableExample.class); + + public static void main(String[] args) { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final SessionTrees.BranchMappingTable branchMappingTable = Diffusion.newBranchMappingTableBuilder() + .addBranchMapping("$Principal is 'admin'", "my/topic/path/for/admin") + .addBranchMapping("$Principal is 'control'", "my/topic/path/for/control") + .addBranchMapping("$Principal is ''", "my/topic/path/for/anonymous") + .create("my/personal/path"); + + session.feature(SessionTrees.class).putBranchMappingTable(branchMappingTable) + .join(); + + LOG.info("Session tree mappings added."); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/sessiontrees/SessionTreesUseCaseExample.java b/java/com/pushtechnology/client/sdk/example/sessiontrees/SessionTreesUseCaseExample.java new file mode 100644 index 00000000..b27bfd05 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/sessiontrees/SessionTreesUseCaseExample.java @@ -0,0 +1,157 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.sessiontrees; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.SessionTrees; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; + +/** + * This example demonstrates how to use session trees in Diffusion to map topics based on + * client session properties. + *

+ * It creates topic branches for different principals (`admin`, `control`, and `anonymous`) + * and maps them to a session tree path. + * Sessions subscribing to `my/personal/path` receive updates based on their principal. + * + * @author DiffusionData Limited + */ +public class SessionTreesUseCaseExample { + + private static final Logger LOG = + LoggerFactory.getLogger(SessionTreesUseCaseExample.class); + + public static void main(String[] args) { + + try (Session adminSession = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final Topics topicsAdminSession = adminSession.feature(Topics.class); + final TopicSpecification topicSpecification = Diffusion.newTopicSpecification(TopicType.STRING); + + topicsAdminSession.addAndSet("my/topic/path/for/admin", topicSpecification, + String.class, "Good morning Administrator") + .join(); + + topicsAdminSession.addAndSet("my/topic/path/for/control", topicSpecification, + String.class, "Good afternoon Control Client") + .join(); + + topicsAdminSession.addAndSet("my/topic/path/for/anonymous", topicSpecification, + String.class, "Good night Anonymous") + .join(); + + final SessionTrees.BranchMappingTable branchMappingTable = Diffusion.newBranchMappingTableBuilder() + .addBranchMapping("$Principal is 'admin'", "my/topic/path/for/admin") + .addBranchMapping("$Principal is 'control'", "my/topic/path/for/control") + .addBranchMapping("$Principal is ''", "my/topic/path/for/anonymous") + .create("my/personal/path"); + + adminSession.feature(SessionTrees.class).putBranchMappingTable(branchMappingTable) + .join(); + + LOG.info("Session tree mappings added."); + + final MyLoggingStringStream myLoggingStringStreamAdminSession = + new MyLoggingStringStream(adminSession.getPrincipal()); + + topicsAdminSession.addStream(">my/personal/path", String.class, myLoggingStringStreamAdminSession); + topicsAdminSession.subscribe(">my/personal/path") + .join(); + + final Session anonymousSession = Diffusion.sessions() + .principal("").open("ws://localhost:8080"); + + final Topics topicsAnonymousSession = anonymousSession.feature(Topics.class); + + final MyLoggingStringStream myLoggingStringStreamAnonymousSession = + new MyLoggingStringStream(anonymousSession.getPrincipal()); + + topicsAnonymousSession.addStream(">my/personal/path", String.class, myLoggingStringStreamAnonymousSession); + topicsAnonymousSession.subscribe(">my/personal/path") + .join(); + + topicsAdminSession.removeStream(myLoggingStringStreamAdminSession); + topicsAnonymousSession.removeStream(myLoggingStringStreamAnonymousSession); + + topicsAdminSession.listSessionTreeBranchesWithMappings() + .join() + .forEach(sessionTreeBranch -> { + LOG.info("{}:", sessionTreeBranch); + }); + + adminSession.close(); + anonymousSession.close(); + } + } + + public static class MyLoggingStringStream implements Topics.ValueStream { + private static final Logger LOG = LoggerFactory.getLogger(MyLoggingStringStream.class); + + private final String principal; + + public MyLoggingStringStream(String principal) { + this.principal = principal; + } + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + String oldValue, + String newValue) { + + LOG.info("Principal: '{}' - '{}' changed from '{}' to '{}}'.", + principal, topicPath, oldValue, newValue); + } + + @Override + public void onSubscription( + String topicPath, + TopicSpecification topicSpecification) { + + LOG.info("Principal: '{}' - subscribed to: '{}'.", principal, topicPath); + } + + @Override + public void onUnsubscription( + String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + + LOG.info("Principal: '{}' - unsubscribed from: '{}', reason: {}.", + principal, topicPath, unsubscribeReason); + } + + @Override + public void onClose() { + LOG.info("Principal: '{}' - on close.", principal); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("Principal: '{}' - on error: {}.", principal, errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/timeseries/TimeSeriesAppendTimestampExample.java b/java/com/pushtechnology/client/sdk/example/timeseries/TimeSeriesAppendTimestampExample.java new file mode 100644 index 00000000..9a280f91 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/timeseries/TimeSeriesAppendTimestampExample.java @@ -0,0 +1,80 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.timeseries; + +import static com.pushtechnology.diffusion.datatype.DataTypes.DOUBLE_DATATYPE_NAME; + +import java.time.Instant; +import java.util.Random; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.TimeSeries; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; + +/** + * This example demonstrates how to append events with user-supplied timestamps to a time series topic in Diffusion. + *

+ * A time series topic is created with a specified retained range and subscription range. + * Events containing double values are appended with explicitly defined timestamps. + * + * @author DiffusionData Limited + */ +public class TimeSeriesAppendTimestampExample { + + private static final Logger LOG = + LoggerFactory.getLogger(TimeSeriesAppendTimestampExample.class); + + public static void main(String[] args) { + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Random r = new Random(); + final String myTopicPath = "my/time/series/topic/path/user/supplied"; + double myValue; + Instant myTimeStamp; + + final TimeSeries timeSeries = session.feature(TimeSeries.class); + final TopicControl topicControl = session.feature(TopicControl.class); + + final TopicSpecification mySpec = Diffusion.newTopicSpecification(TopicType.TIME_SERIES) + .withProperty(TopicSpecification.TIME_SERIES_EVENT_VALUE_TYPE, DOUBLE_DATATYPE_NAME) + .withProperty(TopicSpecification.TIME_SERIES_RETAINED_RANGE, "limit 15 last 10s") + .withProperty(TopicSpecification.TIME_SERIES_SUBSCRIPTION_RANGE, "limit 3"); + + topicControl.addTopic(myTopicPath, mySpec) + .join(); + + for (int i = 0; i < 25; i++) { + myValue = r.nextDouble(); + myTimeStamp = Instant.ofEpochSecond(i); + + timeSeries.append(myTopicPath, Double.class, myValue, myTimeStamp) + .join(); + } + + LOG.info("Topic has been created."); + + topicControl.removeTopics("?.*//").join(); + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/timeseries/TimeSeriesAppendValueExample.java b/java/com/pushtechnology/client/sdk/example/timeseries/TimeSeriesAppendValueExample.java new file mode 100644 index 00000000..55586975 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/timeseries/TimeSeriesAppendValueExample.java @@ -0,0 +1,76 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.timeseries; + +import static com.pushtechnology.diffusion.datatype.DataTypes.DOUBLE_DATATYPE_NAME; + +import java.util.Random; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.TimeSeries; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; + +/** + * This example demonstrates how to append events to a time series topic in Diffusion. + * + * @author DiffusionData Limited + */ +public class TimeSeriesAppendValueExample { + private static final Logger LOG = + LoggerFactory.getLogger(TimeSeriesAppendValueExample.class); + + public static void main(String[] args) { + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final TopicSpecification mySpec = Diffusion.newTopicSpecification(TopicType.TIME_SERIES) + .withProperty(TopicSpecification.TIME_SERIES_EVENT_VALUE_TYPE, DOUBLE_DATATYPE_NAME) + .withProperty(TopicSpecification.TIME_SERIES_RETAINED_RANGE, "limit 15 last 10s") + .withProperty(TopicSpecification.TIME_SERIES_SUBSCRIPTION_RANGE, "limit 3"); + + final TopicControl.AddTopicResult result = + session.feature(TopicControl.class) + .addTopic("my/time/series/topic/path", mySpec) + .join(); + + if (result == TopicControl.AddTopicResult.CREATED) { + System.out.println("Topic has been created."); + } + else { + System.out.println("Topic already exists."); + } + + final TimeSeries timeSeries = session.feature(TimeSeries.class); + final Random r = new Random(); + + for (int i = 0; i < 25; i++) { + timeSeries.append("my/time/series/topic/path", Double.class, r.nextDouble()) + .join(); + } + + session.feature(TopicControl.class).removeTopics("?.*//").join(); + session.close(); + + LOG.info("Topic has been created."); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/timeseries/TimeSeriesAppendViaUpdateStreamExample.java b/java/com/pushtechnology/client/sdk/example/timeseries/TimeSeriesAppendViaUpdateStreamExample.java new file mode 100644 index 00000000..9d9c633e --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/timeseries/TimeSeriesAppendViaUpdateStreamExample.java @@ -0,0 +1,76 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.timeseries; + +import static com.pushtechnology.diffusion.datatype.DataTypes.DOUBLE_DATATYPE_NAME; + +import java.util.Random; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.TopicUpdate; +import com.pushtechnology.diffusion.client.features.UpdateStream; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; + +/** + * This example demonstrates how to append events to a time series topic via + * an update stream in Diffusion. + * + * @author DiffusionData Limited + */ +public class TimeSeriesAppendViaUpdateStreamExample { + private static final Logger LOG = + LoggerFactory.getLogger(TimeSeriesAppendViaUpdateStreamExample.class); + + public static void main(String[] args) { + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Random r = new Random(); + final String myTopicPath = "my/time/series/topic/path/user/supplied"; + double myValue; + + final TopicControl topicControl = session.feature(TopicControl.class); + + final TopicSpecification mySpec = Diffusion.newTopicSpecification(TopicType.TIME_SERIES) + .withProperty(TopicSpecification.TIME_SERIES_EVENT_VALUE_TYPE, DOUBLE_DATATYPE_NAME) + .withProperty(TopicSpecification.TIME_SERIES_RETAINED_RANGE, "limit 15 last 10s") + .withProperty(TopicSpecification.TIME_SERIES_SUBSCRIPTION_RANGE, "limit 3"); + + topicControl.addTopic(myTopicPath, mySpec) + .join(); + + final UpdateStream updateStream = session.feature(TopicUpdate.class) + .newUpdateStreamBuilder() + .build(myTopicPath, Double.class); + + for (int i = 0; i < 25; i++) { + myValue = r.nextDouble(); + updateStream.set(myValue).join(); + } + + topicControl.removeTopics("?.*//").join(); + session.close(); + + LOG.info("Topic has been created."); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/timeseries/TimeSeriesCreateTopicExample.java b/java/com/pushtechnology/client/sdk/example/timeseries/TimeSeriesCreateTopicExample.java new file mode 100644 index 00000000..9f4bfd67 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/timeseries/TimeSeriesCreateTopicExample.java @@ -0,0 +1,61 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.timeseries; + +import static com.pushtechnology.diffusion.datatype.DataTypes.DOUBLE_DATATYPE_NAME; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; + +/** + * This example demonstrates how to create a time series topic in Diffusion. + *

+ * A time series topic is created with a specified event value type, retained range, + * and subscription range. + * + * @author DiffusionData Limited + */ +public class TimeSeriesCreateTopicExample { + private static final Logger LOG = LoggerFactory.getLogger(TimeSeriesCreateTopicExample.class); + + public static void main(String[] args) { + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final TopicControl.AddTopicResult result = + session.feature(TopicControl.class).addTopic( + "my/time/series/topic/path", Diffusion.newTopicSpecification(TopicType.TIME_SERIES) + .withProperty(TopicSpecification.TIME_SERIES_EVENT_VALUE_TYPE, DOUBLE_DATATYPE_NAME) + .withProperty(TopicSpecification.TIME_SERIES_RETAINED_RANGE, "limit 15 last 10s") + .withProperty(TopicSpecification.TIME_SERIES_SUBSCRIPTION_RANGE, "limit 3")) + .join(); + + if (result == TopicControl.AddTopicResult.CREATED) { + LOG.info("Topic has been created."); + } + else { + LOG.info("Topic already exists."); + } + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/timeseries/TimeSeriesCrossCompatibleDatatypesExample.java b/java/com/pushtechnology/client/sdk/example/timeseries/TimeSeriesCrossCompatibleDatatypesExample.java new file mode 100644 index 00000000..d14d594f --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/timeseries/TimeSeriesCrossCompatibleDatatypesExample.java @@ -0,0 +1,114 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.timeseries; + +import static com.pushtechnology.diffusion.datatype.DataTypes.DOUBLE_DATATYPE_NAME; + +import java.util.Random; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.TimeSeries; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates cross-compatible data types when using values streams with time series topics. + *

+ * A time series topic is created with the Double event value type. A value stream of type JSON is added to + * receive updates demonstrating cross-compatibility in data types. + * + * @author DiffusionData Limited + */ +public class TimeSeriesCrossCompatibleDatatypesExample { + private static final Logger LOG = + LoggerFactory.getLogger(TimeSeriesCrossCompatibleDatatypesExample.class); + + public static void main(String[] args) { + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Random r = new Random(); + final String myTopicPath = "my/time/series/topic/path"; + final String myTopicSelector = "?my/time/series//"; + + final TopicControl topicControl = session.feature(TopicControl.class); + final Topics topics = session.feature(Topics.class); + final TimeSeries timeSeries = session.feature(TimeSeries.class); + + final TopicSpecification mySpec = Diffusion.newTopicSpecification(TopicType.TIME_SERIES) + .withProperty(TopicSpecification.TIME_SERIES_EVENT_VALUE_TYPE, DOUBLE_DATATYPE_NAME) + .withProperty(TopicSpecification.TIME_SERIES_RETAINED_RANGE, "limit 15 last 10s") + .withProperty(TopicSpecification.TIME_SERIES_SUBSCRIPTION_RANGE, "limit 3"); + + topicControl.addTopic(myTopicPath, mySpec) + .join(); + + topics.addTimeSeriesStream(myTopicSelector, JSON.class, new MyValueStream()); + topics.subscribe(myTopicSelector).join(); + + double myValue; + for (int i = 0; i < 25; i++) { + myValue = r.nextDouble(); + + timeSeries.append(myTopicPath, Double.class, myValue) + .join(); + } + + topicControl.removeTopics("?.*//").join(); + session.close(); + + LOG.info("Topic has been created."); + } + + private static final class MyValueStream implements Topics.ValueStream> { + + @Override + public void onSubscription(String topicPath, + TopicSpecification topicSpecification) { + System.out.printf("Subscribed to %s\n", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + System.out.printf("Unsubscribed from %s: %s\n", topicPath, unsubscribeReason); + } + + @Override + public void onValue(String topicPath, + TopicSpecification topicSpecification, + TimeSeries.Event oldValue, TimeSeries.Event newValue) { + System.out.printf("%s changed from %f to %f\n", + topicPath, oldValue.value(), newValue.value()); + } + + @Override + public void onClose() { } + + @Override + public void onError(ErrorReason errorReason) { } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/timeseries/TimeSeriesEditValueExample.java b/java/com/pushtechnology/client/sdk/example/timeseries/TimeSeriesEditValueExample.java new file mode 100644 index 00000000..2dbb8a2a --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/timeseries/TimeSeriesEditValueExample.java @@ -0,0 +1,75 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.timeseries; + +import static com.pushtechnology.diffusion.datatype.DataTypes.DOUBLE_DATATYPE_NAME; + +import java.util.Random; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.TimeSeries; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; + +/** + * This example demonstrates how to edit a time series topic by modifying a specific event. + * + * @author DiffusionData Limited + */ +public class TimeSeriesEditValueExample { + private static final Logger LOG = + LoggerFactory.getLogger(TimeSeriesEditValueExample.class); + + public static void main(String[] args) { + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Random r = new Random(); + final String myTopicPath = " my/time/series/topic/path"; + double myValue; + + final TimeSeries timeSeries = session.feature(TimeSeries.class); + final TopicControl topicControl = session.feature(TopicControl.class); + + final TopicSpecification + mySpec = Diffusion.newTopicSpecification(TopicType.TIME_SERIES) + .withProperty(TopicSpecification.TIME_SERIES_EVENT_VALUE_TYPE, DOUBLE_DATATYPE_NAME) + .withProperty(TopicSpecification.TIME_SERIES_RETAINED_RANGE, "limit 20 last 10s") + .withProperty(TopicSpecification.TIME_SERIES_SUBSCRIPTION_RANGE, "limit 3"); + + topicControl.addTopic(myTopicPath, mySpec) + .join(); + + for (int i = 0; i < 25; i++) { + myValue = r.nextDouble(); + timeSeries.append(myTopicPath, Double.class, myValue) + .join(); + } + + timeSeries.edit(myTopicPath, 20, Double.class, 3.14).join(); + + topicControl.removeTopics("?.*//").join(); + session.close(); + + LOG.info("Topic has been created."); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/timeseries/TimeSeriesRangeQueryExample.java b/java/com/pushtechnology/client/sdk/example/timeseries/TimeSeriesRangeQueryExample.java new file mode 100644 index 00000000..5395b1c5 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/timeseries/TimeSeriesRangeQueryExample.java @@ -0,0 +1,79 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.timeseries; + +import static com.pushtechnology.diffusion.datatype.DataTypes.DOUBLE_DATATYPE_NAME; + +import java.util.Random; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.TimeSeries; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.Bytes; + +/** + * This example demonstrates how to query a range of events from a time series topic. + *

+ * A range query is performed to retrieve events from sequence 5 to 15. + * + * @author DiffusionData Limited + */ +public class TimeSeriesRangeQueryExample { + private static final Logger LOG = LoggerFactory.getLogger(TimeSeriesRangeQueryExample.class); + + public static void main(String[] args) { + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final String topicPath = "my/time/series/topic/path"; + + session.feature(TopicControl.class).addTopic( + topicPath, Diffusion.newTopicSpecification(TopicType.TIME_SERIES) + .withProperty(TopicSpecification.TIME_SERIES_EVENT_VALUE_TYPE, DOUBLE_DATATYPE_NAME) + .withProperty(TopicSpecification.TIME_SERIES_RETAINED_RANGE, "limit 20 last 120s") + .withProperty(TopicSpecification.TIME_SERIES_SUBSCRIPTION_RANGE, "limit 3")) + .join(); + + final TimeSeries timeSeries = session.feature(TimeSeries.class); + final Random random = new Random(); + + for (int i = 0; i < 25; i++) { + timeSeries.append(topicPath, Double.class, random.nextDouble()) + .join(); + } + + timeSeries.edit(topicPath, 10, Double.class, 3.14) + .join(); + + final TimeSeries.QueryResult queryResult = + timeSeries.rangeQuery() + .from(5) + .to(15) + .selectFrom(topicPath) + .join(); + + queryResult.stream() + .forEach(event -> LOG.info("{} ({}): {}", event.sequence(), event.timestamp(), event.value())); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/timeseries/TimeSeriesSubscribeExample.java b/java/com/pushtechnology/client/sdk/example/timeseries/TimeSeriesSubscribeExample.java new file mode 100644 index 00000000..d23617fe --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/timeseries/TimeSeriesSubscribeExample.java @@ -0,0 +1,109 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.timeseries; + +import static com.pushtechnology.diffusion.datatype.DataTypes.DOUBLE_DATATYPE_NAME; + +import java.util.Random; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.TimeSeries; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; + +/** + * This example demonstrates how to subscribe to a time series topic and receive updates. + * + * @author DiffusionData Limited + */ +public class TimeSeriesSubscribeExample { + private static final Logger LOG = + LoggerFactory.getLogger(TimeSeriesSubscribeExample.class); + + public static void main(String[] args) { + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Random r = new Random(); + final String myTopicPath = "my/time/series/topic/path"; + final String myTopicSelector = "?my/time/series//"; + + final Topics topics = session.feature(Topics.class); + final TopicControl topicControl = session.feature(TopicControl.class); + final TimeSeries timeSeries = session.feature(TimeSeries.class); + + final TopicSpecification mySpec = Diffusion.newTopicSpecification(TopicType.TIME_SERIES) + .withProperty(TopicSpecification.TIME_SERIES_EVENT_VALUE_TYPE, DOUBLE_DATATYPE_NAME) + .withProperty(TopicSpecification.TIME_SERIES_RETAINED_RANGE, "limit 15 last 10s") + .withProperty(TopicSpecification.TIME_SERIES_SUBSCRIPTION_RANGE, "limit 3"); + + topicControl.addTopic(myTopicPath, mySpec) + .join(); + + topics.addTimeSeriesStream(myTopicSelector, Double.class, new MyValueStream()); + topics.subscribe(myTopicSelector).join(); + + double myValue; + for (int i = 0; i < 25; i++) { + myValue = r.nextDouble(); + + timeSeries.append(myTopicPath, Double.class, myValue) + .join(); + } + + topicControl.removeTopics("?.*//").join(); + session.close(); + + LOG.info("Topic has been created."); + } + private static final class MyValueStream implements Topics.ValueStream> { + + @Override + public void onSubscription(String topicPath, + TopicSpecification topicSpecification) { + System.out.printf("Subscribed to %s\n", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + System.out.printf("Unsubscribed from %s: %s\n", topicPath, unsubscribeReason); + } + + @Override + public void onValue(String topicPath, + TopicSpecification topicSpecification, + TimeSeries.Event oldValue, TimeSeries.Event newValue) { + System.out.printf("%s changed from %f to %f\n", + topicPath, oldValue.value(), newValue.value()); + } + + @Override + public void onClose() { } + + @Override + public void onError(ErrorReason errorReason) { } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/topicviews/api/AddTopicViewExample.java b/java/com/pushtechnology/client/sdk/example/topicviews/api/AddTopicViewExample.java new file mode 100644 index 00000000..8c916349 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/topicviews/api/AddTopicViewExample.java @@ -0,0 +1,66 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.topicviews.api; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to create a topic view in Diffusion. + * + * @author DiffusionData Limited + */ +public class AddTopicViewExample { + private static final Logger + LOG = LoggerFactory.getLogger(AddTopicViewExample.class); + + public static void main(String[] args) { + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Topics topics = session.feature(Topics.class); + final TopicSpecification mySpec = Diffusion.newTopicSpecification(TopicType.JSON); + final JSON jsonValue = Diffusion.dataTypes().json() + .fromJsonString("{ \"diffusion\": \"data\" }"); + + topics.addAndSet("my/topic/path", mySpec, JSON.class, jsonValue) + .join(); + + final String topicViewName = "topic_view_1"; + + topics.createTopicView(topicViewName, "map my/topic/path to views/") + .join(); + + System.out.printf("Topic View <%s> has been created\n", topicViewName); + + topics.removeTopicView(topicViewName).join(); + session.feature(TopicControl.class).removeTopics("?.*//") + .join(); + + session.close(); + + LOG.info("Topic View <{}> has been created.", topicViewName); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/topicviews/api/ListTopicViewsExample.java b/java/com/pushtechnology/client/sdk/example/topicviews/api/ListTopicViewsExample.java new file mode 100644 index 00000000..718f5460 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/topicviews/api/ListTopicViewsExample.java @@ -0,0 +1,86 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.topicviews.api; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.features.control.topics.views.TopicView; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to list topic views in Diffusion. + * + * @author DiffusionData Limited + */ +public class ListTopicViewsExample { + private static final Logger + LOG = LoggerFactory.getLogger(ListTopicViewsExample.class); + + public static void main(String[] args) { + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Topics topics = session.feature(Topics.class); + final TopicSpecification mySpec = + Diffusion.newTopicSpecification(TopicType.JSON); + final JSON jsonValue = Diffusion.dataTypes().json() + .fromJsonString("{ \"diffusion\": \"data\" }"); + + topics.addAndSet("my/topic/path", mySpec, JSON.class, jsonValue) + .join(); + + topics.createTopicView("topic_view_1", "map my/topic/path to views/") + .join(); + + System.out.println("Topic View has been created"); + + topics.addAndSet("my/topic/path/array", mySpec, JSON.class, jsonValue) + .join(); + + topics.createTopicView("topic_view_2", "map my/topic/path/array to views/") + .join(); + + System.out.println("Topic View has been created"); + + final List topicViews = topics.listTopicViews().join(); + + topicViews.forEach(view -> { + final String name = view.getName(); + final String spec = view.getSpecification(); + final String roles = view.getRoles().toString(); + + System.out.printf("Topic View <%s>: <%s> (<%s>)\n", name, spec, roles); + }); + + topics.removeTopicView("topic_view_1").join(); + topics.removeTopicView("topic_view_2").join(); + session.feature(TopicControl.class).removeTopics("?.*//").join(); + + session.close(); + + LOG.info("Topic Views listed: {}", topicViews.size()); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/topicviews/api/RemoveTopicViewExample.java b/java/com/pushtechnology/client/sdk/example/topicviews/api/RemoveTopicViewExample.java new file mode 100644 index 00000000..5cfce706 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/topicviews/api/RemoveTopicViewExample.java @@ -0,0 +1,96 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.topicviews.api; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; +import com.pushtechnology.diffusion.client.features.control.topics.views.TopicView; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to remove a topic view in Diffusion. + * + * @author DiffusionData Limited + */ +public class RemoveTopicViewExample { + private static final Logger + LOG = LoggerFactory.getLogger(RemoveTopicViewExample.class); + + public static void main(String[] args) { + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Topics topics = session.feature(Topics.class); + final TopicSpecification + mySpec = Diffusion.newTopicSpecification(TopicType.JSON); + final JSON jsonValue = Diffusion.dataTypes().json() + .fromJsonString("{ \"diffusion\": \"data\" }"); + + topics.addAndSet("my/topic/path", mySpec, JSON.class, jsonValue) + .join(); + + topics.createTopicView("topic_view_1", "map my/topic/path to views/") + .join(); + + System.out.println("Topic View has been created"); + + topics.addAndSet("my/topic/path/array", mySpec, JSON.class, jsonValue) + .join(); + + topics.createTopicView("topic_view_2", "map my/topic/path/array to views/") + .join(); + + System.out.println("Topic View has been created"); + + List topicViews = topics.listTopicViews().join(); + + topicViews.forEach(view -> { + final String name = view.getName(); + final String spec = view.getSpecification(); + final String roles = view.getRoles().toString(); + + System.out.printf("Topic View <%s>: <%s> (<%s>)\n", name, spec, roles); + }); + + topics.removeTopicView("topic_view_1").join(); + topicViews = topics.listTopicViews().join(); + + topicViews.forEach(view -> { + final String name = view.getName(); + final String spec = view.getSpecification(); + final String roles = view.getRoles().toString(); + + System.out.printf("Topic View <%s>: <%s> (<%s>)\n", name, spec, roles); + }); + + topics.removeTopicView("topic_view_2").join(); + session.feature(TopicControl.class).removeTopics("?.*//").join(); + + session.close(); + + LOG.info("Topic Views listed: {}", topicViews.size()); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslExpandValueExample.java b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslExpandValueExample.java new file mode 100644 index 00000000..a0986518 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslExpandValueExample.java @@ -0,0 +1,113 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.topicviews.dsl; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.views.TopicView; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to use the topic view expand clause. + *

+ * A JSON topic is created containing currency codes. A topic view is then defined + * to create new topics dynamically for each currency code. + * + * @author DiffusionData Limited + */ +public class TopicViewsDslExpandValueExample { + + private static final Logger LOG = + LoggerFactory.getLogger(TopicViewsDslExpandValueExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final String topicPath = "my/topic/path"; + final String viewSelector = "?views//"; + final Topics topics = session.feature(Topics.class); + + final JSON jsonValue = Diffusion.dataTypes().json() + .fromJsonString("{\"currencies\": [\"USD\", \"GBP\", \"EUR\", \"CHF\"]}"); + + final Topics.ValueStream valueStream = new MyStream(); + + topics.addAndSet(topicPath, + Diffusion.newTopicSpecification(TopicType.JSON), + JSON.class, jsonValue) + .join(); + + topics.addStream(viewSelector, JSON.class, valueStream); + topics.subscribe(viewSelector).join(); + + final TopicView topicView = topics.createTopicView("topic_view_1", + "map " + topicPath + " to views/currency").join(); + + LOG.info("Topic View {} has been created", topicView.getName()); + + SECONDS.sleep(1); + + topics.removeStream(valueStream); + session.close(); + } + + static class MyStream implements Topics.ValueStream { + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + LOG.info("{} new value {}", topicPath, newValue.toJsonString()); + } + + @Override + public void onSubscription(String topicPath, + TopicSpecification topicSpecification) { + LOG.info("Subscribed to {}", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + LOG.info("Unsubscribed from {}", topicPath); + } + + @Override + public void onClose() { + LOG.info("stream closed"); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("stream error: {}", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslInsertTransformationsExample.java b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslInsertTransformationsExample.java new file mode 100644 index 00000000..48f228ca --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslInsertTransformationsExample.java @@ -0,0 +1,133 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.topicviews.dsl; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.views.TopicView; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to use the topic view insert clause. + *

+ * A JSON topic containing a list of cast members is created. A topic view is then defined to + * insert additional cast members from separate topics into the list. + * + * @author DiffusionData Limited + */ +public class TopicViewsDslInsertTransformationsExample { + + private static final Logger LOG = + LoggerFactory.getLogger(TopicViewsDslInsertTransformationsExample.class); + + public static void main(String[] args) throws Exception { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final Topics topics = session.feature(Topics.class); + final TopicSpecification specification = Diffusion.newTopicSpecification(TopicType.JSON); + final String viewSelector = "?views//"; + final MyStream myStream = new MyStream(); + + final JSON originalCastJsonValue = Diffusion.dataTypes().json().fromJsonString("[\n" + + " \"Fred Flintstone\"," + + " \"Wilma Flintstone\"," + + " \"Barney Rubble\"," + + " \"Betty Rubble\"" + + "]"); + + final JSON additionalCast1 = Diffusion.dataTypes().json() + .fromJsonString("\"Pebbles Flintstone\""); + + final JSON additionalCast2 = Diffusion.dataTypes().json() + .fromJsonString("\"Bamm-Bamm Rubble\""); + + topics.addAndSet( + "my/topic/path/original_cast", specification, JSON.class, originalCastJsonValue) + .join(); + + topics.addAndSet( + "my/topic/path/additional_cast/1", specification, JSON.class, additionalCast1) + .join(); + + topics.addAndSet( + "my/topic/path/additional_cast/2", specification, JSON.class, additionalCast2) + .join(); + + topics.addStream(viewSelector, JSON.class, myStream); + topics.subscribe(viewSelector).join(); + + final TopicView topicView = topics.createTopicView("topic_view_1", + "map my/topic/path/original_cast\n" + + " to views/the_flintstones\n" + + " insert my/topic/path/additional_cast/1 at /-\n" + + " insert my/topic/path/additional_cast/2 at /-") + .join(); + + LOG.info("Topic View {} has been created", topicView.getName()); + + SECONDS.sleep(1); + + topics.removeStream(myStream); + } + } + + static class MyStream implements Topics.ValueStream { + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + LOG.info("{} new value {}", topicPath, newValue.toJsonString()); + } + + @Override + public void onSubscription(String topicPath, + TopicSpecification topicSpecification) { + LOG.info("Subscribed to {}", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + LOG.info("Unsubscribed from {}", topicPath); + } + + @Override + public void onClose() { + LOG.info("stream closed"); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("stream error: {}", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslOptionsDelayExample.java b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslOptionsDelayExample.java new file mode 100644 index 00000000..bf6db72a --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslOptionsDelayExample.java @@ -0,0 +1,110 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.topicviews.dsl; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.views.TopicView; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; + +/** + * This example demonstrates how to use the topic view delay clause. + *

+ * A topic view with a 5-second delay is created. + * + * @author DiffusionData Limited + */ +public class TopicViewsDslOptionsDelayExample { + + private static final Logger LOG = + LoggerFactory.getLogger(TopicViewsDslOptionsDelayExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Topics topics = session.feature(Topics.class); + final String topicPath = "my/topic/path"; + final String viewSelector = "?views//"; + final Topics.ValueStream valueStream = new MyStream(); + + topics.addAndSet( + topicPath, + Diffusion.newTopicSpecification(TopicType.INT64), Long.class, 0L) + .join(); + + topics.addStream(viewSelector, Long.class, valueStream); + topics.subscribe(viewSelector).join(); + + final TopicView topicView = topics.createTopicView("topic_view_1", + "map my/topic/path to views/ delay by 5 seconds") + .join(); + + LOG.info("Topic View {} has been created", topicView.getName()); + + for (int i = 0; i < 15; i++) { + topics.set(topicPath, Long.class, System.currentTimeMillis()).join(); + SECONDS.sleep(1); + } + + topics.removeStream(valueStream); + session.close(); + } + + public static class MyStream implements Topics.ValueStream { + + @Override + public void onSubscription(String topicPath, + TopicSpecification topicSpecification) { + LOG.info("Subscribed to {}", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + LOG.info("Unsubscribed from {}", topicPath); + } + + @Override + public void onValue(String topicPath, + TopicSpecification topicSpecification, + Long oldValue, + Long newValue) { + LOG.info("{} new value {}", topicPath, newValue); + } + + @Override + public void onClose() { + LOG.info("stream closed"); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("stream error: {}", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslOptionsPreserveTopicsExample.java b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslOptionsPreserveTopicsExample.java new file mode 100644 index 00000000..6ec755a3 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslOptionsPreserveTopicsExample.java @@ -0,0 +1,126 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.topicviews.dsl; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.views.TopicView; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to use the topic view preserve topics clause. + *

+ * A topic view is created with and without the `preserve topics` clause. When applied, + * the derived topics persist even when the source topic changes. + * + * @author DiffusionData Limited + */ +public class TopicViewsDslOptionsPreserveTopicsExample { + + private static final Logger LOG = + LoggerFactory.getLogger(TopicViewsDslOptionsPreserveTopicsExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Topics topics = session.feature(Topics.class); + final String topicPath = "my/topic/path"; + final String viewSelector = "?views//"; + + final JSON value1 = Diffusion.dataTypes().json() + .fromJsonString("{\"name\":\"Fred Flintstone\"}"); + + final JSON value2 = Diffusion.dataTypes().json() + .fromJsonString("{\"name\":\"Wilma Flintstone\"}"); + + final JSON value3 = Diffusion.dataTypes().json() + .fromJsonString("{\"name\":\"Pebbles Flintstone\"}"); + + topics.addAndSet(topicPath, + Diffusion.newTopicSpecification(TopicType.JSON), + JSON.class, value1) + .join(); + + final Topics.ValueStream valueStream = new MyStream(); + topics.addStream(viewSelector, JSON.class, valueStream); + topics.subscribe(viewSelector).join(); + + final TopicView view1 = topics.createTopicView("topic_view_1", + "map my/topic/path to views/preserved/ preserve topics").join(); + + LOG.info("Topic view created: {}", view1.getName()); + + final TopicView view2 = topics.createTopicView("topic_view_2", + "map my/topic/path to views/not_preserved/").join(); + + LOG.info("Topic view created: {}", view2.getName()); + + topics.set(topicPath, JSON.class, value2).join(); + topics.set(topicPath, JSON.class, value3).join(); + + SECONDS.sleep(1); + + topics.removeStream(valueStream); + session.close(); + } + + static class MyStream implements Topics.ValueStream { + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + LOG.info("{} new value {}", topicPath, newValue.toJsonString()); + } + + @Override + public void onSubscription(String topicPath, + TopicSpecification topicSpecification) { + LOG.info("Subscribed to {}", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + LOG.info("Unsubscribed from {}", topicPath); + } + + @Override + public void onClose() { + LOG.info("stream closed"); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("stream error: {}", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslOptionsSeparatorExample.java b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslOptionsSeparatorExample.java new file mode 100644 index 00000000..ca1e9427 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslOptionsSeparatorExample.java @@ -0,0 +1,120 @@ +/******************************************************************************* + * Copyright (C) 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.topicviews.dsl; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.views.TopicView; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to use the topic view separator clause. + *

+ * A topic view is created that maps topics while replacing the default path separator (`/`) + * with an underscore (`_`). + * + * @author DiffusionData Limited + */ +public class TopicViewsDslOptionsSeparatorExample { + + private static final Logger LOG = + LoggerFactory.getLogger(TopicViewsDslOptionsSeparatorExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Topics topics = session.feature(Topics.class); + final TopicSpecification spec = Diffusion.newTopicSpecification(TopicType.JSON); + + final String topicPath = "my/topic/path"; + final String viewSelector = "?views//"; + final Topics.ValueStream valueStream = new MyStream(); + + final JSON value1 = Diffusion.dataTypes().json() + .fromJsonString("{\"name\": \"Fred/Flintstone\"}"); + + final JSON value2 = Diffusion.dataTypes().json() + .fromJsonString("{\"name\": \"Wilma/Flintstone\"}"); + + final JSON value3 = Diffusion.dataTypes().json() + .fromJsonString("{\"name\": \"Wilma/Flintstone\"}"); + + topics.addAndSet(topicPath + "/1", spec, JSON.class, value1).join(); + topics.addAndSet(topicPath + "/2", spec, JSON.class, value2).join(); + topics.addAndSet(topicPath + "/3", spec, JSON.class, value3).join(); + + topics.addStream(viewSelector, JSON.class, valueStream); + topics.subscribe(viewSelector).join(); + + final TopicView myTopicView = topics.createTopicView( + "topic_view_1", + "map ?my/topic/path// to views/ separator '_'").join(); + + LOG.info("Topic View {} has been created", myTopicView.getName()); + + SECONDS.sleep(1); + + topics.removeStream(valueStream); + session.close(); + } + + private static final class MyStream implements Topics.ValueStream { + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + LOG.info("{} new value {}", topicPath, newValue.toJsonString()); + } + + @Override + public void onSubscription(String topicPath, + TopicSpecification topicSpecification) { + LOG.info("Subscribed to {}", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + LOG.info("Unsubscribed from {}", topicPath); + } + + @Override + public void onClose() { + LOG.info("stream closed"); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("stream error: {}", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslOptionsThrottleExample.java b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslOptionsThrottleExample.java new file mode 100644 index 00000000..5087ae04 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslOptionsThrottleExample.java @@ -0,0 +1,112 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.topicviews.dsl; + +import static java.util.concurrent.TimeUnit.MILLISECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.views.TopicView; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; + +/** + * This example demonstrates how to use the topic view throttle clause. + *

+ * A topic view is created that limits updates to at most one every 10 seconds, + * even if the source topic updates more frequently. + * + * @author DiffusionData Limited + */ +public class TopicViewsDslOptionsThrottleExample { + + private static final Logger LOG = + LoggerFactory.getLogger(TopicViewsDslOptionsThrottleExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Topics topics = session.feature(Topics.class); + final String topicPath = "my/topic/path"; + final String viewSelector = "?views//"; + final Topics.ValueStream valueStream = new MyStream(); + + topics.addAndSet( + topicPath, + Diffusion.newTopicSpecification(TopicType.INT64), Long.class, 0L) + .join(); + + topics.addStream(viewSelector, Long.class, valueStream); + topics.subscribe(viewSelector).join(); + + final TopicView myView = topics.createTopicView("topic_view_1", + "map my/topic/path to views/ throttle to 1 update every 10 seconds") + .join(); + + LOG.info("Topic View {} has been created", myView.getName()); + + for (int i = 0; i < 5; i++) { + topics.set(topicPath, Long.class, System.currentTimeMillis()).join(); + MILLISECONDS.sleep(500); + } + + topics.removeStream(valueStream); + session.close(); + } + + private static final class MyStream implements Topics.ValueStream { + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + Long oldValue, + Long newValue) { + LOG.info("{} new value {}", topicPath, newValue); + } + + @Override + public void onSubscription(String topicPath, + TopicSpecification topicSpecification) { + LOG.info("Subscribed to {}", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + LOG.info("Unsubscribed from {}", topicPath); + } + + @Override + public void onClose() { + LOG.info("stream closed"); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("stream error: {}", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslOptionsTopicPropertyMappingExample.java b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslOptionsTopicPropertyMappingExample.java new file mode 100644 index 00000000..842d2b88 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslOptionsTopicPropertyMappingExample.java @@ -0,0 +1,117 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.topicviews.dsl; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.views.TopicView; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to use topic property mapping in a topic view. + *

+ * A topic view is created that maps a source topic while setting specific + * properties such as conflation, compression, and retention behavior. + * + * @author DiffusionData Limited + */ +public class TopicViewsDslOptionsTopicPropertyMappingExample { + + private static final Logger LOG = + LoggerFactory.getLogger(TopicViewsDslOptionsTopicPropertyMappingExample.class); + + public static void main(String[] args) throws Exception { + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Topics topics = session.feature(Topics.class); + final String viewSelector = "?views//"; + final Topics.ValueStream valueStream = new MyStream(); + + final JSON jsonValue = Diffusion.dataTypes().json() + .fromJsonString("[" + + "\"Fred Flintstone\", " + + "\"Wilma Flintstone\", " + + "\"Barney Rubble\", " + + "\"Betty Rubble\"" + + "]"); + + topics.addAndSet( + "my/topic/path", + Diffusion.newTopicSpecification(TopicType.JSON), JSON.class, jsonValue) + .join(); + + topics.addStream(viewSelector, JSON.class, valueStream); + topics.subscribe(viewSelector).join(); + + final TopicView view = topics.createTopicView("topic_view_1", + "map my/topic/path to views/ with properties " + + "'CONFLATION':'off', 'COMPRESSION':'false', 'DONT_RETAIN_VALUE':'true'") + .join(); + + LOG.info("Topic View {} has been created", view.getName()); + + SECONDS.sleep(1); + + topics.removeStream(valueStream); + session.close(); + } + + private static final class MyStream implements Topics.ValueStream { + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + LOG.info("{} new value {}", topicPath, newValue); + } + + @Override + public void onSubscription(String topicPath, + TopicSpecification topicSpecification) { + LOG.info("Subscribed to {}", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + LOG.info("Unsubscribed from {}", topicPath); + } + + @Override + public void onClose() { + LOG.info("stream closed"); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("stream error: {}", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslOptionsTopicTypeExample.java b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslOptionsTopicTypeExample.java new file mode 100644 index 00000000..bc986b9c --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslOptionsTopicTypeExample.java @@ -0,0 +1,82 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.topicviews.dsl; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.TimeSeries; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.views.TopicView; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicType; + +/** + * This example demonstrates how to specify the topic type in a topic view. + *

+ * A topic view is created that maps a source topic to a new topic with a + * different topic type, converting an INT64 topic into a TIME_SERIES topic. + * + * @author DiffusionData Limited + */ +public class TopicViewsDslOptionsTopicTypeExample { + + private static final Logger LOG = + LoggerFactory.getLogger(TopicViewsDslOptionsTopicTypeExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Topics topics = session.feature(Topics.class); + final String topicPath = "my/topic/path"; + + topics.addAndSet( + topicPath, + Diffusion.newTopicSpecification(TopicType.INT64), Long.class, 0L) + .join(); + + final TopicView view = topics.createTopicView("topic_view_1", + "map my/topic/path to views/archive/ type TIME_SERIES") + .join(); + + LOG.info("Topic View {} has been created", view.getName()); + + for (int i = 0; i < 4; i++) { + topics.set(topicPath, Long.class, System.currentTimeMillis()).join(); + SECONDS.sleep(1); + } + + final TimeSeries.QueryResult queryResult = + session.feature(TimeSeries.class) + .rangeQuery() + .forValues() + .fromStart() + .as(Long.class) + .selectFrom("views/archive/my/topic/path").join(); + + queryResult.stream().forEach( + event -> LOG.info("event {} : value {}", event.sequence(), event.value()) + ); + + session.close(); + } +} diff --git a/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslOptionsTopicValueExample.java b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslOptionsTopicValueExample.java new file mode 100644 index 00000000..da2b2fe9 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslOptionsTopicValueExample.java @@ -0,0 +1,117 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.topicviews.dsl; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.views.TopicView; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to use the topic value transformation in a topic view. + *

+ * A topic view is created that maps a source topic to a new topic, using part of the + * source topic's value as the new topic's value. + * + * @author DiffusionData Limited + */ +public class TopicViewsDslOptionsTopicValueExample { + + private static final Logger LOG = + LoggerFactory.getLogger(TopicViewsDslOptionsTopicValueExample.class); + + public static void main(String[] args) throws Exception { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final JSON originalCastJsonValue = Diffusion.dataTypes().json().fromJsonString("{\n" + + " \"account\": \"1234\"," + + " \"balance\": {" + + " \"amount\": 12.57," + + " \"currency\": \"USD\"" + + " }" + + "}"); + + final Topics topics = session.feature(Topics.class); + + topics.addAndSet( + "my/topic/path", + Diffusion.newTopicSpecification(TopicType.JSON), JSON.class, originalCastJsonValue) + .join(); + + final String topicSelectorExpression = "?views//"; + + final MyStream valueStream = new MyStream(); + topics.addStream(topicSelectorExpression, JSON.class, valueStream); + topics.subscribe(topicSelectorExpression).join(); + + final TopicView view = topics.createTopicView("topic_view_1", + "map my/topic/path to views/ as ") + .join(); + + LOG.info("Topic View {} has been created.", view.getName()); + + SECONDS.sleep(1); + topics.removeStream(valueStream); + } + } + + private static final class MyStream implements Topics.ValueStream { + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + LOG.info("{} new value {}", topicPath, newValue.toJsonString()); + } + + @Override + public void onSubscription(String topicPath, + TopicSpecification topicSpecification) { + LOG.info("Subscribed to {}", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + LOG.info("Unsubscribed from {}", topicPath); + } + + @Override + public void onClose() { + LOG.info("stream closed"); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("stream error: {}", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslPatchTransformationAddExample.java b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslPatchTransformationAddExample.java new file mode 100644 index 00000000..880d86b5 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslPatchTransformationAddExample.java @@ -0,0 +1,114 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.topicviews.dsl; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.views.TopicView; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to use the patch transformation to add a new field to a JSON topic. + *

+ * A topic view is created that applies a JSON Patch operation to add a new key-value pair + * to the JSON content of the mapped topic. + * + * @author DiffusionData Limited + */ +public class TopicViewsDslPatchTransformationAddExample { + + private static final Logger LOG = + LoggerFactory.getLogger(TopicViewsDslPatchTransformationAddExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Topics topics = session.feature(Topics.class); + final String viewSelector = "?views//"; + final MyStream valueStream = new MyStream(); + + final JSON jsonValue = Diffusion.dataTypes().json() + .fromJsonString("{\"Fred\":\"Flintstone\",\"Barney\":\"Rubble\"}"); + + topics.addAndSet("my/topic/path", + Diffusion.newTopicSpecification(TopicType.JSON), + JSON.class, + jsonValue) + .join(); + + topics.addStream(viewSelector, JSON.class, valueStream); + topics.subscribe(viewSelector).join(); + + final TopicView view = topics.createTopicView("topic_view_1", + "map ?my/topic/path// to views/ " + + "patch '[{\"op\": \"add\", \"path\": \"/George\", \"value\": \"Jetson\"}]'") + .join(); + + LOG.info("Topic View {} has been created", view.getName()); + + SECONDS.sleep(1); + + topics.removeStream(valueStream); + session.close(); + } + + private static final class MyStream implements Topics.ValueStream { + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + LOG.info("{} new value {}", topicPath, newValue.toJsonString()); + } + + @Override + public void onSubscription(String topicPath, + TopicSpecification topicSpecification) { + LOG.info("Subscribed to {}", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + LOG.info("Unsubscribed from {}", topicPath); + } + + @Override + public void onClose() { + LOG.info("stream closed"); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("stream error: {}", errorReason); + } + } +} \ No newline at end of file diff --git a/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslPatchTransformationCopyExample.java b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslPatchTransformationCopyExample.java new file mode 100644 index 00000000..32b6028d --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslPatchTransformationCopyExample.java @@ -0,0 +1,112 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.topicviews.dsl; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.views.TopicView; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to use the patch transformation to copy a value within a JSON topic. + *

+ * A topic view is created that applies a JSON Patch operation to copy a value from one key + * to another within the JSON content of the mapped topic. + * + * @author DiffusionData Limited + */ +public class TopicViewsDslPatchTransformationCopyExample { + + private static final Logger LOG = + LoggerFactory.getLogger(TopicViewsDslPatchTransformationCopyExample.class); + + public static void main(String[] args) { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Topics topics = session.feature(Topics.class); + final String viewSelector = "?views//"; + final MyStream valueStream = new MyStream(); + + final JSON jsonValue = Diffusion.dataTypes().json() + .fromJsonString("{ \"Meet the Flintstones\": {\"Fred\":\"Flintstone\",\"Barney\":\"Rubble\"}, " + + "\"The Jetsons\": {\"George\":\"Jetson\"}}"); + + topics.addAndSet("my/topic/path", + Diffusion.newTopicSpecification(TopicType.JSON), + JSON.class, + jsonValue) + .join(); + + topics.addStream(viewSelector, JSON.class, valueStream); + topics.subscribe(viewSelector).join(); + + final TopicView view = topics.createTopicView("topic_view_1", + "map ?my/topic/path// to views/ patch " + + "'[ {\"op\": \"copy\", \"from\": \"/Meet the Flintstones/Fred\", " + + "\"path\": \"/The Jetsons/Fred\" }]'") + .join(); + + LOG.info("Topic View {} has been created", view.getName()); + + topics.removeStream(valueStream); + session.close(); + } + + private static final class MyStream implements Topics.ValueStream { + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + LOG.info("{} new value {}", topicPath, newValue.toJsonString()); + } + + @Override + public void onSubscription(String topicPath, + TopicSpecification topicSpecification) { + LOG.info("Subscribed to {}", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + LOG.info("Unsubscribed from {}", topicPath); + } + + @Override + public void onClose() { + LOG.info("stream closed"); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("stream error: {}", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslPatchTransformationMoveExample.java b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslPatchTransformationMoveExample.java new file mode 100644 index 00000000..b991871f --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslPatchTransformationMoveExample.java @@ -0,0 +1,116 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.topicviews.dsl; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.views.TopicView; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to use the patch transformation to move values within a JSON topic. + *

+ * A topic view is created that applies JSON Patch operations to move values from one key + * to another within the JSON content of the mapped topic. + * + * @author DiffusionData Limited + */ +public class TopicViewsDslPatchTransformationMoveExample { + + private static final Logger LOG = + LoggerFactory.getLogger(TopicViewsDslPatchTransformationMoveExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Topics topics = session.feature(Topics.class); + final String viewSelector = "?views//"; + final JSON jsonValue = Diffusion.dataTypes().json() + .fromJsonString("{\"Fred\":\"Flintstone\",\"Barney\":\"Rubble\",\"George\":\"Jetson\"}"); + + final MyStream valueStream = new MyStream(); + + topics.addAndSet("my/topic/path", + Diffusion.newTopicSpecification(TopicType.JSON), + JSON.class, + jsonValue) + .join(); + + topics.addStream(viewSelector, JSON.class, valueStream); + topics.subscribe(viewSelector).join(); + + final TopicView view = topics.createTopicView("topic_view_1", + "map ?my/topic/path// to views/ patch '[ " + + "{\"op\": \"move\", \"from\": \"/Fred\", \"path\": \"/Meet The Flintstones~1Fred\" }, " + + "{\"op\": \"move\", \"from\": \"/Barney\", \"path\": \"/Meet The Flintstones~1Barney\" }, " + + "{\"op\": \"move\", \"from\": \"/George\", \"path\": \"/The Jetsons~1George\" }]'") + .join(); + + LOG.info("Topic View {} has been created", view.getName()); + + SECONDS.sleep(1); + + topics.removeStream(valueStream); + session.close(); + } + + private static final class MyStream implements Topics.ValueStream { + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + LOG.info("{} new value {}", topicPath, newValue.toJsonString()); + } + + @Override + public void onSubscription(String topicPath, + TopicSpecification topicSpecification) { + LOG.info("Subscribed to {}", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + LOG.info("Unsubscribed from {}", topicPath); + } + + @Override + public void onClose() { + LOG.info("stream closed"); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("stream error: {}", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslPatchTransformationRemoveExample.java b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslPatchTransformationRemoveExample.java new file mode 100644 index 00000000..d8d1837e --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslPatchTransformationRemoveExample.java @@ -0,0 +1,117 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.topicviews.dsl; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.views.TopicView; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to use the patch transformation to remove values within a JSON topic. + *

+ * A topic view is created that applies a JSON Patch operation to remove a specific key from the + * JSON content of the mapped topic. + * + * @author DiffusionData Limited + */ +public class TopicViewsDslPatchTransformationRemoveExample { + + private static final Logger LOG = + LoggerFactory.getLogger(TopicViewsDslPatchTransformationRemoveExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Topics topics = session.feature(Topics.class); + final String viewSelector = "?views//"; + final MyStream valueStream = new MyStream(); + + final JSON jsonValue = Diffusion.dataTypes().json() + .fromJsonString("{" + + "\"Fred\":\"Flintstone\"," + + "\"Barney\":\"Rubble\"," + + "\"George\":\"Jetson\"" + + "}"); + + topics.addAndSet("my/topic/path", + Diffusion.newTopicSpecification(TopicType.JSON), + JSON.class, + jsonValue) + .join(); + + topics.addStream(viewSelector, JSON.class, valueStream); + topics.subscribe(viewSelector).join(); + + final TopicView view = topics.createTopicView("topic_view_1", + "map ?my/topic/path// to views/ patch '[{\"op\": \"remove\", \"path\": \"/George\"}]'") + .join(); + + LOG.info("Topic View {} has been created", view.getName()); + + SECONDS.sleep(1); + + topics.removeStream(valueStream); + session.close(); + } + + private static final class MyStream implements Topics.ValueStream { + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + LOG.info("{} new value {}", topicPath, newValue.toJsonString()); + } + + @Override + public void onSubscription(String topicPath, + TopicSpecification topicSpecification) { + LOG.info("Subscribed to {}", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + LOG.info("Unsubscribed from {}", topicPath); + } + + @Override + public void onClose() { + LOG.info("stream closed"); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("stream error: {}", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslPatchTransformationReplaceExample.java b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslPatchTransformationReplaceExample.java new file mode 100644 index 00000000..31d89843 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslPatchTransformationReplaceExample.java @@ -0,0 +1,114 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.topicviews.dsl; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.views.TopicView; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to use the patch transformation to replace values within a JSON topic. + *

+ * A topic view is created that applies a JSON Patch operation to replace a specific key's value + * within the JSON content of the mapped topic. + * + * @author DiffusionData Limited + */ +public class TopicViewsDslPatchTransformationReplaceExample { + + private static final Logger LOG = + LoggerFactory.getLogger(TopicViewsDslPatchTransformationReplaceExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Topics topics = session.feature(Topics.class); + final String viewSelector = "?views//"; + final MyStream valueStream = new MyStream(); + + final JSON jsonValue = Diffusion.dataTypes().json() + .fromJsonString("{\"Fred\":\"Flintstone\",\"Barney\":\"Rubble\",\"George\":\"Jetson\"}"); + + topics.addAndSet("my/topic/path", + Diffusion.newTopicSpecification(TopicType.JSON), + JSON.class, + jsonValue) + .join(); + + topics.addStream(viewSelector, JSON.class, valueStream); + topics.subscribe(viewSelector).join(); + + final TopicView view = topics.createTopicView("topic_view_1", + "map ?my/topic/path// to views/ patch '[{\"op\": " + + "\"replace\", \"path\": \"/George\", \"value\": \"Bedrock\" }]'") + .join(); + + LOG.info("Topic View {} has been created", view.getName()); + + SECONDS.sleep(1); + + topics.removeStream(valueStream); + session.close(); + } + + private static final class MyStream implements Topics.ValueStream { + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + LOG.info("{} new value {}", topicPath, newValue.toJsonString()); + } + + @Override + public void onSubscription(String topicPath, + TopicSpecification topicSpecification) { + LOG.info("Subscribed to {}", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + LOG.info("Unsubscribed from {}", topicPath); + } + + @Override + public void onClose() { + LOG.info("stream closed"); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("stream error: {}", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslPatchTransformationTestExample.java b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslPatchTransformationTestExample.java new file mode 100644 index 00000000..89196e36 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslPatchTransformationTestExample.java @@ -0,0 +1,114 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.topicviews.dsl; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.views.TopicView; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to use the patch transformation to apply a test operation + * within a JSON topic. + *

+ * A topic view is created that verifies whether a specific key's value matches an expected value + * before allowing transformations to proceed. + * + * @author DiffusionData Limited + */ +public class TopicViewsDslPatchTransformationTestExample { + + private static final Logger LOG = + LoggerFactory.getLogger(TopicViewsDslPatchTransformationTestExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Topics topics = session.feature(Topics.class); + final String viewSelector = "?views//"; + final Topics.ValueStream valueStream = new MyStream(); + + final JSON jsonValue = Diffusion.dataTypes().json() + .fromJsonString("{\"Fred\":\"Flintstone\",\"Barney\":\"Rubble\",\"George\":\"Jetson\"}"); + + topics.addAndSet("my/topic/path", + Diffusion.newTopicSpecification(TopicType.JSON), + JSON.class, jsonValue) + .join(); + + topics.addStream(viewSelector, JSON.class, valueStream); + topics.subscribe(viewSelector).join(); + + final TopicView view = topics.createTopicView("topic_view_1", + "map ?my/topic/path// to views/ patch " + + "'[{\"op\": \"test\", \"path\": \"/Fred\", \"value\": \"Flintstone\" }]'") + .join(); + + LOG.info("Topic View {} has been created", view.getName()); + + SECONDS.sleep(1); + + topics.removeStream(valueStream); + session.close(); + } + + private static final class MyStream implements Topics.ValueStream { + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + LOG.info("{} new value {}", topicPath, newValue.toJsonString()); + } + + @Override + public void onSubscription(String topicPath, + TopicSpecification topicSpecification) { + LOG.info("Subscribed to {}", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + LOG.info("Unsubscribed from {}", topicPath); + } + + @Override + public void onClose() { + LOG.info("stream closed"); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("stream error: {}", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslProcessTransformationContinueExample.java b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslProcessTransformationContinueExample.java new file mode 100644 index 00000000..7b251c07 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslProcessTransformationContinueExample.java @@ -0,0 +1,129 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.topicviews.dsl; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.views.TopicView; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to use the process transformation with a continue condition + * in a topic view. + *

+ * A topic view is created that filters topics based on the value of the `/price_per_share` field, + * only allowing topics where the price is greater than 20 to be included in the view. + * + * @author DiffusionData Limited + */ +public class TopicViewsDslProcessTransformationContinueExample { + + private static final Logger LOG = + LoggerFactory.getLogger(TopicViewsDslProcessTransformationContinueExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Topics topics = session.feature(Topics.class); + final String viewSelector = "?views//"; + final Topics.ValueStream valueStream = new MyStream(); + + final TopicSpecification mySpec = Diffusion + .newTopicSpecification(TopicType.JSON); + + final JSON jsonValue1 = Diffusion.dataTypes().json() + .fromJsonString("{\n" + + " \"name\": \"APPL\",\n" + + " \"quantity\": 100,\n" + + " \"price_per_share\": 12.34\n" + + "}"); + + topics.addAndSet("my/topic/path/1", mySpec, JSON.class, jsonValue1).join(); + + final JSON jsonValue2 = Diffusion.dataTypes().json() + .fromJsonString("{\n" + + " \"name\": \"AMZN\",\n" + + " \"quantity\": 256,\n" + + " \"price_per_share\": 87.65\n" + + "}"); + + topics.addAndSet("my/topic/path/2", mySpec, JSON.class, jsonValue2).join(); + + topics.addStream(viewSelector, JSON.class, valueStream); + topics.subscribe(viewSelector).join(); + + final TopicView view = topics.createTopicView("topic_view_1", + "map ?my/topic/path// to views/ process\n" + + "{\n" + + " if '/price_per_share > 20' continue\n" + + "}") + .join(); + + LOG.info("Topic View {} has been created", view.getName()); + + SECONDS.sleep(1); + + topics.removeStream(valueStream); + session.close(); + } + + private static final class MyStream implements Topics.ValueStream { + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + LOG.info("{} new value {}", topicPath, newValue.toJsonString()); + } + + @Override + public void onSubscription(String topicPath, + TopicSpecification topicSpecification) { + LOG.info("Subscribed to {}", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + LOG.info("Unsubscribed from {}", topicPath); + } + + @Override + public void onClose() { + LOG.info("stream closed"); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("stream error: {}", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslProcessTransformationRemoveExample.java b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslProcessTransformationRemoveExample.java new file mode 100644 index 00000000..1451f89f --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslProcessTransformationRemoveExample.java @@ -0,0 +1,131 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.topicviews.dsl; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.views.TopicView; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to use the process transformation to remove fields + * from a JSON topic in a topic view. + *

+ * A topic view is created that calculates a new field `/total` by multiplying + * `/quantity` and `/price_per_share`, then removes the `/quantity` and `/price_per_share` + * fields from the JSON structure. + * + * @author DiffusionData Limited + */ +public class TopicViewsDslProcessTransformationRemoveExample { + + private static final Logger LOG = + LoggerFactory.getLogger(TopicViewsDslProcessTransformationRemoveExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Topics topics = session.feature(Topics.class); + final String viewSelector = "?views//"; + final Topics.ValueStream valueStream = new MyStream(); + + final TopicSpecification mySpec = Diffusion + .newTopicSpecification(TopicType.JSON); + + final JSON jsonValue1 = Diffusion.dataTypes().json() + .fromJsonString("{\n" + + " \"name\": \"APPL\",\n" + + " \"quantity\": 100,\n" + + " \"price_per_share\": 12.34\n" + + "}"); + + topics.addAndSet("my/topic/path/1", mySpec, JSON.class, jsonValue1).join(); + + final JSON jsonValue2 = Diffusion.dataTypes().json() + .fromJsonString("{\n" + + " \"name\": \"AMZN\",\n" + + " \"quantity\": 256,\n" + + " \"price_per_share\": 87.65\n" + + "}"); + + topics.addAndSet("my/topic/path/2", mySpec, JSON.class, jsonValue2).join(); + topics.addStream(viewSelector, JSON.class, valueStream); + topics.subscribe(viewSelector).join(); + + final TopicView view = topics.createTopicView("topic_view_1", + "map ?my/topic/path// to views/ process\n" + + "{\n" + + " set(/total, calc '/quantity * /price_per_share');\n" + + " remove(/quantity);\n" + + " remove(/price_per_share)\n" + + "}") + .join(); + + LOG.info("Topic View {} has been created", view.getName()); + + SECONDS.sleep(1); + + topics.removeStream(valueStream); + session.close(); + } + + private static final class MyStream implements Topics.ValueStream { + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + LOG.info("{} new value {}", topicPath, newValue.toJsonString()); + } + + @Override + public void onSubscription(String topicPath, + TopicSpecification topicSpecification) { + LOG.info("Subscribed to {}", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + LOG.info("Unsubscribed from {}", topicPath); + } + + @Override + public void onClose() { + LOG.info("stream closed"); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("stream error: {}", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslProcessTransformationSetExample.java b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslProcessTransformationSetExample.java new file mode 100644 index 00000000..39f7a248 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslProcessTransformationSetExample.java @@ -0,0 +1,138 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.topicviews.dsl; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.views.TopicView; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to use the process transformation to set new fields + * in a JSON topic within a topic view. + *

+ * A topic view is created that assigns a Tier value based on the balance amount, + * and calculates the amount in cents as a new field. + * + * @author DiffusionData Limited + */ +public class TopicViewsDslProcessTransformationSetExample { + + private static final Logger LOG = + LoggerFactory.getLogger(TopicViewsDslProcessTransformationSetExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Topics topics = session.feature(Topics.class); + final String viewSelector = "?views//"; + final Topics.ValueStream valueStream = new MyStream(); + + final TopicSpecification mySpec = Diffusion + .newTopicSpecification(TopicType.JSON); + + final JSON jsonValue1 = Diffusion.dataTypes().json() + .fromJsonString("{\n" + + " \"account\": \"1234\"," + + " \"balance\": {" + + " \"amount\": 12.57," + + " \"currency\": \"USD\"" + + " }" + + "}"); + + topics.addAndSet("my/topic/path/1", mySpec, JSON.class, jsonValue1).join(); + + final JSON jsonValue2 = Diffusion.dataTypes().json() + .fromJsonString("{\n" + + " \"account\": \"5678\"," + + " \"balance\": {" + + " \"amount\": 98.76," + + " \"currency\": \"USD\"" + + " }" + + "}"); + + topics.addAndSet("my/topic/path/2", mySpec, JSON.class, jsonValue2).join(); + topics.addStream(viewSelector, JSON.class, valueStream); + topics.subscribe(viewSelector).join(); + + final TopicView myTopicView = topics.createTopicView("topic_view_1", + "map ?my/topic/path// to views/ process {\n" + + " if '/balance/amount > 20'\n" + + " set(/Tier, 1)\n" + + " else\n" + + " set(/Tier, 2)\n" + + "}\n" + + "process {\n" + + " set(/balance/amount_in_cents, calc '/balance/amount * " + + "100')\n" + + "}") + .join(); + + LOG.info("Topic View {} has been created", myTopicView.getName()); + + SECONDS.sleep(1); + + topics.removeStream(valueStream); + session.close(); + } + + private static final class MyStream implements Topics.ValueStream { + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + LOG.info("{} new value {}", topicPath, newValue.toJsonString()); + } + + @Override + public void onSubscription(String topicPath, + TopicSpecification topicSpecification) { + LOG.info("Subscribed to {}", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + LOG.info("Unsubscribed from {}", topicPath); + } + + @Override + public void onClose() { + LOG.info("stream closed"); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("stream error: {}", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslRemoteTopicViewExample.java b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslRemoteTopicViewExample.java new file mode 100644 index 00000000..b704e231 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslRemoteTopicViewExample.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.topicviews.dsl; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.features.control.RemoteServers; +import com.pushtechnology.diffusion.client.features.control.topics.views.TopicView; +import com.pushtechnology.diffusion.client.features.control.topics.views.TopicViews; +import com.pushtechnology.diffusion.client.session.Session; + +/** + * This example demonstrates how to create a topic view that maps topics from a remote server. + *

+ * A remote server connection is established, and a topic view is created to map + * topics from the remote server to a local topic path. + * + * @author DiffusionData Limited + */ +public class TopicViewsDslRemoteTopicViewExample { + + private static final Logger LOG = + LoggerFactory.getLogger(TopicViewsDslRemoteTopicViewExample.class); + + public static void main(String[] args) throws Exception { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final String remoteTopicViewName = "remote_topic_view_1"; + + final RemoteServers.RemoteServer remoteServer = + Diffusion.newRemoteServerBuilder(RemoteServers.SecondaryInitiator.SecondaryInitiatorBuilder.class) + .principal("admin").credentials(Diffusion.credentials().password("password")) + .connectionOption(RemoteServers.RemoteServer.ConnectionOption.RECONNECTION_TIMEOUT, "120000") + .connectionOption(RemoteServers.RemoteServer.ConnectionOption.MAXIMUM_QUEUE_SIZE, "1000") + .connectionOption(RemoteServers.RemoteServer.ConnectionOption.CONNECTION_TIMEOUT, "15000") + .build("Remote Server 1", "ws://new.server.url.com"); + + session.feature(RemoteServers.class).createRemoteServer(remoteServer) + .join(); + + final TopicView view = session.feature(TopicViews.class).createTopicView( + remoteTopicViewName, + "map my/topic/path from 'Remote Server 1' to views/remote/") + .join(); + + LOG.info("Remote Topic View '{}' has been created.", view.getName()); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslScalarDirectiveExample.java b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslScalarDirectiveExample.java new file mode 100644 index 00000000..ae26f41e --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslScalarDirectiveExample.java @@ -0,0 +1,119 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.topicviews.dsl; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.features.control.topics.views.TopicView; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to use the scalar directive in a topic view. + *

+ * A JSON topic is created with account and balance information. The scalar directive + * is used to dynamically create topic paths based on the account number and currency. + * + * @author DiffusionData Limited + */ +public class TopicViewsDslScalarDirectiveExample { + + private static final Logger LOG = + LoggerFactory.getLogger(TopicViewsDslScalarDirectiveExample.class); + + public static void main(String[] args) throws Exception { + + final Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080"); + + final Topics topics = session.feature(Topics.class); + final String viewSelector = "?views//"; + final Topics.ValueStream valueStream = new MyStream(); + + final JSON jsonValue = Diffusion.dataTypes().json() + .fromJsonString("{\n" + + " \"account\": \"1234\"," + + " \"balance\": {" + + " \"amount\": 12.57," + + " \"currency\": \"USD\"" + + " }" + + "}"); + + topics.addAndSet("my/topic/path", + Diffusion.newTopicSpecification(TopicType.JSON), + JSON.class, jsonValue) + .join(); + + topics.addStream(viewSelector, JSON.class, valueStream); + topics.subscribe(viewSelector).join(); + + final TopicView myTopicView = topics.createTopicView("topic_view_1", + " map my/topic/path to " + + "views/currency//account/") + .join(); + + LOG.info("Topic View {} has been created", myTopicView.getName()); + + SECONDS.sleep(1); + + topics.removeStream(valueStream); + session.close(); + } + + private static final class MyStream implements Topics.ValueStream { + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + LOG.info("{} new value {}", topicPath, newValue.toJsonString()); + } + + @Override + public void onSubscription(String topicPath, + TopicSpecification topicSpecification) { + LOG.info("Subscribed to {}", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + LOG.info("Unsubscribed from {}", topicPath); + } + + @Override + public void onClose() { + LOG.info("stream closed"); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("stream error: {}", errorReason); + } + } +} diff --git a/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslSourcePathDirectiveExample.java b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslSourcePathDirectiveExample.java new file mode 100644 index 00000000..92a67a94 --- /dev/null +++ b/java/com/pushtechnology/client/sdk/example/topicviews/dsl/TopicViewsDslSourcePathDirectiveExample.java @@ -0,0 +1,127 @@ +/******************************************************************************* + * Copyright (C) 2023 - 2024 DiffusionData Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ +package com.pushtechnology.client.sdk.example.topicviews.dsl; + +import static java.util.concurrent.TimeUnit.SECONDS; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.pushtechnology.diffusion.client.Diffusion; +import com.pushtechnology.diffusion.client.callbacks.ErrorReason; +import com.pushtechnology.diffusion.client.features.Topics; +import com.pushtechnology.diffusion.client.session.Session; +import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; +import com.pushtechnology.diffusion.client.topics.details.TopicType; +import com.pushtechnology.diffusion.datatype.json.JSON; + +/** + * This example demonstrates how to use the source path directive in a topic view. + *

+ * A JSON topic is created at a deep path. The source path directive is used to extract + * different segments of the path to dynamically generate new topic paths. + * + * @author DiffusionData Limited + */ +public class TopicViewsDslSourcePathDirectiveExample { + + private static final Logger LOG = + LoggerFactory.getLogger(TopicViewsDslSourcePathDirectiveExample.class); + + public static void main(String[] args) throws Exception { + + try (Session session = Diffusion.sessions() + .principal("admin") + .password("password") + .open("ws://localhost:8080")) { + + final JSON originalCastJsonValue = Diffusion.dataTypes().json().fromJsonString("{\n" + + " \"account\": \"1234\"," + + " \"balance\": {" + + " \"amount\": 12.57," + + " \"currency\": \"USD\"" + + " }" + + "}"); + + final Topics topics = session.feature(Topics.class); + final String viewSelector = "?views//"; + final Topics.ValueStream valueStream = new MyStream(); + + topics.addAndSet( + "a/b/c/d/e/f/g", + Diffusion.newTopicSpecification(TopicType.JSON), + JSON.class, originalCastJsonValue) + .join(); + + topics.addStream(viewSelector, JSON.class, valueStream); + topics.subscribe(viewSelector).join(); + + final String[] topicViewExpressionMappings = new String[]{ + "map a/b/c/d/e/f/g to views/", + "map a/b/c/d/e/f/g to views/", + "map a/b/c/d/e/f/g to views/" + }; + + for (int i = 0; i < topicViewExpressionMappings.length; i++) { + final String topicViewName = "topic_view_" + (i + 1); + final String topicViewExpressionMapping = topicViewExpressionMappings[i]; + + topics.createTopicView(topicViewName, + topicViewExpressionMapping) + .join(); + + LOG.info("Topic View {} has been created.", topicViewName); + } + + topics.removeStream(valueStream); + SECONDS.sleep(1); + } + } + + static class MyStream implements Topics.ValueStream { + + @Override + public void onValue( + String topicPath, + TopicSpecification topicSpecification, + JSON oldValue, + JSON newValue) { + LOG.info("{} new value {}", topicPath, newValue.toJsonString()); + } + + @Override + public void onSubscription(String topicPath, + TopicSpecification topicSpecification) { + LOG.info("Subscribed to {}", topicPath); + } + + @Override + public void onUnsubscription(String topicPath, + TopicSpecification topicSpecification, + Topics.UnsubscribeReason unsubscribeReason) { + LOG.info("Unsubscribed from {}", topicPath); + } + + @Override + public void onClose() { + LOG.info("stream closed"); + } + + @Override + public void onError(ErrorReason errorReason) { + LOG.error("stream error: {}", errorReason); + } + } +} diff --git a/java/pom.xml b/java/pom.xml deleted file mode 100644 index a222523a..00000000 --- a/java/pom.xml +++ /dev/null @@ -1,105 +0,0 @@ - - 4.0.0 - - - com.pushtechnology.sample - sample-parent - 1.10 - - - com.pushtechnology.diffusion - diffusion-api-java-examples - 6.9.8 - jar - Diffusion public API examples. - - - - push-repository - https://download.pushtechnology.com/maven/ - - - - - - net.jcip - jcip-annotations - - - - org.slf4j - slf4j-api - - - - com.pushtechnology.diffusion - diffusion-api - 6.9.0 - - - - com.fasterxml.jackson.core - jackson-databind - 2.9.7 - - - - com.fasterxml.jackson.dataformat - jackson-dataformat-cbor - 2.9.7 - - - - com.pushtechnology.diffusion - diffusion-client - 6.9.8 - runtime - - - - org.json - json - 20160810 - - - - - ch.qos.logback - logback-classic - 1.0.13 - runtime - - - - - - - - org.codehaus.mojo - exec-maven-plugin - 1.4.0 - - - - java - - - - - com.pushtechnology.diffusion.gettingstarted.PublishingClient - - - - - diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ClientConsumingJSONTopics.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ClientConsumingJSONTopics.java deleted file mode 100644 index 0c9b9cfd..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ClientConsumingJSONTopics.java +++ /dev/null @@ -1,163 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2016 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import static java.util.Objects.requireNonNull; - -import java.io.IOException; -import java.math.BigDecimal; -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.dataformat.cbor.CBORFactory; -import com.fasterxml.jackson.dataformat.cbor.CBORParser; -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.Topics; -import com.pushtechnology.diffusion.client.features.Topics.UnsubscribeReason; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; -import com.pushtechnology.diffusion.datatype.json.JSON; - -/** - * This demonstrates a client consuming JSON topics. - *

- * It is assumed that under the FX topic there is a JSON topic for each currency - * which contains a map of conversion rates to each target currency. For - * example, FX/GBP could contain {"USD":"123.45","HKD":"456.3"}. - *

- * All updates will be notified to a listener. - * - * @author DiffusionData Limited - * @since 5.7 - * @see ControlClientUpdatingJSONTopics - */ -public final class ClientConsumingJSONTopics { - - private static final Logger LOG = - LoggerFactory.getLogger(ClientConsumingJSONTopics.class); - - private static final String ROOT_TOPIC = "FX"; - private static final String TOPIC_SELECTOR = String.format("?%s/", ROOT_TOPIC); - - private final RatesListener listener; - - private final Session session; - - /** - * Constructor. - * - * @param serverUrl for example "ws://diffusion.example.com:80 - */ - public ClientConsumingJSONTopics(String serverUrl, RatesListener listener) { - - this.listener = requireNonNull(listener); - - session = - Diffusion.sessions().principal("client").password("password") - .open(serverUrl); - - // Use the Topics feature to add a topic stream and subscribe to all - // topics under the root - final Topics topics = session.feature(Topics.class); - topics.addStream(TOPIC_SELECTOR, JSON.class, new RatesStream()); - - topics.subscribe(TOPIC_SELECTOR) - .whenComplete((voidResult, exception) -> { - if (exception != null) { - LOG.info("subscription failed", exception); - } - }); - } - - /** - * Close session. - */ - public void close() { - session.close(); - } - - private static String pathToCurrency(String path) { - return path.substring(path.indexOf('/') + 1); - } - - /** - * A listener for Rates updates. - */ - public interface RatesListener { - - /** - * Notification of a new rate or rate update. - * - * @param currency the base currency - * @param rates map of rates - */ - void onNewRates(String currency, Map rates); - - /** - * Notification of a rate being removed. - * - * @param currency the base currency - */ - void onRatesRemoved(String currency); - } - - /** - * The value stream. - */ - private final class RatesStream extends Topics.ValueStream.Default { - - private final CBORFactory factory = new CBORFactory(); - private final ObjectMapper mapper = new ObjectMapper(); - private final TypeReference> typeReference = - new TypeReference>() { - }; - - @Override - public void onValue( - String topicPath, - TopicSpecification specification, - JSON oldValue, - JSON newValue) { - try { - // Use the third-party Jackson library to parse the newValue's - // binary representation and convert to a map - final CBORParser parser = - factory.createParser(newValue.asInputStream()); - final Map map = - mapper.readValue(parser, typeReference); - final String currency = pathToCurrency(topicPath); - listener.onNewRates(currency, map); - } - catch (IOException ex) { - ex.printStackTrace(); - } - } - - @Override - public void onUnsubscription( - String topicPath, - TopicSpecification specification, - UnsubscribeReason reason) { - - final String currency = pathToCurrency(topicPath); - listener.onRatesRemoved(currency); - } - - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ClientConsumingRecordV2Topics.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ClientConsumingRecordV2Topics.java deleted file mode 100644 index db0116d3..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ClientConsumingRecordV2Topics.java +++ /dev/null @@ -1,408 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2017 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import static java.util.Objects.requireNonNull; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.Topics; -import com.pushtechnology.diffusion.client.features.Topics.UnsubscribeReason; -import com.pushtechnology.diffusion.client.features.Topics.ValueStream; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; -import com.pushtechnology.diffusion.datatype.recordv2.RecordV2; -import com.pushtechnology.diffusion.datatype.recordv2.RecordV2Delta; -import com.pushtechnology.diffusion.datatype.recordv2.RecordV2Delta.Change; -import com.pushtechnology.diffusion.datatype.recordv2.model.RecordModel; -import com.pushtechnology.diffusion.datatype.recordv2.schema.Schema; -import com.pushtechnology.diffusion.datatype.recordv2.schema.SchemaParseException; - -/** - * This demonstrates a client consuming RecordV2 topics. - *

- * It has been contrived to demonstrate the various techniques for Diffusion - * record topics and is not necessarily realistic or efficient in its - * processing. - *

- * It can be run using a schema or not using a schema and demonstrates how the - * processing could be done in both cases. - *

- * This makes use of the 'Topics' feature only. - *

- * To subscribe to a topic, the client session must have the 'select_topic' and - * 'read_topic' permissions for that branch of the topic tree. - *

- * This example receives updates to currency conversion rates via a branch of - * the topic tree where the root topic is called "FX" which under it has a topic - * for each base currency and under each of those is a topic for each target - * currency which contains the bid and ask rates. So a topic FX/GBP/USD would - * contain the rates for GBP to USD. - *

- * This example maintains a local map of the rates and also notifies a listener - * of any rates changes. - * - * @author DiffusionData Limited - * @since 6.0 - * @see ControlClientUpdatingRecordV2Topics - */ -public final class ClientConsumingRecordV2Topics { - - private static final Logger LOG = - LoggerFactory.getLogger(ClientConsumingRecordV2Topics.class); - - private static final String ROOT_TOPIC = "FX"; - - /** - * The map of currency codes to currency objects which each maintain rates - * for each target currency. - */ - private final Map currencies = new ConcurrentHashMap<>(); - - private Schema schema; - - private final RatesListener listener; - - private final Session session; - - /** - * Constructor. - * - * @param serverUrl for example "ws://diffusion.example.com:80" - * @param listener a listener that will be notified of all rates and rate - * changes - */ - public ClientConsumingRecordV2Topics(String serverUrl, - RatesListener listener) { - - this.listener = requireNonNull(listener); - - session = - Diffusion.sessions().principal("client").password("password") - .open(serverUrl); - - // Use the Topics feature to add a record value stream and subscribe to - // all topics under the root. - final Topics topics = session.feature(Topics.class); - final String topicSelector = String.format("?%s//", ROOT_TOPIC); - - topics.addStream( - topicSelector, - RecordV2.class, - new RatesValueStream()); - - topics.subscribe(topicSelector) - .whenComplete((voidResult, exception) -> { - if (exception != null) { - LOG.info("subscription failed", exception); - } - }); - } - - /** - * Returns the rates for a given base and target currency. - * - * @param currency the base currency - * @param targetCurrency the target currency - * @return the rates or null if there is no such base or target currency - */ - public Rates getRates(String currency, String targetCurrency) { - final Currency currencyObject = currencies.get(currency); - if (currencyObject != null) { - return currencyObject.getRates(targetCurrency); - } - return null; - } - - /** - * This is used to apply topic stream updates to the local map and notify - * listener of changes. - */ - private void applyUpdate( - String currency, - String targetCurrency, - RecordV2 oldValue, - RecordV2 newValue) { - - Currency currencyObject = currencies.get(currency); - if (currencyObject == null) { - currencyObject = new Currency(); - currencies.put(currency, currencyObject); - } - - if (schema == null) { - updateWithoutSchema( - currency, - targetCurrency, - oldValue, - newValue, - currencyObject); - } - else { - updateWithSchema( - currency, - targetCurrency, - oldValue, - newValue, - currencyObject); - } - } - - private void updateWithSchema( - String currency, - String targetCurrency, - RecordV2 oldValue, - RecordV2 newValue, - Currency currencyObject) { - - // A data model is generated using the schema allowing direct access to - // the fields within it - final RecordModel model = newValue.asModel(schema); - final String bid = model.get("Bid"); - final String ask = model.get("Ask"); - - currencyObject.setRate(targetCurrency, bid, ask); - - if (oldValue == null) { - listener.onNewRate(currency, targetCurrency, bid, ask); - } - else { - // Generate a structural delta to determine what has changed - final RecordV2Delta delta = newValue.diff(oldValue); - for (Change change : delta.changes(schema)) { - final String fieldName = change.fieldName(); - listener.onRateChange( - currency, - targetCurrency, - fieldName, - model.get(fieldName)); - } - } - } - - private void updateWithoutSchema( - String currency, - String targetCurrency, - RecordV2 oldValue, - RecordV2 newValue, - Currency currencyObject) { - - // All of the fields in the value are obtained. - final List fields = newValue.asFields(); - final String bid = fields.get(0); - final String ask = fields.get(1); - - currencyObject.setRate(targetCurrency, bid, ask); - - if (oldValue == null) { - listener.onNewRate(currency, targetCurrency, bid, ask); - } - else { - // Fields in the old value are obtained to determine what has - // changed - final List oldfields = oldValue.asFields(); - final String oldBid = oldfields.get(0); - final String oldAsk = oldfields.get(1); - if (!bid.equals(oldBid)) { - listener.onRateChange(currency, targetCurrency, "Bid", bid); - } - if (!ask.equals(oldAsk)) { - listener.onRateChange(currency, targetCurrency, "Ask", ask); - } - } - } - - private void removeCurrency(String currency) { - final Currency oldCurrency = currencies.remove(currency); - for (String targetCurrency : oldCurrency.rates.keySet()) { - listener.onRateRemoved(currency, targetCurrency); - } - } - - private void removeRate( - String currency, - String targetCurrency) { - - final Currency currencyObject = currencies.get(currency); - if (currencyObject != null) { - if (currencyObject.rates.remove(targetCurrency) != null) { - listener.onRateRemoved(currency, targetCurrency); - } - } - } - - /** - * Close session. - */ - public void close() { - currencies.clear(); - session.close(); - } - - /** - * Encapsulates a base currency and all of its known rates. - */ - private static class Currency { - - private final Map rates = new HashMap<>(); - - private Rates getRates(String currency) { - return rates.get(currency); - } - - private void setRate(String currency, String bid, String ask) { - rates.put(currency, new Rates(bid, ask)); - } - - } - - /** - * Encapsulates the rates for a particular base/target currency pair. - */ - public static final class Rates { - - private final String bidRate; - private final String askRate; - - /** - * Constructor. - * - * @param bid the bid rate or "" - * @param ask the ask rate or "" - */ - private Rates(String bid, String ask) { - bidRate = bid; - askRate = ask; - } - - /** - * Returns the bid rate. - * - * @return bid rate or "" if not available - */ - public String getBidRate() { - return bidRate; - } - - /** - * Returns the ask rate. - * - * @return ask rate or "" if not available - */ - public String getAskRate() { - return askRate; - } - - } - - /** - * A listener for Rates updates. - */ - public interface RatesListener { - - /** - * Notification of a new rate or rate update. - * - * @param currency the base currency - * @param targetCurrency the target currency - * @param bid rate - * @param ask rate - */ - void onNewRate(String currency, String targetCurrency, String bid, - String ask); - - /** - * Notification of a change to the bid or ask value for a rate. - * - * @param currency the base currency - * @param targetCurrency the target currency - * @param bidOrAsk "Bid" or "Ask" - * @param rate the new rate - */ - void onRateChange(String currency, String targetCurrency, - String bidOrAsk, String rate); - - /** - * Notification of a rate being removed. - * - * @param currency the base currency - * @param targetCurrency the target currency - */ - void onRateRemoved(String currency, String targetCurrency); - } - - private final class RatesValueStream - extends ValueStream.Default { - - @Override - public void onSubscription(String topicPath, TopicSpecification specification) { - final boolean isRatesTopic = Diffusion.topicSelectors().parse("?FX/.*/.*").selects(topicPath); - // Only retrieve a schema when subscribing to a rates topic - if (isRatesTopic) { - final String schemaString = specification.getProperties().get(TopicSpecification.SCHEMA); - // If a schema is provided on subscription, retrieve it and set it once - // All schemas are identical for rates topics. - if (schemaString != null && schema == null) { - try { - schema = Diffusion.dataTypes().recordV2().parseSchema(schemaString); - } - catch (SchemaParseException e) { - LOG.error("Unable to parse recordV2 schema", e); - } - } - } - } - - @Override - public void onValue(String topicPath, TopicSpecification specification, - RecordV2 oldValue, RecordV2 newValue) { - final String[] topicElements = elements(topicPath); - // It is only a rate update if topic has 2 elements below root path - if (topicElements.length == 2) { - applyUpdate( - topicElements[0], // The base currency - topicElements[1], // The target currency - oldValue, - newValue); - } - } - - @Override - public void onUnsubscription(String topicPath, - TopicSpecification specification, UnsubscribeReason reason) { - final String[] topicElements = elements(topicPath); - if (topicElements.length == 2) { - removeRate(topicElements[0], topicElements[1]); - } - else if (topicElements.length == 1) { - removeCurrency(topicElements[0]); - } - } - - private String[] elements(String topicPath) { - final String subPath = - topicPath.replaceFirst("^" + ROOT_TOPIC + "/", ""); - return subPath.split("/"); - } - } - -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ClientConsumingSimpleTopics.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ClientConsumingSimpleTopics.java deleted file mode 100644 index e7824bfb..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ClientConsumingSimpleTopics.java +++ /dev/null @@ -1,102 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2017 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.Topics; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; -import com.pushtechnology.diffusion.client.topics.details.TopicType; - -/** - * This demonstrates a client consuming simple scalar topics. - *

- * All updates will be routed to listeners appropriate for the topic type. - *

- * This example shows a client consuming a {@link TopicType#STRING STRING} topic - * but the same technique could be used for {@link TopicType#INT64 INT64} or - * {@link TopicType#DOUBLE DOUBLE} topics. - * - * @author DiffusionData Limited - * @since 6.0 - * @see ControlClientUpdatingSimpleTopics - */ -public final class ClientConsumingSimpleTopics { - - private static final Logger LOG = - LoggerFactory.getLogger(ClientConsumingSimpleTopics.class); - - private final Session session; - - /** - * Constructor. - * - * @param serverUrl for example "ws://diffusion.example.com:80 - */ - public ClientConsumingSimpleTopics( - String serverUrl, - final StringListener stringListener) { - - session = - Diffusion.sessions().principal("client").password("password") - .open(serverUrl); - - // Use the Topics feature to add stream and subscribe to the topic. - final Topics topics = session.feature(Topics.class); - - topics.addStream( - "StringTopic", - String.class, - new Topics.ValueStream.Default() { - @Override - public void onValue( - String topicPath, - TopicSpecification specification, - String oldValue, - String newValue) { - - stringListener.onNewValue(topicPath, newValue); - } - }); - - topics.subscribe("StringTopic") - .whenComplete((voidResult, exception) -> { - if (exception != null) { - LOG.info("subscription failed", exception); - } - }); - } - - /** - * Close session. - */ - public void close() { - session.close(); - } - - /** - * A listener for string values. - */ - public interface StringListener { - - /** - * Notification of a new String value. - */ - void onNewValue(String topic, String value); - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ClientConsumingTimeSeriesTopics.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ClientConsumingTimeSeriesTopics.java deleted file mode 100644 index e15038df..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ClientConsumingTimeSeriesTopics.java +++ /dev/null @@ -1,65 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2017 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.TimeSeries; -import com.pushtechnology.diffusion.client.features.TimeSeries.Event; -import com.pushtechnology.diffusion.client.features.Topics; -import com.pushtechnology.diffusion.client.features.Topics.ValueStream; -import com.pushtechnology.diffusion.client.session.Session; - -/** - * This demonstrates a client session subscribing to a - * {@link TimeSeries} topic. - * - * @author DiffusionData Limited - * @since 6.0 - * @see ControlClientUpdatingTimeSeriesTopics - * @see TimeSeriesQueryExample - */ -public class ClientConsumingTimeSeriesTopics { - - private static final String TOPIC_PATH = "foo/timeseries"; - - private Session session; - - /** - * Constructor. - * - * @param serverUrl for example "ws://diffusion.example.com:80" - * @param valueStream value stream to receive time series topic events - */ - public ClientConsumingTimeSeriesTopics(String serverUrl, ValueStream> valueStream) - throws InterruptedException, ExecutionException, TimeoutException { - session = Diffusion.sessions().principal("client").password("password") - .open(serverUrl); - - final Topics topics = session.feature(Topics.class); - topics.addTimeSeriesStream(TOPIC_PATH, Long.class, valueStream); - topics.subscribe(TOPIC_PATH).get(5, TimeUnit.SECONDS); - } - - /** - * Close the session. - */ - public void close() { - session.close(); - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ClientCreatingRecordV2Schema.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ClientCreatingRecordV2Schema.java deleted file mode 100644 index 1f69c6d8..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ClientCreatingRecordV2Schema.java +++ /dev/null @@ -1,147 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2017 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.datatype.recordv2.RecordV2DataType; -import com.pushtechnology.diffusion.datatype.recordv2.schema.Schema; -import com.pushtechnology.diffusion.datatype.recordv2.schema.SchemaBuilder; - -/** - * This example class has a number of methods that demonstrate the creation of - * schemas for RECORD_V2 topics, using the Diffusion Client API. - *

- * Note that no client session is required in order to create a schema. - * - * @author DiffusionData Limited - * @since 6.0 - */ -public final class ClientCreatingRecordV2Schema { - - private final RecordV2DataType dataType = Diffusion.dataTypes().recordV2(); - - /** - * Constructor. - */ - public ClientCreatingRecordV2Schema() { - } - - /** - * Example of a schema consisting of a single record with three fields each - * of s different data type. - * - * @return a schema - */ - public Schema createSimpleSchema() { - final SchemaBuilder builder = dataType.schemaBuilder(); - return builder - .record("Record") - .string("string").integer("integer").decimal("decimal", 3) - .build(); - } - - /** - * Example of a schema consisting of multiple records, each record with a - * single field of a specific type. - * - * @return a schema - */ - public Schema createMultipleRecordsSchema() { - final SchemaBuilder builder = dataType.schemaBuilder(); - return builder - .record("StringRecord").string("string") - .record("IntegerRecord").integer("integer") - .record("DecimalRecord").decimal("decimal", 3) - .build(); - } - - /** - * Example of a schema consisting of a record (with a single string field) - * repeating exactly 10 times. - * - * @return a schema - */ - public Schema createFixedRepeatingRecordsSchema() { - final SchemaBuilder builder = dataType.schemaBuilder(); - return builder - .record("RepeatingRecord", 10).string("string") - .build(); - } - - /** - * Example of a schema consisting of 2 record types. "FixedRecord" is a - * record that occurs 5 times. "RepeatingRecord" is an optional record that - * can be repeated as many times as required (unlimited). - * - * @return a schema - */ - public Schema createVariableRepeatingRecordsSchema() { - final SchemaBuilder builder = dataType.schemaBuilder(); - return builder - .record("FixedRecord", 5).string("a") - .record("RepeatingRecord", 0, -1).string("b") - .build(); - } - - /** - * Example of a schema consisting of a single record with a string field - * that occurs exactly 10 times. - * - * @return a schema - */ - public Schema createFixedRepeatingFieldsSchema() { - final SchemaBuilder builder = dataType.schemaBuilder(); - return builder - .record("Record").string("repeatingString", 10) - .build(); - } - - /** - * Example of a schema consisting of two records. The first record (A) has a - * field, "repeatingField", which can occur between 2 and 5 times. The - * second record (B) has a field, "repeatingFieldUnlimited", which can occur - * as many times as required but at least once. - * - * @return a schema - */ - public Schema createVariableRepeatingFieldsSchema() { - final SchemaBuilder builder = dataType.schemaBuilder(); - return builder - .record("A").string("repeatingField", 2, 5) - .record("B").string("repeatingFieldUnlimited", 1, -1) - .build(); - } - - /** - * Example of a schema consisting of a single record and multiple fields - * encapsulating a person's name and address. - * - * @return a schema - */ - public Schema createNameAndAddressSchema() { - final SchemaBuilder builder = dataType.schemaBuilder(); - return builder - .record("nameAndAddress") - .string("firstName") - .string("surname") - .integer("houseNumber") - .string("street") - .string("town") - .string("state") - .string("postCode") - .build(); - } - -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ClientRequestHandling.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ClientRequestHandling.java deleted file mode 100644 index 18aab6dc..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ClientRequestHandling.java +++ /dev/null @@ -1,129 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2017, 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.callbacks.ErrorReason; -import com.pushtechnology.diffusion.client.features.Messaging; -import com.pushtechnology.diffusion.client.features.Messaging.RequestStream; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.session.SessionId; -import com.pushtechnology.diffusion.datatype.json.JSON; - -/** - * This is a simple example of a client that uses the request/response - * API of the 'Messaging' feature to send requests to a topic path, and - * receive requests sent directly to the session. - *

- * To send a request on a topic path, the client session requires the - * 'send_to_message_handler' permission. - * - * @see ControlClientRequestHandling - * - * @author DiffusionData Limited - * @since 6.0 - */ -public class ClientRequestHandling { - - private static final Logger LOG = - LoggerFactory.getLogger(ClientRequestHandling.class); - - private final Session session; - private final Messaging messaging; - - /** - * Construct a request handling application. - * - * @param serverURL url of the server to connect to. - */ - public ClientRequestHandling(String serverURL) { - session = Diffusion.sessions().principal("client").password("password") - .open(serverURL); - messaging = session.feature(Messaging.class); - } - - /** - * Get the sessionId of the session. - * - * @return the session id of the session - */ - public SessionId getSessionId() { - return session.getSessionId(); - } - - /** - * Sets up a JSON {@link RequestStream} for a particular message path. - * - * @param messagePath message path to receive requests from - */ - public void setRequestStream(String messagePath) { - messaging.setRequestStream(messagePath, JSON.class, JSON.class, new JSONRequestStream()); - } - - /** - * Sends a simple JSON request to a specified message path. - * The response is logged when received. - * - * @param messagePath the message path - * @param request JSON request to send - * - * @return response to the request - */ - public JSON send(String messagePath, JSON request) - throws InterruptedException, ExecutionException, TimeoutException { - final JSON response = - messaging.sendRequest(messagePath, request, JSON.class, JSON.class).get(10, TimeUnit.SECONDS); - LOG.info("Response received: {}", response); - - return response; - } - - /** - * Close the session. - */ - public void close() { - session.close(); - } - - /** - * Request stream that logs received requests and echoes them back to the original client. - */ - private final class JSONRequestStream implements RequestStream { - - @Override - public void onClose() { - LOG.info("JSONRequestStream closed"); - } - - @Override - public void onError(ErrorReason errorReason) { - LOG.info("JSONRequestStream error: {}", errorReason); - } - - @Override - public void onRequest(String path, JSON request, Responder responder) { - LOG.info("Stream received request: {} on message path: {}", request.toJsonString(), path); - //Echo the request back to the requester - responder.respond(request); - } - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ClientSimpleSubscriber.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ClientSimpleSubscriber.java deleted file mode 100644 index 256abb5f..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ClientSimpleSubscriber.java +++ /dev/null @@ -1,104 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2014, 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.Topics; -import com.pushtechnology.diffusion.client.features.Topics.ValueStream; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; -import com.pushtechnology.diffusion.datatype.json.JSON; - -/** - * In this simple and commonest case for a client we just subscribe to a few - * topics and assign handlers for each to receive content. - *

- * This makes use of the 'Topics' feature only. - *

- * To subscribe to a topic, the client session must have the - * 'select_topic' and 'read_topic' permissions for that branch of the - * topic tree. - * - * @author DiffusionData Limited - * @since 5.0 - */ -public final class ClientSimpleSubscriber { - - private static final Logger LOG = - LoggerFactory.getLogger(ClientSimpleSubscriber.class); - - private final Session session; - - /** - * Constructor. - */ - public ClientSimpleSubscriber() { - - session = - Diffusion.sessions().principal("client").password("password") - .open("ws://diffusion.example.com:80"); - - // Use the Topics feature to add a topic stream for - // Foo and all topics under Bar and request subscription to those topics - final Topics topics = session.feature(Topics.class); - topics.addStream(">Foo", String.class, new FooStream()); - topics.addStream(">Bar//", JSON.class, new BarStream()); - - topics.subscribe(Diffusion.topicSelectors().anyOf("Foo", "Bar//")) - .whenComplete((voidResult, exception) -> { - if (exception != null) { - LOG.info("subscription failed", exception); - } - }); - } - - /** - * Close session. - */ - public void close() { - session.close(); - } - - /** - * The stream for all messages on the 'Foo' String topic. - */ - private class FooStream extends ValueStream.Default { - @Override - public void onValue( - String topicPath, - TopicSpecification specification, - String oldValue, - String newValue) { - LOG.info(newValue); - } - } - - /** - * The stream for all messages on 'Bar' topics which are JSON topics. - */ - private class BarStream extends ValueStream.Default { - @Override - public void onValue( - String topicPath, - TopicSpecification specification, - JSON oldValue, - JSON newValue) { - LOG.info(newValue.toJsonString()); - } - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ClientUsingCredentials.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ClientUsingCredentials.java deleted file mode 100644 index a29db333..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ClientUsingCredentials.java +++ /dev/null @@ -1,77 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2014, 2015 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import java.util.concurrent.ExecutionException; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.Security; -import com.pushtechnology.diffusion.client.session.Session; - -/** - * This demonstrates a client's use of credentials, specifically the ability to - * change the principal for an active session. - *

- * This is not a realistic use case on its own, but is shown separately here for - * clarity. - * - * @author DiffusionData Limited - * @since 5.0 - */ -public class ClientUsingCredentials { - - private final Session session; - private final Security security; - - /** - * Constructor. - */ - public ClientUsingCredentials(String serverUrl) { - session = - Diffusion.sessions().principal("client").password("password") - .open(serverUrl); - security = session.feature(Security.class); - } - - /** - * Request a change of principal for the session, blocking until a response - * is received. - * - * @param principal the new principal name - * @param password the password - * @return true if the principal was changed - * @throws InterruptedException if interrupted while waiting - * @throws ExecutionException if the ping failed. The chained - * {@link ExecutionException#getCause() cause} provides more - * information, e.g. SessionClosedException. - */ - public boolean changePrincipal( - String principal, - String password) throws InterruptedException, ExecutionException { - - return security.changePrincipal( - principal, - Diffusion.credentials().password(password)) - .get(); - } - - /** - * Close the session. - */ - public void close() { - session.close(); - } - -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ClientUsingFetch.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ClientUsingFetch.java deleted file mode 100644 index d5759e4c..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ClientUsingFetch.java +++ /dev/null @@ -1,247 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import static java.util.concurrent.TimeUnit.SECONDS; - -import java.util.EnumSet; -import java.util.List; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeoutException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.Topics; -import com.pushtechnology.diffusion.client.features.Topics.FetchResult; -import com.pushtechnology.diffusion.client.features.Topics.FetchResult.TopicResult; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.TopicSelector; -import com.pushtechnology.diffusion.client.topics.details.TopicType; -import com.pushtechnology.diffusion.datatype.Bytes; -import com.pushtechnology.diffusion.datatype.json.JSON; - -/** - * This provides various examples of using the new fetch capabilities introduced - * in release 6.2. - *

- * This makes use of the 'Topics' feature only. - * - * @author DiffusionData Limited - * @since 6.2 - */ -public final class ClientUsingFetch { - - private static final Logger LOG = - LoggerFactory.getLogger(ClientUsingFetch.class); - - private final Session session; - private final Topics topics; - - /** - * Constructor. - */ - public ClientUsingFetch(String serverUrl) { - - session = - Diffusion.sessions().principal("client").password("password") - .open(serverUrl); - - topics = session.feature(Topics.class); - } - - /** - * This shows an example of retrieving all topics - only topic path and type - * are returned in each result. - */ - public List> fetchAll() - throws InterruptedException, ExecutionException, TimeoutException { - - return topics.fetchRequest().fetch("*.*").get(5, SECONDS).results(); - } - - /** - * This shows an example of retrieving all string topics that satisfy a - * specified topic selector with values. - */ - public List> - fetchAllStringTopics(TopicSelector selector) - throws InterruptedException, ExecutionException, TimeoutException { - - return topics.fetchRequest() - .withValues(String.class) - .fetch(selector).get(5, SECONDS).results(); - } - - /** - * This shows an example of retrieving a single string topic with value and - * properties. - */ - public TopicResult fetchStringTopic(String topicPath) - throws InterruptedException, ExecutionException, TimeoutException { - return - topics.fetchRequest() - .withValues(String.class) - .withProperties() - .fetch(topicPath) - .get(5, SECONDS) - .results() - .stream() - .findFirst() - .orElse(null); - } - - /** - * This shows how to obtain the value of a specified string topic. - *

- * Uses {@link #fetchStringTopic(String)}. - */ - public String getStringTopicValue(String topicPath) - throws InterruptedException, ExecutionException, TimeoutException { - - final TopicResult result = fetchStringTopic(topicPath); - return result != null ? result.value() : null; - } - - /** - * This shows an example of retrieving all JSON topics that match a - * specified selector with values. - * - * This would return results only for JSON topics and not type compatible - * subtypes. - */ - public List> fetchJSONTopics(TopicSelector selector) - throws InterruptedException, ExecutionException, TimeoutException { - - return topics.fetchRequest() - .withValues(JSON.class) - .topicTypes(EnumSet.of(TopicType.JSON)) - .fetch(selector).get(5, SECONDS).results(); - } - - /** - * Shows how to obtain an inclusive range of topics, with values. - */ - public List> fetchRange(String from, String to) - throws InterruptedException, ExecutionException, TimeoutException { - - return topics.fetchRequest() - .from(from) - .to(to) - .withValues(Bytes.class) - .fetch("*.*").get(5, SECONDS).results(); - } - - /** - * Shows how to obtain the next group of topics, with values, from a - * specified start point. - *

- * This demonstrates paging and could be used repeatedly specifying the - * after value as the path of the last topic retrieved from the previous - * call of the next method. The {@link FetchResult#hasMore() hasMore} method - * on the result can be used to determine whether there may be more results. - *

- * Bytes is used as the value type so that all topic types are selected. - */ - public FetchResult next(String after, int limit) - throws InterruptedException, ExecutionException, TimeoutException { - - return topics.fetchRequest() - .after(after) - .withValues(Bytes.class) - .first(limit) - .fetch("*.*").get(5, SECONDS); - } - - /** - * Shows how to obtain the prior group of topics, with values, from a - * specified end point. - *

- * This demonstrates paging and could be used to retrieve the set of topics - * prior to the first topic from a previous call of prior or next. - */ - public FetchResult prior(String before, int limit) - throws InterruptedException, ExecutionException, TimeoutException { - - return topics.fetchRequest() - .before(before) - .withValues(Bytes.class) - .last(limit) - .fetch("*.*").get(5, SECONDS); - } - - /** - * Shows how to utilise deep branching limits, with values, from - * a start point and limiting the number of matching topics. - *

- * This demonstrates how one could easily limit the number of results of similar - * topics, or children of topics. - */ - public FetchResult limitDeepBranches(String start, int limitTopLevel, int limitPerBranch) - throws InterruptedException, ExecutionException, TimeoutException { - return topics.fetchRequest() - .withValues(Bytes.class) - .limitDeepBranches(limitTopLevel, limitPerBranch) - .fetch(start).get(5, SECONDS); - } - - /** - * This example shows how to log the values of all STRING topics, grouped - * into pages of size as specified. - */ - public void listAllStringTopics(int pageSize) - throws InterruptedException, ExecutionException, TimeoutException { - - int page = 1; - - // Fetch the first page - FetchResult result = - topics.fetchRequest() - .withValues(String.class) - .first(pageSize) - .fetch("*.*").get(5, SECONDS); - - // Log the page results repeatedly until no more - while (logPage(page, result)) { - result = - topics.fetchRequest() - .after(result.results().get(pageSize - 1).path()) - .withValues(String.class) - .first(pageSize) - .fetch("*.*").get(5, SECONDS); - page++; - } - } - - private static boolean logPage(int pageNumber, FetchResult result) { - final List> results = result.results(); - if (results.size() > 0) { - LOG.info("Page {}", pageNumber); - result.results().forEach(r -> { - LOG.info("{} = {}", r.path(), r.value()); - }); - } - return result.hasMore(); - } - - /** - * Close the session. - */ - public void close() { - session.close(); - } - -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ClientUsingInitialConnectionRetryStrategy.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ClientUsingInitialConnectionRetryStrategy.java deleted file mode 100644 index b8ca3b09..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ClientUsingInitialConnectionRetryStrategy.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.session.retry.RetryStrategy; - -/** - * This demonstrates a client's use of an initial connection retry strategy. - * - * @author DiffusionData Limited - * @since 6.9 - */ -public class ClientUsingInitialConnectionRetryStrategy { - - /** - * Create a session with an initial retry strategy. - *

- * Specify the retry interval and number of retry attempts. - */ - public Session connectWithRetryStrategy(String url, long interval, int attempts) { - return Diffusion.sessions() - .initialRetryStrategy(new RetryStrategy(interval, attempts)) - .open(url); - } - - /** - * Specify an initial retry strategy with indefinite retries. - */ - public Session retryStrategyWithIndefiniteRetries(String url) { - return Diffusion.sessions() - .initialRetryStrategy(new RetryStrategy(1)) - .open(url); - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ClientUsingPings.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ClientUsingPings.java deleted file mode 100644 index de47ce3a..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ClientUsingPings.java +++ /dev/null @@ -1,79 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2014, 2016 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.Pings; -import com.pushtechnology.diffusion.client.features.Pings.PingDetails; -import com.pushtechnology.diffusion.client.session.Session; - -/** - * This is a simple client example that pings the server and prints out the - * round-trip time. - *

- * This uses the 'Pings' feature only. - * - * @author DiffusionData Limited - * @since 5.0 - */ -public final class ClientUsingPings { - - private final Session session; - private final Pings pings; - - /** - * Constructor. - */ - public ClientUsingPings(String serverUrl) { - session = - Diffusion.sessions().principal("client").password("password") - .open(serverUrl); - pings = session.feature(Pings.class); - } - - /** - * Ping the server, blocking until a response is received. - * - * @return the round-trip time in milliseconds - * @throws InterruptedException if interrupted while waiting - * @throws ExecutionException if the ping failed. The chained - * {@link ExecutionException#getCause() cause} provides more - * information, e.g. SessionClosedException. - */ - public long ping() throws InterruptedException, ExecutionException { - return pings.pingServer().get().getRoundTripTime(); - } - - /** - * Ping the server, returning the result asynchronously using a - * CompletableFuture. - * - * @return provides the round-trip time in milliseconds when the ping - * response is received - */ - public CompletableFuture pingAsync() { - return pings.pingServer().thenApply(PingDetails::getRoundTripTime); - } - - /** - * Close the session. - */ - public void close() { - session.close(); - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ClientUsingSessionLocks.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ClientUsingSessionLocks.java deleted file mode 100644 index 6464bbe9..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ClientUsingSessionLocks.java +++ /dev/null @@ -1,173 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018, 2020 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.Topics; -import com.pushtechnology.diffusion.client.features.Topics.UnsubscribeReason; -import com.pushtechnology.diffusion.client.features.Topics.ValueStream; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.session.Session.SessionLock; -import com.pushtechnology.diffusion.client.session.Session.SessionLockScope; -import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; -import com.pushtechnology.diffusion.client.types.PathPermission; - -/** - * An example of a client that uses session locks to coordinate actions with - * other sessions. - * - *

- * In this example, a single session receives and processes updates from the - * topic {@code topicA}. Each client instance running this code creates a - * session and competes for the session lock {@code lockA}. The session that is - * assigned the session lock will subscribe to the topic and log updates. - * - *

- * {@link SessionLockScope#UNLOCK_ON_CONNECTION_LOSS UNLOCK_ON_CONNECTION_LOSS} - * session locks are used. If the session that owns the session lock loses its - * connection to the server, the server will reassign the lock to another - * session. This example uses a session listener to independently detect the - * connection loss, unsubscribe, unregister the stream listening for updates, - * and compete for the lock again. - * - *

- * The locking protocol has races documented under {@link SessionLock}. In the - * context of this example, the consequences are: - *

    - *
  • There may be a transient period where two sessions are subscribed to the - * topic, and both process the same update. - *
  • A session acquiring a lock may miss one or more updates that were not - * processed by the session that previously held the lock. - *
- * - *

Security note

- * - *

- * To run this example, the "client" principal must be granted - * {@link PathPermission#ACQUIRE_LOCK ACQUIRE_LOCK} permission to - * {@code lockA}. - * - * @author DiffusionData Limited - * @since 6.1 - */ -public class ClientUsingSessionLocks { - - private static final Logger LOG = - LoggerFactory.getLogger(ClientUsingSessionLocks.class); - - private static final String LOCK_NAME = "lockA"; - private static final String TOPIC_PATH = "topicA"; - - private final Session session; - - private final ValueStream stream = new LogUpdates(); - - /** - * Construct a request handling application. - * - * @param serverURL url of the server to connect to - */ - public ClientUsingSessionLocks(String serverURL) { - - // The "client" principal must have ACQUIRE_LOCK permission, see note in - // class Javadoc. - session = Diffusion.sessions().principal("client").password("password") - .open(serverURL); - } - - /** - * Start competing for the lock. - */ - public void start() { - session.addListener((s, oldState, newState) -> { - if (newState.isClosed()) { - onLockLost(); - } - }); - - requestLock(); - } - - private void requestLock() { - session.lock(LOCK_NAME, SessionLockScope.UNLOCK_ON_CONNECTION_LOSS) - .thenAccept(lock -> onLockAcquired()); - } - - private void onLockAcquired() { - final Topics topics = session.feature(Topics.class); - topics.subscribe(TOPIC_PATH); - topics.addStream(TOPIC_PATH, String.class, stream); - } - - private void onLockLost() { - final Topics topics = session.feature(Topics.class); - - // Remove the stream from the local registry. This will prevent - // processing of updates that may already be queued for this session and - // will be delivered on reconnection. - topics.removeStream(stream); - - // Unsubscribe from the topic. This will not take effect until this - // session has reconnected to the server. - topics.unsubscribe(TOPIC_PATH); - - // Compete for the lock again. This will not take effect until this - // session has reconnected to the server, and will be processed after - // the unsubscription. - requestLock(); - } - - /** - * Close the session. If the session owned the lock, the server is free to - * reassign it to another session. - */ - public void close() { - session.close(); - } - - /** - * Log updates received for a topic. - */ - private static class LogUpdates extends Topics.ValueStream.Default { - - @Override - public void onSubscription( - String topicPath, - TopicSpecification specification) { - - LOG.info("onSubscription({})", topicPath); - } - - @Override - public void onUnsubscription(String topicPath, - TopicSpecification specification, UnsubscribeReason reason) { - - LOG.info("onUnsubscription({})", topicPath); - } - - @Override - public void onValue( - String topicPath, - TopicSpecification specification, - String oldValue, - String newValue) { - - LOG.info("onValue({}, {})", topicPath, newValue); - } - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ClientWithReconnectionStrategy.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ClientWithReconnectionStrategy.java deleted file mode 100644 index 9137bf85..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ClientWithReconnectionStrategy.java +++ /dev/null @@ -1,107 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2014, 2015 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.session.Session.Listener; -import com.pushtechnology.diffusion.client.session.Session.State; -import com.pushtechnology.diffusion.client.session.reconnect.ReconnectionStrategy; - -/** - * This example class demonstrates the ability to set a custom - * {@link ReconnectionStrategy} when creating sessions. - * - * @author DiffusionData Limited - * @since 5.5 - */ -public class ClientWithReconnectionStrategy { - - private volatile int retries = 0; - - /** - * Constructor. - */ - public ClientWithReconnectionStrategy() { - - // Set the maximum amount of time we'll try and reconnect for to 10 - // minutes. - final int maximumTimeoutDuration = 1000 * 60 * 10; - - // Set the maximum interval between reconnect attempts to 60 seconds. - final long maximumAttemptInterval = 1000 * 60; - - // Create a new reconnection strategy that applies an exponential - // backoff - final ReconnectionStrategy reconnectionStrategy = - new ReconnectionStrategy() { - - private final ScheduledExecutorService scheduler = - Executors.newScheduledThreadPool(1); - - @Override - public void performReconnection( - final ReconnectionAttempt reconnection) { - - final long exponentialWaitTime = - Math.min((long) Math.pow(2, retries++) * 100L, - maximumAttemptInterval); - - scheduler.schedule( - new Runnable() { - @Override - public void run() { - reconnection.start(); - } - }, - exponentialWaitTime, TimeUnit.MILLISECONDS); - } - }; - - final Session session = - Diffusion.sessions().reconnectionTimeout(maximumTimeoutDuration) - .reconnectionStrategy(reconnectionStrategy) - .open("ws://diffusion.example.com:80"); - - session.addListener(new Listener() { - @Override - public void onSessionStateChanged(Session session, State oldState, - State newState) { - - if (newState == State.RECOVERING_RECONNECT) { - // The session has been disconnected, and has entered - // recovery state. It is during this state that - // the reconnect strategy will be called - } - - if (newState == State.CONNECTED_ACTIVE) { - // The session has connected for the first time, or it has - // been reconnected. - retries = 0; - } - - if (oldState == State.RECOVERING_RECONNECT) { - // The session has left recovery state. It may either be - // attempting to reconnect, or the attempt has been aborted; - // this will be reflected in the newState. - } - } - }); - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlAuthenticationClient.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ControlAuthenticationClient.java deleted file mode 100644 index ea8c5054..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlAuthenticationClient.java +++ /dev/null @@ -1,128 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2014, 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.TimeUnit; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.callbacks.Stream; -import com.pushtechnology.diffusion.client.features.control.clients.AuthenticationControl; -import com.pushtechnology.diffusion.client.features.control.clients.AuthenticationControl.ControlAuthenticator; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.types.Credentials; - -/** - * This is a control client which registers an authentication handler with a - * Diffusion server. - * - * @author DiffusionData Limited - * @since 5.0 - */ -public final class ControlAuthenticationClient { - - private ControlAuthenticationClient() { - } - - /** - * Main entry point for the control client. - */ - // CHECKSTYLE.OFF: UncommentedMain - public static void main(final String[] args) throws Exception { - - // The control client connects to the server using the principal 'admin' - // which is authenticated by the system authentication handler (see - // etc/SystemAuthentication.store). - // The principal must have REGISTER_HANDLER and AUTHENTICATE permissions. - final Session session = - Diffusion.sessions() - .principal("admin") - .password("password") - .open("ws://diffusion.example.com:80"); - - session.feature(AuthenticationControl.class).setAuthenticationHandler( - "after-system-handler", - new ExampleControlAuthenticationHandler()).get(10, TimeUnit.SECONDS); - - while (true) { - Thread.sleep(60000); - } - } - // CHECKSTYLE.ON: UncommentedMain - - /** - * An example of a control authentication handler. - *

- * This shows a simple example using a table of permitted principals with - * their passwords. It also demonstrates how the handler can change the - * properties of the client being authenticated. - */ - private static class ExampleControlAuthenticationHandler - extends Stream.Default - implements ControlAuthenticator { - - private static final Map PASSWORDS = new HashMap<>(); - static { - PASSWORDS.put("manager", "password".getBytes(Charset.forName("UTF-8"))); - PASSWORDS.put("guest", "asecret".getBytes(Charset.forName("UTF-8"))); - PASSWORDS.put("brian", "boru".getBytes(Charset.forName("UTF-8"))); - PASSWORDS.put("another", "apassword".getBytes(Charset.forName("UTF-8"))); - } - - @Override - public void authenticate( - String principal, - Credentials credentials, - Map sessionProperties, - Map proposedProperties, - Callback callback) { - - final byte[] passwordBytes = PASSWORDS.get(principal); - - if (passwordBytes != null && - credentials.getType() == Credentials.Type.PLAIN_PASSWORD && - Arrays.equals(credentials.toBytes(), passwordBytes)) { - if ("manager".equals(principal)) { - // manager allows all proposed properties - callback.allow(proposedProperties); - } - else if ("brian".equals(principal)) { - // brian is allowed all proposed properties and also gets - // the 'super' role added - final Map result = - new HashMap<>(proposedProperties); - final Set roles = - Diffusion.stringToRoles( - sessionProperties.get(Session.ROLES)); - roles.add("super"); - result.put(Session.ROLES, Diffusion.rolesToString(roles)); - callback.allow(result); - } - else { - // all others authenticated but ignoring proposed properties - callback.allow(); - } - } - else { - // Any principal not in the table is denied. - callback.deny(); - } - } - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientAddingAndRemovingTopics.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientAddingAndRemovingTopics.java deleted file mode 100644 index f7d22174..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientAddingAndRemovingTopics.java +++ /dev/null @@ -1,170 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2014, 2020 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import static com.pushtechnology.diffusion.client.Diffusion.newTopicSpecification; -import static com.pushtechnology.diffusion.client.topics.details.TopicSpecification.REMOVAL; -import static java.util.concurrent.TimeUnit.SECONDS; - -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeoutException; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; -import com.pushtechnology.diffusion.client.features.control.topics.TopicControl.AddTopicResult; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; -import com.pushtechnology.diffusion.client.topics.details.TopicType; - -/** - * An example of using a control client to add topics. - *

- * This uses the 'TopicControl' feature only. - *

- * To add or remove topics, the client session must have the 'modify_topic' - * permission for that branch of the topic tree. - * - * @author DiffusionData Limited - * @since 5.0 - */ -public class ControlClientAddingAndRemovingTopics { - - private final Session session; - - private final TopicControl topicControl; - - /** - * Constructor. - */ - public ControlClientAddingAndRemovingTopics(String serverUrl) { - - session = - Diffusion.sessions().principal("control").password("password") - .open(serverUrl); - - topicControl = session.feature(TopicControl.class); - - } - - /** - * This shows the simplest method for adding a topic. - *

- * This caters for adding most topic types with their default properties. - * - * @param topicPath the topic path - * @param topicType the topic type - * @return true if the topic was added or false if it already existed - * @throws ExecutionException if adding the topic fails - * @throws TimeoutException if operation does not complete within 5 seconds - * @throws InterruptedException if the current thread is interrupted whilst - * waiting for the result - * @since 6.0 - */ - public boolean addTopic(String topicPath, TopicType topicType) - throws ExecutionException, TimeoutException, InterruptedException { - - return topicControl.addTopic(topicPath, topicType).get(5, SECONDS) == - AddTopicResult.CREATED; - } - - /** - * This shows the action of adding a topic with a specification instead of - * simply a type. - *

- * This mechanism is suitable for adding most types of topic when something - * other than the default topic properties are required. - * - * @param topicPath the topic path - * @param specification the topic specification - * @throws ExecutionException if adding the topic fails - * @throws TimeoutException if operation does not complete within 5 seconds - * @throws InterruptedException if the current thread is interrupted whilst - * waiting for the result - * @since 6.0 - */ - public void addTopic(String topicPath, TopicSpecification specification) - throws InterruptedException, ExecutionException, TimeoutException { - topicControl.addTopic(topicPath, specification).get(5, SECONDS); - } - - /** - * This shows how to create a topic that will be automatically removed, - * along with all of its descendants, when the session closes. - * - * @param topicPath the topic path - * @param topicType the topic type - * @return true if the topic was added or false if it already existed - * @throws ExecutionException if adding the topic fails - * @throws TimeoutException if operation does not complete within 5 seconds - * @throws InterruptedException if the current thread is interrupted whilst - * waiting for the result - * @since 6.1 - */ - public boolean addSessionTopic(String topicPath, TopicType topicType) - throws ExecutionException, TimeoutException, InterruptedException { - - final TopicSpecification specification = - newTopicSpecification(topicType).withProperty( - REMOVAL, - "when this session closes remove '?" + topicPath + "//'"); - - return - topicControl.addTopic(topicPath, specification).get(5, SECONDS) == - AddTopicResult.CREATED; - } - - /** - * Remove a single topic given its path. - * - * @param topicPath the topic path - * @return a CompletableFuture that completes when a response is received - * from the server - */ - public CompletableFuture removeTopic(String topicPath) { - return removeTopics(">" + topicPath); - } - - /** - * Remove a topic and all of its descendants. - * - * @param topicPath the topic path - * @return a CompletableFuture that completes when a response is received - * from the server - */ - public CompletableFuture removeTopicBranch(String topicPath) { - return removeTopics("?" + topicPath + "//"); - } - - /** - * Remove one or more topics using a topic selector expression. - * - * @param topicSelector the selector expression - * @return a CompletableFuture that completes when a response is received - * from the server - */ - public CompletableFuture removeTopics(String topicSelector) { - return topicControl.removeTopics(topicSelector) - .thenApply(TopicControl.TopicRemovalResult::getRemovedCount); - } - - /** - * Close the session. - */ - public void close() { - session.close(); - } - -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientAsExclusiveUpdater.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientAsExclusiveUpdater.java deleted file mode 100644 index 3730a63a..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientAsExclusiveUpdater.java +++ /dev/null @@ -1,153 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2014, 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import static com.pushtechnology.diffusion.client.Diffusion.newTopicSpecification; -import static com.pushtechnology.diffusion.client.Diffusion.updateConstraints; -import static com.pushtechnology.diffusion.client.topics.details.TopicSpecification.REMOVAL; -import static com.pushtechnology.diffusion.client.topics.details.TopicType.STRING; -import static java.util.concurrent.TimeUnit.SECONDS; - -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeoutException; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.TopicUpdate; -import com.pushtechnology.diffusion.client.features.UpdateConstraint; -import com.pushtechnology.diffusion.client.features.UpdateStream; -import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; - -/** - * An example of using a control client as an event feed to a topic. - *

- * This uses the 'TopicControl' feature to create a topic and the - * 'TopicUpdate' feature to send updates to it. - *

- * To create the topic, the client session requires the 'modify_topic' - * permission for that branch of the topic tree. - *

- * To send updates to a topic, the client session requires the 'update_topic' - * permission for that branch of the topic tree. - * - * @author DiffusionData Limited - * @since 5.0 - */ -public class ControlClientAsExclusiveUpdater { - - private static final String TOPIC_NAME = "Feeder"; - - private final Session session; - - /** - * Constructor. - */ - public ControlClientAsExclusiveUpdater(String serverUrl) { - session = - Diffusion.sessions().principal("control").password("password") - .open(serverUrl); - } - - /** - * Start the feed. - * - * @param provider the provider of prices - * @param scheduler a scheduler service to schedule a periodic feeder task - * @throws TimeoutException if the topic was not created within 5 seconds - * @throws ExecutionException if topic creation failed - * @throws InterruptedException if the current thread was interrupted whilst - * waiting for the topic to be created - */ - public void start( - final PriceProvider provider, - final ScheduledExecutorService scheduler) - throws InterruptedException, ExecutionException, TimeoutException { - - // Add the topic with a REMOVAL policy indicating that the topic - // will be removed when the session no longer exists. - final TopicControl topicControl = session.feature(TopicControl.class); - - final TopicSpecification specification = - newTopicSpecification(STRING) - .withProperty(REMOVAL, "when this session closes"); - - topicControl.addTopic( - TOPIC_NAME, - specification).get(5, SECONDS); - - final TopicUpdate topicUpdate = - session.feature(TopicUpdate.class); - - session - .lock(TOPIC_NAME) - .thenAccept(lock -> onLockAcquired(lock, provider, scheduler, topicUpdate)); - } - - private static void onLockAcquired( - Session.SessionLock lock, - PriceProvider provider, - ScheduledExecutorService scheduler, - TopicUpdate topicUpdate) { - - // Use the session lock to create an update stream without any other - // session competing for a stream for the topic. Start a periodic task - // to poll the provider every second and update the topic. When the - // update stream fails, stop the scheduled task and release the lock. - final UpdateConstraint exclusiveAccessConstraint = - updateConstraints().locked(lock); - final UpdateStream updateStream = topicUpdate.newUpdateStreamBuilder() - .constraint(exclusiveAccessConstraint).build(TOPIC_NAME, String.class); - final CompletableFuture failureHandler = new CompletableFuture<>(); - final ScheduledFuture theFeeder = scheduler.scheduleAtFixedRate( - () -> updateStream - .set(provider.getPrice()) - .whenComplete((result, ex) -> { - if (ex != null) { - failureHandler.completeExceptionally(ex); - } - }), - 1, - 1, - SECONDS); - failureHandler.whenComplete((result, ex) -> { - theFeeder.cancel(false); - lock.unlock(); - }); - } - - /** - * Close the session. - */ - public void close() { - session.close(); - } - - /** - * Interface of a price provider that can periodically be polled for a - * price. - */ - public interface PriceProvider { - /** - * Get the current price. - * - * @return current price as a decimal string - */ - String getPrice(); - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientChangingSecurity.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientChangingSecurity.java deleted file mode 100644 index 9266b267..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientChangingSecurity.java +++ /dev/null @@ -1,192 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2014, 2020 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import static java.util.Collections.emptySet; -import static java.util.stream.Collectors.toCollection; - -import java.util.Set; -import java.util.TreeSet; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.control.clients.SecurityControl; -import com.pushtechnology.diffusion.client.features.control.clients.SecurityControl.Role; -import com.pushtechnology.diffusion.client.features.control.clients.SecurityControl.ScriptBuilder; -import com.pushtechnology.diffusion.client.features.control.clients.SecurityControl.SecurityConfiguration; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.types.PathPermission; - -/** - * An example of using a control client to alter the security configuration. - *

- * This uses the {@link SecurityControl} feature only. - * - * @author DiffusionData Limited - * @since 5.3 - */ -public class ControlClientChangingSecurity { - - private static final Logger LOG = - LoggerFactory.getLogger( - ControlClientChangingSecurity.class); - - private final SecurityControl securityControl; - private final ScriptBuilder emptyScript; - - /** - * Constructor. - */ - public ControlClientChangingSecurity() { - - final Session session = Diffusion.sessions() - // Authenticate with a user that has the VIEW_SECURITY and - // MODIFY_SECURITY permissions. - .principal("admin").password("password") - // Use a secure channel because we're transferring sensitive - // information. - .open("wss://diffusion.example.com:80"); - - securityControl = session.feature(SecurityControl.class); - emptyScript = securityControl.scriptBuilder(); - } - - /** - * This will update the security store to ensure that all roles start with a - * capital letter (note that this does not address changing the use of the - * roles in the system authentication store). - * - * @return a CompletableFuture that completes when the operation succeeds or - * fails. - * - *

- * If the operation was successful, the CompletableFuture will - * complete successfully. - * - *

- * Otherwise, the CompletableFuture will complete exceptionally with - * an {@link ExecutionException}. See - * {@link SecurityControl#getSecurity()} and - * {@link SecurityControl#updateStore(String)} for common failure - * reasons. - */ - public CompletableFuture capitalizeRoles() { - return securityControl.getSecurity().thenCompose(this::capitalizeRoles); - } - - private CompletableFuture capitalizeRoles( - SecurityConfiguration configuration) { - - final String script = emptyScript - - .setRolesForAnonymousSessions( - capitalizeSet(configuration.getRolesForAnonymousSessions())) - - .setRolesForNamedSessions( - capitalizeSet(configuration.getRolesForNamedSessions())) - - .append(configuration - // For each role ... - .getRoles().stream() - // ... build a script that capitalises that role ... - .map(this::capitalizeRole) - /// .. and combine the per-role scripts into one. - .reduce(emptyScript, (sb1, sb2) -> sb1.append(sb2))) - - .script(); - - LOG.info("Sending the following script to the server:\n{}", script); - - return securityControl.updateStore(script) - // Convert CompletableFuture to CompletableFuture. - .thenAccept(ignored -> { }); - } - - private ScriptBuilder capitalizeRole(Role role) { - final String oldName = role.getName(); - final String newName = capitalizeString(oldName); - - ScriptBuilder builder = emptyScript; - - // Only if new name is different - if (!oldName.equals(newName)) { - if (!role.getGlobalPermissions().isEmpty()) { - builder = builder - // Remove global permissions for old role - .setGlobalPermissions(oldName, emptySet()) - // Set global permissions for new role - .setGlobalPermissions( - newName, role.getGlobalPermissions()); - } - - if (!role.getDefaultPathPermissions().isEmpty()) { - builder = builder - // Remove default path permissions for old role - .setDefaultPathPermissions(oldName, emptySet()) - // Set default path permissions for new role - .setDefaultPathPermissions( - newName, role.getDefaultPathPermissions()); - } - - builder = builder.append( - role.getPathPermissions().entrySet().stream().map( - entry -> { - final String path = entry.getKey(); - final Set permissions = entry.getValue(); - - return emptyScript - // Remove path permissions for old role - .removePathPermissions(oldName, path) - // Set path permissions for new role - .setPathPermissions(newName, path, permissions); - }) - .reduce(emptyScript, (sb1, sb2) -> sb1.append(sb2))); - } - - final Set oldIncludedRoles = role.getIncludedRoles(); - - if (oldIncludedRoles.isEmpty()) { - return builder; - } - - return builder - // Remove old included roles. - .setRoleIncludes(oldName, emptySet()) - - // Set new roles even if role name did not change as the included - // roles may be changed. - .setRoleIncludes(newName, capitalizeSet(oldIncludedRoles)); - } - - private static Set capitalizeSet(Set roles) { - return roles.stream() - .map(ControlClientChangingSecurity::capitalizeString) - .collect(toCollection(TreeSet::new)); - } - - private static String capitalizeString(String role) { - return Character.toUpperCase(role.charAt(0)) + role.substring(1); - } - - /** - * Close the session. - */ - public void close() { - securityControl.getSession().close(); - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientChangingSystemAuthentication.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientChangingSystemAuthentication.java deleted file mode 100644 index e72b23c7..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientChangingSystemAuthentication.java +++ /dev/null @@ -1,128 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2014, 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.control.clients.SystemAuthenticationControl; -import com.pushtechnology.diffusion.client.features.control.clients.SystemAuthenticationControl.ScriptBuilder; -import com.pushtechnology.diffusion.client.session.Session; - -/** - * An example of using a control client to alter the system authentication - * configuration. - *

- * This uses the {@link SystemAuthenticationControl} feature only. - * - * @author DiffusionData Limited - * @since 5.2 - */ -public class ControlClientChangingSystemAuthentication { - - private static final Logger LOG = - LoggerFactory.getLogger( - ControlClientChangingSystemAuthentication.class); - - private final SystemAuthenticationControl systemAuthenticationControl; - private final ScriptBuilder emptyScript; - - /** - * Constructor. - */ - public ControlClientChangingSystemAuthentication() { - - final Session session = Diffusion.sessions() - // Authenticate with a user that has the VIEW_SECURITY and - // MODIFY_SECURITY permissions. - .principal("admin").password("password") - // Use a secure channel because we're transferring sensitive - // information. - .open("wss://diffusion.example.com:80"); - - systemAuthenticationControl = - session.feature(SystemAuthenticationControl.class); - emptyScript = systemAuthenticationControl.scriptBuilder(); - } - - /** - * For all system users, update the assigned roles to replace the - * "SUPERUSER" role and with "ADMINISTRATOR". - * - * @return a CompletableFuture that completes when the operation succeeds or - * fails. - * - *

- * If the operation was successful, the CompletableFuture will - * complete successfully. - * - *

- * Otherwise, the CompletableFuture will complete exceptionally with - * an {@link ExecutionException}. See - * {@link SystemAuthenticationControl#getSystemAuthentication()} and - * {@link SystemAuthenticationControl#updateStore(String)} for - * common failure reasons. - */ - public CompletableFuture changeSuperUsersToAdministrators() { - - return systemAuthenticationControl - .getSystemAuthentication() - .thenCompose(configuration -> { - - final String script = configuration - - // For each principal ... - .getPrincipals().stream() - - // ... that has the SUPERUSER assigned role ... - .filter(p -> p.getAssignedRoles().contains("SUPERUSER")) - - // ... create a script that updates the assigned roles to - // replace SUPERUSER with ADMINISTRATOR ... - .map(p -> { - final Set newRoles = - new HashSet<>(p.getAssignedRoles()); - newRoles.remove("SUPERUSER"); - newRoles.add("ADMINISTRATOR"); - return emptyScript.assignRoles(p.getName(), newRoles); - }) - - // ... create a single combined script. - .reduce(emptyScript, (sb1, sb2) -> sb1.append(sb2)) - .script(); - - LOG.info("Sending the following script to the server:\n{}", - script); - - return systemAuthenticationControl.updateStore(script) - // Convert CompletableFuture to - // CompletableFuture. - .thenAccept(ignored -> { }); - }); - } - - /** - * Close the session. - */ - public void close() { - systemAuthenticationControl.getSession().close(); - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientConnectingAsynchronously.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientConnectingAsynchronously.java deleted file mode 100644 index 5579fc57..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientConnectingAsynchronously.java +++ /dev/null @@ -1,55 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2014, 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import java.util.concurrent.CompletableFuture; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; -import com.pushtechnology.diffusion.client.features.control.topics.TopicControl.AddTopicResult; -import com.pushtechnology.diffusion.client.session.SessionFactory; -import com.pushtechnology.diffusion.client.topics.details.TopicType; - -/** - * This is a simple example of a client that uses asynchronous connection to - * connect, create a topic and then disconnect. - * - * @author DiffusionData Limited - * @since 5.3 - */ -public final class ControlClientConnectingAsynchronously { - - private final SessionFactory sessionFactory = - Diffusion.sessions().principal("control").password("password"); - - /** - * Create a session to the server, add a string topic, then close the - * session. - * - * @param topicPath path of session to add - * @return a CompletableFuture that completes when the topic has been added - */ - public CompletableFuture createTopic(String topicPath) { - - return sessionFactory - .openAsync("ws://diffusion.example.com:80") - .thenCompose(session -> { - return session - .feature(TopicControl.class) - .addTopic(topicPath, TopicType.STRING) - .whenComplete((result, ex) -> session.close()); - }); - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientDeletesTopicsWithoutSubscribers.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientDeletesTopicsWithoutSubscribers.java deleted file mode 100644 index 7f8c8cd1..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientDeletesTopicsWithoutSubscribers.java +++ /dev/null @@ -1,85 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018, 2019 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import static com.pushtechnology.diffusion.client.Diffusion.newTopicSpecification; -import static com.pushtechnology.diffusion.client.topics.details.TopicSpecification.REMOVAL; -import static com.pushtechnology.diffusion.client.topics.details.TopicType.JSON; -import static java.util.concurrent.TimeUnit.SECONDS; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeoutException; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; - -/** - * This example control client provides a methods that allows a topic to be - * created that will be automatically removed when the number of subscribers - * falls to and remains at zero for 10 seconds. - * - * @author DiffusionData Limited - */ -public final class ControlClientDeletesTopicsWithoutSubscribers { - - private final Session session; - private final TopicControl topicControl; - private final TopicSpecification specification; - - /** - * Construct client that can add topics that will be automatically - * removed. - * - * @param serverURL url of the server to connect to. - */ - public ControlClientDeletesTopicsWithoutSubscribers(String serverURL) { - - session = Diffusion.sessions() - .principal("control").password("password") - .open(serverURL); - - topicControl = session.feature(TopicControl.class); - - specification = - newTopicSpecification(JSON) - .withProperty(REMOVAL, "when subscriptions < 1 for 10s"); - - } - - /** - * Creates a topic that will be automatically removed after it has had - * no subscribers for at least 10 seconds. - * - * @param topicPath the topic path - * @throws InterruptedException - * @throws ExecutionException if the add topic request failed - * @throws TimeoutException timed out waiting for response from add topic - * request - */ - public void addTopic(String topicPath) - throws InterruptedException, ExecutionException, TimeoutException { - topicControl.addTopic(topicPath, specification).get(10, SECONDS); - } - - /** - * Close session. - */ - public void close() { - session.close(); - } - -} \ No newline at end of file diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientHandlingMissingTopicNotification.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientHandlingMissingTopicNotification.java deleted file mode 100644 index 65879e90..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientHandlingMissingTopicNotification.java +++ /dev/null @@ -1,101 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2014, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.callbacks.ErrorReason; -import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; -import com.pushtechnology.diffusion.client.features.control.topics.TopicControl.MissingTopicNotification; -import com.pushtechnology.diffusion.client.features.control.topics.TopicControl.MissingTopicNotificationStream; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.TopicSelector.Type; -import com.pushtechnology.diffusion.client.topics.details.TopicType; - -/** - * An example of registering a missing topic notification handler and processing - * notifications using a control client. - * - * @author DiffusionData Limited - */ -public final class ControlClientHandlingMissingTopicNotification { - - private static final Logger LOG = - LoggerFactory.getLogger(ControlClientHandlingMissingTopicNotification.class); - - private final Session session; - private final TopicControl topicControl; - - /** - * Constructor. - */ - public ControlClientHandlingMissingTopicNotification(String serverUrl) - throws InterruptedException, ExecutionException, TimeoutException { - // Create a session - session = Diffusion.sessions().password("password").principal("admin") - .open(serverUrl); - - topicControl = session.feature(TopicControl.class); - - // Registers a missing topic notification on a topic path - topicControl.addMissingTopicHandler( - "Accounts", - new NotificationStream()).get(5, TimeUnit.SECONDS); - - } - - private final class NotificationStream implements - MissingTopicNotificationStream { - @Override - public void onClose() { - } - - @Override - public void onError(ErrorReason errorReason) { - } - - @Override - public void onMissingTopic(MissingTopicNotification notification) { - // This handler will create a missing topic if a path selector - // requesting a topic starting with "Accounts/" is selected and - // the requesting session has the principal 'control'. - if (notification.getTopicSelector().getType() == Type.PATH) { - final String path = notification.getTopicPath(); - if (path.startsWith("Accounts/") && - "control".equals( - notification.getSessionProperties().get(Session.PRINCIPAL))) { - - topicControl.addTopic( - path, - TopicType.STRING).whenComplete((result, ex) -> { - if (ex == null) { - LOG.info("Missing topic " + path + " " + result); - } - else { - LOG.warn("Failed to create missing topic " + path, ex); - } - }); - } - } - } - } - -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientManagingSessionTrees.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientManagingSessionTrees.java deleted file mode 100644 index 21ba8e86..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientManagingSessionTrees.java +++ /dev/null @@ -1,124 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import static com.pushtechnology.diffusion.client.Diffusion.newBranchMappingTableBuilder; -import static java.util.concurrent.TimeUnit.SECONDS; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeoutException; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.control.topics.SessionTrees; -import com.pushtechnology.diffusion.client.features.control.topics.SessionTrees.BranchMappingTable; -import com.pushtechnology.diffusion.client.session.Session; - -/** - * An example of using session trees. - *

- * This demonstrates creating, retrieving, and removing a branch mapping table - * for the {@code market/prices} topic tree branch. - * - * @author DiffusionData Limited - * @since 6.7 - */ -public final class ControlClientManagingSessionTrees { - - private final Session session; - - /** - * Constructor. - *

- * A session is connected to the supplied url. - * - * @param serverUrl url for server (or any server in a cluster) - */ - public ControlClientManagingSessionTrees(String serverUrl) { - session = Diffusion.sessions().principal("admin").password("password") - .open(serverUrl); - } - - /** - * Creates (or replaces) a branch mapping table for the - * {@code market/prices} branch. - *

- * In this example a session subscribing to topic path market/prices/X would - * map to actual topics as follows:- - *

    - *
  • User tier 1 or Germany – {@code backend/discounted_prices/X} - *
  • User tier 2 – {@code backend/standard_prices/X} - *
  • Anonyomous user – {@code backend/delayed_prices/X} - *
  • All others – {@code market/prices/X} - *
- * The mappings are evaluated in order. - *

- * A subscription only completes if there is actually a topic at the derived - * path. - *

- * No matter what topic the session actually gets subscribed to it will see - * it as {@code market/prices/X}. - */ - public void createBranchMappingTable() - throws InterruptedException, ExecutionException, TimeoutException { - - final BranchMappingTable branchMappingTable = - newBranchMappingTableBuilder() - .addBranchMapping( - "USER_TIER is '1' or $Country is 'DE'", - "backend/discounted_prices") - .addBranchMapping( - "USER_TIER is '2'", - "backend/standard_prices") - .addBranchMapping( - "$Principal is ''", - "backend/delayed_prices") - .create("market/prices"); - - session.feature(SessionTrees.class) - .putBranchMappingTable(branchMappingTable).get(5, SECONDS); - } - - /** - * Returns the {@code market/prices} branch mapping table. - */ - public BranchMappingTable getBranchMappingTable() - throws InterruptedException, ExecutionException, TimeoutException { - - return session.feature(SessionTrees.class) - .getBranchMappingTable("market/prices").get(5, SECONDS); - } - - /** - * Removes the {@code market/prices} branch mapping table. - */ - public void removeBranchMappingTable() - throws InterruptedException, ExecutionException, TimeoutException { - - // Removal is achieved by putting an empty table - final BranchMappingTable branchMappingTable = - newBranchMappingTableBuilder().create("market/prices"); - - session.feature(SessionTrees.class) - .putBranchMappingTable(branchMappingTable).get(5, SECONDS); - } - - /** - * Closes the session. - */ - public void close() { - session.close(); - } - -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientPartiallyUpdatingTopic.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientPartiallyUpdatingTopic.java deleted file mode 100644 index ceb4a4ca..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientPartiallyUpdatingTopic.java +++ /dev/null @@ -1,105 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2019 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.TopicUpdate; -import com.pushtechnology.diffusion.client.features.TopicUpdate.JsonPatchResult; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; -import com.pushtechnology.diffusion.client.topics.details.TopicType; -import com.pushtechnology.diffusion.datatype.json.JSON; -import com.pushtechnology.diffusion.datatype.json.JSONDataType; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -/** - * This example demonstrates the use of partial update. A JSON patch is used to - * update the existing value of the topic by adding a new key-value pair. - *

- * The 'TopicUpdate' feature provides this functionality. The patch is provided - * as a String that is parsed on the server. A JSON patch is a JSON document - * containing a list of operations: add, replace, copy, move, remove and test. - *

- * To perform a partial update the topic must have a JSON value and the client - * must have the 'update_topic' permission for the path. - * - * @author DiffusionData Limited - * @since 6.4 - * @see JavaScript Object Notation (JSON) Patch - */ - -public final class ControlClientPartiallyUpdatingTopic { - - private static final JSONDataType JSON_DATATYPE = Diffusion.dataTypes().json(); - - private final Session session; - private final TopicUpdate topicUpdate; - - /** - * Constructor. - * - * @param serverUrl for example "ws://diffusion.example.com:80" - */ - public ControlClientPartiallyUpdatingTopic(String serverUrl) { - - // 1. Connect to the Diffusion endpoint. - session = Diffusion.sessions().principal("control").password("password") - .open(serverUrl); - - // 2. Access the TopicUpdate feature. - topicUpdate = session.feature(TopicUpdate.class); - } - - /** - * Patches can have multiple operations which are applied incrementally and - * atomically. - * - * @param topicPath the path of the topic - * - * @throws ExecutionException - * @throws InterruptedException - * @throws TimeoutException - */ - public void applySimpleJsonPatch(String topicPath) - throws ExecutionException, InterruptedException, TimeoutException { - - // 1. Create JSON topic specification. - final TopicSpecification specification = - Diffusion.newTopicSpecification(TopicType.JSON); - - // 2. Set the initial value to an empty JSON object. - final JSON initialValue = JSON_DATATYPE.fromJsonString("{}"); - topicUpdate.addAndSet(topicPath, specification, JSON.class, initialValue).get(5, TimeUnit.SECONDS); - - // 3. The patch [{"op":"add", "path":"/array","value":"[0, 1, 2]"}] will - // add the array at the designated path changing the value to - // {"array" : [0, 1, 2]}. - final String addArrayPatch = "[{\"op\": \"add\", \"path\": \"/array\", \"value\": [0, 1, 2]}]"; - - // 4. Apply the patch. - final JsonPatchResult result = - topicUpdate.applyJsonPatch(topicPath, addArrayPatch).get(5, TimeUnit.SECONDS); - - // 5. Check for failure. - result.failedOperation().ifPresent(failedOperation -> { - // If an operation in the JSON patch did not apply to the value, the - // Integer failedOperation will be the index of the operation in the - // JSON patch that failed and can be handled accordingly. - }); - } -} \ No newline at end of file diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientRequestHandling.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientRequestHandling.java deleted file mode 100644 index f50c77b4..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientRequestHandling.java +++ /dev/null @@ -1,157 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2017, 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.callbacks.ErrorReason; -import com.pushtechnology.diffusion.client.callbacks.Registration; -import com.pushtechnology.diffusion.client.features.Messaging; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.session.SessionId; -import com.pushtechnology.diffusion.datatype.json.JSON; - -/** - * This is an example of a control client using the 'Messaging' feature - * to receive requests from clients and send requests to clients. - *

- * It is a trivial example that simply responds to all requests on a particular - * branch of the topic tree by echoing them back to the client exactly as they - * are. - * - * @see ClientRequestHandling - * - * @author DiffusionData Limited - * @since 6.0 - */ -public class ControlClientRequestHandling { - - private static final Logger LOG = - LoggerFactory.getLogger(ControlClientRequestHandling.class); - - private final Session session; - private final Messaging messaging; - - /** - * Constructor. - * - * @param serverURL url of the server to connect to. - */ - public ControlClientRequestHandling(String serverURL) { - session = Diffusion.sessions().principal("control").password("password") - .open(serverURL); - messaging = session.feature(Messaging.class); - } - - /** - * Register a request handler on a path. - * - * @param messagePath path to register a handler on - * @return handler registration - */ - public Registration addRequestHandler(String messagePath) - throws InterruptedException, ExecutionException, TimeoutException { - return messaging.addRequestHandler( - messagePath, JSON.class, JSON.class, new JSONRequestHandler()).get(5, TimeUnit.SECONDS); - } - - /** - * Sends a request directly to the request echoing session. - * - * @param sessionId session to send a request to - * @param messagePath path to send the request to - * @param request request to send - * - * @return the response to the request - */ - public JSON sendRequest(SessionId sessionId, String messagePath, JSON request) - throws InterruptedException, ExecutionException, TimeoutException { - final JSON response = messaging.sendRequest( - sessionId, messagePath, request, JSON.class, JSON.class).get(5, TimeUnit.SECONDS); - LOG.info("Response received: {}", response.toJsonString()); - - return response; - } - - /** - * Close the session. - */ - public void close() { - session.close(); - } - - /** - * Send a request to sessions using a filter to match against receiving sessions. - * - * @param messagePath path to send the request to - * @param request the request to send - * @param filter filter to match sessions against - * - * @return the number of requests dispatched to clients - */ - public int sendRequestToFilter(String messagePath, JSON request, String filter) - throws InterruptedException, ExecutionException, TimeoutException { - final int numberSent = messaging.sendRequestToFilter(filter, messagePath, request, - JSON.class, JSON.class, new JSONFilterRequestCallback()).get(5, TimeUnit.SECONDS); - LOG.info("{} requests sent", numberSent); - - return numberSent; - } - - /** - * Request handler that logs received requests and echoes them back to the original session. - */ - private final class JSONRequestHandler implements Messaging.RequestHandler { - - @Override - public void onClose() { - LOG.info("JSONRequestHandler closed"); - } - - @Override - public void onError(ErrorReason errorReason) { - LOG.info("JSONRequestHandler error: {}", errorReason); - } - - @Override - public void onRequest(JSON request, RequestContext context, Responder responder) { - LOG.info("Handler received request: {} from session {}", request.toJsonString(), context.getSessionId()); - //Echo the request back to the requester - responder.respond(request); - } - } - - /** - * Filter callback that logs responses to the request. - */ - private final class JSONFilterRequestCallback implements Messaging.FilteredRequestCallback { - - @Override - public void onResponse(SessionId sessionId, JSON response) { - LOG.info("Response received: {} from session {}", response.toJsonString(), sessionId); - } - - @Override - public void onResponseError(SessionId sessionId, Throwable throwable) { - LOG.info("Response error from session {} due to {}", sessionId, throwable); - } - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientSubscriptionControl.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientSubscriptionControl.java deleted file mode 100644 index 5258f5c0..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientSubscriptionControl.java +++ /dev/null @@ -1,95 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2014, 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import java.util.concurrent.CompletableFuture; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.control.topics.SubscriptionControl; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.session.SessionId; - -/** - * This demonstrates using a client to subscribe and unsubscribe other clients - * to topics. - *

- * This uses the 'SubscriptionControl' feature. - * - * @author DiffusionData Limited - * @since 5.0 - */ -public class ControlClientSubscriptionControl { - - private final Session session; - - private final SubscriptionControl subscriptionControl; - - /** - * Constructor. - */ - public ControlClientSubscriptionControl(String serverUrl) { - - session = - Diffusion.sessions().principal("control").password("password") - .open(serverUrl); - - subscriptionControl = session.feature(SubscriptionControl.class); - } - - /** - * Subscribe a client to topics. - * - * @param sessionId client to subscribe - * @param topicSelector topic selector expression - * @return a CompletableFuture that completes when a response is received - * from the server - */ - public CompletableFuture subscribe( - SessionId sessionId, - String topicSelector) { - - // To subscribe a client to a topic, this client session - // must have the 'modify_session' permission. - return subscriptionControl.subscribe( - sessionId, - topicSelector); - } - - /** - * Unsubscribe a client from topics. - * - * @param sessionId client to unsubscribe - * @param topicSelector topic selector expression - * @return a CompletableFuture that completes when a response is received - * from the server - */ - public CompletableFuture unsubscribe( - SessionId sessionId, - String topicSelector) { - - // To unsubscribe a client from a topic, this client session - // must have the 'modify_session' permission. - return subscriptionControl.unsubscribe( - sessionId, - topicSelector); - } - - /** - * Close the session. - */ - public void close() { - session.close(); - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientSubscriptionControlRouting.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientSubscriptionControlRouting.java deleted file mode 100644 index efbb84c2..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientSubscriptionControlRouting.java +++ /dev/null @@ -1,95 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2014, 2020 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import java.util.concurrent.CompletableFuture; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.callbacks.Registration; -import com.pushtechnology.diffusion.client.features.control.topics.SubscriptionControl; -import com.pushtechnology.diffusion.client.features.control.topics.SubscriptionControl.RoutingSubscriptionRequest; -import com.pushtechnology.diffusion.client.features.control.topics.SubscriptionControl.RoutingSubscriptionRequest.RoutingHandler; -import com.pushtechnology.diffusion.client.session.Session; - -/** - * This demonstrates using a control client to be notified of subscription - * requests to routing topics. - *

- * This uses the 'SubscriptionControl' feature. - * - * @author DiffusionData Limited - * @since 5.0 - */ -public class ControlClientSubscriptionControlRouting { - - private static final Logger LOG = - LoggerFactory.getLogger(ControlClientSubscriptionControlRouting.class); - - private final Session session; - private final SubscriptionControl subscriptionControl; - - /** - * Constructor. - */ - public ControlClientSubscriptionControlRouting(String serverUrl) { - - session = - Diffusion.sessions().principal("control").password("password") - .open(serverUrl); - - subscriptionControl = - session.feature(SubscriptionControl.class); - - } - - /** - * Route a subscription from one topic to another. - * - * @param topic the topic to receive data from its routed subscription - * @param sourceTopic the topic to route subscriptions to - * @return a CompletableFuture that completes when a response is received - * from the server - */ - public CompletableFuture addRoute(String topic, String sourceTopic) { - // Sets up a handler so that all subscriptions to topic are routed - // to sourceTopic - // To do this, the client session requires the 'view_session', - // 'modify_session', and 'register_handler' permissions. - return subscriptionControl.addRoutingSubscriptionHandler( - topic, - new RoutingHandler.Default() { - @Override - public void onSubscriptionRequest( - final RoutingSubscriptionRequest request) { - - request.route(sourceTopic).whenComplete((voidResult, exception) -> { - if (exception != null) { - LOG.info("subscription routing failed", exception); - } - }); - } - }); - } - - /** - * Close the session. - */ - public void close() { - session.close(); - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientTopicNotifications.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientTopicNotifications.java deleted file mode 100644 index 2dd125e9..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientTopicNotifications.java +++ /dev/null @@ -1,463 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2017, 2108 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import java.io.Closeable; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.callbacks.Registration; -import com.pushtechnology.diffusion.client.features.control.topics.TopicNotifications; -import com.pushtechnology.diffusion.client.features.control.topics.TopicNotifications.NotificationRegistration; -import com.pushtechnology.diffusion.client.features.control.topics.TopicNotifications.TopicNotificationListener; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; - -/** - * Examples for using the {@link TopicNotifications} feature to receive - * notifications for the topic tree. - * - * @author DiffusionData Limited - * @since 6.0 - */ -public class ControlClientTopicNotifications { - - private final Session session; - private final TopicNotifications notifications; - - /** - * Constructor. - * - */ - public ControlClientTopicNotifications() { - this.session = - Diffusion.sessions().principal("control") - .password("password") - .open("ws://diffusion.example.com:80"); - - this.notifications = session.feature(TopicNotifications.class); - } - - /** - * Basic example of receiving notifications about all topics under a given - * branch. This registers a long-lived notification listener and selects all - * topics under the provided root path. - * - * With topics at the following paths: - * - *

-     * a
-     * a/b
-     * a/b/c/d
-     *
-     * e/f
-     * e/f/g/h/i
-     * 
- * - * To listen for topic events: - * - *
-     * TreeListener listener = new TreeListener() {
-     *
-     *     public void onTopicAdded(String topicPath,
-     *         TopicSpecification specification) {
-     *         // Handle topic addition
-     *     }
-     *
-     *     public void onTopicRemoved(String topicPath,
-     *         TopicSpecification specification) {
-     *         // Handle topic removal
-     *     }
-     *
-     *     public void onClose() {
-     *         // The listener has been closed
-     *     }
-     * };
-     *
-     * // Get notifications of all topics at or below the topic path "a"
-     * topicsForBranch("a", listener);
-     *
-     * // Get notifications of all topics at or below the topic path "e"
-     * topicsForBranch("e", listener);
-     * 
- * - * which would result in each topic path and specification being notified to - * {@link ControlClientTopicNotifications.TreeListener#onTopicAdded(String, TopicSpecification) - * onTopicAdded}. - * - * @param rootPath the topic path from which to start walking the tree - * @param listener the listener on which to receive tree structure callbacks - * @return a closeable allowing the cancellation of the registered listener - */ - public Closeable topicsForBranch(String rootPath, TreeListener listener) { - - final CompletableFuture registration = - notifications.addListener( - new TopicNotificationListener.Default() { - @Override - public void onTopicNotification(String topicPath, - TopicSpecification spec, NotificationType type) { - switch (type) { - case ADDED: - case SELECTED: - listener.onTopicAdded(topicPath, spec); - return; - case REMOVED: - case DESELECTED: - listener.onTopicRemoved(topicPath, spec); - return; - default: - // No default action - } - } - - @Override - public void onClose() { - listener.onClose(); - } - }); - - registration.thenAccept(r -> { - r.select(rootPath + "//"); - }); - - return new Closeable() { - @Override - public void close() { - registration.thenAccept(Registration::close); - } - }; - } - - /** - * Listener for receiving callbacks about the structure of the topic tree. - */ - interface TreeListener { - /** - * Notification that this listener has been closed. - */ - void onClose(); - - /** - * Notification that a topic has been added. - * - * @param topicPath the topic path - * @param specification the topic specification - */ - void onTopicAdded(String topicPath, TopicSpecification specification); - - /** - * Notification that a topic has been removed. - * - * @param topicPath the topic path - * @param specification the topic specification - */ - void onTopicRemoved(String topicPath, TopicSpecification specification); - } - - /** - * Advanced example of walking the topic tree from a given root path in - * conjunction with a GUI system, with each topic that the GUI is notified - * about providing a means to descend further down the topic tree in - * reaction to user-controlled events. - *

- * With topics at the following paths: - * - *

-     * a
-     * a/b
-     * a/b/c/d
-     * a/e
-     * a/e/f
-     * 
- * - * Running the following code will result in the GUI being notified of topic - * {@code "a"}: - * - *
-     * // Some abstract GUI reference
-     * GUI gui = new GUI() {
-     *      void onTopicAdded(
-     *          String topicPath,
-     *          TopicSpecification specification,
-     *          Consumer<Boolean> selectDescendants) {
-     *          ...
-     *      }
-     *
-     *      void onTopicRemoved(String topicPath) {
-     *          ...
-     *      }
-     * };
-     *
-     * walkTree("a", new TreeWalker() {
-     *     void onTopicAdded(
-     *         TreeNode node,
-     *         TopicSpecification specification) {
-     *              // Add a selected topic and its specification to the GUI,
-     *              // along with a function to toggle selection of
-     *              // the node's immediate descendants
-     *              gui.onTopicAdded(
-     *                  node.getTopicPath(),
-     *                  specification,
-     *                  node::selectDescendants);
-     *     }
-     *
-     *     void onTopicRemoved(TreeNode node) {
-     *         // Remove a selected topic from the GUI
-     *         gui.onTopicRemoved(node.getTopicPath());
-     *     }
-     * });
-     * 
- * - * Once the callback provided to the GUI to select descendants is invoked - * (such as by a user clicking to 'expand' the tree), the walker will be - * notified of topics {@code "a/b"} and {@code "a/e"}. For each of those - * topics, the GUI can choose to select the descendants of that path. When - * the GUI decides to expand {@code "a/b"}, it will then be informed of - * topic {@code "a/b/c/d"}. - *

- * When the returned {@code Closeable} is invoked to close the walker, the - * GUI will be informed of the removal of all topics. No further - * interactions will occur. - * - * @param rootPath the root topic path from which to begin walking the topic - * tree - * @param walker the tree walker to receive topic notifications - * @return a closeable to allow deregistration of the tree walker - * @throws Exception - */ - public Closeable walkTree(String rootPath, TreeWalker walker) - throws Exception { - - final InternalListener listener = - new InternalListener(rootPath, walker); - - final CompletableFuture registration = - notifications.addListener(listener); - - registration.thenAccept(listener::initialise); - - return new Closeable() { - @Override - public void close() throws IOException { - registration.thenAccept(Registration::close); - } - }; - } - - /** - * Callback interface for walking the topic tree via {@link #walkTree}. - */ - interface TreeWalker { - /** - * Notification that a topic has been added. - * - * @param node the tree node for this topic - * @param specification the topic specification for this topic - */ - void onTopicAdded(TreeNode node, TopicSpecification specification); - - /** - * Notification that a topic has been removed. - * - * @param node the tree node for this topic - */ - void onTopicRemoved(TreeNode node); - } - - /** - * Representation of a bound topic path, providing navigation operations for - * walking further down the tree. - */ - interface TreeNode { - /** - * @return the topic path that this node references - */ - String getTopicPath(); - - /** - * Toggle whether immediate descendants of this topic node should be - * selected or not. - * - * @param select {@code true} if this node should select immediate - * descendants - */ - void selectDescendants(boolean select); - } - - /** - * An internal implementation of TopicNotificationListener, providing a - * means of registering new listeners for each exposed TreeNode, and - * maintaining references to child nodes that have been created. - */ - private static class InternalListener - extends TopicNotificationListener.Default { - - private final ConcurrentMap topicNodes = - new ConcurrentHashMap<>(); - - private volatile NotificationRegistration registration; - - private final String rootPath; - private final TreeWalker walker; - - /** - * Constructor. - * - * @param rootPath the root path - * @param walker the associated tree walker - */ - InternalListener(String rootPath, TreeWalker walker) { - this.rootPath = rootPath; - this.walker = walker; - } - - public void initialise(NotificationRegistration newRegistration) { - registration = newRegistration; - registration.select(rootPath); - } - - @Override - public void onTopicNotification( - String topicPath, - TopicSpecification specification, - NotificationType type) { - - if (type == NotificationType.ADDED || - type == NotificationType.SELECTED) { - final InternalTreeNode node = - new InternalTreeNode(registration, topicPath); - - topicNodes.put(topicPath, node); - walker.onTopicAdded(node, specification); - } - else { - walker.onTopicRemoved(topicNodes.remove(topicPath)); - } - } - - @Override - public void onDescendantNotification( - String topicPath, - NotificationType type) { - - InternalTreeNode parent = null; - String path = topicPath; - - // Walk up the path until we find the closest registered topic - while (true) { - final int index = path.lastIndexOf("/"); - - if (index == -1) { - break; - } - - path = path.substring(0, index); - parent = topicNodes.get(path); - - if (parent != null) { - break; - } - } - - // If we don't have any parent nodes, then we're at the root path - - // so just directly select it - if (parent == null) { - registration.select(topicPath); - } - // Otherwise, add to the registered node, and let the 'select - // descendants' toggle determine if we select - else if (type == NotificationType.ADDED || - type == NotificationType.SELECTED) { - parent.addDescendant(topicPath); - } - else { - parent.removeDescendant(topicPath); - } - } - - @Override - public void onClose() { - - final List pathsToRemove = - new ArrayList<>(topicNodes.keySet()); - - // Sort by length – longer paths are lower in the topic tree, - // so we remove topics by walking up the - // tree - pathsToRemove.sort((s1, s2) -> s1.length() > s2.length() ? -1 : - s2.length() > s1.length() ? 1 : 0); - - for (String topicPath : pathsToRemove) { - walker.onTopicRemoved(topicNodes.remove(topicPath)); - } - } - - private class InternalTreeNode implements TreeNode { - - // Maintain a list of all unselected topics below this node - private final List descendants = new ArrayList<>(); - - private final NotificationRegistration registration; - private final String topicPath; - - private boolean selectsDescendants = false; - - InternalTreeNode( - NotificationRegistration registration, - String topicPath) { - this.registration = registration; - this.topicPath = topicPath; - } - - @Override - public String getTopicPath() { - return topicPath; - } - - @Override - public synchronized void selectDescendants(boolean selects) { - selectsDescendants = selects; - - if (selectsDescendants) { - for (String descendant : descendants) { - registration.select(descendant); - } - } - } - - public synchronized void addDescendant(String descendantPath) { - descendants.add(descendantPath); - - if (selectsDescendants) { - registration.select(descendantPath); - } - } - - public synchronized void removeDescendant(String descendantPath) { - descendants.remove(descendantPath); - - if (selectsDescendants) { - registration.deselect(descendantPath); - } - } - } - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientUpdatingJSONTopics.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientUpdatingJSONTopics.java deleted file mode 100644 index 793fa64d..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientUpdatingJSONTopics.java +++ /dev/null @@ -1,167 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2016, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import static com.pushtechnology.diffusion.client.Diffusion.newTopicSpecification; -import static com.pushtechnology.diffusion.client.topics.details.TopicSpecification.REMOVAL; -import static java.util.Objects.requireNonNull; -import static java.util.concurrent.TimeUnit.SECONDS; - -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeoutException; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.TopicUpdate; -import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; -import com.pushtechnology.diffusion.client.topics.details.TopicType; -import com.pushtechnology.diffusion.datatype.json.JSON; -import com.pushtechnology.diffusion.datatype.json.JSONDataType; - -/** - * This example shows a control client creating a JSON topic and sending updates - * to it. - *

- * There will be a topic for each currency for which rates are provided. The - * topic will be created under the FX topic - so, for example FX/GBP will - * contain a map of all rate conversions from the base GBP currency. The rates - * are represented as string decimal values (e.g. "12.457"). - *

- * Topic values are represented in JSON format e.g. {"USD":"123.45","HKD":"456.3"} - * for which the corresponding JSONString would be "{\"USD\":\"123.45\",\"HKD\":\"456.3\"}" - *

- * The {@code addRates} method shows how to create a new rates topic, specifying - * its initial values in a JSON string. - *

- * The {@code changeRates} method which takes a JSON string shows how to completely - * replace the set of rates for a currency with new values. - *

- * After the first usage of changeRates for any topic the value is cached, - * and so subsequent set calls can compare with the last value - * and send only the differences to the server. - * - * @author DiffusionData Limited - * @since 5.7 - * @see ClientConsumingJSONTopics - */ -public final class ControlClientUpdatingJSONTopics { - - private static final String ROOT_TOPIC = "FX"; - - private final Session session; - private final TopicControl topicControl; - private final TopicUpdate topicUpdate; - private final TopicSpecification topicSpecification; - private final JSONDataType jsonDataType = Diffusion.dataTypes().json(); - - /** - * Constructor. - * - * @param serverUrl for example "ws://diffusion.example.com:80" - */ - public ControlClientUpdatingJSONTopics(String serverUrl) - throws InterruptedException, ExecutionException, TimeoutException { - - session = - Diffusion.sessions().principal("control").password("password") - .open(serverUrl); - - topicControl = session.feature(TopicControl.class); - topicUpdate = session.feature(TopicUpdate.class); - topicSpecification = newTopicSpecification(TopicType.JSON); - - - - // Create the root topic that will remove itself when the session closes - final TopicSpecification specification = - topicSpecification - .withProperty(REMOVAL, - "When this session closes remove '?" + ROOT_TOPIC + "//'"); - - topicControl.addTopic(ROOT_TOPIC, specification).get(5, SECONDS); - } - - /** - * Add a new rates topic and sets initial values. - * - * @param currency the base currency - * @param value JSON string of initial rates values - */ - public void addRates( - String currency, - String value) { - topicUpdate - .addAndSet(rateTopicName(currency), - topicSpecification, - JSON.class, - jsonDataType.fromJsonString(value)); - } - - /** - * Update an existing rates topic. - * - * @param currency the base currency - * @param jsonString a JSON string specifying the map of currency rates - * @return a CompletableFuture that completes when a response is received - * from the server - */ - public CompletableFuture changeRates( - String currency, - String jsonString) - throws IllegalArgumentException { - - return topicUpdate.set( - rateTopicName(currency), - JSON.class, - jsonDataType.fromJsonString(jsonString)); - } - - /** - * Remove a rates entry (removes its topic). - * - * @param currency the currency - * - * @return a CompletableFuture that completes when a response is received - * from the server - */ - public CompletableFuture removeRates(String currency) { - - final String topicName = rateTopicName(currency); - - return topicControl.removeTopics(topicName); - } - - /** - * Close the session. - */ - public void close() { - session.close(); - } - - /** - * Generate a hierarchical topic name for a rates topic. - *

- * e.g. for currency=GBP would return "FX/GBP". - * - * @param currency the currency - * @return the topic name - */ - private static String rateTopicName(String currency) { - return String.format("%s/%s", ROOT_TOPIC, requireNonNull(currency)); - } - -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientUpdatingJSONTopicsWithCBOR.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientUpdatingJSONTopicsWithCBOR.java deleted file mode 100644 index bcbda721..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientUpdatingJSONTopicsWithCBOR.java +++ /dev/null @@ -1,187 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import static com.pushtechnology.diffusion.client.Diffusion.newTopicSpecification; -import static com.pushtechnology.diffusion.client.topics.details.TopicSpecification.REMOVAL; -import static java.util.Objects.requireNonNull; -import static java.util.concurrent.TimeUnit.SECONDS; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeoutException; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.dataformat.cbor.CBORFactory; -import com.fasterxml.jackson.dataformat.cbor.CBORGenerator; -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.TopicUpdate; -import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; -import com.pushtechnology.diffusion.client.topics.details.TopicType; -import com.pushtechnology.diffusion.datatype.json.JSON; -import com.pushtechnology.diffusion.datatype.json.JSONDataType; - -/** - * This example shows a control client creating a JSON topic and sending updates - * using a CBOR-format binary. - *

- * There will be a topic for each currency for which rates are provided. The - * topic will be created under the FX topic - so, for example FX/GBP will - * contain a map of all rate conversions from the base GBP currency. The rates - * are represented as string decimal values (e.g. "12.457"). - *

- * Topic values are represented in JSON format e.g. {"USD":"123.45","HKD":"456.3"}. - *

- * The {@code addRates} method shows how to create a new rates topic, specifying - * its initial map of values. - *

- * The {@code changeRates} method which takes a map shows how to completely - * replace the set of rates for a currency with a new map of rates. - *

- * After the first usage of changeRates for any topic the values is cached, - * and so subsequent set calls can compare with the last value - * and send only the differences to the server. - * - * @author DiffusionData Limited - * @since 6.8 - * @see ClientConsumingJSONTopics - */ -public final class ControlClientUpdatingJSONTopicsWithCBOR { - - private static final String ROOT_TOPIC = "FX"; - - private final Session session; - private final TopicControl topicControl; - private final TopicUpdate topicUpdate; - private final TopicSpecification topicSpecification; - private final CBORFactory cborFactory = new CBORFactory(); - private final JSONDataType jsonDataType = Diffusion.dataTypes().json(); - - /** - * Constructor. - * - * @param serverUrl for example "ws://diffusion.example.com:80" - */ - public ControlClientUpdatingJSONTopicsWithCBOR(String serverUrl) - throws InterruptedException, ExecutionException, TimeoutException { - - cborFactory.setCodec(new ObjectMapper()); - - session = - Diffusion.sessions().principal("control").password("password") - .open(serverUrl); - - topicControl = session.feature(TopicControl.class); - topicUpdate = session.feature(TopicUpdate.class); - topicSpecification = newTopicSpecification(TopicType.JSON); - - // Create the root topic that will remove itself when the session closes - final TopicSpecification specification = - topicSpecification - .withProperty(REMOVAL, - "When this session closes remove '?" + ROOT_TOPIC + "//'"); - - topicControl.addTopic(ROOT_TOPIC, specification).get(5, SECONDS); - } - - /** - * Add a new rates topic and sets initial values. - * - * @param currency the base currency - * @param value the full map of initial rates values - * @throws IOException - * @throws UnsupportedOperationException - * @throws IllegalArgumentException - */ - public void addRates( - String currency, Map value) - throws IllegalArgumentException, UnsupportedOperationException, IOException { - topicUpdate - .addAndSet(rateTopicName(currency), - topicSpecification, - JSON.class, - mapToJSON(value)); - } - - /** - * Update an existing rates topic, replacing the rates mappings with a new - * set of mappings. - * - * @param currency the base currency - * @param values the new rates values - * @return a CompletableFuture that completes when a response is received - * from the server - * @throws IOException if unable to convert rates map - */ - public CompletableFuture changeRates( - String currency, - Map values) throws IOException { - - return topicUpdate.set( - rateTopicName(currency), - JSON.class, - mapToJSON(values)); - } - - /** - * Convert a given map to a JSON object. - */ - private JSON mapToJSON(Map values) throws IOException { - // Use the third-party Jackson library to write out the values map as a - // CBOR-format binary. - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - final CBORGenerator generator = cborFactory.createGenerator(baos); - generator.writeObject(values); - return jsonDataType.readValue(baos.toByteArray()); - } - - /** - * Remove a rates entry (removes its topic). - * - * @param currency the currency - * - * @return a CompletableFuture that completes when a response is received - * from the server - */ - public CompletableFuture removeRates(String currency) { - final String topicName = rateTopicName(currency); - return topicControl.removeTopics(topicName); - } - - /** - * Close the session. - */ - public void close() { - session.close(); - } - - /** - * Generate a hierarchical topic name for a rates topic. - *

- * e.g. for currency=GBP would return "FX/GBP". - * - * @param currency the currency - * @return the topic name - */ - private static String rateTopicName(String currency) { - return String.format("%s/%s", ROOT_TOPIC, requireNonNull(currency)); - } - -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientUpdatingRecordV2Topics.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientUpdatingRecordV2Topics.java deleted file mode 100644 index d112d050..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientUpdatingRecordV2Topics.java +++ /dev/null @@ -1,223 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2017, 2019 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import static com.pushtechnology.diffusion.client.Diffusion.newTopicSpecification; -import static com.pushtechnology.diffusion.client.topics.details.TopicSpecification.REMOVAL; -import static com.pushtechnology.diffusion.client.topics.details.TopicSpecification.SCHEMA; -import static com.pushtechnology.diffusion.client.topics.details.TopicType.RECORD_V2; -import static com.pushtechnology.diffusion.client.topics.details.TopicType.STRING; -import static java.util.concurrent.TimeUnit.SECONDS; - -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeoutException; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.TopicUpdate; -import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; -import com.pushtechnology.diffusion.datatype.recordv2.RecordV2; -import com.pushtechnology.diffusion.datatype.recordv2.RecordV2DataType; -import com.pushtechnology.diffusion.datatype.recordv2.model.MutableRecordModel; -import com.pushtechnology.diffusion.datatype.recordv2.schema.Schema; - -/** - * An example of using a control client to create and update a RecordV2 topic in - * exclusive mode. - *

- * This uses the 'TopicControl' feature to create a topic and the - * 'TopicUpdate' feature to send updates to it. - *

- * To send updates to a topic, the client session requires the 'update_topic' - * permission for that branch of the topic tree. - *

- * The example can be used with or without the use of a schema. This is simply - * to demonstrate the different mechanisms and is not necessarily demonstrating - * the most efficient way to update such a topic. - * - * @author DiffusionData Limited - * @since 6.0 - * @see ClientConsumingRecordV2Topics - */ -public final class ControlClientUpdatingRecordV2Topics { - - private static final String ROOT_TOPIC = "FX"; - - private final Session session; - private final TopicControl topicControl; - private final TopicSpecification topicSpecification; - private final Schema schema; - private final RecordV2DataType dataType; - - /** - * Constructor. - * - * @param serverUrl for example "ws://diffusion.example.com:80" - */ - public ControlClientUpdatingRecordV2Topics( - String serverUrl, - boolean withSchema) - throws InterruptedException, ExecutionException, TimeoutException { - - session = - Diffusion.sessions().principal("control").password("password") - .open(serverUrl); - - topicControl = session.feature(TopicControl.class); - - // Create the root topic that will remove itself when the session closes - final TopicSpecification specification = - newTopicSpecification(STRING) - .withProperty( - REMOVAL, - "when this session closes remove '?" + ROOT_TOPIC + "//'"); - - topicControl.addTopic(ROOT_TOPIC, specification).get(5, SECONDS); - - dataType = Diffusion.dataTypes().recordV2(); - - if (withSchema) { - schema = dataType.schemaBuilder() - .record("Rates").decimal("Bid", 5).decimal("Ask", 5).build(); - // Create the topic specification to be used for all rates topics - topicSpecification = - newTopicSpecification(RECORD_V2) - .withProperty( - SCHEMA, - schema.asJSONString()); - } - else { - schema = null; - // Create the topic specification to be used for all rates topics - topicSpecification = - newTopicSpecification(RECORD_V2); - } - } - - /** - * Adds a new conversion rate in terms of base currency and target currency. - * - * The bid and ask rates are entered as strings which may be a decimal value - * which will be parsed and validated, rounding to 5 decimal places. - * - * @param currency the base currency (e.g. GBP) - * - * @param targetCurrency the target currency (e.g. USD) - */ - public void addRateTopic( - String currency, - String targetCurrency) - throws InterruptedException, ExecutionException, TimeoutException { - - topicControl.addTopic( - rateTopicName(currency, targetCurrency), - topicSpecification).get(5, SECONDS); - } - - /** - * Set a rate. - *

- * The rate topic in question must have been added first using - * {@link #addRateTopic} otherwise this will fail. - * - * @param currency the base currency - * - * @param targetCurrency the target currency - * - * @param bid the new bid rate - * - * @param ask the new ask rate - * @return a CompletableFuture that completes when a response is received - * from the server - */ - public CompletableFuture setRate( - String currency, - String targetCurrency, - String bid, - String ask) { - - final RecordV2 value; - if (schema == null) { - value = dataType.valueBuilder().addFields(bid, ask).build(); - } - else { - // Mutable models could be kept and reused but for this simple - // example one is created every time - final MutableRecordModel model = - schema.createMutableModel(); - model.set("Bid", bid); - model.set("Ask", ask); - value = model.asValue(); - } - - return session.feature(TopicUpdate.class).set( - rateTopicName(currency, targetCurrency), - RecordV2.class, - value); - } - - /** - * Remove a rate (removes its topic). - * - * @param currency the base currency - * - * @param targetCurrency the target currency - */ - public void removeRate( - String currency, - String targetCurrency) - throws InterruptedException, ExecutionException, TimeoutException { - - topicControl.removeTopics( - rateTopicName(currency, targetCurrency)) - .get(5, SECONDS); - } - - /** - * Removes a currency (removes its topic and all subordinate rate topics). - * - * @param currency the base currency - */ - public void removeCurrency(String currency) - throws InterruptedException, ExecutionException, TimeoutException { - topicControl - .removeTopics(String.format("?%s/%s//", ROOT_TOPIC, currency)) - .get(5, SECONDS); - } - - /** - * Close the session. - */ - public void close() throws InterruptedException { - session.close(); - } - - /** - * Generates a hierarchical topic name for a rate topic. - *

- * e.g. for currency=GBP and targetCurrency=USD would return "FX/GBP/USD". - * - * @param currency the base currency - * @param targetCurrency the target currency - * @return the topic name - */ - private static String rateTopicName(String currency, - String targetCurrency) { - return String.format("%s/%s/%s", ROOT_TOPIC, currency, targetCurrency); - } - -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientUpdatingSimpleTopics.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientUpdatingSimpleTopics.java deleted file mode 100644 index 898acb74..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientUpdatingSimpleTopics.java +++ /dev/null @@ -1,93 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2017, 2019 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import static com.pushtechnology.diffusion.client.Diffusion.newTopicSpecification; -import static com.pushtechnology.diffusion.client.topics.details.TopicSpecification.REMOVAL; -import static com.pushtechnology.diffusion.client.topics.details.TopicType.STRING; -import static java.util.concurrent.TimeUnit.SECONDS; - -import java.util.concurrent.CompletableFuture; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.TopicUpdate; -import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; - -/** - * An example of using a control client to create and update a simple scalar - * topic in non exclusive mode (as opposed to acting as an exclusive update - * source). In this mode other clients could update the same topic (on a last - * update wins basis). - *

- * This uses the 'TopicControl' feature to create a topic and the - * 'TopicUpdate' feature to send updates to it. - *

- * To send updates to a topic, the client session requires the 'update_topic' - * permission for that branch of the topic tree. - * - * @author DiffusionData Limited - * @since 6.0 - */ -public final class ControlClientUpdatingSimpleTopics { - - private static final String TOPIC = "StringTopic"; - - private final Session session; - - /** - * Constructor. - * - * @param serverUrl for example "ws://diffusion.example.com:80" - */ - public ControlClientUpdatingSimpleTopics(String serverUrl) throws Exception { - - session = - Diffusion.sessions().principal("control").password("password") - .open(serverUrl); - - final TopicControl topicControl = session.feature(TopicControl.class); - - // Create the topic and request that it is removed when the session - // closes - final TopicSpecification specification = - newTopicSpecification(STRING) - .withProperty( - REMOVAL, - "when this session closes remove '?" + TOPIC + "//'"); - - topicControl.addTopic(TOPIC, specification).get(5, SECONDS); - } - - /** - * Update the topic with a string value. - * - * @param value the update value - * @return a CompletableFuture that completes when a response is received - * from the server - */ - public CompletableFuture update(String value) { - return session.feature(TopicUpdate.class) - .set(TOPIC, String.class, value); - } - - /** - * Close the session. - */ - public void close() { - session.close(); - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientUpdatingTimeSeriesTopics.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientUpdatingTimeSeriesTopics.java deleted file mode 100644 index 7a2ac552..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientUpdatingTimeSeriesTopics.java +++ /dev/null @@ -1,140 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2017, 2020 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import static com.pushtechnology.diffusion.client.Diffusion.newTopicSpecification; -import static com.pushtechnology.diffusion.datatype.DataTypes.INT64_DATATYPE_NAME; - -import java.time.Instant; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.TimeSeries; -import com.pushtechnology.diffusion.client.features.TimeSeries.EventMetadata; -import com.pushtechnology.diffusion.client.features.TopicUpdate; -import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; -import com.pushtechnology.diffusion.client.topics.details.TopicType; - -/** - * This example shows a control client creating a {@link TimeSeries} topic. - * Values can be appended to the topic using {@link #appendValue(long)}, and - * the last value of the topic can be edited using {@link #editLast(long)}. - * Alternatively, the methods provided by the {@link TopicUpdate} feature can be - * used. See {@link TopicUpdateExample} for example usages of this API. - * - * @author DiffusionData Limited - * @since 6.0 - * @see ClientConsumingTimeSeriesTopics - * @see TimeSeriesQueryExample - */ -public class ControlClientUpdatingTimeSeriesTopics { - - private static final String TOPIC_PATH = "foo/timeseries"; - private static final Logger LOG = - LoggerFactory.getLogger(ControlClientUpdatingTimeSeriesTopics.class); - - private final Session session; - private final TimeSeries timeSeries; - private final TopicControl topicControl; - - /** - * Constructor. - * - * @param serverUrl server URL to connect to example "ws://diffusion.example.com:80" - */ - public ControlClientUpdatingTimeSeriesTopics(String serverUrl) - throws InterruptedException, ExecutionException, TimeoutException { - - session = Diffusion.sessions().principal("control").password("password") - .open(serverUrl); - - timeSeries = session.feature(TimeSeries.class); - topicControl = session.feature(TopicControl.class); - - final TopicSpecification spec = newTopicSpecification(TopicType.TIME_SERIES) - .withProperty(TopicSpecification.TIME_SERIES_EVENT_VALUE_TYPE, INT64_DATATYPE_NAME); - - topicControl.addTopic(TOPIC_PATH, spec) - .thenAccept(result -> LOG.info("Add topic result: {}", result)).get(5, TimeUnit.SECONDS); - } - - /** - * Appends a value to the time series topic. - * - * @param value value to append - * @return the event metadata from the successful append - */ - public EventMetadata appendValue(long value) - throws IllegalArgumentException, InterruptedException, ExecutionException, TimeoutException { - return timeSeries.append(TOPIC_PATH, Long.class, value).get(5, TimeUnit.SECONDS); - } - - /** - * Close the session and remove the time series topic. - */ - public void close() - throws IllegalArgumentException, InterruptedException, ExecutionException, TimeoutException { - topicControl.removeTopics("?foo//").get(5, TimeUnit.SECONDS); - session.close(); - } - - /** - * Edit the last value in a time series topic. - * - * @param value value to edit with - */ - public void editLast(long value) { - //Obtain the last value in the time series topic - timeSeries.rangeQuery().fromLast(1).as(Long.class).selectFrom(TOPIC_PATH) - .whenComplete((query, ex) -> { - if (ex != null) { - LOG.error("Error obtaining the range query: {}", ex); - return; - } - //Perform the value edit - query.stream().forEach(event -> { - timeSeries.edit(TOPIC_PATH, event.sequence(), Long.class, value) - .whenComplete((metadata, e) -> { - if (e != null) { - LOG.error("Error editing topic: {}", e); - return; - } - LOG.info("EventMetadata from edit: {}", metadata); - }); - }); - }); - } - - /** - * Appends a value to the time series topic. Allows for creation of events - * with a custom timestamp. This can be used for loading historic or future - * values. - * - * @param value value to append - * @param timestamp the user supplied timestamp - * @return the event metadata from the successful append - */ - public EventMetadata appendValue(long value, Instant timestamp) - throws IllegalArgumentException, InterruptedException, ExecutionException, TimeoutException { - return timeSeries.append(TOPIC_PATH, Long.class, value, timestamp).get(5, TimeUnit.SECONDS); - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientUsingFiltersAndProperties.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientUsingFiltersAndProperties.java deleted file mode 100644 index be7bcc56..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientUsingFiltersAndProperties.java +++ /dev/null @@ -1,117 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015, 2020 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.callbacks.ErrorReason; -import com.pushtechnology.diffusion.client.features.Messaging; -import com.pushtechnology.diffusion.client.features.Messaging.FilteredRequestCallback; -import com.pushtechnology.diffusion.client.features.Messaging.RequestHandler; -import com.pushtechnology.diffusion.client.session.Session; - -/** - * This is an example of a control client using the 'Messaging' feature to send - * messages to clients using message filters. It also demonstrates the ability - * to register a request handler with an interest in session property values. - * - * @author DiffusionData Limited - * @since 5.5 - */ -public final class ControlClientUsingFiltersAndProperties { - - private final Session session; - private final Messaging messaging; - - private static final FilteredRequestCallback FILTERED_CALLBACK = - new FilteredRequestCallback.Default<>(); - - /** - * Constructor. - * @throws TimeoutException - * @throws ExecutionException - * @throws InterruptedException - */ - public ControlClientUsingFiltersAndProperties(String serverUrl) - throws InterruptedException, ExecutionException, TimeoutException { - - session = - Diffusion.sessions().principal("control").password("password") - .open(serverUrl); - - messaging = session.feature(Messaging.class); - - // Register to receive all messages sent by clients on the "foo" branch - // and include the "JobTitle" session property value with each message. - // To do this, the client session must have the 'register_handler' - // permission. - messaging.addRequestHandler( - "foo", - String.class, - String.class, - new BroadcastHandler(), - "JobTitle").get(5, TimeUnit.SECONDS); - } - - /** - * Close the session. - */ - public void close() { - session.close(); - } - - /** - * Handler that will pass any message to all sessions that have a "JobTitle" - * property set to "Staff" if, and only if it comes from a session that has - * a "JobTitle" set to "Manager". - */ - private class BroadcastHandler implements RequestHandler { - - @Override - public void onRequest( - String request, - RequestContext context, - final Responder responder) { - - if ("Manager".equals( - context.getSessionProperties().get("JobTitle"))) { - messaging.sendRequestToFilter( - "JobTitle is 'Staff'", - "foo", - request, - String.class, - String.class, - FILTERED_CALLBACK) - .thenAccept(sentTo -> - responder.respond("Sent to " + sentTo + " staff")); - } - else { - responder.respond("Not sent"); - } - } - - @Override - public void onClose() { - } - - @Override - public void onError(ErrorReason errorReason) { - } - } - -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientUsingSessionProperties.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientUsingSessionProperties.java deleted file mode 100644 index 3bfd51c0..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientUsingSessionProperties.java +++ /dev/null @@ -1,133 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015, 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.control.clients.ClientControl; -import com.pushtechnology.diffusion.client.features.control.topics.SubscriptionControl; -import com.pushtechnology.diffusion.client.features.control.topics.SubscriptionControl.SubscriptionByFilterResult; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.session.SessionId; - -/** - * This is an example of a control client using both the 'ClientControl' feature - * and the 'SubscriptionControl' feature to monitor and subscribe clients. - *

- * The example shows a control client that configures all clients that are in - * Italy and are in the "Accounts" department (determined by an additional - * property) to be subscribed to the "ITAccounts" topic. - *

- * It also has a method which makes use of filtered subscription to change the - * topic that all matching clients are subscribed to. - * - * @author DiffusionData Limited - * @since 5.6 - */ -public final class ControlClientUsingSessionProperties { - - private final Session session; - private final ClientControl clientControl; - private final SubscriptionControl subscriptionControl; - - private volatile String currentTopic = "ITAccounts"; - - /** - * Constructor. - */ - public ControlClientUsingSessionProperties() { - - session = - Diffusion.sessions().principal("control").password("password") - .open("ws://diffusion.example.com:80"); - - clientControl = session.feature(ClientControl.class); - subscriptionControl = session.feature(SubscriptionControl.class); - - /** - * Configure a listener will be notified firstly of all open client - * sessions and then of all that subsequently open. All that are in the - * Italian Accounts department get subscribed to the current topic. - * The country and department properties only are requested. - */ - clientControl.setSessionPropertiesListener( - new ClientControl.SessionPropertiesListener.Default() { - @Override - public void onSessionOpen( - SessionId sessionId, - Map properties) { - - if ("Accounts".equals(properties.get("Department")) && - "IT".equals(properties.get("$Country"))) { - - subscriptionControl.subscribe( - sessionId, - currentTopic); - } - } - }, - "$Country", "$Department"); - } - - /** - * This can be used to change the topic that all of the Italian accounts - * department is subscribed to. It will unsubscribe all current clients from - * the old topic and subscribe them to the new one. All new clients will be - * subscribed to the new one. - * - * @param newTopic the new topic name - * @return a CompletableFuture that completes when the operation succeeds or - * fails. - * - *

- * If the operation was successful, the CompletableFuture will - * complete successfully. - * - *

- * Otherwise, the CompletableFuture will complete exceptionally with - * an {@link ExecutionException}. See - * {@link SubscriptionControl#unsubscribeByFilter} and - * {@link SubscriptionControl#subscribeByFilter} for common failure - * reasons. - */ - public CompletableFuture - changeTopic(String newTopic) { - - final String filter = "Department is 'Accounts' and $Country is 'IT'"; - - final String oldTopic = currentTopic; - // Change the topic that all new clients will be subscribed to. - currentTopic = newTopic; - - return - // Unsubscribe all from the current topic... - subscriptionControl.unsubscribeByFilter(filter, oldTopic) - - // ...then subscribe all to the new topic... - .thenCompose(unsubscriptionResult -> - subscriptionControl.subscribeByFilter(filter, currentTopic)); - } - - /** - * Close the session. - */ - public void close() { - session.close(); - } - -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientUsingTopicLifecycleProperties.java b/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientUsingTopicLifecycleProperties.java deleted file mode 100644 index 6766ed2e..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/ControlClientUsingTopicLifecycleProperties.java +++ /dev/null @@ -1,286 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018, 2019 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import static com.pushtechnology.diffusion.client.Diffusion.newTopicSpecification; -import static com.pushtechnology.diffusion.client.topics.details.TopicSpecification.OWNER; -import static com.pushtechnology.diffusion.client.topics.details.TopicSpecification.PERSISTENT; -import static com.pushtechnology.diffusion.client.topics.details.TopicSpecification.REMOVAL; -import static com.pushtechnology.diffusion.client.topics.details.TopicType.STRING; -import static java.util.concurrent.TimeUnit.SECONDS; - -import java.util.Date; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeoutException; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; -import com.pushtechnology.diffusion.client.topics.details.TopicType; - -/** - * An example of using a control client to create topics using the various topic - * lifecycle properties. - *

- * This also includes an example of how to create a branch of the topic tree - * that is for the specific use of a named principal and will be automatically - * removed when the principal no longer has a session. - *

- * For simplicity all topics created are {@link TopicType#STRING string} topics. - * Also for simplicity all topic creations are blocking and there is no specific - * error handling. - * - * @author DiffusionData Limited - * @since 6.1 - */ -public final class ControlClientUsingTopicLifecycleProperties { - - private final Session session; - private final TopicControl topicControl; - private final TopicSpecification stringSpecification; - - /** - * Constructor. - * - * @param serverUrl for example "ws://diffusion.example.com:80" - */ - public ControlClientUsingTopicLifecycleProperties(String serverUrl) - throws Exception { - - session = - Diffusion.sessions().principal("control").password("password") - .open(serverUrl); - - topicControl = session.feature(TopicControl.class); - - stringSpecification = newTopicSpecification(STRING); - - } - - /** - * Creates a topic that will be removed after a specified date and time. - */ - public void createTopicRemovedAfter(String topicPath, Date dateAndTime) - throws IllegalArgumentException, InterruptedException, - ExecutionException, TimeoutException { - - topicControl.addTopic( - topicPath, - stringSpecification - .withProperty( - REMOVAL, - "when time after " + dateAndTime.getTime())) - .get(5, SECONDS); - } - - /** - * Creates a topic that will be removed after a a time specified in RFC_1123 - * format (e.g. "Sun, 3 Jun 2018 11:05:30 GMT"). The topic itself and all - * descendants of the topic will be removed after the specified time. - */ - public void createTopicRemovedAfter(String topicPath, String dateAndTime) - throws IllegalArgumentException, InterruptedException, - ExecutionException, TimeoutException { - - topicControl.addTopic( - topicPath, - stringSpecification - .withProperty( - REMOVAL, - "when time after '" + dateAndTime + "' remove '*" + - topicPath + "//'")) - .get(5, SECONDS); - } - - /** - * Creates a topic that will be removed when it has had no subscriptions for - * 5 minutes after an initial period of 1 hour. - */ - public void createTopicRemovedWhenNoSubscriptions(String topicPath) - throws IllegalArgumentException, InterruptedException, - ExecutionException, TimeoutException { - - topicControl.addTopic( - topicPath, - stringSpecification - .withProperty( - REMOVAL, - "when subscriptions < 1 for 5m after 1h")) - .get(5, SECONDS); - } - - /** - * Creates a topic that will be removed when it has had no updates for 5 - * minutes after an initial period of 1 hour. - */ - public void createTopicRemovedWhenNoUpdates(String topicPath) - throws IllegalArgumentException, InterruptedException, - ExecutionException, TimeoutException { - - topicControl.addTopic( - topicPath, - stringSpecification - .withProperty( - REMOVAL, - "when no updates for 5m after 1h")) - .get(5, SECONDS); - } - - /** - * Creates a topic that will be removed when the session creating it closes. - */ - public void createTopicRemovedWhenSessionCloses(String topicPath) - throws IllegalArgumentException, InterruptedException, - ExecutionException, TimeoutException { - - topicControl.addTopic( - topicPath, - stringSpecification - .withProperty( - REMOVAL, - "when this session closes")) - .get(5, SECONDS); - } - - /** - * Creates a topic that will be removed when there are have been no sessions - * authenticated with the given principal for 30 minutes. - */ - public void createTopicRemovedWhenNoPrincipal( - String topicPath, - String principal) - throws IllegalArgumentException, InterruptedException, - ExecutionException, TimeoutException { - - topicControl.addTopic( - topicPath, - stringSpecification - .withProperty( - REMOVAL, - "when no session has '$Principal is \"" + - principal + - "\"' for 30m")) - .get(5, SECONDS); - } - - /** - * Creates a topic that will be removed when there are have been no sessions - * with the 'Department' session property set to 'Accounts' for 1 hour but - * only checking after 1 day has elapsed. - */ - public void createTopicRemovedWhenNoAccountsSession(String topicPath) - throws IllegalArgumentException, InterruptedException, - ExecutionException, TimeoutException { - - topicControl.addTopic( - topicPath, - stringSpecification - .withProperty( - REMOVAL, - "when no session has 'Department is \"Accounts\"' for 1h after 1d")) - .get(5, SECONDS); - } - - /** - * Creates a topic that will be removed when a specified date and time (in - * RFC_1123 format) has passed AND either the topic has had no subscriptions - * for a continuous period of 10 minutes after that time plus one hour OR it - * has had no updates for a continuous period of 20 minutes. - */ - public void createTopicRemovedWhenTimeAfterAndNoSubscriptionsOrUpdates( - String topicPath, - String dateAndTime) - throws IllegalArgumentException, InterruptedException, - ExecutionException, TimeoutException { - - topicControl.addTopic( - topicPath, - stringSpecification - .withProperty( - REMOVAL, - "when time after '" + dateAndTime + - "' and (subscriptions < 1 for 10m after 1h or no updates for 20m) ")) - .get(5, SECONDS); - } - - /** - * Creates a topic that will not be persisted if persistence is in use at - * the server and will be removed after a specified date and time. - */ - public void createNonPersistentTopicRemovedAfter( - String topicPath, - Date dateAndTime) - throws IllegalArgumentException, InterruptedException, - ExecutionException, TimeoutException { - - topicControl.addTopic( - topicPath, - stringSpecification - .withProperty( - REMOVAL, - "when time after " + dateAndTime.getTime()) - .withProperty(PERSISTENT, "false")) - .get(5, SECONDS); - } - - /** - * Creates a branch of the topic tree that the given principal will have - * READ_TOPIC, MODIFY_TOPIC, and UPDATE_TOPIC permissions to and will be - * automatically removed when there have been no sessions authenticated with - * the principal for a period of 5 minutes. - *

- * The names of the topics to be created within the branch are supplied. The - * principal will have permissions to all of the topics in the branch and - * all of the topics in the branch will be removed when no sessions for the - * principal remain. - *

- * None of the topics created will be persisted. - */ - public void createPrivateTopicBranch( - String topicPath, - String principal, - String... subTopics) - throws IllegalArgumentException, InterruptedException, - ExecutionException, TimeoutException { - - topicControl.addTopic( - topicPath, - stringSpecification - .withProperty(OWNER, "$Principal is '" + principal + "'") - .withProperty( - REMOVAL, - "when no session has '$Principal is \"" + principal + - "\"' for 5m remove '*" + topicPath + "//'") - .withProperty(PERSISTENT, "false")) - .get(5, SECONDS); - - for (String subTopic : subTopics) { - topicControl.addTopic( - topicPath + "/" + subTopic, - stringSpecification - .withProperty(OWNER, "$Principal is '" + principal + "'") - .withProperty(PERSISTENT, "false")) - .get(5, SECONDS); - } - } - - /** - * Close the session. - */ - public void close() { - session.close(); - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/CreateRemoteTopicView.java b/java/src/main/java/com/pushtechnology/diffusion/examples/CreateRemoteTopicView.java deleted file mode 100644 index 2f3ccb5d..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/CreateRemoteTopicView.java +++ /dev/null @@ -1,147 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import static java.util.concurrent.TimeUnit.SECONDS; - -import java.util.Arrays; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.TopicUpdate; -import com.pushtechnology.diffusion.client.features.control.RemoteServers; -import com.pushtechnology.diffusion.client.features.control.topics.views.TopicViews; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicType; -import com.pushtechnology.diffusion.datatype.json.JSON; -import com.pushtechnology.diffusion.datatype.json.JSONDataType; - -/** - * An example of creating a remote topic view. - *

- * Two sessions are established and a remote topic view is created to map part - * of the topic tree from the primary server to the secondary server - * - * @author DiffusionData Limited - * @since 6.5 - */ -public final class CreateRemoteTopicView { - - private static final String ROOT_TOPIC = "Accounts"; - private final String primaryServerUrl; - private final String secondaryServerUrl; - - /** - * Constructor. - * - * @param primaryServerUrl url for primary server - * @param secondaryServerUrl url for secondary server - */ - public CreateRemoteTopicView( - String primaryServerUrl, - String secondaryServerUrl) { - this.primaryServerUrl = primaryServerUrl; - this.secondaryServerUrl = secondaryServerUrl; - } - - /** - * Creates a topic tree on primary server. - *

- * Populates topic tree with JSON data - */ - private void addTopics(Session session) - throws Exception { - - final JSONDataType jsonDataType = Diffusion.dataTypes().json(); - final JSON value = jsonDataType.fromJsonString("{\"foo\" : \"bar\" }"); - - for (String type : Arrays.asList("Free", "Premium")) { - for (int i = 0; i < 10; i++) { - session.feature(TopicUpdate.class).addAndSet( - String.format( - "%s/%s/%s-Account-%d", - ROOT_TOPIC, - type, - type, - i), - Diffusion.newTopicSpecification(TopicType.JSON), - JSON.class, - value).get(5, SECONDS); - } - } - } - - /** - * Establish remote server. - * - * @param name name of the remote server - */ - private void createRemoteServer(Session session, String name) - throws Exception { - - session.feature(RemoteServers.class).createRemoteServer( - Diffusion.newRemoteServerBuilder() - .principal("admin") - .credentials(Diffusion.credentials().password("password")) - .create(name, primaryServerUrl)) - .get(5, SECONDS); - - } - - /** - * Create the remote topic view. - * - * @param serverName name of the remote server - * @param viewName name of the remote view - */ - private void createRemoteTopicView( - Session session, - String serverName, - String viewName) - throws Exception { - - final String specification = - String.format( - "map ?%s/%s// from %s to %s/", - ROOT_TOPIC, - "Premium", - serverName, - viewName); - - session.feature(TopicViews.class).createTopicView( - viewName, - specification).get(5, SECONDS); - } - - /** - * Run the example. - */ - public void run() throws Exception { - - final Session primarySession = - Diffusion.sessions().principal("admin").password("password") - .open(primaryServerUrl); - - final Session secondarySession = - Diffusion.sessions().principal("admin").password("password") - .open(secondaryServerUrl); - - addTopics(primarySession); - createRemoteServer(secondarySession, "foo"); - createRemoteTopicView(secondarySession, "foo", "bar"); - - primarySession.close(); - secondarySession.close(); - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/CreateSecondaryKeys.java b/java/src/main/java/com/pushtechnology/diffusion/examples/CreateSecondaryKeys.java deleted file mode 100644 index 158aa5be..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/CreateSecondaryKeys.java +++ /dev/null @@ -1,102 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2019 Push Technology Ltd., All Rights Reserved. - * - * Use is subject to license terms. - * - * NOTICE: All information contained herein is, and remains the - * property of Push Technology. The intellectual and technical - * concepts contained herein are proprietary to Push Technology and - * may be covered by U.S. and Foreign Patents, patents in process, and - * are protected by trade secret or copyright law. - *******************************************************************************/ - -package com.pushtechnology.diffusion.examples; - -import static com.pushtechnology.diffusion.client.Diffusion.newTopicSpecification; -import static java.lang.String.format; - -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.atomic.AtomicInteger; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.TopicUpdate; -import com.pushtechnology.diffusion.client.features.control.topics.views.TopicViews; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicType; -import com.pushtechnology.diffusion.datatype.json.JSON; -import com.pushtechnology.diffusion.datatype.json.JSONDataType; - -/** - * This example shows a control client creating a topic view that uses secondary - * keys. - *

- * It presents a simplified sportsbook and uses a topic view to create a - * secondary key on the country sporting events take place in. - * - * @author DiffusionData Limited - * @since 6.3 - */ -public final class CreateSecondaryKeys implements AutoCloseable { - private final Session session; - private final TopicUpdate topicUpdate; - private final TopicViews topicViews; - private final JSONDataType jsonDataType = Diffusion.dataTypes().json(); - private final AtomicInteger idGenerator = new AtomicInteger(0); - - /** - * Constructor. - * - * @param serverUrl for example "ws://diffusion.example.com:80" - */ - public CreateSecondaryKeys(String serverUrl) { - session = Diffusion - .sessions() - .principal("control") - .password("password") - .open(serverUrl); - - topicUpdate = session.feature(TopicUpdate.class); - topicViews = session.feature(TopicViews.class); - } - - /** - * Create a football event. - * - * @param country the country the event is in - * @param homeTeam the home team - * @param awayTeam the away team - * @return future representing the creation of the event - */ - public CompletableFuture createEvent(String country, String homeTeam, String awayTeam) { - // Create a path for the event containing a unique ID - final String path = format("Football/All/%d", idGenerator.getAndIncrement()); - // Format the initial value describing the event - final JSON value = jsonDataType.fromJsonString(format( - "{\"country\":\"%s\",\"home\":\"%s\",\"away\":\"%s\"}", - country, - homeTeam, - awayTeam)); - return topicUpdate.addAndSet(path, newTopicSpecification(TopicType.JSON), JSON.class, value); - } - - /** - * Create a secondary key that groups events by country the event is in. - * - * @return future representing the creation of the secondary keys - */ - public CompletableFuture createSecondaryKeyByCountry() { - // This creates a single topic view that selects all football events - // and maps them to a path containing their country, preserving the ID - // generated for the topic - return topicViews - .createTopicView( - "football-by-country", - "map '?Football/All/' " + - "to 'Football//'"); - } - - @Override - public void close() { - session.close(); - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/CreateTopicView.java b/java/src/main/java/com/pushtechnology/diffusion/examples/CreateTopicView.java deleted file mode 100644 index 932edd90..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/CreateTopicView.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.pushtechnology.diffusion.examples; - -/******************************************************************************* - * Copyright (C) 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -import static java.util.concurrent.TimeUnit.SECONDS; - -import java.util.Arrays; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.TopicUpdate; -import com.pushtechnology.diffusion.client.features.control.topics.views.TopicViews; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; -import com.pushtechnology.diffusion.client.topics.details.TopicType; -import com.pushtechnology.diffusion.datatype.json.JSON; - -/** - * An example of creating a topic view. - * - * @author DiffusionData Limited - * @since 6.7 - */ - public final class CreateTopicView { - - private static final String ROOT_TOPIC = "Accounts"; - private static final JSON TOPIC_VALUE - = Diffusion.dataTypes().json().fromJsonString("{\"foo\" : \"bar\" }"); - private static final TopicSpecification TOPIC_SPECIFICATION - = Diffusion.newTopicSpecification(TopicType.JSON); - private final Session session; - - /** - * Constructor. - * @param serverUrl url for Diffusion server - */ - public CreateTopicView(String serverUrl) throws Exception { - session = - Diffusion.sessions().principal("control").password("password") - .open(serverUrl); - } - - /** - * Create a topic tree on the server. - *

- * Populate topic tree with JSON data - */ - private void addTopics() throws Exception { - //our topic tree has two branches, 'Free' and 'Premium' - for (String accountType : Arrays.asList("Free", "Premium")) { - for (int i = 0; i < 10; i++) { - final String topicPath = String.format("%s/%s/%s-Account-%d", - ROOT_TOPIC, accountType, accountType, i); - session.feature(TopicUpdate.class) - .addAndSet(topicPath, TOPIC_SPECIFICATION, JSON.class, TOPIC_VALUE) - .get(5, SECONDS); - } - } - } - - /** - * Create the topic view. - *

- * @param viewName name of the topic view - *

- * The path mapping clause is the part after the 'to' keyword. path is a directive, with '2' as its only parameter. - * The clause will make reference topics for all the topics under Accounts/Premium at Premium-Accounts-Only - */ - private void createTopicView() { - final String viewSpecification = "map ?Accounts/Premium// to Premium-Accounts-Only/"; - session.feature(TopicViews.class).createTopicView("premium-view", viewSpecification); - } - - /** - * Run the example. - */ - public void run() throws Exception { - addTopics(); - createTopicView(); - session.close(); - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/TimeSeriesQueryExample.java b/java/src/main/java/com/pushtechnology/diffusion/examples/TimeSeriesQueryExample.java deleted file mode 100644 index 15702cf8..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/TimeSeriesQueryExample.java +++ /dev/null @@ -1,258 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2016 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples; - -import static java.lang.Math.max; -import static java.util.Collections.unmodifiableSortedMap; - -import java.io.IOException; -import java.time.Instant; -import java.util.SortedMap; -import java.util.TreeMap; -import java.util.function.Consumer; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.dataformat.cbor.CBORFactory; -import com.pushtechnology.diffusion.client.callbacks.ErrorReason; -import com.pushtechnology.diffusion.client.features.TimeSeries; -import com.pushtechnology.diffusion.client.features.Topics; -import com.pushtechnology.diffusion.client.features.TimeSeries.Event; -import com.pushtechnology.diffusion.client.features.TimeSeries.Query; -import com.pushtechnology.diffusion.client.features.Topics.ValueStream; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; -import com.pushtechnology.diffusion.datatype.json.JSON; - -/** - * Demonstrate the TimeSeries API. - * - *

- * This demonstrates client-side view maintenance for a simple chat application. - * - *

- * The view is modeled by the {@link ChatView} class. This has a start time, and - * a map of sequence number to messages that have occurred after the start time. - * - *

- * The {@link #subscribeChatView subscribeChatView} method subscribes a session - * to a time series topic of chat messages stored as JSON objects. ChatView - * models each chat message using the {@link ChatMessage} class. Once - * subscribed, the ChatView will be asynchronously updated with new messages and - * edits to existing messages. - * - * @author DiffusionData Limited - * @since 6.0 - */ -public final class TimeSeriesQueryExample { - /** Jackson ObjectMapper used by {@link #jsonToChat(JSON)}. */ - private static final ObjectMapper CBOR_MAPPER = - new ObjectMapper(new CBORFactory()); - - private TimeSeriesQueryExample() { - } - - /** - * Connect a ChatView to a time series topic. - * - * @param chatView the ChatView - * @param chatTopicPath path of a JSON time series topic storing chat - * messages - * @param errorHandler called if an operation fails - */ - public static void subscribeChatView( - Session session, - ChatView chatView, - String chatTopicPath, - Consumer errorHandler) { - - final Topics topics = session.feature(Topics.class); - - final ValueStream> subscriptionStream = - new ValueStream.Default>() { - private volatile boolean initialValue = true; - - @Override - public void onValue( - String topicPath, - TopicSpecification specification, - Event oldEvent, - Event event) { - - // When the subscription initially completes, the stream - // will receive an initial range of events from the server. - // If there is a gap between the latest event processed by - // the ChatView and the first event received, query the - // time series topic to retrieve the missing events. - if (initialValue && - event.sequence() > chatView.expectedNextSequence()) { - - initialValue = false; - - final Query query = chatView.missingEventQuery( - session.feature(TimeSeries.class), - event.sequence()); - - query - .selectFrom(chatTopicPath) - .whenComplete((result, e) -> { - if (e != null) { - topics.removeStream(this); - errorHandler.accept(e); - } - else { - result.stream().forEach(chatView::addEvent); - } - }); - } - - chatView.addEvent(event); - } - - @Override - public void onError(ErrorReason errorReason) { - errorHandler.accept(new RuntimeException( - "Subscription stream failed: " + errorReason)); - } - }; - - topics.addTimeSeriesStream(chatTopicPath, JSON.class, subscriptionStream); - - topics.subscribe(chatTopicPath) - .whenComplete((result, e) -> { - if (e != null) { - topics.removeStream(subscriptionStream); - errorHandler.accept(e); - } - }); - } - - /** - * A client-side model of a time series of ChatMessages. - */ - public static class ChatView { - - private final Instant startOfView; - private final SortedMap> messages = - new TreeMap<>(); - - private long latestSequence = -1; - - /** - * Constructor. - * - * @param startOfView the start of the view - */ - public ChatView(Instant startOfView) { - this.startOfView = startOfView; - } - - /** - * @return an ordered map of sequence number -> chat message events - */ - public SortedMap> getMessages() { - return unmodifiableSortedMap(messages); - } - - private synchronized void addEvent(Event event) { - if (event.timestamp() >= startOfView.toEpochMilli()) { - messages.put( - event.originalEvent().sequence(), - event.withValue(jsonToChat(event.value()))); - } - - latestSequence = max(latestSequence, event.sequence()); - } - - private synchronized long expectedNextSequence() { - return latestSequence + 1; - } - - /** - * @return a query configured to return all events that affect the view - * from the next expected event until receivedSequence - */ - private synchronized Query missingEventQuery( - TimeSeries timeSeries, - long receivedSequence) { - - return timeSeries.rangeQuery() - .from(startOfView) - .editRange().from(latestSequence + 1) - .to(receivedSequence - 1) - .as(JSON.class); - } - } - - /** - * Simple model of a chat message that combines application metadata - * (priority, senderId) with a textual message. - */ - public static class ChatMessage { - private final String text; - private final int priority; - private final int senderId; - - /** - * Constructor. - */ - @JsonCreator - public ChatMessage( - @JsonProperty("text") String text, - @JsonProperty("priority") int priority, - @JsonProperty("senderId") int senderId) { - this.text = text; - this.priority = priority; - this.senderId = senderId; - } - - - /** - * @return the message text. - */ - public String getText() { - return text; - } - - /** - * @return a priority code; high priority messages may be rendered - * differently - */ - public int getPriority() { - return priority; - } - - /** - * Used by the send to de-duplicate pending messages on reconnection. - */ - public int getSenderId() { - return senderId; - } - } - - /** - * Use the third-party Jackson library to parse a JSON message as a - * ChatMessage. - */ - private static ChatMessage jsonToChat(JSON value) { - try { - return CBOR_MAPPER.readValue(value.asInputStream(), ChatMessage.class); - } - catch (IOException e) { - throw new RuntimeException("Failed to parse event as chat message", e); - } - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/TopicUpdateExample.java b/java/src/main/java/com/pushtechnology/diffusion/examples/TopicUpdateExample.java deleted file mode 100644 index 42a58be0..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/TopicUpdateExample.java +++ /dev/null @@ -1,335 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2018, 2022 Push Technology Ltd., All Rights Reserved. - * - * Use is subject to license terms. - * - * NOTICE: All information contained herein is, and remains the - * property of Push Technology. The intellectual and technical - * concepts contained herein are proprietary to Push Technology and - * may be covered by U.S. and Foreign Patents, patents in process, and - * are protected by trade secret or copyright law. - *******************************************************************************/ - -package com.pushtechnology.diffusion.examples; - -import static com.pushtechnology.diffusion.client.Diffusion.newTopicSpecification; -import static com.pushtechnology.diffusion.client.Diffusion.updateConstraints; -import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor; -import static java.util.concurrent.TimeUnit.SECONDS; - -import java.util.Random; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.function.Supplier; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.pushtechnology.diffusion.client.features.TopicCreationResult; -import com.pushtechnology.diffusion.client.features.TopicUpdate; -import com.pushtechnology.diffusion.client.features.UpdateConstraint; -import com.pushtechnology.diffusion.client.features.UpdateStream; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicType; - -/** - * Example showing the use of the {@link TopicUpdate} feature. - * - * @author DiffusionData Limited - * @since 6.2 - */ -public final class TopicUpdateExample { - private static final Logger LOG = LoggerFactory.getLogger(TopicUpdateExample.class); - - private TopicUpdateExample() { - } - - /** - * Set an INT_64 topic to 6. - */ - public static void statelessSet(Session session) { - - session - .feature(TopicUpdate.class) - .set("a/path", Long.class, 6L) - .whenComplete(TopicUpdateExample::updateHandler); - } - - /** - * Set an INT_64 topic to 6 if the session holds "a/lock" and its current value is 5. - */ - public static void statelessSetWithConstraint(Session session) { - final TopicUpdate update = session.feature(TopicUpdate.class); - final UpdateConstraint.Factory constraints = updateConstraints(); - - session - // Acquire a lock - .lock("a/lock") - // Construct a constraint that requires the lock to be held and the value of the topic to be 5 - .thenApply(lock -> constraints.value(5L).and(constraints.locked(lock))) - // Increments the topic value from 5 to 6 if the lock is still held - .thenCompose(constraint -> update.set("a/path", Long.class, 6L, constraint)) - .whenComplete(TopicUpdateExample::updateHandler); - } - - /** - * Set a string topic multiple times using the same updater. - */ - public static void statelessSetRepeatedly(Session session) { - - final TopicUpdate update = session.feature(TopicUpdate.class); - final UpdateConstraint.Factory constraints = updateConstraints(); - - update - // Set the value of the topic to a string - .set("a/path", String.class, "hello") - // Remove the value of the topic by setting it to null - .thenCompose(x -> update.set("a/path", String.class, null)) - // Set the value of the topic if it has no value - .thenCompose(x -> - update.set("a/path", String.class, "who are you?", constraints.noValue())) - .whenComplete(TopicUpdateExample::updateHandler); - } - - /** - * Set "random/long" with a random long every 5 seconds while the updater is active. - */ - public static void statelessSetPeriodically(Session session) { - final TopicUpdate updater = session.feature(TopicUpdate.class); - - final Random random = new Random(); - runPeriodicallyUntilFirstFailure( - newSingleThreadScheduledExecutor(), - // Set the topic to a random value - () -> updater.set("random/long", Long.class, random.nextLong()), - 5, - SECONDS) - .whenComplete(TopicUpdateExample::updateHandler); - } - - /** - * Add a string topic and set to a new value. If the topic exists it will - * be updated to the new value. - */ - public static void addAndSetTopicWithStateless(Session session) { - - final TopicUpdate updater = session.feature(TopicUpdate.class); - - updater - .addAndSet("a/path", newTopicSpecification(TopicType.STRING), String.class, "hello") - .thenAccept(result -> { - if (result == TopicCreationResult.CREATED) { - LOG.info("A new topic was created"); - } - else { - LOG.info("An existing topic was updated"); - } - }); - } - - /** - * Update an INT_64 topic to 6 using an update stream. - */ - public static void streamSet(Session session) { - - session - .feature(TopicUpdate.class) - // Create an update stream - .newUpdateStreamBuilder().build("a/path", Long.class) - // Use the update stream to set the topic value. This will invalidate - // any update stream that exists for the topic. This stream can be - // invalidated once this completes. - .set(6L) - .whenComplete(TopicUpdateExample::updateHandler); - } - - /** - * Set an INT_64 topic to 6 if the session holds "a/lock" and its current value is 5 using an update stream. - */ - public static void streamSetWithConstraint(Session session) { - final TopicUpdate update = session.feature(TopicUpdate.class); - final UpdateConstraint.Factory constraints = updateConstraints(); - - session - .lock("a/lock") - .thenApply(lock -> constraints.value(5L).and(constraints.locked(lock))) - // Create an update stream. The constraint will not be evaluated yet. - .thenApply(constraint -> update.newUpdateStreamBuilder() - .constraint(constraint).build("a/path", Long.class)) - // Use the update stream to set the topic value. This will evaluate the constraint. - .thenCompose(updateStream -> updateStream.set(6L)) - .whenComplete(TopicUpdateExample::updateHandler); - } - - /** - * Set a string topic multiple times using the same update stream. - */ - public static void streamSetRepeatedly(Session session) { - - final UpdateConstraint.Factory constraints = updateConstraints(); - final UpdateStream updateStream = session - .feature(TopicUpdate.class).newUpdateStreamBuilder() - .constraint(constraints.noValue()).build("a/path", String.class); - - - // This sends the path with the value and validates the constraint - updateStream.set("hello") - // These send a reference to the update stream with the value. The constraint is not reevaluated. - .thenCompose(x -> updateStream.set(null)) - .thenCompose(x -> updateStream.set("who are you?")) - .whenComplete(TopicUpdateExample::updateHandler); - } - - /** - * Set a string topic multiple times using the same update stream without waiting for the previous operation to - * complete. - */ - public static void streamSetRepeatedlyWithoutWaiting(Session session) { - - final UpdateConstraint.Factory constraints = updateConstraints(); - final UpdateStream updateStream = session - .feature(TopicUpdate.class).newUpdateStreamBuilder() - .constraint(constraints.noValue()).build("a/path", String.class); - - // This sends the path with the value and validates the constraint - updateStream.set("hello"); - // These may be deferred until after the completion of the previous operation - updateStream.set(null); - updateStream.set("who are you?"); - } - - /** - * Set "random/long" with a random long every 5 seconds while the update stream is active. - */ - public static void streamSetPeriodically(Session session) { - final UpdateStream updateStream = session - .feature(TopicUpdate.class) - .newUpdateStreamBuilder().build("random/long", Long.class); - - final CompletableFuture validation = updateStream.validate(); - - validation - .whenComplete((result, ex) -> { - if (ex != null) { - LOG.warn("Failed to validate stream", ex); - } - }); - - final Random random = new Random(); - validation - .thenCompose(result -> runPeriodicallyUntilFirstFailure( - newSingleThreadScheduledExecutor(), - () -> updateStream.set(random.nextLong()), - 5, - SECONDS)) - .whenComplete(TopicUpdateExample::updateHandler); - } - - /** - * Create a string topic with a stream. - */ - public static void createTopicWithStream(Session session) { - - final UpdateStream updateStream = session - .feature(TopicUpdate.class) - // Creates the update stream. This does not add the topic - .newUpdateStreamBuilder() - .specification(newTopicSpecification(TopicType.STRING)) - .build("a/path", String.class); - - updateStream - // This will add the topic without setting it to any value - .validate() - .thenAccept(result -> { - if (result == TopicCreationResult.CREATED) { - LOG.info("The topic was created"); - } - else { - LOG.info("The topic already exist"); - } - }); - } - - /** - * Create an update stream that adds a string topic and sets it to a new - * value. If the topic exists it will be updated to the new value. - */ - public static void addAndSetTopicWithStream(Session session) { - - final UpdateStream updateStream = session - .feature(TopicUpdate.class) - .newUpdateStreamBuilder() - .specification(newTopicSpecification(TopicType.STRING)) - .build("a/path", String.class); - - updateStream - // This will add the topic if it is missing and set the value - .set("hello") - .thenAccept(result -> { - if (result == TopicCreationResult.CREATED) { - LOG.info("A new topic was created"); - } - else { - LOG.info("An existing topic was updated"); - } - }); - } - - /** - * Schedule a periodic set operation as long as the update source is active. - * - * @return a future representing the task - */ - private static CompletableFuture runPeriodicallyUntilFirstFailure( - ScheduledExecutorService executor, - Supplier> task, - long period, - TimeUnit unit) { - - final CompletableFuture taskHandle = new CompletableFuture<>(); - scheduleNextUpdate(executor, task, period, unit, taskHandle); - return taskHandle; - } - - private static void scheduleNextUpdate( - ScheduledExecutorService executor, - Supplier> task, - long period, - TimeUnit unit, - CompletableFuture taskHandle) { - - executor - .schedule( - () -> { - // Skip if task completed or cancelled - if (taskHandle.isDone()) { - return; - } - - // Send update - task - .get() - .whenComplete((result, ex) -> { - if (ex != null) { - // Complete task exceptionally if update failed - taskHandle.completeExceptionally(ex); - } - else { - // If task completed or cancelled, schedule next execution - if (!taskHandle.isDone()) { - scheduleNextUpdate(executor, task, period, unit, taskHandle); - } - } - }); - }, - period, - unit); - } - - private static void updateHandler(@SuppressWarnings("unused")T result, Throwable ex) { - if (ex != null) { - LOG.error("Update failed", ex); - } - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/package-info.java b/java/src/main/java/com/pushtechnology/diffusion/examples/package-info.java deleted file mode 100644 index 1a5750a8..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/package-info.java +++ /dev/null @@ -1,22 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2014, 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -/** - * This provides a number of examples of using the Diffusion API. - * - * @author DiffusionData Limited - * @since 5.0 - */ -package com.pushtechnology.diffusion.examples; \ No newline at end of file diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/AbstractClient.java b/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/AbstractClient.java deleted file mode 100644 index 76148645..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/AbstractClient.java +++ /dev/null @@ -1,166 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2016, 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and -* limitations under the License. - *******************************************************************************/ - -package com.pushtechnology.diffusion.examples.runnable; - -import static com.pushtechnology.diffusion.client.session.Session.State.CONNECTING; - -import java.util.concurrent.CountDownLatch; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.callbacks.ErrorReason; -import com.pushtechnology.diffusion.client.session.Session; - -/** - * Abstract client. Supporting a simplified state model and starting and - * stopping the client. - * - * @author DiffusionData Limited - * @since 5.7 - */ -public abstract class AbstractClient { - private static final Logger LOG = LoggerFactory - .getLogger(AbstractClient.class); - - private final String url; - private final String principal; - - private boolean running = false; - private Session currentSession; - private CountDownLatch waitForStoppedLatch; - - /** - * Constructor. - * @param url The URL to connect to - * @param principal The principal to connect as - */ - public AbstractClient(String url, String principal) { - this.url = url; - this.principal = principal; - } - - /** - * Start the client. - * @param password The password to connect with - * @throws IllegalStateException If the client is already running - */ - public final void start(String password) { - synchronized (this) { - if (running) { - throw new IllegalStateException("Already running"); - } - running = true; - waitForStoppedLatch = new CountDownLatch(1); - } - - Diffusion.sessions() - .principal(principal) - .password(password) - .listener(new Session.Listener() { - @Override - public void onSessionStateChanged( - Session session, - Session.State oldState, - Session.State newState) { - - synchronized (AbstractClient.this) { - if (CONNECTING == oldState && newState.isConnected()) { - onStarted(session); - } - - if (!oldState.isConnected() && newState.isConnected()) { - currentSession = session; - onConnected(session); - } - - if (oldState.isConnected() && !newState.isConnected()) { - onDisconnected(); - } - - if (newState.isClosed()) { - waitForStoppedLatch.countDown(); - waitForStoppedLatch = null; - running = false; - } - } - } - }) - .open(url); - } - - /** - * Stop the client. Returns immediately, does not wait for the client to - * stop. - * @throws IllegalStateException If the client is not running - */ - public final synchronized void stop() { - if (!running) { - throw new IllegalStateException("Not currently running"); - } - - currentSession.close(); - } - - /** - * Wait for the client to stop. - * @throws InterruptedException If the thread was interrupted while waiting - * for the client to stop - */ - public final void waitForStopped() throws InterruptedException { - final CountDownLatch currentLatch; - synchronized (this) { - if (waitForStoppedLatch == null) { - return; - } - currentLatch = waitForStoppedLatch; - } - currentLatch.await(); - } - - /** - * Notified when the client starts. A new session has been opened. - * @param session The session that opened - */ - public void onStarted(Session session) { - LOG.debug("Client started"); - } - - /** - * Notified when the client connects. Either initially or after recovering - * from a disconnection. - * @param session The session that connected - */ - public void onConnected(Session session) { - LOG.debug("Client connected"); - } - - /** - * Notified when the client disconnects. Either temporarily or permanently. - */ - public void onDisconnected() { - LOG.debug("Client disconnected"); - } - - /** - * Notified when an error prevents the start of the client. - * @param errorReason The error reason - */ - public void onError(ErrorReason errorReason) { - LOG.error("Failed to start client: {}", errorReason); - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/CompetitiveIncrement.java b/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/CompetitiveIncrement.java deleted file mode 100644 index 33ea1919..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/CompetitiveIncrement.java +++ /dev/null @@ -1,265 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018, 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -package com.pushtechnology.diffusion.examples.runnable; - -import static com.pushtechnology.diffusion.client.Diffusion.newTopicSpecification; -import static com.pushtechnology.diffusion.client.topics.details.TopicType.INT64; - -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.ClusterRoutingException; -import com.pushtechnology.diffusion.client.features.IncompatibleTopicException; -import com.pushtechnology.diffusion.client.features.IncompatibleTopicStateException; -import com.pushtechnology.diffusion.client.features.NoSuchTopicException; -import com.pushtechnology.diffusion.client.features.TopicCreationResult; -import com.pushtechnology.diffusion.client.features.Topics; -import com.pushtechnology.diffusion.client.features.Topics.ValueStream.Default; -import com.pushtechnology.diffusion.client.features.UnsatisfiedConstraintException; -import com.pushtechnology.diffusion.client.features.UpdateConstraint; -import com.pushtechnology.diffusion.client.features.control.topics.TopicControl.TopicLicenseLimitException; -import com.pushtechnology.diffusion.client.session.PermissionsException; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.session.SessionClosedException; -import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; - -/** - * A client that increments a topic using stateless operations. - *

- * The client will increment the topic every 5 seconds. - *

- * Multiple instances of the client can compete to increment the topic without - * generating an incorrect sequence of updates or knowing about other sessions. - *

- * The client subscribes to the topic to obtain the latest known value. Every - * 5 seconds it attempts to increment the topic using the known value as a - * constraint. If another session has changed the topic value, the update will - * fail and the client will retry with the latest known value. - * - * @author DiffusionData Limited - * @since 6.2 - */ -public final class CompetitiveIncrement extends AbstractClient { - private static final Logger LOG = LoggerFactory - .getLogger(CompetitiveIncrement.class); - private static final UpdateConstraint.Factory CONSTRAINTS = - Diffusion.updateConstraints(); - - private final ScheduledExecutorService executor = Executors - .newSingleThreadScheduledExecutor(); - - private volatile Future updateTask; - private volatile Long value; - - /** - * Constructor. - * - * @param url The URL to connect to - * @param principal The principal to connect as - */ - public CompetitiveIncrement(String url, String principal) { - super(url, principal); - } - - @Override - public void onStarted(Session session) { - subscribeToPath(session); - } - - private void subscribeToPath(Session session) { - // Subscribe to the topic to get the latest value - final Topics topics = session.feature(Topics.class); - topics - .addStream("long/increment", Long.class, new Default() { - @Override - public void onValue( - String topicPath, - TopicSpecification specification, - Long oldValue, - Long newValue) { - - // Update the latest known value - value = newValue; - } - }); - topics - .subscribe("long/increment") - .whenComplete((result, ex) -> { - if (ex != null) { - LOG.warn("Subscription failed", ex); - stop(); - } - else { - initialiseTopic(topics); - } - }); - } - - private void initialiseTopic(Topics topics) { - // Create the topic and initialise it to 0 if it does not exist - topics - .addAndSet( - "long/increment", - newTopicSpecification(INT64), - Long.class, - 0L, - CONSTRAINTS.noTopic()) - .whenComplete((result, ex) -> { - if (ex != null) { - final Throwable cause = ex.getCause(); - if (cause instanceof UnsatisfiedConstraintException) { - // The constraint was unsatisfied so the topic must - // already exist. Begin incrementing the topic value. - LOG.info("Topic exists"); - scheduleIncrement(topics); - } - else if (cause instanceof IncompatibleTopicException) { - // A topic exists with a different type. This implies - // that something else is responsible for the path. - LOG.warn("An existing topic is not compatible"); - stop(); - } - else if (cause instanceof IncompatibleTopicStateException) { - // A topic exists, managed by a component that does not - // allow updates from the API like fanout. Something - // else is responsible for the path. - LOG.warn("An existing topic is managed by a different component"); - stop(); - } - else if (cause instanceof TopicLicenseLimitException) { - // The topic can't be created because the server has - // reached the limit it is licensed for. - LOG.warn("License limit reached", ex); - stop(); - } - else { - LOG.warn("Topic creation failed", ex); - stop(); - } - } - else if (result == TopicCreationResult.CREATED) { - // Begin incrementing the topic value. - LOG.info("Topic created"); - scheduleIncrement(topics); - } - }); - } - - /** - * Schedule an increment in 5 seconds. - */ - private void scheduleIncrement(Topics topics) { - updateTask = executor.schedule( - () -> performIncrement(topics), - 5L, - TimeUnit.SECONDS); - } - - /** - * Perform an increment of the latest known value. - */ - private void performIncrement(Topics topics) { - final Long currentValue = value; - - topics - .set( - "long/increment", - Long.class, - currentValue + 1, - CONSTRAINTS.value(currentValue)) - .whenComplete((result, ex) -> { - if (ex != null) { - // Handle any failure - handleIncrementFailure(topics, ex); - } - else { - // On success schedule the next update - LOG.info("Topic incremented {} -> {}", currentValue, currentValue + 1); - scheduleIncrement(topics); - } - }); - } - - private void handleIncrementFailure(Topics topics, Throwable ex) { - final Throwable cause = ex.getCause(); - if (cause instanceof ClusterRoutingException || cause instanceof UnsatisfiedConstraintException) { - // A transient cluster failure occurred during the increment - // or the constraint was not satisfied, another session must - // have updated the topic. - // Retry incrementing the topic until successful. - performIncrement(topics); - } - else if (cause instanceof NoSuchTopicException) { - // The topic has been removed since it was created. This could be - // recoverable, but it implies that something else has taken - // responsibility for the path. Attempting to recover could cause - // this and something else to compete over the topic. - LOG.warn("The topic has been deleted"); - stop(); - } - else if (cause instanceof IncompatibleTopicException) { - // The topic has been replaced with a topic of a different type - // since it was created. This implies that something else has taken - // responsibility for the path. - LOG.warn("The topic is not compatible"); - stop(); - } - else if (cause instanceof IncompatibleTopicStateException) { - // The topic is managed by a component that does not allow updates - // from the API like fanout. Something else has taken - // responsibility for the path. - LOG.warn("The topic is managed by a different component"); - stop(); - } - else if (cause instanceof PermissionsException) { - // The session does't have permission update update the path. - // This is not recoverable. - LOG.warn("The session does't have permission to update the path"); - stop(); - } - else if (cause instanceof SessionClosedException) { - // The session has closed. This is not recoverable. - LOG.warn("The session has closed"); - stop(); - } - } - - @Override - public void onDisconnected() { - final Future task = this.updateTask; - if (task != null) { - task.cancel(false); - } - } - - /** - * Entry point for the example. - * @param args The command line arguments - * @throws InterruptedException If the main thread was interrupted - */ - public static void main(String[] args) throws InterruptedException { - final CompetitiveIncrement client = - new CompetitiveIncrement("ws://diffusion.example.com:80", "auth"); - client.start("auth_secret"); - client.waitForStopped(); - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/ConsumingBinary.java b/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/ConsumingBinary.java deleted file mode 100644 index f936c84d..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/ConsumingBinary.java +++ /dev/null @@ -1,85 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2016 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -package com.pushtechnology.diffusion.examples.runnable; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.pushtechnology.diffusion.client.features.Topics; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; -import com.pushtechnology.diffusion.datatype.binary.Binary; - -/** - * A client that consumes Binary topics. - * - * @author DiffusionData Limited - * @since 5.7 - */ -public final class ConsumingBinary extends AbstractClient { - private static final Logger LOG = LoggerFactory - .getLogger(ConsumingBinary.class); - - /** - * Constructor. - * @param url The URL to connect to - * @param principal The principal to connect as - */ - public ConsumingBinary(String url, String principal) { - super(url, principal); - } - - @Override - public void onStarted(Session session) { - final Topics topics = session.feature(Topics.class); - - // Add the stream to receive binary values - topics.addStream( - ">binary/random", - Binary.class, - new Topics.ValueStream.Default() { - @Override - public void onValue( - String topicPath, - TopicSpecification specification, - Binary oldValue, - Binary newValue) { - - LOG.info("New data {}", RandomData.fromBinary(newValue)); - } - }); - - // Subscribe to the topic - topics.subscribe("binary/random") - .whenComplete((voidResult, exception) -> { - if (exception != null) { - LOG.info("subscription failed", exception); - } - }); - } - - /** - * Entry point for the example. - * @param args The command line arguments - * @throws InterruptedException If the main thread was interrupted - */ - public static void main(String[] args) throws InterruptedException { - final ConsumingBinary client = - new ConsumingBinary("ws://diffusion.example.com:80", "auth"); - client.start("auth_secret"); - client.waitForStopped(); - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/ConsumingJson.java b/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/ConsumingJson.java deleted file mode 100644 index 36b3dec0..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/ConsumingJson.java +++ /dev/null @@ -1,111 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2016 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -package com.pushtechnology.diffusion.examples.runnable; - -import java.io.IOException; -import java.math.BigInteger; -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.dataformat.cbor.CBORFactory; -import com.fasterxml.jackson.dataformat.cbor.CBORParser; -import com.pushtechnology.diffusion.client.features.Topics; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; -import com.pushtechnology.diffusion.datatype.json.JSON; - -/** - * A client that consumes JSON topics. - * - * @author DiffusionData Limited - * @since 5.7 - */ -public final class ConsumingJson extends AbstractClient { - private static final CBORFactory CBOR_FACTORY = new CBORFactory(); - private static final ObjectMapper OBJECT_MAPPER = - new ObjectMapper(CBOR_FACTORY); - private static final Logger LOG = - LoggerFactory.getLogger(ConsumingJson.class); - private static final TypeReference> INT_MAP_TYPE = - new TypeReference>() { }; - - /** - * Constructor. - * @param url The URL to connect to - * @param principal The principal to connect as - */ - public ConsumingJson(String url, String principal) { - super(url, principal); - } - - @Override - public void onStarted(Session session) { - final Topics topics = session.feature(Topics.class); - - // Add the stream to receive JSON values - topics.addStream( - ">json/random", - JSON.class, - new Topics.ValueStream.Default() { - @Override - public void onValue( - String topicPath, - TopicSpecification specification, - JSON oldValue, - JSON newValue) { - - try { - // Converts a Json map into a Java Map. - final CBORParser parser = - CBOR_FACTORY.createParser(newValue.asInputStream()); - final Map map = OBJECT_MAPPER - .readValue(parser, INT_MAP_TYPE); - parser.close(); - - // Log the timestamp from the map - LOG.info("New timestamp {}", map.get("timestamp")); - } - catch (IOException e) { - LOG.warn("Failed to transform value '{}'", newValue, e); - } - } - }); - - // Subscribe to the topic - topics.subscribe("json/random") - .whenComplete((voidResult, exception) -> { - if (exception != null) { - LOG.info("subscription failed", exception); - } - }); - } - - /** - * Entry point for the example. - * @param args The command line arguments - * @throws InterruptedException If the main thread was interrupted - */ - public static void main(String[] args) throws InterruptedException { - final ConsumingJson client = - new ConsumingJson("ws://diffusion.example.com:80", "auth"); - client.start("auth_secret"); - client.waitForStopped(); - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/CoordinatingSessionExample.java b/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/CoordinatingSessionExample.java deleted file mode 100644 index 6f811ad7..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/CoordinatingSessionExample.java +++ /dev/null @@ -1,221 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018, 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -package com.pushtechnology.diffusion.examples.runnable; - -import static com.pushtechnology.diffusion.client.Diffusion.newTopicSpecification; -import static com.pushtechnology.diffusion.client.Diffusion.updateConstraints; - -import java.util.Random; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.function.Supplier; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.pushtechnology.diffusion.client.features.ClusterRoutingException; -import com.pushtechnology.diffusion.client.features.IncompatibleTopicException; -import com.pushtechnology.diffusion.client.features.InvalidUpdateStreamException; -import com.pushtechnology.diffusion.client.features.NoSuchTopicException; -import com.pushtechnology.diffusion.client.features.TopicUpdate; -import com.pushtechnology.diffusion.client.features.UnsatisfiedConstraintException; -import com.pushtechnology.diffusion.client.features.UpdateConstraint; -import com.pushtechnology.diffusion.client.features.UpdateStream; -import com.pushtechnology.diffusion.client.session.PermissionsException; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.session.SessionClosedException; -import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; -import com.pushtechnology.diffusion.client.topics.details.TopicType; - -/** - * Example showing how session locks and the {@link TopicUpdate} feature can - * be used to coordinate topic control between sessions. - *

- * Session locks are used to ensure a single instance of the client is - * responsible for updating a path at any one time. Responsibility is - * transferred when a session loses connection. The client handles transient - * issues caused by cluster repartitioning. - * - * @author DiffusionData Limited - * @since 6.2 - */ -public final class CoordinatingSessionExample extends AbstractClient { - private static final Logger LOG = LoggerFactory.getLogger(CoordinatingSessionExample.class); - private static final long PERIOD = 5000; - private static final TimeUnit UNIT = TimeUnit.MILLISECONDS; - - private final ScheduledExecutorService executor = Executors - .newSingleThreadScheduledExecutor(); - private final Random random = new Random(); - - /** - * Constructor. - * - * @param url The URL to connect to - * @param principal The principal to connect as - */ - public CoordinatingSessionExample(String url, String principal) { - super(url, principal); - } - - @Override - public void onConnected(Session session) { - updatePath(session, "topic"); - } - - private void updatePath(Session session, String path) { - session - // The topic path being updated is used as the lock name - .lock(path, Session.SessionLockScope.UNLOCK_ON_CONNECTION_LOSS) - .thenAccept(lock -> onLockAcquired(session, path, lock)); - } - - private void onLockAcquired(Session session, String path, Session.SessionLock lock) { - final TopicUpdate topicUpdate = session.feature(TopicUpdate.class); - - // If this session still owns the lock, update a String topic, setting - // its value to the session ID of this session. The topic will be - // created if it doesn't already exist. - final UpdateConstraint locked = updateConstraints().locked(lock); - topicUpdate.addAndSet( - path + "/last_updater", - newTopicSpecification(TopicType.STRING), - String.class, - session.getSessionId().toString(), - locked); - - // Create a factory for update streams - final TopicSpecification specification = newTopicSpecification(TopicType.INT64); - final Supplier> updateStreamFactory = - () -> topicUpdate.newUpdateStreamBuilder() - .specification(specification) - .constraint(locked) - .build(path, Long.class); - - final UpdateStream updateStream = updateStreamFactory.get(); - updateStream - .validate() - .whenComplete((result, ex) -> { - if (ex != null) { - LOG.warn("Unable to initialise first value stream. Unable to begin updating path.", ex); - // The lock will be released with the session - stop(); - } - else { - // Begin updating with the stream - final UpdateTask updateTask = new UpdateTask(updateStreamFactory, updateStream, random::nextLong); - updateTask.scheduleUpdate(); - } - }); - } - - private final class UpdateTask { - private final Supplier> updateStreamFactory; - private final Supplier valueSupplier; - private volatile UpdateStream updateStream; - - private UpdateTask( - Supplier> updateStreamFactory, - UpdateStream updateStream, - Supplier valueSupplier) { - - this.updateStreamFactory = updateStreamFactory; - this.updateStream = updateStream; - this.valueSupplier = valueSupplier; - } - - private void scheduleUpdate() { - executor.schedule((Runnable) this::performUpdate, PERIOD, UNIT); - } - - private void performUpdate() { - // Generate the next value and send update - performUpdate(valueSupplier.get()); - } - - private void performUpdate(long value) { - // Send update - updateStream - .set(value) - .whenComplete((result, ex) -> { - if (ex != null) { - handleUpdateFailure(value, ex); - } - else { - scheduleUpdate(); - } - }); - } - - private void handleUpdateFailure(long value, Throwable ex) { - final Throwable cause = ex.getCause(); - if (cause instanceof ClusterRoutingException) { - // Replace stream and retry the update - updateStream = updateStreamFactory.get(); - performUpdate(value); - } - else if (cause instanceof UnsatisfiedConstraintException) { - // Another session gained the session lock and is now - // responsible for the the topic. - LOG.warn("Another session has gained the responsibility for updating the topic"); - // The lock will be released with the session - stop(); - } - else if (cause instanceof NoSuchTopicException) { - // The topic has been removed since the stream was created, - // this could be recoverable but it implies that something - // else has taken responsibility for the path. Attempting - // to recover could cause this and something else to compete - // over the topic. - LOG.warn("The topic has been deleted"); - // The lock will be released with the session - stop(); - } - else if (cause instanceof InvalidUpdateStreamException) { - // Something other than the stream changed the topic, this - // could be recoverable but it implies that something else has - // taken responsibility for the topic. Attempting to recover - // could cause this and something else to compete over the - // topic. For example this session could have lost connection - // and another has taken over its role. - LOG.warn("The update stream is no longer valid"); - // The lock will be released with the session - stop(); - } - else if (cause instanceof IncompatibleTopicException) { - // Following an attempt to replace the stream, it was found the - // topic has been removed and replaced with an incompatible - // topic. This implies that something else has taken - // responsibility for the path. - LOG.warn("The topic is not compatible"); - // The lock will be released with the session - stop(); - } - else if (cause instanceof PermissionsException) { - // The session does't have permission update update the path. - // This is not recoverable. - LOG.warn("The session doesn't have permission to update the path"); - // The lock will be released with the session - stop(); - } - else if (cause instanceof SessionClosedException) { - // The session has closed. This is not recoverable. - LOG.warn("The session has closed"); - } - } - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/ProducingBinary.java b/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/ProducingBinary.java deleted file mode 100644 index 8b467c9d..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/ProducingBinary.java +++ /dev/null @@ -1,101 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2016, 2019 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.examples.runnable; - -import static com.pushtechnology.diffusion.client.Diffusion.newTopicSpecification; -import static com.pushtechnology.diffusion.client.topics.details.TopicSpecification.REMOVAL; -import static com.pushtechnology.diffusion.client.topics.details.TopicType.BINARY; -import static java.util.concurrent.TimeUnit.SECONDS; - -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.ScheduledExecutorService; - -import com.pushtechnology.diffusion.client.features.TopicUpdate; -import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; -import com.pushtechnology.diffusion.datatype.binary.Binary; - -/** - * A client that creates and updates Binary topics. - * - * @author DiffusionData Limited - * @since 5.7 - */ -public final class ProducingBinary extends AbstractClient { - private static final ScheduledExecutorService EXECUTOR = Executors - .newSingleThreadScheduledExecutor(); - - private volatile Future updateTask; - - /** - * Constructor. - * @param url The URL to connect to - * @param principal The principal to connect as - */ - public ProducingBinary(String url, String principal) { - super(url, principal); - } - - @Override - public void onStarted(Session session) { - final TopicControl topicControl = session.feature(TopicControl.class); - - final TopicSpecification specification = - newTopicSpecification(BINARY) - .withProperty(REMOVAL, "when this session closes"); - - topicControl.addTopic("binary/random", specification); - } - - @Override - public void onConnected(Session session) { - final TopicUpdate topicUpdate = session.feature(TopicUpdate.class); - - updateTask = EXECUTOR.scheduleAtFixedRate( - new Runnable() { - @Override - public void run() { - // Update the topic with random data - topicUpdate.set( - "binary/random", - Binary.class, - RandomData.toBinary(RandomData.next())); - } - }, - 0L, - 1L, - SECONDS); - } - - @Override - public void onDisconnected() { - // Cancel updates when disconnected - updateTask.cancel(false); - } - - /** - * Entry point for the example. - * @param args The command line arguments - * @throws InterruptedException If the main thread was interrupted - */ - public static void main(String[] args) throws InterruptedException { - final ProducingBinary client = - new ProducingBinary("ws://diffusion.example.com:80", "auth"); - client.start("auth_secret"); - client.waitForStopped(); - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/ProducingJson.java b/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/ProducingJson.java deleted file mode 100644 index e1126271..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/ProducingJson.java +++ /dev/null @@ -1,114 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2016, 2019 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -package com.pushtechnology.diffusion.examples.runnable; - -import static com.pushtechnology.diffusion.client.Diffusion.newTopicSpecification; -import static com.pushtechnology.diffusion.client.topics.details.TopicSpecification.REMOVAL; -import static com.pushtechnology.diffusion.client.topics.details.TopicType.JSON; -import static java.util.concurrent.TimeUnit.SECONDS; - -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.ScheduledExecutorService; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.pushtechnology.diffusion.client.features.TopicUpdate; -import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; -import com.pushtechnology.diffusion.datatype.json.JSON; - -/** - * A client that creates and updates JSON topics. - * - * @author DiffusionData Limited - * @since 5.7 - */ -public final class ProducingJson extends AbstractClient { - private static final Logger LOG = LoggerFactory - .getLogger(ProducingJson.class); - - private final ScheduledExecutorService executor = Executors - .newSingleThreadScheduledExecutor(); - private volatile Future updateTask; - - /** - * Constructor. - * @param url The URL to connect to - * @param principal The principal to connect as - */ - public ProducingJson(String url, String principal) { - super(url, principal); - } - - @Override - public void onStarted(Session session) { - final TopicControl topicControl = session.feature(TopicControl.class); - - final TopicSpecification specification = - newTopicSpecification(JSON) - .withProperty(REMOVAL, "when this session closes"); - - topicControl.addTopic("json/random", specification); - } - - @Override - public void onConnected(Session session) { - final TopicUpdate topicUpdate = session.feature(TopicUpdate.class); - - updateTask = executor.scheduleAtFixedRate( - new Runnable() { - @Override - public void run() { - try { - // Update the topic with random data - topicUpdate.set( - "json/random", - JSON.class, - // Converts a RandomData object into a Json map - RandomData.toJSON(RandomData.next())); - } - catch (JsonProcessingException e) { - LOG.warn("Failed to transform data", e); - } - } - }, - 0L, - 1L, - SECONDS); - } - - @Override - public void onDisconnected() { - // Cancel updates when disconnected - updateTask.cancel(false); - } - - /** - * Entry point for the example. - * @param args The command line arguments - * @throws InterruptedException If the main thread was interrupted - */ - public static void main(String[] args) throws InterruptedException { - final ProducingJson client = - new ProducingJson("ws://diffusion.example.com:80", "auth"); - client.start("auth_secret"); - client.waitForStopped(); - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/RandomData.java b/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/RandomData.java deleted file mode 100644 index d42b8f18..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/RandomData.java +++ /dev/null @@ -1,133 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2016 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -package com.pushtechnology.diffusion.examples.runnable; - -import static java.lang.Integer.MAX_VALUE; -import static java.lang.System.currentTimeMillis; - -import java.nio.ByteBuffer; -import java.util.Random; -import java.util.concurrent.atomic.AtomicInteger; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.dataformat.cbor.CBORFactory; -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.datatype.binary.Binary; -import com.pushtechnology.diffusion.datatype.json.JSON; - -/** - * Random data for examples. - * - * @author DiffusionData Limited - * @since 5.7 - */ -public final class RandomData { - private static final AtomicInteger ID_GENERATOR = new AtomicInteger(0); - private static final Random RANDOM = new Random(); - private static final CBORFactory CBOR_FACTORY = new CBORFactory(); - private static final ObjectMapper OBJECT_MAPPER = - new ObjectMapper(CBOR_FACTORY); - - private final int id; - private final long timestamp; - private final int randomInt; - - private RandomData(int id, long timestamp, int randomInt) { - this.id = id; - this.timestamp = timestamp; - this.randomInt = randomInt; - } - - /** - * @return The ID of the data value - */ - public int getId() { - return id; - } - - /** - * @return The timestamp the data value was created - */ - public long getTimestamp() { - return timestamp; - } - - /** - * @return The random integer of the data value - */ - public int getRandomInt() { - return randomInt; - } - - @Override - public String toString() { - return getClass().getSimpleName() + "() { - @Override - public void onRequest(JSON request, RequestContext context, - Responder responder) { - - LOG.info("Received request {}", request); - - // Respond to the client that sent a message - responder.respond( - // Create the JSON value 'true' - Diffusion.dataTypes().json().fromJsonString("true")); - } - - @Override - public void onClose() { - LOG.info("RequestHandler closed"); - } - - @Override - public void onError(ErrorReason errorReason) { - LOG.info("RequestHandler error: {}", errorReason); - } - }); - } - - /** - * Entry point for the example. - * @param args The command line arguments - * @throws InterruptedException If the main thread was interrupted - */ - public static void main(String[] args) throws InterruptedException { - final ReceivingJson client = - new ReceivingJson("ws://diffusion.example.com:80", "auth"); - client.start("auth_secret"); - client.waitForStopped(); - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/SendingJson.java b/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/SendingJson.java deleted file mode 100644 index 369d348d..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/SendingJson.java +++ /dev/null @@ -1,92 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2016, 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -package com.pushtechnology.diffusion.examples.runnable; - -import java.util.concurrent.CompletableFuture; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.pushtechnology.diffusion.client.features.Messaging; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.datatype.json.JSON; - -/** - * A client that creates and sends JSON requests. - * - * @author DiffusionData Limited - * @since 5.7 - * @see ReceivingJson - */ -public final class SendingJson extends AbstractClient { - private static final Logger LOG = LoggerFactory - .getLogger(ProducingJson.class); - - /** - * Constructor. - * @param url The URL to connect to - * @param principal The principal to connect as - */ - public SendingJson(String url, String principal) { - super(url, principal); - } - - @Override - public void onConnected(Session session) { - - final JSON request; - - try { - request = RandomData.toJSON(RandomData.next()); - } - catch (JsonProcessingException e) { - LOG.error("Failed to transform RandomData to Content"); - return; - } - - final Messaging messaging = session.feature(Messaging.class); - - // Send the request to the server - final CompletableFuture response = - messaging.sendRequest( - "json/request", - request, - JSON.class, - JSON.class); - - response.whenComplete((result, error) -> { - if (error != null) { - LOG.error("Request failed", error); - } - else { - LOG.info("Received response {}", result); - } - }); - } - - /** - * Entry point for the example. - * @param args The command line arguments - * @throws InterruptedException If the main thread was interrupted - */ - public static void main(String[] args) throws InterruptedException { - final SendingJson client = - new SendingJson("ws://diffusion.example.com:80", "auth"); - client.start("auth_secret"); - client.waitForStopped(); - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/package-info.java b/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/package-info.java deleted file mode 100644 index 932e9b1c..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/examples/runnable/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2016, 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -/** - * This provides a number of runnable examples of using the Diffusion API. The examples provide main methods - * as entry points. The Diffusion Client Library must be present on the classpath for them to run. - * - * @author DiffusionData Limited - * @since 5.7 - */ -package com.pushtechnology.diffusion.examples.runnable; \ No newline at end of file diff --git a/java/src/main/java/com/pushtechnology/diffusion/gettingstarted/PublishingClient.java b/java/src/main/java/com/pushtechnology/diffusion/gettingstarted/PublishingClient.java deleted file mode 100644 index 0a8d7f57..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/gettingstarted/PublishingClient.java +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2017, 2019 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.gettingstarted; - -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.TopicUpdate; -import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicType; - -/** - * A client that publishes an incrementing count to the topic 'foo/counter'. - * - * @author DiffusionData Limited - * @since 5.5 - */ -public final class PublishingClient { - - /** - * Main. - */ - public static void main(String... arguments) throws InterruptedException, ExecutionException, TimeoutException { - - // Connect using a principal with 'modify_topic' and 'update_topic' - // permissions - final Session session = - Diffusion.sessions().principal("principal").password("password"). - open("ws://host:80"); - - // Get the TopicControl and TopicUpdate feature - final TopicControl topicControl = session.feature(TopicControl.class); - - final TopicUpdate topicUpdate = session.feature(TopicUpdate.class); - - // Create an int64 topic 'foo/counter' - final CompletableFuture future = topicControl.addTopic( - "foo/counter", - TopicType.INT64); - - // Wait for the CompletableFuture to complete - future.get(10, TimeUnit.SECONDS); - - // Update the topic - for (long i = 0; i < 1000; ++i) { - - // Use the non-exclusive updater to update the topic without locking it - topicUpdate.set("foo/counter", Long.class, i); - - Thread.sleep(1000); - } - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/gettingstarted/SubscribingClient.java b/java/src/main/java/com/pushtechnology/diffusion/gettingstarted/SubscribingClient.java deleted file mode 100644 index 204363b0..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/gettingstarted/SubscribingClient.java +++ /dev/null @@ -1,77 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2014, 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.gettingstarted; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.Topics; -import com.pushtechnology.diffusion.client.features.Topics.ValueStream; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; - -/** - * A client that subscribes to the topic 'foo/counter. - * - * @author DiffusionData Limited - * @since 5.5 - */ -public class SubscribingClient { - - private static final Logger LOG = - LoggerFactory.getLogger(SubscribingClient.class); - - /** - * Main. - */ - public static void main(String... arguments) throws Exception { - - // Connect anonymously - // Replace 'host' with your hostname - final Session session = Diffusion.sessions().open("ws://host:80"); - - // Get the Topics feature to subscribe to topics - final Topics topics = session.feature(Topics.class); - - // Add a new stream for 'foo/counter' - topics.addStream(">foo/counter", Long.class, new ValueStreamPrintLn()); - - // Subscribe to the topic 'foo/counter' - topics.subscribe("foo/counter") - .whenComplete((voidResult, exception) -> { - if (exception != null) { - LOG.info("subscription failed", exception); - } - }); - - // Wait for a minute while the stream prints updates - Thread.sleep(60000); - } - - /** - * A topic stream that prints updates to the console. - */ - private static class ValueStreamPrintLn extends ValueStream.Default { - @Override - public void onValue( - String topicPath, - TopicSpecification specification, - Long oldValue, - Long newValue) { - System.out.println(topicPath + ": " + newValue); - } - } -} \ No newline at end of file diff --git a/java/src/main/java/com/pushtechnology/diffusion/gettingstarted/package-info.java b/java/src/main/java/com/pushtechnology/diffusion/gettingstarted/package-info.java deleted file mode 100644 index 691c6848..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/gettingstarted/package-info.java +++ /dev/null @@ -1,22 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2014, 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -/** - * This provides simple getting started examples using the Diffusion API. - * - * @author DiffusionData Limited - * @since 5.5 - */ -package com.pushtechnology.diffusion.gettingstarted; \ No newline at end of file diff --git a/java/src/main/java/com/pushtechnology/diffusion/tutorials/PubSubExample.java b/java/src/main/java/com/pushtechnology/diffusion/tutorials/PubSubExample.java deleted file mode 100644 index 5dff2d61..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/tutorials/PubSubExample.java +++ /dev/null @@ -1,88 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2017, 2019 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ -package com.pushtechnology.diffusion.tutorials; - -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import com.pushtechnology.diffusion.client.Diffusion; -import com.pushtechnology.diffusion.client.features.TopicUpdate; -import com.pushtechnology.diffusion.client.features.Topics; -import com.pushtechnology.diffusion.client.features.control.topics.TopicControl; -import com.pushtechnology.diffusion.client.session.Session; -import com.pushtechnology.diffusion.client.topics.details.TopicSpecification; -import com.pushtechnology.diffusion.client.topics.details.TopicType; -import com.pushtechnology.diffusion.datatype.json.JSON; -import com.pushtechnology.diffusion.datatype.json.JSONDataType; - -/** - * Example of basic publish / subscribe functionality. - * - * @author DiffusionData Limited - * @since 6.0 - */ -public class PubSubExample { - public static void main(String... arguments) throws Exception { - - /** - * Connect to Diffusion using hostname/port, with supplied credentials - */ - final Session session = Diffusion.sessions() - .principal("admin") - .password("password") - .open("ws://localhost:8080"); - - final Topics topics = session.feature(Topics.class); - final TopicControl topicControl = session.feature(TopicControl.class); - - /** - * Subscribe to the "counter" topic and establish a JSON value stream - */ - topics.addStream("counter", JSON.class, new Topics.ValueStream.Default() { - @Override - public void onSubscription(String topicPath, TopicSpecification specification) { - System.out.println("Subscribed to: " + topicPath); - } - - @Override - public void onValue(String topicPath, TopicSpecification specification, JSON oldValue, JSON newValue) { - System.out.println(topicPath + " : " + newValue.toJsonString()); - } - }); - - topics.subscribe("counter"); - - /** - * Add the "counter" topic - */ - topicControl.addTopic("counter", TopicType.JSON); - - final JSONDataType jsonDataType = Diffusion.dataTypes().json(); - final TopicUpdate topicUpdate = session.feature(TopicUpdate.class); - - final AtomicInteger i = new AtomicInteger(0); - - /** - * Schedule a recurring task that increments the counter and updates the "counter" topic with a JSON value - */ - Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> { - final JSON value = jsonDataType.fromJsonString( - String.format("{\"count\" : %d }", i.getAndIncrement())); - - topicUpdate.set("counter", JSON.class, value); - }, 1000, 1000, TimeUnit.MILLISECONDS); - } -} diff --git a/java/src/main/java/com/pushtechnology/diffusion/tutorials/package-info.java b/java/src/main/java/com/pushtechnology/diffusion/tutorials/package-info.java deleted file mode 100644 index a0f870e1..00000000 --- a/java/src/main/java/com/pushtechnology/diffusion/tutorials/package-info.java +++ /dev/null @@ -1,22 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2017, 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -/** - * This provides a number of examples of using the Diffusion API. - * - * @author DiffusionData Limited - * @since 6.0 - */ -package com.pushtechnology.diffusion.tutorials; \ No newline at end of file diff --git a/java/src/main/resources/logback.xml b/java/src/main/resources/logback.xml deleted file mode 100644 index ee449794..00000000 --- a/java/src/main/resources/logback.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} %marker %msg%n - - - - - - - diff --git a/js/README.md b/js/README.md deleted file mode 100644 index 5d0957e5..00000000 --- a/js/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# JavaScript Examples for the Diffusion APIs - -This directory contains examples showing the use of the JavaScript API -for Diffusion and Diffusion Cloud. - - -## Client libraries - -You can install the Node version of the JavaScript client library with the following command: - -`npm install diffusion` - - -You can download the browser version of the JavaScript client library from the following locations: - -* Download from [our website](https://www.pushtechnology.com/developers/release/latest/#js-sdk) - -* The client libraries are also available in the `clients` directory of the Diffusion installation. diff --git a/js/connection/connect-securely.js b/js/connection/connect-securely.js new file mode 100644 index 00000000..e8536bb4 --- /dev/null +++ b/js/connection/connect-securely.js @@ -0,0 +1,38 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function connectSecurelyExample() { + /// tag::connection_establishment_accept_all_certificates[] + const session = await diffusion.connect({ + host: 'localhost', + port: 443, + secure: true, + principal: 'admin', + credentials: 'password' + }); + + console.log(`Connected. Session Identifier: ${session.sessionId.toString()}`); + + // Insert work here + /// tag::log + expect(session.sessionId).not.toBeNull(); + expect(session.isConnected()).toBe(true); + /// end::log + + await session.closeSession(); + /// end::connection_establishment_accept_all_certificates[] +} diff --git a/js/connection/connect-shared-existing.js b/js/connection/connect-shared-existing.js new file mode 100644 index 00000000..796ecca6 --- /dev/null +++ b/js/connection/connect-shared-existing.js @@ -0,0 +1,36 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function connectSharedExistingExample() { + /// tag::connection_establishment_connect_via_shared_worker[] + // Connect to the server through an existing shared session. + const session = await diffusion.connectShared( + 'my-shared-session', + 'http://localhost/path/to/diffusion-worker.js' + ); + + console.log(`Connected. Session Identifier: ${session.sessionId.toString()}`); + + // Insert work here + /// tag::log + expect(session.sessionId).not.toBeNull(); + expect(session.isConnected()).toBe(true); + /// end::log + + await session.closeSession(); + /// end::connection_establishment_connect_via_shared_worker[] +} diff --git a/js/connection/connect-shared-new.js b/js/connection/connect-shared-new.js new file mode 100644 index 00000000..ad74f518 --- /dev/null +++ b/js/connection/connect-shared-new.js @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function connectSharedNewExample() { + /// tag::connection_establishment_connect_new_shared_worker[] + // Connect to the server creating a new shared session. + const session = await diffusion.connect( + { + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }, + 'my-shared-session', + 'http://localhost/path/to/diffusion-worker.js' + ); + + console.log(`Connected. Session Identifier: ${session.sessionId.toString()}`); + + // Insert work here + /// tag::log + expect(session.sessionId).not.toBeNull(); + expect(session.isConnected()).toBe(true); + /// end::log + + await session.closeSession(); + /// end::connection_establishment_connect_new_shared_worker[] +} diff --git a/js/connection/connect.js b/js/connection/connect.js new file mode 100644 index 00000000..1921f964 --- /dev/null +++ b/js/connection/connect.js @@ -0,0 +1,37 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function connectExample() { + /// tag::connection_establishment_connect_async[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + console.log(`Connected. Session Identifier: ${session.sessionId.toString()}`); + + // Insert work here + /// tag::log + expect(session.sessionId).not.toBeNull(); + expect(session.isConnected()).toBe(true); + /// end::log + + await session.closeSession(); + /// end::connection_establishment_connect_async[] +} diff --git a/js/connection/resilience-reconnect.js b/js/connection/resilience-reconnect.js new file mode 100644 index 00000000..abd1dd49 --- /dev/null +++ b/js/connection/resilience-reconnect.js @@ -0,0 +1,61 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function connectionReconnectExample() { + /// tag::connection_resilience_reconnection_strategy[] + let session; + let attempts = 0; + + try { + // Connect to the server. + session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password', + reconnect: { + // Set the maximum amount of time the client will try and reconnect for to 10 minutes + timeout: 1000 * 60 * 10, + // The reconnection strategy is a function that is called when the session is + // disconnected unexpectedly + strategy: (reconnect, abort) => { + if (attempts > 10) { + // abort after 10 attempts + abort(); + } else { + // retry after 3 seconds + setTimeout(reconnect, 3000); + } + } + } + }); + } catch (err) { + console.error('Connection could not be established.', err); + throw err; + } + + console.log(`Connected. Session Identifier: ${session.sessionId.toString()}`); + + // Insert work here + /// tag::log + expect(session.sessionId).not.toBeNull(); + expect(session.isConnected()).toBe(true); + /// end::log + + await session.closeSession(); + /// end::connection_resilience_reconnection_strategy[] +} diff --git a/js/connection/resilience-retry.js b/js/connection/resilience-retry.js new file mode 100644 index 00000000..9d2203a9 --- /dev/null +++ b/js/connection/resilience-retry.js @@ -0,0 +1,48 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function initialConnectRetryExample() { + /// tag::connection_resilience_session_establishment_retry_mechanism[] + let session; + try { + // Connect to the server. + session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password', + retry: { + attempts: 10, + interval: 250 + } + }); + } catch (err) { + console.error('Connection could not be established.', err); + throw err; + } + + console.log(`Connected. Session Identifier: ${session.sessionId.toString()}`); + + // Insert work here + /// tag::log + expect(session.sessionId).not.toBeNull(); + expect(session.isConnected()).toBe(true); + /// end::log + + await session.closeSession(); + /// end::connection_resilience_session_establishment_retry_mechanism[] +} diff --git a/js/connection/session-state-listener.js b/js/connection/session-state-listener.js new file mode 100644 index 00000000..cee8e6f0 --- /dev/null +++ b/js/connection/session-state-listener.js @@ -0,0 +1,71 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester } = require('../../../test/util'); +/// end::log + +export async function sessionStateListenerExample() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['close'] + ]); + /// end::log + /// tag::connection_session_state_listener[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + // Attach state listeners + session.on({ + disconnect : () => { + console.log('State changed to disconnected'); + /// tag::log + check.log('disconnect'); + /// end::log + }, + reconnect : () => { + console.log('State changed to reconnected'); + /// tag::log + check.log('reconnect'); + /// end::log + }, + error : (error) => { + console.log('An error occured', error); + /// tag::log + check.log('error'); + /// end::log + }, + close : (reason) => { + console.log('State changed to closed', reason); + /// tag::log + check.log('close'); + /// end::log + } + }); + + // Insert work here + + await session.closeSession(); + /// end::connection_session_state_listener[] + /// tag::log + check.done(); + /// end::log +} diff --git a/js/examples/addTopics.js b/js/examples/addTopics.js deleted file mode 100644 index 01b5aed8..00000000 --- a/js/examples/addTopics.js +++ /dev/null @@ -1,67 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -var diffusion = require('diffusion'); - -// Connect to the server. Change these options to suit your own environment. -// Node.js does not accept self-signed certificates by default. If you have -// one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 -// before running this example. -diffusion.connect({ - host : 'diffusion.example.com', - port : 443, - secure : true, - principal : 'control', - credentials : 'password' -}).then(function(session) { - // 1. Topics can be created with a topic path and a TopicType or TopicSpecification. The '/' delimiter allows topics - // to be created in a hierarchy. - - var TopicSpecification = diffusion.topics.TopicSpecification; - var TopicType = diffusion.topics.TopicType; - - // Create a topic from a topic type - session.topics.add('topic/string', new TopicSpecification(TopicType.STRING)); - - // Create a topic from a topic specification, with optional properties - session.topics.add('topic/integer', new TopicSpecification(TopicType.INT64, { - VALIDATES_VALUES : "true" - })); - - // 2. Adding a topic returns a result, which allows us to handle when the operation has either completed - // successfully or encountered an error. - session.topics.add('topic/result', new TopicSpecification(TopicType.JSON)).then(function(result) { - console.log('Added topic: ' + result.topic); - }, function(reason) { - console.log('Failed to add topic: ', reason); - }); - - // Adding a topic that already exists will succeed, so long as it has the same value type - session.topics.add('topic/result', new TopicSpecification(TopicType.JSON)).then(function(result) { - // result.added will be false, as the topic already existed - console.log('Added topic: ' + result.topic, result.added); - }); - - // 3. Because the result returned from adding a topic is a promise, we can easily chain multiple topic adds together - session.topics.add('chain/foo', new TopicSpecification(TopicType.STRING)) - .then(session.topics.add('chain/bar', new TopicSpecification(TopicType.STRING))) - .then(session.topics.add('chain/baz', new TopicSpecification(TopicType.STRING))) - .then(session.topics.add('chain/bob', new TopicSpecification(TopicType.STRING))) - .then(function() { - console.log('Added all topics'); - }, function(reason) { - console.log('Failed to add topic', reason); - }); -}); diff --git a/js/examples/clientControl.js b/js/examples/clientControl.js deleted file mode 100644 index cd898629..00000000 --- a/js/examples/clientControl.js +++ /dev/null @@ -1,76 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -var diffusion = require('diffusion'); - -// Connect to the server. Change these options to suit your own environment. -// Node.js does not accept self-signed certificates by default. If you have -// one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 -// before running this example. -diffusion.connect({ - host : 'localhost', - port : 8080, - secure : false, - principal : 'control', - credentials : 'password' -}).then(function(session) { - - // Get our own fixed properties - session.clients.getSessionProperties(session.sessionId, diffusion.clients.PropertyKeys.ALL_FIXED_PROPERTIES) - .then(function(props) { - console.log('getSessionProperties returns properties:', props); - }, function(err) { - console.log('An error has occurred:', err); - }); - - // Register a listener for session properties - session.clients.setSessionPropertiesListener(diffusion.clients.PropertyKeys.ALL_FIXED_PROPERTIES, { - onActive : function(deregister) { - console.log("Session properties listener opened"); - - // Call deregister() to close this listener - }, - onClose : function() { - console.log("Session properties listener closed"); - }, - onSessionOpen : function(session, properties) { - // Notification that a session has been opened - console.log("Session opened: " + session, JSON.stringify(properties)); - }, - onSessionEvent : function(session, event, properties) { - // Notification that a session's properties have changed - switch (event) { - case session.clients.SessionEventType.UPDATED : - console.log("Session updated: " + session, JSON.stringify(properties)); - break; - case session.clients.SessionEventType.DISCONNECTED : - console.log("Session disconnected: " + session, JSON.stringify(properties)); - break; - case session.clients.SessionEventType.RECONNECTED : - console.log("Session reconnected: " + session, JSON.stringify(properties)); - break; - case session.clients.SessionEventType.FAILED_OVER : - console.log("Session failed over: " + session, JSON.stringify(properties)); - } - }, - onSessionClose : function(session, properties, reason) { - console.log("Session closed: " + session + " reason: " + reason, JSON.stringify(properties)); - } - }).then(function() { - console.log("Session listener successfully registered"); - }, function(err) { - console.log('An error occurred registering a session listener:', err); - }); -}); diff --git a/js/examples/connectRetry.js b/js/examples/connectRetry.js deleted file mode 100644 index 5edbca46..00000000 --- a/js/examples/connectRetry.js +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -import { connect, Session } from 'diffusion'; - -// example showcasing how to set an initial connection retry -export async function connectionRetryExample() { - - // When establishing a session, it is possible to specify whether the initial - // connection attempt should be retried when a failure occurs - - // Connect to the server. - const session = await connect({ - host: 'diffusion.example.com', - port: 443, - secure: true, - principal: 'control', - credentials: 'password', - retry: { - // perform 5 initial connection attempts before giving up - attempts: 5, - // set 300 ms between connection attempts - interval: 300 - } - }); - - console.log(`Connection established ${session.sessionId}`); -} diff --git a/js/examples/datatypes.js b/js/examples/datatypes.js deleted file mode 100644 index 742a2921..00000000 --- a/js/examples/datatypes.js +++ /dev/null @@ -1,76 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -var diffusion = require('diffusion'); - -// Connect to the server. Change these options to suit your own environment. -// Node.js does not accept self-signed certificates by default. If you have -// one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 -// before running this example. -diffusion.connect({ - host : 'diffusion.example.com', - port : 443, - secure : true, - principal : 'control', - credentials : 'password' -}).then(function(session) { - - // 1. Data Types are exposed from the top level Diffusion namespace. It is often easier - // to assign these directly to a local variable. - var stringDataType = diffusion.datatypes.string(); - var jsonDataType = diffusion.datatypes.json(); - var TopicSpecification = diffusion.topics.TopicSpecification; - var TopicType = diffusion.topics.TopicType; - - // 2. Data Types are currently provided for JSON, Binary, String, Double, Int64 and RecordV2 topic types. - session.topics.add('topic/string', new TopicSpecification(TopicType.STRING)); - session.topics.add('topic/json', new TopicSpecification(TopicType.JSON)); - - // 3. Values can be created directly from the data type. - var jsonValue = jsonDataType.from({ - "foo" : "bar" - }); - - // Topics are updated using the standard update mechanisms - session.topicUpdate.set('topic/json', jsonDataType, jsonValue), - - // For String, Double and Int64 topics, values can be passed directly - session.topicUpdate.set('topic/string', stringDataType, "This is a new string value") - - - session.select('?topic//'); - - // 4. Add a value streams for receiving JSON values. - session.addStream('topic/json', jsonDataType).on('value', function(topic, spec, newValue, oldValue) { - // When a JSON or Binary topic is updated, any value handlers on a subscription will be called with both the - // new value, and the old value. - - // The oldValue parameter will be undefined if this is the first value received for a topic. - - // For JSON topics, value#get returns a JavaScript object. - // For Binary topics, value#get returns a Buffer instance. - console.log("Update for " + topic, newValue.get()); - }); - - session.addStream('topic/string', stringDataType).on('value', function(topic, spec, newValue, oldValue) { - // Unlike JSON or Binary, String, Double and Int64 datatypes provide values as primitive types. - // This means you don't need to call #get to receive the actual data. - console.log("Update for string topic: " + newValue); - }); - - // 5. Raw values of an appropriate type can also be used for JSON and Binary topics. - // For example, plain JSON objects can be used to update JSON topics. - session.topicUpdate.set('topic/json', jsonDataType, {"foo" : "baz", "numbers" : [1, 2, 3] }); -}); diff --git a/js/examples/fallbackStream.js b/js/examples/fallbackStream.js deleted file mode 100644 index 58a8d36e..00000000 --- a/js/examples/fallbackStream.js +++ /dev/null @@ -1,74 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -var diffusion = require('diffusion'); - -// Data Types are exposed from the top level Diffusion namespace. It is often easier -// to assign these directly to a local variable. -var stringDataType = diffusion.datatypes.string(); -var TopicSpecification = diffusion.topics.TopicSpecification; -var TopicType = diffusion.topics.TopicType; - -// Connect to the server. Change these options to suit your own environment. -// Node.js does not accept self-signed certificates by default. If you have -// one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 -// before running this example. -diffusion.connect({ - host : 'diffusion.example.com', - port : 443, - secure : true, - principal : 'control', - credentials : 'password' -}).then(function(session) { - - // 1. Create a String topic type - session.topics.add('topic/foo', new TopicSpecification(TopicType.STRING)).then(function() { - // Once the topic is added successfully then update it with a new value - session.topicUpdate.set('topic/foo', stringDataType, "foo-string"); - }, function(err) { - console.log("Fail to update topic 'foo': ", err); - }); - - // Create another String topic type - session.topics.add('topic/bar', new TopicSpecification(TopicType.STRING)).then(function() { - session.session.topicUpdate.set('topic/bar', stringDataType, 'bar-string'); - }, function(err) { - console.log("Fail to update topic 'bar': ", err); - }); - - // And another String topic type - session.topics.add('topic/baz', new TopicSpecification(TopicType.STRING)).then(function() { - session.topicUpdate.set('topic/baz', stringDataType, "baz-string"); - }, function(err) { - console.log("Fail to update topic 'baz': ", err); - }); - - // 2. Register a value stream for receiving String value update - session.addStream('topic/foo', stringDataType) - .on('value', function(topic, specification, newValue, oldValue) { - console.log("Received update ", newValue); - }); - - - // 3. Register a fallback value stream to receive update for any topics that don't have a stream register - // In this example, the falback stream will receive updates from 'topic/bar' and 'topic/baz' - session.addFallbackStream(stringDataType) - .on('value', function(topic, specification, newValue, oldValue) { - console.log("Received update ", newValue); - }); - - // 4. Subscribe - session.select('?topic//'); -}); \ No newline at end of file diff --git a/js/examples/fetchRequest.js b/js/examples/fetchRequest.js deleted file mode 100644 index 2b25604b..00000000 --- a/js/examples/fetchRequest.js +++ /dev/null @@ -1,81 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -var diffusion = require('diffusion'); - -var jsonDataType = diffusion.datatypes.json(); -var TopicType = diffusion.topics.TopicType; - - -// Connect to the server. Change these options to suit your own environment. -// Node.js does not accept self-signed certificates by default. If you have -// one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 -// before running this example. -diffusion.connect({ - host : 'diffusion.example.com', - port : 443, - secure : true, - principal : 'client', - credentials : 'password' -}).then(function(session) { - session - .fetchRequest() // obtain a FetchRequest - .from("SomeTopic/B") // limit to topics after and including SomeTopic/B - .to("SomeTopic/X") // limit to topics before and including SomeTopic/X - .first(10) // only fetch the first 10 topics - .topicTypes([TopicType.STRING, TopicType.INT64]) // limit to string and integer topic types - .withValues(jsonDataType) // fetch values return them as JSON objects - .withProperties() // get the topic properties - .fetch("*SomeTopic//") // perform the fetch request using a topic selector - .then(function(fetchResult) { - var results = fetchResult.results(); - console.log("Fetch Request returned "+results.length+" topics"); - - results.forEach(function(topicResult) { - console.log("Path: "+topicResult.path()); - console.log("Type: "+topicResult.type()); - console.log("Value: "+topicResult.value().get()); - }); - - if (fetchResult.hasMore()) { - console.log("There are more topics"); - } - }); - - session - .fetchRequest() // obtain a FetchRequest - .limitBranchDepth(3, 3) // A deep branch has a root path that has a - // number of parts equal to the deep_branch_depth parameter. - // The deep_branch_limit specifies the maximum number of results for each deep branch. - .withProperties() // get the topic properties - .topicTypes([TopicType.STRING, TopicType.INT64]) // limit to string and integer topic types - .withValues(jsonDataType) // fetch values return them as JSON objects - .fetch("?.//") // perform the fetch using a topic selector - .then(function(fetchResult) { - var results = fetchResult.results() - - console.log("Fetch Request returned "+results.length+" topics"); - - results.forEach(function(topicResult) { - console.log("Path: "+topicResult.path()); - console.log("Type: "+topicResult.type()); - console.log("Value: "+topicResult.value().get()); - }); - - if (fetchResult.hasMore()) { - console.log("There are more topics"); - } - }); -}); diff --git a/js/examples/jsonSubscription.js b/js/examples/jsonSubscription.js deleted file mode 100644 index d829d6d7..00000000 --- a/js/examples/jsonSubscription.js +++ /dev/null @@ -1,52 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -var diffusion = require('diffusion'); - -// Connect to the server. Change these options to suit your own environment. -// Node.js will not accept self-signed certificates by default. If you have -// one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 -// before running this example. -diffusion.connect({ - host : 'diffusion.example.com', - port : 443, - secure : true -}).then(function(session) { - - // 1. ValueStreams are the best way to receive values from JSON and Binary topics. - - // Streams for notifications can be registered separately from subscribing to a topic. Registering a stream is a - // local operation and does not change the data the client receives. - - // Like subscribing, streams are registered using a topic selection. Each stream will only receive notifications - // from topics that match the topic selector it is registered with. - - // A ValueStream will only receive notifications from topics that match the topic selector it is registered - // with and that match its DataType. - - // A ValueStream emits a 'value' notification, listeners for 'value' events will be passed the topic path, - // topic specification, the new value of the topic and the previous value. - - // A ValueStream also emits 'open', 'close', 'subscribe' and 'unsubscribe' events. - - session - .addStream('foo', diffusion.datatypes.json()) - .on('value', function(path, specification, newValue, oldValue) { - console.log('Got JSON update for topic: ' + path, newValue.get()); - }); - - // 2. Subscribe to the "foo" topic. The value stream registered earlier will now start to receive notifications. - session.select('foo'); -}); diff --git a/js/examples/messages-filter.js b/js/examples/messages-filter.js deleted file mode 100644 index 550614f3..00000000 --- a/js/examples/messages-filter.js +++ /dev/null @@ -1,64 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -var diffusion = require('diffusion'); - -// Connect to the server. Change these options to suit your own environment. -// Node.js will not accept self-signed certificates by default. If you have -// one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 -// before running this example. -diffusion.connect({ - host : 'diffusion.example.com', - port : 443, - secure : true, - principal : 'control', - credentials : 'password' -}).then(function(session) { - // Create a request handler that handles strings - var requestSream = { - onRequest: function(path, request, responder) { - console.log('Received request: ' + request); // Log the request - responder.respond('something'); - }, - onError: function() { - console.log('An error occurred'); - }, - onClose: function() { - console.log('Handler closed'); - } - }; - - // Register the stream - session.messages.setRequestStream('foo/bar', requestSream); - - // Send a message to another session listening on 'foo' by way of - // session properties. - var responseHandler = { - onResponse : function(sessionID, response) { - console.log("Received response " + response); - }, - onResponseError : function() { - console.log("There was an error when receiving the response"); - }, - onError : function() { - console.log("There was an with the response handler"); - }, - onClose : function() { - console.log("The response handler was closed"); - } - }; - - session.messages.sendRequestToFilter('$Principal is "control"', 'foo/bar', 'Hello world', responseHandler); -}); diff --git a/js/examples/messages.js b/js/examples/messages.js deleted file mode 100644 index 8280b517..00000000 --- a/js/examples/messages.js +++ /dev/null @@ -1,85 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -var diffusion = require('diffusion'); - -// Connect to the server. Change these options to suit your own environment. -// Node.js will not accept self-signed certificates by default. If you have -// one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 -// before running this example. -diffusion.connect({ - host : 'diffusion.example.com', - port : 443, - secure : true, - principal : 'control', - credentials : 'password' -}).then(function(session) { - - // 1. Messages can be sent & received between sessions. - // Create a request handler that handles strings - var handler = { - onRequest: function(request, context, responder) { - console.log('Received request: ' + request); // Log the request - responder.respond('something'); - }, - onError: function() { - console.log('An error occurred'); - }, - onClose: function() { - console.log('Handler closed'); - } - }; - - // Register the handler - session.messages.addRequestHandler('foo/bar', handler).then(function() { - console.log("Request handler has been added") - }, function(error) { - console.log('Failed to register request handler: ', e); - }); - - // 2. Messages can be sent & received between sessions. - - // Send a message to another session. It is the application's responsibility - // to find the SessionID of the intended recipient. - session.messages.sendRequest('foo/bar', 'Hello World', 'another-session-id', diffusion.datatypes.string(), diffusion.datatypes.string()) - .then(function(response) { - console.log("Received response " + response); - }); - - // 3. Messages can also be sent without a recipient, in which case they will be dispatched to any Message Handlers - // that have been registered for the same path. If multiple handlers are registered to the same path, any given - // message will only be dispatched to one handler. - - // Send a message at a lower path, without an explicit recipient - this will be received by the Handler. - session.messages.sendRequest('foo/bar', 'Hello World', diffusion.datatypes.string(), diffusion.datatypes.string()) - .then(function(response) { - console.log("Received response " + response); - }); - - // 4. The datatype of the message and the response can be specified using topic types or omitted altogether. - // In the latter case, the datatype is inferred from the value passed to sendRequest() - - // Send a message using topic types to specify the datatype - session.messages.sendRequest('foo/bar', 'Hello World', diffusion.topics.TopicType.STRING, diffusion.topics.TopicType.STRING) - .then(function(response) { - console.log("Received response " + response); - }); - - // Send a message leaving out the datatype - session.messages.sendRequest('foo/bar', 'Hello World') - .then(function(response) { - console.log("Received response " + response); - }); -}); diff --git a/js/examples/missing-topic-notification.js b/js/examples/missing-topic-notification.js deleted file mode 100644 index 1a52bced..00000000 --- a/js/examples/missing-topic-notification.js +++ /dev/null @@ -1,70 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -var diffusion = require('diffusion'); - -// Connect to the server. Change these options to suit your own environment. -// Node.js will not accept self-signed certificates by default. If you have -// one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 -// before running this example. -diffusion.connect({ - host : 'diffusion.example.com', - port : 443, - secure : true -}).then(function(session) { - var stringDataType = diffusion.datatypes.string(); - var TopicType = diffusion.topics.TopicType; - var TopicSpecification = diffusion.topics.TopicSpecification; - - // Register a missing topic handler on the 'example' root topic - // Any subscriptions to missing topics along this path will invoke this handler - session.topics.addMissingTopicHandler('example', { - // Called when a handler is successfully registered - onRegister : function(path, close) { - console.log(`Registered missing topic handler on path: ${path}`); - - // Once we've registered the handler, we subscribe with the selector '?example/topic/.*' - session.select('?example/topic/.*'); - - // Register a stream to listen for a subscription event - session.addStream('?example/topic/.*', stringDataType).on('subscribe', function(topic, specification) { - console.log(`Subscribed to topic: ${topic}`); - }); - }, - // Called when the handler is closed - onClose : function(path) { - console.log(`Missing topic handler on path '${path}' has been closed`); - }, - // Called if there is an error on the handler - onError : function(path, error) { - console.log('Error on missing topic handler'); - }, - // Called when we've received a missing topic notification on our registered handler path - onMissingTopic : function(notification) { - console.log(`Received missing topic notification with selector: ${notification.selector}`); - - // Once we've received the missing topic notification initiated from subscribing to '?example/topic/.*', - // we add a topic that will match the selector - var topic = 'example/topic/foo'; - - session.topics.add(topic, new TopicSpecification(TopicType.STRING)).then(function(result) { - console.log(`Topic add success: ${path}`); - }, function(reason) { - console.log(`Topic add failed: ${reason}`); - }); - } - }); - -}); diff --git a/js/examples/reconnect.js b/js/examples/reconnect.js deleted file mode 100644 index 81de9e28..00000000 --- a/js/examples/reconnect.js +++ /dev/null @@ -1,79 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -var diffusion = require('diffusion'); - -// When establishing a session, it is possible to specify whether reconnection -// should be attempted in the event of an unexpected disconnection. This allows -// the session to recover its previous state. - -// Set the maximum amount of time we'll try and reconnect for to 10 minutes -var maximumTimeoutDuration = 1000 * 60 * 10; - -// Set the maximum interval between reconnect attempts to 60 seconds -var maximumAttemptInterval = 1000 * 60; - -// Set an upper limit to the number of times we'll try to reconnect for -var maximumAttempts = 25; - -// Count the number of reconnection attempts we've made -var attempts = 0; - -// Create a reconnection strategy that applies an exponential back-off -// The strategy will be called with two arguments, start & abort. Both -// of these are functions, which allow the strategy to either start a -// reconnection attempt, or to abort reconnection (which will close the session) -var reconnectionStrategy = function(start, abort) { - if (attempts > maximumAttempts) { - abort(); - } else { - var wait = Math.min(Math.pow(2, attempts++) * 100, maximumAttemptInterval); - - // Wait the specified time period, and then start the reconnection attempt - setTimeout(start, wait); - } -}; - -// Connect to the server. -diffusion.connect({ - host : 'diffusion.example.com', - port : 443, - secure : true, - principal : 'control', - credentials : 'password', - reconnect : { - timeout : maximumTimeoutDuration, - strategy : reconnectionStrategy - } -}).then(function(session) { - - session.on('disconnect', function(reason) { - // This will be called when we lose connection. Because we've specified the - // reconnection strategy, it will be called automatically when this event - // is dispatched - }); - - session.on('reconnect', function() { - // If the session is able to reconnect within the reconnect timeout, this - // event will be dispatched to notify that normal operations may resume - attempts = 0; - }); - - session.on('close', function() { - // If the session is closed normally, or the session is unable to reconnect, - // this event will be dispatched to notify that the session is no longer - // operational. - }); -}); diff --git a/js/examples/removeTopicWhenNoSessionIdExist.js b/js/examples/removeTopicWhenNoSessionIdExist.js deleted file mode 100644 index b17f9068..00000000 --- a/js/examples/removeTopicWhenNoSessionIdExist.js +++ /dev/null @@ -1,59 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -var diffusion = require('diffusion'); - -// Connect to the server. Change these options to suit your own environment. -// Node.js does not accept self-signed certificates by default. If you have -// one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 -// before running this example. -diffusion.connect({ - host : 'diffusion.example.com', - port : 443, - secure : true, - principal : 'control', - credentials : 'password' -}).then(function(session) { - // Subscribe to topic 'foo' - session.select("foo"); - - // Register a JSON value stream and listen for subscription/unsubscription events - var stream = session.addStream("foo", diffusion.datatypes.json()); - stream.on({ - 'subscribe': function (topic, spec) { - console.log("Subscribed to topic: ", topic); - }, - 'unsubscribe': function (topic, spec, reason) { - console.log("Unsubscribed from topic: ", topic); - console.log("Reason: ", reason); - - // Finally close the session - session.close(); - } - }); - - // Remove a topic 2 seconds when no clients with principal 'unknown' - var expression = "when no session has '$Principal is \"unknown\"' for 2s"; - - // Add a JSON topic type with the REMOVAL topic specification property - var jsonSpec = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON) - .withProperty(diffusion.topics.TopicSpecification.REMOVAL, expression); - - session.topics.add("foo", jsonSpec).then(function() { - console.log("Topic added"); - }, function(err) { - console.log("Failed ", err); - }); -}); diff --git a/js/examples/removeTopics.js b/js/examples/removeTopics.js deleted file mode 100644 index b0bd9756..00000000 --- a/js/examples/removeTopics.js +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -var diffusion = require('diffusion'); - -// Connect to the server. Change these options to suit your own environment. -// Node.js will not accept self-signed certificates by default. If you have -// one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 -// before running this example. -diffusion.connect({ - host : 'diffusion.example.com', - port : 443, - secure : true, - principal : 'control', - credentials : 'password' -}).then(async function(session) { - - var TopicSpecification = diffusion.topics.TopicSpecification; - var TopicType = diffusion.topics.TopicType; - - // 1. Like session.topics.add(), remove returns a promise, so we can chain together calls. - await session.topics.add('foo', new TopicSpecification(TopicType.STRING)); - try { - await session.topics.remove('foo'); - console.log('Removed topic foo'); - } catch (reason) { - console.log('Failed to remove topic foo: ', reason); - } - - // 2. Removing a topic will not remove any topics underneath it. - - // Add a hierarchy of topics. - await Promise.all([ - session.topics.add('a', new TopicSpecification(TopicType.STRING)), - session.topics.add('a/b', new TopicSpecification(TopicType.STRING)), - session.topics.add('a/b/c', new TopicSpecification(TopicType.STRING)), - session.topics.add('a/b/c/d', new TopicSpecification(TopicType.STRING)) - ]); - - // Wait until we've removed the root topics - await session.topics.remove('a'); - - // Child topic still exists - await session.topicUpdate.set('a/b', diffusion.datatypes.string(), 'hello'); - - // Removing all topics using a topic selector expression - await session.topics.remove('?a//'); - - console.log('Removed all topics including & under "a"'); -}); diff --git a/js/examples/rxjs.js b/js/examples/rxjs.js deleted file mode 100644 index e68ba82a..00000000 --- a/js/examples/rxjs.js +++ /dev/null @@ -1,64 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -var diffusion = require('diffusion'); -var Rx = require('rx'); - -// Connect to the server. Change these options to suit your own environment. -// Node.js does not accept self-signed certificates by default. If you have -// one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 -// before running this example. -diffusion.connect({ - host : 'diffusion.example.com', - port : 8080, - principal : 'control', - credentials : 'password' -}).then(function(session){ - var topic = 'foo'; - var jsonType = diffusion.datatypes.json(); - - // Create rxjs observable - var source = observable(session, topic, jsonType) - - // Subscribe to the rxjs observable - source.subscribe( - function (value) { - console.log('New value: ' + value); - }, - function (err) { - console.log('Error: %s', err); - }); - - // Subscribe to the topic - session.select(topic); -}); - -// Create and return an observable which creates a value stream to receive topic updates on its handler. -// The value stream is closed when the subscription to the observable is disposed of. -function observable(session, topic, type) { - var valueStream; - return Rx.Observable.fromEventPattern( - function(handler) { - valueStream = session.addStream(topic, type).on({ - value: function(topic, spec, newV, oldV) { - // Pass the new value to the handler - handler(newV); - } - }); - }, - function() { - valueStream.close(); - }); -} \ No newline at end of file diff --git a/js/examples/security.js b/js/examples/security.js deleted file mode 100644 index 21fddec8..00000000 --- a/js/examples/security.js +++ /dev/null @@ -1,83 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -var diffusion = require('diffusion'); - -// Session security allows you to change the principal that a session is authenticated as. It also allows users to -// query and update server-side security and authentication stores, which control users, roles and permissions. -// This enables you to manage the capabilities that any logged in user will have access to. - -// Connect to Diffusion with control client credentials -diffusion.connect({ - host : 'diffusion.example.com', - port : 443, - secure : true, - principal : 'control', - credentials : 'password' -}).then(function(session) { - - // 1. A session change their principal by re-authenticating - session.security.changePrincipal('admin', 'password').then(function() { - console.log('Authenticated as admin'); - }); - - // 2. The security configuration provides details about roles and their assigned permissions - session.security.getSecurityConfiguration().then(function(config) { - console.log('Roles for anonymous sessions: ', config.anonymous); - console.log('Roles for named sessions: ', config.named); - console.log('Available roles: ', config.roles); - }, function(error) { - console.log('Unable to fetch security configuration', error); - }); - - // 3. Changes to the security configuration are done with a SecurityScriptBuilder - var securityScriptBuilder = session.security.securityScriptBuilder(); - - // Set the permissions for a particular role - global and topic-scoped - // Each method on a script builder returns a new builder - var setPermissionScript = securityScriptBuilder.setGlobalPermissions('SUPERUSER', ['REGISTER_HANDLER']) - .setTopicPermissions('SUPERUSER', '/foo', ['UPDATE_TOPIC']) - .build(); - - // Update the server-side store with the generated script - session.security.updateSecurityStore(setPermissionScript).then(function() { - console.log('Security configuration updated successfully'); - }, function(error) { - console.log('Failed to update security configuration: ', error); - }); - - // 4. The system authentication configuration lists all users & roles - session.security.getSystemAuthenticationConfiguration().then(function(config) { - console.log('System principals: ', config.principals); - console.log('Anonymous sessions: ', config.anonymous); - }, function(error) { - console.log('Unable to fetch system authentication configuration', error); - }); - - // 5. Changes to the system authentication config are done with a SystemAuthenticationScriptBuilder - var authenticationScriptBuilder = session.security.authenticationScriptBuilder(); - - // Add a new user and set password & roles. - var addUserScript = authenticationScriptBuilder.addPrincipal('Superman', 'correcthorsebatterystapler') - .assignRoles('Superman', ['SUPERUSER']) - .build(); - - // Update the system authentication store - session.security.updateAuthenticationStore(addUserScript).then(function() { - console.log('Updated system authentication config'); - }, function(error) { - console.log('Failed to update system authentication: ', error); - }); -}); diff --git a/js/examples/sessionLocks.js b/js/examples/sessionLocks.js deleted file mode 100644 index a7705363..00000000 --- a/js/examples/sessionLocks.js +++ /dev/null @@ -1,77 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -var diffusion = require('diffusion'); - -var stringDataType = diffusion.datatypes.string(); -var SessionLockScope = diffusion.locks.SessionLockScope; - -var LOCK_NAME = "lockA"; - -var session1, session2; -var session1Lock, session2Lock; - -function acquireLockSession1() { - console.log("Requestinglock 1"); - session1.lock(LOCK_NAME, SessionLockScope.UNLOCK_ON_CONNECTION_LOSS) - .then(function(lock) { - console.log("Acquired lock 1"); - session1Lock = lock; - acquireLockSession2(); - setTimeout(function () { - releaseLock1(); - }, 1000); - }); -} - -function acquireLockSession2() { - console.log("Requesting lock 2"); - session2.lock(LOCK_NAME, SessionLockScope.UNLOCK_ON_CONNECTION_LOSS) - .then(function(lock) { - console.log("Acquired lock 2"); - session2Lock = lock; - }); -} - -function releaseLock1() { - console.log("Requesting lock 1 release"); - session1Lock.unlock().then(function() { - console.log("Released lock 1"); - }); -} - -// Connect to the server. Change these options to suit your own environment. -// Node.js does not accept self-signed certificates by default. If you have -// one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 -// before running this example. -diffusion.connect({ - host : 'diffusion.example.com', - port : 443, - secure : true, - principal : 'control', - credentials : 'password' -}).then(function(session) { - session1 = session; - diffusion.connect({ - host : 'diffusion.example.com', - port : 443, - secure : true, - principal : 'control', - credentials : 'password' - }).then(function(session) { - session2 = session; - acquireLockSession1(); - }); -}); diff --git a/js/examples/sessionTrees.js b/js/examples/sessionTrees.js deleted file mode 100644 index c9b9b7c0..00000000 --- a/js/examples/sessionTrees.js +++ /dev/null @@ -1,55 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -const diffusion = require('diffusion'); - -// example showcasing how create and query session tree branch mappings -diffusion.connect({ - host: 'diffusion.example.com', - port: 443, - secure: true, - principal: 'control', - credentials: 'password' -}).then(async function() { - - // Connect to the server. Change these options to suit your own environment. - // Node.js does not accept self-signed certificates by default. If you have - // one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 - // before running this example. - const session = await - - const table = diffusion.newBranchMappingTableBuilder() - .addBranchMapping("$Principal is 'control'", "target/1") - .addBranchMapping("all", "target/2") - .create("topic/path"); - - await session.sessionTrees.putBranchMappingTable(table); - - console.log(`Branch mapping table for session tree branch ${table.getSessionTreeBranch()} has been added`); - - const listSessionTreeBranches: string[] = await session.sessionTrees.getSessionTreeBranchesWithMappings(); - - console.log(`Session tree branches with mappings obtained: ${listSessionTreeBranches.join(', ')}`); - - for (const sessionTreeBranch of listSessionTreeBranches) - { - const branchMappingTable = await session.sessionTrees.getBranchMappingTable(sessionTreeBranch); - - for (var branchMapping of branchMappingTable.getBranchMappings()) - { - console.log(`Session tree branch: '${sessionTreeBranch}', Session filter: '${branchMapping.sessionFilter}', Topic tree branch: '${branchMapping.topicTreeBranch}'`); - } - } -}); diff --git a/js/examples/subscription.js b/js/examples/subscription.js deleted file mode 100644 index 592dc284..00000000 --- a/js/examples/subscription.js +++ /dev/null @@ -1,58 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -var diffusion = require('diffusion'); - -// Connect to the server. Change these options to suit your own environment. -// Node.js will not accept self-signed certificates by default. If you have -// one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 -// before running this example. -diffusion.connect({ - host : 'diffusion.example.com', - port : 443, - secure : true -}).then(function(session) { - - // 1. Subscriptions are how sessions receive streams of data from the server. - - // When subscribing, a topic selector is used to select which topics to subscribe to. Topics do not need to exist - // at the time of subscription - the server dynamically resolves subscriptions as topics are added or removed. - - // Subscribe to the "foo" topic - session.select('foo'); - - // 2. Sessions may unsubscribe from any topic to stop receiving data - - // Unsubscribe from the "foo" topic. Sessions do not need to have previously been subscribed to the topics they are - // unsubscribing from. - session.unsubscribe('foo'); - - // 3. Subscriptions / Unsubscriptions can select multiple topics using Topic Selectors - - // Topic Selectors provide regex-like capabilities for subscribing to topics. These are resolved dynamically, much - // like subscribing to a single topic. - session.select('?foo/.*/[a-z]'); - - // 4. Register a value stream - var valueStream = session.addStream('baz', diffusion.datatypes.json()); - - // Receive update values - valueStream.on('value', function(topic, spec, newValue, oldValue) { - console.log('Got JSON update for topic: ' + topic, newValue.get()); - }); - - // Subscribe to a JSON topic - session.select('baz'); -}); diff --git a/js/examples/timeseries.js b/js/examples/timeseries.js deleted file mode 100644 index a682931e..00000000 --- a/js/examples/timeseries.js +++ /dev/null @@ -1,70 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018, 2021 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -var diffusion = require('diffusion'); - -var TopicSpecification = diffusion.topics.TopicSpecification; -var TopicType = diffusion.topics.TopicType; -var dataType = diffusion.datatypes.double(); - -// Connect to the server. Change these options to suit your own environment. -// Node.js does not accept self-signed certificates by default. If you have -// one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 -// before running this example. -diffusion.connect({ - host : 'diffusion.example.com', - port : 443, - secure : true, - principal : 'control', - credentials : 'password' -}).then(function(session) { - // 1. Create a time series topic specification with events - // of type double - var specification = new TopicSpecification(TopicType.TIME_SERIES, { - TIME_SERIES_EVENT_VALUE_TYPE : "double" - }); - - // 2. Create a time series topic - session.topics.add('topic/timeseries', specification).then(function() { - // 3. Register a value stream - session.addStream('topic/timeseries', dataType).on('value', function(topic, specification, newValue, oldValue) { - var value = newValue.toString(); - - if (newValue.isEditEvent === true) { - console.log("New value edited on topic: " + value); - } - else { - console.log("New value appended to topic: " + value); - } - }); - - // 4. Subscribe - session.select('topic/timeseries'); - - for (var i = 0; i < 10; i++) { - // 4. Append values 0-9 to the topic - session.timeseries.append("topic/timeseries", i, dataType); - } - - for (var i = 10; i < 20; i++) { - // 5. Append values 10 - 19 to the topic using a value constructor to specify the datatype - session.timeseries.append("topic/timeseries", i, Number); - } - // 5. Retrieve the last time series event and edit it - session.timeseries.rangeQuery().as(dataType).fromLast(1).selectFrom("topic/timeseries").then(function(result) { - session.timeseries.edit("topic/timeseries", result.events[0].sequence, 999, dataType); - }); - }); -}); diff --git a/js/examples/topicNotifications.js b/js/examples/topicNotifications.js deleted file mode 100644 index 569c9ffe..00000000 --- a/js/examples/topicNotifications.js +++ /dev/null @@ -1,70 +0,0 @@ - -var diffusion = require('diffusion'); - -// Connect to the server. Change these options to suit your own environment. -// Node.js will not accept self-signed certificates by default. If you have -// one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 -// before running this example. -diffusion.connect({ - host : 'diffusion.example.com', - port : 443, - secure : true, - principal: 'client', - credentials: 'password' -}).then(async function(session) { - var TopicNotificationType = session.notifications.TopicNotificationType; - - // A topic notification listener can be used to listen to topic notifications - var topicNotificationListener = { - // Called when the session receives a notification for a selected topic - onTopicNotification: (path, specification, type) => { - switch (type) { - case TopicNotificationType.ADDED: - console.log(`Topic ${path} has been added`); - break; - case TopicNotificationType.REMOVED: - console.log(`Topic ${path} has been removed`); - break; - case TopicNotificationType.SELECTED: - console.log(`Topic ${path} existed at the time of the selector registration.`); - break; - case TopicNotificationType.DESELECTED: - console.log(`Topic ${path} has been deselected`); - break; - } - }, - // Called when the session receives a notification for an immediate - // descendant of a selected topic - onDescendantNotification: (path, type) => { - switch (type) { - case TopicNotificationType.ADDED: - console.log(`Topic ${path} has been added as a descendant of a selected topic`); - break; - case TopicNotificationType.REMOVED: - console.log(`Topic ${path} has been removed as a descendant of a selected topic`); - break; - case TopicNotificationType.SELECTED: - console.log(`Topic ${path} existed as a descendant of a selected topic at the time of the selector registration.`); - break; - case TopicNotificationType.DESELECTED: - console.log(`Topic ${path} has been deselected as a descendant of a selected topic`); - break; - } - }, - // Called when the listener is closed - onClose: () => { - console.log('Topic notification listener has been closed'); - }, - // Called when an error has occurred - onError(error) { - console.log('An error has occurred'); - } - } - - // register the listener - session.notifications.addListener(topicNotificationListener).then((registration) => { - // select topics - // topic notifications will be emitted on all selected topics - registration.select('?foo/bar//'); - }); -}); diff --git a/js/examples/topicUpdate.js b/js/examples/topicUpdate.js deleted file mode 100644 index b7c70e98..00000000 --- a/js/examples/topicUpdate.js +++ /dev/null @@ -1,151 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -var diffusion = require('diffusion'); -var session; - -var stringDataType = diffusion.datatypes.string(); -var jsonDataType = diffusion.datatypes.json(); -var TopicType = diffusion.topics.TopicType; - - -function basicSetOperation() { - return Promise.all([ - session.topicUpdate.set('foo_topic', stringDataType, 'hello'), - session.topicUpdate.set('bar_topic', jsonDataType, {foo: 'foo', qux: 'qux'}) - ]); -} - -function setOperationWithValueConstraint() { - var constraint = diffusion.updateConstraints().value('hello', stringDataType); - return session.topicUpdate.set('foo_topic', stringDataType, 'world', {constraint}); -} - -function setOperationWithSessionLockConstraint() { - return session.lock("lock") - .then(function(sessionLock){ - var constraint = diffusion.updateConstraints().locked(sessionLock); - return session.topicUpdate.set('foo_topic', stringDataType, 'lorem ipsum', {constraint}); - }); -} - -function setOperationWithPartialJSONConstraint() { - return session.lock("lock") - .then(function(sessionLock){ - var constraint = diffusion.updateConstraints().jsonValue() - .with('/foo', 'foo', stringDataType) - .without('/bar'); - return session.topicUpdate.set('bar_topic', jsonDataType, {foo:'baz', bar:'bar'}, {constraint}); - }); -} - -function basicAddAndSetOperation() { - var topicSpec = new diffusion.topics.TopicSpecification(TopicType.STRING); - return session.topicUpdate.set('baz_topic', stringDataType, 'hello', {specification: topicSpec}); -} - -function addAndSetOperationWithNoTopicConstraint() { - var topicSpec = new diffusion.topics.TopicSpecification(TopicType.STRING); - var constraint = diffusion.updateConstraints().noTopic(); - return session.topicUpdate.set('qux_topic', stringDataType, 'hello', {specification: topicSpec, constraint}); -} - -function createUpdateStream() { - var stream = session.topicUpdate.newUpdateStreamBuilder() - .build('foo_topic', stringDataType); - stream.validate(); - stream.set('hello'); - var cachedValue = stream.get(); - return stream.set('world'); -} - -function createUpdateStreamWithValueConstraint() { - var constraint = diffusion.updateConstraints().value('world', stringDataType); - var stream = session.topicUpdate.newUpdateStreamBuilder() - .constraint(constraint) - .build('foo_topic', stringDataType); - stream.validate(); - stream.set('hello'); - var cachedValue = stream.get(); - return stream.set('world'); -} - - -function createUpdateStreamThatAddsTopic() { - var topicSpec = new diffusion.topics.TopicSpecification(TopicType.STRING); - var stream = session.topicUpdate.newUpdateStreamBuilder() - .specification(topicSpec) - .build('quux_topic', stringDataType); - // the first call to validate() or set() resolves in a TopicCreationResult - stream.validate().then((result) => { - if (result === diffusion.topicUpdate.TopicCreationResult.CREATED) { - console.log('A new topic has been created!'); - } else { - console.log('The topic already existed.'); - } - }); - stream.set('hello'); - var cachedValue = stream.get(); - return stream.set('world'); -} - -function createUpdateStreamThatAddsTopicWithNoTopicConstraint() { - var topicSpec = new diffusion.topics.TopicSpecification(TopicType.STRING); - var constraint = diffusion.updateConstraints().noTopic(); - var stream = session.topicUpdate.newUpdateStreamBuilder() - .specification(topicSpec) - .constraint(constraint) - .build('quuz_topic', stringDataType); - // the first call to validate() or set() resolves in a TopicCreationResult - stream.validate().then((result) => { - if (result === diffusion.topicUpdate.TopicCreationResult.CREATED) { - console.log('A new topic has been created!'); - } else { - console.log('The topic already existed.'); - } - }); - stream.set('hello'); - var cachedValue = stream.get(); - return stream.set('world'); -} - -// Connect to the server. Change these options to suit your own environment. -// Node.js does not accept self-signed certificates by default. If you have -// one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 -// before running this example. -diffusion.connect({ - host : 'diffusion.example.com', - port : 443, - secure : true, - principal : 'control', - credentials : 'password' -}) -.then(function(sess) { - session = sess; - return Promise.all([ - session.topics.add('foo_topic', TopicType.STRING), - session.topics.add('bar_topic', TopicType.JSON) - ]); -}) -.then(basicSetOperation) -.then(setOperationWithValueConstraint) -.then(setOperationWithSessionLockConstraint) -.then(setOperationWithPartialJSONConstraint) -.then(basicAddAndSetOperation) -.then(addAndSetOperationWithNoTopicConstraint) -.then(createUpdateStream) -.then(createUpdateStreamWithValueConstraint) -.then(createUpdateStreamThatAddsTopic) -.then(createUpdateStreamThatAddsTopicWithNoTopicConstraint); diff --git a/js/examples/topicViews.js b/js/examples/topicViews.js deleted file mode 100644 index 793e6965..00000000 --- a/js/examples/topicViews.js +++ /dev/null @@ -1,70 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2020 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the 'License'); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an 'AS IS' BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -const diffusion = require('diffusion'); -let session; - -async function createTopicView() { - // First create a topic called 'some/topic'. - await session.topics.add('some/topic', diffusion.topics.TopicType.STRING); - - // Now add a topic view. - // This will create a topic 'other/topic' that mirrors the value of 'some/topic' - await session.topicViews.createTopicView('example-view', 'map ?some/ to other/'); -} - -async function listTopicViews() { - // list all topic views - const views = await session.topicViews.listTopicViews(); - - // show the name and specification of each topic view - console.log('All Topic Views:'); - views.forEach((topicView) => { - console.log(`${topicView.name}: ${topicView.specification}`); - }); -} - -async function getTopicView() { - // get a topic view - const topicView = await session.topicViews.getTopicView('example-view'); - - // show the name and specification of the topic view - console.log('Topic View:'); - console.log(`${topicView.name}: ${topicView.specification}`); -} - -async function removeTopicViews() { - // remove a named topic view - await session.topicViews.removeTopicView('example-view'); -} - -// Connect to the server. Change these options to suit your own environment. -// Node.js does not accept self-signed certificates by default. If you have -// one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 -// before running this example. -diffusion.connect({ - host : 'diffusion.example.com', - port : 443, - secure : true, - principal : 'control', - credentials : 'password' -}) -.then(function(sess) { - session = sess; -}) -.then(createTopicView) -.then(listTopicViews) -.then(getTopicView) -.then(removeTopicViews); diff --git a/js/examples/updateJson.js b/js/examples/updateJson.js deleted file mode 100644 index f8b93732..00000000 --- a/js/examples/updateJson.js +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -var diffusion = require('diffusion'); - -// Connect to the server. Change these options to suit your own environment. -// Node.js will not accept self-signed certificates by default. If you have -// one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 -// before running this example. -diffusion.connect({ - host : 'diffusion.example.com', - port : 443, - secure : true, - principal : 'control', - credentials : 'password' -}).then(function(session) { - var jsonDataType = diffusion.datatypes.json(); - var TopicSpecification = diffusion.topics.TopicSpecification; - var TopicType = diffusion.topics.TopicType; - - // A session may update any existing topic. Update values must be of the same type as the topic being updated. - - // Add a topic first with topic specification - session.topics.add('foo', new TopicSpecification(TopicType.JSON)).then(function() { - // Update the topic with JSON content - return session.topicUpdate.set('foo', jsonDataType, jsonDataType.from({ "hello": "bar", "foo": "world" })); - }).then(function() { - // Update the topic again with JSON converted from a JSON string - return session.topicUpdate.set('foo', jsonDataType, jsonDataType.fromJsonString("{ \"hello\": \"foo\", \"foo\": \"hello\" }")); - }).then(function() { - // Update the topic again with a standard JavaScript JSON object - return session.topicUpdate.set('foo', jsonDataType, { hello: "world", foo: "bar" }); - }); -}); diff --git a/js/examples/updateRecordContent.js b/js/examples/updateRecordContent.js deleted file mode 100644 index ee3e85f0..00000000 --- a/js/examples/updateRecordContent.js +++ /dev/null @@ -1,95 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -var diffusion = require('diffusion'); - -// Connect to the server. Change these options to suit your own environment. -// Node.js will not accept self-signed certificates by default. If you have -// one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 -// before running this example. -diffusion.connect({ - host : 'diffusion.example.com', - port : 443, - secure : true, - principal : 'control', - credentials : 'password' -}).then(function(session) { - // Record values allow topics to contain data that conforms to a particular schema. Producing a schema allows new - // values to be easily constructed. - - var TopicSpecification = diffusion.topics.TopicSpecification; - var TopicType = diffusion.topics.TopicType; - - var RecordV2DataType = diffusion.datatypes.recordv2(); - - // 1. Create a new schema using the SchemaBuilder API - var schema = RecordV2DataType.schemaBuilder() - .record("Row1").decimal("Field1", 3).integer("Field2") - .record("Row2").string("Field3") - .build(); - - // 2. To create a RecordV2 topic, use a TopicSpecification with the defined schema - var specification = new TopicSpecification(TopicType.RECORD_V2, { - SCHEMA : schema.asJSONString() - }); - - session.topics.add('topic/record', specification).then(function() { - // 3. Produce RecordV2 values from the schema by creating a mutable model - var model = schema.createMutableModel(); - - model.set("Row1.Field1", 123.456); - model.set("Row1.Field2", 789); - model.set("Row2.Field3", "Hello world"); - - var update1 = model.asValue(); - - session.topicUpdate.set('topic/record', RecordV2DataType, update1); - - // 4. Subsequent updates can be produced from the same model - - model.set("Row2.Field3", "Hello everybody"); - - var update2 = model.asValue(); - - session.topicUpdate.set('topic/record', RecordV2DataType, update2); - }); - - - // RecordV2 values can be easily consumed, too - session - .addStream('topic/record', RecordV2DataType) - .on('value', function(topic, specification, newValue, oldValue) { - // 5. The schema can be used to produce a model that allows key-based lookup of records and fields - var model = newValue.asModel(schema); - - var f1 = model.get("Row1.Field1"); - var f2 = model.get("Row1.Field2"); - var f3 = model.get("Row2.Field3"); - - console.log( - "Field1: " + f1 + - "Field2: " + f2 + - "Field3: " + f3); - - // 6. If the schema is not known, it is possible to iterate across the received records and fields - newValue.asRecords().forEach(function(record) { - record.forEach(function(field) { - console.log("Field value: " + field); - }); - }); - }); - - session.select('topic/record'); -}); diff --git a/js/examples/updateSingleValue.js b/js/examples/updateSingleValue.js deleted file mode 100644 index c34fa22b..00000000 --- a/js/examples/updateSingleValue.js +++ /dev/null @@ -1,52 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2018 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -var diffusion = require('diffusion'); - -// Connect to the server. Change these options to suit your own environment. -// Node.js will not accept self-signed certificates by default. If you have -// one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 -// before running this example. -diffusion.connect({ - host : 'diffusion.example.com', - port : 443, - secure : true, - principal : 'control', - credentials : 'password' -}).then(function(session) { - var TopicSpecification = diffusion.topics.TopicSpecification; - var TopicType = diffusion.topics.TopicType; - - var stringDataType = diffusion.datatypes.string(); - var doubleDataType = diffusion.datatypes.double(); - - // A session may update any existing topic. Update values must be of the same type as the topic being updated. - - // Add a topic first with a string type - session.topics.add('foo', new TopicSpecification(TopicType.STRING)).then(function() { - // Update the topic - return session.topicUpdate.set('foo', stringDataType, 'hello'); - }).then(function() { - // Update the topic again - return session.topicUpdate.set('foo', stringDataType, 'world'); - }); - - // Add a topic with a double type - session.topics.add('bar', new TopicSpecification(TopicType.DOUBLE)).then(function() { - return session.topicUpdate.set('bar', doubleDataType, 123); - }).then(function() { - return session.topicUpdate.set('bar', doubleDataType, 456.789); - }); -}); diff --git a/js/getting_started/README.md b/js/getting_started/README.md deleted file mode 100644 index 93eceab9..00000000 --- a/js/getting_started/README.md +++ /dev/null @@ -1,106 +0,0 @@ -# JavaScript simple clients - -## Subscribing client - -The file `index.html` is a browser client that connects to a Diffusion server or Diffusion Cloud service and subscribes to a topic. When the topic is updated, the web page displays the updated value of the topic. - -#### Using this client - -Before you can use this client with any Diffusion service, you will need to edit the location of the Diffusion client library: - -1. Change the path in the script tag from `path_to_library` to point at your Diffusion client library. - -To use this client with a Diffusion Cloud service, make the following edits: - -1. Change the URL in the `diffusion.connect` method to that of your Diffusion Cloud service. - - diffusion.connect({ - host : 'service_url', - principal : 'client', - credentials : 'password' - }) - - -To use this client with a Diffusion server, make the following edits: - -1. Change the URL in the `diffusion.connect` method to that of your Diffusion server. - -2. You might also have to add the port parameter to specify the port on which the Diffusion server receives client connections. If no port is specified, - the JavaScript client assumes port 80 for standard connections and port 443 for secure connections. - - diffusion.connect({ - host : 'diffusion_url', - port : port, - principal : 'client', - credentials : 'password' - }) - - - - -Open `index.html` in a browser, it makes a connection to your Diffusion Cloud service or Diffusion server and subscribes to the topic `foo/counter`. - -#### Testing this client - -The client subscribes to the topic `foo/counter`. The web page is updated every time the data on the `foo/counter` topic is updated. -To see the client working you must publish updates to `foo\counter`. You can update the data on `foo/counter` by using one of the following tools: - -* The publishing client example in this GitHub project -* A test client - + For Diffusion Cloud, a test client is provided on the Dashboard - + For Diffusion, test clients are provided in the `tools` directory of your installation - -#### Further information - -[Diffusion user manual](https://docs.pushtechnology.com/docs/6.2/) - -[Diffusion Cloud user manual](https://docs.pushtechnology.com/cloud/latest/) - - -## Publishing client - -The file `publishing.js` is a Node client that connects to Diffusion Cloud or your Diffusion server, creates a topic `foo/counter`, and publishes an incrementing count to the topic. - -#### Prerequisites - -1. Install NodeJS and NPM on the system that hosts this client. - -2. Install the Diffusion JS library on your system: - - npm install diffusion - -#### Using this client -To use this client with a Diffusion Cloud service or Diffusion server, make the following edits: - -1. Change the URL in the `diffusion.connect` method to that of your Diffusion Cloud service or Diffusion server. - - diffusion.connect({ - host : 'url', - principal : 'control', - credentials : 'password' - }) - -2. (Diffusion only) If required, add a port parameter to the connect method to specify the port on which the Diffusion server receives client connections. If no port is specified, - the JavaScript client assumes port 80 for standard connections and port 443 for secure connections. - -3. Run `publishing.js` from the command line using node: - - node publishing.js - -#### Testing this client - -The client creates the topic `foo/counter` and publishes a value to it every second. - -To see the client working you must subscribe to the topic to receive the updates. You can subscribe to `foo/counter` by using one of the following tools: - -* The subscribing client example in this GitHub project -* A test client - * For Diffusion Cloud, a test client is provided on the Dashboard - * For Diffusion, test clients are provided in the `tools` directory of your installation - -#### Further information - -[Diffusion user manual](https://docs.pushtechnology.com/docs/6.2/) - -[Diffusion Cloud user manual](https://docs.pushtechnology.com/cloud/latest/) - diff --git a/js/getting_started/index-modular.html b/js/getting_started/index-modular.html deleted file mode 100644 index 94f8e372..00000000 --- a/js/getting_started/index-modular.html +++ /dev/null @@ -1,59 +0,0 @@ - - - JavaScript example - - - -

The value of foo/counter is:

- - - diff --git a/js/getting_started/index.html b/js/getting_started/index.html deleted file mode 100644 index 56f0f620..00000000 --- a/js/getting_started/index.html +++ /dev/null @@ -1,34 +0,0 @@ - - - JavaScript example - - - - -

The value of foo/counter is:

- - - diff --git a/js/getting_started/publishing.js b/js/getting_started/publishing.js deleted file mode 100644 index a4dca474..00000000 --- a/js/getting_started/publishing.js +++ /dev/null @@ -1,36 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2014, 2015 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -var diffusion = require('diffusion'); - -diffusion.connect({ - host : 'hostname', - principal : 'control', - credentials : 'password' -}).then(function(session) { - console.log('Connected!'); - - // Create a topic that contains Double values - var doubleSpec = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.DOUBLE); - - session.topics.add('foo/counter', doubleSpec); - - // Start updating the topic every second - var count = 0; - - setInterval(function() { - session.topicUpdate.set('foo/counter', diffusion.datatypes.double(), count++); - }, 1000); -}); diff --git a/js/messaging/send-to-path.js b/js/messaging/send-to-path.js new file mode 100644 index 00000000..3dfa8ab5 --- /dev/null +++ b/js/messaging/send-to-path.js @@ -0,0 +1,83 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester, promiseWithResolvers } = require('../../../test/util'); +/// end::log + +export async function messagingSendToPath() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Received message: Hello'], + ['Received response: Goodbye'], + ['Message handler was closed.'], + ]); + + const closedPromise = promiseWithResolvers(); + /// end::log + /// tag::messaging_send_to_path[] + // Connect to the server. + const session1 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const handler = { + onRequest: (request, context, responder) => { + console.log(`Received message: ${request}`); + /// tag::log + check.log(`Received message: ${request}`); + /// end::log + responder.respond('Goodbye'); + }, + onError: (error) => { + console.error('An error occurred.', error); + }, + onClose: () => { + console.log('Message handler was closed.'); + /// tag::log + check.log('Message handler was closed.'); + closedPromise.resolve(); + /// end::log + } + }; + + await session1.messages.addRequestHandler('my/message/path', handler); + + // Connect to the server. + const session2 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const response = await session2.messages.sendRequest('my/message/path', 'Hello'); + console.log(`Received response: ${response}`); + /// tag::log + check.log(`Received response: ${response}`); + /// end::log + + await session1.closeSession(); + await session2.closeSession(); + /// end::messaging_send_to_path[] + /// tag::log + await closedPromise.promise; + await check.done(); + /// end::log +} diff --git a/js/messaging/send-to-session-filter.js b/js/messaging/send-to-session-filter.js new file mode 100644 index 00000000..d8d0a3b0 --- /dev/null +++ b/js/messaging/send-to-session-filter.js @@ -0,0 +1,119 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester, promiseWithResolvers } = require('../../../test/util'); +/// end::log + +export async function messagingSendToSessionFilter() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Received message: Hello'], + ['Received response: Goodbye'], + ]); + + const responsePromise = promiseWithResolvers(); + /// end::log + /// tag::messaging_send_to_session_filter[] + // Connect to the server. + const session1 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const stream1 = { + onRequest: (path, request, responder) => { + console.log(`Received message: ${request}`); + /// tag::log + check.log(`Received message: ${request}`); + /// end::log + responder.respond('Goodbye'); + }, + onError: (error) => { + console.error('An error occurred.', error); + }, + onClose: () => { + console.log('Message handler was closed.'); + } + }; + + session1.messages.setRequestStream('my/message/path', stream1); + + // Connect to the server. + const session2 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'control', + credentials: 'password' + }); + + const stream2 = { + onRequest: (path, request, responder) => { + console.log(`Received message: ${request}`); + responder.respond('I\'m not supposed to receive a message.'); + /// tag::log + check.log('I\'m not supposed to receive a message.'); + /// end::log + }, + onError: (error) => { + console.error('An error occurred.', error); + }, + onClose: () => { + console.log('Message handler was closed.'); + } + }; + + session2.messages.setRequestStream('my/message/path',stream2); + + // Connect to the server. + const session3 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'control', + credentials: 'password' + }); + + await session3.messages.sendRequestToFilter( + '$Principal EQ "admin"', + 'my/message/path', + 'Hello', + { + onResponse: (sessionId, response)=> { + console.log(`Received response: ${response}`); + /// tag::log + check.log(`Received response: ${response}`); + responsePromise.resolve(); + /// end::log + }, + onResponseError: (sessionId, error) => { + console.error('Received an error response', error); + } + } + ); + /// tag::log + await responsePromise.promise; + /// end::log + + await session1.closeSession(); + await session2.closeSession(); + await session3.closeSession(); + /// end::messaging_send_to_session_filter[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/messaging/send-to-session-id.js b/js/messaging/send-to-session-id.js new file mode 100644 index 00000000..2209d9d1 --- /dev/null +++ b/js/messaging/send-to-session-id.js @@ -0,0 +1,107 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester } = require('../../../test/util'); +/// end::log + +export async function messagingSendToSessionId() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Received message: Hello'], + ['Received response: Goodbye'], + ]); + /// end::log + /// tag::messaging_send_to_session_id[] + // Connect to the server. + const session1 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const stream1 = { + onRequest: (path, request, responder) => { + console.log(`Received message: ${request}`); + /// tag::log + check.log(`Received message: ${request}`); + /// end::log + responder.respond('Goodbye'); + }, + onError: (error) => { + console.error('An error occurred.', error); + }, + onClose: () => { + console.log('Message handler was closed.'); + } + }; + + session1.messages.setRequestStream('my/message/path', stream1); + + // Connect to the server. + const session2 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const stream2 = { + onRequest: (path, request, responder) => { + console.log(`Received message: ${request}`); + responder.respond('I\'m not supposed to receive a message.'); + /// tag::log + check.log('I\'m not supposed to receive a message.'); + /// end::log + }, + onError: (error) => { + console.error('An error occurred.', error); + }, + onClose: () => { + console.log('Message handler was closed.'); + } + }; + + session2.messages.setRequestStream('my/message/path',stream2); + + // Connect to the server. + const session3 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const response = await session3.messages.sendRequest( + 'my/message/path', + 'Hello', + session1.sessionId, + diffusion.datatypes.string() + ); + console.log(`Received response: ${response}`); + /// tag::log + check.log(`Received response: ${response}`); + /// end::log + + await session1.closeSession(); + await session2.closeSession(); + await session3.closeSession(); + /// end::messaging_send_to_session_id[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/monitoring/missing-topic-notifications.js b/js/monitoring/missing-topic-notifications.js new file mode 100644 index 00000000..8475c0d2 --- /dev/null +++ b/js/monitoring/missing-topic-notifications.js @@ -0,0 +1,90 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester, promiseWithResolvers } = require('../../../test/util'); +/// end::log + +export async function monitoringMissingTopicNotifications() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ 'missing topic notification my/topic/path/does/not/exist/yet' ], + [ 'Subscribed to my/topic/path/does/not/exist/yet' ], + ]); + const promise = promiseWithResolvers(); + /// end::log + /// tag::monitoring_missing_topic_notifications[] + // Connect to the server. + const session1 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const missingTopicHandler = { + onMissingTopic: async (notification) => { + /// tag::log + check.log(`missing topic notification ${notification.path}`); + /// end::log + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.STRING); + await session1.topics.add(notification.path, specification); + }, + onRegister: (path, deregister) => {}, + onClose: (path) => {}, + onError: (path, error) => {} + }; + await session1.topics.addMissingTopicHandler('my/topic/path', missingTopicHandler); + + // Connect to the server. + const session2 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'client', + credentials: 'password' + }); + + const valueStream = session2.addStream('?my/topic/path//', diffusion.datatypes.string()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + promise.resolve(); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${oldValue.get()} to ${newValue.get()}`); + } + }); + + await session2.select('my/topic/path/does/not/exist/yet'); + + // wait until topic has been created + /// tag::log + await promise.promise; + /// end::log + + await session1.closeSession(); + await session2.closeSession(); + /// end::monitoring_missing_topic_notifications[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/monitoring/session-event-listener.js b/js/monitoring/session-event-listener.js new file mode 100644 index 00000000..acf7a04f --- /dev/null +++ b/js/monitoring/session-event-listener.js @@ -0,0 +1,78 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester, promiseWithResolvers } = require('../../../test/util'); +/// end::log + +export async function monitoringSessionEventListener() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ 'Session open' ]]); + const sessionOpenPromise = promiseWithResolvers(); + /// end::log + /// tag::monitoring_session_event_listener[] + const session1 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const session2 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'client', + credentials: 'password' + }); + + const sessionEventStream = { + onSessionEvent: (event) => { + if (event.isOpenEvent()) { + console.log(`New session: id=${event.sessionId}`); + /// tag::log + check.log(`Session open`); + sessionOpenPromise.resolve(); + /// end::log + } else if (event.type === diffusion.clients.SessionEventStreamEventType.STATE) { + console.log(`Session state changed: id=${event.sessionId}, state=${event.state}`); + } else { + console.log( + `Session properties changed: id=${event.sessionId}, properties=${JSON.stringify(event.changedProperties)}` + ); + } + }, + onClose: () => { + console.log('Stream closed'); + }, + onError: (err) => { + console.error(`An error occured: ${err}`); + } + }; + await session1.clients.addSessionEventListener(sessionEventStream, { + properties: new Set(diffusion.clients.PropertyKeys.ALL_FIXED_PROPERTIES), + filter: `$Principal NE 'admin'` + }); + + /// tag::log + await sessionOpenPromise.promise; + /// end::log + await session2.closeSession(); + await session1.closeSession(); + /// end::monitoring_session_event_listener[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/monitoring/topic-notifications.js b/js/monitoring/topic-notifications.js new file mode 100644 index 00000000..2b56822f --- /dev/null +++ b/js/monitoring/topic-notifications.js @@ -0,0 +1,110 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester } = require('../../../test/util'); +/// end::log + +export async function monitoringTopicNotifications() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Topic my/topic/path has been added.', + 'Descendant Topic my/topic/path/descendant has been added.' + ]]); + /// end::log + /// tag::monitoring_topic_notifications[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const topicNotificationListener = { + onTopicNotification: (path, specification, type) => { + switch (type) { + case diffusion.TopicNotificationType.ADDED: + console.log(`Topic ${path} has been added.`); + /// tag::log + check.log(`Topic ${path} has been added.`); + /// end::log + break; + case diffusion.TopicNotificationType.SELECTED: + console.log(`Topic ${path} has been selected.`); + break; + case diffusion.TopicNotificationType.DESELECTED: + console.log(`Topic ${path} has been deselected.`); + break; + case diffusion.TopicNotificationType.REMOVED: + console.log(`Topic ${path} has been removed.`); + break; + } + }, + onDescendantNotification: (path, type) => { + switch (type) { + case diffusion.TopicNotificationType.ADDED: + console.log(`Descendant Topic ${path} has been added.`); + /// tag::log + check.log(`Descendant Topic ${path} has been added.`); + /// end::log + break; + case diffusion.TopicNotificationType.SELECTED: + console.log(`Descendant Topic ${path} has been selected.`); + break; + case diffusion.TopicNotificationType.DESELECTED: + console.log(`Descendant Topic ${path} has been deselected.`); + break; + case diffusion.TopicNotificationType.REMOVED: + console.log(`Descendant Topic ${path} has been removed.`); + break; + } + }, + onClose: () => {}, + onError: (error) => {} + }; + const registration = await session.notifications.addListener(topicNotificationListener); + await registration.select('>my/topic/path'); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.STRING); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.string(), + 'Good morning', + { specification: specification } + ); + await session.topicUpdate.set( + 'my/topic/path/descendant', + diffusion.datatypes.string(), + 'Good afternoon', + { specification: specification } + ); + await session.topicUpdate.set( + 'other/path/of/the/topic/tree', + diffusion.datatypes.string(), + 'This will not generate a notification', + { specification: specification } + ); + + await session.topics.remove('my/topic/path/descendant'); + + await session.unsubscribe('?my/topic/path//'); + + await session.closeSession(); + /// end::monitoring_topic_notifications[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/package.json b/js/package.json deleted file mode 100644 index 306f61f0..00000000 --- a/js/package.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "diffusion-examples", - "version": "6.9.8", - "description": "Examples for using the Diffusion JavaScript client", - "main": "index.js", - "directories": { - "example": "examples" - }, - "license": "Apache-2.0", - "dependencies": { - "@types/long": "4.0.1", - "@types/node": "16.7.10", - "@typescript-eslint/eslint-plugin": "4.31.1", - "@typescript-eslint/parser": "4.31.1", - "eslint": "7.32.0", - "eslint-plugin-deprecation": "1.2.1", - "long": "4.0.0", - "typescript": "4.4.3" - }, - "scripts": { - "start": "npm run check && npm run compile", - "check": "eslint manual/**/*.ts", - "compile": "tsc" - } -} diff --git a/js/ping/ping-server.js b/js/ping/ping-server.js new file mode 100644 index 00000000..dce3020f --- /dev/null +++ b/js/ping/ping-server.js @@ -0,0 +1,33 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function pingExample() { + /// tag::ping_server[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + await session.pingServer(); + console.log('Received Ping response.'); + + await session.closeSession(); + /// end::ping_server[] +} diff --git a/js/pubsub/constraint/add-topic-and-set-and-operator.js b/js/pubsub/constraint/add-topic-and-set-and-operator.js new file mode 100644 index 00000000..4b9e632e --- /dev/null +++ b/js/pubsub/constraint/add-topic-and-set-and-operator.js @@ -0,0 +1,77 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue } = require('../../../../test/util'); +/// end::log + +export async function addTopicAndSetAndConstraintExample() { + /// tag::pub_sub_publish_with_constraint_add_and_set_topic_and[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + try { + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData = diffusion.datatypes.json().from({ diffusion: 'data' }); + + const topicCreationResult = await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + + if (topicCreationResult === diffusion.topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult).toBe(diffusion.topicUpdate.TopicCreationResult.CREATED); + /// end::log + + const updateConstraintA = diffusion.updateConstraints() + .jsonValue() + .without('/bar'); + const updateConstraintB = diffusion.updateConstraints() + .jsonValue() + .with('/diffusion', 'data', diffusion.topicUpdate.UpdateConstraintOperator.IS) + + const updateConstraint = updateConstraintA.and(updateConstraintB); + const newJsonData = diffusion.datatypes.json().from({ diffusion: 'baz' }); + + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + newJsonData, + { constraint: updateConstraint } + ); + } catch (err) { + console.error('Topic value could not be set.', err); + throw err; + } + + await session.closeSession(); + /// end::pub_sub_publish_with_constraint_add_and_set_topic_and[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path', { diffusion: 'baz' }); + /// end::log +} diff --git a/js/pubsub/constraint/add-topic-and-set-json-value-with.js b/js/pubsub/constraint/add-topic-and-set-json-value-with.js new file mode 100644 index 00000000..ba094ee9 --- /dev/null +++ b/js/pubsub/constraint/add-topic-and-set-json-value-with.js @@ -0,0 +1,73 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue } = require('../../../../test/util'); +/// end::log + +export async function addTopicAndSetJsonValueWithConstraintExample() { + /// tag::pub_sub_publish_with_constraint_add_and_set_topic_json_value_with[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + try { + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + + const jsonData = diffusion.datatypes.json().from({ diffusion: 'bar' }); + const topicCreationResult = await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + + if (topicCreationResult === diffusion.topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + throw new Error('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult).toBe(diffusion.topicUpdate.TopicCreationResult.CREATED); + /// end::log + + const updateConstraint = diffusion.updateConstraints() + .jsonValue().with('/diffusion', 'bar', diffusion.topicUpdate.UpdateConstraintOperator.IS); + + const jsonData2 = diffusion.datatypes.json().from({ diffusion: 'baz' }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData2, + { constraint: updateConstraint } + ); + + console.log('Topic value has been set.'); + } catch (err) { + console.error('Topic value could not be set.', err); + throw err; + } + + await session.closeSession(); + /// end::pub_sub_publish_with_constraint_add_and_set_topic_json_value_with[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path', { diffusion: 'baz' }); + /// end::log +} diff --git a/js/pubsub/constraint/add-topic-and-set-json-value-without.js b/js/pubsub/constraint/add-topic-and-set-json-value-without.js new file mode 100644 index 00000000..a6ca4da3 --- /dev/null +++ b/js/pubsub/constraint/add-topic-and-set-json-value-without.js @@ -0,0 +1,73 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue } = require('../../../../test/util'); +/// end::log + +export async function addTopicAndSetJsonValueWithoutConstraintExample() { + /// tag::pub_sub_publish_with_constraint_add_and_set_topic_json_value_without[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + try { + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + + const jsonData = diffusion.datatypes.json().from({ diffusion: 'data' }); + const topicCreationResult = await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + + if (topicCreationResult === diffusion.topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + throw new Error('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult).toBe(diffusion.topicUpdate.TopicCreationResult.CREATED); + /// end::log + + const updateConstraint = diffusion.updateConstraints() + .jsonValue().without('/bar'); + + const jsonData2 = diffusion.datatypes.json().from({ diffusion: 'baz' }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData2, + { constraint: updateConstraint } + ); + + console.log('Topic value has been set.'); + } catch (err) { + console.error('Topic value could not be set.', err); + throw err; + } + + await session.closeSession(); + /// end::pub_sub_publish_with_constraint_add_and_set_topic_json_value_without[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path', { diffusion: 'baz' }); + /// end::log +} diff --git a/js/pubsub/constraint/add-topic-and-set-no-topic.js b/js/pubsub/constraint/add-topic-and-set-no-topic.js new file mode 100644 index 00000000..0743812f --- /dev/null +++ b/js/pubsub/constraint/add-topic-and-set-no-topic.js @@ -0,0 +1,63 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue } = require('../../../../test/util'); +/// end::log + +export async function addTopicAndSetNoTopicConstraintExample() { + /// tag::pub_sub_publish_with_constraint_add_and_set_topic_no_topic[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + try { + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const updateConstraint = diffusion.updateConstraints().noTopic(); + + const jsonData = diffusion.datatypes.json().from({ diffusion: 'data' }); + const topicCreationResult = await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { specification: specification, constraint: updateConstraint } + ); + + if (topicCreationResult === diffusion.topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult).toBe(diffusion.topicUpdate.TopicCreationResult.CREATED); + /// end::log + + console.log('Topic value has been set.'); + } catch (err) { + console.error('Topic value could not be set.', err); + throw err; + } + + await session.closeSession(); + /// end::pub_sub_publish_with_constraint_add_and_set_topic_no_topic[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path', { diffusion: 'data' }); + /// end::log +} diff --git a/js/pubsub/constraint/add-topic-and-set-session-lock.js b/js/pubsub/constraint/add-topic-and-set-session-lock.js new file mode 100644 index 00000000..48cdb4e2 --- /dev/null +++ b/js/pubsub/constraint/add-topic-and-set-session-lock.js @@ -0,0 +1,64 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue } = require('../../../../test/util'); +/// end::log + +export async function addTopicAndSetSessionLockConstraintExample() { + /// tag::pub_sub_publish_with_constraint_add_and_set_topic_session_lock[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + try { + const lock = await session.lock('My Session Lock'); + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const updateConstraint = diffusion.updateConstraints().locked(lock); + + const jsonData = diffusion.datatypes.json().from({ diffusion: 'data' }); + const topicCreationResult = await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { specification: specification, constraint: updateConstraint } + ); + + if (topicCreationResult === diffusion.topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult).toBe(diffusion.topicUpdate.TopicCreationResult.CREATED); + /// end::log + + console.log('Topic value has been set.'); + } catch (err) { + console.error('Topic value could not be set.', err); + throw err; + } + + await session.closeSession(); + /// end::pub_sub_publish_with_constraint_add_and_set_topic_session_lock[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path', { diffusion: 'data' }); + /// end::log +} diff --git a/js/pubsub/constraint/add-topic-and-set-value.js b/js/pubsub/constraint/add-topic-and-set-value.js new file mode 100644 index 00000000..47f92bcc --- /dev/null +++ b/js/pubsub/constraint/add-topic-and-set-value.js @@ -0,0 +1,71 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue } = require('../../../../test/util'); +/// end::log + +export async function addTopicAndSetValueConstraintExample() { + /// tag::pub_sub_publish_with_constraint_add_and_set_topic_value[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + try { + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + + const jsonData = diffusion.datatypes.json().from({ diffusion: 'data' }); + const topicCreationResult = await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + + if (topicCreationResult === diffusion.topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + throw new Error('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult).toBe(diffusion.topicUpdate.TopicCreationResult.CREATED); + /// end::log + + const updateConstraint = diffusion.updateConstraints().value(jsonData); + const jsonData2 = diffusion.datatypes.json().from({ diffusion: 'data2' }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData2, + { constraint: updateConstraint } + ); + + console.log('Topic value has been set.'); + } catch (err) { + console.error('Topic value could not be set.', err); + throw err; + } + + await session.closeSession(); + /// end::pub_sub_publish_with_constraint_add_and_set_topic_value[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path', { diffusion: 'data2' }); + /// end::log +} diff --git a/js/pubsub/constraint/set-topic-json-value-with.js b/js/pubsub/constraint/set-topic-json-value-with.js new file mode 100644 index 00000000..d36eb9c2 --- /dev/null +++ b/js/pubsub/constraint/set-topic-json-value-with.js @@ -0,0 +1,61 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue } = require('../../../../test/util'); +/// end::log + +export async function setTopicJsonValueWithConstraintExample() { + /// tag::pub_sub_publish_with_constraint_set_topic_json_value_with[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + try { + const jsonData = diffusion.datatypes.json().from({ diffusion: 'bar' }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData + ); + + const updateConstraint = diffusion.updateConstraints() + .jsonValue().with('/diffusion', 'bar', diffusion.topicUpdate.UpdateConstraintOperator.IS); + + const jsonData2 = diffusion.datatypes.json().from({ diffusion: 'baz' }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData2, + { constraint: updateConstraint } + ); + + console.log('Topic value has been set.'); + } catch (err) { + console.error('Topic value could not be set.', err); + throw err; + } + + await session.closeSession(); + /// end::pub_sub_publish_with_constraint_set_topic_json_value_with[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path', { diffusion: 'baz' }); + /// end::log +} diff --git a/js/pubsub/constraint/set-topic-json-value-without.js b/js/pubsub/constraint/set-topic-json-value-without.js new file mode 100644 index 00000000..45b1a7db --- /dev/null +++ b/js/pubsub/constraint/set-topic-json-value-without.js @@ -0,0 +1,61 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue } = require('../../../../test/util'); +/// end::log + +export async function setTopicJsonValueWithoutConstraintExample() { + /// tag::pub_sub_publish_with_constraint_set_topic_json_value_without[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + try { + const jsonData = diffusion.datatypes.json().from({ diffusion: null }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData + ); + + const updateConstraint = diffusion.updateConstraints() + .jsonValue().without('/bar'); + + const jsonData2 = diffusion.datatypes.json().from({ diffusion: 'baz' }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData2, + { constraint: updateConstraint } + ); + + console.log('Topic value has been set.'); + } catch (err) { + console.error('Topic value could not be set.', err); + throw err; + } + + await session.closeSession(); + /// end::pub_sub_publish_with_constraint_set_topic_json_value_without[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path', { diffusion: 'baz' }); + /// end::log +} diff --git a/js/pubsub/constraint/set-topic-no-value.js b/js/pubsub/constraint/set-topic-no-value.js new file mode 100644 index 00000000..a69fe1ab --- /dev/null +++ b/js/pubsub/constraint/set-topic-no-value.js @@ -0,0 +1,58 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue, expectTopicExists } = require('../../../../test/util'); +/// end::log + +export async function setTopicNoValueConstraintExample() { + /// tag::pub_sub_publish_with_constraint_set_topic_no_value[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + try { + await session.topics.add('my/topic/path', diffusion.topics.TopicType.JSON); + + const jsonData = diffusion.datatypes.json().from({ + diffusion: ['data', 'more data'] + }); + + const updateConstraint = diffusion.updateConstraints().noValue(); + + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { constraint: updateConstraint } + ); + + console.log('Topic value has been set.'); + } catch (err) { + console.error('Topic value could not be set.', err); + throw err; + } + + await session.closeSession(); + /// end::pub_sub_publish_with_constraint_set_topic_no_value[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path', { diffusion: ['data', 'more data'] }); + /// end::log +} diff --git a/js/pubsub/constraint/set-topic-session-lock.js b/js/pubsub/constraint/set-topic-session-lock.js new file mode 100644 index 00000000..41874602 --- /dev/null +++ b/js/pubsub/constraint/set-topic-session-lock.js @@ -0,0 +1,54 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue } = require('../../../../test/util'); +/// end::log + +export async function setTopicSessionLockConstraintExample() { + /// tag::pub_sub_publish_with_constraint_set_topic_session_lock[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + try { + const lock = await session.lock('My Session Lock'); + const updateConstraint = diffusion.updateConstraints().locked(lock); + + const jsonData = diffusion.datatypes.json().from({ diffusion: ['data', 'more data'] }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { constraint: updateConstraint } + ); + + console.log('Topic value has been set.'); + } catch (err) { + console.error('Topic value could not be set.', err); + throw err; + } + + await session.closeSession(); + /// end::pub_sub_publish_with_constraint_set_topic_session_lock[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path', { diffusion: ['data', 'more data'] }); + /// end::log +} diff --git a/js/pubsub/constraint/set-topic-value.js b/js/pubsub/constraint/set-topic-value.js new file mode 100644 index 00000000..01f6505a --- /dev/null +++ b/js/pubsub/constraint/set-topic-value.js @@ -0,0 +1,59 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue } = require('../../../../test/util'); +/// end::log + +export async function setTopicValueConstraintExample() { + /// tag::pub_sub_publish_with_constraint_set_topic_value[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + try { + const jsonData = diffusion.datatypes.json().from({ diffusion: ['data', 'more data'] }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData + ); + + const updateConstraint = diffusion.updateConstraints().value(jsonData); + const jsonData2 = diffusion.datatypes.json().from({ diffusion: ['data', 'more data', 'yet more data'] }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData2, + { constraint: updateConstraint } + ); + + console.log('Topic value has been set.'); + } catch (err) { + console.error('Topic value could not be set.', err); + throw err; + } + + await session.closeSession(); + /// end::pub_sub_publish_with_constraint_set_topic_value[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path', { diffusion: ['data', 'more data', 'yet more data'] }); + /// end::log +} diff --git a/js/pubsub/fetch/fetch-topics-properties.js b/js/pubsub/fetch/fetch-topics-properties.js new file mode 100644 index 00000000..dc892676 --- /dev/null +++ b/js/pubsub/fetch/fetch-topics-properties.js @@ -0,0 +1,114 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester } = require('../../../../test/util'); +/// end::log + +export async function pubSubFetchTopicProperties() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ + 'my/topic/path/with/properties/0 DONT_RETAIN_VALUE: true', + 'my/topic/path/with/properties/0 PERSISTENT: false', + 'my/topic/path/with/properties/0 PUBLISH_VALUES_ONLY: true', + 'my/topic/path/with/properties/1 DONT_RETAIN_VALUE: true', + 'my/topic/path/with/properties/1 PERSISTENT: false', + 'my/topic/path/with/properties/1 PUBLISH_VALUES_ONLY: true', + 'my/topic/path/with/properties/2 DONT_RETAIN_VALUE: true', + 'my/topic/path/with/properties/2 PERSISTENT: false', + 'my/topic/path/with/properties/2 PUBLISH_VALUES_ONLY: true', + 'my/topic/path/with/properties/3 DONT_RETAIN_VALUE: true', + 'my/topic/path/with/properties/3 PERSISTENT: false', + 'my/topic/path/with/properties/3 PUBLISH_VALUES_ONLY: true', + 'my/topic/path/with/properties/4 DONT_RETAIN_VALUE: true', + 'my/topic/path/with/properties/4 PERSISTENT: false', + 'my/topic/path/with/properties/4 PUBLISH_VALUES_ONLY: true' + ] + ]); + /// end::log + /// tag::pub_sub_fetch_topic_properties[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + + const specification1 = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON, { + 'DONT_RETAIN_VALUE': 'true', + 'PERSISTENT': 'false', + 'PUBLISH_VALUES_ONLY': 'true' + }); + for (let count = 0; count < 5; count++) { + const jsonData = diffusion.datatypes.json().from({ diffusion: `data #${count}` }); + await session.topicUpdate.set( + `my/topic/path/with/properties/${count}`, + diffusion.datatypes.json(), + jsonData, + { specification: specification1 } + ); + } + + const specification2 = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.STRING); + for (let count = 0; count < 5; count++) { + await session.topicUpdate.set( + `my/topic/path/with/default/properties/${count}`, + diffusion.datatypes.string(), + `diffusion data #${count}`, + { specification: specification2 } + ); + } + + const fetchResult1 = await session.fetchRequest() + .withProperties() + .topicTypes([ diffusion.topics.TopicType.JSON ]) + .fetch('?my/topic/path//'); + for (const result of fetchResult1.results()) { + console.log(`${result.path()} properties:`); + const properties = result.specification().properties; + for (const property of Object.keys(properties)) { + console.log(` ${property}: ${properties[property]}`); + /// tag::log + if (['DONT_RETAIN_VALUE', 'PERSISTENT', 'PUBLISH_VALUES_ONLY'].includes(property)) { + check.log(`${result.path()} ${property}: ${properties[property]}`); + } + /// end::log + } + } + + const fetchResult2 = await session.fetchRequest() + .withProperties() + .topicTypes([ diffusion.topics.TopicType.STRING ]) + .fetch('?my/topic/path//'); + for (const result of fetchResult2.results()) { + console.log(`${result.path} properties:`); + const properties = result.specification().properties; + for (const property of Object.keys(properties)) { + console.log(` ${property}: ${properties[property]}`); + /// tag::log + if (['DONT_RETAIN_VALUE', 'PERSISTENT', 'PUBLISH_VALUES_ONLY'].includes(property)) { + check.log(`${result.path()} ${property}: ${properties[property]}`); + } + /// end::log + } + } + + await session.closeSession(); + /// end::pub_sub_fetch_topic_properties[] +} diff --git a/js/pubsub/fetch/fetch-topics-via-paging.js b/js/pubsub/fetch/fetch-topics-via-paging.js new file mode 100644 index 00000000..bc437202 --- /dev/null +++ b/js/pubsub/fetch/fetch-topics-via-paging.js @@ -0,0 +1,84 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester } = require('../../../../test/util'); +/// end::log + +export async function pubSubFetchTopicViaPaging() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + Array.from({length: 25}). map((v, i) => `my/topic/path/${i}: diffusion data #${i}`), + ]); + /// end::log + /// tag::pub_sub_fetch_topic_via_paging[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.STRING); + + for (let count = 0; count < 25; count++) { + await session.topicUpdate.set( + `my/topic/path/${count}`, + diffusion.datatypes.string(), + `diffusion data #${count}`, + { specification: specification } + ); + } + + let fetchResult; + let lastTopicPath = undefined; + do { + let fetchRequest = session.fetchRequest() + .withValues(diffusion.datatypes.string()) + .first(10); + if (lastTopicPath !== undefined) { + fetchRequest = fetchRequest.after(lastTopicPath); + } + fetchResult = await fetchRequest.fetch('?my/topic/path//'); + const topicResults = fetchResult.results(); + for (const result of topicResults) { + console.log(`${result.path()}: ${result.value()}`); + /// tag::log + check.log(`${result.path()}: ${result.value()}`); + /// end::log + } + if (fetchResult.hasMore()) { + /// tag::log + expect(topicResults.length).toBe(10); + /// end::log + console.log('loading next page'); + lastTopicPath = topicResults[topicResults.length - 1].path(); + } else { + /// tag::log + expect(topicResults.length).toBe(5); + /// end::log + console.log('done'); + } + } while (fetchResult.hasMore()); + + await session.closeSession(); + /// end::pub_sub_fetch_topic_via_paging[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/pubsub/json-patch/json-patch-add.js b/js/pubsub/json-patch/json-patch-add.js new file mode 100644 index 00000000..23ba46d0 --- /dev/null +++ b/js/pubsub/json-patch/json-patch-add.js @@ -0,0 +1,105 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester, promiseWithResolvers } = require('../../../../test/util'); +/// end::log + +export async function jsonPatchAddExample() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Subscribed to my/topic/path'], + ['my/topic/path changed'], + ['old value Fred: Flintstone', 'old value Barney: Rubble'], + ['new value Fred: Flintstone', 'new value Barney: Rubble', 'new value George: Jetson'], + ['Closed'], + ]); + const valuePromise = promiseWithResolvers(); + /// end::log + /// tag::pub_sub_json_patch_add[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData = diffusion.datatypes.json().from({ + Fred: 'Flintstone', + Barney: 'Rubble' + }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addStream('my/topic/path', diffusion.datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + /// tag::log + close : () => { + check.log(`Closed`); + }, + /// end::log + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${JSON.stringify(oldValue.get())} to ${JSON.stringify(newValue.get())}`); + /// tag::log + check.log(`${topic} changed`); + const oldJson = oldValue.get(); + const newJson = newValue.get(); + for (const key of Object.keys(oldJson)) { + check.log(`old value ${key}: ${oldJson[key]}`); + } + for (const key of Object.keys(newJson)) { + check.log(`new value ${key}: ${newJson[key]}`); + } + valuePromise.resolve(); + /// end::log + } + }); + + await session.select('my/topic/path'); + + await session.topicUpdate.applyJsonPatch( + 'my/topic/path', [{ + op: 'add', + path: '/George', + value: 'Jetson' + }] + ); + + /// tag::log + await valuePromise.promise; + /// end::log + await session.closeSession(); + /// end::pub_sub_json_patch_add[] + /// tag::log + await check.done(); + /// end::log +} + diff --git a/js/pubsub/json-patch/json-patch-copy.js b/js/pubsub/json-patch/json-patch-copy.js new file mode 100644 index 00000000..35ed9532 --- /dev/null +++ b/js/pubsub/json-patch/json-patch-copy.js @@ -0,0 +1,123 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester, promiseWithResolvers } = require('../../../../test/util'); +/// end::log + +export async function jsonPatchCopyExample() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Subscribed to my/topic/path'], + ['my/topic/path changed'], + [ + 'old value Meet the Flintstones/Fred: Flintstone', + 'old value Meet the Flintstones/Barney: Rubble', + 'old value The Jetsons/George: Jetson' + ], + [ + 'new value Meet the Flintstones/Fred: Flintstone', + 'new value Meet the Flintstones/Barney: Rubble', + 'new value The Jetsons/George: Jetson', + 'new value The Jetsons/Fred: Flintstone' + ], + ['Closed'], + ]); + const valuePromise = promiseWithResolvers(); + /// end::log + /// tag::pub_sub_json_patch_copy[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData = diffusion.datatypes.json().from({ + 'Meet the Flintstones': { + 'Fred': 'Flintstone', + 'Barney': 'Rubble' + }, + 'The Jetsons': { + 'George': 'Jetson' + } + }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addStream('my/topic/path', diffusion.datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + /// tag::log + close : () => { + check.log(`Closed`); + }, + /// end::log + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${JSON.stringify(oldValue.get())} to ${JSON.stringify(newValue.get())}`); + /// tag::log + check.log(`${topic} changed`); + const oldJson = oldValue.get(); + const newJson = newValue.get(); + for (const key of Object.keys(oldJson)) { + for (const name of Object.keys(oldJson[key])) { + check.log(`old value ${key}/${name}: ${oldJson[key][name]}`); + } + } + for (const key of Object.keys(newJson)) { + for (const name of Object.keys(newJson[key])) { + check.log(`new value ${key}/${name}: ${newJson[key][name]}`); + } + } + valuePromise.resolve(); + /// end::log + } + }); + + await session.select('my/topic/path'); + + await session.topicUpdate.applyJsonPatch( + 'my/topic/path', [{ + 'op': 'copy', + 'from': '/Meet the Flintstones/Fred', + 'path': '/The Jetsons/Fred' + }] + ); + + /// tag::log + await valuePromise.promise; + /// end::log + await session.closeSession(); + /// end::pub_sub_json_patch_copy[] + /// tag::log + await check.done(); + /// end::log +} + diff --git a/js/pubsub/json-patch/json-patch-move.js b/js/pubsub/json-patch/json-patch-move.js new file mode 100644 index 00000000..45f7b6c8 --- /dev/null +++ b/js/pubsub/json-patch/json-patch-move.js @@ -0,0 +1,106 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester, promiseWithResolvers } = require('../../../../test/util'); +/// end::log + +export async function jsonPatchMoveExample() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Subscribed to my/topic/path'], + ['my/topic/path changed'], + ['old value Fred: Flintstone', 'old value Barney: Rubble', 'old value George: Jetson'], + ['new value Meet The Flintstones/Fred: Flintstone', 'new value Barney: Rubble', 'new value George: Jetson'], + ['Closed'], + ]); + const valuePromise = promiseWithResolvers(); + /// end::log + /// tag::pub_sub_json_patch_move[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData = diffusion.datatypes.json().from({ + Fred: 'Flintstone', + Barney: 'Rubble', + George: 'Jetson' + }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addStream('my/topic/path', diffusion.datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + /// tag::log + close : () => { + check.log(`Closed`); + }, + /// end::log + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${JSON.stringify(oldValue.get())} to ${JSON.stringify(newValue.get())}`); + /// tag::log + check.log(`${topic} changed`); + const oldJson = oldValue.get(); + const newJson = newValue.get(); + for (const key of Object.keys(oldJson)) { + check.log(`old value ${key}: ${oldJson[key]}`); + } + for (const key of Object.keys(newJson)) { + check.log(`new value ${key}: ${newJson[key]}`); + } + valuePromise.resolve(); + /// end::log + } + }); + + await session.select('my/topic/path'); + + await session.topicUpdate.applyJsonPatch( + 'my/topic/path', [{ + 'op': 'move', + 'from': '/Fred', + 'path': '/Meet The Flintstones~1Fred' + }] + ); + + /// tag::log + await valuePromise.promise; + /// end::log + await session.closeSession(); + /// end::pub_sub_json_patch_move[] + /// tag::log + await check.done(); + /// end::log +} + diff --git a/js/pubsub/json-patch/json-patch-remove.js b/js/pubsub/json-patch/json-patch-remove.js new file mode 100644 index 00000000..730f516f --- /dev/null +++ b/js/pubsub/json-patch/json-patch-remove.js @@ -0,0 +1,105 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester, promiseWithResolvers } = require('../../../../test/util'); +/// end::log + +export async function jsonPatchRemoveExample() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Subscribed to my/topic/path'], + ['my/topic/path changed'], + ['old value Fred: Flintstone', 'old value Barney: Rubble', 'old value George: Jetson'], + ['new value Fred: Flintstone', 'new value Barney: Rubble'], + ['Closed'], + ]); + const valuePromise = promiseWithResolvers(); + /// end::log + /// tag::pub_sub_json_patch_remove[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData = diffusion.datatypes.json().from({ + Fred: 'Flintstone', + Barney: 'Rubble', + George: 'Jetson' + }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addStream('my/topic/path', diffusion.datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + /// tag::log + close : () => { + check.log(`Closed`); + }, + /// end::log + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${JSON.stringify(oldValue.get())} to ${JSON.stringify(newValue.get())}`); + /// tag::log + check.log(`${topic} changed`); + const oldJson = oldValue.get(); + const newJson = newValue.get(); + for (const key of Object.keys(oldJson)) { + check.log(`old value ${key}: ${oldJson[key]}`); + } + for (const key of Object.keys(newJson)) { + check.log(`new value ${key}: ${newJson[key]}`); + } + valuePromise.resolve(); + /// end::log + } + }); + + await session.select('my/topic/path'); + + await session.topicUpdate.applyJsonPatch( + 'my/topic/path', [{ + op: 'remove', + path: '/George' + }] + ); + + /// tag::log + await valuePromise.promise; + /// end::log + await session.closeSession(); + /// end::pub_sub_json_patch_remove[] + /// tag::log + await check.done(); + /// end::log +} + diff --git a/js/pubsub/json-patch/json-patch-replace.js b/js/pubsub/json-patch/json-patch-replace.js new file mode 100644 index 00000000..3d1c1df7 --- /dev/null +++ b/js/pubsub/json-patch/json-patch-replace.js @@ -0,0 +1,106 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester, promiseWithResolvers } = require('../../../../test/util'); +/// end::log + +export async function jsonPatchReplaceExample() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Subscribed to my/topic/path'], + ['my/topic/path changed'], + ['old value Fred: Flintstone', 'old value Barney: Rubble', 'old value George: Jetson'], + ['new value Fred: Flintstone', 'new value Barney: Rubble', 'new value George: Bedrock'], + ['Closed'], + ]); + const valuePromise = promiseWithResolvers(); + /// end::log + /// tag::pub_sub_json_patch_replace[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData = diffusion.datatypes.json().from({ + Fred: 'Flintstone', + Barney: 'Rubble', + George: 'Jetson' + }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addStream('my/topic/path', diffusion.datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + /// tag::log + close : () => { + check.log(`Closed`); + }, + /// end::log + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${JSON.stringify(oldValue.get())} to ${JSON.stringify(newValue.get())}`); + /// tag::log + check.log(`${topic} changed`); + const oldJson = oldValue.get(); + const newJson = newValue.get(); + for (const key of Object.keys(oldJson)) { + check.log(`old value ${key}: ${oldJson[key]}`); + } + for (const key of Object.keys(newJson)) { + check.log(`new value ${key}: ${newJson[key]}`); + } + valuePromise.resolve(); + /// end::log + } + }); + + await session.select('my/topic/path'); + + await session.topicUpdate.applyJsonPatch( + 'my/topic/path', [{ + op: 'replace', + path: '/George', + value: 'Bedrock' + }] + ); + + /// tag::log + await valuePromise.promise; + /// end::log + await session.closeSession(); + /// end::pub_sub_json_patch_replace[] + /// tag::log + await check.done(); + /// end::log +} + diff --git a/js/pubsub/json-patch/json-patch-test.js b/js/pubsub/json-patch/json-patch-test.js new file mode 100644 index 00000000..9060b51c --- /dev/null +++ b/js/pubsub/json-patch/json-patch-test.js @@ -0,0 +1,98 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester } = require('../../../../test/util'); +/// end::log + +export async function jsonPatchTestExample() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Subscribed to my/topic/path'], + ['Closed'], + ]); + /// end::log + /// tag::pub_sub_json_patch_test[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData = diffusion.datatypes.json().from({ + Fred: 'Flintstone', + Barney: 'Rubble', + George: 'Jetson' + }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addStream('my/topic/path', diffusion.datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + /// tag::log + close : () => { + check.log(`Closed`); + }, + /// end::log + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${JSON.stringify(oldValue.get())} to ${JSON.stringify(newValue.get())}`); + /// tag::log + check.log(`${topic} changed`); + const oldJson = oldValue.get(); + const newJson = newValue.get(); + for (const key of Object.keys(oldJson)) { + check.log(`old value ${key}: ${oldJson[key]}`); + } + for (const key of Object.keys(newJson)) { + check.log(`new value ${key}: ${newJson[key]}`); + } + /// end::log + } + }); + + await session.select('my/topic/path'); + + await session.topicUpdate.applyJsonPatch( + 'my/topic/path', [{ + op: 'test', + path: '/Fred', + value: 'Flintstone' + }] + ); + + await session.closeSession(); + /// end::pub_sub_json_patch_test[] + /// tag::log + await check.done(); + /// end::log +} + diff --git a/js/pubsub/publishing/add-topic-and-set.js b/js/pubsub/publishing/add-topic-and-set.js new file mode 100644 index 00000000..bac99b44 --- /dev/null +++ b/js/pubsub/publishing/add-topic-and-set.js @@ -0,0 +1,46 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue } = require('../../../../test/util'); +/// end::log + +export async function addTopicAndSetExample() { + /// tag::pub_sub_publish_add_and_set_topic[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData = diffusion.datatypes.json().from({ diffusion: 'data' }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + console.log('Topic value has been set.'); + + await session.closeSession(); + /// end::pub_sub_publish_add_and_set_topic[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path', { diffusion: 'data' }); + /// end::log +} diff --git a/js/pubsub/publishing/add-topic-with-properties.js b/js/pubsub/publishing/add-topic-with-properties.js new file mode 100644 index 00000000..babe70ba --- /dev/null +++ b/js/pubsub/publishing/add-topic-with-properties.js @@ -0,0 +1,51 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectTopicExists } = require('../../../../test/util'); +/// end::log + +export async function addTopicWithPropertiesExample() { + /// tag::pub_sub_publish_add_topic_custom_properties[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON, { + 'DONT_RETAIN_VALUE': 'true', + 'PERSISTENT': 'false', + 'PUBLISH_VALUES_ONLY': 'true' + }); + const topicAddResult = await session.topics.add('my/topic/path', specification); + if (topicAddResult.added) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicAddResult.added).toBe(true); + /// end::log + + await session.closeSession(); + /// end::pub_sub_publish_add_topic_custom_properties[] + /// tag::log + await expectTopicExists('my/topic/path'); + /// end::log +} diff --git a/js/pubsub/publishing/add-topic.js b/js/pubsub/publishing/add-topic.js new file mode 100644 index 00000000..ae36cbf4 --- /dev/null +++ b/js/pubsub/publishing/add-topic.js @@ -0,0 +1,47 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectTopicExists } = require('../../../../test/util'); +/// end::log + +export async function addTopicExample() { + /// tag::pub_sub_publish_add_topic[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const topicAddResult = await session.topics.add('my/topic/path', specification); + if (topicAddResult.added) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicAddResult.added).toBe(true); + /// end::log + + await session.closeSession(); + /// end::pub_sub_publish_add_topic[] + /// tag::log + await expectTopicExists('my/topic/path'); + /// end::log +} diff --git a/js/pubsub/publishing/set-topic.js b/js/pubsub/publishing/set-topic.js new file mode 100644 index 00000000..23f6277b --- /dev/null +++ b/js/pubsub/publishing/set-topic.js @@ -0,0 +1,44 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue } = require('../../../../test/util'); +/// end::log + +export async function setTopicExample() { + /// tag::pub_sub_publish_set_topic[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const jsonData = diffusion.datatypes.json().from({ diffusion: 'data' }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData + ); + console.log('Topic value has been set.'); + + await session.closeSession(); + /// end::pub_sub_publish_set_topic[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path', { diffusion: 'data' }); + /// end::log +} diff --git a/js/pubsub/publishing/update-stream-add-and-set.js b/js/pubsub/publishing/update-stream-add-and-set.js new file mode 100644 index 00000000..f40e0d45 --- /dev/null +++ b/js/pubsub/publishing/update-stream-add-and-set.js @@ -0,0 +1,51 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue } = require('../../../../test/util'); +/// end::log + +export async function updateSreamAddAndSetExample() { + /// tag::pub_sub_publish_add_and_set_topic_via_update_stream[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData = diffusion.datatypes.json().from({ diffusion: 'data' }); + const updateStream = session.topicUpdate.newUpdateStreamBuilder() + .specification(specification) + .build('my/topic/path/with/update/stream', diffusion.datatypes.json()); + const topicCreationResult = await updateStream.set(jsonData); + if (topicCreationResult === diffusion.topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult).toBe(diffusion.topicUpdate.TopicCreationResult.CREATED); + /// end::log + + await session.closeSession(); + /// end::pub_sub_publish_add_and_set_topic_via_update_stream[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path/with/update/stream', { diffusion: 'data' }); + /// end::log +} diff --git a/js/pubsub/publishing/update-stream-set.js b/js/pubsub/publishing/update-stream-set.js new file mode 100644 index 00000000..a96a03e0 --- /dev/null +++ b/js/pubsub/publishing/update-stream-set.js @@ -0,0 +1,45 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue } = require('../../../../test/util'); +/// end::log + +export async function updateSreamSetExample() { + /// tag::pub_sub_publish_set_topic_via_update_stream[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + await session.topics.add('my/topic/path/with/update/stream', specification); + + const jsonData = diffusion.datatypes.json().from({ diffusion: ['data', 'more data'] }); + const updateStream = session.topicUpdate.newUpdateStreamBuilder() + .build('my/topic/path/with/update/stream', diffusion.datatypes.json()); + await updateStream.set(jsonData); + console.log('Topic value has been set.'); + + await session.closeSession(); + /// end::pub_sub_publish_set_topic_via_update_stream[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path/with/update/stream', { diffusion: ['data', 'more data'] }); + /// end::log +} diff --git a/js/pubsub/removal/automatic-topic-removal.js b/js/pubsub/removal/automatic-topic-removal.js new file mode 100644 index 00000000..bd9dd5a2 --- /dev/null +++ b/js/pubsub/removal/automatic-topic-removal.js @@ -0,0 +1,149 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectTopicCounts } = require('../../../../test/util'); +/// end::log + +export async function pubSubAutomaticTopicRemoval() { + /// tag::pub_sub_remove_automatic_topic_removal[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification1 = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON, { + REMOVAL: 'when time after "Tue, 4 May 2077 11:05:30 GMT"' + }); + const topicCreationResult1 = await session.topics.add('my/topic/path/to/be/removed/time/after', specification1); + if (topicCreationResult1.added) { + console.log(`Topic "${topicCreationResult1.topic}" has been created.`); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult1.added).toBeTrue(); + /// end::log + + const specification2 = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON, { + REMOVAL: 'when subscriptions < 1 for 10m' + }); + const topicCreationResult2 = await session.topics.add('my/topic/path/to/be/removed/subscriptions', specification2); + if (topicCreationResult2.added) { + console.log(`Topic "${topicCreationResult2.topic}" has been created.`); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult2.added).toBeTrue(); + /// end::log + + const specification3 = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON, { + REMOVAL: 'when local subscriptions < 1 for 10m' + }); + const topicCreationResult3 = await session.topics.add('my/topic/path/to/be/removed/local/subscriptions', specification3); + if (topicCreationResult3.added) { + console.log(`Topic "${topicCreationResult3.topic}" has been created.`); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult3.added).toBeTrue(); + /// end::log + + const specification4 = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON, { + REMOVAL: 'when no updates for 10m' + }); + const topicCreationResult4 = await session.topics.add('my/topic/path/to/be/removed/no/updates', specification4); + if (topicCreationResult4.added) { + console.log(`Topic "${topicCreationResult4.topic}" has been created.`); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult4.added).toBeTrue(); + /// end::log + + const specification5 = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON, { + REMOVAL: 'when no session has \'$Principal is "client"\' for 1h' + }); + const topicCreationResult5 = await session.topics.add('my/topic/path/to/be/removed/no/session', specification5); + if (topicCreationResult5.added) { + console.log(`Topic "${topicCreationResult5.topic}" has been created.`); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult5.added).toBeTrue(); + /// end::log + + const specification6 = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON, { + REMOVAL: 'when no local session has \'Department is "Accounts"\' for 1h after 1d' + }); + const topicCreationResult6 = await session.topics.add('my/topic/path/to/be/removed/no/local/session', specification6); + if (topicCreationResult6.added) { + console.log(`Topic "${topicCreationResult6.topic}" has been created.`); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult6.added).toBeTrue(); + /// end::log + + const specification7 = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON, { + REMOVAL: 'when subscriptions < 1 for 10m or no updates for 20m' + }); + const topicCreationResult7 = await session.topics.add('my/topic/path/to/be/removed/subcriptions/or/updates', specification7); + if (topicCreationResult7.added) { + console.log(`Topic "${topicCreationResult7.topic}" has been created.`); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult7.added).toBeTrue(); + /// end::log + + const specification8 = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON, { + REMOVAL: 'when subscriptions < 1 for 10m and no updates for 20m' + }); + const topicCreationResult8 = await session.topics.add('my/topic/path/to/be/removed/subcriptions/and/updates', specification8); + if (topicCreationResult8.added) { + console.log(`Topic "${topicCreationResult8.topic}" has been created.`); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult8.added).toBeTrue(); + /// end::log + + await session.closeSession(); + /// end::pub_sub_remove_automatic_topic_removal[] + /// tag::log + await expectTopicCounts({ + 'my/topic/path/to/be/removed/time/after': 1, + 'my/topic/path/to/be/removed/subscriptions': 1, + 'my/topic/path/to/be/removed/local/subscriptions': 1, + 'my/topic/path/to/be/removed/no/updates': 1, + 'my/topic/path/to/be/removed/no/session': 1, + 'my/topic/path/to/be/removed/no/local/session': 1, + 'my/topic/path/to/be/removed/subcriptions/or/updates': 1, + 'my/topic/path/to/be/removed/subcriptions/and/updates': 1 + }); + /// end::log +} diff --git a/js/pubsub/removal/remove-multiple-topics.js b/js/pubsub/removal/remove-multiple-topics.js new file mode 100644 index 00000000..e9fea357 --- /dev/null +++ b/js/pubsub/removal/remove-multiple-topics.js @@ -0,0 +1,110 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectTopicCounts } = require('../../../../test/util'); +/// end::log + +export async function pubSubRemoveMultipleTopicsViaSelector() { + /// tag::pub_sub_remove_multiple_topics_via_selector[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData1 = diffusion.datatypes.json().from({ diffusion: [ 'data', 'more data' ] }); + const topicCreationResult1 = await session.topicUpdate.set( + 'my/topic/path/to/be/removed', + diffusion.datatypes.json(), + jsonData1, + { specification: specification } + ); + if (topicCreationResult1 === diffusion.topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult1).toBe(diffusion.topicUpdate.TopicCreationResult.CREATED); + /// end::log + + const jsonData2 = diffusion.datatypes.json().from({ diffusion: [ 'data', 'also more data' ] }); + const topicCreationResult2 = await session.topicUpdate.set( + 'my/topic/path/to/be/also/removed', + diffusion.datatypes.json(), + jsonData1, + { specification: specification } + ); + if (topicCreationResult2 === diffusion.topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult2).toBe(diffusion.topicUpdate.TopicCreationResult.CREATED); + /// end::log + + const jsonData3 = diffusion.datatypes.json().from({ diffusion: [ 'no data' ] }); + const topicCreationResult3 = await session.topicUpdate.set( + 'my/topic/path/will/not/be/removed', + diffusion.datatypes.json(), + jsonData3, + { specification: specification } + ); + if (topicCreationResult3 === diffusion.topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult3).toBe(diffusion.topicUpdate.TopicCreationResult.CREATED); + /// end::log + + const jsonData4 = diffusion.datatypes.json().from({ diffusion: [ 'no data either' ] }); + const topicCreationResult4 = await session.topicUpdate.set( + 'my/topic/path/will/not/be/removed/either', + diffusion.datatypes.json(), + jsonData4, + { specification: specification } + ); + if (topicCreationResult4 === diffusion.topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult4).toBe(diffusion.topicUpdate.TopicCreationResult.CREATED); + /// end::log + + + const removalResult = await session.topics.remove('?my/topic/path/to/be//'); + console.log(`${removalResult.removedCount} topics have been removed.`); + + await session.closeSession(); + /// end::pub_sub_remove_multiple_topics_via_selector[] + /// tag::log + await expectTopicCounts({ + 'my/topic/path/to/be/removed': 0, + 'my/topic/path/to/be/also/removed': 0, + 'my/topic/path/will/not/be/removed': 1, + 'my/topic/path/will/not/be/removed/either': 1 + }); + /// end::log +} diff --git a/js/pubsub/removal/remove-single-topic.js b/js/pubsub/removal/remove-single-topic.js new file mode 100644 index 00000000..371ba830 --- /dev/null +++ b/js/pubsub/removal/remove-single-topic.js @@ -0,0 +1,92 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectTopicCounts } = require('../../../../test/util'); +/// end::log + +export async function pubSubRemoveSingleTopicViaPath() { + /// tag::pub_sub_remove_single_topic_via_path[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData1 = diffusion.datatypes.json().from({ diffusion: [ 'data', 'more data' ] }); + const topicCreationResult1 = await session.topicUpdate.set( + 'my/topic/path/to/be/removed', + diffusion.datatypes.json(), + jsonData1, + { specification: specification } + ); + if (topicCreationResult1 === diffusion.topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult1).toBe(diffusion.topicUpdate.TopicCreationResult.CREATED); + /// end::log + + const jsonData2 = diffusion.datatypes.json().from({ diffusion: [ 'no data' ] }); + const topicCreationResult2 = await session.topicUpdate.set( + 'my/topic/path/will/not/be/removed', + diffusion.datatypes.json(), + jsonData2, + { specification: specification } + ); + if (topicCreationResult2 === diffusion.topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult2).toBe(diffusion.topicUpdate.TopicCreationResult.CREATED); + /// end::log + + const jsonData3 = diffusion.datatypes.json().from({ diffusion: [ 'no data either' ] }); + const topicCreationResult3 = await session.topicUpdate.set( + 'my/topic/path/will/not/be/removed/either', + diffusion.datatypes.json(), + jsonData3, + { specification: specification } + ); + if (topicCreationResult3 === diffusion.topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult3).toBe(diffusion.topicUpdate.TopicCreationResult.CREATED); + /// end::log + + await session.topics.remove('my/topic/path/to/be/removed'); + console.log('Topic has been removed.'); + + await session.closeSession(); + /// end::pub_sub_remove_single_topic_via_path[] + /// tag::log + await expectTopicCounts({ + 'my/topic/path/to/be/removed': 0, + 'my/topic/path/will/not/be/removed': 1, + 'my/topic/path/will/not/be/removed/either': 1 + }); + /// end::log +} diff --git a/js/pubsub/subscribing/subscribe-cross-compatible.js b/js/pubsub/subscribing/subscribe-cross-compatible.js new file mode 100644 index 00000000..2bfe5530 --- /dev/null +++ b/js/pubsub/subscribing/subscribe-cross-compatible.js @@ -0,0 +1,107 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester } = require('../../../../test/util'); +/// end::log + +export async function pubSubSubscribeCrossCompatible() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ + 'JSON stream subscribed to my/int/topic/path', + 'String stream subscribed to my/int/topic/path' + ], + [ + 'JSON stream closed', + 'String stream closed' + ], + ]); + /// end::log + /// tag::pub_sub_subscribe_cross_compatible[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.INT64); + await session.topics.add('my/int/topic/path', specification); + + const jsonValueStream = session.addStream('my/int/topic/path', diffusion.datatypes.json()); + jsonValueStream.on({ + subscribe : (topic, specification) => { + console.log(`JSON stream subscribed to ${topic}`); + /// tag::log + check.log(`JSON stream subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`JSON stream unsubscribed from ${topic}: ${reason}`); + /// tag::log + check.log(`JSON stream unsubscribed from ${topic}: ${reason}`); + /// end::log + }, + /// tag::log + close : () => { + check.log(`JSON stream closed`); + }, + /// end::log + value : (topic, spec, newValue, oldValue) => { + console.log(`JSON stream ${topic} changed from ${oldValue.get()} to ${newValue.get()}`); + /// tag::log + check.log(`JSON stream ${topic} changed from ${oldValue.get()} to ${newValue.get()}`); + /// end::log + } + }); + + const stringValueStream = session.addStream('my/int/topic/path', diffusion.datatypes.string()); + stringValueStream.on({ + subscribe : (topic, specification) => { + console.log(`String stream subscribed to ${topic}`); + /// tag::log + check.log(`String stream subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`String stream unsubscribed from ${topic}: ${reason}`); + /// tag::log + check.log(`String stream unsubscribed from ${topic}: ${reason}`); + /// end::log + }, + /// tag::log + close : () => { + check.log(`String stream closed`); + }, + /// end::log + value : (topic, spec, newValue, oldValue) => { + console.log(`String stream ${topic} changed from ${oldValue} to ${newValue}`); + /// tag::log + check.log(`String stream ${topic} changed from ${oldValue} to ${newValue}`); + /// end::log + } + }); + + await session.select('my/int/topic/path'); + + await session.closeSession(); + /// end::pub_sub_subscribe_cross_compatible[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/pubsub/subscribing/subscribe-fallback-streams.js b/js/pubsub/subscribing/subscribe-fallback-streams.js new file mode 100644 index 00000000..cbdd4ece --- /dev/null +++ b/js/pubsub/subscribing/subscribe-fallback-streams.js @@ -0,0 +1,84 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester } = require('../../../../test/util'); +/// end::log + +export async function pubSubSubscribeFallbackStream() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ + 'Subscribed to my/topic/path', + 'Subscribed to my/other/topic/path', + 'Subscribed to my/additional/topic/path' + ], + ['Closed'], + ]); + /// end::log + /// tag::pub_sub_subscribe_fallback_stream[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + await session.topics.add('my/topic/path', specification); + await session.topics.add('my/other/topic/path', specification); + + const valueStream = session.addFallbackStream(diffusion.datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + /// tag::log + check.log(`Unsubscribed from ${topic}: ${reason}`); + /// end::log + }, + /// tag::log + close : () => { + check.log(`Closed`); + }, + /// end::log + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${oldValue.get()} to ${newValue.get()}`); + /// tag::log + check.log(`${topic} changed from ${oldValue.get()} to ${newValue.get()}`); + /// end::log + } + }); + + await session.select('?my//'); + + console.log('Creating my/additional/topic/path'); + await session.topics.add('my/additional/topic/path', specification); + console.log('Creating this/topic/path/will/not/be/picked/up'); + await session.topics.add('this/topic/path/will/not/be/picked/up', specification); + + await session.closeSession(); + /// end::pub_sub_subscribe_fallback_stream[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/pubsub/subscribing/subscribe-multiple-topics.js b/js/pubsub/subscribing/subscribe-multiple-topics.js new file mode 100644 index 00000000..85d03f20 --- /dev/null +++ b/js/pubsub/subscribing/subscribe-multiple-topics.js @@ -0,0 +1,82 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester } = require('../../../../test/util'); +/// end::log + +export async function subscribeMultipleTopicExample() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ + 'Subscribed to my/topic/path', + 'Subscribed to my/other/topic/path', + 'Subscribed to my/additional/topic/path' + ], + ['Closed'], + ]); + /// end::log + /// tag::pub_sub_subscribe_multiple_topics_via_selector[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + await session.topics.add('my/topic/path', specification); + await session.topics.add('my/other/topic/path', specification); + + const valueStream = session.addStream('?my//', diffusion.datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + /// tag::log + check.log(`Unsubscribed from ${topic}: ${reason}`); + /// end::log + }, + /// tag::log + close : () => { + check.log(`Closed`); + }, + /// end::log + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${oldValue.get()} to ${newValue.get()}`); + /// tag::log + check.log(`${topic} changed from ${oldValue.get()} to ${newValue.get()}`); + /// end::log + } + }); + + await session.select('?my//'); + + console.log('Creating my/additional/topic/path'); + await session.topics.add('my/additional/topic/path', specification); + + await session.closeSession(); + /// end::pub_sub_subscribe_multiple_topics_via_selector[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/pubsub/subscribing/subscribe-single-topic.js b/js/pubsub/subscribing/subscribe-single-topic.js new file mode 100644 index 00000000..83c2f88d --- /dev/null +++ b/js/pubsub/subscribing/subscribe-single-topic.js @@ -0,0 +1,92 @@ +/******************************************************************************* + * Copyright (C) 2024 - 2025 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester } = require('../../../../test/util'); +/// end::log + +export async function subscribeSingleTopicExample() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Subscribed to my/topic/path'], + ['my/topic/path changed from undefined to {"diffusion":"data"}'], + ['my/topic/path changed from {"diffusion":"data"} to {"diffusion":"more data"}'], + ['Closed'], + ]); + /// end::log + /// tag::pub_sub_subscribe_single_topic_via_path[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + await session.topics.add('my/topic/path', specification); + + const valueStream = session.addStream('my/topic/path', diffusion.datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + /// tag::log + check.log(`Unsubscribed from ${topic}: ${reason}`); + /// end::log + }, + /// tag::log + close : () => { + check.log(`Closed`); + }, + /// end::log + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${JSON.stringify(oldValue?.get())} to ${JSON.stringify(newValue?.get())}`); + /// tag::log + check.log(`${topic} changed from ${JSON.stringify(oldValue?.get())} to ${JSON.stringify(newValue?.get())}`); + /// end::log + } + }); + + await session.select('my/topic/path'); + + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + diffusion.datatypes.json().from({ "diffusion": "data" }) + ); + + await new Promise(resolve => setTimeout(resolve, 2000)); + + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + diffusion.datatypes.json().from({ "diffusion": "more data" }) + ); + + await new Promise(resolve => setTimeout(resolve, 2000)); + + await session.closeSession(); + /// end::pub_sub_subscribe_single_topic_via_path[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/pubsub/subscribing/subscribe-topic-selection-scopes.js b/js/pubsub/subscribing/subscribe-topic-selection-scopes.js new file mode 100644 index 00000000..ae470f01 --- /dev/null +++ b/js/pubsub/subscribing/subscribe-topic-selection-scopes.js @@ -0,0 +1,128 @@ +/******************************************************************************* + * Copyright (C) 2025 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester } = require('../../../../test/util'); +/// end::log + +export async function subscribeTopicSelectionScopesExample() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ + 'componentA: Subscribed to my/topic/path', + 'componentB: Subscribed to my/topic/path' + ], + ['componentB: Subscribed to my/other/path'], + [ + 'componentA: Unsubscribed from my/topic/path', + 'componentB: Unsubscribed from my/topic/path', + 'componentB: Unsubscribed from my/other/path' + ] + ]); + /// end::log + /// tag::pub_sub_subscribe_selection_scopes[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + // Create topics 'my/topic/path' and 'my/other/path' + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.STRING); + await session.topics.add('my/topic/path', specification); + await session.topics.add('my/other/path', specification); + + // each component registers a stream for the topics they are interested in + // and subscribe to the topics with their own scope + + const componentAStream = session.addStream('my/topic/path', diffusion.datatypes.string()); + const componentBStream = session.addStream('?my//', diffusion.datatypes.string()); + + componentAStream.on({ + subscribe : (topic, specification) => { + console.log(`componentA: Subscribed to ${topic}`); + /// tag::log + check.log(`componentA: Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`componentA: Unsubscribed from ${topic}`); + /// tag::log + check.log(`componentA: Unsubscribed from ${topic}`); + /// end::log + }, + close : () => { + console.log(`componentA: stream closed`); + }, + value : (topic, spec, newValue, oldValue) => { + console.log(`componentA: ${topic} changed from ${oldValue?.get()} to ${newValue?.get()}`); + } + }); + + componentBStream.on({ + subscribe : (topic, specification) => { + console.log(`componentB: Subscribed to ${topic}`); + /// tag::log + check.log(`componentB: Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`componentB: Unsubscribed from ${topic}`); + /// tag::log + check.log(`componentB: Unsubscribed from ${topic}`); + /// end::log + }, + close : () => { + console.log(`componentB: stream closed`); + }, + value : (topic, spec, newValue, oldValue) => { + console.log(`componentB: ${topic} changed from ${oldValue?.get()} to ${newValue?.get()}`); + } + }); + + await session.selectWithScope('my/topic/path', 'scopeA'); + await session.selectWithScope('my/topic/path', 'scopeB'); + await session.selectWithScope('my/other/path', 'scopeB'); + + const selectionsA = await session.clients.getTopicSelections(session.sessionId); + for (const selection of Object.keys(selectionsA)) { + console.log(`Scope ${selection}: ${selectionsA[selection].map(topic => topic.selector).join(', ')}`); + } + + // componentB unsubscribes from 'my/topic/path', scopeA is unaffected + await session.unsubscribeWithScope('my/topic/path', 'scopeB'); + + const selectionsB = await session.clients.getTopicSelections(session.sessionId); + for (const selection of Object.keys(selectionsB)) { + console.log(`Scope ${selection}: ${selectionsB[selection].map(topic => topic.selector).join(', ')}`); + } + + // componentA unsubscribes from all topics, scopeB is unaffected + // 'my/topic/path' is no longer in any scopes and is unsubscribed for the session + await session.unsubscribeWithScope("?.*//", "scopeA"); + + // a control client unsubscribes all remaining scopes for 'my/other/path' which + // is now unsubscribed for the session + await session.clients.unsubscribeAllScopes(session.sessionId, 'my/other/path'); + + await session.closeSession(); + /// end::pub_sub_subscribe_selection_scopes[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/security/change-principal.js b/js/security/change-principal.js new file mode 100644 index 00000000..19540ef1 --- /dev/null +++ b/js/security/change-principal.js @@ -0,0 +1,33 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function changePrincipalExample() { + /// tag::security_change_principal[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + await session.security.changePrincipal('control', 'password'); + console.log('Principal has been changed to control'); + + await session.closeSession(); + /// end::security_change_principal[] +} diff --git a/js/security/get-global-permissions.js b/js/security/get-global-permissions.js new file mode 100644 index 00000000..1a273c6e --- /dev/null +++ b/js/security/get-global-permissions.js @@ -0,0 +1,59 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester } = require('../../../test/util'); +/// end::log + +export async function getGlobalPermissionsExample() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ + 'VIEW_SESSION', + 'MODIFY_SESSION', + 'REGISTER_HANDLER', + 'VIEW_SERVER', + 'CONTROL_SERVER', + 'VIEW_SECURITY', + 'MODIFY_SECURITY', + 'READ_TOPIC_VIEWS', + 'MODIFY_TOPIC_VIEWS' + ] + ]); + /// end::log + /// tag::security_get_global_permissions[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const globalPermissions = await session.security.getGlobalPermissions(); + for (const permission of globalPermissions) { + console.log(permission); + /// tag::log + check.log(permission); + /// end::log + } + + await session.closeSession(); + /// end::security_get_global_permissions[] + /// tag::log + check.done(); + /// end::log +} diff --git a/js/security/get-path-permissions.js b/js/security/get-path-permissions.js new file mode 100644 index 00000000..1621e3e3 --- /dev/null +++ b/js/security/get-path-permissions.js @@ -0,0 +1,60 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester } = require('../../../test/util'); +/// end::log + +export async function getPathPermissionsExample() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ + 'SELECT_TOPIC', + 'READ_TOPIC', + 'UPDATE_TOPIC', + 'MODIFY_TOPIC', + 'SEND_TO_MESSAGE_HANDLER', + 'SEND_TO_SESSION', + 'EDIT_TIME_SERIES_EVENTS', + 'ACQUIRE_LOCK', + 'EXPOSE_BRANCH' + + ] + ]); + /// end::log + /// tag::security_get_path_permissions[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const pathPermissions = await session.security.getPathPermissions('.*//'); + for (const permission of pathPermissions) { + console.log(permission); + /// tag::log + check.log(permission); + /// end::log + } + + await session.closeSession(); + /// end::security_get_path_permissions[] + /// tag::log + check.done(); + /// end::log +} diff --git a/js/server-configuration/metrics/get-metrics/metrics-console.js b/js/server-configuration/metrics/get-metrics/metrics-console.js new file mode 100644 index 00000000..9e13c646 --- /dev/null +++ b/js/server-configuration/metrics/get-metrics/metrics-console.js @@ -0,0 +1,95 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester } = require('../../../../../test/util'); +/// end::log + +export async function metricsRequestMetricsConsole() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ + 'diffusion_license: diffusion_license (INFO)', + 'diffusion_multiplexer_manager_number_of_multiplexers: diffusion_multiplexer_manager_number_of_multiplexers (GAUGE)', + 'diffusion_release: diffusion_release (INFO)', + 'diffusion_server_free_memory_bytes: diffusion_server_free_memory_bytes bytes (GAUGE)', + 'diffusion_server_license_expiry_date: diffusion_server_license_expiry_date (INFO)', + 'diffusion_server_max_memory_bytes: diffusion_server_max_memory_bytes bytes (GAUGE)', + 'diffusion_server_number_of_topics: diffusion_server_number_of_topics (GAUGE)', + 'diffusion_server_session_locks: diffusion_server_session_locks (INFO)', + 'diffusion_server_start_date: diffusion_server_start_date (INFO)', + 'diffusion_server_start_date_millis: diffusion_server_start_date_millis millis (GAUGE)', + 'diffusion_server_time_zone: diffusion_server_time_zone (INFO)', + 'diffusion_server_total_memory_bytes: diffusion_server_total_memory_bytes bytes (GAUGE)', + 'diffusion_server_uptime: diffusion_server_uptime (INFO)', + 'diffusion_server_uptime_millis: diffusion_server_uptime_millis millis (GAUGE)', + 'diffusion_server_used_physical_memory_size_bytes: diffusion_server_used_physical_memory_size_bytes bytes (GAUGE)', + 'diffusion_server_used_swap_space_size_bytes: diffusion_server_used_swap_space_size_bytes bytes (GAUGE)', + 'diffusion_server_user_directory: diffusion_server_user_directory (INFO)', + 'diffusion_server_user_name: diffusion_server_user_name (INFO)' + ], + ]); + /// end::log + /// tag::metrics_get_metrics_console[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const metricsResult = await session.metrics.metricsRequest() + .filter([ + 'diffusion_server_time_zone', + 'diffusion_server_user_directory', + 'diffusion_server_license_expiry_date', + 'diffusion_server_uptime_millis', + 'diffusion_license', + 'diffusion_server_free_memory_bytes', + 'diffusion_server_max_memory_bytes', + 'diffusion_server_total_memory_bytes', + 'diffusion_release', + 'diffusion_server_start_date', + 'diffusion_server_start_date_millis', + 'diffusion_server_used_swap_space_size_bytes', + 'diffusion_server_used_physical_memory_size_bytes', + 'diffusion_server_number_of_topics', + 'diffusion_server_session_locks', + 'diffusion_server_user_name', + 'diffusion_server_uptime', + 'diffusion_multiplexer_manager_number_of_multiplexers' + ]) + .currentServer() + .fetch(); + + const servers = metricsResult.getServerNames(); + /// tag::log + expect(servers.size).toBe(1); + /// end::log + const collections = metricsResult.getMetrics([...servers.values()][0]); + for (const collection of collections) { + for (const sample of collection.samples) { + console.log(`${collection.name}: ${sample.value} ${collection.unit} (${diffusion.MetricType[collection.type]})`); + /// tag::log + check.log(`${collection.name}: ${sample.name} ${collection.unit} (${diffusion.MetricType[collection.type]})`); + /// end::log + } + } + + await session.closeSession(); + /// end::metrics_get_metrics_console[] +} diff --git a/js/server-configuration/metrics/get-metrics/outbound-bytes.js b/js/server-configuration/metrics/get-metrics/outbound-bytes.js new file mode 100644 index 00000000..fa3c4255 --- /dev/null +++ b/js/server-configuration/metrics/get-metrics/outbound-bytes.js @@ -0,0 +1,46 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function metricsGetOutboundBytes() { + /// tag::metrics_get_metrics_outbound_bytes[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const metricsResult = await session.metrics.metricsRequest() + .filter('diffusion_network_outbound_bytes') + .currentServer() + .fetch(); + + const servers = metricsResult.getServerNames(); + /// tag::log + expect(servers.size).toBe(1); + /// end::log + const collections = metricsResult.getMetrics([...servers.values()][0]); + /// tag::log + expect(collections[0].samples.length).toBe(1); + /// end::log + const sample = collections[0].samples[0]; + console.log(`${collections[0].name}: ${sample.value} ${collections[0].unit} (${collections[0].type})`); + + await session.closeSession(); + /// end::metrics_get_metrics_outbound_bytes[] +} diff --git a/js/server-configuration/metrics/session-metric-collector/list-session-metric-collectors.js b/js/server-configuration/metrics/session-metric-collector/list-session-metric-collectors.js new file mode 100644 index 00000000..5d1c8c60 --- /dev/null +++ b/js/server-configuration/metrics/session-metric-collector/list-session-metric-collectors.js @@ -0,0 +1,60 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function metricsListSessionMetricCollectors() { + /// tag::metrics_session_metric_collector_list[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const sessionMetricCollector1 = diffusion.newSessionMetricCollectorBuilder() + .exportToPrometheus(false) + .maximumGroups(10) + .removeMetricsWithNoMatches(true) + .groupByProperty('$Location') + .create('Session Metric Collector 1', '$Principal is "control"'); + const sessionMetricCollector2 = diffusion.newSessionMetricCollectorBuilder() + .exportToPrometheus(true) + .maximumGroups(250) + .removeMetricsWithNoMatches(true) + .groupByProperty('$Location') + .create('Session Metric Collector 2', '$Principal is "control"'); + await Promise.all([ + session.metrics.putSessionMetricCollector(sessionMetricCollector1), + session.metrics.putSessionMetricCollector(sessionMetricCollector2) + ]); + + const sessionMetricCollectors = await session.metrics.listSessionMetricCollectors(); + for (const collector of sessionMetricCollectors.collectors) { + console.log(`${collector.name}: ${collector.sessionFilter} (${collector.maximumGroups}, ` + + `${collector.exportToPrometheus}, ${collector.removeMetricsWithNoMatches}, ` + + `[${collector.groupByProperties.join(', ')}])`); + } + /// tag::log + expect(sessionMetricCollectors.collectors.length).toBe(2); + expect(sessionMetricCollectors.collectors.map((c) => c.name)).toEqual(jasmine.arrayContaining( + ['Session Metric Collector 1', 'Session Metric Collector 2'] + )); + /// end::log + + await session.closeSession(); + /// end::metrics_session_metric_collector_list[] +} diff --git a/js/server-configuration/metrics/session-metric-collector/put-session-metric-collector.js b/js/server-configuration/metrics/session-metric-collector/put-session-metric-collector.js new file mode 100644 index 00000000..607cb8c0 --- /dev/null +++ b/js/server-configuration/metrics/session-metric-collector/put-session-metric-collector.js @@ -0,0 +1,43 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function metricsPutSessionMetricCollector() { + /// tag::metrics_session_metric_collector_put[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const sessionMetricCollector = diffusion.newSessionMetricCollectorBuilder() + .exportToPrometheus(false) + .maximumGroups(10) + .removeMetricsWithNoMatches(true) + .groupByProperty('$Location') + .create('Session Metric Collector 1', '$Principal is "control"'); + await session.metrics.putSessionMetricCollector(sessionMetricCollector); + /// tag::log + const sessionMetricCollectors = await session.metrics.listSessionMetricCollectors(); + expect(sessionMetricCollectors.collectors.length).toBe(1); + expect(sessionMetricCollectors.collectors[0].name).toBe('Session Metric Collector 1'); + /// end::log + + await session.closeSession(); + /// end::metrics_session_metric_collector_put[] +} diff --git a/js/server-configuration/metrics/session-metric-collector/remove-session-metric-collector.js b/js/server-configuration/metrics/session-metric-collector/remove-session-metric-collector.js new file mode 100644 index 00000000..accad826 --- /dev/null +++ b/js/server-configuration/metrics/session-metric-collector/remove-session-metric-collector.js @@ -0,0 +1,49 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function metricsRemoveSessionMetricCollector() { + /// tag::metrics_session_metric_collector_remove[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const sessionMetricCollector = diffusion.newSessionMetricCollectorBuilder() + .exportToPrometheus(false) + .maximumGroups(10) + .removeMetricsWithNoMatches(true) + .groupByProperty('$Location') + .create('Session Metric Collector 1', '$Principal is "control"'); + await session.metrics.putSessionMetricCollector(sessionMetricCollector); + /// tag::log + const sessionMetricCollectors1 = await session.metrics.listSessionMetricCollectors(); + expect(sessionMetricCollectors1.collectors.length).toBe(1); + expect(sessionMetricCollectors1.collectors[0].name).toBe('Session Metric Collector 1'); + /// end::log + + await session.metrics.removeSessionMetricCollector('Session Metric Collector 1'); + /// tag::log + const sessionMetricCollectors2 = await session.metrics.listSessionMetricCollectors(); + expect(sessionMetricCollectors2.collectors.length).toBe(0); + /// end::log + + await session.closeSession(); + /// end::metrics_session_metric_collector_remove[] +} diff --git a/js/server-configuration/metrics/topic-metric-collector/list-topic-metric-collectors.js b/js/server-configuration/metrics/topic-metric-collector/list-topic-metric-collectors.js new file mode 100644 index 00000000..9d4897a1 --- /dev/null +++ b/js/server-configuration/metrics/topic-metric-collector/list-topic-metric-collectors.js @@ -0,0 +1,61 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function metricsListTopicMetricCollectors() { + /// tag::metrics_topic_metric_collector_list[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const topicMetricCollector1 = diffusion.newTopicMetricCollectorBuilder() + .exportToPrometheus(false) + .maximumGroups(10) + .groupByTopicType(true) + .groupByTopicView(true) + .groupByPathPrefixParts(15) + .create('Topic Metric Collector 1', '?my/topic//'); + const topicMetricCollector2 = diffusion.newTopicMetricCollectorBuilder() + .exportToPrometheus(false) + .maximumGroups(10) + .groupByTopicType(true) + .groupByTopicView(true) + .groupByPathPrefixParts(15) + .create('Topic Metric Collector 2', '?my/topic//'); + await Promise.all([ + session.metrics.putTopicMetricCollector(topicMetricCollector1), + session.metrics.putTopicMetricCollector(topicMetricCollector2) + ]); + + const topicMetricCollectors = await session.metrics.listTopicMetricCollectors(); + for (const collector of topicMetricCollectors.collectors) { + console.log(`${collector.name}: ${collector.topicSelector} (${collector.maximumGroups}, ` + + `${collector.exportToPrometheus}, ${collector.groupByTopicType}, ${collector.groupByTopicView}, ${collector.groupByPathPrefixParts})`); + } + /// tag::log + expect(topicMetricCollectors.collectors.length).toBe(2); + expect(topicMetricCollectors.collectors.map((c) => c.name)).toEqual(jasmine.arrayContaining( + ['Topic Metric Collector 1', 'Topic Metric Collector 2'] + )); + /// end::log + + await session.closeSession(); + /// end::metrics_topic_metric_collector_list[] +} diff --git a/js/server-configuration/metrics/topic-metric-collector/put-topic-metric-collector.js b/js/server-configuration/metrics/topic-metric-collector/put-topic-metric-collector.js new file mode 100644 index 00000000..cb44552c --- /dev/null +++ b/js/server-configuration/metrics/topic-metric-collector/put-topic-metric-collector.js @@ -0,0 +1,44 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function metricsPutTopicMetricCollector() { + /// tag::metrics_topic_metric_collector_put[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const topicMetricCollector = diffusion.newTopicMetricCollectorBuilder() + .exportToPrometheus(false) + .maximumGroups(10) + .groupByTopicType(true) + .groupByTopicView(true) + .groupByPathPrefixParts(15) + .create('Topic Metric Collector 1', '?my/topic//'); + await session.metrics.putTopicMetricCollector(topicMetricCollector); + /// tag::log + const topicMetricCollectors = await session.metrics.listTopicMetricCollectors(); + expect(topicMetricCollectors.collectors.length).toBe(1); + expect(topicMetricCollectors.collectors[0].name).toBe('Topic Metric Collector 1'); + /// end::log + + await session.closeSession(); + /// end::metrics_topic_metric_collector_put[] +} diff --git a/js/server-configuration/metrics/topic-metric-collector/remove-topic-metric-collector.js b/js/server-configuration/metrics/topic-metric-collector/remove-topic-metric-collector.js new file mode 100644 index 00000000..a536d65a --- /dev/null +++ b/js/server-configuration/metrics/topic-metric-collector/remove-topic-metric-collector.js @@ -0,0 +1,50 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function metricsRemoveTopicMetricCollector() { + /// tag::metrics_topic_metric_collector_remove[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const topicMetricCollector = diffusion.newTopicMetricCollectorBuilder() + .exportToPrometheus(false) + .maximumGroups(10) + .groupByTopicType(true) + .groupByTopicView(true) + .groupByPathPrefixParts(15) + .create('Topic Metric Collector 1', '?my/topic//'); + await session.metrics.putTopicMetricCollector(topicMetricCollector); + /// tag::log + const topicMetricCollectors1 = await session.metrics.listTopicMetricCollectors(); + expect(topicMetricCollectors1.collectors.length).toBe(1); + expect(topicMetricCollectors1.collectors[0].name).toBe('Topic Metric Collector 1'); + /// end::log + + await session.metrics.removeTopicMetricCollector('Topic Metric Collector 1'); + /// tag::log + const topicMetricCollectors2 = await session.metrics.listTopicMetricCollectors(); + expect(topicMetricCollectors2.collectors.length).toBe(0); + /// end::log + + await session.closeSession(); + /// end::metrics_topic_metric_collector_remove[] +} diff --git a/js/server-configuration/remote-servers/check-remote-server.js b/js/server-configuration/remote-servers/check-remote-server.js new file mode 100644 index 00000000..d337cb4d --- /dev/null +++ b/js/server-configuration/remote-servers/check-remote-server.js @@ -0,0 +1,96 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester } = require('../../../../test/util'); +/// end::log + +export async function remoteServersCheck() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Remote Server 1 (ws://new.server.url.com): connection failed (Feature \'REMOTE_CONNECTIONS\' is not licensed.)', + 'Remote Server 2 (ws://another.server.url.com): connection failed (Feature \'REMOTE_CONNECTIONS\' is not licensed.)' + ]]); + /// end::log + /// tag::remote_servers_check[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const builder = diffusion.newRemoteServerBuilder(diffusion.RemoteServerType.SECONDARY_INITIATOR) + .principal('admin') + .credentials('password') + .connectionOptions({ + [diffusion.ConnectionOption.RECONNECTION_TIMEOUT] : '120000', + [diffusion.ConnectionOption.MAXIMUM_QUEUE_SIZE]: '1000', + [diffusion.ConnectionOption.CONNECTION_TIMEOUT]: '15000' + }) + .missingTopicNotificationFilter('?abc'); + await session.remoteServers.createRemoteServer( + builder.build('Remote Server 1', 'ws://new.server.url.com') + ); + builder.reset() + .principal('control') + .credentials('password') + .connectionOptions({ + [diffusion.ConnectionOption.RECONNECTION_TIMEOUT] : '60000', + [diffusion.ConnectionOption.MAXIMUM_QUEUE_SIZE]: '10000', + [diffusion.ConnectionOption.CONNECTION_TIMEOUT]: '5000' + }); + await session.remoteServers.createRemoteServer( + builder.build('Remote Server 2', 'ws://another.server.url.com') + ); + + const remoteServers = await session.remoteServers.listRemoteServers(); + for (const remoteServer of remoteServers) { + const status = await session.remoteServers.checkRemoteServer(remoteServer.name); + let statusMessage = ''; + switch (status.connectionState) { + case diffusion.ConnectionState.INACTIVE: + statusMessage = 'inactive'; + break; + case diffusion.ConnectionState.CONNECTED: + statusMessage = 'connected'; + break; + case diffusion.ConnectionState.MISSING: + statusMessage = 'missing'; + break; + case diffusion.ConnectionState.FAILED: + statusMessage = `connection failed (${status.failureMessage})`; + break; + case diffusion.ConnectionState.RETRYING: + statusMessage = `retrying (${status.failureMessage})`; + break; + } + console.log(`${remoteServer.name} (${remoteServer.url}): ${statusMessage}`); + /// tag::log + check.log(`${remoteServer.name} (${remoteServer.url}): ${statusMessage}`); + /// end::log + } + + // Clean up + await session.remoteServers.removeRemoteServer('Remote Server 1'); + await session.remoteServers.removeRemoteServer('Remote Server 2'); + await session.closeSession(); + /// end::remote_servers_check[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/server-configuration/remote-servers/create-primary-initiator.js b/js/server-configuration/remote-servers/create-primary-initiator.js new file mode 100644 index 00000000..e06e84bc --- /dev/null +++ b/js/server-configuration/remote-servers/create-primary-initiator.js @@ -0,0 +1,47 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function remoteServersCreatePrimaryInitiator() { + /// tag::remote_servers_create_primary_initiator[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const definition = diffusion.newRemoteServerBuilder(diffusion.RemoteServerType.PRIMARY_INITIATOR) + .retryDelay(2500) + .build( + 'Remote Server 1', + ['ws://new.server.url.com:8080', 'ws://new.server.url.com:8081', 'ws://new.server.url.com:8082'], + 'High Volume Connector' + ); + await session.remoteServers.createRemoteServer(definition); + /// tag::log + const remoteServers = await session.remoteServers.listRemoteServers(); + expect(remoteServers.length).toBe(1); + expect(remoteServers[0].name).toBe('Remote Server 1'); + /// end::log + + + // Clean up + await session.remoteServers.removeRemoteServer('Remote Server 1'); + await session.closeSession(); + /// end::remote_servers_create_primary_initiator[] +} diff --git a/js/server-configuration/remote-servers/create-secondary-acceptor.js b/js/server-configuration/remote-servers/create-secondary-acceptor.js new file mode 100644 index 00000000..8f2daf63 --- /dev/null +++ b/js/server-configuration/remote-servers/create-secondary-acceptor.js @@ -0,0 +1,49 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function remoteServersCreateSecondaryAcceptor() { + /// tag::remote_servers_create_secondary_acceptor[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const definition = diffusion.newRemoteServerBuilder(diffusion.RemoteServerType.SECONDARY_ACCEPTOR) + .principal('') + .credentials(null) + .connectionOptions({ + [diffusion.ConnectionOption.WRITE_TIMEOUT] : '2000', + [diffusion.ConnectionOption.MAXIMUM_QUEUE_SIZE]: '1000', + [diffusion.ConnectionOption.CONNECTION_TIMEOUT]: '15000' + }) + .missingTopicNotificationFilter('?abc') + .build('Remote Server 1', 'ws://new.server.url.com'); + await session.remoteServers.createRemoteServer(definition); + /// tag::log + const remoteServers = await session.remoteServers.listRemoteServers(); + expect(remoteServers.length).toBe(1); + expect(remoteServers[0].name).toBe('Remote Server 1'); + /// end::log + + // Clean up + await session.remoteServers.removeRemoteServer('Remote Server 1'); + await session.closeSession(); + /// end::remote_servers_create_secondary_acceptor[] +} diff --git a/js/server-configuration/remote-servers/create-secondary-initiator.js b/js/server-configuration/remote-servers/create-secondary-initiator.js new file mode 100644 index 00000000..41dc5f8d --- /dev/null +++ b/js/server-configuration/remote-servers/create-secondary-initiator.js @@ -0,0 +1,49 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function remoteServersCreateSecondaryInitiator() { + /// tag::remote_servers_create_secondary_initiator[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const definition = diffusion.newRemoteServerBuilder(diffusion.RemoteServerType.SECONDARY_INITIATOR) + .principal('admin') + .credentials('password') + .connectionOptions({ + [diffusion.ConnectionOption.RECONNECTION_TIMEOUT] : '120000', + [diffusion.ConnectionOption.MAXIMUM_QUEUE_SIZE]: '1000', + [diffusion.ConnectionOption.CONNECTION_TIMEOUT]: '15000' + }) + .missingTopicNotificationFilter('?abc') + .build('Remote Server 1', 'ws://new.server.url.com'); + await session.remoteServers.createRemoteServer(definition); + /// tag::log + const remoteServers = await session.remoteServers.listRemoteServers(); + expect(remoteServers.length).toBe(1); + expect(remoteServers[0].name).toBe('Remote Server 1'); + /// end::log + + // Clean up + await session.remoteServers.removeRemoteServer('Remote Server 1'); + await session.closeSession(); + /// end::remote_servers_create_secondary_initiator[] +} diff --git a/js/server-configuration/remote-servers/list-remote-servers.js b/js/server-configuration/remote-servers/list-remote-servers.js new file mode 100644 index 00000000..339105ae --- /dev/null +++ b/js/server-configuration/remote-servers/list-remote-servers.js @@ -0,0 +1,77 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester } = require('../../../../test/util'); +/// end::log + +export async function remoteServersList() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Remote Server 1 (ws://new.server.url.com)', + 'Remote Server 2 (ws://another.server.url.com)' + ]]); + /// end::log + /// tag::remote_servers_list[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const builder = diffusion.newRemoteServerBuilder(diffusion.RemoteServerType.SECONDARY_INITIATOR) + .principal('admin') + .credentials('password') + .connectionOptions({ + [diffusion.ConnectionOption.RECONNECTION_TIMEOUT] : '120000', + [diffusion.ConnectionOption.MAXIMUM_QUEUE_SIZE]: '1000', + [diffusion.ConnectionOption.CONNECTION_TIMEOUT]: '15000' + }) + .missingTopicNotificationFilter('?abc'); + await session.remoteServers.createRemoteServer( + builder.build('Remote Server 1', 'ws://new.server.url.com') + ); + builder.reset() + .principal('control') + .credentials('password') + .connectionOptions({ + [diffusion.ConnectionOption.RECONNECTION_TIMEOUT] : '6000', + [diffusion.ConnectionOption.MAXIMUM_QUEUE_SIZE]: '10000', + [diffusion.ConnectionOption.CONNECTION_TIMEOUT]: '5000' + }); + await session.remoteServers.createRemoteServer( + builder.build('Remote Server 2', 'ws://another.server.url.com') + ); + + const remoteServers = await session.remoteServers.listRemoteServers(); + for (const remoteServer of remoteServers) { + console.log(`${remoteServer.name} (${remoteServer.url})`); + /// tag::log + check.log(`${remoteServer.name} (${remoteServer.url})`); + /// end::log + } + + // Clean up + await session.remoteServers.removeRemoteServer('Remote Server 1'); + await session.remoteServers.removeRemoteServer('Remote Server 2'); + await session.closeSession(); + /// end::remote_servers_list[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/server-configuration/remote-servers/remove-remote-server.js b/js/server-configuration/remote-servers/remove-remote-server.js new file mode 100644 index 00000000..6013aaa2 --- /dev/null +++ b/js/server-configuration/remote-servers/remove-remote-server.js @@ -0,0 +1,53 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function remoteServersRemove() { + /// tag::remote_servers_remove[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const definition = diffusion.newRemoteServerBuilder(diffusion.RemoteServerType.SECONDARY_INITIATOR) + .principal('admin') + .credentials('password') + .connectionOptions({ + [diffusion.ConnectionOption.RECONNECTION_TIMEOUT] : '120000', + [diffusion.ConnectionOption.MAXIMUM_QUEUE_SIZE]: '1000', + [diffusion.ConnectionOption.CONNECTION_TIMEOUT]: '15000' + }) + .missingTopicNotificationFilter('?abc') + .build('Remote Server 1', 'ws://new.server.url.com'); + await session.remoteServers.createRemoteServer(definition); + /// tag::log + const remoteServers1 = await session.remoteServers.listRemoteServers(); + expect(remoteServers1.length).toBe(1); + expect(remoteServers1[0].name).toBe('Remote Server 1'); + /// end::log + + await session.remoteServers.removeRemoteServer('Remote Server 1'); + /// tag::log + const remoteServers2 = await session.remoteServers.listRemoteServers(); + expect(remoteServers2.length).toBe(0); + /// end::log + + await session.closeSession(); + /// end::remote_servers_remove[] +} diff --git a/js/server-configuration/security-control/define-roles-hierarchy.js b/js/server-configuration/security-control/define-roles-hierarchy.js new file mode 100644 index 00000000..998313f3 --- /dev/null +++ b/js/server-configuration/security-control/define-roles-hierarchy.js @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function securityControlDefineRolesHierarchy() { + /// tag::security_control_define_roles_hierarchy[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const securityScript = session.security.securityScriptBuilder() + .setRoleIncludes('OPERATOR', [ 'CLIENT', 'CLIENT_CONTROL' ]) + .build(); + console.log('OPERATOR now includes CLIENT and CLIENT_CONTROL roles.'); + console.log(securityScript); + await session.security.updateSecurityStore(securityScript); + + // Clean up + const securityScriptCleanup = session.security.securityScriptBuilder() + .setRoleIncludes('OPERATOR', [ 'CLIENT' ]) + .build(); + await session.security.updateSecurityStore(securityScriptCleanup); + await session.closeSession(); + /// end::security_control_define_roles_hierarchy[] +} diff --git a/js/server-configuration/security-control/deisolate-path.js b/js/server-configuration/security-control/deisolate-path.js new file mode 100644 index 00000000..d7faae30 --- /dev/null +++ b/js/server-configuration/security-control/deisolate-path.js @@ -0,0 +1,44 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function securityControlDeisolatePath() { + /// tag::security_control_deisolate_path[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const securityScript1 = session.security.securityScriptBuilder() + .isolatePath('my/topic/path') + .build(); + console.log('Isolating my/topic/path permissions from parent and default path permissions.'); + console.log(securityScript1); + await session.security.updateSecurityStore(securityScript1); + + const securityScript2 = session.security.securityScriptBuilder() + .deisolatePath('my/topic/path') + .build(); + console.log('Removing my/topic/path permission isolation.'); + console.log(securityScript2); + await session.security.updateSecurityStore(securityScript2); + + await session.closeSession(); + /// end::security_control_deisolate_path[] +} diff --git a/js/server-configuration/security-control/isolate-path.js b/js/server-configuration/security-control/isolate-path.js new file mode 100644 index 00000000..83c41a36 --- /dev/null +++ b/js/server-configuration/security-control/isolate-path.js @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function securityControlIsolatePath() { + /// tag::security_control_isolate_path[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const securityScript = session.security.securityScriptBuilder() + .isolatePath('my/topic/path') + .build(); + console.log('Isolating my/topic/path permissions from parent and default path permissions.'); + console.log(securityScript); + await session.security.updateSecurityStore(securityScript); + + // Clean up + const securityScriptCleanup = session.security.securityScriptBuilder() + .deisolatePath('my/topic/path') + .build(); + await session.security.updateSecurityStore(securityScriptCleanup); + await session.closeSession(); + /// end::security_control_isolate_path[] +} diff --git a/js/server-configuration/security-control/remove-path-permissions.js b/js/server-configuration/security-control/remove-path-permissions.js new file mode 100644 index 00000000..aff435d8 --- /dev/null +++ b/js/server-configuration/security-control/remove-path-permissions.js @@ -0,0 +1,44 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function securityControlRemovePathPermissions() { + /// tag::security_control_remove_path_permissions[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const securityScript1 = session.security.securityScriptBuilder() + .setPathPermissions('CLIENT','my/topic/path', [ 'UPDATE_TOPIC', 'MODIFY_TOPIC' ]) + .build(); + console.log('Allowing Role CLIENT to update and modify my/topic/path.'); + console.log(securityScript1); + await session.security.updateSecurityStore(securityScript1); + + const securityScript2 = session.security.securityScriptBuilder() + .removePathPermissions('CLIENT','my/topic/path') + .build(); + console.log('Removing path permissions for Role CLIENT at my/topic/path.'); + console.log(securityScript2); + await session.security.updateSecurityStore(securityScript2); + + await session.closeSession(); + /// end::security_control_remove_path_permissions[] +} diff --git a/js/server-configuration/security-control/restrict-role.js b/js/server-configuration/security-control/restrict-role.js new file mode 100644 index 00000000..3fb70aec --- /dev/null +++ b/js/server-configuration/security-control/restrict-role.js @@ -0,0 +1,43 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function securityControlRestrictRole() { + /// tag::security_control_restrict_role_edit_permissions[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const securityScript = session.security.securityScriptBuilder() + .setRoleLockedByPrincipal('EXAMPLE', 'admin') + .build(); + console.log('EXAMPLE role has been locked by admin principal.'); + console.log(securityScript); + await session.security.updateSecurityStore(securityScript); + + // Clean up + const securityScriptCleanup = session.security.authenticationScriptBuilder() + .removePrincipal('admin') + .addPrincipal('admin', 'password', ['ADMINISTRATOR']) + .build(); + await session.security.updateAuthenticationStore(securityScriptCleanup); + await session.closeSession(); + /// end::security_control_restrict_role_edit_permissions[] +} diff --git a/js/server-configuration/security-control/set-default-path-permissions.js b/js/server-configuration/security-control/set-default-path-permissions.js new file mode 100644 index 00000000..e64b3d90 --- /dev/null +++ b/js/server-configuration/security-control/set-default-path-permissions.js @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function securityControlSetDefaultPathPermissions() { + /// tag::security_control_set_default_path_permissions[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const securityScript = session.security.securityScriptBuilder() + .setDefaultPathPermissions('CLIENT', [ 'UPDATE_TOPIC', 'MODIFY_TOPIC' ]) + .build(); + console.log('Adding the following permissions to the default path permisions of Role CLIENT: MODIFY_TOPIC and UPDATE_TOPIC'); + console.log(securityScript); + await session.security.updateSecurityStore(securityScript); + + // Clean up + const securityScriptCleanup = session.security.securityScriptBuilder() + .setDefaultPathPermissions('CLIENT', [ 'SELECT_TOPIC', 'READ_TOPIC', 'SEND_TO_MESSAGE_HANDLER' ]) + .build(); + await session.security.updateSecurityStore(securityScriptCleanup); + await session.closeSession(); + /// end::security_control_set_default_path_permissions[] +} diff --git a/js/server-configuration/security-control/set-default-roles-for-anonymous-sessions.js b/js/server-configuration/security-control/set-default-roles-for-anonymous-sessions.js new file mode 100644 index 00000000..9c8c314d --- /dev/null +++ b/js/server-configuration/security-control/set-default-roles-for-anonymous-sessions.js @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function securityControlSetDefaultRolesForAnonymousSessions() { + /// tag::security_control_set_default_roles_for_anonymous_sessions[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const securityScript = session.security.securityScriptBuilder() + .setRolesForAnonymousSessions([ 'AUTHENTICATION_HANDLER' ]) + .build(); + console.log('All anonymous sessions now have AUTHENTICATION_HANDLER priviledges.'); + console.log(securityScript); + await session.security.updateSecurityStore(securityScript); + + // Clean up + const securityScriptCleanup = session.security.securityScriptBuilder() + .setRolesForAnonymousSessions([ 'CLIENT' ]) + .build(); + await session.security.updateSecurityStore(securityScriptCleanup); + await session.closeSession(); + /// end::security_control_set_default_roles_for_anonymous_sessions[] +} diff --git a/js/server-configuration/security-control/set-default-roles-for-named-sessions.js b/js/server-configuration/security-control/set-default-roles-for-named-sessions.js new file mode 100644 index 00000000..508236dd --- /dev/null +++ b/js/server-configuration/security-control/set-default-roles-for-named-sessions.js @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function securityControlSetDefaultRolesForNamedSessions() { + /// tag::security_control_set_default_roles_for_named_sessions[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const securityScript = session.security.securityScriptBuilder() + .setRolesForNamedSessions([ 'ADMINISTRATOR' ]) + .build(); + console.log('All named sessions now have ADMINISTRATOR priviledges.'); + console.log(securityScript); + await session.security.updateSecurityStore(securityScript); + + // Clean up + const securityScriptCleanup = session.security.securityScriptBuilder() + .setRolesForNamedSessions([ 'CLIENT' ]) + .build(); + await session.security.updateSecurityStore(securityScriptCleanup); + await session.closeSession(); + /// end::security_control_set_default_roles_for_named_sessions[] +} diff --git a/js/server-configuration/security-control/set-global-permissions.js b/js/server-configuration/security-control/set-global-permissions.js new file mode 100644 index 00000000..fcdc0c77 --- /dev/null +++ b/js/server-configuration/security-control/set-global-permissions.js @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function securityControlSetGlobalPermissions() { + /// tag::security_control_set_global_permissions[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const securityScript = session.security.securityScriptBuilder() + .setGlobalPermissions('CLIENT', [ 'VIEW_SERVER', 'VIEW_SESSION' ]) + .build(); + console.log('Adding the following permissions to the global permissions of Role CLIENT: VIEW_SERVER and VIEW_SESSION'); + console.log(securityScript); + await session.security.updateSecurityStore(securityScript); + + // Clean up + const securityScriptCleanup = session.security.securityScriptBuilder() + .setGlobalPermissions('CLIENT', []) + .build(); + await session.security.updateSecurityStore(securityScriptCleanup); + await session.closeSession(); + /// end::security_control_set_global_permissions[] +} diff --git a/js/server-configuration/security-control/set-path-permissions.js b/js/server-configuration/security-control/set-path-permissions.js new file mode 100644 index 00000000..d7fcfbc3 --- /dev/null +++ b/js/server-configuration/security-control/set-path-permissions.js @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function securityControlSetPathPermissions() { + /// tag::security_control_set_path_permissions[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const securityScript = session.security.securityScriptBuilder() + .setPathPermissions('CLIENT','my/topic/path', [ 'UPDATE_TOPIC', 'MODIFY_TOPIC' ]) + .build(); + console.log('Allowing Role CLIENT to update and modify my/topic/path.'); + console.log(securityScript); + await session.security.updateSecurityStore(securityScript); + + // Clean up + const securityScriptCleanup = session.security.securityScriptBuilder() + .removePathPermissions('CLIENT', 'my/topic/path') + .build(); + await session.security.updateSecurityStore(securityScriptCleanup); + await session.closeSession(); + /// end::security_control_set_path_permissions[] +} diff --git a/js/server-configuration/system-authentication-control/abstain-anonymous-connections.js b/js/server-configuration/system-authentication-control/abstain-anonymous-connections.js new file mode 100644 index 00000000..fd07acd6 --- /dev/null +++ b/js/server-configuration/system-authentication-control/abstain-anonymous-connections.js @@ -0,0 +1,83 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function abstainAnonymousConnections() { + /// tag::system_authentication_control_abstain_anonymous_connections[] + // Connect to the server. + const session1 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const authenticationScript = session1.security.authenticationScriptBuilder() + .abstainAnonymousConnections() + .build(); + await session1.security.updateAuthenticationStore(authenticationScript); + + const session2 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'control', + credentials: 'password' + }); + const authenticator = { + authenticate: ( + principal, + credentials, + sessionProperties, + proposedPorperties, + callback + ) => { + if (credentials === null) { + callback.deny(); + } else { + callback.allow(); + } + }, + onClose: () => {}, + onError: () => {} + }; + + await session2.security.setAuthenticator('after-system-handler', authenticator); + + try { + await connect({ + host: 'localhost', + port: 8080 + }); + /// tag::log + fail('Anonymous connection should be denied'); + /// end::log + } + catch (err) { + // expected to fail + console.error('Could not connect', err.message); + } + + /// tag::log + const restoreScript = session1.security.authenticationScriptBuilder() + .denyAnonymousConnections() + .allowAnonymousConnections(['CLIENT']) + .build(); + await session1.security.updateAuthenticationStore(restoreScript); + /// end::log + await session1.closeSession(); + await session2.closeSession(); + /// end::system_authentication_control_abstain_anonymous_connections[] +} diff --git a/js/server-configuration/system-authentication-control/add-locked-principal.js b/js/server-configuration/system-authentication-control/add-locked-principal.js new file mode 100644 index 00000000..de5debf0 --- /dev/null +++ b/js/server-configuration/system-authentication-control/add-locked-principal.js @@ -0,0 +1,41 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function addLockedPrincipal() { + /// tag::system_authentication_control_add_locked_principal[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const authenticationScript = session.security.authenticationScriptBuilder() + .addPrincipal('super_user', 'password12345', [ 'ADMINISTRATOR' ], 'admin') + .build(); + await session.security.updateAuthenticationStore(authenticationScript); + + /// tag::log + const restoreScript = session.security.authenticationScriptBuilder() + .removePrincipal('super_user') + .build(); + await session.security.updateAuthenticationStore(restoreScript); + /// end::log + await session.closeSession(); + /// end::system_authentication_control_add_locked_principal[] +} diff --git a/js/server-configuration/system-authentication-control/add-principal.js b/js/server-configuration/system-authentication-control/add-principal.js new file mode 100644 index 00000000..5b271e75 --- /dev/null +++ b/js/server-configuration/system-authentication-control/add-principal.js @@ -0,0 +1,41 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function addPrincipal() { + /// tag::system_authentication_control_add_principal[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const authenticationScript = session.security.authenticationScriptBuilder() + .addPrincipal('super_user', 'password12345', [ 'ADMINISTRATOR' ]) + .build(); + await session.security.updateAuthenticationStore(authenticationScript); + + /// tag::log + const restoreScript = session.security.authenticationScriptBuilder() + .removePrincipal('super_user') + .build(); + await session.security.updateAuthenticationStore(restoreScript); + /// end::log + await session.closeSession(); + /// end::system_authentication_control_add_principal[] +} diff --git a/js/server-configuration/system-authentication-control/allow-anonymous-connections.js b/js/server-configuration/system-authentication-control/allow-anonymous-connections.js new file mode 100644 index 00000000..e77ecf59 --- /dev/null +++ b/js/server-configuration/system-authentication-control/allow-anonymous-connections.js @@ -0,0 +1,49 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function allowAnonymousConnections() { + /// tag::system_authentication_control_allow_anonymous_connections[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const authenticationScript = session.security.authenticationScriptBuilder() + .allowAnonymousConnections() + .build(); + await session.security.updateAuthenticationStore(authenticationScript); + + const anonymous = await diffusion.connect({ + host: 'localhost', + port: 8080 + }); + console.log(`Anonymous session has been established: ${anonymous.sessionId}`); + + /// tag::log + const restoreScript = session.security.authenticationScriptBuilder() + .denyAnonymousConnections() + .allowAnonymousConnections(['CLIENT']) + .build(); + await session.security.updateAuthenticationStore(restoreScript); + /// end::log + await anonymous.closeSession(); + await session.closeSession(); + /// end::system_authentication_control_allow_anonymous_connections[] +} diff --git a/js/server-configuration/system-authentication-control/assign-roles.js b/js/server-configuration/system-authentication-control/assign-roles.js new file mode 100644 index 00000000..31a2cc96 --- /dev/null +++ b/js/server-configuration/system-authentication-control/assign-roles.js @@ -0,0 +1,46 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function assignRoles() { + /// tag::system_authentication_control_assign_roles[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const authenticationScript1 = session.security.authenticationScriptBuilder() + .addPrincipal('super_user', 'password12345', [ 'CLIENT' ]) + .build(); + await session.security.updateAuthenticationStore(authenticationScript1); + + const authenticationScript2 = session.security.authenticationScriptBuilder() + .assignRoles('super_user', [ 'ADMINISTRATOR' ]) + .build(); + await session.security.updateAuthenticationStore(authenticationScript2); + + /// tag::log + const restoreScript = session.security.authenticationScriptBuilder() + .removePrincipal('super_user') + .build(); + await session.security.updateAuthenticationStore(restoreScript); + /// end::log + await session.closeSession(); + /// end::system_authentication_control_assign_roles[] +} diff --git a/js/server-configuration/system-authentication-control/change-password.js b/js/server-configuration/system-authentication-control/change-password.js new file mode 100644 index 00000000..5211d1c0 --- /dev/null +++ b/js/server-configuration/system-authentication-control/change-password.js @@ -0,0 +1,46 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function changePassword() { + /// tag::system_authentication_control_change_password[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const authenticationScript1 = session.security.authenticationScriptBuilder() + .addPrincipal('super_user', 'password12345', [ 'CLIENT' ]) + .build(); + await session.security.updateAuthenticationStore(authenticationScript1); + + const authenticationScript2 = session.security.authenticationScriptBuilder() + .setPassword('super_user', 'hunter2') + .build(); + await session.security.updateAuthenticationStore(authenticationScript2); + + /// tag::log + const restoreScript = session.security.authenticationScriptBuilder() + .removePrincipal('super_user') + .build(); + await session.security.updateAuthenticationStore(restoreScript); + /// end::log + await session.closeSession(); + /// end::system_authentication_control_change_password[] +} diff --git a/js/server-configuration/system-authentication-control/deny-anonymous-connections.js b/js/server-configuration/system-authentication-control/deny-anonymous-connections.js new file mode 100644 index 00000000..8baf0c27 --- /dev/null +++ b/js/server-configuration/system-authentication-control/deny-anonymous-connections.js @@ -0,0 +1,55 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function denyAnonymousConnections() { + /// tag::system_authentication_control_deny_anonymous_connections[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const authenticationScript = session.security.authenticationScriptBuilder() + .denyAnonymousConnections() + .build(); + await session.security.updateAuthenticationStore(authenticationScript); + + try { + await connect({ + host: 'localhost', + port: 8080 + }); + /// tag::log + fail('Anonymous connection should be denied'); + /// end::log + } + catch (err) { + // expected to fail + console.error('Could not connect', err.message); + } + + /// tag::log + const restoreScript = session.security.authenticationScriptBuilder() + .allowAnonymousConnections(['CLIENT']) + .build(); + await session.security.updateAuthenticationStore(restoreScript); + /// end::log + await session.closeSession(); + /// end::system_authentication_control_deny_anonymous_connections[] +} diff --git a/js/server-configuration/system-authentication-control/ignore-client-proposed-property.js b/js/server-configuration/system-authentication-control/ignore-client-proposed-property.js new file mode 100644 index 00000000..a9b6740b --- /dev/null +++ b/js/server-configuration/system-authentication-control/ignore-client-proposed-property.js @@ -0,0 +1,90 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function ignoreClientProposedProperty() { + /// tag::system_authentication_control_ignore_client_proposed_property[] + // Connect to the server. + const session1 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const authenticationScript1 = session1.security.authenticationScriptBuilder() + .ignoreClientProposedProperty('Rubble') + .trustClientProposedPropertyMatches('Flintstone', '.*_Flintstone') + .build(); + await session1.security.updateAuthenticationStore(authenticationScript1); + + const session2 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'control', + credentials: 'password', + properties: { + 'Rubble': 'Barney_Rubble' + } + }); + + const properties2 = await session1.clients.getSessionProperties( + session2.sessionId, + diffusion.clients.PropertyKeys.ALL_PROPERTIES + ); + console.log('Received the following session properties:'); + for (const key of Object.keys(properties2)) { + console.log(` ${key}: ${properties2[key]}`); + } + /// tag::log + expect(properties2['Rubble']).toBeUndefined(); + /// end::log + + await session2.closeSession(); + + const session3 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'control', + credentials: 'password', + properties: { + 'Flintstone': 'Fred_Flintstone' + } + }); + + const properties3 = await session1.clients.getSessionProperties( + session3.sessionId, + diffusion.clients.PropertyKeys.ALL_PROPERTIES + ); + console.log('Received the following session properties:'); + for (const key of Object.keys(properties3)) { + console.log(` ${key}: ${properties3[key]}`); + } + /// tag::log + expect(properties3['Flintstone']).toBe('Fred_Flintstone'); + /// end::log + + await session3.closeSession(); + + /// tag::log + const restoreScript = session1.security.authenticationScriptBuilder() + .ignoreClientProposedProperty('Flintstone') + .build(); + await session1.security.updateAuthenticationStore(restoreScript); + /// end::log + await session1.closeSession(); + /// end::system_authentication_control_ignore_client_proposed_property[] +} diff --git a/js/server-configuration/system-authentication-control/remove-principal.js b/js/server-configuration/system-authentication-control/remove-principal.js new file mode 100644 index 00000000..5be83cf9 --- /dev/null +++ b/js/server-configuration/system-authentication-control/remove-principal.js @@ -0,0 +1,40 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function removePrincipal() { + /// tag::system_authentication_control_remove_principal[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const authenticationScript1 = session.security.authenticationScriptBuilder() + .addPrincipal('super_user', 'password12345', [ 'ADMINISTRATOR' ]) + .build(); + await session.security.updateAuthenticationStore(authenticationScript1); + + const authenticationScript2 = session.security.authenticationScriptBuilder() + .removePrincipal('super_user') + .build(); + await session.security.updateAuthenticationStore(authenticationScript2); + + await session.closeSession(); + /// end::system_authentication_control_remove_principal[] +} diff --git a/js/server-configuration/system-authentication-control/trust-client-proposed-property-in.js b/js/server-configuration/system-authentication-control/trust-client-proposed-property-in.js new file mode 100644 index 00000000..60eba672 --- /dev/null +++ b/js/server-configuration/system-authentication-control/trust-client-proposed-property-in.js @@ -0,0 +1,89 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function trustClientProposedPropertyIn() { + /// tag::system_authentication_control_trust_client_proposed_property_in[] + // Connect to the server. + const session1 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const authenticationScript1 = session1.security.authenticationScriptBuilder() + .trustClientProposedPropertyIn('Flintstone', [ 'Fred', 'Wilma', 'Pebbles' ]) + .build(); + await session1.security.updateAuthenticationStore(authenticationScript1); + + const session2 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'control', + credentials: 'password', + properties: { + 'Flintstone': 'Barney' + } + }); + + const properties2 = await session1.clients.getSessionProperties( + session2.sessionId, + diffusion.clients.PropertyKeys.ALL_PROPERTIES + ); + console.log('Received the following session properties:'); + for (const key of Object.keys(properties2)) { + console.log(` ${key}: ${properties2[key]}`); + } + /// tag::log + expect(properties2['Flintstone']).toBeUndefined(); + /// end::log + + await session2.closeSession(); + + const session3 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'control', + credentials: 'password', + properties: { + 'Flintstone': 'Fred' + } + }); + + const properties3 = await session1.clients.getSessionProperties( + session3.sessionId, + diffusion.clients.PropertyKeys.ALL_PROPERTIES + ); + console.log('Received the following session properties:'); + for (const key of Object.keys(properties3)) { + console.log(` ${key}: ${properties3[key]}`); + } + /// tag::log + expect(properties3['Flintstone']).toBe('Fred'); + /// end::log + + await session3.closeSession(); + + /// tag::log + const restoreScript = session1.security.authenticationScriptBuilder() + .ignoreClientProposedProperty('Flintstone') + .build(); + await session1.security.updateAuthenticationStore(restoreScript); + /// end::log + await session1.closeSession(); + /// end::system_authentication_control_trust_client_proposed_property_in[] +} diff --git a/js/server-configuration/system-authentication-control/trust-client-proposed-property-matches.js b/js/server-configuration/system-authentication-control/trust-client-proposed-property-matches.js new file mode 100644 index 00000000..b5e2c5d4 --- /dev/null +++ b/js/server-configuration/system-authentication-control/trust-client-proposed-property-matches.js @@ -0,0 +1,89 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function trustClientProposedPropertyMatches() { + /// tag::system_authentication_control_trust_client_proposed_property_matches[] + // Connect to the server. + const session1 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const authenticationScript1 = session1.security.authenticationScriptBuilder() + .trustClientProposedPropertyMatches('Flintstone', '.*_Flintstone') + .build(); + await session1.security.updateAuthenticationStore(authenticationScript1); + + const session2 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'control', + credentials: 'password', + properties: { + 'Flintstone': 'Barney_Rubble' + } + }); + + const properties2 = await session1.clients.getSessionProperties( + session2.sessionId, + diffusion.clients.PropertyKeys.ALL_PROPERTIES + ); + console.log('Received the following session properties:'); + for (const key of Object.keys(properties2)) { + console.log(` ${key}: ${properties2[key]}`); + } + /// tag::log + expect(properties2['Flintstone']).toBeUndefined(); + /// end::log + + await session2.closeSession(); + + const session3 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'control', + credentials: 'password', + properties: { + 'Flintstone': 'Fred_Flintstone' + } + }); + + const properties3 = await session1.clients.getSessionProperties( + session3.sessionId, + diffusion.clients.PropertyKeys.ALL_PROPERTIES + ); + console.log('Received the following session properties:'); + for (const key of Object.keys(properties3)) { + console.log(` ${key}: ${properties3[key]}`); + } + /// tag::log + expect(properties3['Flintstone']).toBe('Fred_Flintstone'); + /// end::log + + await session3.closeSession(); + + /// tag::log + const restoreScript = session1.security.authenticationScriptBuilder() + .ignoreClientProposedProperty('Flintstone') + .build(); + await session1.security.updateAuthenticationStore(restoreScript); + /// end::log + await session1.closeSession(); + /// end::system_authentication_control_trust_client_proposed_property_matches[] +} diff --git a/js/server-configuration/system-authentication-control/verify-password.js b/js/server-configuration/system-authentication-control/verify-password.js new file mode 100644 index 00000000..d7aa4668 --- /dev/null +++ b/js/server-configuration/system-authentication-control/verify-password.js @@ -0,0 +1,78 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function verifyPassword() { + /// tag::system_authentication_control_verify_password[] + // Connect to the server. + const session1 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const authenticationScript1 = session1.security.authenticationScriptBuilder() + .verifyPassword('control', 'password') + .setPassword('control', '12345') + .build(); + await session1.security.updateAuthenticationStore(authenticationScript1); + + const session2 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'control', + credentials: '12345' + }); + console.log(`Control session has been established: ${session2.sessionId}`); + await session2.closeSession(); + + const authenticationScript2 = session1.security.authenticationScriptBuilder() + .verifyPassword('control', 'this_is_not_the_right_password') + .setPassword('control', 'new_password') + .build(); + try { + await session1.security.updateAuthenticationStore(authenticationScript2); + } catch (err) { + // expected to fail + console.log('Password verification failed'); + } + + try { + await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'control', + credentials: 'new_password' + }); + /// tag::log + fail('Connection should be denied'); + /// end::log + } + catch (err) { + // expected to fail + console.error('Could not connect', err.message); + } + + /// tag::log + const restoreScript = session1.security.authenticationScriptBuilder() + .setPassword('control', 'password') + .build(); + await session1.security.updateAuthenticationStore(restoreScript); + /// end::log + await session1.closeSession(); + /// end::system_authentication_control_verify_password[] +} diff --git a/js/session-management/authentication-control.js b/js/session-management/authentication-control.js new file mode 100644 index 00000000..48452157 --- /dev/null +++ b/js/session-management/authentication-control.js @@ -0,0 +1,117 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester } = require('../../../test/util'); +/// end::log + +export async function sessionManagementAuthenticationControl() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Rejecting anonymous connection attempt.'], + ['Anonymous connection failed.'], + ['Rejecting connection attempt from principal not statring with diffusion_.'], + ['control connection failed.'], + ['Accepting connection attempt from principal starting with diffusion_.'], + ['diffusion_control connection established.'] + ]); + /// end::log + /// tag::session_management_authentication_control[] + // Connect to the server. + const session1 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'control', + credentials: 'password' + }); + + const authenticator = { + authenticate: (principal, credentials, sessionProperties, proposedPorperties, callback) => { + if (principal === '') { + console.log('Anonymous connection attempt detected. Session establishment rejected.'); + /// tag::log + check.log('Rejecting anonymous connection attempt.'); + /// end::log + callback.deny(); + } else if (principal.startsWith('diffusion_')) { + console.log('Principal begins with diffusion_ prefix. Session establishment accepted.'); + /// tag::log + check.log('Accepting connection attempt from principal starting with diffusion_.'); + /// end::log + callback.allow(); + } else { + console.log('Principal does not begin with diffusion_ prefix. Session establishment rejected.'); + /// tag::log + check.log('Rejecting connection attempt from principal not statring with diffusion_.'); + /// end::log + callback.deny(); + } + }, + onClose: () => {}, + onError: () => {} + }; + await session1.security.setAuthenticator('before-system-handler', authenticator); + + let session2 = undefined; + try { + // Connect to the server. + session2 = await diffusion.connect({ + host: 'localhost', + port: 8080 + }); + } catch (err) { + console.error('Connection could not be established. (Expected)', err); + /// tag::log + check.log('Anonymous connection failed.'); + /// end::log + } + + let session3 = undefined; + try { + // Connect to the server. + session3 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'control', + credentials: 'password' + }); + } catch (err) { + console.error('Connection could not be established. (Expected)', err); + /// tag::log + check.log('control connection failed.'); + /// end::log + } + + // Connect to the server. + const session4 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'diffusion_control', + credentials: 'password' + }); + /// tag::log + check.log('diffusion_control connection established.'); + /// end::log + + await session1.closeSession(); + await session2?.closeSession(); + await session3?.closeSession(); + await session4.closeSession(); + /// end::session_management_authentication_control[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/session-management/client-control/change-roles-via-session-filter.js b/js/session-management/client-control/change-roles-via-session-filter.js new file mode 100644 index 00000000..c410b032 --- /dev/null +++ b/js/session-management/client-control/change-roles-via-session-filter.js @@ -0,0 +1,59 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function clientControlChangeRolesViaSessionFilter() { + /// tag::client_control_change_roles_via_session_filter[] + // Connect to the server. + const session1 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + // Connect to the server. + const session2 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'client', + credentials: 'password' + }); + + const properties1 = await session1.clients.getSessionProperties( + session2.sessionId, + ['$Roles'] + ); + console.log(`Original session roles: ${properties1['$Roles']}`); + /// tag::log + expect(properties1['$Roles']).toBe('"CLIENT"'); + /// end::log + + await session1.clients.changeRoles('$Principal is "client"', [], ['TOPIC_CONTROL']); + + const properties2 = await session1.clients.getSessionProperties( + session2.sessionId, + ['$Roles'] + ); + console.log(`Changed session roles: ${properties2['$Roles']}`); + /// tag::log + expect(properties2['$Roles']).toBe('"CLIENT","TOPIC_CONTROL"'); + /// end::log + + await session1.closeSession(); + await session2.closeSession(); + /// end::client_control_change_roles_via_session_filter[] +} diff --git a/js/session-management/client-control/change-roles-via-session-id.js b/js/session-management/client-control/change-roles-via-session-id.js new file mode 100644 index 00000000..2296cf3c --- /dev/null +++ b/js/session-management/client-control/change-roles-via-session-id.js @@ -0,0 +1,59 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function clientControlChangeRolesViaSessionId() { + /// tag::client_control_change_roles_via_session_id[] + // Connect to the server. + const session1 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + // Connect to the server. + const session2 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'client', + credentials: 'password' + }); + + const properties1 = await session1.clients.getSessionProperties( + session2.sessionId, + ['$Roles'] + ); + console.log(`Original session roles: ${properties1['$Roles']}`); + /// tag::log + expect(properties1['$Roles']).toBe('"CLIENT"'); + /// end::log + + await session1.clients.changeRoles(session2.sessionId, [], ['TOPIC_CONTROL']); + + const properties2 = await session1.clients.getSessionProperties( + session2.sessionId, + ['$Roles'] + ); + console.log(`Changed session roles: ${properties2['$Roles']}`); + /// tag::log + expect(properties2['$Roles']).toBe('"CLIENT","TOPIC_CONTROL"'); + /// end::log + + await session1.closeSession(); + await session2.closeSession(); + /// end::client_control_change_roles_via_session_id[] +} diff --git a/js/session-management/client-control/close-client-via-session-filter.js b/js/session-management/client-control/close-client-via-session-filter.js new file mode 100644 index 00000000..59c73709 --- /dev/null +++ b/js/session-management/client-control/close-client-via-session-filter.js @@ -0,0 +1,57 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { promiseWithResolvers } = require('../../../../test/util'); +/// end::log + +export async function clientControlCloseClientViaSessionFilter() { + /// tag::log + const { promise, resolve } = promiseWithResolvers(); + /// end::log + /// tag::client_control_close_client_via_session_filter[] + // Connect to the server. + const session1 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + // Connect to the server. + const session2 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'client', + credentials: 'password' + }); + + session2.on('close', () => { + console.log('Session closed'); + /// tag::log + resolve(); + /// end::log + }); + + await session1.clients.close('$Principal is "client"'); + + await session1.closeSession(); + /// tag::log + await promise; + expect(session2.isClosed()).toBe(true); + /// end::log + /// end::client_control_close_client_via_session_filter[] +} diff --git a/js/session-management/client-control/close-client-via-session-id.js b/js/session-management/client-control/close-client-via-session-id.js new file mode 100644 index 00000000..aee91fbf --- /dev/null +++ b/js/session-management/client-control/close-client-via-session-id.js @@ -0,0 +1,57 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { promiseWithResolvers } = require('../../../../test/util'); +/// end::log + +export async function clientControlCloseClientViaSessionId() { + /// tag::log + const { promise, resolve } = promiseWithResolvers(); + /// end::log + /// tag::client_control_close_client_via_session_id[] + // Connect to the server. + const session1 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + // Connect to the server. + const session2 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'client', + credentials: 'password' + }); + + session2.on('close', () => { + console.log('Session closed'); + /// tag::log + resolve(); + /// end::log + }); + + await session1.clients.close(session2.sessionId); + + await session1.closeSession(); + /// tag::log + await promise; + expect(session2.isClosed()).toBe(true); + /// end::log + /// end::client_control_close_client_via_session_id[] +} diff --git a/js/session-management/client-control/get-session-properties-via-session-id.js b/js/session-management/client-control/get-session-properties-via-session-id.js new file mode 100644 index 00000000..4b3dc18e --- /dev/null +++ b/js/session-management/client-control/get-session-properties-via-session-id.js @@ -0,0 +1,75 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester } = require('../../../../test/util'); +/// end::log + +export async function clientControlGetSessionPropertiesViaSessionId() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + '$Country', + '$ClientIP', + '$Environment', + '$SessionId', + '$Transport', + '$Principal', + '$ServerName', + '$StartTime', + '$Language', + '$Latitude', + '$Connector', + '$Longitude', + '$ClientType', + '$Roles', + ]]); + /// end::log + /// tag::client_control_get_session_properties_via_session_id[] + // Connect to the server. + const session1 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + // Connect to the server. + const session2 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const properties = await session1.clients.getSessionProperties( + session2.sessionId, + diffusion.clients.PropertyKeys.ALL_FIXED_PROPERTIES + ); + console.log(`${session2.toString()}:`); + for (const key of Object.keys(properties)) { + console.log(` ${key}: ${properties[key]}`); + /// tag::log + check.log(`${key}`); + /// end::log + } + + await session1.closeSession(); + await session2.closeSession(); + /// end::client_control_get_session_properties_via_session_id[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/session-management/client-control/queue-conflation-via-session-filter.js b/js/session-management/client-control/queue-conflation-via-session-filter.js new file mode 100644 index 00000000..2c09a5d6 --- /dev/null +++ b/js/session-management/client-control/queue-conflation-via-session-filter.js @@ -0,0 +1,50 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester } = require('../../../../test/util'); +/// end::log + +export async function clientControlQueueConflationViaSessionFilter() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([]); + /// end::log + /// tag::client_control_queue_conflation_via_session_filter[] + // Connect to the server. + const session1 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + // Connect to the server. + const session2 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + await session1.clients.setConflated('$Principal is "client"', false); + + await session1.closeSession(); + await session2.closeSession(); + /// end::client_control_queue_conflation_via_session_filter[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/session-management/client-control/queue-conflation-via-session-id.js b/js/session-management/client-control/queue-conflation-via-session-id.js new file mode 100644 index 00000000..1c1fb2f9 --- /dev/null +++ b/js/session-management/client-control/queue-conflation-via-session-id.js @@ -0,0 +1,50 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester } = require('../../../../test/util'); +/// end::log + +export async function clientControlQueueConflationViaSessionId() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([]); + /// end::log + /// tag::client_control_queue_conflation_via_session_id[] + // Connect to the server. + const session1 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + // Connect to the server. + const session2 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'client', + credentials: 'password' + }); + + await session1.clients.setConflated(session2.sessionId, false); + + await session1.closeSession(); + await session2.closeSession(); + /// end::client_control_queue_conflation_via_session_id[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/session-management/client-control/set-session-properties-via-filter.js b/js/session-management/client-control/set-session-properties-via-filter.js new file mode 100644 index 00000000..1e4aa14e --- /dev/null +++ b/js/session-management/client-control/set-session-properties-via-filter.js @@ -0,0 +1,65 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function clientControlSetSessionPropertiesViaSessionFilter() { + /// tag::client_control_set_session_properties_via_session_filter[] + // Connect to the server. + const session1 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + // Connect to the server. + const session2 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'client', + credentials: 'password' + }); + + const properties1 = await session1.clients.getSessionProperties( + session2.sessionId, + diffusion.clients.PropertyKeys.ALL_FIXED_PROPERTIES + ); + console.log('Original session properties:'); + for (const key of Object.keys(properties1)) { + console.log(` ${key}: ${properties1[key]}`); + } + + await session1.clients.setSessionPropertiesByFilter( + '$Principal is "client"', + { '$Language': 'en-gb' } + ); + + const properties2 = await session1.clients.getSessionProperties( + session2.sessionId, + diffusion.clients.PropertyKeys.ALL_FIXED_PROPERTIES + ); + console.log('Changed session properties:'); + for (const key of Object.keys(properties2)) { + console.log(` ${key}: ${properties2[key]}`); + } + /// tag::log + expect(properties2['$Language']).toBe('en-gb'); + /// end::log + + await session1.closeSession(); + await session2.closeSession(); + /// end::client_control_set_session_properties_via_session_filter[] +} diff --git a/js/session-management/client-control/set-session-properties-via-session-id.js b/js/session-management/client-control/set-session-properties-via-session-id.js new file mode 100644 index 00000000..74c3dbcc --- /dev/null +++ b/js/session-management/client-control/set-session-properties-via-session-id.js @@ -0,0 +1,65 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function clientControlSetSessionPropertiesViaSessionId() { + /// tag::client_control_set_session_properties_via_session_id[] + // Connect to the server. + const session1 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + // Connect to the server. + const session2 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const properties1 = await session1.clients.getSessionProperties( + session2.sessionId, + diffusion.clients.PropertyKeys.ALL_FIXED_PROPERTIES + ); + console.log('Original session properties:'); + for (const key of Object.keys(properties1)) { + console.log(` ${key}: ${properties1[key]}`); + } + + await session1.clients.setSessionProperties( + session2.sessionId, + { '$Language': 'en-gb' } + ); + + const properties2 = await session1.clients.getSessionProperties( + session2.sessionId, + diffusion.clients.PropertyKeys.ALL_FIXED_PROPERTIES + ); + console.log('Changed session properties:'); + for (const key of Object.keys(properties2)) { + console.log(` ${key}: ${properties2[key]}`); + } + /// tag::log + expect(properties2['$Language']).toBe('en-gb'); + /// end::log + + await session1.closeSession(); + await session2.closeSession(); + /// end::client_control_set_session_properties_via_session_id[] +} diff --git a/js/session-management/subscription-control.js b/js/session-management/subscription-control.js new file mode 100644 index 00000000..99431ba3 --- /dev/null +++ b/js/session-management/subscription-control.js @@ -0,0 +1,123 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester, promiseWithResolvers } = require('../../../test/util'); +/// end::log + +export async function sessionManagementSubscriptionControl() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['subscribed client'], + ['Subscribed to my/topic/path/hello'], + ['unsubscribed client', 'Unsubscribed from my/topic/path/hello'] + ]); + const subscribedPromise = promiseWithResolvers(); + const unsubscribeTopicPromise = promiseWithResolvers(); + /// end::log + /// tag::session_management_subscription_control[] + // Connect to the server. + const session1 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.STRING); + await session1.topicUpdate.set( + 'my/topic/path/hello', + diffusion.datatypes.string(), + 'Hello World!', + { specification: specification } + ); + console.log('Topic value has been set.'); + + let deferredUnsubscribeResolve; + const unsubscribePromise = new Promise((resolve) => { + deferredUnsubscribeResolve = resolve; + }); + + const sessionEventStream = { + onSessionEvent: (event) => { + console.log(`Session ${event.sessionId.toString()} has been updated:`); + console.log(` Type: ${event.type}`); + console.log(` State: ${event.state}`); + + if ( + event.type === diffusion.clients.SessionEventStreamEventType.STATE + && event.state === diffusion.clients.SessionState.ACTIVE + && event.sessionId.toString() !== session1.sessionId.toString() + ) { + session1.clients.subscribe(event.sessionId, '?my/topic/path//'); + /// tag::log + check.log('subscribed client'); + /// end::log + setTimeout(async () => { + /// tag::log + await subscribedPromise.promise; + /// end::log + await session1.clients.unsubscribe(event.sessionId, '?my/topic/path//'); + /// tag::log + check.log('unsubscribed client'); + /// end::log + deferredUnsubscribeResolve(); + }, 5000); + } + }, + onClose: () => {}, + onError: () => {} + }; + await session1.clients.addSessionEventListener(sessionEventStream, {}); + + // Connect to the server. + const session2 = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const valueStream = session2.addFallbackStream(diffusion.datatypes.string()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + subscribedPromise.resolve(); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + /// tag::log + check.log(`Unsubscribed from ${topic}`); + unsubscribeTopicPromise.resolve(); + /// end::log + }, + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${oldValue.get()} to ${newValue.get()}`); + } + }); + + await unsubscribePromise; + /// tag::log + await unsubscribeTopicPromise.promise; + /// end::log + + await session1.closeSession(); + await session2.closeSession(); + /// end::session_management_subscription_control[] +} diff --git a/js/timeseries/append-timeseries-topic-with-timestamp.js b/js/timeseries/append-timeseries-topic-with-timestamp.js new file mode 100644 index 00000000..6df8f9d3 --- /dev/null +++ b/js/timeseries/append-timeseries-topic-with-timestamp.js @@ -0,0 +1,67 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectTimeseriesDoubleTopicToHaveValues } = require('../../../test/util'); +/// end::log + +export async function timeSeriesAppendUserSuppliedTimestamp() { + /// tag::log + const values = []; + /// end::log + /// tag::time_series_append_user_supplied_timestamp[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.TIME_SERIES, { + 'TIME_SERIES_EVENT_VALUE_TYPE': 'double', + 'TIME_SERIES_RETAINED_RANGE': 'limit 15 last 10s', + 'TIME_SERIES_SUBSCRIPTION_RANGE': 'limit 3' + }); + + await session.topics.add('my/time/series/topic/path/user/supplied', specification); + + let timestamp = 1000001; + for (let count = 0; count < 25; count++) { + const value = Math.random(); + await session.timeseries.append( + 'my/time/series/topic/path/user/supplied', + value, + diffusion.datatypes.double(), + timestamp + ); + /// tag::log + values.push(value); + /// end::log + timestamp++; + } + + await session.closeSession(); + /// end::time_series_append_user_supplied_timestamp[] + /// tag::log + const timestamps = values.map((_, i) => 1000001 + i); + await expectTimeseriesDoubleTopicToHaveValues( + 'my/time/series/topic/path/user/supplied', + values.slice(-15), + timestamps.slice(-15) + ); + /// end::log +} diff --git a/js/timeseries/append-timeseries-topic.js b/js/timeseries/append-timeseries-topic.js new file mode 100644 index 00000000..a7e96c42 --- /dev/null +++ b/js/timeseries/append-timeseries-topic.js @@ -0,0 +1,67 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectTimeseriesDoubleTopicToHaveValues } = require('../../../test/util'); +/// end::log + + +export async function timeSeriesAppendValue() { + /// tag::log + const values = []; + /// end::log + /// tag::time_series_append_value[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.TIME_SERIES, { + 'TIME_SERIES_EVENT_VALUE_TYPE': 'double', + 'TIME_SERIES_RETAINED_RANGE': 'limit 15 last 10s', + 'TIME_SERIES_SUBSCRIPTION_RANGE': 'limit 3' + }); + + const addResult = await session.topics.add('my/time/series/topic/path', specification); + if (addResult.added) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(addResult.added).toBeTrue(); + /// end::log + + for (let count = 0; count < 25; count++) { + const value = Math.random(); + await session.timeseries.append('my/time/series/topic/path', value, diffusion.datatypes.double()); + /// tag::log + values.push(value); + /// end::log + } + + await session.closeSession(); + /// end::time_series_append_value[] + /// tag::log + await expectTimeseriesDoubleTopicToHaveValues( + 'my/time/series/topic/path', + values.slice(-15) + ); + /// end::log +} diff --git a/js/timeseries/append-timeseries-update-stream.js b/js/timeseries/append-timeseries-update-stream.js new file mode 100644 index 00000000..7709e9aa --- /dev/null +++ b/js/timeseries/append-timeseries-update-stream.js @@ -0,0 +1,60 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectTimeseriesDoubleTopicToHaveValues } = require('../../../test/util'); +/// end::log + +export async function timeSeriesAppendValueViaUpdateStream() { + /// tag::log + const values = []; + /// end::log + /// tag::time_series_append_value_via_update_stream[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.TIME_SERIES, { + 'TIME_SERIES_EVENT_VALUE_TYPE': 'double', + 'TIME_SERIES_RETAINED_RANGE': 'limit 15 last 10s', + 'TIME_SERIES_SUBSCRIPTION_RANGE': 'limit 3' + }); + + await session.topics.add('my/time/series/topic/path', specification); + + const updateStream = session.topicUpdate.newUpdateStreamBuilder() + .build('my/time/series/topic/path', diffusion.datatypes.double()); + for (let count = 0; count < 25; count++) { + const value = Math.random(); + await updateStream.set(value); + /// tag::log + values.push(value); + /// end::log + } + + await session.closeSession(); + /// end::time_series_append_value_via_update_stream[] + /// tag::log + await expectTimeseriesDoubleTopicToHaveValues( + 'my/time/series/topic/path', + values.slice(-15) + ); + /// end::log +} diff --git a/js/timeseries/create-timeseries-topic.js b/js/timeseries/create-timeseries-topic.js new file mode 100644 index 00000000..bf50e79c --- /dev/null +++ b/js/timeseries/create-timeseries-topic.js @@ -0,0 +1,52 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectTopicExists } = require('../../../test/util'); +/// end::log + +export async function timeSeriesCreateTopic() { + /// tag::time_series_create_topic[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.TIME_SERIES, { + 'TIME_SERIES_EVENT_VALUE_TYPE': 'double', + 'TIME_SERIES_RETAINED_RANGE': 'limit 15 last 10s', + 'TIME_SERIES_SUBSCRIPTION_RANGE': 'limit 3' + }); + + const addResult = await session.topics.add('my/time/series/topic/path', specification); + if (addResult.added) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(addResult.added).toBeTrue(); + /// end::log + + await session.closeSession(); + /// end::time_series_create_topic[] + /// tag::log + await expectTopicExists('my/time/series/topic/path'); + /// end::log +} diff --git a/js/timeseries/edit-timeseries-topic.js b/js/timeseries/edit-timeseries-topic.js new file mode 100644 index 00000000..54f70f9e --- /dev/null +++ b/js/timeseries/edit-timeseries-topic.js @@ -0,0 +1,73 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectTimeseriesDoubleTopicToHaveValues } = require('../../../test/util'); +/// end::log + +export async function timeSeriesEditValue() { + /// tag::log + const values = []; + /// end::log + /// tag::time_series_edit_value[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.TIME_SERIES, { + 'TIME_SERIES_EVENT_VALUE_TYPE': 'double', + 'TIME_SERIES_RETAINED_RANGE': 'limit 15 last 10s', + 'TIME_SERIES_SUBSCRIPTION_RANGE': 'limit 3' + }); + + await session.topics.add('my/time/series/topic/path', specification); + + const metaData = []; + for (let count = 0; count < 25; count++) { + const value = Math.random(); + const result = await session.timeseries.append( + 'my/time/series/topic/path', + value, + diffusion.datatypes.double() + ); + metaData.push(result); + /// tag::log + values.push(value); + /// end::log + } + + const eventToEdit = metaData[20]; + await session.timeseries.edit( + 'my/time/series/topic/path', + eventToEdit.sequence, + 3.14, + diffusion.datatypes.double() + ); + + await session.closeSession(); + /// end::time_series_edit_value[] + /// tag::log + values[20] = 3.14; + await expectTimeseriesDoubleTopicToHaveValues( + 'my/time/series/topic/path', + values.slice(-14) + ); + /// end::log +} diff --git a/js/timeseries/range-query-timeseries-topic.js b/js/timeseries/range-query-timeseries-topic.js new file mode 100644 index 00000000..4a0271f5 --- /dev/null +++ b/js/timeseries/range-query-timeseries-topic.js @@ -0,0 +1,87 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function timeSeriesRangeQuery() { + /// tag::log + const values = []; + /// end::log + /// tag::time_series_range_query[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.TIME_SERIES, { + 'TIME_SERIES_EVENT_VALUE_TYPE': 'double', + 'TIME_SERIES_RETAINED_RANGE': 'limit 50 last 120s', + 'TIME_SERIES_SUBSCRIPTION_RANGE': 'limit 3' + }); + + await session.topics.add('my/time/series/topic/path', specification); + + const metaData = []; + for (let count = 0; count < 25; count++) { + const value = Math.random(); + const result = await session.timeseries.append( + 'my/time/series/topic/path', + value, + diffusion.datatypes.double() + ); + metaData.push(result); + /// tag::log + values.push(value); + /// end::log + } + + const eventToEdit = metaData[10]; + await session.timeseries.edit( + 'my/time/series/topic/path', + eventToEdit.sequence, + 3.14, + diffusion.datatypes.double() + ); + + const queryResult = await session.timeseries.rangeQuery() + .from(metaData[5].sequence) + .to(metaData[15].sequence) + .selectFrom('my/time/series/topic/path'); + /// tag::log + let count = 0; + expect(queryResult.events.length).toBe(11); + /// end::log + for (const event of queryResult.events) { + const value = diffusion.datatypes.double().readValue(event.value); + console.log(`${event.sequence} (${event.timestamp}): ${value}`); + /// tag::log + if (count === 5) { + expect(value).toBe(3.14); + expect(event.sequence).toBe(25); + } else { + expect(value).toBe(values[5 + count]); + expect(event.sequence).toBe(metaData[5 + count].sequence); + expect(event.timestamp).toBe(metaData[5 + count].timestamp); + } + count++; + /// end::log + } + + await session.closeSession(); + /// end::time_series_range_query[] +} diff --git a/js/timeseries/subscribe-timeseries-topic-cross-compatible.js b/js/timeseries/subscribe-timeseries-topic-cross-compatible.js new file mode 100644 index 00000000..751ef3a1 --- /dev/null +++ b/js/timeseries/subscribe-timeseries-topic-cross-compatible.js @@ -0,0 +1,95 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester, promiseWithResolvers } = require('../../../test/util'); +/// end::log + +export async function timeSeriesSubscribeCrossCompatible() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Subscribed to my/time/series/topic/path'] + ]); + + const valuePromise = promiseWithResolvers(); + let valueCount = 0; + let oldValue = 'undefined'; + /// end::log + /// tag::time_series_subscribe_cross_compatible[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.TIME_SERIES, { + 'TIME_SERIES_EVENT_VALUE_TYPE': 'double', + 'TIME_SERIES_RETAINED_RANGE': 'limit 15 last 10s', + 'TIME_SERIES_SUBSCRIPTION_RANGE': 'limit 3' + }); + + await session.topics.add('my/time/series/topic/path', specification); + + const jsonValueStream = session.addStream('my/time/series/topic/path', diffusion.datatypes.json()); + jsonValueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + /// tag::log + close : () => { + check.log(`Closed`); + }, + /// end::log + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${oldValue?.get()} to ${newValue.get()}`); + /// tag::log + if (++valueCount >= 25) { + valuePromise.resolve(); + } + check.log(`${topic} changed from ${oldValue?.get()} to ${newValue.get()}`); + /// end::log + } + }); + + await session.select('?my/time/series//'); + + for (let count = 0; count < 25; count++) { + const value = Math.random(); + /// tag::log + check.appendExpected([`my/time/series/topic/path changed from ${oldValue} to ${value}`]); + oldValue = `${value}`; + /// end::log + await session.timeseries.append('my/time/series/topic/path', value, diffusion.datatypes.double()); + } + + /// tag::log + check.appendExpected([`Closed`]); + await valuePromise.promise; + /// end::log + await session.closeSession(); + /// end::time_series_subscribe_cross_compatible[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/timeseries/subscribe-timeseries-topic.js b/js/timeseries/subscribe-timeseries-topic.js new file mode 100644 index 00000000..59835eca --- /dev/null +++ b/js/timeseries/subscribe-timeseries-topic.js @@ -0,0 +1,98 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester, promiseWithResolvers } = require('../../../test/util'); +/// end::log + +export async function timeSeriesSubscribe() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Subscribed to my/time/series/topic/path'], + ]); + + const valuePromise = promiseWithResolvers(); + let valueCount = 0; + let oldValue = 'undefined'; + /// end::log + /// tag::time_series_subscribe[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.TIME_SERIES, { + 'TIME_SERIES_EVENT_VALUE_TYPE': 'double', + 'TIME_SERIES_RETAINED_RANGE': 'limit 15 last 10s', + 'TIME_SERIES_SUBSCRIPTION_RANGE': 'limit 3' + }); + + await session.topics.add('my/time/series/topic/path', specification); + + const valueStream = session.addStream( + 'my/time/series/topic/path', + diffusion.datatypes.timeseries(diffusion.datatypes.double()) + ); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + /// tag::log + close : () => { + check.log(`Closed`); + }, + /// end::log + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${oldValue?.value} to ${newValue.value}`); + /// tag::log + if (++valueCount >= 25) { + valuePromise.resolve(); + } + check.log(`${topic} changed from ${oldValue?.value} to ${newValue.value}`); + /// end::log + } + }); + + await session.select('?my/time/series//'); + + for (let count = 0; count < 25; count++) { + const value = Math.random(); + /// tag::log + check.appendExpected([`my/time/series/topic/path changed from ${oldValue} to ${value}`]); + oldValue = `${value}`; + /// end::log + await session.timeseries.append('my/time/series/topic/path', value, diffusion.datatypes.double()); + } + + /// tag::log + check.appendExpected([`Closed`]); + await valuePromise.promise; + /// end::log + await session.closeSession(); + /// end::time_series_subscribe[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/wrangling/session-trees/get-branch-mapping-table.js b/js/wrangling/session-trees/get-branch-mapping-table.js new file mode 100644 index 00000000..bf8bd0af --- /dev/null +++ b/js/wrangling/session-trees/get-branch-mapping-table.js @@ -0,0 +1,78 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester } = require('../../../../test/util'); +/// end::log + +export async function sessionTreesGetBranchMappingTable() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'my/personal/path', + '$Principal is "admin": my/topic/path/for/admin', + '$Principal is "control": my/topic/path/for/control', + '$Principal is "": my/topic/path/for/anonymous', + 'my/alternate/path', + '$Transport is "WEBSOCKET": my/alternate/path/for/websocket', + '$Transport is "HTTP_LONG_POLL": my/alternate/path/for/http', + '$Transport is "TCP": my/alternate/path/for/tcp' + ]]); + /// end::log + /// tag::session_trees_get_branch_mapping_table[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const branchMappingTable1 = diffusion.newBranchMappingTableBuilder() + .addBranchMapping('$Principal is "admin"', 'my/topic/path/for/admin') + .addBranchMapping('$Principal is "control"', 'my/topic/path/for/control') + .addBranchMapping('$Principal is ""', 'my/topic/path/for/anonymous') + .create('my/personal/path'); + await session.sessionTrees.putBranchMappingTable(branchMappingTable1); + + const branchMappingTable2 = diffusion.newBranchMappingTableBuilder() + .addBranchMapping('$Transport is "WEBSOCKET"', 'my/alternate/path/for/websocket') + .addBranchMapping('$Transport is "HTTP_LONG_POLL"', 'my/alternate/path/for/http') + .addBranchMapping('$Transport is "TCP"', 'my/alternate/path/for/tcp') + .create('my/alternate/path'); + await session.sessionTrees.putBranchMappingTable(branchMappingTable2); + + + const sessionTrees = await session.sessionTrees.getSessionTreeBranchesWithMappings(); + for (const sessionTreeBranch of sessionTrees) { + console.log(`${sessionTreeBranch}:`); + /// tag::log + check.log(sessionTreeBranch); + /// end::log + const mappingTable = await session.sessionTrees.getBranchMappingTable(sessionTreeBranch); + for (const branchMapping of mappingTable.getBranchMappings()) { + console.log(` ${branchMapping.sessionFilter}: ${branchMapping.topicTreeBranch}`); + /// tag::log + check.log(`${branchMapping.sessionFilter}: ${branchMapping.topicTreeBranch}`); + /// end::log + } + } + + await session.closeSession(); + /// end::session_trees_get_branch_mapping_table[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/wrangling/session-trees/list-session-tree-branches-with-mappings.js b/js/wrangling/session-trees/list-session-tree-branches-with-mappings.js new file mode 100644 index 00000000..e1459e62 --- /dev/null +++ b/js/wrangling/session-trees/list-session-tree-branches-with-mappings.js @@ -0,0 +1,63 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester } = require('../../../../test/util'); +/// end::log + +export async function sessionTreesListSessionTreeBranchesWithMappings() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'my/personal/path', + 'my/alternate/path', + ]]); + /// end::log + /// tag::session_trees_list_session_tree_branches_with_mappings[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const branchMappingTable1 = diffusion.newBranchMappingTableBuilder() + .addBranchMapping('$Principal is "admin"', 'my/topic/path/for/admin') + .addBranchMapping('$Principal is "control"', 'my/topic/path/for/control') + .addBranchMapping('$Principal is ""', 'my/topic/path/for/anonymous') + .create('my/personal/path'); + await session.sessionTrees.putBranchMappingTable(branchMappingTable1); + + const branchMappingTable2 = diffusion.newBranchMappingTableBuilder() + .addBranchMapping('$Transport is "WEBSOCKET"', 'my/alternate/path/for/websocket') + .addBranchMapping('$Transport is "HTTP_LONG_POLL"', 'my/alternate/path/for/http') + .addBranchMapping('$Transport is "TCP"', 'my/alternate/path/for/tcp') + .create('my/alternate/path'); + await session.sessionTrees.putBranchMappingTable(branchMappingTable2); + + const sessionTrees = await session.sessionTrees.getSessionTreeBranchesWithMappings(); + for (const sessionTree of sessionTrees) { + console.log(sessionTree); + /// tag::log + check.log(sessionTree); + /// end::log + } + + await session.closeSession(); + /// end::session_trees_list_session_tree_branches_with_mappings[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/wrangling/session-trees/put-branch-mapping-table.js b/js/wrangling/session-trees/put-branch-mapping-table.js new file mode 100644 index 00000000..df9e7a74 --- /dev/null +++ b/js/wrangling/session-trees/put-branch-mapping-table.js @@ -0,0 +1,56 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester } = require('../../../../test/util'); +/// end::log + +export async function sessionTreesPutBranchMappingTable() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + '$Principal is "admin": my/topic/path/for/admin', + '$Principal is "control": my/topic/path/for/control', + '$Principal is "": my/topic/path/for/anonymous' + ]]); + /// end::log + /// tag::session_trees_put_branch_mapping_table[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const branchMappingTable = diffusion.newBranchMappingTableBuilder() + .addBranchMapping('$Principal is "admin"', 'my/topic/path/for/admin') + .addBranchMapping('$Principal is "control"', 'my/topic/path/for/control') + .addBranchMapping('$Principal is ""', 'my/topic/path/for/anonymous') + .create('my/personal/path'); + await session.sessionTrees.putBranchMappingTable(branchMappingTable); + /// tag::log + const mappingTable = await session.sessionTrees.getBranchMappingTable('my/personal/path'); + for (const branchMapping of mappingTable.getBranchMappings()) { + check.log(`${branchMapping.sessionFilter}: ${branchMapping.topicTreeBranch}`); + } + /// end::log + + await session.closeSession(); + /// end::session_trees_put_branch_mapping_table[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/wrangling/session-trees/put-remove-branch-mapping-table.js b/js/wrangling/session-trees/put-remove-branch-mapping-table.js new file mode 100644 index 00000000..f34b1f9a --- /dev/null +++ b/js/wrangling/session-trees/put-remove-branch-mapping-table.js @@ -0,0 +1,64 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester } = require('../../../../test/util'); +/// end::log + +export async function sessionTreesPutAndRemoveBranchMappingTable() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + '$Principal is "admin": my/topic/path/for/admin', + '$Principal is "control": my/topic/path/for/control', + '$Principal is "": my/topic/path/for/anonymous' + ]]); + /// end::log + /// tag::session_trees_put_and_remove_branch_mapping_table[] + // Connect to the server. + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const branchMappingTable = diffusion.newBranchMappingTableBuilder() + .addBranchMapping('$Principal is "admin"', 'my/topic/path/for/admin') + .addBranchMapping('$Principal is "control"', 'my/topic/path/for/control') + .addBranchMapping('$Principal is ""', 'my/topic/path/for/anonymous') + .create('my/personal/path'); + await session.sessionTrees.putBranchMappingTable(branchMappingTable); + /// tag::log + const mappingTable = await session.sessionTrees.getBranchMappingTable('my/personal/path'); + for (const branchMapping of mappingTable.getBranchMappings()) { + check.log(`${branchMapping.sessionFilter}: ${branchMapping.topicTreeBranch}`); + } + /// end::log + + const emptyBranchMappingTable = diffusion.newBranchMappingTableBuilder() + .create('my/personal/path'); + await session.sessionTrees.putBranchMappingTable(emptyBranchMappingTable); + /// tag::log + const mappingTable2 = await session.sessionTrees.getBranchMappingTable('my/personal/path'); + expect(mappingTable2.getBranchMappings().length).toBe(0); + /// end::log + + await session.closeSession(); + /// end::session_trees_put_and_remove_branch_mapping_table[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/wrangling/session-trees/use-case.js b/js/wrangling/session-trees/use-case.js new file mode 100644 index 00000000..797acb09 --- /dev/null +++ b/js/wrangling/session-trees/use-case.js @@ -0,0 +1,164 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester, promiseWithResolvers } = require('../../../../test/util'); +/// end::log + +export async function sessionTreesUseCase() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Session1 subscribed to my/personal/path', + 'Session2 subscribed to my/personal/path', + 'Session1 value changed to Good morning Administrator', + 'Session2 value changed to Good night Anonymous', + ]]); + const promiseValue1 = promiseWithResolvers(); + const promiseValue2 = promiseWithResolvers(); + /// end::log + /// tag::session_trees_use_case[] + let session; + try { + // Connect to the server. + session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + } catch (err) { + console.error('Connection could not be established.', err); + throw err; + } + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.STRING); + try { + await session.topicUpdate.set( + 'my/topic/path/for/admin', + diffusion.datatypes.string(), + 'Good morning Administrator', + { specification: specification } + ); + + await session.topicUpdate.set( + 'my/topic/path/for/control', + diffusion.datatypes.string(), + 'Good afternoon Control Client', + { specification: specification } + ); + + await session.topicUpdate.set( + 'my/topic/path/for/anonymous', + diffusion.datatypes.string(), + 'Good night Anonymous', + { specification: specification } + ); + } catch (err) { + console.error('Topic values could not be set.', err); + throw err; + } + + try { + const branchMappingTable = diffusion.newBranchMappingTableBuilder() + .addBranchMapping('$Principal is "admin"', 'my/topic/path/for/admin') + .addBranchMapping('$Principal is "control"', 'my/topic/path/for/control') + .addBranchMapping('$Principal is ""', 'my/topic/path/for/anonymous') + .create('my/personal/path'); + await session.sessionTrees.putBranchMappingTable(branchMappingTable); + } catch (err) { + console.error('Could not put branch mapping table', err); + } + + const valueStream = session.addStream('my/personal/path', diffusion.datatypes.string()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Session1 subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${oldValue} to ${newValue}`); + /// tag::log + check.log(`Session1 value changed to ${newValue}`); + promiseValue1.resolve(); + /// end::log + } + }); + + try { + await session.select('my/personal/path'); + } catch (err) { + console.error('Could not select topic.', err); + throw err; + } + + let session2; + try { + // Connect to the server. + session2 = await diffusion.connect({ + host: 'localhost', + port: 8080 + }); + } catch (err) { + console.error('Connection could not be established.', err); + throw err; + } + + const valueStream2 = session2.addStream('my/personal/path', diffusion.datatypes.string()); + valueStream2.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Session2 subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${oldValue} to ${newValue}`); + /// tag::log + check.log(`Session2 value changed to ${newValue}`); + promiseValue2.resolve(); + /// end::log + } + }); + + try { + await session2.select('my/personal/path'); + } catch (err) { + console.error('Could not select topic.', err); + throw err; + } + + /// tag::log + await Promise.all([promiseValue1.promise, promiseValue2.promise]); + /// end::log + try { + await session.closeSession(); + await session2.closeSession(); + } catch (err) { + console.error('An error occurred when closing session.', err); + } + /// end::session_trees_use_case[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/wrangling/topic-views/api/add-topic-view.js b/js/wrangling/topic-views/api/add-topic-view.js new file mode 100644 index 00000000..94356c5f --- /dev/null +++ b/js/wrangling/topic-views/api/add-topic-view.js @@ -0,0 +1,55 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue, expectTopicCounts } = require('../../../../../test/util'); +/// end::log + +export async function topicViewsApiAdd() { + /// tag::topic_views_api_add[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData = diffusion.datatypes.json().from({ diffusion: 'data' }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + 'map my/topic/path to views/' + ); + console.log(`Topic View ${topicView.name} has been created.`); + /// tag::log + await expectJsonTopicToHaveValue('views/my/topic/path', { diffusion: 'data' }); + /// end::log + + await session.topicViews.removeTopicView('topic_view_1'); + + await session.closeSession(); + /// end::topic_views_api_add[] + /// tag::log + await expectTopicCounts({ 'views/my/topic/path': 0 }); + /// end::log +} diff --git a/js/wrangling/topic-views/api/list-topic-views.js b/js/wrangling/topic-views/api/list-topic-views.js new file mode 100644 index 00000000..b8cb1575 --- /dev/null +++ b/js/wrangling/topic-views/api/list-topic-views.js @@ -0,0 +1,84 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectTopicCounts, PartiallyOrderedCheckpointTester } = require('../../../../../test/util'); +/// end::log + +export async function topicViewsApiList() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ + 'Topic View topic_view_1: map my/topic/path to views/ (ADMINISTRATOR)', + 'Topic View topic_view_2: map my/topic/path/array to views/ (ADMINISTRATOR)' + ] + ]); + /// end::log + /// tag::topic_views_api_list[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData = diffusion.datatypes.json().from({ diffusion: 'data' }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + + const topicView1 = await session.topicViews.createTopicView( + 'topic_view_1', + 'map my/topic/path to views/' + ); + console.log(`Topic View ${topicView1.name} has been created.`); + + await session.topicUpdate.set( + 'my/topic/path/array', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + + const topicView2 = await session.topicViews.createTopicView( + 'topic_view_2', + 'map my/topic/path/array to views/' + ); + console.log(`Topic View ${topicView2.name} has been created.`); + + const topicViews = await session.topicViews.listTopicViews(); + for (const topicView of topicViews) { + console.log(`Topic View ${topicView.name}: ${topicView.specification} (${[...topicView.roles]})`); + /// tag::log + check.log(`Topic View ${topicView.name}: ${topicView.specification} (${[...topicView.roles]})`); + /// end::log + } + + await session.closeSession(); + /// end::topic_views_api_list[] + /// tag::log + await expectTopicCounts({ + 'views/my/topic/path': 1, + 'views/my/topic/path/array': 1, + + }); + await check.done(); + /// end::log +} diff --git a/js/wrangling/topic-views/api/remove-topic-views.js b/js/wrangling/topic-views/api/remove-topic-views.js new file mode 100644 index 00000000..5cb17b4e --- /dev/null +++ b/js/wrangling/topic-views/api/remove-topic-views.js @@ -0,0 +1,98 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } = require('../../../../../test/util'); +/// end::log + +export async function topicViewsApiRemove() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ + 'Topic View topic_view_1: map my/topic/path to views/ (ADMINISTRATOR)', + 'Topic View topic_view_2: map my/topic/path/array to views/ (ADMINISTRATOR)' + ], + [ + 'Topic View topic_view_2: map my/topic/path/array to views/ (ADMINISTRATOR)' + ] + ]); + /// end::log + /// tag::topic_views_api_remove[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData = diffusion.datatypes.json().from({ diffusion: 'data' }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + + const topicView1 = await session.topicViews.createTopicView( + 'topic_view_1', + 'map my/topic/path to views/' + ); + console.log(`Topic View ${topicView1.name} has been created.`); + /// tag::log + await expectJsonTopicToHaveValue('views/my/topic/path', { diffusion: 'data' }); + /// end::log + + await session.topicUpdate.set( + 'my/topic/path/array', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + + const topicView2 = await session.topicViews.createTopicView( + 'topic_view_2', + 'map my/topic/path/array to views/' + ); + console.log(`Topic View ${topicView2.name} has been created.`); + /// tag::log + await expectJsonTopicToHaveValue('views/my/topic/path/array', { diffusion: 'data' }); + /// end::log + + const topicViews1 = await session.topicViews.listTopicViews(); + for (const topicView of topicViews1) { + console.log(`Topic View ${topicView.name}: ${topicView.specification} (${[...topicView.roles]})`); + /// tag::log + check.log(`Topic View ${topicView.name}: ${topicView.specification} (${[...topicView.roles]})`); + /// end::log + } + + await session.topicViews.removeTopicView('topic_view_1'); + + const topicViews2 = await session.topicViews.listTopicViews(); + for (const topicView of topicViews2) { + console.log(`Topic View ${topicView.name}: ${topicView.specification} (${[...topicView.roles]})`); + /// tag::log + check.log(`Topic View ${topicView.name}: ${topicView.specification} (${[...topicView.roles]})`); + /// end::log + } + + await session.closeSession(); + /// end::topic_views_api_remove[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/wrangling/topic-views/dsl/expand-value.js b/js/wrangling/topic-views/dsl/expand-value.js new file mode 100644 index 00000000..73e49fed --- /dev/null +++ b/js/wrangling/topic-views/dsl/expand-value.js @@ -0,0 +1,79 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } = require('../../../../../test/util'); +/// end::log + +export async function topicViewsDslExpandValue() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/currency0', + 'Subscribed to views/currency1', + 'Subscribed to views/currency2', + 'Subscribed to views/currency3' + ]]); + /// end::log + /// tag::topic_views_dsl_expand_value[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData = diffusion.datatypes.json().from({ + 'currencies': ['USD', 'GBP', 'EUR', 'CHF'] + }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(diffusion.datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + 'map my/topic/path to views/currency' + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_expand_value[] + /// tag::log + await expectJsonTopicToHaveValue('views/currency0', 'USD'); + await expectJsonTopicToHaveValue('views/currency1', 'GBP'); + await expectJsonTopicToHaveValue('views/currency2', 'EUR'); + await expectJsonTopicToHaveValue('views/currency3', 'CHF'); + + await check.done(); + /// end::log +} diff --git a/js/wrangling/topic-views/dsl/insert-transformations.js b/js/wrangling/topic-views/dsl/insert-transformations.js new file mode 100644 index 00000000..f5297115 --- /dev/null +++ b/js/wrangling/topic-views/dsl/insert-transformations.js @@ -0,0 +1,102 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } = require('../../../../../test/util'); +/// end::log + +export async function topicViewsDslInsertTransformations() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/the_flintstones' + ]]); + /// end::log + /// tag::topic_views_dsl_insert_transformations[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData1 = diffusion.datatypes.json().from([ + 'Fred Flintstone', + 'Wilma Flintstone', + 'Barney Rubble', + 'Betty Rubble' + ]); + await session.topicUpdate.set( + 'my/topic/path/original_cast', + diffusion.datatypes.json(), + jsonData1, + { specification: specification } + ); + + const jsonData2 = diffusion.datatypes.json().from('Pebbles Flintstone'); + await session.topicUpdate.set( + 'my/topic/path/additional_cast/1', + diffusion.datatypes.json(), + jsonData2, + { specification: specification } + ); + + const jsonData3 = diffusion.datatypes.json().from('Bamm-Bamm Rubble'); + await session.topicUpdate.set( + 'my/topic/path/additional_cast/2', + diffusion.datatypes.json(), + jsonData3, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(diffusion.datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + `map my/topic/path/original_cast + to views/the_flintstones + insert my/topic/path/additional_cast/1 at /- + insert my/topic/path/additional_cast/2 at /-` + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_insert_transformations[] + /// tag::log + await expectJsonTopicToHaveValue('views/the_flintstones', [ + 'Fred Flintstone', + 'Wilma Flintstone', + 'Barney Rubble', + 'Betty Rubble', + 'Pebbles Flintstone', + 'Bamm-Bamm Rubble' + ]); + + await check.done(); + /// end::log +} diff --git a/js/wrangling/topic-views/dsl/options-delay.js b/js/wrangling/topic-views/dsl/options-delay.js new file mode 100644 index 00000000..30ee3ab2 --- /dev/null +++ b/js/wrangling/topic-views/dsl/options-delay.js @@ -0,0 +1,87 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } = require('../../../../../test/util'); +/// end::log + +export async function topicViewsDslOptionsDelay() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ 'Subscribed to my/topic/path' ] + ]); + /// end::log + /// tag::topic_views_dsl_options_delay[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.INT64); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.int64(), + 0, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(diffusion.datatypes.int64()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${oldValue} to ${newValue}`); + /// tag::log + if (topic !== 'my/topic/path') { + check.log(`${topic} changed from ${oldValue}`); + } + /// end::log + } + }); + + await session.select('?.*//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + 'map my/topic/path to views/ delay by 5 seconds' + ); + console.log(`Topic View ${topicView.name} has been created.`); + + for (let i = 0; i < 15; i++) { + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.int64(), + Date.now(), + { specification: specification } + ); + await new Promise((resolve) => setTimeout(resolve, 1000)); + } + + await session.closeSession(); + /// end::topic_views_dsl_options_delay[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/wrangling/topic-views/dsl/options-preserve-topics.js b/js/wrangling/topic-views/dsl/options-preserve-topics.js new file mode 100644 index 00000000..02e1ba8d --- /dev/null +++ b/js/wrangling/topic-views/dsl/options-preserve-topics.js @@ -0,0 +1,137 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue, expectTopicCounts, PartiallyOrderedCheckpointTester } = require('../../../../../test/util'); +/// end::log + +export async function topicViewsDslOptionsPreserveTopics() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ + 'Subscribed to views/preserved/Fred Flintstone', + 'Subscribed to views/not_preserved/Fred Flintstone', + ], + [ + 'Subscribed to views/preserved/Wilma Flintstone', + 'Subscribed to views/not_preserved/Wilma Flintstone', + ], + [ + 'Subscribed to views/preserved/Pebbles Flintstone', + 'Subscribed to views/not_preserved/Pebbles Flintstone' + ] + ]); + /// end::log + /// tag::topic_views_dsl_options_preserve_topics[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData1 = diffusion.datatypes.json().from({ + name: 'Fred Flintstone' + }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData1, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(diffusion.datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView1 = await session.topicViews.createTopicView( + 'topic_view_1', + 'map my/topic/path to views/preserved/ preserve topics' + ); + console.log(`Topic View ${topicView1.name} has been created.`); + const topicView2 = await session.topicViews.createTopicView( + 'topic_view_2', + 'map my/topic/path to views/not_preserved/' + ); + console.log(`Topic View ${topicView2.name} has been created.`); + + await new Promise(resolve => setTimeout(resolve, 2000)); + + const jsonData2 = diffusion.datatypes.json().from({ + name: 'Wilma Flintstone' + }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData2, + ); + + await new Promise(resolve => setTimeout(resolve, 2000)); + + const jsonData3 = diffusion.datatypes.json().from({ + name: 'Pebbles Flintstone' + }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData3, + ); + + await new Promise(resolve => setTimeout(resolve, 2000)); + /// tag::log + await expectTopicCounts({ + 'my/topic/path': 1, + 'views/preserved/Fred Flintstone': 1, + 'views/preserved/Wilma Flintstone': 1, + 'views/preserved/Pebbles Flintstone': 1, + 'views/not_preserved/Fred Flintstone': 0, + 'views/not_preserved/Wilma Flintstone': 0, + 'views/not_preserved/Pebbles Flintstone': 1 + }); + + await expectJsonTopicToHaveValue('views/preserved/Fred Flintstone', { + name: 'Fred Flintstone' + }); + await expectJsonTopicToHaveValue('views/preserved/Wilma Flintstone', { + name: 'Wilma Flintstone' + }); + await expectJsonTopicToHaveValue('views/preserved/Pebbles Flintstone', { + name: 'Pebbles Flintstone' + }); + await expectJsonTopicToHaveValue('views/not_preserved/Pebbles Flintstone', { + name: 'Pebbles Flintstone' + }); + /// end::log + + await session.topics.remove('my/topic/path'); + + await session.closeSession(); + /// end::topic_views_dsl_options_preserve_topics[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/wrangling/topic-views/dsl/options-separator.js b/js/wrangling/topic-views/dsl/options-separator.js new file mode 100644 index 00000000..a8fadec4 --- /dev/null +++ b/js/wrangling/topic-views/dsl/options-separator.js @@ -0,0 +1,103 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } = require('../../../../../test/util'); +/// end::log + +export async function topicViewsDslOptionsSeparator() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/Fred_Flintstone', + 'Subscribed to views/Wilma_Flintstone', + 'Subscribed to views/Pebbles_Flintstone' + ]]); + /// end::log + /// tag::topic_views_dsl_options_separator[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData1 = diffusion.datatypes.json().from({ + name: 'Fred/Flintstone' + }); + await session.topicUpdate.set( + 'my/topic/path/1', + diffusion.datatypes.json(), + jsonData1, + { specification: specification } + ); + + const jsonData2 = diffusion.datatypes.json().from({ + name: 'Wilma/Flintstone' + }); + await session.topicUpdate.set( + 'my/topic/path/2', + diffusion.datatypes.json(), + jsonData2, + { specification: specification } + ); + + const jsonData3 = diffusion.datatypes.json().from({ + name: 'Pebbles/Flintstone' + }); + await session.topicUpdate.set( + 'my/topic/path/3', + diffusion.datatypes.json(), + jsonData3, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(diffusion.datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + `map ?my/topic/path// to views/ separator '_'` + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_options_separator[] + /// tag::log + await expectJsonTopicToHaveValue('views/Fred_Flintstone', { + name: 'Fred/Flintstone' + }); + await expectJsonTopicToHaveValue('views/Wilma_Flintstone', { + name: 'Wilma/Flintstone' + }); + await expectJsonTopicToHaveValue('views/Pebbles_Flintstone', { + name: 'Pebbles/Flintstone' + }); + + await check.done(); + /// end::log +} diff --git a/js/wrangling/topic-views/dsl/options-throttle.js b/js/wrangling/topic-views/dsl/options-throttle.js new file mode 100644 index 00000000..c2776c2e --- /dev/null +++ b/js/wrangling/topic-views/dsl/options-throttle.js @@ -0,0 +1,91 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { PartiallyOrderedCheckpointTester } = require('../../../../../test/util'); +/// end::log + +export async function topicViewsDslOptionsThrottle() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ 'Subscribed to views/my/topic/path', 'Subscribed to my/topic/path' ], + [ + 'views/my/topic/path changed from undefined', + 'views/my/topic/path changed from 0' + ], + ]); + /// end::log + /// tag::topic_views_dsl_options_throttle[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.INT64); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.int64(), + 0, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(diffusion.datatypes.int64()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${oldValue} to ${newValue}`); + /// tag::log + if (topic !== 'my/topic/path') { + check.log(`${topic} changed from ${oldValue}`); + } + /// end::log + } + }); + + await session.select('?.*//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + 'map my/topic/path to views/ throttle to 1 update every 3 seconds' + ); + console.log(`Topic View ${topicView.name} has been created.`); + + for (let i = 0; i < 15; i++) { + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.int64(), + Date.now(), + { specification: specification } + ); + await new Promise((resolve) => setTimeout(resolve, 1000)); + } + + await session.closeSession(); + /// end::topic_views_dsl_options_throttle[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/js/wrangling/topic-views/dsl/options-topic-property-mapping.js b/js/wrangling/topic-views/dsl/options-topic-property-mapping.js new file mode 100644 index 00000000..3db575dc --- /dev/null +++ b/js/wrangling/topic-views/dsl/options-topic-property-mapping.js @@ -0,0 +1,83 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectTopicToHaveProperties, PartiallyOrderedCheckpointTester } = require('../../../../../test/util'); +/// end::log + +export async function topicViewsDslOptionsTopicPropertyMapping() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/my/topic/path' + ]]); + /// end::log + /// tag::topic_views_dsl_options_topic_property_mapping[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData = diffusion.datatypes.json().from([ + 'Fred Flintstone', + 'Wilma Flintstone', + 'Barney Rubble', + 'Betty Rubble' + ]); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(diffusion.datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + `map ?my/topic/path// to views/ + with properties 'CONFLATION':'off', 'COMPRESSION':'false', 'DONT_RETAIN_VALUE':'true'` + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_options_topic_property_mapping[] + /// tag::log + await expectTopicToHaveProperties('views/my/topic/path', { + CONFLATION: 'off', + COMPRESSION: 'false', + DONT_RETAIN_VALUE: 'true', + PERSISTENT: 'false', + _VIEW: 'topic_view_1' + }); + + await check.done(); + /// end::log +} diff --git a/js/wrangling/topic-views/dsl/options-topic-type.js b/js/wrangling/topic-views/dsl/options-topic-type.js new file mode 100644 index 00000000..f8328b98 --- /dev/null +++ b/js/wrangling/topic-views/dsl/options-topic-type.js @@ -0,0 +1,66 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function topicViewsDslOptionsTopicType() { + /// tag::topic_views_dsl_options_topic_type[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.INT64); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.int64(), + 0, + { specification: specification } + ); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + 'map my/topic/path to views/archive/ type TIME_SERIES' + ); + console.log(`Topic View ${topicView.name} has been created.`); + + for (let i = 0; i < 15; i++) { + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.int64(), + Date.now(), + { specification: specification } + ); + await new Promise((resolve) => setTimeout(resolve, 1000)); + } + /// tag::log + await new Promise((resolve) => setTimeout(resolve, 2000)); + /// end::log + + const queryResult = await session.timeseries.rangeQuery() + .fromStart() + .selectFrom('views/archive/my/topic/path'); + for (const event of queryResult.events) { + console.log(`${event.sequence} (${event.timestamp}): ${event.value}`); + } + /// tag::log + expect(queryResult.events.length).toBe(10); + /// end::log + + await session.closeSession(); + /// end::topic_views_dsl_options_topic_type[] +} diff --git a/js/wrangling/topic-views/dsl/options-topic-value.js b/js/wrangling/topic-views/dsl/options-topic-value.js new file mode 100644 index 00000000..4cd4b8ff --- /dev/null +++ b/js/wrangling/topic-views/dsl/options-topic-value.js @@ -0,0 +1,84 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } = require('../../../../../test/util'); +/// end::log + +export async function topicViewsDslOptionsTopicValue() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/1234' + ]]); + /// end::log + /// tag::topic_views_dsl_options_topic_value[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData = diffusion.datatypes.json().from({ + account: '1234', + balance: { + amount: 12.57, + currency: 'USD' + } + }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(diffusion.datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${oldValue.get()} to ${newValue.get()}`); + } + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + 'map my/topic/path to views/ as ' + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_options_topic_value[] + /// tag::log + await expectJsonTopicToHaveValue('views/1234', { + amount: 12.57, + currency: 'USD' + }); + + await check.done(); + /// end::log +} diff --git a/js/wrangling/topic-views/dsl/patch-transformations-add.js b/js/wrangling/topic-views/dsl/patch-transformations-add.js new file mode 100644 index 00000000..189dd6e9 --- /dev/null +++ b/js/wrangling/topic-views/dsl/patch-transformations-add.js @@ -0,0 +1,84 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } = require('../../../../../test/util'); +/// end::log + +export async function topicViewsDslPatchTransformationsAdd() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/my/topic/path' + ]]); + /// end::log + /// tag::topic_views_dsl_patch_transformations_add[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData = diffusion.datatypes.json().from({ + Fred: 'Flintstone', + Barney: 'Rubble' + }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(diffusion.datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + `map ?my/topic/path// to views/ patch '[ + { + "op": "add", + "path": "/George", + "value": "Jetson" + } + ]'` + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_patch_transformations_add[] + /// tag::log + await expectJsonTopicToHaveValue('views/my/topic/path', { + Fred: 'Flintstone', + Barney: 'Rubble', + George: 'Jetson' + }); + + await check.done(); + /// end::log +} diff --git a/js/wrangling/topic-views/dsl/patch-transformations-copy.js b/js/wrangling/topic-views/dsl/patch-transformations-copy.js new file mode 100644 index 00000000..df163239 --- /dev/null +++ b/js/wrangling/topic-views/dsl/patch-transformations-copy.js @@ -0,0 +1,94 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } = require('../../../../../test/util'); +/// end::log + +export async function topicViewsDslPatchTransformationsCopy() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/my/topic/path' + ]]); + /// end::log + /// tag::topic_views_dsl_patch_transformations_copy[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData = diffusion.datatypes.json().from({ + 'Meet the Flintstones': { + Fred: 'Flintstone', + Barne: 'Rubble' + }, + 'The Jetsons': { + George: 'Jetson' + } + }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(diffusion.datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + `map ?my/topic/path// to views/ patch '[ + { + "op": "copy", + "from": "/Meet the Flintstones/Fred", + "path": "/The Jetsons/Fred" + } + ]'` + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_patch_transformations_copy[] + /// tag::log + await expectJsonTopicToHaveValue('views/my/topic/path', { + 'Meet the Flintstones': { + Fred: 'Flintstone', + Barne: 'Rubble' + }, + 'The Jetsons': { + Fred: 'Flintstone', + George: 'Jetson' + } + }); + + await check.done(); + /// end::log +} diff --git a/js/wrangling/topic-views/dsl/patch-transformations-move.js b/js/wrangling/topic-views/dsl/patch-transformations-move.js new file mode 100644 index 00000000..98bdee25 --- /dev/null +++ b/js/wrangling/topic-views/dsl/patch-transformations-move.js @@ -0,0 +1,95 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } = require('../../../../../test/util'); +/// end::log + +export async function topicViewsDslPatchTransformationsMove() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/my/topic/path' + ]]); + /// end::log + /// tag::topic_views_dsl_patch_transformations_move[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData = diffusion.datatypes.json().from({ + Fred: 'Flintstone', + Barney: 'Rubble', + George: 'Jetson' + }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(diffusion.datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + `map ?my/topic/path// to views/ patch '[ + { + "op": "move", + "from": "/Fred", + "path": "/Meet The Flintstones~1Fred" + }, + { + "op": "move", + "from": "/Barney", + "path": "/Meet The Flintstones~1Barney" + }, + { + "op": "move", + "from": "/George", + "path": "/The Jetsons~1George" + } + ]'` + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_patch_transformations_move[] + /// tag::log + await expectJsonTopicToHaveValue('views/my/topic/path', { + "Meet The Flintstones/Fred": 'Flintstone', + "Meet The Flintstones/Barney": 'Rubble', + "The Jetsons/George": 'Jetson' + }); + + await check.done(); + /// end::log +} diff --git a/js/wrangling/topic-views/dsl/patch-transformations-remove.js b/js/wrangling/topic-views/dsl/patch-transformations-remove.js new file mode 100644 index 00000000..73e636b5 --- /dev/null +++ b/js/wrangling/topic-views/dsl/patch-transformations-remove.js @@ -0,0 +1,83 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } = require('../../../../../test/util'); +/// end::log + +export async function topicViewsDslPatchTransformationsRemove() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/my/topic/path' + ]]); + /// end::log + /// tag::topic_views_dsl_patch_transformations_remove[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData = diffusion.datatypes.json().from({ + Fred: 'Flintstone', + Barney: 'Rubble', + George: 'Jetson' + }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(diffusion.datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + `map ?my/topic/path// to views/ patch '[ + { + "op": "remove", + "path": "/George" + } + ]'` + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_patch_transformations_remove[] + /// tag::log + await expectJsonTopicToHaveValue('views/my/topic/path', { + Fred: 'Flintstone', + Barney: 'Rubble' + }); + + await check.done(); + /// end::log +} diff --git a/js/wrangling/topic-views/dsl/patch-transformations-replace.js b/js/wrangling/topic-views/dsl/patch-transformations-replace.js new file mode 100644 index 00000000..fe7acf5c --- /dev/null +++ b/js/wrangling/topic-views/dsl/patch-transformations-replace.js @@ -0,0 +1,85 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } = require('../../../../../test/util'); +/// end::log + +export async function topicViewsDslPatchTransformationsReplace() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/my/topic/path' + ]]); + /// end::log + /// tag::topic_views_dsl_patch_transformations_replace[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData = diffusion.datatypes.json().from({ + Fred: 'Flintstone', + Barney: 'Rubble', + George: 'Jetson' + }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(diffusion.datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + `map ?my/topic/path// to views/ patch '[ + { + "op": "replace", + "path": "/George", + "value": "Bedrock" + } + ]'` + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_patch_transformations_replace[] + /// tag::log + await expectJsonTopicToHaveValue('views/my/topic/path', { + Fred: 'Flintstone', + Barney: 'Rubble', + George: 'Bedrock' + }); + + await check.done(); + /// end::log +} diff --git a/js/wrangling/topic-views/dsl/patch-transformations-test.js b/js/wrangling/topic-views/dsl/patch-transformations-test.js new file mode 100644 index 00000000..738e5856 --- /dev/null +++ b/js/wrangling/topic-views/dsl/patch-transformations-test.js @@ -0,0 +1,85 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } = require('../../../../../test/util'); +/// end::log + +export async function topicViewsDslPatchTransformationsTest() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/my/topic/path' + ]]); + /// end::log + /// tag::topic_views_dsl_patch_transformations_test[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData = diffusion.datatypes.json().from({ + Fred: 'Flintstone', + Barney: 'Rubble', + George: 'Jetson' + }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(diffusion.datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + `map ?my/topic/path// to views/ patch '[ + { + "op": "test", + "path": "/Fred", + "value": "Flintstone" + } + ]'` + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_patch_transformations_test[] + /// tag::log + await expectJsonTopicToHaveValue('views/my/topic/path', { + Fred: 'Flintstone', + Barney: 'Rubble', + George: 'Jetson' + }); + + await check.done(); + /// end::log +} diff --git a/js/wrangling/topic-views/dsl/process-transformations-set-continue.js b/js/wrangling/topic-views/dsl/process-transformations-set-continue.js new file mode 100644 index 00000000..9b707f9e --- /dev/null +++ b/js/wrangling/topic-views/dsl/process-transformations-set-continue.js @@ -0,0 +1,96 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue, expectTopicCounts, PartiallyOrderedCheckpointTester } = require('../../../../../test/util'); +/// end::log + +export async function topicViewsDslProcessTransformationsContinue() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/2' + ]]); + /// end::log + /// tag::topic_views_dsl_process_transformations_continue[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData1 = diffusion.datatypes.json().from({ + name: 'APPL', + quantity: 100, + price_per_share: 12.34 + }); + await session.topicUpdate.set( + 'my/topic/path/1', + diffusion.datatypes.json(), + jsonData1, + { specification: specification } + ); + const jsonData2 = diffusion.datatypes.json().from({ + name: 'AMZN', + quantity: 256, + price_per_share: 87.65 + }); + await session.topicUpdate.set( + 'my/topic/path/2', + diffusion.datatypes.json(), + jsonData2, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(diffusion.datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + `map ?my/topic/path// to views/ + process + { + if '/price_per_share > 20' continue + }` + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_process_transformations_continue[] + /// tag::log + await expectJsonTopicToHaveValue('views/2', { + name: 'AMZN', + quantity: 256, + price_per_share: 87.65 + }); + + await expectTopicCounts({ 'views/1': 0 }); + + await check.done(); + /// end::log +} diff --git a/js/wrangling/topic-views/dsl/process-transformations-set-remove.js b/js/wrangling/topic-views/dsl/process-transformations-set-remove.js new file mode 100644 index 00000000..c66bb097 --- /dev/null +++ b/js/wrangling/topic-views/dsl/process-transformations-set-remove.js @@ -0,0 +1,100 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } = require('../../../../../test/util'); +/// end::log + +export async function topicViewsDslProcessTransformationsRemove() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/1', + 'Subscribed to views/2' + ]]); + /// end::log + /// tag::topic_views_dsl_process_transformations_remove[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData1 = diffusion.datatypes.json().from({ + name: 'APPL', + quantity: 100, + price_per_share: 12.34 + }); + await session.topicUpdate.set( + 'my/topic/path/1', + diffusion.datatypes.json(), + jsonData1, + { specification: specification } + ); + const jsonData2 = diffusion.datatypes.json().from({ + name: 'AMZN', + quantity: 256, + price_per_share: 87.65 + }); + await session.topicUpdate.set( + 'my/topic/path/2', + diffusion.datatypes.json(), + jsonData2, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(diffusion.datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + `map ?my/topic/path// to views/ + process + { + set(/total, calc '/quantity * /price_per_share'); + remove(/quantity); + remove(/price_per_share) + }` + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_process_transformations_remove[] + /// tag::log + await expectJsonTopicToHaveValue('views/1', { + name: 'APPL', + total: 1234 + }); + await expectJsonTopicToHaveValue('views/2', { + name: 'AMZN', + total: 256*87.65 + }); + + await check.done(); + /// end::log +} diff --git a/js/wrangling/topic-views/dsl/process-transformations-set.js b/js/wrangling/topic-views/dsl/process-transformations-set.js new file mode 100644 index 00000000..2a4e2e7e --- /dev/null +++ b/js/wrangling/topic-views/dsl/process-transformations-set.js @@ -0,0 +1,118 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } = require('../../../../../test/util'); +/// end::log + +export async function topicViewsDslProcessTransformationsSet() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/1', + 'Subscribed to views/2' + ]]); + /// end::log + /// tag::topic_views_dsl_process_transformations_set[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData1 = diffusion.datatypes.json().from({ + account: '1234', + balance: { + amount: 12.57, + currency: 'USD' + } + }); + await session.topicUpdate.set( + 'my/topic/path/1', + diffusion.datatypes.json(), + jsonData1, + { specification: specification } + ); + + const jsonData2 = diffusion.datatypes.json().from({ + account: '5678', + balance: { + amount: 98.76, + currency: 'USD' + } + }); + await session.topicUpdate.set( + 'my/topic/path/2', + diffusion.datatypes.json(), + jsonData2, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(diffusion.datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + `map ?my/topic/path// to views/ + process { + if '/balance/amount > 20' + set(/tier, 1) + else + set(/tier, 2) + } + process { + set(/balance/amount_in_cents, calc '/balance/amount * 100') + }` + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_process_transformations_set[] + /// tag::log + await expectJsonTopicToHaveValue('views/1', { + account: '1234', + balance: { + amount: 12.57, + amount_in_cents: 1257, + currency: 'USD' + }, + tier: 2 + }); + await expectJsonTopicToHaveValue('views/2', { + account: '5678', + balance: { + amount: 98.76, + amount_in_cents: 9876, + currency: 'USD' + }, + tier: 1 + }); + + await check.done(); + /// end::log +} diff --git a/js/wrangling/topic-views/dsl/remote-topic-view.js b/js/wrangling/topic-views/dsl/remote-topic-view.js new file mode 100644 index 00000000..19b08b46 --- /dev/null +++ b/js/wrangling/topic-views/dsl/remote-topic-view.js @@ -0,0 +1,47 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); + +export async function topicViewsDslRemoteTopicView() { + /// tag::topic_views_dsl_remote_topic_view[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const definition = diffusion.newRemoteServerBuilder() + .principal('admin') + .credentials('password') + .connectionOptions({ + [diffusion.ConnectionOption.RECONNECTION_TIMEOUT]: '120000', + [diffusion.ConnectionOption.MAXIMUM_QUEUE_SIZE]: '1000', + [diffusion.ConnectionOption.CONNECTION_TIMEOUT]: '15000' + }) + .create('Remote Server 1', 'ws://new.server.url.com'); + await session.remoteServers.createRemoteServer(definition); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + 'map my/topic/path from \'Remote Server 1\' to views/remote/' + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.remoteServers.removeRemoteServer('Remote Server 1'); + await session.closeSession(); + /// end::topic_views_dsl_remote_topic_view[] +} diff --git a/js/wrangling/topic-views/dsl/scalar-directive.js b/js/wrangling/topic-views/dsl/scalar-directive.js new file mode 100644 index 00000000..f0d833fd --- /dev/null +++ b/js/wrangling/topic-views/dsl/scalar-directive.js @@ -0,0 +1,84 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } = require('../../../../../test/util'); +/// end::log + +export async function topicViewsDslScalarDirective() { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Subscribed to views/currency/USD/account/1234'] + ]); + /// end::log + /// tag::topic_views_dsl_scalar_directive[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData = diffusion.datatypes.json().from({ + account: '1234', + balance: { + amount: 12.57, + currency: 'USD' + } + }); + await session.topicUpdate.set( + 'my/topic/path', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(diffusion.datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + 'map my/topic/path to views/currency//account/' + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_scalar_directive[] + /// tag::log + const expectedValue = { + account: '1234', + balance: { + amount: 12.57, + currency: 'USD' + } + }; + await expectJsonTopicToHaveValue('views/currency/USD/account/1234', expectedValue); + + await check.done(); + /// end::log +} diff --git a/js/wrangling/topic-views/dsl/source-path-directive.js b/js/wrangling/topic-views/dsl/source-path-directive.js new file mode 100644 index 00000000..12e1f5e4 --- /dev/null +++ b/js/wrangling/topic-views/dsl/source-path-directive.js @@ -0,0 +1,86 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +const diffusion = require('diffusion'); +/// tag::log +const { expectJsonTopicToHaveValue } = require('../../../../../test/util'); +/// end::log + +export async function topicViewsDslSourcePathDirective() { + /// tag::topic_views_dsl_source_path_directive[] + const session = await diffusion.connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new diffusion.topics.TopicSpecification(diffusion.topics.TopicType.JSON); + const jsonData = diffusion.datatypes.json().from({ + account: '1234', + balance: { + amount: 12.57, + currency: 'USD' + } + }); + await session.topicUpdate.set( + 'a/b/c/d/e/f/g', + diffusion.datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(diffusion.datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView1 = await session.topicViews.createTopicView( + 'topic_view_1', + 'map a/b/c/d/e/f/g to views/' + ); + console.log(`Topic View ${topicView1.name} has been created.`); + const topicView2 = await session.topicViews.createTopicView( + 'topic_view_2', + 'map a/b/c/d/e/f/g to views/' + ); + console.log(`Topic View ${topicView2.name} has been created.`); + const topicView3 = await session.topicViews.createTopicView( + 'topic_view_3', + 'map a/b/c/d/e/f/g to views/' + ); + console.log(`Topic View ${topicView3.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_source_path_directive[] + /// tag::log + const expectedValue = { + account: '1234', + balance: { + amount: 12.57, + currency: 'USD' + } + }; + await expectJsonTopicToHaveValue('views/a/b/c/d/e/f/g', expectedValue); + await expectJsonTopicToHaveValue('views/c/d/e/f/g', expectedValue); + await expectJsonTopicToHaveValue('views/d/e/f/g', expectedValue); + /// end::log +} diff --git a/python/README.md b/python/README.md deleted file mode 100644 index 2d012bac..00000000 --- a/python/README.md +++ /dev/null @@ -1,34 +0,0 @@ -# Diffusion Python Client Examples - -This project contains a set of examples for accessing the Diffusion server using the - Python SDK, grouped into directories representing different areas of Diffusion - functionalities. There are two types of examples for each area: - -* Short Python code snippets, each illustrating a single use case. These snippets can be - used directly in application code, making sure that various variables are changed to - reflect the actual system. -* Jupyter notebooks, which can be executed (assuming there is a running Diffusion server - they can connect to) to illustrate the functionalities in practice. The notebooks are - designed to work out of the box in most cases, provided there is a Diffusion server - they can connect to. - -Python Client for Diffusion can be installed using `pip`: -```shell -$ pip install diffusion -``` - -For more information on using Diffusion, please refer to the [online documentation](https://docs.pushtechnology.com). - -## Examples as Python Scripts -Each directory in the project includes one or more self-contained Python scripts. To - execute the example scripts, you can call them either directly or as Python modules: - -```shell script -$ python examples/messaging/send_request_to_path.py -$ python -m examples.messaging.send_request_to_path -``` - -## Examples as Jupyter Notebooks - -Each directory in the project also a Jupyter notebook for each example, with the same - functionality as the corresponding Python script. \ No newline at end of file diff --git a/python/examples/README.md b/python/examples/README.md new file mode 100644 index 00000000..e3369b3f --- /dev/null +++ b/python/examples/README.md @@ -0,0 +1,29 @@ +# Diffusion Python Client Examples + +This project contains a set of examples for accessing the Diffusion server using the + Python SDK, grouped into directories representing different areas of Diffusion + functionalities. Each illustrates a single use case. These snippets can be + used directly in application code, making sure that various variables are changed to + reflect the actual system. + +Python Client for Diffusion can be installed using `pip`: +```shell +$ pip install diffusion +``` + +For more information on using Diffusion, please refer to the [online documentation](https://docs.diffusiondata.com). + +## Examples as Python Scripts +Each directory in the project includes one or more self-contained Python scripts. To + execute the example scripts, you can call them either directly or as Python modules: + +```shell script +$ python src/diffusion_examples/mapping_and_wrangling/session_trees/get_branch_mapping_table.py +$ python -m diffusion_examples.mapping_and_wrangling.session_trees.get_branch_mapping_table +``` + +### Typical 'run' method arguments + +- `principal` - username of the principal connecting to the server +- `password` - password of the principal connecting to the server +- `server_url` - URL of the server diff --git a/python/examples/connecting/__init__.py b/python/examples/connecting/__init__.py deleted file mode 100644 index 9121b24c..00000000 --- a/python/examples/connecting/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -# Copyright (c) 2022 Push Technology Ltd., All Rights Reserved. -# -# Use is subject to license terms. -# -# NOTICE: All information contained herein is, and remains the -# property of Push Technology. The intellectual and technical -# concepts contained herein are proprietary to Push Technology and -# may be covered by U.S. and Foreign Patents, patents in process, and -# are protected by trade secret or copyright law. diff --git a/python/examples/connecting/initial_session_establishment_retry_strategy.py b/python/examples/connecting/initial_session_establishment_retry_strategy.py deleted file mode 100644 index e0f72a4a..00000000 --- a/python/examples/connecting/initial_session_establishment_retry_strategy.py +++ /dev/null @@ -1,71 +0,0 @@ -# Copyright (c) 2022 Push Technology Ltd., All Rights Reserved. -# -# Use is subject to license terms. -# -# NOTICE: All information contained herein is, and remains the -# property of Push Technology. The intellectual and technical -# concepts contained herein are proprietary to Push Technology and -# may be covered by U.S. and Foreign Patents, patents in process, and -# are protected by trade secret or copyright law. - -import asyncio -import traceback - -import diffusion -from diffusion.session.retry_strategy import RetryStrategy - -# Because Python SDK for Diffusion is async, all the code needs to be -# wrapped inside a coroutine function, and executed using asyncio.run. -from diffusion.session import SessionEstablishmentException - - -async def main(): - # tag::initial_retry_strategy[] - # Diffusion server connection information; same for both sessions - # adjust as needed for the server used in practice - server_url = "ws://localhost:8080" - principal = "admin" - credentials = diffusion.Credentials("password") - # Create an initial session establishment retry strategy. - # It will attempt 10 times to connect to the Diffusion server, - # with 5 seconds interval between attempts. - initial_retry_strategy = RetryStrategy(attempts=10, interval=5) - - # starting a session provided by using the results of - # SessionFactory.open() as an async context manager - try: - async with ( - diffusion.sessions() - .principal(principal) - .credentials(credentials) - .initial_retry_strategy(initial_retry_strategy) - .open(server_url) - ) as session: - print(f"Connected. Session Identifier: {session.session_id} (via context manager)") - - except SessionEstablishmentException: - print(f"Failed to open session: {traceback.format_exc()}") - raise - - # starting a session provided by using the results of - # awaiting SessionFactory.open() as a Session - try: - session = ( - await diffusion.sessions() - .principal(principal) - .credentials(credentials) - .initial_retry_strategy(initial_retry_strategy) - .open(server_url) - ) - print(f"Connected. Session Identifier: {session.session_id} (via await)") - except SessionEstablishmentException: - print(f"Failed to open session: {traceback.format_exc()}") - raise - finally: - await session.close() - - # end::initial_retry_strategy[] - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/python/examples/consuming/__init__.py b/python/examples/consuming/__init__.py deleted file mode 100644 index 9121b24c..00000000 --- a/python/examples/consuming/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -# Copyright (c) 2022 Push Technology Ltd., All Rights Reserved. -# -# Use is subject to license terms. -# -# NOTICE: All information contained herein is, and remains the -# property of Push Technology. The intellectual and technical -# concepts contained herein are proprietary to Push Technology and -# may be covered by U.S. and Foreign Patents, patents in process, and -# are protected by trade secret or copyright law. diff --git a/python/examples/consuming/time_series_topics.py b/python/examples/consuming/time_series_topics.py deleted file mode 100644 index 54ebcfa6..00000000 --- a/python/examples/consuming/time_series_topics.py +++ /dev/null @@ -1,140 +0,0 @@ -# Copyright (c) 2022 Push Technology Ltd., All Rights Reserved. -# -# Use is subject to license terms. -# -# NOTICE: All information contained herein is, and remains the -# property of Push Technology. The intellectual and technical -# concepts contained herein are proprietary to Push Technology and -# may be covered by U.S. and Foreign Patents, patents in process, and -# are protected by trade secret or copyright law. -import asyncio -import typing - -import diffusion.datatypes - -from diffusion.datatypes.timeseries import Event -from diffusion.features.timeseries import TimeSeries -from diffusion.features.topics import ValueStreamHandler -from diffusion.features.topics.details.topic_specification import TopicSpecification -from diffusion.internal.services.topics import UnsubscribeReason -from diffusion.internal.session.exception_handler import ErrorReason - - -# Diffusion server connection information; -# adjust as needed for the server used in practice. -server_url = "ws://localhost:8080" -principal = "admin" -credentials = diffusion.Credentials("password") - -TOPIC_PREFIX = "time-series" - - -async def main(): - """ - Client implementation which subscribes to a string time series topic and - consumes the data it receives. - """ - # Creating the session. - async with diffusion.Session( - url=server_url, principal=principal, credentials=credentials - ) as session: - # Create a string topic - topic_type = diffusion.datatypes.STRING - topic = f"?{TOPIC_PREFIX}/{topic_type.type_name}//" - - # Add a value stream - time_series_string_stream = TimeSeriesStringStream() - session.topics.add_value_stream(topic, time_series_string_stream) - - # Subscribe to the topic - await session.topics.subscribe(topic) - - # Run until the ending of the example - await asyncio.sleep(0.3) - - -# noinspection PyUnusedLocal -class TimeSeriesStringStream(ValueStreamHandler): - """ - Basic implementation of the ValueStreamHandler for time series string topics. - """ - def __init__(self): - super().__init__( - TimeSeries.of(diffusion.datatypes.STRING), - update=self.update, - subscribe=self.subscribe, - unsubscribe=self.unsubscribe, - error=self.error, - close=self.close, - ) - - async def close(self): - """ - Notification of the stream being closed normally. - """ - print("The subscrption stream is now closed.") - - async def error(self, error_reason: ErrorReason): - """ - Notification of a contextual error related to this callback. - - Situations in which OnError is called include - the session being closed, a communication - timeout, or a problem with the provided parameters. - No further calls will be made to this callback. - - Args: - error_reason: Error reason. - """ - print(f"An error has occured : {error_reason}.") - - async def subscribe( - self, - *, - topic_path: str, - topic_spec: TopicSpecification, - topic_value: typing.Optional[Event[diffusion.datatypes.STRING]] = None, - ): - """ - Notification of a successful subscription. - - Args: - topic_path: Topic path. - topic_spec: Topic specification. - topic_value: Topic value. - """ - print(f"Client subscribed to {topic_path}.") - - async def unsubscribe( - self, - *, - topic_path: str, - topic_spec: TopicSpecification, - reason: typing.Optional[UnsubscribeReason] = None, - ): - """ - Args: - topic_path: Topic path. - topic_spec: Topic specification. - reason: error reason. - """ - print(f"Client unsubscribed from {topic_path} : {reason}.") - - async def update( - self, - *, - topic_path: str, - topic_spec: TopicSpecification, - old_value: Event[diffusion.datatypes.STRING], - topic_value: Event[diffusion.datatypes.STRING], - ): - """ - Topic update received. - - Args: - topic_path: Topic path. - topic_spec: Topic specification. - old_value: Value prior to update. - topic_value: Value after update. - """ - print(f"New value of {topic_path} is {topic_value}.") diff --git a/python/examples/features/__init__.py b/python/examples/features/__init__.py deleted file mode 100644 index 9121b24c..00000000 --- a/python/examples/features/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -# Copyright (c) 2022 Push Technology Ltd., All Rights Reserved. -# -# Use is subject to license terms. -# -# NOTICE: All information contained herein is, and remains the -# property of Push Technology. The intellectual and technical -# concepts contained herein are proprietary to Push Technology and -# may be covered by U.S. and Foreign Patents, patents in process, and -# are protected by trade secret or copyright law. diff --git a/python/examples/features/session_locks.py b/python/examples/features/session_locks.py deleted file mode 100644 index d13df918..00000000 --- a/python/examples/features/session_locks.py +++ /dev/null @@ -1,81 +0,0 @@ -import asyncio -import dataclasses -import traceback -import typing - -import diffusion -from diffusion.session import SessionLockScope -from diffusion.session.locks.session_locks import SessionLock - -LOCK_NAME = "lockA" - - -async def main( - server_url: str = "", - principal: str = "", - password: str = "", -): - async with diffusion.Session( - url=server_url, principal=principal, credentials=diffusion.Credentials(password) - ) as session1, diffusion.Session( - url=server_url, principal=principal, credentials=diffusion.Credentials(password) - ) as session2: - print("Sessions 1 and 2 have been created.") - await ContendedCluster(session1, session2).acquire_lock_session1() - - -# noinspection PyBroadException -@dataclasses.dataclass -class ContendedCluster(object): - session1: diffusion.Session - session2: diffusion.Session - _session_lock1: typing.Optional[SessionLock] = dataclasses.field(init=False, default=None) - _session_lock2: typing.Optional[SessionLock] = dataclasses.field(init=False, default=None) - - async def acquire_lock_session1(self): - try: - print("Requesting lock 1...") - self._session_lock1 = await self.session1.lock( - LOCK_NAME, SessionLockScope.UNLOCK_ON_CONNECTION_LOSS - ) - print("Lock 1 has been acquired.") - asyncio.create_task( - self.acquire_lock_session2() - ) # spawn as a "background" task - await asyncio.sleep(1) - await self.release_lock1() - except Exception as ex: - print(f"Failed to get lock 1 : {traceback.format_exc()}.") - - async def acquire_lock_session2(self): - try: - print("Requesting lock 2...") - self._session_lock2 = await self.session2.lock( - LOCK_NAME, SessionLockScope.UNLOCK_ON_CONNECTION_LOSS - ) - print("Lock 2 has been acquired.") - await asyncio.sleep(1) - await self.release_lock2() - except Exception: - print(f"Failed to get lock 2 : {traceback.format_exc()}.") - - async def release_lock1(self): - try: - print("Requesting lock 1 release...") - await self._session_lock1.unlock() - print("Lock 1 has been released.") - except Exception as ex: - print(f"Failed to release lock 1 : {traceback.format_exc()}.") - - async def release_lock2(self): - try: - print("Requesting lock 2 release...") - await self._session_lock2.unlock() - print("Lock 2 has been released.") - except Exception as ex: - print(f"Failed to release lock 2 : {traceback.format_exc()}.") - - -asyncio.run( - main(server_url="ws://localhost:8080", principal="control", password="password") -) diff --git a/python/examples/messaging/add_request_handler.py b/python/examples/messaging/add_request_handler.py deleted file mode 100644 index 060edf9a..00000000 --- a/python/examples/messaging/add_request_handler.py +++ /dev/null @@ -1,62 +0,0 @@ -""" Example of setting a request handler. """ -import asyncio -import diffusion - -from diffusion.messaging import RequestHandler - - -# Diffusion server connection information; -# adjust as needed for the server used in practice. -server_url = "ws://localhost:8080" -principal = "admin" -credentials = diffusion.Credentials("password") - - -# handler callback function -def callback(request: str, context=None) -> diffusion.datatypes.STRING: - return diffusion.datatypes.STRING(f"Hello there, {request}!") - - -path = "path" -request_type = diffusion.datatypes.STRING # datatype of the request - - -# Because Python SDK for Diffusion is async, all the code needs to be -# wrapped inside a coroutine function, and executed using asyncio.run. -async def main(): - - # creating the session - async with diffusion.Session( - url=server_url, principal=principal, credentials=credentials - ) as session: - - # registering the request handler - print("Registering the request handler...") - - handler = RequestHandler( - callback, - request_type=request_type, - response_type=request_type - ) - - try: - await session.messaging.add_request_handler( - path, - handler=handler - ) - - except diffusion.DiffusionError as ex: - print(f"ERROR: {ex}") - else: - print("... request handler registered") - - # For the duration of the session, any requests of the right type sent - # to the path will be received by the session, and then processed and - # responded to by the callback function registered above. - - # keeping the session alive for 15 seconds - await asyncio.sleep(15) - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/python/examples/messaging/send_request_to_filter.py b/python/examples/messaging/send_request_to_filter.py deleted file mode 100644 index cf39bb1c..00000000 --- a/python/examples/messaging/send_request_to_filter.py +++ /dev/null @@ -1,95 +0,0 @@ -""" Example of sending a request to a session filter. """ -import asyncio -import diffusion - -from diffusion.messaging import RequestHandler - -# Diffusion server connection information; same for both sessions -# adjust as needed for the server used in practice -server_url = "ws://localhost:8080" -principal = "admin" -credentials = diffusion.Credentials("password") - - -# filter response handler function -def on_filter_response(response, **kwargs): - print("Received response from session '{session_id}':".format(**kwargs)) - print(f" - Response: {response}") - print(" - Request was sent to {filter} on path '{path}'".format(**kwargs)) - print(" - Received {received} of {expected} response(s).".format(**kwargs)) - - -# error handler function -def on_error(code: int, description: str): - print("ERROR received via filter response handler {code}: {description}") - - -filter_response_handler = diffusion.handlers.EventStreamHandler( - response=on_filter_response, - on_error=on_error -) - - -# Messaging request callback function -def callback(request: str, **kwargs) -> diffusion.datatypes.STRING: - return diffusion.datatypes.STRING(f"Hello there, {request}!") - - -# request properties -request = "Pushme Pullyou" -path = "path" -request_type = diffusion.datatypes.STRING # datatype of the request - - -# Because Python SDK for Diffusion is async, all the code needs to be -# wrapped inside a coroutine function, and executed using asyncio.run. -async def main(): - - # creating the session - async with diffusion.Session( - url=server_url, principal=principal, credentials=credentials - ) as session: - - # specifying the session filter - # this is a very simple filter, addressing all the sessions - # with the same principal as the current session - session_filter = f"$Principal is '{principal}'" - - # Register handler to receive the request - handler = RequestHandler( - callback, - request_type=request_type, - response_type=request_type - ) - session.messaging.add_stream_handler(path, handler=handler, addressed=True) - - # adding filter response handler - session.messaging.add_filter_response_handler( - session_filter=session_filter, handler=filter_response_handler - ) - - # sending the request and receiving the number of expected responses - print(f"Sending request: '{request}' to session filter `{session_filter}`...") - try: - response = await session.messaging.send_request_to_filter( - session_filter=session_filter, - path=path, - request=request_type(request), - ) - except diffusion.DiffusionError as ex: - print(f"ERROR while sending request to session filter: {ex}") - else: - print(f"... expecting {response} response(s) ...") - - # The response received from the server is the number of sessions that - # match the filter, i.e. that the request will be forwarded to. All of - # these sessions that have a handler for the given path should send - # a response, which will be handled by the filter response handlers - # added above. - - # keeping the session alive to provide time for all responses to arrive - await asyncio.sleep(15) - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/python/examples/messaging/send_request_to_path.py b/python/examples/messaging/send_request_to_path.py deleted file mode 100644 index 0c81bff7..00000000 --- a/python/examples/messaging/send_request_to_path.py +++ /dev/null @@ -1,64 +0,0 @@ -""" Example of sending a request to a path. """ -import asyncio -import diffusion - -from diffusion.messaging import RequestHandler - -# Diffusion server connection information; -# adjust as needed for the server used in practice. -server_url = "ws://localhost:8080" -principal = "admin" -credentials = diffusion.Credentials("password") - - -def callback(request: str, **kwargs) -> diffusion.datatypes.STRING: - return diffusion.datatypes.STRING(f"Hello there, {request}!") - - -# request properties -request = "Pushme Pullyou" -path = "path" -request_type = diffusion.datatypes.STRING # datatype of the request - - -# Because Python SDK for Diffusion is async, all the code needs to be -# wrapped inside a coroutine function, and executed using asyncio.run. -async def main(): - - # Creating the session. - async with diffusion.Session( - url=server_url, principal=principal, credentials=credentials - ) as session: - - # Register handler to receive the request - handler = RequestHandler( - callback, - request_type=request_type, - response_type=request_type - ) - - print("Registering request handler...") - try: - await session.messaging.add_request_handler(path, handler=handler) - except diffusion.DiffusionError as ex: - print(f"ERROR: {ex}") - else: - print("... request handler registered") - - # Sending the request and receiving the response. - print(f"Sending request: '{request}' to path '{path}'...") - try: - response = await session.messaging.send_request_to_path( - path=path, request=request_type(request) - ) - except diffusion.DiffusionError as ex: - print(f"ERROR: {ex}") - else: - print(f"... received response '{response}'") - - # keeping the session alive to provide time for all responses to arrive - await asyncio.sleep(15) - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/python/examples/messaging/send_request_to_session.py b/python/examples/messaging/send_request_to_session.py deleted file mode 100644 index 8777bd07..00000000 --- a/python/examples/messaging/send_request_to_session.py +++ /dev/null @@ -1,62 +0,0 @@ -""" Example of sending a request to a single session. """ -import asyncio -import diffusion - -from diffusion.messaging import RequestHandler - - -# Diffusion server connection information; -# adjust as needed for the server used in practice. -server_url = "ws://localhost:8080" -principal = "admin" -credentials = diffusion.Credentials("password") - - -def callback(request: str, **kwargs) -> diffusion.datatypes.STRING: - return diffusion.datatypes.STRING(f"Hello there, {request}!") - - -# request properties -request = "Pushme Pullyou" -path = "path" -request_type = diffusion.datatypes.STRING # datatype of the request - - -# Because Python SDK for Diffusion is async, all the code needs to be -# wrapped inside a coroutine function, and executed using asyncio.run. -async def main(): - - # Creating the session. - async with diffusion.Session( - url=server_url, principal=principal, credentials=credentials - ) as session: - - # Specifying the recipient session ID. In this example, the session - # simply sends a request to itself; change as needed. - session_id = session.session_id - - # Register handler to receive the request - handler = RequestHandler( - callback, - request_type=request_type, - response_type=request_type - ) - session.messaging.add_stream_handler(path, handler=handler, addressed=True) - - # Sending the request and receiving the response. - print(f"Sending request: '{request}' to session {session_id}...") - try: - response = await session.messaging.send_request_to_session( - path=path, session_id=session_id, request=request_type(request) - ) - except diffusion.DiffusionError as ex: - print(f"ERROR: {ex}") - else: - print(f"... received response '{response}'") - - # keeping the session alive to provide time for all responses to arrive - await asyncio.sleep(15) - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/python/examples/metrics/session_metrics.py b/python/examples/metrics/session_metrics.py deleted file mode 100644 index b9fb30aa..00000000 --- a/python/examples/metrics/session_metrics.py +++ /dev/null @@ -1,83 +0,0 @@ -# Copyright (c) 2021 Push Technology Ltd., All Rights Reserved. -# -# Use is subject to license terms. -# -# NOTICE: All information contained herein is, and remains the -# property of Push Technology. The intellectual and technical -# concepts contained herein are proprietary to Push Technology and -# may be covered by U.S. and Foreign Patents, patents in process, and -# are protected by trade secret or copyright law. - -# Client implementation that demonstrates the session metric collector. - -import asyncio -import diffusion -from diffusion.features.control.metrics.session_metrics import SessionMetricCollectorBuilder - -server_url = "ws://localhost:8080" -principal = "admin" -credentials = diffusion.Credentials("password") - - -# Because Python SDK for Diffusion is async, all the code needs to be -# wrapped inside a coroutine function, and executed using asyncio.run. -async def main(): - # Runs the session metric collector example. - # creating the session - async with diffusion.Session( - url=server_url, principal=principal, credentials=credentials - ) as session: - metrics = session.metrics - session_filter = "x is 'y'" - - try: - print( - f"""\ -Adding the session metric collector 'Test' with session filter '{session_filter}'.""" - ) - - collector = ( - SessionMetricCollectorBuilder() - .group_by_properties("$Location") - .remove_metrics_with_no_matches(True) - .maximum_groups(10) - .create("Test", session_filter) - ) - - await metrics.put_session_metric_collector(collector) - - print(f"Session metric collector '{collector.name}' added.") - except Exception as ex: - print(f"Failed to add session metric collector : {ex}.") - return - - try: - print("The following session metric collectors exist:") - - listSessionMetricCollectors = await metrics.list_session_metric_collectors() - - for session_metric_collector in listSessionMetricCollectors: - print( - f""" -Name: '{session_metric_collector.name}', -Session filter: '{session_metric_collector.session_filter}', -Maximum Groups: {session_metric_collector.maximum_groups}, -Exports to Prometheus: '{session_metric_collector.exports_to_prometheus}', -Removes metrics with no matches: '{session_metric_collector.removes_metrics_with_no_matches}' - """ - ) - - for property in session_metric_collector.group_by_properties: - print(f"Group by: '{property}' property") - except Exception as ex: - print(f"Failed to list session metric collectors : {ex}.") - - try: - await metrics.remove_session_metric_collector(collector.name) - - print(f"Collector '{collector.name}' removed.") - except Exception as ex: - print(f"Failed to remove session metric collector : {ex}.") - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/python/examples/metrics/topic_metrics.py b/python/examples/metrics/topic_metrics.py deleted file mode 100644 index 0e609a92..00000000 --- a/python/examples/metrics/topic_metrics.py +++ /dev/null @@ -1,83 +0,0 @@ -# Copyright (c) 2021-2023 Push Technology Ltd., All Rights Reserved. -# -# Use is subject to license terms. -# -# NOTICE: All information contained herein is, and remains the -# property of Push Technology. The intellectual and technical -# concepts contained herein are proprietary to Push Technology and -# may be covered by U.S. and Foreign Patents, patents in process, and -# are protected by trade secret or copyright law. - -# Client implementation that demonstrates the session metric collector. - -import asyncio -import diffusion -from diffusion.features.control.metrics.topic_metrics import TopicMetricCollectorBuilder - -server_url = "ws://localhost:8080" -principal = "admin" -credentials = diffusion.Credentials("password") - - -# Because Python SDK for Diffusion is async, all the code needs to be -# wrapped inside a coroutine function, and executed using asyncio.run. -async def main(): - # Runs the session metric collector example. - # creating the session - async with diffusion.Session( - url=server_url, principal=principal, credentials=credentials - ) as session: - metrics = session.metrics - topic_selector = "selector" - - try: - print( - f"""\ -Adding the topic metric collector 'Test' with topic selector '{topic_selector}'. - """ - ) - - collector = ( - TopicMetricCollectorBuilder() - .group_by_topic_type(True) - .maximum_groups(10) - .group_by_path_prefix_parts(55) - .create("Test", topic_selector) - ) - - await metrics.put_topic_metric_collector(collector) - - print(f"Topic metric collector '{collector.name}' added.") - except Exception as ex: - print(f"Failed to add topic metric collector : {ex}.") - return - - try: - print("The following topic metric collectors exist:") - - list_topic_metric_collectors = await metrics.list_topic_metric_collectors() - - for topic_metric_collector in list_topic_metric_collectors: - print( - f"""\ -Name: '{topic_metric_collector.name}', \ -Maximum Groups: {topic_metric_collector.maximum_groups}, \ -Topic selector: '{topic_metric_collector.topic_selector}', \ -Group By Path Prefix Parts: {topic_metric_collector.group_by_path_prefix_parts}, \ -Exports to Prometheus: '{topic_metric_collector.exports_to_prometheus}', \ -Groups by topic type: '{topic_metric_collector.groups_by_topic_type}''""" - ) - except Exception as ex: - print(f"Failed to list topic metric collectors : {ex}.") - return - - try: - await metrics.remove_topic_metric_collector(collector.name) - - print(f"Collector '{collector.name}' removed.") - except Exception as ex: - print(f"Failed to remove topic metric collector : {ex}.") - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/python/examples/publishing/__init__.py b/python/examples/publishing/__init__.py deleted file mode 100644 index 9121b24c..00000000 --- a/python/examples/publishing/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -# Copyright (c) 2022 Push Technology Ltd., All Rights Reserved. -# -# Use is subject to license terms. -# -# NOTICE: All information contained herein is, and remains the -# property of Push Technology. The intellectual and technical -# concepts contained herein are proprietary to Push Technology and -# may be covered by U.S. and Foreign Patents, patents in process, and -# are protected by trade secret or copyright law. diff --git a/python/examples/publishing/time_series_add_topics.py b/python/examples/publishing/time_series_add_topics.py deleted file mode 100644 index ab41d655..00000000 --- a/python/examples/publishing/time_series_add_topics.py +++ /dev/null @@ -1,68 +0,0 @@ -# Copyright (c) 2022 Push Technology Ltd., All Rights Reserved. -# -# Use is subject to license terms. -# -# NOTICE: All information contained herein is, and remains the -# property of Push Technology. The intellectual and technical -# concepts contained herein are proprietary to Push Technology and -# may be covered by U.S. and Foreign Patents, patents in process, and -# are protected by trade secret or copyright law. - - -# -# Control client implementation that adds a time series topic. -# - -import asyncio -import datetime - -import diffusion -import diffusion.datatypes - - -# Diffusion server connection information; -# adjust as needed for the server used in practice. -from diffusion.features.timeseries import TimeSeries - -server_url = "ws://localhost:8080" -principal = "admin" -credentials = diffusion.Credentials("password") - -TOPIC_PREFIX = "time-series" - - -async def main(): - """ - Runs the time series add topics control client example. - """ - # Creating the session. - async with diffusion.Session( - url=server_url, principal=principal, credentials=credentials - ) as session: - # Create a string topic - topic_type = diffusion.datatypes.STRING - topic = f"{TOPIC_PREFIX}/{topic_type.type_name}/{datetime.datetime.utcnow()}" - specification = TimeSeries.of(topic_type).with_properties() - - try: - await session.topics.add_topic(topic, specification) - - new_value = f"{datetime.datetime.today()} {datetime.datetime.now().time()}" - - try: - await session.topics.set_topic( - topic, new_value, diffusion.datatypes.STRING - ) - await asyncio.sleep(0.3) - except Exception as ex: - print(f"Topic {topic} could not be updated : {ex}.") - except Exception as ex: - print(f"Failed to add topic '{topic}' : {ex}.") - await session.close() - return - - # Remove the string topic - try: - await session.topics.remove_topic(topic) - except Exception as ex: - print(f"Failed to remove topic '{topic}' : {ex}.") diff --git a/python/examples/publishing/time_series_append.py b/python/examples/publishing/time_series_append.py deleted file mode 100644 index d2b4d2ba..00000000 --- a/python/examples/publishing/time_series_append.py +++ /dev/null @@ -1,73 +0,0 @@ -# Copyright (c) 2022 Push Technology Ltd., All Rights Reserved. -# -# Use is subject to license terms. -# -# NOTICE: All information contained herein is, and remains the -# property of Push Technology. The intellectual and technical -# concepts contained herein are proprietary to Push Technology and -# may be covered by U.S. and Foreign Patents, patents in process, and -# are protected by trade secret or copyright law. - - -# Control client implementation that appends values to a time series topic. - -import asyncio -import datetime - -import diffusion -import diffusion.datatypes - - -from diffusion.features.timeseries import TimeSeries - -# Diffusion server connection information; -# adjust as needed for the server used in practice. -server_url = "ws://localhost:8080" -principal = "admin" -credentials = diffusion.Credentials("password") - -TOPIC_PREFIX = "time-series" - - -async def main(): - """ - Runs the time series topic append control client example. - """ - # Creating the session. - async with diffusion.Session( - url=server_url, principal=principal, credentials=credentials - ) as session: - # Create a string topic - topic_type = diffusion.datatypes.STRING - topic_path = f"{TOPIC_PREFIX}/{topic_type.type_name}/{datetime.datetime.utcnow()}" - specification = TimeSeries.of(topic_type).with_properties() - - try: - await session.topics.add_topic(topic_path, specification) - except Exception as ex: - print(f"Failed to add topic '{topic_path}' : {ex}.") - await session.close() - return - - try: - await session.time_series.append( - topic_path, "Value 1", diffusion.datatypes.STRING - ) - await session.time_series.append( - topic_path, "Value 2", diffusion.datatypes.STRING - ) - await session.time_series.append( - topic_path, "Value 3", diffusion.datatypes.STRING - ) - await session.time_series.append( - topic_path, "Value 4", diffusion.datatypes.STRING - ) - await asyncio.sleep(0.3) - except Exception as ex: - print(f"Topic {topic_path} value could not be appended : {ex}.") - - # Remove the string topic - try: - await session.topics.remove_topic(topic_path) - except Exception as ex: - print(f"Failed to remove topic '{topic_path}' : {ex}.") diff --git a/python/examples/publishing/time_series_append_with_timestamp.py b/python/examples/publishing/time_series_append_with_timestamp.py deleted file mode 100644 index d18c2c25..00000000 --- a/python/examples/publishing/time_series_append_with_timestamp.py +++ /dev/null @@ -1,96 +0,0 @@ -# Copyright (c) 2022 Push Technology Ltd., All Rights Reserved. -# -# Use is subject to license terms. -# -# NOTICE: All information contained herein is, and remains the -# property of Push Technology. The intellectual and technical -# concepts contained herein are proprietary to Push Technology and -# may be covered by U.S. and Foreign Patents, patents in process, and -# are protected by trade secret or copyright law. - - -import asyncio -import datetime - -import diffusion -import diffusion.datatypes - - -# Diffusion server connection information; -# adjust as needed for the server used in practice. -from diffusion.features.timeseries import TimeSeries - -server_url = "ws://localhost:8080" -principal = "admin" -credentials = diffusion.Credentials("password") - -TOPIC_PREFIX = "time-series" - - -async def main(): - """ - Control client implementation that appends values - with a user supplied timestamp to a time series topic. - """ - # Creating the session. - async with diffusion.Session( - url=server_url, principal=principal, credentials=credentials - ) as session: - # Create a string topic - topic_type = diffusion.datatypes.STRING - topic_path = f"{TOPIC_PREFIX}/{topic_type.type_name}/{datetime.datetime.utcnow()}" - specification = TimeSeries.of(topic_type).with_properties() - - try: - await session.topics.add_topic(topic_path, specification) - except Exception as ex: - print(f"Failed to add topic '{topic_path}' : {ex}.") - await session.close() - return - - try: - await session.time_series.append( - topic_path, - "Value1", - diffusion.datatypes.STRING, - timestamp=datetime.datetime.now() - + datetime.timedelta(milliseconds=322), - ) - await session.time_series.append( - topic_path, - "Value1", - diffusion.datatypes.STRING, - timestamp=datetime.datetime.now() - + datetime.timedelta(milliseconds=323), - ) - await session.time_series.append( - topic_path, - "Value1", - diffusion.datatypes.STRING, - timestamp=datetime.datetime.now() - + datetime.timedelta(milliseconds=323), - ) - await session.time_series.append( - topic_path, - "Value1", - diffusion.datatypes.STRING, - timestamp=datetime.datetime.now() - + datetime.timedelta(milliseconds=324), - ) - await session.time_series.append( - topic_path, - "Value1", - diffusion.datatypes.STRING, - timestamp=datetime.datetime.now() - + datetime.timedelta(milliseconds=325), - ) - - await asyncio.sleep(0.3) - except Exception as ex: - print(f"Topic {topic_path} value could not be appended : {ex}.") - - # Remove the string topic - try: - await session.topics.remove_topic(topic_path) - except Exception as ex: - print(f"Failed to remove topic '{topic_path}' : {ex}.") diff --git a/python/examples/publishing/time_series_edit.py b/python/examples/publishing/time_series_edit.py deleted file mode 100644 index 3df6ef9b..00000000 --- a/python/examples/publishing/time_series_edit.py +++ /dev/null @@ -1,77 +0,0 @@ -# Copyright (c) 2022 Push Technology Ltd., All Rights Reserved. -# -# Use is subject to license terms. -# -# NOTICE: All information contained herein is, and remains the -# property of Push Technology. The intellectual and technical -# concepts contained herein are proprietary to Push Technology and -# may be covered by U.S. and Foreign Patents, patents in process, and -# are protected by trade secret or copyright law. - - -# Control client implementation that edits values of a time series topic. - -import datetime -import diffusion -import diffusion.datatypes - - -# Diffusion server connection information; -# adjust as needed for the server used in practice. -from diffusion.features.timeseries import TimeSeries - -server_url = "ws://localhost:8080" -principal = "admin" -credentials = diffusion.Credentials("password") - -TOPIC_PREFIX = "time-series" - - -async def main(): - """ - Runs the time series topic edit control client example. - """ - # Creating the session. - async with diffusion.Session( - url=server_url, principal=principal, credentials=credentials - ) as session: - # Create a string topic - topic_type = diffusion.datatypes.STRING - topic_path = f"{TOPIC_PREFIX}/{topic_type.type_name}/{datetime.datetime.utcnow()}" - specification = TimeSeries.of(topic_type).with_properties() - - try: - await session.topics.add_topic(topic_path, specification) - except Exception as ex: - print(f"Failed to add topic '{topic_path}' : {ex}.") - await session.close() - return - - try: - await session.time_series.append( - topic_path, "Value 1", diffusion.datatypes.STRING - ) - except Exception as ex: - print(f"Topic {topic_path} value could not be appended : {ex}.") - - try: - await session.time_series.edit( - topic_path, 0, "Value 1a", diffusion.datatypes.STRING - ) - await session.time_series.edit( - topic_path, 0, "Value 1b", diffusion.datatypes.STRING - ) - await session.time_series.edit( - topic_path, 0, "Value 1c", diffusion.datatypes.STRING - ) - await session.time_series.edit( - topic_path, 0, "Value 1d", diffusion.datatypes.STRING - ) - except Exception as ex: - print(f"Topic {topic_path} value could not be edited : {ex}.") - - # Remove the string topic - try: - await session.topics.remove_topic(topic_path) - except Exception as ex: - print(f"Failed to remove topic '{topic_path}' : {ex}.") diff --git a/python/examples/publishing/time_series_range_query.py b/python/examples/publishing/time_series_range_query.py deleted file mode 100644 index 731e6d06..00000000 --- a/python/examples/publishing/time_series_range_query.py +++ /dev/null @@ -1,101 +0,0 @@ -# Copyright (c) 2022 Push Technology Ltd., All Rights Reserved. -# -# Use is subject to license terms. -# -# NOTICE: All information contained herein is, and remains the -# property of Push Technology. The intellectual and technical -# concepts contained herein are proprietary to Push Technology and -# may be covered by U.S. and Foreign Patents, patents in process, and -# are protected by trade secret or copyright law. - - -# Control client implementation that performs a range query of a time series. - -import diffusion -from datetime import datetime, timedelta -from diffusion.features.timeseries import TimeSeries -from diffusion.datatypes import STRING - -# Diffusion server connection information; -# adjust as needed for the server used in practice. -server_url = "ws://localhost:8080" -principal = "admin" -credentials = diffusion.Credentials("password") - -TOPIC_PREFIX = "time-series" - - -async def main(): - """ - Runs the time series topic range query example. - """ - # Creating the session. - async with diffusion.Session( - url=server_url, principal=principal, credentials=credentials - ) as session: - # Create a string topic - data_type = STRING - topic_path = f"{TOPIC_PREFIX}/{data_type.type_name}/{datetime.utcnow()}" - specification = TimeSeries.of(data_type) - - try: - await session.topics.add_topic(topic_path, specification) - except Exception as ex: - print(f"Failed to add topic '{topic_path}' : {ex}.") - return - - epoch = datetime.fromtimestamp(0) - try: - await session.time_series.append( - topic_path, "Value1", STRING, epoch + timedelta(milliseconds=200) - ) - await session.time_series.append( - topic_path, "Value2", STRING, epoch + timedelta(milliseconds=301) - ) - await session.time_series.append( - topic_path, "Value3", STRING, epoch + timedelta(milliseconds=301) - ) - await session.time_series.append( - topic_path, "Value4", STRING, epoch + timedelta(milliseconds=301) - ) - await session.time_series.append( - topic_path, "Value5", STRING, epoch + timedelta(milliseconds=324) - ) - await session.time_series.append( - topic_path, "Value6", STRING, epoch + timedelta(milliseconds=501) - ) - await session.time_series.append( - topic_path, "Value7", STRING, epoch + timedelta(milliseconds=501) - ) - await session.time_series.append( - topic_path, "Value8", STRING, epoch + timedelta(milliseconds=501) - ) - - except Exception as ex: - print(f"Topic {topic_path} value could not be appended : {ex}.") - - try: - range_query = session.time_series.range_query(STRING) - - range = await ( - range_query.from_(timedelta(milliseconds=301)) - .to(timedelta(milliseconds=501)) - .select_from(topic_path) - ) - - results = range.events - print(f"{len(results)} results obtained from range query (301 to 501):") - - for result in results: - print( - f"Sequence number: {result.metadata.sequence}, Value: {result.value} " - f"with Timestamp: {result.metadata.timestamp}" - ) - except Exception as ex: - print(f"Range query failed for topic {topic_path} : {ex}.") - - # Remove the string topic - try: - await session.topics.remove_topic(topic_path) - except Exception as ex: - print(f"Failed to remove topic '{topic_path}' : {ex}.") diff --git a/python/examples/pyproject.toml b/python/examples/pyproject.toml new file mode 100644 index 00000000..546b72cb --- /dev/null +++ b/python/examples/pyproject.toml @@ -0,0 +1,97 @@ +[build-system] +requires = ["setuptools >= 40.8.0", "wheel"] +build-backend = "setuptools.build_meta" +isolated_build = true + +[tool.black] +line-length = 96 +target-version = ["py38", "py39", "py310", "py311", "py312"] +verbose = false +skip-string-normalization = false + +[tool.pytest.ini_options] +testpaths = "src/diffusion_examples" +junit_family = "xunit2" +cache_dir = "target/.pytest_cache" +filterwarnings = ["ignore:coroutine 'Connection.read_loop' was never awaited", ] +markers = [ + "slow: marks tests as slow (deselect with '-m \"not slow\"')" +] +python_files = [ "conftest.py","*.py", "test_*.py"] +python_functions = ["run"] +asyncio_mode = "auto" + +[tool.mypy] +mypy_path = "diffusion/" +cache_dir = "target/.mypy_cache" +ignore_missing_imports = true +disallow_untyped_defs = false +exclude = [ + "csharp" +] + +[tool.pydantic-pycharm-plugin] +constrained-type = "lenient" +parsable-type-highlight = "disable" +acceptable-type-highlight = "disable" + +[tool.pydantic-pycharm-plugin.parsable-types] +diffusion.internal.validation.pydantic.StrictPositiveInt = ["int"] +diffusion.internal.validation.pydantic.StrictPositiveIntClass = ["int"] + +[tool.ruff] +exclude = [ + "build", + "dist", + "target", + "csharp", + ".gitignore" +] +line-length = 96 +select = [ + "E", + "F", + "W", + "RUF013", + "N8" +] +target-version = "py38" + +[tool.ruff.per-file-ignores] +"*/__init__.py" = ["F401"] +"*/generated/*.py" = ["E501"] + +[tool.ruff.lint.pydocstyle] +convention = "pep257" + +[project] +name = "diffusion_examples" +dynamic = ["readme", "version"] +dependencies = [ + 'diffusion>=6.10.4,<7.0.0' +] +requires-python = "<3.13,>=3.8" +authors = [{ name = "DiffusionData Limited", email = "contact@diffusiondata.com" }] +license = { text = "Proprietary" } +keywords = [ + "diffusion", + "cloud", + "websockets", + "data"] +classifiers = [ + "License :: Other/Proprietary License", + "Environment :: Other Environment", + "Development Status :: 4 - Beta", +] +description = "Python SDK for Diffusion." + +[project.urls] +homepage = "https://www.diffusiondata.com/" + +[tool.setuptools.dynamic] +readme = { file = ["README.md"], content-type = "text/markdown" } +version = { file = ["__version__"]} + +[tool.setuptools.package-data] +devtools = ["*.md"] +diffusion = ["*.dot"] diff --git a/python/examples/session_trees/session_trees.py b/python/examples/session_trees/session_trees.py deleted file mode 100644 index 0d1d401c..00000000 --- a/python/examples/session_trees/session_trees.py +++ /dev/null @@ -1,70 +0,0 @@ -import asyncio -import diffusion.datatypes -from diffusion.features.control.session_trees.branch_mapping_table import ( - BranchMappingTable, -) - -server_url = "ws://localhost:8080" -principal = "control" -credentials = diffusion.Credentials("password") - -path = "foo/bar" -topic_type = diffusion.datatypes.STRING -value = "bla bla" - - -# Because Python SDK for Diffusion is async, all the code needs to be -# wrapped inside a coroutine function, and executed using asyncio.run. -async def main(): - # creating the session - async with diffusion.Session( - url=server_url, principal="control", credentials=credentials - ) as session: - - # adding a topic, setting its value - try: - table = ( - BranchMappingTable.Builder() - .add_branch_mapping("$Principal is 'control'", "target/1") - .add_branch_mapping("all", "target/2") - .create("source/path") - ) - await session.session_trees.put_branch_mapping_table(table) - - print(f"""\ -Branch mapping table created for session tree branch '{table.session_tree_branch}'.""" - ) - except Exception as ex: - print(f"Failed to create branch mapping table : {ex}.") - return - - try: - print("Retrieving session tree branches.") - list_session_tree_branches = ( - await session.session_trees.get_session_tree_branches_with_mappings() - ) - except Exception as ex: - print(f"Failed to retrieve session tree branches : {ex}.") - return - - try: - print("Retrieving branch mapping table:") - - for session_tree_branch in list_session_tree_branches: - branch_mapping_table = await session.session_trees.get_branch_mapping_table( - session_tree_branch - ) - - for branch_mapping in branch_mapping_table.branch_mappings: - print( - f"""\ -Session tree branch: '{session_tree_branch}', -Session filter: '{branch_mapping.session_filter}', -Topic tree branch: '{branch_mapping.topic_tree_branch}'""" - ) - except Exception as ex: - print(f"Failed to retrieve a branch mapping : {ex}.") - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/python/examples/src/diffusion_examples/__init__.py b/python/examples/src/diffusion_examples/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/python/examples/src/diffusion_examples/__init__.py @@ -0,0 +1 @@ + diff --git a/python/examples/src/diffusion_examples/connection/__init__.py b/python/examples/src/diffusion_examples/connection/__init__.py new file mode 100644 index 00000000..193e0360 --- /dev/null +++ b/python/examples/src/diffusion_examples/connection/__init__.py @@ -0,0 +1,9 @@ +# Copyright (c) 2022 - 2023 DiffusionData Ltd., All Rights Reserved. +# +# Use is subject to licence terms. +# +# NOTICE: All information contained herein is, and remains the +# property of DiffusionData. The intellectual and technical +# concepts contained herein are proprietary to DiffusionData and +# may be covered by U.S. and Foreign Patents, patents in process, and +# are protected by trade secret or copyright law. diff --git a/python/examples/src/diffusion_examples/connection/establishment/__init__.py b/python/examples/src/diffusion_examples/connection/establishment/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/python/examples/src/diffusion_examples/connection/establishment/__init__.py @@ -0,0 +1 @@ + diff --git a/python/examples/src/diffusion_examples/connection/establishment/connect_synchronously.py b/python/examples/src/diffusion_examples/connection/establishment/connect_synchronously.py new file mode 100644 index 00000000..e3c65b9e --- /dev/null +++ b/python/examples/src/diffusion_examples/connection/establishment/connect_synchronously.py @@ -0,0 +1,43 @@ +""" +Copyright © 2023 - 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +from diffusion import sessions, Credentials +from diffusion_examples.utils.program import Example + + + +class ConnectSynchronously(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + print(f"Connected. Session Identifier: {session.session_id}.") + # Insert work here... + + +if __name__ == "__main__": + asyncio.run( + ConnectSynchronously().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/connection/establishment/connect_using_a_session_factory.py b/python/examples/src/diffusion_examples/connection/establishment/connect_using_a_session_factory.py new file mode 100644 index 00000000..2c774ad7 --- /dev/null +++ b/python/examples/src/diffusion_examples/connection/establishment/connect_using_a_session_factory.py @@ -0,0 +1,39 @@ +# Copyright © 2024 Diffusion Data Ltd. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import asyncio + +from diffusion import sessions, Credentials +from diffusion_examples.utils.program import Example + + +class ConnectUsingASessionFactory(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + print(f"Connected. Session Identifier: {session.session_id}.") + + + +if __name__ == '__main__': + asyncio.run(ConnectUsingASessionFactory().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + )) diff --git a/python/examples/src/diffusion_examples/connection/establishment/session_state_listener.py b/python/examples/src/diffusion_examples/connection/establishment/session_state_listener.py new file mode 100644 index 00000000..3b0c890b --- /dev/null +++ b/python/examples/src/diffusion_examples/connection/establishment/session_state_listener.py @@ -0,0 +1,61 @@ +""" +Copyright © 2023 - 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" +from __future__ import annotations +import asyncio +import typing + +from diffusion import sessions, Credentials +if typing.TYPE_CHECKING: + from diffusion.session import State + +from diffusion.session import SessionListener, Session + +from diffusion_examples.utils.program import Example + + +class Listener(SessionListener): + async def on_session_event( + self, + *, + session: Session, + old_state: typing.Optional[State], + new_state: State, + ): + print(f"State changed from {old_state} to {new_state}.") + + +class SessionStateListener(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + session.add_listener(Listener()) + print(f"Connected. Session Identifier: {session.session_id}.") + # Insert work here... + + +if __name__ == "__main__": + asyncio.run( + SessionStateListener().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/connection/resilience/__init__.py b/python/examples/src/diffusion_examples/connection/resilience/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/python/examples/src/diffusion_examples/connection/resilience/__init__.py @@ -0,0 +1 @@ + diff --git a/python/examples/src/diffusion_examples/connection/resilience/initial_session_establishment_retry_mechanism.py b/python/examples/src/diffusion_examples/connection/resilience/initial_session_establishment_retry_mechanism.py new file mode 100644 index 00000000..c5247833 --- /dev/null +++ b/python/examples/src/diffusion_examples/connection/resilience/initial_session_establishment_retry_mechanism.py @@ -0,0 +1,49 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +from diffusion import sessions, Credentials +from diffusion.session.retry_strategy import RetryStrategy + +from diffusion_examples.utils.program import Example + + + +class InitialSessionEstablishmentRetryMechanism(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + # Create an initial session establishment retry strategy. + # It will attempt 5 times to connect to the Diffusion server, + # with 250 milliseconds interval between attempts. + retry_strategy = RetryStrategy(interval=250, attempts=5) + async with sessions().principal(principal).credentials( + Credentials(password) + ).initial_retry_strategy(retry_strategy).open(server_url) as session: + print(f"Connected. Session Identifier: {session.session_id}.") + # Insert work here... + + +if __name__ == "__main__": + asyncio.run( + InitialSessionEstablishmentRetryMechanism().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/default_creds.py b/python/examples/src/diffusion_examples/default_creds.py new file mode 100644 index 00000000..77841afe --- /dev/null +++ b/python/examples/src/diffusion_examples/default_creds.py @@ -0,0 +1,3 @@ +PASSWORD = "password" +PRINCIPAL = "admin" +SERVER_URL = "ws://localhost:8080" diff --git a/python/examples/__init__.py b/python/examples/src/diffusion_examples/messaging/__init__.py similarity index 100% rename from python/examples/__init__.py rename to python/examples/src/diffusion_examples/messaging/__init__.py diff --git a/python/examples/src/diffusion_examples/messaging/message_to_message_path.py b/python/examples/src/diffusion_examples/messaging/message_to_message_path.py new file mode 100644 index 00000000..5097cfee --- /dev/null +++ b/python/examples/src/diffusion_examples/messaging/message_to_message_path.py @@ -0,0 +1,78 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +import typing + +from diffusion import sessions, Credentials, SessionId +from diffusion.messaging import RequestHandler +from diffusion_examples.utils.program import Example +import diffusion.datatypes + + +class MessageToMessagePath(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ) -> None: + path = "my/message/path" + + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + request_handler = SimpleRequestHandler() + await session.messaging.add_request_handler(path, request_handler) + + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session2: + response = await session2.messaging.send_request_to_path( + path, diffusion.datatypes.STRING("Hello") + ) + print(f"Received response: {response}.") + + +class SimpleRequestHandler(RequestHandler): + def __init__(self) -> None: + super().__init__( + self.on_request, + diffusion.datatypes.STRING, + diffusion.datatypes.STRING, + ) + + # noinspection PyUnusedLocal + async def on_request( + self, + request: typing.Optional[str], + *, + sender_session_id: typing.Optional[SessionId] = None, + path: typing.Optional[str] = None, + **kwargs, + ) -> str: + print(f"Received message: {request}.") + return "Goodbye" + + + +if __name__ == "__main__": + asyncio.run( + MessageToMessagePath().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/messaging/message_to_session_filter.py b/python/examples/src/diffusion_examples/messaging/message_to_session_filter.py new file mode 100644 index 00000000..6a46b2a3 --- /dev/null +++ b/python/examples/src/diffusion_examples/messaging/message_to_session_filter.py @@ -0,0 +1,137 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +import typing + +from diffusion import sessions, Credentials, SessionId +from diffusion.handlers import EventStreamHandler +from diffusion.messaging import RequestHandler +import diffusion.datatypes +from diffusion.session import SessionProperties + +from diffusion_examples.utils.program import Example + + +class MessageToSessionFilter(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ) -> None: + path = "my/message/path" + + async with sessions().principal("admin").credentials( + Credentials(password) + ).open(server_url) as session: + request_stream = SimpleRequestStream() + session.messaging.add_stream_handler( + path, request_stream, addressed=True + ) + + async with sessions().principal("control").credentials( + Credentials(password) + ).open(server_url) as session2: + request_stream2 = AnotherRequestStream() + session2.messaging.add_stream_handler(path, request_stream2, addressed=True) + + async with sessions().principal("control").credentials( + Credentials(password) + ).open(server_url) as session3: + request_callback = RequestCallback() + session3.messaging.add_filter_response_handler( + "$Principal is 'admin'", request_callback + ) + await session3.messaging.send_request_to_filter( + "$Principal EQ 'admin'", + path, + diffusion.datatypes.STRING("Hello"), + ) + + +class SimpleRequestStream(RequestHandler): + def __init__(self) -> None: + super().__init__( + self.on_request, + diffusion.datatypes.STRING, + diffusion.datatypes.STRING, + ) + + # noinspection PyUnusedLocal + async def on_request( + self, + request: typing.Optional[str], + sender_session_id: typing.Optional[SessionId] = None, + path: typing.Optional[str] = None, + session_properties: typing.Optional[SessionProperties] = None, + **kwargs, + ) -> str: + print(f"{type(self).__qualname__}: Received message: {request}.") + return "Goodbye" + + +class AnotherRequestStream(RequestHandler): + def __init__(self) -> None: + super().__init__( + self.on_request, + diffusion.datatypes.STRING, + diffusion.datatypes.STRING, + ) + + # noinspection PyUnusedLocal + async def on_request( + self, + request: typing.Optional[str], + sender_session_id: typing.Optional[SessionId] = None, + path: typing.Optional[str] = None, + session_properties: typing.Optional[SessionProperties] = None, + **kwargs, + ) -> str: + print(f"{type(self).__qualname__}: Received message: {request}.") + return "I'm not supposed to receive a message." + + +class RequestCallback(EventStreamHandler): + def __init__(self) -> None: + super().__init__( + error=self.on_response_error, response=self.on_response + ) + + # noinspection PyUnusedLocal + async def on_response( + self, + response: typing.Optional[diffusion.datatypes.AbstractDataType], + *, + sender_session_id: SessionId, + path: str, + received: int, + expected: int, + **kwargs, + ) -> None: + print(f"{type(self).__qualname__}: Received response: {response}.") + + async def on_response_error(self, code: int, description: str, **kwargs) -> None: + pass + + +if __name__ == "__main__": + asyncio.run( + MessageToSessionFilter().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/messaging/message_to_session_id.py b/python/examples/src/diffusion_examples/messaging/message_to_session_id.py new file mode 100644 index 00000000..ed9d343c --- /dev/null +++ b/python/examples/src/diffusion_examples/messaging/message_to_session_id.py @@ -0,0 +1,113 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio + +import typing + +from diffusion import SessionId +from diffusion import sessions, Credentials +from diffusion.messaging import RequestHandler +from diffusion_examples.utils.program import Example +import diffusion.datatypes + + + +class MessageToSessionID(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + path = "my/message/path" + + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + request_stream = SimpleRequestStream() + session.messaging.add_stream_handler(path, request_stream, addressed=True) + + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session2: + request_stream2 = AnotherRequestStream() + session2.messaging.add_stream_handler( + path, request_stream2, addressed=True + ) + + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session3: + response = await session3.messaging.send_request_to_session( + path, + session.session_id, + diffusion.datatypes.STRING("Hello"), + ) + print(f"Received response: {response}.") + + +class SimpleRequestStream(RequestHandler): + def __init__(self) -> None: + super().__init__( + self.on_request, + diffusion.datatypes.STRING, + diffusion.datatypes.STRING, + ) + + async def on_request( + self, + request: typing.Optional[str], + *, + sender_session_id: typing.Optional[SessionId] = None, + session_properties: typing.Optional[typing.Mapping[str, typing.Any]] = None, + path: typing.Optional[str] = None, + **kwargs, + ) -> str: + print(f"Received message: {request}.") + return "Goodbye" + + + +class AnotherRequestStream(RequestHandler): + def __init__(self): + super().__init__( + self.on_request, + diffusion.datatypes.STRING, + diffusion.datatypes.STRING, + ) + + async def on_request( + self, + request: typing.Optional[str], + *, + sender_session_id: typing.Optional[SessionId] = None, + path: typing.Optional[str] = None, + **kwargs, + ): + print(f"Received message: {request}.") + return "I'm not supposed to receive a message." + + + + +if __name__ == "__main__": + asyncio.run( + MessageToSessionID().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/messaging/__init__.py b/python/examples/src/diffusion_examples/ping/__init__.py similarity index 100% rename from python/examples/messaging/__init__.py rename to python/examples/src/diffusion_examples/ping/__init__.py diff --git a/python/examples/src/diffusion_examples/ping/ping_server.py b/python/examples/src/diffusion_examples/ping/ping_server.py new file mode 100644 index 00000000..505d76c8 --- /dev/null +++ b/python/examples/src/diffusion_examples/ping/ping_server.py @@ -0,0 +1,42 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +from diffusion import sessions, Credentials + +from diffusion_examples.utils.program import Example + + +class PingServer(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + await session.ping_server() + + +if __name__ == "__main__": + asyncio.run( + PingServer().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/session_trees/__init__.py b/python/examples/src/diffusion_examples/pubsub/__init__.py similarity index 100% rename from python/examples/session_trees/__init__.py rename to python/examples/src/diffusion_examples/pubsub/__init__.py diff --git a/python/examples/src/diffusion_examples/pubsub/fetch_topics/__init__.py b/python/examples/src/diffusion_examples/pubsub/fetch_topics/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/python/examples/src/diffusion_examples/pubsub/fetch_topics/__init__.py @@ -0,0 +1 @@ + diff --git a/python/examples/src/diffusion_examples/pubsub/fetch_topics/fetch_multiple_topics_by_iterating_through_paging.py b/python/examples/src/diffusion_examples/pubsub/fetch_topics/fetch_multiple_topics_by_iterating_through_paging.py new file mode 100644 index 00000000..7caa26e7 --- /dev/null +++ b/python/examples/src/diffusion_examples/pubsub/fetch_topics/fetch_multiple_topics_by_iterating_through_paging.py @@ -0,0 +1,79 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio + +import diffusion +from diffusion import Credentials +from diffusion_examples.utils.program import Example +import diffusion.datatypes + + +class FetchMultipleTopicsByIteratingThroughPaging(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with diffusion.sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + topic_specification = diffusion.datatypes.STRING.with_properties() + for i in range(1, 26): + string_value = f"diffusion data #{i}" + await session.topics.add_and_set_topic( + f"my/topic/path/{i}", + topic_specification, + string_value, + ) + + topic_selector = "?my/topic/path//" + # Fetch the values for the topic selector using a maximum result size of 10. + fetch_result = ( + await session.topics.fetch_request() + .with_values(diffusion.datatypes.STRING) + .first(10) + .fetch(topic_selector) + ) + + while True: + for topic in fetch_result.results: + addition = f"{topic.path}: {topic.value}" + print(addition) + if fetch_result.has_more: + # Fetch the next 10 values. + path = fetch_result.results[-1].path + fetch_result = await ( + session.topics.fetch_request() + .after(path) + .with_values(diffusion.datatypes.STRING) + .first(10) + .fetch(topic_selector) + ) + print("Loading next page.") + else: + print("Done.") + break + + + + +if __name__ == "__main__": + asyncio.run( + FetchMultipleTopicsByIteratingThroughPaging().run( + server_url="ws://localhost:8080", principal="admin", password="password" + ) + ) diff --git a/python/examples/src/diffusion_examples/pubsub/fetch_topics/fetch_topic_properties.py b/python/examples/src/diffusion_examples/pubsub/fetch_topics/fetch_topic_properties.py new file mode 100644 index 00000000..747d8e92 --- /dev/null +++ b/python/examples/src/diffusion_examples/pubsub/fetch_topics/fetch_topic_properties.py @@ -0,0 +1,98 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio + +from diffusion import sessions, Credentials +import diffusion.datatypes +from diffusion_examples.utils.program import Example + + + +class FetchTopicsProperties(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + topics = session.topics + for i in range(1, 6): + await topics.add_and_set_topic( + f"my/topic/path/with/properties/{i}", + diffusion.datatypes.JSON.with_properties( + DONT_RETAIN_VALUE=True, + PERSISTENT=False, + PUBLISH_VALUES_ONLY=True, + ), + {"diffusion": "data #{i}"}, + ) + + await topics.add_and_set_topic( + f"my/topic/path/with/default/properties/{i}", + diffusion.datatypes.STRING.with_properties( + DONT_RETAIN_VALUE=True, + PERSISTENT=False, + PUBLISH_VALUES_ONLY=True, + ), + f"diffusion data #{i}", + ) + + fetch_result = ( + await topics.fetch_request() + .topic_types({diffusion.datatypes.JSON}) + .with_properties() + .fetch("?my/topic/path//") + ) + + for topic in fetch_result.results: + print(f"{topic.path}:") + for ( + prop_key, + prop_value, + ) in topic.specification.properties.items(): + print(f"{prop_key}: {prop_value}") + + + # Fetch the topic properties for the topic path selector my/topic/path/. + fetch_result = ( + await topics.fetch_request() + .topic_types({diffusion.datatypes.STRING}) + .with_properties() + .fetch("?my/topic/path//") + ) + + for topic in fetch_result.results: + print(f"{topic.path} properties:") + for ( + prop_key, + prop_value, + ) in topic.specification.properties.items(): + print(f"{prop_key}: {prop_value}") + + + + +if __name__ == "__main__": + asyncio.run( + FetchTopicsProperties().run( + server_url="wss://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/pubsub/publishing_topics/__init__.py b/python/examples/src/diffusion_examples/pubsub/publishing_topics/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/python/examples/src/diffusion_examples/pubsub/publishing_topics/__init__.py @@ -0,0 +1 @@ + diff --git a/python/examples/src/diffusion_examples/pubsub/publishing_topics/add_and_set_topic.py b/python/examples/src/diffusion_examples/pubsub/publishing_topics/add_and_set_topic.py new file mode 100644 index 00000000..5b5f5d45 --- /dev/null +++ b/python/examples/src/diffusion_examples/pubsub/publishing_topics/add_and_set_topic.py @@ -0,0 +1,54 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio + +import diffusion +from diffusion import Credentials +from diffusion.features.topics import TopicAddResponse +from diffusion.datatypes import JSON +from diffusion_examples.utils.program import Example + + + +class AddAndSetTopic(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with diffusion.sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + topic = "my/topic/path" + json_data = {"diffusion": "data"} + result = await session.topics.add_and_set_topic( + topic, JSON.with_properties(), JSON(json_data) + ) + + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + print("Topic already exists.") + + + +if __name__ == "__main__": + asyncio.run( + AddAndSetTopic().run( + server_url="ws://localhost:8080", principal="admin", password="password" + ) + ) diff --git a/python/examples/src/diffusion_examples/pubsub/publishing_topics/add_topic.py b/python/examples/src/diffusion_examples/pubsub/publishing_topics/add_topic.py new file mode 100644 index 00000000..f8421918 --- /dev/null +++ b/python/examples/src/diffusion_examples/pubsub/publishing_topics/add_topic.py @@ -0,0 +1,52 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" +import asyncio + +from diffusion import sessions, Credentials +from diffusion_examples.utils.program import Example +from diffusion.features.topics import TopicAddResponse +import diffusion.datatypes + + + +class AddTopic(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + topic = "my/topic/path" + + topic_specification = diffusion.datatypes.JSON.with_properties() + result = await session.topics.add_topic( + topic, topic_specification + ) + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + print("Topic already exists.") + + + +if __name__ == "__main__": + asyncio.run( + AddTopic().run( + server_url="ws://localhost:8080", principal="admin", password="password" + ) + ) diff --git a/python/examples/src/diffusion_examples/pubsub/publishing_topics/add_topic_with_custom_topic_properties.py b/python/examples/src/diffusion_examples/pubsub/publishing_topics/add_topic_with_custom_topic_properties.py new file mode 100644 index 00000000..6bc1e540 --- /dev/null +++ b/python/examples/src/diffusion_examples/pubsub/publishing_topics/add_topic_with_custom_topic_properties.py @@ -0,0 +1,59 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio + +from diffusion import sessions, Credentials +from diffusion.features.topics import TopicAddResponse +from diffusion_examples.utils.program import Example +import diffusion.datatypes + + + +class AddTopicWithCustomTopicProperties(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + topic = "my/topic/path/with/properties" + + topic_specification = diffusion.datatypes.JSON.with_properties( + DONT_RETAIN_VALUE=True, + PERSISTENT=False, + PUBLISH_VALUES_ONLY=True + ) + result = await session.topics.add_topic( + topic, topic_specification + ) + + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + print("Topic already exists.") + + + + +if __name__ == "__main__": + asyncio.run( + AddTopicWithCustomTopicProperties().run( + server_url="ws://localhost:8080", principal="admin", password="password" + ) + ) diff --git a/python/examples/src/diffusion_examples/pubsub/publishing_topics/set_topic.py b/python/examples/src/diffusion_examples/pubsub/publishing_topics/set_topic.py new file mode 100644 index 00000000..66f4c309 --- /dev/null +++ b/python/examples/src/diffusion_examples/pubsub/publishing_topics/set_topic.py @@ -0,0 +1,62 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" +import asyncio + +from diffusion import sessions, Credentials +import diffusion.datatypes +from diffusion_examples.utils.program import Example +from diffusion.features.topics import TopicAddResponse + + + +class SetTopic(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + topic = "my/topic/path" + + result = await session.topics.add_topic( + topic, diffusion.datatypes.JSON.with_properties() + ) + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + print("Topic already exists.") + + json_data = {"diffusion": ["data", "more data"]} + await session.topics.set_topic( + topic, + diffusion.datatypes.JSON(json_data), + diffusion.datatypes.JSON.with_properties(), + ) + print("Topic value has been set.") + + + + +if __name__ == "__main__": + asyncio.run( + SetTopic().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/topics/__init__.py b/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/__init__.py similarity index 100% rename from python/examples/topics/__init__.py rename to python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/__init__.py diff --git a/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/add_and_set_topic_and.py b/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/add_and_set_topic_and.py new file mode 100644 index 00000000..6c4d1737 --- /dev/null +++ b/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/add_and_set_topic_and.py @@ -0,0 +1,80 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +from diffusion import sessions, Credentials +from diffusion.features.topics import TopicAddResponse +from diffusion.features.topics.update.constraint_factory import ( + ConstraintFactory, +) +from diffusion.datatypes import JSON, STRING +from diffusion_examples.utils.program import Example + +class AddAndSetTopicAnd(Example): + topic = "my/topic/path" + + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + json_data_1 = {"diffusion": "data"} + # Add and set the topic with the first value + result = await session.topics.add_and_set_topic( + self.topic, JSON.with_properties(), JSON(json_data_1) + ) + + # Create the constraint with both 'with' and 'without' + constraint_factory = ConstraintFactory() + constraint_with = constraint_factory.json_value().with_( + "/diffusion", STRING("data") + ) + constraint_without = constraint_factory.json_value().without("/bar") + combined_constraint = constraint_with and constraint_without + + if result == TopicAddResponse.CREATED: + print("Topic has been created with the first value.") + else: + print("Topic already exists.") + + json_data_2 = {"diffusion": "baz"} + # Set the topic with the second value (using the same constraint) + result = await session.topics.add_and_set_topic( + self.topic, + JSON.with_properties(), + JSON(json_data_2), + combined_constraint, + ) + + if result == TopicAddResponse.EXISTS: + print("Topic updated with the second value.") + else: + print("Topic was not updated.") + + + + +if __name__ == "__main__": + asyncio.run( + AddAndSetTopicAnd().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/add_and_set_topic_json_value_with.py b/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/add_and_set_topic_json_value_with.py new file mode 100644 index 00000000..755fafb8 --- /dev/null +++ b/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/add_and_set_topic_json_value_with.py @@ -0,0 +1,75 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +from diffusion import sessions, Credentials +from diffusion.features.topics import TopicAddResponse +from diffusion.features.topics.update.constraint_factory import ( + ConstraintFactory, +) +from diffusion_examples.utils.program import Example +import diffusion.datatypes + + +class AddAndSetTopicJSONValueWith(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + topic = "my/topic/path" + json = {"diffusion": "bar"} + + constraint = ConstraintFactory().json_value.with_( + "/diffusion", diffusion.datatypes.STRING("bar") + ) + topic_specification = diffusion.datatypes.JSON.with_properties() + result = await session.topics.add_and_set_topic( + topic, + topic_specification, + diffusion.datatypes.JSON(json), + ) + + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + raise RuntimeError("Topic failed to be created.") + json2 = {"diffusion": "baz"} + result = await session.topics.add_and_set_topic( + topic, + topic_specification, + diffusion.datatypes.JSON(json2), + constraint, + ) + + if result == TopicAddResponse.EXISTS: + print("Topic already exists.") + else: + raise RuntimeError("Topic should exist already.") + + + +if __name__ == "__main__": + asyncio.run( + AddAndSetTopicJSONValueWith().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/add_and_set_topic_json_value_without.py b/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/add_and_set_topic_json_value_without.py new file mode 100644 index 00000000..6a46cf6e --- /dev/null +++ b/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/add_and_set_topic_json_value_without.py @@ -0,0 +1,66 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +from diffusion import sessions, Credentials +from diffusion.features.topics import TopicAddResponse +from diffusion.features.topics.update.constraint_factory import ( + ConstraintFactory, +) +from diffusion.datatypes import JSON +from diffusion_examples.utils.program import Example + +class AddAndSetTopicJSONValueWithout(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + topic = "my/topic/path" + json_data = {"diffusion": "data"} + constraint = ConstraintFactory().json_value.without("/bar") + topic_specification = JSON.with_properties() + result = await session.topics.add_and_set_topic( + topic, topic_specification, JSON(json_data) + ) + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + raise RuntimeError("Topic failed to be created.") + + + json_data2 = {"diffusion": "baz"} + result = await session.topics.add_and_set_topic( + topic, topic_specification, JSON(json_data2), constraint + ) + if result == TopicAddResponse.EXISTS: + print("Topic already exists.") + else: + raise Exception("Topic should exist already.") + + + +if __name__ == "__main__": + asyncio.run( + AddAndSetTopicJSONValueWithout().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/add_and_set_topic_no_topic.py b/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/add_and_set_topic_no_topic.py new file mode 100644 index 00000000..ae96c443 --- /dev/null +++ b/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/add_and_set_topic_no_topic.py @@ -0,0 +1,56 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +from diffusion import sessions, Credentials +from diffusion.features.topics import TopicAddResponse +from diffusion.features.topics.update.constraint_factory import ( + ConstraintFactory, +) +from diffusion.datatypes import JSON +from diffusion_examples.utils.program import Example + + +class AddAndSetTopicNoTopic(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + topic = "my/topic/path" + json_data = {"diffusion": "data"} + constraint = ConstraintFactory().no_topic() + result = await session.topics.add_and_set_topic( + topic, JSON.with_properties(), JSON(json_data), constraint + ) + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + print("Topic already exists.") + + + +if __name__ == "__main__": + asyncio.run( + AddAndSetTopicNoTopic().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/add_and_set_topic_session_lock.py b/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/add_and_set_topic_session_lock.py new file mode 100644 index 00000000..5d7b023b --- /dev/null +++ b/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/add_and_set_topic_session_lock.py @@ -0,0 +1,58 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +from diffusion import sessions, Credentials +from diffusion.features.topics import TopicAddResponse +from diffusion.features.topics.update.constraint_factory import ( + ConstraintFactory, +) +from diffusion.datatypes import JSON +from diffusion_examples.utils.program import Example + + +class AddAndSetTopicSessionLock(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + topic = "my/topic/path" + json_data = {"diffusion": "data"} + session_lock = await session.lock("SessionLock1") + constraint = ConstraintFactory().locked(session_lock) + result = await session.topics.add_and_set_topic( + topic, JSON.with_properties(), JSON(json_data), constraint + ) + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + print("Topic already exists.") + await session_lock.unlock() + + + +if __name__ == "__main__": + asyncio.run( + AddAndSetTopicSessionLock().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/add_and_set_topic_value.py b/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/add_and_set_topic_value.py new file mode 100644 index 00000000..f72440dd --- /dev/null +++ b/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/add_and_set_topic_value.py @@ -0,0 +1,66 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +from diffusion import sessions, Credentials +from diffusion.features.topics import TopicAddResponse +from diffusion.features.topics.update.constraint_factory import ( + ConstraintFactory, +) +from diffusion.datatypes import JSON +from diffusion_examples.utils.program import Example + + +class AddAndSetTopicValue(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + topic = "my/topic/path" + json_data = {"diffusion": "data"} + constraint = ConstraintFactory().value(JSON(json_data)) + result = await session.topics.add_and_set_topic( + topic, JSON.with_properties(), JSON(json_data) + ) + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + raise RuntimeError("Topic failed to be created.") + + + json_data2 = {"diffusion": "data2"} + result = await session.topics.add_and_set_topic( + topic, JSON.with_properties(), JSON(json_data2), constraint + ) + if result == TopicAddResponse.EXISTS: + print("Topic already exists.") + else: + raise Exception("Topic should exist already.") + + + +if __name__ == "__main__": + asyncio.run( + AddAndSetTopicValue().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/set_topic_json_value_with.py b/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/set_topic_json_value_with.py new file mode 100644 index 00000000..70beba21 --- /dev/null +++ b/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/set_topic_json_value_with.py @@ -0,0 +1,69 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +import diffusion.datatypes +from diffusion import sessions, Credentials +from diffusion.features.topics import ( + TopicAddResponse, +) +from diffusion.features.topics.update.constraint_factory import ( + ConstraintFactory, +) +from diffusion.datatypes import JSON +from diffusion_examples.utils.program import Example + + +class SetTopicJSONValueWith(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + topic = "my/topic/path" + result = await session.topics.add_topic(topic, JSON) + + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + print("Topic already exists.") + + json_data = {"diffusion": "bar"} + constraint = ConstraintFactory().json_value.with_( + "/diffusion", diffusion.datatypes.STRING("bar") + ) + await session.topics.set_topic(topic, JSON(json_data), JSON) + + json_data2 = {"diffusion": "baz"} + await session.topics.set_topic( + topic, JSON(json_data2), JSON, constraint + ) + + print("Topic value has been set.") + + + +if __name__ == "__main__": + asyncio.run( + SetTopicJSONValueWith().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/set_topic_json_value_without.py b/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/set_topic_json_value_without.py new file mode 100644 index 00000000..0ad8c95f --- /dev/null +++ b/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/set_topic_json_value_without.py @@ -0,0 +1,60 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +from diffusion import sessions, Credentials +from diffusion.features.topics import TopicAddResponse +from diffusion.features.topics.update.constraint_factory import ConstraintFactory +from diffusion.datatypes import JSON +from diffusion_examples.utils.program import Example + + +class SetTopicJSONValueWithout(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + topic = "my/topic/path" + result = await session.topics.add_topic(topic, JSON) + + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + print("Topic already exists.") + + json_data = {"diffusion": None} + constraint = ConstraintFactory().json_value.without("/bar") + await session.topics.set_topic(topic, JSON(json_data), JSON) + + json_data2 = {"diffusion": "baz"} + await session.topics.set_topic(topic, JSON(json_data2), JSON, constraint) + + print("Topic value has been set.") + + + +if __name__ == "__main__": + asyncio.run( + SetTopicJSONValueWithout().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/set_topic_no_value.py b/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/set_topic_no_value.py new file mode 100644 index 00000000..f88a15f3 --- /dev/null +++ b/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/set_topic_no_value.py @@ -0,0 +1,66 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +from diffusion import sessions, Credentials +from diffusion.features.topics import TopicAddResponse +from diffusion.datatypes import JSON +from diffusion_examples.utils.program import Example +from diffusion.features.topics.update.constraint_factory import ConstraintFactory + + +class SetTopicNoValue(Example): + """ + Example class that demonstrates setting a topic value with no prior value. + """ + + TOPIC = "my/topic/path" + + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + topic_specification = JSON.with_properties() + + result = await session.topics.add_topic(self.TOPIC, topic_specification) + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + print("Topic already exists.") + + json_data = {"diffusion": ["data", "more data"]} + + constraint = ConstraintFactory().no_value + await session.topics.set_topic( + self.TOPIC, JSON(json_data), topic_specification, constraint + ) + + print("Topic value has been set.") + + + +if __name__ == "__main__": + asyncio.run( + SetTopicNoValue().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/set_topic_session_lock.py b/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/set_topic_session_lock.py new file mode 100644 index 00000000..20aa9974 --- /dev/null +++ b/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/set_topic_session_lock.py @@ -0,0 +1,65 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +from diffusion import sessions, Credentials +from diffusion.features.topics import TopicAddResponse +from diffusion.datatypes import JSON +from diffusion.features.topics.update.constraint_factory import ( + ConstraintFactory, +) +from diffusion_examples.utils.program import Example + + +class SetTopicSessionLock(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + topic = "my/topic/path" + result = await session.topics.add_topic(topic, JSON) + + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + print("Topic already exists.") + + json_data = {"diffusion": ["data", "more data"]} + session_lock = await session.lock("SessionLock1") + await session.topics.set_topic( + topic, + JSON(json_data), + JSON, + ConstraintFactory().locked(session_lock), + ) + + print("Topic value set with JSON data and session lock.") + await session_lock.unlock() + + + +if __name__ == "__main__": + asyncio.run( + SetTopicSessionLock().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/set_topic_value.py b/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/set_topic_value.py new file mode 100644 index 00000000..d9f947d6 --- /dev/null +++ b/python/examples/src/diffusion_examples/pubsub/publishing_topics_with_constraint/set_topic_value.py @@ -0,0 +1,68 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio + +from diffusion import sessions, Credentials +import diffusion.datatypes +from diffusion.features.topics.update.constraint_factory import ConstraintFactory +from diffusion_examples.utils.program import Example +from diffusion.features.topics import TopicAddResponse + + + +class SetTopicValue(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + topic = "my/topic/path" + + topic_specification = diffusion.datatypes.JSON.with_properties() + result = await session.topics.add_topic( + topic, topic_specification + ) + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + print("Topic already exists.") + + json_data = {"diffusion": ["data", "more data"]} + constraint = ConstraintFactory().value(diffusion.datatypes.JSON(json_data)) + await session.topics.set_topic( + topic, diffusion.datatypes.JSON(json_data), topic_specification + ) + + json_data2 = {"diffusion": ["data", "more data", "yet more data"]} + await session.topics.set_topic( + topic, diffusion.datatypes.JSON(json_data2), topic_specification, constraint + ) + print("Topic value has been set.") + + + +if __name__ == "__main__": + asyncio.run( + SetTopicValue().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/pubsub/removing_topics/__init__.py b/python/examples/src/diffusion_examples/pubsub/removing_topics/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/python/examples/src/diffusion_examples/pubsub/removing_topics/removing_a_single_topic_using_topic_path.py b/python/examples/src/diffusion_examples/pubsub/removing_topics/removing_a_single_topic_using_topic_path.py new file mode 100644 index 00000000..1c49a1c1 --- /dev/null +++ b/python/examples/src/diffusion_examples/pubsub/removing_topics/removing_a_single_topic_using_topic_path.py @@ -0,0 +1,86 @@ +""" +Copyright © 2023 - 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +from diffusion import Session, sessions, Credentials +from diffusion_examples.utils.program import Example +from diffusion.features.topics import TopicAddResponse, TopicSpecification +from diffusion.datatypes import JSON + + +class RemovingASingleTopicUsingTopicPath(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + topic_control = session.topics + + topic = "my/topic/path/to/be/removed" + topic_specification = JSON.with_properties() + + await self.add_and_set_topic( + session, + topic, + topic_specification, + {"diffusion": ["data", "more data"]}, + ) + await self.add_and_set_topic( + session, + "my/topic/path/will/not/be/removed", + topic_specification, + {"diffusion": ["no data"]}, + ) + await self.add_and_set_topic( + session, + "my/topic/path/will/not/be/removed/either", + topic_specification, + {"diffusion": ["no data either"]}, + ) + + await topic_control.remove_topic(topic) + print("Topic has been removed.") + + + async def add_and_set_topic( + self, + session: Session, + topic: str, + topic_specification: TopicSpecification, + json_data, + ): + topic_update = session.topics + topic_control = session.topics + result = await topic_control.add_topic(topic, topic_specification) + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + print("Topic already exists.") + + await topic_update.set_topic(topic, JSON(json_data), topic_specification) + + +if __name__ == "__main__": + asyncio.run( + RemovingASingleTopicUsingTopicPath().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/pubsub/removing_topics/removing_multiple_topics_using_a_topic_selector.py b/python/examples/src/diffusion_examples/pubsub/removing_topics/removing_multiple_topics_using_a_topic_selector.py new file mode 100644 index 00000000..88dc5f4b --- /dev/null +++ b/python/examples/src/diffusion_examples/pubsub/removing_topics/removing_multiple_topics_using_a_topic_selector.py @@ -0,0 +1,93 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +import typing + +import diffusion.datatypes +from diffusion import sessions, Credentials +from diffusion.features.topics import ( + TopicAddResponse, + TopicSpecification +) +from diffusion.datatypes import JSON +from diffusion_examples.utils.program import Example + + + +class RemovingMultipleTopicsUsingATopicSelector(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + topic_specification = JSON.with_properties() + await self.add_and_set_topic( + session, + "my/topic/path/to/be/removed", + topic_specification, + {"diffusion": ["data", "more data"]}, + ) + await self.add_and_set_topic( + session, + "my/topic/path/to/be/also/removed", + topic_specification, + {"diffusion": ["data", "also more data"]}, + ) + await self.add_and_set_topic( + session, + "my/topic/path/will/not/be/removed", + topic_specification, + {"diffusion": ["no data"]}, + ) + await self.add_and_set_topic( + session, + "my/topic/path/will/not/be/removed/either", + topic_specification, + {"diffusion": ["no data either"]}, + ) + result = await session.topics.remove_topic("?my/topic/path/to/be//") + print(f"{result.removed_count} topics have been removed.") + + async def add_and_set_topic( + self, + session: diffusion.session.Session, + topic: str, + topic_specification: TopicSpecification, + json_data: typing.Any, + ): + result = await session.topics.add_topic(topic, topic_specification) + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + print("Topic already exists.") + assert result == TopicAddResponse.CREATED + await session.topics.set_topic(topic, JSON(json_data), topic_specification) + + + + +if __name__ == "__main__": + asyncio.run( + RemovingMultipleTopicsUsingATopicSelector().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/pubsub/removing_topics/removing_topics_with_automatic_topic_removal.py b/python/examples/src/diffusion_examples/pubsub/removing_topics/removing_topics_with_automatic_topic_removal.py new file mode 100644 index 00000000..2e6f89d3 --- /dev/null +++ b/python/examples/src/diffusion_examples/pubsub/removing_topics/removing_topics_with_automatic_topic_removal.py @@ -0,0 +1,74 @@ +# Copyright © 2024 Diffusion Data Ltd. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import asyncio + +import diffusion.datatypes +from diffusion import sessions, Credentials +from diffusion.features.topics import TopicAddResponse +from diffusion_examples.utils.program import Example + + +class RemovingTopicsWithAutomaticTopicRemoval(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials(Credentials(password)).open( + server_url) as session: + await self.add_topic(session, 'my/topic/path/to/be/removed/time/after', + "when time after 'Tue, 4 May 2077 11:05:30 GMT'") + + await self.add_topic(session, 'my/topic/path/to/be/removed/subscriptions', + 'when subscriptions < 1 for 10m') + + await self.add_topic(session, 'my/topic/path/to/be/removed/local/subscriptions', + 'when local subscriptions < 1 for 10m') + + await self.add_topic(session, 'my/topic/path/to/be/removed/no/updates', + 'when no updates for 10m') + + await self.add_topic(session, 'my/topic/path/to/be/removed/no/session', + 'when no session has \'$Principal is "client"\' for 1h') + + await self.add_topic(session, 'my/topic/path/to/be/removed/no/local/session', + 'when no local session has \'Department is "Accounts"\' for 1h after 1d') # noqa: E501 + + await self.add_topic(session, 'my/topic/path/to/be/removed/subcriptions/or/updates', + 'when subscriptions < 1 for 10m or no updates for 20m') + await self.add_topic(session, + 'my/topic/path/to/be/removed/subcriptions/and/updates', + 'when subscriptions < 1 for 10m and no updates for 20m') + + + async def add_topic(self, session, topic: str, removal_value: str): + topic_specification = diffusion.datatypes.JSON.with_properties(REMOVAL=removal_value) + + result = await session.topics.add_topic(topic, topic_specification) + + if result == TopicAddResponse.CREATED: + print('Topic has been created.') + else: + print('Topic already exists.') + + + + +if __name__ == '__main__': + asyncio.run(RemovingTopicsWithAutomaticTopicRemoval().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + )) diff --git a/python/examples/src/diffusion_examples/pubsub/subscribing_to_topics/__init__.py b/python/examples/src/diffusion_examples/pubsub/subscribing_to_topics/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/python/examples/src/diffusion_examples/pubsub/subscribing_to_topics/subscribe_to_multiple_topics_using_topic_selector.py b/python/examples/src/diffusion_examples/pubsub/subscribing_to_topics/subscribe_to_multiple_topics_using_topic_selector.py new file mode 100644 index 00000000..3addc66b --- /dev/null +++ b/python/examples/src/diffusion_examples/pubsub/subscribing_to_topics/subscribe_to_multiple_topics_using_topic_selector.py @@ -0,0 +1,127 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +import typing + +from diffusion import sessions, Credentials +from diffusion.features.topics import ( + TopicAddResponse, + ValueStreamHandler, + TopicSpecification, +) +import diffusion.datatypes +from diffusion_examples.utils.program import Example + + +class SubscribeToMultipleTopicsUsingTopicSelector(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + topic_specification = diffusion.datatypes.JSON.with_properties() + await add_topic(session, "my/topic/path", topic_specification) + await add_topic(session, "my/other/topic/path", topic_specification) + topic_selector = "?my//" + json_stream = JSONStream() + session.topics.add_value_stream(topic_selector, json_stream) + await session.topics.subscribe(topic_selector) + + await asyncio.sleep(5) + print("Creating my/additional/topic/path") + await add_topic( + session, "my/additional/topic/path", topic_specification + ) + await asyncio.sleep(5) + await session.topics.unsubscribe(topic_selector) + await session.topics.remove_stream(json_stream) + + + +async def add_topic(session, topic, topic_specification): + result = await session.topics.add_topic(topic, topic_specification) + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + print("Topic already exists.") + + +class JSONStream(ValueStreamHandler): + def __init__(self) -> None: + super().__init__( + diffusion.datatypes.JSON, + subscribe=self.on_subscription, + unsubscribe=self.on_unsubscription, + update=self.on_update, + close=self.on_close, + ) + self._stream_values: typing.List[str] = [] + + + async def on_close( + self, + topic_path: str, + topic_spec: TopicSpecification, + topic_value: typing.Optional[diffusion.datatypes.JSON], + **kwargs + ) -> None: + pass + + # noinspection PyUnusedLocal,PyMethodMayBeStatic + async def on_subscription( + self, + topic_path: str, + topic_spec: TopicSpecification, + topic_value: typing.Optional[diffusion.datatypes.JSON], + **kwargs + ) -> None: + print(f"Subscribed to {topic_path}.") + + # noinspection PyUnusedLocal,PyMethodMayBeStatic + async def on_unsubscription( + self, + topic_path: str, + topic_spec: TopicSpecification, + topic_value: typing.Optional[diffusion.datatypes.JSON], + reason: typing.Any, + **kwargs + ) -> None: + print(f"Unsubscribed from {topic_path}: {reason}.") + + # noinspection PyUnusedLocal,PyMethodMayBeStatic + async def on_update( + self, + topic_path: str, + topic_spec: TopicSpecification, + old_value: typing.Optional[diffusion.datatypes.JSON], + topic_value: typing.Optional[diffusion.datatypes.JSON], + **kwargs + ) -> None: + print(f"{topic_path} changed from {old_value} to {topic_value}.") + + +if __name__ == "__main__": + asyncio.run( + SubscribeToMultipleTopicsUsingTopicSelector().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/pubsub/subscribing_to_topics/subscribe_to_single_topic_using_topic_path.py b/python/examples/src/diffusion_examples/pubsub/subscribing_to_topics/subscribe_to_single_topic_using_topic_path.py new file mode 100644 index 00000000..3d5310dc --- /dev/null +++ b/python/examples/src/diffusion_examples/pubsub/subscribing_to_topics/subscribe_to_single_topic_using_topic_path.py @@ -0,0 +1,122 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +import typing + +from diffusion import sessions, Credentials +from diffusion.features.topics import ( + TopicAddResponse, + ValueStreamHandler, + TopicSpecification, +) +import diffusion.datatypes +from diffusion_examples.utils.program import Example + +class SubscribeToSingleTopicUsingTopicPath(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + topic = "my/topic/path" + topic_selector = ">my/topic/path" + topic_specification = diffusion.datatypes.JSON.with_properties() + result = await session.topics.add_topic(topic, topic_specification) + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + print("Topic already exists.") + + json_stream = JSONStream() + session.topics.add_value_stream(topic_selector, json_stream) + await session.topics.subscribe(topic_selector) + await session.topics.set_topic( + topic, diffusion.datatypes.JSON({"diffusion": "bar"}), diffusion.datatypes.JSON + ) + + await asyncio.sleep(5) + await session.topics.unsubscribe(topic_selector) + await session.topics.remove_stream(json_stream) + + + +class JSONStream(ValueStreamHandler): + def __init__(self) -> None: + super().__init__( + diffusion.datatypes.JSON, + subscribe=self.on_subscription, + unsubscribe=self.on_unsubscription, + update=self.on_update, + close=self.on_close + ) + self._stream_values: typing.List[str] = [] + + + async def on_close( + self, + topic_path: str, + topic_spec: TopicSpecification, + topic_value: typing.Optional[diffusion.datatypes.JSON], + **kwargs + ) -> None: + pass + + + # noinspection PyUnusedLocal,PyMethodMayBeStatic + async def on_subscription( + self, + topic_path: str, + topic_spec: TopicSpecification, + topic_value: typing.Optional[diffusion.datatypes.JSON], + **kwargs + ) -> None: + print(f"Subscribed to {topic_path}.") + + # noinspection PyUnusedLocal,PyMethodMayBeStatic + async def on_unsubscription( + self, + topic_path: str, + topic_spec: TopicSpecification, + topic_value: typing.Optional[diffusion.datatypes.JSON], + reason: typing.Any, + **kwargs + ) -> None: + print(f"Unsubscribed from {topic_path}: {reason}.") + + # noinspection PyUnusedLocal,PyMethodMayBeStatic + async def on_update( + self, + topic_path: str, + topic_spec: TopicSpecification, + old_value: typing.Optional[diffusion.datatypes.JSON], + topic_value: typing.Optional[diffusion.datatypes.JSON], + **kwargs + ) -> None: + print(f"{topic_path} changed from {old_value} to {topic_value}.") + + +if __name__ == "__main__": + asyncio.run( + SubscribeToSingleTopicUsingTopicPath().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/pubsub/subscribing_to_topics/subscribe_using_fallback_streams.py b/python/examples/src/diffusion_examples/pubsub/subscribing_to_topics/subscribe_using_fallback_streams.py new file mode 100644 index 00000000..267dbd3a --- /dev/null +++ b/python/examples/src/diffusion_examples/pubsub/subscribing_to_topics/subscribe_using_fallback_streams.py @@ -0,0 +1,123 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +import typing + +from diffusion import sessions, Credentials +from diffusion.features.topics import ( + TopicAddResponse, + ValueStreamHandler, + TopicSpecification, +) +from diffusion_examples.utils.program import Example +import diffusion.datatypes + + + +class SubscribeUsingFallbackStreams(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + topic_specification = diffusion.datatypes.JSON.with_properties() + await add_topic(session, "my/topic/path", topic_specification) + await add_topic(session, "my/other/topic/path", topic_specification) + + fallback_stream = FallbackStream() + session.topics.add_fallback_stream(fallback_stream) + + topic_selector = "?my//" + await session.topics.subscribe(topic_selector) + + await asyncio.sleep(5) + print("Creating my/additional/topic/path") + await add_topic(session, "my/additional/topic/path", topic_specification) + await asyncio.sleep(5) + print("Creating this/topic/path/will/not/be/picked/up") + await add_topic( + session, "this/topic/path/will/not/be/picked/up", topic_specification + ) + await asyncio.sleep(5) + await session.topics.unsubscribe(topic_selector) + await session.topics.remove_stream(fallback_stream) + + + +async def add_topic(session, topic, topic_specification): + result = await session.topics.add_topic(topic, topic_specification) + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + print("Topic already exists.") + + +class FallbackStream(ValueStreamHandler): + def __init__(self) -> None: + super().__init__( + diffusion.datatypes.JSON, + subscribe=self.on_subscription, + unsubscribe=self.on_unsubscription, + update=self.on_update, + ) + self._stream_values: typing.List[str] = [] + + + # noinspection PyUnusedLocal,PyMethodMayBeStatic + async def on_subscription( + self, + topic_path: str, + topic_spec: TopicSpecification, + topic_value: typing.Optional[diffusion.datatypes.JSON], + **kwargs + ) -> None: + print(f"Subscribed to {topic_path}.") + + # noinspection PyUnusedLocal,PyMethodMayBeStatic + async def on_unsubscription( + self, + topic_path: str, + topic_spec: TopicSpecification, + topic_value: typing.Optional[diffusion.datatypes.JSON], + reason: typing.Optional[typing.Any], + **kwargs + ) -> None: + print(f"Unsubscribed from {topic_path}: {reason}.") + + # noinspection PyUnusedLocal,PyMethodMayBeStatic + async def on_update( + self, + topic_path: str, + topic_spec: TopicSpecification, + old_value: typing.Optional[diffusion.datatypes.JSON], + topic_value: typing.Optional[diffusion.datatypes.JSON], + **kwargs + ) -> None: + print(f"{topic_path} changed from {old_value} to {topic_value}.") + + +if __name__ == "__main__": + asyncio.run( + SubscribeUsingFallbackStreams().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/pubsub/subscribing_to_topics/subscribe_with_cross_compatible_value_stream.py b/python/examples/src/diffusion_examples/pubsub/subscribing_to_topics/subscribe_with_cross_compatible_value_stream.py new file mode 100644 index 00000000..2c30661c --- /dev/null +++ b/python/examples/src/diffusion_examples/pubsub/subscribing_to_topics/subscribe_with_cross_compatible_value_stream.py @@ -0,0 +1,165 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +import typing + +from diffusion import sessions, Credentials +from diffusion.features.topics import ( + TopicAddResponse, + ValueStreamHandler, + TopicSpecification, +) +import diffusion.datatypes +from diffusion_examples.utils.program import Example + + + +class SubscribeWithCrossCompatibleValueStream(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + topic = "my/int/topic/path" + topic_selector = ">my/int/topic/path" + topic_specification = diffusion.datatypes.INT64.with_properties() + result = await session.topics.add_topic(topic, topic_specification) + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + print("Topic already exists.") + json_stream = JSONStream() + session.topics.add_value_stream(topic_selector, json_stream) + string_stream = StringStream() + session.topics.add_value_stream(topic_selector, string_stream) + await session.topics.subscribe(topic_selector) + + await asyncio.sleep(5) + await session.topics.unsubscribe(topic_selector) + await session.topics.remove_stream(json_stream) + await session.topics.remove_stream(string_stream) + + + +class JSONStream(ValueStreamHandler): + def __init__(self) -> None: + super().__init__( + diffusion.datatypes.JSON, + subscribe=self.on_subscription, + unsubscribe=self.on_unsubscription, + update=self.on_update, + close=self.on_close + ) + self._stream_values: typing.List[str] = [] + + + def on_close( + self, + topic_path: str, + topic_spec: TopicSpecification, + topic_value: typing.Optional[diffusion.datatypes.JSON], + **kwargs + ) -> None: + pass + + # noinspection PyUnusedLocal,PyMethodMayBeStatic + async def on_subscription( + self, + topic_path: str, + topic_spec: TopicSpecification, + topic_value: typing.Optional[diffusion.datatypes.JSON], + **kwargs + ) -> None: + print(f"JSON stream subscribed to {topic_path}.") + + # noinspection PyUnusedLocal,PyMethodMayBeStatic + async def on_unsubscription( + self, + topic_path: str, + topic_spec: TopicSpecification, + topic_value: typing.Optional[diffusion.datatypes.JSON], + reason: typing.Any, + **kwargs + ) -> None: + print(f"JSON stream unsubscribed from {topic_path}: {reason}.") + + # noinspection PyUnusedLocal,PyMethodMayBeStatic + async def on_update( + self, + topic_path: str, + topic_spec: TopicSpecification, + old_value: typing.Optional[diffusion.datatypes.JSON], + topic_value: typing.Optional[diffusion.datatypes.JSON], + ) -> None: + print(f"JSON stream {topic_path} changed from {old_value} to {topic_value}.") + + +class StringStream(ValueStreamHandler): + def __init__(self) -> None: + super().__init__( + diffusion.datatypes.STRING, + subscribe=self.on_subscription, + unsubscribe=self.on_unsubscription, + update=self.on_update, + ) + self._stream_values: typing.List[str] = [] + + + # noinspection PyUnusedLocal,PyMethodMayBeStatic + async def on_subscription( + self, + topic_path: str, + topic_spec: TopicSpecification, + topic_value: typing.Optional[diffusion.datatypes.STRING], + **kwargs + ) -> None: + print(f"String stream subscribed to {topic_path}.") + + # noinspection PyUnusedLocal,PyMethodMayBeStatic + async def on_unsubscription( + self, + topic_path: str, + topic_spec: TopicSpecification, + topic_value: typing.Optional[diffusion.datatypes.STRING], + reason: typing.Any, + **kwargs + ) -> None: + print(f"String stream unsubscribed from {topic_path}: {reason}.") + + # noinspection PyUnusedLocal,PyMethodMayBeStatic + async def on_update( + self, + topic_path: str, + topic_spec: TopicSpecification, + old_value: typing.Optional[diffusion.datatypes.STRING], + topic_value: typing.Optional[diffusion.datatypes.STRING], + **kwargs + ) -> None: + print(f"String stream {topic_path} changed from {old_value} to {topic_value}.") + + +if __name__ == "__main__": + asyncio.run( + SubscribeWithCrossCompatibleValueStream().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/server_configuration/__init__.py b/python/examples/src/diffusion_examples/server_configuration/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/python/examples/src/diffusion_examples/server_configuration/metrics/__init__.py b/python/examples/src/diffusion_examples/server_configuration/metrics/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/python/examples/src/diffusion_examples/server_configuration/metrics/session_metric_collector/__init__.py b/python/examples/src/diffusion_examples/server_configuration/metrics/session_metric_collector/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/python/examples/src/diffusion_examples/server_configuration/metrics/session_metric_collector/list_session_metric_collectors.py b/python/examples/src/diffusion_examples/server_configuration/metrics/session_metric_collector/list_session_metric_collectors.py new file mode 100644 index 00000000..da9e9d04 --- /dev/null +++ b/python/examples/src/diffusion_examples/server_configuration/metrics/session_metric_collector/list_session_metric_collectors.py @@ -0,0 +1,83 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +from diffusion import sessions, Credentials +from diffusion.features.control.metrics.session_metrics import ( + SessionMetricCollectorBuilder, +) +from diffusion_examples.utils.program import Example + + +class ListSessionMetricCollectors(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + session_filter = "$Principal is 'control'" + + collector = ( + SessionMetricCollectorBuilder() + .export_to_prometheus(False) + .group_by_properties("$Location") + .remove_metrics_with_no_matches(True) + .maximum_groups(10) + .create("Session Metric Collector 1", session_filter) + ) + await session.metrics.put_session_metric_collector(collector) + + collector = ( + SessionMetricCollectorBuilder() + .export_to_prometheus(True) + .group_by_properties("$Location") + .remove_metrics_with_no_matches(True) + .maximum_groups(250) + .create("Session Metric Collector 2", session_filter) + ) + await session.metrics.put_session_metric_collector(collector) + + list_session_metric_collectors = ( + await session.metrics.list_session_metric_collectors() + ) + + for session_metric_collector in list_session_metric_collectors: + output = ( + f"{session_metric_collector.name}: " + f"{session_metric_collector.session_filter} " + f"({session_metric_collector.maximum_groups}, " + f"{self.get_answer(session_metric_collector.exports_to_prometheus)}, " + f"{self.get_answer(session_metric_collector.removes_metrics_with_no_matches)}, " # noqa: E501 + f"{','.join(session_metric_collector.group_by_properties)})" + ) + print(output) + + def get_answer(self, result): + return "Yes" if result else "No" + + + +if __name__ == "__main__": + asyncio.run( + ListSessionMetricCollectors().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/server_configuration/metrics/session_metric_collector/put_session_metric_collector.py b/python/examples/src/diffusion_examples/server_configuration/metrics/session_metric_collector/put_session_metric_collector.py new file mode 100644 index 00000000..b2c70da2 --- /dev/null +++ b/python/examples/src/diffusion_examples/server_configuration/metrics/session_metric_collector/put_session_metric_collector.py @@ -0,0 +1,70 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +from diffusion import sessions, Credentials +from diffusion.features.control.metrics.session_metrics import ( + SessionMetricCollectorBuilder, +) + +from diffusion_examples.utils.program import Example + + + +class PutSessionMetricCollector(Example): + """Example class for creating Session Metric Collector.""" + + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + """Run the session metric collector. + + Args: + server_url (str): The server URL. + principal (str): The principal. + password (str): The password. + """ + session_filter = "$Principal is 'control'" + + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + collector_name = "Session Metric Collector 1" + # Put session metric collector asynchronously and wait + builder = SessionMetricCollectorBuilder() + builder = builder.export_to_prometheus(False) + builder = builder.group_by_properties("$Location") + builder = builder.remove_metrics_with_no_matches(True) + builder = builder.maximum_groups(10) + collector = builder.create(collector_name, session_filter) + + await session.metrics.put_session_metric_collector(collector) + print(f"Session metric collector '{collector_name}' added.") + + # Wait for the task to complete + + + +if __name__ == "__main__": + asyncio.run( + PutSessionMetricCollector().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/server_configuration/metrics/session_metric_collector/remove_session_metric_collector.py b/python/examples/src/diffusion_examples/server_configuration/metrics/session_metric_collector/remove_session_metric_collector.py new file mode 100644 index 00000000..76401a2c --- /dev/null +++ b/python/examples/src/diffusion_examples/server_configuration/metrics/session_metric_collector/remove_session_metric_collector.py @@ -0,0 +1,60 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +from diffusion.features.control.metrics.session_metrics import ( + SessionMetricCollectorBuilder, +) +from diffusion import sessions, Credentials +from diffusion_examples.utils.program import Example + + +class RemoveSessionMetricCollector(Example): + async def run( + self, + server_url="", + principal="", + password="", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + session_filter = "$Principal is 'control'" + builder = ( + SessionMetricCollectorBuilder() + .export_to_prometheus(False) + .group_by_properties("$Location") + .remove_metrics_with_no_matches(True) + .maximum_groups(10) + ) + collector = builder.create( + "Session Metric Collector 1", session_filter + ) + await session.metrics.put_session_metric_collector(collector) + await session.metrics.remove_session_metric_collector( + collector.name + ) + print(f"{collector.name} has been removed.") + + + +if __name__ == "__main__": + asyncio.run( + RemoveSessionMetricCollector().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/server_configuration/metrics/topic_metric_collector/__init__.py b/python/examples/src/diffusion_examples/server_configuration/metrics/topic_metric_collector/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/python/examples/src/diffusion_examples/server_configuration/metrics/topic_metric_collector/__init__.py @@ -0,0 +1 @@ + diff --git a/python/examples/src/diffusion_examples/server_configuration/metrics/topic_metric_collector/list_topic_metric_collectors.py b/python/examples/src/diffusion_examples/server_configuration/metrics/topic_metric_collector/list_topic_metric_collectors.py new file mode 100644 index 00000000..b3c974f4 --- /dev/null +++ b/python/examples/src/diffusion_examples/server_configuration/metrics/topic_metric_collector/list_topic_metric_collectors.py @@ -0,0 +1,87 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import typing +import asyncio + +from diffusion import sessions, Credentials +from diffusion.features.control.metrics.topic_metrics import ( + TopicMetricCollectorBuilder, +) + +from diffusion_examples.utils.program import Example + + + +class ListTopicMetricCollectors(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + topic_selector = "?my/topic//" + + # Create first collector + builder = TopicMetricCollectorBuilder() + builder.export_to_prometheus(False) + builder.group_by_topic_type(True) + builder.group_by_topic_view(True) + builder.group_by_path_prefix_parts(15) + builder.maximum_groups(10) + collector = builder.create("Topic Metric Collector 1", topic_selector) + await session.metrics.put_topic_metric_collector(collector) + + # Create second collector + builder = TopicMetricCollectorBuilder() + builder.export_to_prometheus(True) + builder.group_by_topic_type(False) + builder.group_by_topic_view(True) + builder.group_by_path_prefix_parts(15) + builder.maximum_groups(250) + collector = builder.create("Topic Metric Collector 2", topic_selector) + await session.metrics.put_topic_metric_collector(collector) + list_topic_metric_collectors = ( + await session.metrics.list_topic_metric_collectors() + ) + for topic_metric_collector in list_topic_metric_collectors: + result_str = ( + f"{topic_metric_collector.name}: " + f"{topic_metric_collector.topic_selector} " + f"({topic_metric_collector.maximum_groups}, " + f"{get_answer(topic_metric_collector.exports_to_prometheus)}, " + f"{get_answer(topic_metric_collector.groups_by_topic_type)}, " + f"{get_answer(topic_metric_collector.groups_by_topic_view)}, " + f"{topic_metric_collector.group_by_path_prefix_parts})" + ) + print(result_str) + + +# noinspection PyMethodMayBeStatic +def get_answer(result: typing.Optional[bool]): + return "Yes" if result else "No" + + +if __name__ == "__main__": + asyncio.run( + ListTopicMetricCollectors().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/server_configuration/metrics/topic_metric_collector/put_topic_metric_collector.py b/python/examples/src/diffusion_examples/server_configuration/metrics/topic_metric_collector/put_topic_metric_collector.py new file mode 100644 index 00000000..e61e44e8 --- /dev/null +++ b/python/examples/src/diffusion_examples/server_configuration/metrics/topic_metric_collector/put_topic_metric_collector.py @@ -0,0 +1,58 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio + +from diffusion import sessions, Credentials +from diffusion.features.control.metrics.topic_metrics import ( + TopicMetricCollectorBuilder, +) + + +from diffusion_examples.utils.program import Example + + +class PutTopicMetricCollector(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + topic_selector = "?my/topic//" + builder = TopicMetricCollectorBuilder() + builder = builder.export_to_prometheus(False) + builder = builder.group_by_topic_type(True) + builder = builder.group_by_topic_view(True) + builder = builder.group_by_path_prefix_parts(15) + builder = builder.maximum_groups(10) + collector = builder.create( + "Topic Metric Collector 1", topic_selector + ) + await session.metrics.put_topic_metric_collector(collector) + print(f"Topic metric collector '{collector.name}' added.") + + +if __name__ == "__main__": + asyncio.run( + PutTopicMetricCollector().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/server_configuration/metrics/topic_metric_collector/remove_topic_metric_collector.py b/python/examples/src/diffusion_examples/server_configuration/metrics/topic_metric_collector/remove_topic_metric_collector.py new file mode 100644 index 00000000..d7c05512 --- /dev/null +++ b/python/examples/src/diffusion_examples/server_configuration/metrics/topic_metric_collector/remove_topic_metric_collector.py @@ -0,0 +1,58 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio + +from diffusion import sessions, Credentials +from diffusion.features.control.metrics.topic_metrics import ( + TopicMetricCollectorBuilder, +) + + +from diffusion_examples.utils.program import Example + + +class RemoveTopicMetricCollector(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + topic_selector = "?my/topic//" + builder = TopicMetricCollectorBuilder().export_to_prometheus(False) + builder = builder.group_by_topic_type(True) + builder = builder.group_by_topic_view(True) + builder = builder.group_by_path_prefix_parts(15) + builder = builder.maximum_groups(10) + collector = builder.create( + "Topic Metric Collector 1", topic_selector + ) + await session.metrics.put_topic_metric_collector(collector) + await session.metrics.remove_topic_metric_collector(collector.name) + print(f"{collector.name} has been removed.") + + +if __name__ == "__main__": + asyncio.run( + RemoveTopicMetricCollector().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/time_series/__init__.py b/python/examples/src/diffusion_examples/time_series/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/python/examples/src/diffusion_examples/time_series/append_to_time_series_topic.py b/python/examples/src/diffusion_examples/time_series/append_to_time_series_topic.py new file mode 100644 index 00000000..61bfd99b --- /dev/null +++ b/python/examples/src/diffusion_examples/time_series/append_to_time_series_topic.py @@ -0,0 +1,59 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +import diffusion.features.timeseries +import diffusion.datatypes +from diffusion.features.topics import TopicAddResponse +from diffusion_examples.utils.program import Example, random_double + +class AppendToTimeSeriesTopic(Example): + + async def run(self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with diffusion.sessions().principal(principal).credentials( + diffusion.Credentials(password) + ).open(server_url) as session: + specification = diffusion.features.timeseries.TimeSeries.of( + diffusion.datatypes.DOUBLE + ).with_properties( + TIME_SERIES_RETAINED_RANGE="limit 15 last 10s", + TIME_SERIES_SUBSCRIPTION_RANGE="limit 3", + ) + topic = "my/time/series/topic/path" + result = await session.topics.add_topic(topic, specification) + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + print("Topic already exists.") + for i in range(25): + new_value = random_double() + await session.time_series.append( + topic, new_value, diffusion.datatypes.DOUBLE + ) + + + +if __name__ == "__main__": + asyncio.run( + AppendToTimeSeriesTopic().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/time_series/append_to_time_series_topic_with_user_supplied_timestamp.py b/python/examples/src/diffusion_examples/time_series/append_to_time_series_topic_with_user_supplied_timestamp.py new file mode 100644 index 00000000..72bc646d --- /dev/null +++ b/python/examples/src/diffusion_examples/time_series/append_to_time_series_topic_with_user_supplied_timestamp.py @@ -0,0 +1,73 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +import datetime + +import diffusion.datatypes +from diffusion import Credentials +from diffusion.features.timeseries import TimeSeries +from diffusion.features.topics import TopicAddResponse +from diffusion_examples.utils.program import Example, random_double + + +class AppendToTimeSeriesTopicWithUserSuppliedTimestamp(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with diffusion.sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + specification = TimeSeries.of( + diffusion.datatypes.DOUBLE + ).with_properties( + TIME_SERIES_RETAINED_RANGE="limit 15 last 10s", + TIME_SERIES_SUBSCRIPTION_RANGE="limit 3", + ) + topic = "my/time/series/topic/path/user/supplied" + result = await session.topics.add_topic(topic, specification) + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + print("Topic already exists.") + + + millis = 1000000 + + for i in range(25): + new_value = random_double() + millis += 1 + await session.time_series.append( + topic, + new_value, + diffusion.datatypes.DOUBLE, + datetime.datetime.fromtimestamp( + millis, tz=datetime.timezone.utc + ), + ) + + + +if __name__ == "__main__": + asyncio.run( + AppendToTimeSeriesTopicWithUserSuppliedTimestamp().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/time_series/create_time_series_topic.py b/python/examples/src/diffusion_examples/time_series/create_time_series_topic.py new file mode 100644 index 00000000..3c0b9a20 --- /dev/null +++ b/python/examples/src/diffusion_examples/time_series/create_time_series_topic.py @@ -0,0 +1,59 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" +import diffusion +import asyncio +import diffusion.datatypes +import diffusion.features.timeseries +from diffusion.features.topics import TopicAddResponse + +from diffusion_examples.utils.program import Example + + +class CreateTimeSeriesTopic(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with diffusion.sessions().principal(principal).credentials( + diffusion.Credentials(password) + ).open(server_url) as session: + specification = diffusion.features.timeseries.TimeSeries.of( + diffusion.datatypes.DOUBLE + ).with_properties( + TIME_SERIES_RETAINED_RANGE="limit 15 last 10s", + TIME_SERIES_SUBSCRIPTION_RANGE="limit 3", + ) + + topic = "my/time/series/topic/path" + result = await session.topics.add_topic(topic, specification) + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + print("Topic already exists.") + + + + +if __name__ == "__main__": + asyncio.run( + CreateTimeSeriesTopic().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) + diff --git a/python/examples/src/diffusion_examples/time_series/edit_time_series_topic.py b/python/examples/src/diffusion_examples/time_series/edit_time_series_topic.py new file mode 100644 index 00000000..577cf663 --- /dev/null +++ b/python/examples/src/diffusion_examples/time_series/edit_time_series_topic.py @@ -0,0 +1,70 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +import random +from diffusion import Credentials +from diffusion.features.topics import TopicAddResponse +from diffusion_examples.utils.program import Example +import diffusion.datatypes +import diffusion.features.timeseries + + +class EditTimeSeriesTopic(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with diffusion.sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + specification = diffusion.features.timeseries.TimeSeries.of( + diffusion.datatypes.DOUBLE + ).with_properties( + TIME_SERIES_RETAINED_RANGE="limit 15 last 10s", + TIME_SERIES_SUBSCRIPTION_RANGE="limit 3", + ) + + topic = "my/time/series/topic/path" + result = await session.topics.add_topic(topic, specification) + + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + print("Topic already exists.") + + for _ in range(0, 25): + new_value = random.random() + await session.time_series.append( + topic, new_value, diffusion.datatypes.DOUBLE + ) + + await session.time_series.edit( + topic, 20, 3.14, diffusion.datatypes.DOUBLE + ) + + + + +if __name__ == "__main__": + asyncio.run( + EditTimeSeriesTopic().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/time_series/range_query_a_time_series_topic.py b/python/examples/src/diffusion_examples/time_series/range_query_a_time_series_topic.py new file mode 100644 index 00000000..b7b4b463 --- /dev/null +++ b/python/examples/src/diffusion_examples/time_series/range_query_a_time_series_topic.py @@ -0,0 +1,87 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +import random +from diffusion import Credentials +from diffusion.features.topics import TopicAddResponse +from diffusion_examples.utils.program import Example +import diffusion.datatypes +import diffusion.features.timeseries + + +class RangeQueryATimeSeriesTopic(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with diffusion.sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + specification = diffusion.features.timeseries.TimeSeries.of( + diffusion.datatypes.DOUBLE + ).with_properties( + TIME_SERIES_RETAINED_RANGE="limit 50 last 120s", + TIME_SERIES_SUBSCRIPTION_RANGE="limit 3", + ) + + topic = "my/time/series/topic/path" + result = await session.topics.add_topic(topic, specification) + + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + print("Topic already exists.") + + + for _ in range(0, 25): + new_value = random.random() + await session.time_series.append( + topic, new_value, diffusion.datatypes.DOUBLE + ) + + await session.time_series.edit( + topic, 10, 3.14, diffusion.datatypes.DOUBLE + ) + + range_query = session.time_series.range_query().as_( + diffusion.datatypes.DOUBLE + ) + + # Create a time series range query from values 5 to 15. + + query_result = await range_query.from_(5).to(15).select_from(topic) + + event_results = query_result.events + + for event_result in event_results: + report = ( + f"{event_result.metadata.sequence} " + f"({event_result.metadata.timestamp}): {event_result.value}" + ) + print(report) + + + +if __name__ == "__main__": + asyncio.run( + RangeQueryATimeSeriesTopic().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/time_series/subscribe_to_time_series_topics.py b/python/examples/src/diffusion_examples/time_series/subscribe_to_time_series_topics.py new file mode 100644 index 00000000..a323b3b0 --- /dev/null +++ b/python/examples/src/diffusion_examples/time_series/subscribe_to_time_series_topics.py @@ -0,0 +1,136 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +import random +import typing + +from diffusion import Credentials +from diffusion.features.topics import TopicAddResponse, TopicSpecification +from diffusion_examples.utils.program import Example +import diffusion.datatypes +import diffusion.features.timeseries +from diffusion.features.topics.streams import ValueStreamHandler + + +class SubscribeToTimeSeriesTopics(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with diffusion.sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + specification = diffusion.features.timeseries.TimeSeries.of( + diffusion.datatypes.DOUBLE + ).with_properties( + TIME_SERIES_RETAINED_RANGE="limit 15 last 10s", + TIME_SERIES_SUBSCRIPTION_RANGE="limit 3", + ) + + topic = "my/time/series/topic/path" + topic_selector = "?my/time/series//" + result = await session.topics.add_topic(topic, specification) + + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + print("Topic already exists.") + + for _ in range(25): + new_value = random.random() + await session.time_series.append( + topic, new_value, diffusion.datatypes.DOUBLE + ) + + value_stream = self.ValueStream() + session.topics.add_value_stream(topic_selector, value_stream) + + await session.topics.subscribe(topic_selector) + + await session.topics.unsubscribe(topic_selector) + await session.topics.remove_stream(value_stream) + + + class ValueStream(ValueStreamHandler): + def __init__(self) -> None: + super().__init__( + diffusion.datatypes.DOUBLE, + subscribe=self.on_subscription, + unsubscribe=self.on_unsubscription, + update=self.on_update, + close=self.on_close, + ) + self._stream_values: typing.List[str] = [] + + + + async def on_close( + self, + topic_path: str, + topic_spec: TopicSpecification, + topic_value: typing.Optional[diffusion.datatypes.DOUBLE], + **kwargs + ) -> None: + pass + + # noinspection PyUnusedLocal + def on_subscription( + self, + topic_path: str, + topic_spec: TopicSpecification, + topic_value: typing.Optional[diffusion.datatypes.DOUBLE], + **kwargs + ) -> None: + message = f"Subscribed to {topic_path}." + print(message) + + # noinspection PyUnusedLocal + def on_unsubscription( + self, + topic_path: str, + topic_spec: TopicSpecification, + topic_value: typing.Optional[diffusion.datatypes.DOUBLE], + reason: typing.Any, + **kwargs + ) -> None: + message = f"Unsubscribed from {topic_path}: {reason}." + print(message) + + def on_update( + self, + topic_path: str, + topic_spec: TopicSpecification, + old_value: typing.Optional[diffusion.datatypes.DOUBLE], + topic_value: typing.Optional[diffusion.datatypes.DOUBLE], + **kwargs, + ) -> None: + message = ( + f"{topic_path} changed from " + f"{'NULL' if old_value is None else old_value} to {topic_value}." + ) + print(message) + + +if __name__ == "__main__": + asyncio.run( + SubscribeToTimeSeriesTopics().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/time_series/time_series_cross_compatible_datatypes.py b/python/examples/src/diffusion_examples/time_series/time_series_cross_compatible_datatypes.py new file mode 100644 index 00000000..83543d71 --- /dev/null +++ b/python/examples/src/diffusion_examples/time_series/time_series_cross_compatible_datatypes.py @@ -0,0 +1,130 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +import random +import typing + +import diffusion.datatypes +from diffusion import Credentials +from diffusion.features.topics import TopicAddResponse, ValueStreamHandler, TopicSpecification +import diffusion.features.timeseries +from diffusion_examples.utils.program import Example + +class TimeSeriesCrossCompatibleDatatypes(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with diffusion.sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + specification = diffusion.features.timeseries.TimeSeries.of( + diffusion.datatypes.DOUBLE + ).with_properties( + TIME_SERIES_RETAINED_RANGE="limit 15 last 10s", + TIME_SERIES_SUBSCRIPTION_RANGE="limit 3", + ) + + topic = "my/time/series/topic/path" + topic_selector = "?my/time/series//" + + result = await session.topics.add_topic(topic, specification) + + if result == TopicAddResponse.CREATED: + print("Topic has been created.") + else: + print("Topic already exists.") + + for i in range(25): + new_value = random.random() + await session.time_series.append( + topic, new_value, diffusion.datatypes.DOUBLE + ) + + json_stream = JSONStream() + session.topics.add_value_stream(topic_selector, json_stream) + + await session.topics.subscribe(topic_selector) + + await session.topics.unsubscribe(topic_selector) + await session.topics.remove_stream(json_stream) + + +class JSONStream(ValueStreamHandler): + def __init__(self) -> None: + super().__init__( + data_type=diffusion.datatypes.JSON, + subscribe=self.on_subscription, + update=self.on_update, + close=self.on_close, + unsubscribe=self.on_unsubscription, + ) + + def on_close( + self, + topic_path: str, + topic_spec: TopicSpecification, + topic_value: typing.Optional[diffusion.datatypes.JSON], + **kwargs + ) -> None: + pass + + def on_subscription( + self, + topic_path: str, + topic_spec: TopicSpecification, + topic_value: typing.Optional[diffusion.datatypes.JSON], + **kwargs + ) -> None: + + print(f"Subscribed to {topic_path}.") + + def on_unsubscription( + self, + topic_path: str, + topic_spec: TopicSpecification, + topic_value: typing.Optional[diffusion.datatypes.JSON], + reason: typing.Optional[typing.Any], + **kwargs + ) -> None: + print(f"Unsubscribed from {topic_path}: {reason}.") + + def on_update( + self, + topic_path: str, + topic_spec: TopicSpecification, + old_value: typing.Optional[diffusion.datatypes.JSON], + topic_value: typing.Optional[diffusion.datatypes.JSON], + **kwargs + ) -> None: + addition = ( + f"{topic_path} changed from " + f"{('NULL' if old_value is None else old_value.value)}" + f" to {'NULL' if topic_value is None else topic_value.value}." + ) + print(addition) + + +if __name__ == "__main__": + asyncio.run( + TimeSeriesCrossCompatibleDatatypes().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/utils/__init__.py b/python/examples/src/diffusion_examples/utils/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/python/examples/src/diffusion_examples/utils/program.py b/python/examples/src/diffusion_examples/utils/program.py new file mode 100644 index 00000000..4686b00c --- /dev/null +++ b/python/examples/src/diffusion_examples/utils/program.py @@ -0,0 +1,45 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +from __future__ import annotations + +import abc +import random +import struct + + + + +def random_double(): + # Generate a random 64-bit integer + random_bits = random.getrandbits(64) + # Pack this integer as a binary data in big-endian format (64-bit) + packed = struct.pack(">Q", random_bits) + # Unpack the binary data as a double-precision float + random_float = struct.unpack(">d", packed)[0] + return random_float + + +class Example: + + @abc.abstractmethod + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + ... + diff --git a/python/examples/src/diffusion_examples/wrangling/__init__.py b/python/examples/src/diffusion_examples/wrangling/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/python/examples/src/diffusion_examples/wrangling/session_trees/__init__.py b/python/examples/src/diffusion_examples/wrangling/session_trees/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/python/examples/src/diffusion_examples/wrangling/session_trees/__init__.py @@ -0,0 +1 @@ + diff --git a/python/examples/src/diffusion_examples/wrangling/session_trees/get_branch_mapping_table.py b/python/examples/src/diffusion_examples/wrangling/session_trees/get_branch_mapping_table.py new file mode 100644 index 00000000..ae7e295a --- /dev/null +++ b/python/examples/src/diffusion_examples/wrangling/session_trees/get_branch_mapping_table.py @@ -0,0 +1,98 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio + +import diffusion +from diffusion.session import Session +from diffusion.features.control.session_trees.branch_mapping_table import ( + BranchMappingTable, +) +from diffusion_examples.utils.program import Example + +class GetBranchMappingTable(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with Session( + server_url, + principal=principal, + credentials=diffusion.Credentials(password), + ) as session: + # noinspection DuplicatedCode + session_trees = session.session_trees + table = ( + BranchMappingTable.Builder() + .add_branch_mapping( + "$Principal is 'admin'", "my/topic/path/for/admin" + ) + .add_branch_mapping( + "$Principal is 'control'", "my/topic/path/for/control" + ) + .add_branch_mapping( + "$Principal is ''", "my/topic/path/for/anonymous" + ) + .create("my/personal/path") + ) + + await session_trees.put_branch_mapping_table(table) + + table2 = ( + BranchMappingTable.Builder() + .add_branch_mapping( + "$Transport is 'WEBSOCKET'", + "my/alternate/path/for/websocket", + ) + .add_branch_mapping( + "$Transport is 'HTTP_LONG_POLL'", + "my/alternate/path/for/http", + ) + .add_branch_mapping( + "$Transport is 'TCP'", "my/alternate/path/for/tcp" + ) + .create("my/alternate/path") + ) + + await session_trees.put_branch_mapping_table(table2) + + list_session_tree_branches = ( + await session_trees.get_session_tree_branches_with_mappings() + ) + for session_tree_branch in list_session_tree_branches: + print(f"{session_tree_branch}:") + branch_mapping_table = ( + await session_trees.get_branch_mapping_table( + session_tree_branch + ) + ) + for branch_mapping in branch_mapping_table.branch_mappings: + print( + f"{branch_mapping.session_filter}: {branch_mapping.topic_tree_branch}" + ) + + + + +if __name__ == "__main__": + asyncio.run( + GetBranchMappingTable().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/wrangling/session_trees/list_session_tree_branches_with_mappings.py b/python/examples/src/diffusion_examples/wrangling/session_trees/list_session_tree_branches_with_mappings.py new file mode 100644 index 00000000..475736a2 --- /dev/null +++ b/python/examples/src/diffusion_examples/wrangling/session_trees/list_session_tree_branches_with_mappings.py @@ -0,0 +1,86 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio + +import diffusion +from diffusion.features.control.session_trees.branch_mapping_table import ( + BranchMappingTable, +) +from diffusion_examples.utils.program import Example + + + +class ListSessionTreeBranchesWithMappings(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with diffusion.sessions().principal(principal).credentials( + diffusion.Credentials(password) + ).open(server_url) as session: + table = ( + BranchMappingTable.Builder() + .add_branch_mapping( + "$Principal is 'admin'", "my/topic/path/for/admin" + ) + .add_branch_mapping( + "$Principal is 'control'", "my/topic/path/for/control" + ) + .add_branch_mapping( + "$Principal is ''", "my/topic/path/for/anonymous" + ) + .create("my/personal/path") + ) + + await session.session_trees.put_branch_mapping_table(table) + + table2 = ( + BranchMappingTable.Builder() + .add_branch_mapping( + "$Transport is 'WEBSOCKET'", + "my/alternate/path/for/websocket", + ) + .add_branch_mapping( + "$Transport is 'HTTP_LONG_POLL'", + "my/alternate/path/for/http", + ) + .add_branch_mapping( + "$Transport is 'TCP'", "my/alternate/path/for/tcp" + ) + .create("my/alternate/path") + ) + + await session.session_trees.put_branch_mapping_table(table2) + + list_session_tree_branches = ( + await session.session_trees.get_session_tree_branches_with_mappings() + ) + for session_tree_branch in list_session_tree_branches: + print(session_tree_branch) + + + + +if __name__ == "__main__": + asyncio.run( + ListSessionTreeBranchesWithMappings().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/wrangling/session_trees/put_and_remove_branch_mapping_table.py b/python/examples/src/diffusion_examples/wrangling/session_trees/put_and_remove_branch_mapping_table.py new file mode 100644 index 00000000..8db3dd57 --- /dev/null +++ b/python/examples/src/diffusion_examples/wrangling/session_trees/put_and_remove_branch_mapping_table.py @@ -0,0 +1,52 @@ +# Copyright © 2024 Diffusion Data Ltd. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import asyncio +from diffusion import sessions, Credentials +from diffusion_examples.utils.program import Example +from diffusion.features.control.session_trees import BranchMappingTable + + +class PutAndRemoveBranchMappingTable(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials(Credentials(password)).open( + server_url + ) as session: + table = ( + BranchMappingTable.Builder() + .add_branch_mapping("$Principal is 'admin'", "my/topic/path/for/admin") + .add_branch_mapping("$Principal is 'control'", "my/topic/path/for/control") + .add_branch_mapping("$Principal is ''", "my/topic/path/for/anonymous") + .create("my/personal/path") + ) + + await session.session_trees.put_branch_mapping_table(table) + print("Session tree mappings added.") + await session.session_trees.put_branch_mapping_table( + BranchMappingTable.Builder().create("my/personal/path") + ) + print("Session tree mapping table and mappings removed.") + + + +if __name__ == '__main__': + asyncio.run(PutAndRemoveBranchMappingTable().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + )) diff --git a/python/examples/src/diffusion_examples/wrangling/session_trees/put_branch_mapping_table.py b/python/examples/src/diffusion_examples/wrangling/session_trees/put_branch_mapping_table.py new file mode 100644 index 00000000..2573f589 --- /dev/null +++ b/python/examples/src/diffusion_examples/wrangling/session_trees/put_branch_mapping_table.py @@ -0,0 +1,65 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio + +import diffusion +from diffusion.features.control.session_trees.branch_mapping_table import ( + BranchMappingTable, +) + +from diffusion_examples.utils.program import Example + + +class PutBranchMappingTable(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with diffusion.sessions().principal(principal).credentials( + diffusion.Credentials(password) + ).open(server_url) as session: + table = ( + BranchMappingTable.Builder() + .add_branch_mapping( + "$Principal is 'admin'", "my/topic/path/for/admin" + ) + .add_branch_mapping( + "$Principal is 'control'", "my/topic/path/for/control" + ) + .add_branch_mapping( + "$Principal is ''", "my/topic/path/for/anonymous" + ) + .create("my/personal/path") + ) + + await session.session_trees.put_branch_mapping_table(table) + print( + "Branch mapping table created for session tree branch " + f"'{table.session_tree_branch}'." + ) + + + +if __name__ == "__main__": + asyncio.run( + PutBranchMappingTable().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/src/diffusion_examples/wrangling/session_trees/use_case.py b/python/examples/src/diffusion_examples/wrangling/session_trees/use_case.py new file mode 100644 index 00000000..1785a0ed --- /dev/null +++ b/python/examples/src/diffusion_examples/wrangling/session_trees/use_case.py @@ -0,0 +1,205 @@ +""" +Copyright © 2024 Diffusion Data Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +import typing + +from diffusion import sessions, Credentials +from diffusion.features.control.session_trees.branch_mapping_table import ( + BranchMappingTable, +) +import diffusion.datatypes +from diffusion_examples.utils.program import Example +from diffusion.features.topics.streams import ValueStreamHandler +from diffusion.features.topics.details.topic_specification import ( + TopicSpecification, +) + + + +class UseCase(Example): + async def run( + self, + server_url: str = "", + principal: str = "", + password: str = "", + ): + async with sessions().principal(principal).credentials( + Credentials(password) + ).open(server_url) as session: + topic_specification = diffusion.datatypes.STRING + await session.topics.add_and_set_topic( + "my/topic/path/for/admin", + topic_specification, + "Good morning Administrator", + ) + await session.topics.add_and_set_topic( + "my/topic/path/for/control", + topic_specification, + "Good afternoon Control Client", + ) + await session.topics.add_and_set_topic( + "my/topic/path/for/anonymous", + topic_specification, + "Good night Anonymous", + ) + + table = ( + BranchMappingTable.Builder() + .add_branch_mapping( + "$Principal is 'admin'", "my/topic/path/for/admin" + ) + .add_branch_mapping( + "$Principal is 'control'", "my/topic/path/for/control" + ) + .add_branch_mapping( + "$Principal is ''", "my/topic/path/for/anonymous" + ) + .create("my/personal/path") + ) + await session.session_trees.put_branch_mapping_table(table) + + topic_selector = ">my/personal/path" + string_stream = StringStream() + session.topics.add_value_stream(topic_selector, string_stream) + await session.topics.subscribe(topic_selector) + + await asyncio.sleep(5) + + async with sessions().open(server_url) as session2: + another_string_stream = AnotherStringStream() + session2.topics.add_value_stream( + topic_selector, another_string_stream + ) + await session2.topics.subscribe(topic_selector) + + await asyncio.sleep(5) + + list_session_tree_branches = ( + await session.session_trees.get_session_tree_branches_with_mappings() + ) + for session_tree_branch in list_session_tree_branches: + print(f"{session_tree_branch}:") + branch_mapping_table = ( + await session.session_trees.get_branch_mapping_table( + session_tree_branch + ) + ) + for branch_mapping in branch_mapping_table.branch_mappings: + print( + f"{branch_mapping.session_filter}: " + f"{branch_mapping.topic_tree_branch}" + ) + + + await session2.topics.unsubscribe(topic_selector) + await asyncio.sleep(5) + + + +class StringStream(ValueStreamHandler): + def __init__(self) -> None: + super().__init__( + diffusion.datatypes.STRING, + update=self.on_update, + subscribe=self.on_subscription, + unsubscribe=self.on_subscription, + ) + + async def on_update( + self, + topic_path: str, + topic_spec: TopicSpecification, + old_value: typing.Optional[diffusion.datatypes.JSON], + topic_value: typing.Optional[diffusion.datatypes.JSON], + **kwargs + ) -> None: + print( + f"{topic_path} changed from {old_value or 'NULL'} to {topic_value}." + ) + + # noinspection PyUnusedLocal,PyMethodMayBeStatic + async def on_subscription( + self, + topic_path: str, + topic_spec: TopicSpecification, + topic_value: typing.Optional[diffusion.datatypes.STRING], + **kwargs + ) -> None: + print(f"Subscribed to {topic_path}.") + + # noinspection PyUnusedLocal,PyMethodMayBeStatic + async def on_unsubscription( + self, + topic_path: str, + topic_spec: TopicSpecification, + topic_value: typing.Optional[diffusion.datatypes.STRING], + reason: typing.Optional[typing.Any], + **kwargs + ) -> None: + print(f"Unsubscribed from {topic_path}: {reason}.") + + +class AnotherStringStream(ValueStreamHandler): + def __init__(self): + super().__init__( + diffusion.datatypes.STRING, + update=self.on_update, + subscribe=self.on_subscription, + unsubscribe=self.on_subscription, + ) + + async def on_update( + self, + topic_path: str, + topic_spec: TopicSpecification, + old_value: typing.Optional[diffusion.datatypes.STRING], + topic_value: typing.Optional[diffusion.datatypes.STRING], + **kwargs + ) -> None: + print( + f"{topic_path} changed from {old_value or 'NULL'} to {topic_value}." + ) + + # noinspection PyUnusedLocal,PyMethodMayBeStatic + async def on_subscription( + self, + topic_path: str, + topic_spec: TopicSpecification, + topic_value: typing.Optional[diffusion.datatypes.STRING], + **kwargs + ): + print(f"Subscribed to {topic_path}.") + + # noinspection PyUnusedLocal,PyMethodMayBeStatic + async def on_unsubscription( + self, + topic_path: str, + topic_spec: TopicSpecification, + topic_value: typing.Optional[diffusion.datatypes.STRING], + reason: typing.Optional[typing.Any], + **kwargs + ): + print(f"Unsubscribed from {topic_path}: {reason}.") + + +if __name__ == "__main__": + asyncio.run( + UseCase().run( + server_url="ws://localhost:8080", + principal="admin", + password="password", + ) + ) diff --git a/python/examples/topics/add_and_set_topic.py b/python/examples/topics/add_and_set_topic.py deleted file mode 100644 index ad24a604..00000000 --- a/python/examples/topics/add_and_set_topic.py +++ /dev/null @@ -1,31 +0,0 @@ -import asyncio -import diffusion - -server_url = "ws://localhost:8080" -principal = "admin" -credentials = diffusion.Credentials("password") - -path = "foo/bar" -topic_type = diffusion.datatypes.STRING -value = "bla bla" - - -# Because Python SDK for Diffusion is async, all the code needs to be -# wrapped inside a coroutine function, and executed using asyncio.run. -async def main(): - # creating the session - async with diffusion.Session( - url=server_url, principal=principal, credentials=credentials - ) as session: - - # adding a topic, setting its value - add_response = await session.topics.add_and_set_topic(path, topic_type, value) - - if add_response == session.topics.CREATED: - print(f"Topic {path} successfully created.") - if add_response == session.topics.EXISTS: - print(f"Topic {path} already exists.") - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/python/examples/topics/add_and_set_topic_JSON.py b/python/examples/topics/add_and_set_topic_JSON.py deleted file mode 100644 index ef5dc509..00000000 --- a/python/examples/topics/add_and_set_topic_JSON.py +++ /dev/null @@ -1,32 +0,0 @@ -import asyncio -import diffusion -import json - -server_url = "ws://localhost:8080" -principal = "admin" -credentials = diffusion.Credentials("password") - -path = "foo/bar/json" -topic_type = diffusion.datatypes.JSON -value = json.loads("{ \"bla\" : \"bla\" }") - - -# Because Python SDK for Diffusion is async, all the code needs to be -# wrapped inside a coroutine function, and executed using asyncio.run. -async def main(): - # creating the session - async with diffusion.Session( - url=server_url, principal=principal, credentials=credentials - ) as session: - - # adding a topic, setting its value - add_response = await session.topics.add_and_set_topic(path, topic_type, value) - - if add_response == session.topics.CREATED: - print(f"Topic {path} successfully created.") - if add_response == session.topics.EXISTS: - print(f"Topic {path} already exists.") - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/python/examples/topics/add_and_set_topic_with_constraint.py b/python/examples/topics/add_and_set_topic_with_constraint.py deleted file mode 100644 index ba4b3b00..00000000 --- a/python/examples/topics/add_and_set_topic_with_constraint.py +++ /dev/null @@ -1,41 +0,0 @@ -import asyncio -import diffusion.datatypes -from diffusion.features.topics.update.constraint_factory import ConstraintFactory - -server_url = "ws://localhost:8080" -principal = "admin" -credentials = diffusion.Credentials("password") - -path = "foo/bar" -topic_type = diffusion.datatypes.STRING - - -# Because Python SDK for Diffusion is async, all the code needs to be -# wrapped inside a coroutine function, and executed using asyncio.run. -async def main(): - # creating the session - async with diffusion.Session( - url=server_url, principal=principal, credentials=credentials - ) as session: - await session.topics.remove_topic(path) - update_constraint = ConstraintFactory().no_topic - await session.topics.add_and_set_topic( - path, topic_type, "Value1", update_constraint - ) - print( - f"Topic {path} successfully added as the topic did not originally exist - " - "with it's value set to 'Value1'." - ) - update_constraint2 = ConstraintFactory().value( - diffusion.datatypes.STRING("Value1") - ) - await session.topics.add_and_set_topic( - path, topic_type, "Value2", update_constraint2 - ) - print( - "Topic value set successfully with 'Value2' as topic value was previously 'Value1'." - ) - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/python/examples/topics/add_fallback_stream.py b/python/examples/topics/add_fallback_stream.py deleted file mode 100644 index a0b1e3e2..00000000 --- a/python/examples/topics/add_fallback_stream.py +++ /dev/null @@ -1,81 +0,0 @@ -# Copyright (c) 2021 Push Technology Ltd., All Rights Reserved. -# -# Use is subject to license terms. -# -# NOTICE: All information contained herein is, and remains the -# property of Push Technology. The intellectual and technical -# concepts contained herein are proprietary to Push Technology and -# may be covered by U.S. and Foreign Patents, patents in process, and -# are protected by trade secret or copyright law. -""" Example of sending a request to a session filter. """ - -import asyncio -import diffusion -import diffusion.features.topics as topics - -# Diffusion server connection information; same for both sessions -# adjust as needed for the server used in practice -server_url = "ws://localhost:8080" -principal = "admin" -credentials = diffusion.Credentials("password") - - -# stream callback functions -def on_update(*, old_value, topic_path, topic_value, **kwargs): - print("Topic:", topic_path) - if old_value is None: - print(" Initial value:", topic_value) - else: - print(" Value updated") - print(" Old value:", old_value) - print(" New value:", topic_value) - - -def on_subscribe(*, topic_path, **kwargs): - print(f"Subscribed to {topic_path}") - - -def on_unsubscribe(*, reason, topic_path, **kwargs): - print(f"Unsubscribed from {topic_path} because {str(reason)}") - - -# example properties -topic_selector = "foo/bar" -topic_type = diffusion.datatypes.STRING - -session_duration = 15 - -# fallback stream object -fallback_stream = topics.ValueStreamHandler( - data_type=topic_type, - update=on_update, - subscribe=on_subscribe, - unsubscribe=on_unsubscribe, -) - - -# Because Python SDK for Diffusion is async, all the code needs to be -# wrapped inside a coroutine function, and executed using asyncio.run. -async def main(): - - # creating the session - async with diffusion.Session( - url=server_url, principal=principal, credentials=credentials - ) as session: - - print("Adding fallback stream") - session.topics.add_fallback_stream(fallback_stream) - - print(f"Subscribing to {topic_selector}") - await session.topics.subscribe(topic_selector) - - await asyncio.sleep(session_duration) - - print(f"Unsubscribing from {topic_selector}") - await session.topics.unsubscribe(topic_selector) - - await asyncio.sleep(5) # keep alive to display the unsubscription message - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/python/examples/topics/add_topic.py b/python/examples/topics/add_topic.py deleted file mode 100644 index e1ef00c8..00000000 --- a/python/examples/topics/add_topic.py +++ /dev/null @@ -1,40 +0,0 @@ -import asyncio -import diffusion -import diffusion.datatypes as datatypes - -server_url = "ws://localhost:8080" -principal = "admin" -credentials = diffusion.Credentials("password") - - -# Because Python SDK for Diffusion is async, all the code needs to be -# wrapped inside a coroutine function, and executed using asyncio.run. -async def main(): - # creating the session - async with diffusion.Session( - url=server_url, principal=principal, credentials=credentials - ) as session: - - # Create a topic from a topic type - path = "topic/string" - add_response = await session.topics.add_topic(path, diffusion.datatypes.STRING) - - print_response(add_response, path, session) - - # Create a topic from a topic specification, with optional properties - path = "topic/integer" - add_response = await session.topics.add_topic( - path, datatypes.INT64.with_properties(VALIDATES_VALUES=True) - ) - print_response(add_response, path, session) - - -def print_response(add_response, path, session): - if add_response == session.topics.CREATED: - print(f"Topic {path} successfully created.") - if add_response == session.topics.EXISTS: - print(f"Topic {path} already exists.") - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/python/examples/topics/add_value_stream.py b/python/examples/topics/add_value_stream.py deleted file mode 100644 index 7dcb1f9d..00000000 --- a/python/examples/topics/add_value_stream.py +++ /dev/null @@ -1,82 +0,0 @@ -# Copyright (c) 2021 Push Technology Ltd., All Rights Reserved. -# -# Use is subject to license terms. -# -# NOTICE: All information contained herein is, and remains the -# property of Push Technology. The intellectual and technical -# concepts contained herein are proprietary to Push Technology and -# may be covered by U.S. and Foreign Patents, patents in process, and -# are protected by trade secret or copyright law. -""" Example of sending a request to a session filter. """ - -import asyncio -import diffusion -import diffusion.features.topics as topics - -# Diffusion server connection information; same for both sessions -# adjust as needed for the server used in practice -server_url = "ws://localhost:8080" -principal = "admin" -credentials = diffusion.Credentials("password") - - -# stream callback functions -def on_update(*, old_value, topic_path, topic_value, **kwargs): - print("Topic:", topic_path) - if old_value is None: - print(" Initial value:", topic_value) - else: - print(" Value updated") - print(" Old value:", old_value) - print(" New value:", topic_value) - - -def on_subscribe(*, topic_path, **kwargs): - print(f"Subscribed to {topic_path}") - - -def on_unsubscribe(*, reason, topic_path, **kwargs): - print(f"Unsubscribed from {topic_path} because {str(reason)}") - - -# example properties -topic_selector = "foo/bar" -topic_type = diffusion.datatypes.STRING - -session_duration = 15 - -# value stream instance -value_stream = topics.ValueStreamHandler( - data_type=topic_type, - update=on_update, - subscribe=on_subscribe, - unsubscribe=on_unsubscribe, -) - - -# Because Python SDK for Diffusion is async, all the code needs to be -# wrapped inside a coroutine function, and executed using asyncio.run. -async def main(): - - # creating the session - async with diffusion.Session( - url=server_url, principal=principal, credentials=credentials - ) as session: - - print("Adding value stream") - session.topics.add_value_stream( - topic_selector=topic_selector, stream=value_stream - ) - - print(f"Subscribing to {topic_selector}") - await session.topics.subscribe(topic_selector) - await asyncio.sleep(session_duration) - - print(f"Unsubscribing from {topic_selector}") - await session.topics.unsubscribe(topic_selector) - - await asyncio.sleep(5) # keep alive to display the unsubscription message - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/python/examples/topics/remove_topic.py b/python/examples/topics/remove_topic.py deleted file mode 100644 index ed62d35a..00000000 --- a/python/examples/topics/remove_topic.py +++ /dev/null @@ -1,29 +0,0 @@ -import asyncio -import diffusion - -server_url = "ws://localhost:8080" -principal = "admin" -credentials = diffusion.Credentials("password") - -path = "foo/bar" -topic_type = diffusion.datatypes.STRING - - -# Because Python SDK for Diffusion is async, all the code needs to be -# wrapped inside a coroutine function, and executed using asyncio.run. -async def main(): - # creating the session - async with diffusion.Session( - url=server_url, principal=principal, credentials=credentials - ) as session: - - # adding a topic - await session.topics.add_topic(path, topic_type) - - # removing the topic - removed = await session.topics.remove_topic(path) - print(f"Removed {removed} topic(s)") - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/python/examples/topics/set_topic.py b/python/examples/topics/set_topic.py deleted file mode 100644 index 4aa96be5..00000000 --- a/python/examples/topics/set_topic.py +++ /dev/null @@ -1,34 +0,0 @@ -import asyncio -import diffusion -import diffusion.datatypes - -server_url = "ws://localhost:8080" -principal = "admin" -credentials = diffusion.Credentials("password") - -path = "foo/bar" -topic_type = diffusion.datatypes.STRING -value = "bla bla" - - -# Because Python SDK for Diffusion is async, all the code needs to be -# wrapped inside a coroutine function, and executed using asyncio.run. -async def main(): - # creating the session - async with diffusion.Session( - url=server_url, principal=principal, credentials=credentials - ) as session: - - # adding a topic, setting its value - add_response = await session.topics.add_topic(path, topic_type) - - if add_response == session.topics.CREATED: - print(f"Topic {path} successfully created.") - if add_response == session.topics.EXISTS: - print(f"Topic {path} already exists.") - - await session.topics.set_topic(path, value, specification=topic_type) - print(f"Topic {path} successfully set to {value}") - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/python/examples/topics/set_topic_with_constraint.py b/python/examples/topics/set_topic_with_constraint.py deleted file mode 100644 index 3dea11da..00000000 --- a/python/examples/topics/set_topic_with_constraint.py +++ /dev/null @@ -1,63 +0,0 @@ -import asyncio -import traceback - -import diffusion -import diffusion.datatypes -from diffusion.features.topics.update.constraint_factory import ConstraintFactory -from diffusion.session import SessionLockScope -from diffusion.session.exceptions import UnsatisfiedConstraintError - -server_url = "ws://localhost:8080" -principal = "admin" -credentials = diffusion.Credentials("password") - -path = "foo/bar" -topic_type = diffusion.datatypes.STRING -value = "bla bla" - - -# Because Python SDK for Diffusion is async, all the code needs to be -# wrapped inside a coroutine function, and executed using asyncio.run. -async def main(): - # creating the session - async with diffusion.Session( - url=server_url, principal=principal, credentials=credentials - ) as session: - await session.topics.remove_topic(path) - await session.topics.add_topic(path, topic_type) - print(f"Topic '{path} successfully added.") - - update_constraint = ConstraintFactory().no_value - await session.topics.set_topic(path, "Value1", topic_type, update_constraint) - print( - "Topic value set successfully with 'Value1' as topic had no value originally." - ) - update_constraint2 = ConstraintFactory().value( - diffusion.datatypes.STRING("Value1") - ) - await session.topics.set_topic(path, "Value2", topic_type, update_constraint2) - print( - "Topic value set successfully with 'Value2' as topic value was previously 'Value1'." - ) - lock = await session.lock(path, SessionLockScope.UNLOCK_ON_SESSION_LOSS) - update_constraint3 = ConstraintFactory().locked(lock) - await session.topics.set_topic(path, "Value3", topic_type, update_constraint3) - print( - "Topic value set successfully with 'Value3' as topic value was previously 'Value2'." - ) - await lock.unlock() - try: - await session.topics.set_topic( - path, "Value4", topic_type, update_constraint3 - ) - print("This line should never run") - except UnsatisfiedConstraintError: - print( - f""" -As expected, tried to set {path} with Lock Constraint, but without lock, got: -{traceback.format_exc()}""" - ) - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/python/requirements.txt b/python/requirements.txt deleted file mode 100644 index d1a83db5..00000000 --- a/python/requirements.txt +++ /dev/null @@ -1,3 +0,0 @@ -diffusion==${python.release.version} -jupyter -requests \ No newline at end of file diff --git a/ts/README.md b/ts/README.md deleted file mode 100644 index f22e406e..00000000 --- a/ts/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# TypeScript examples for JavaScript client - -This directory contains examples showing the use of the JavaScript API in TypeScript for Diffusion and Diffusion Cloud. - -## Client libraries - -You can install the Node version of the JavaScript client library including the TypeScript definitions with the following command: - -`npm install diffusion` - -You can download the TypeScript definitions separately from the following locations: - -* Download from [our website](http://download.pushtechnology.com/cloud/latest/sdks.html#ts) - -* The typescript definitions are also available in the `typescript` directory of the Diffusion installation. diff --git a/ts/connection/connect-securely.ts b/ts/connection/connect-securely.ts new file mode 100644 index 00000000..e74d620d --- /dev/null +++ b/ts/connection/connect-securely.ts @@ -0,0 +1,39 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; + +export async function connectSecurelyExample(): Promise { + /// tag::connection_establishment_accept_all_certificates[] + // Connect to the server securely. + const session = await connect({ + host: 'localhost', + port: 443, + secure: true, + principal: 'admin', + credentials: 'password' + }); + + console.log(`Connected. Session Identifier: ${session.sessionId.toString()}`); + + // Insert work here + /// tag::log + expect(session.sessionId).not.toBeNull(); + expect(session.isConnected()).toBe(true); + /// end::log + + await session.closeSession(); + /// end::connection_establishment_accept_all_certificates[] +} diff --git a/ts/connection/connect-shared-existing.ts b/ts/connection/connect-shared-existing.ts new file mode 100644 index 00000000..82d389c6 --- /dev/null +++ b/ts/connection/connect-shared-existing.ts @@ -0,0 +1,36 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connectShared } from 'diffusion'; + +export async function connectSharedExistingExample(): Promise { + /// tag::connection_establishment_connect_via_shared_worker[] + // Connect to the server through an existing shared session. + const session = await connectShared( + 'my-shared-session', + 'http://localhost/path/to/diffusion-worker.js' + ); + + console.log(`Connected. Session Identifier: ${session.sessionId.toString()}`); + + // Insert work here + /// tag::log + expect(session.sessionId).not.toBeNull(); + expect(session.isConnected()).toBe(true); + /// end::log + + await session.closeSession(); + /// end::connection_establishment_connect_via_shared_worker[] +} diff --git a/ts/connection/connect-shared-new.ts b/ts/connection/connect-shared-new.ts new file mode 100644 index 00000000..9d9597e0 --- /dev/null +++ b/ts/connection/connect-shared-new.ts @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; + +export async function connectSharedNewExample(): Promise { + /// tag::connection_establishment_connect_new_shared_worker[] + // Connect to the server creating a new shared session. + const session = await connect( + { + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }, + 'my-shared-session', + 'http://localhost/path/to/diffusion-worker.js' + ); + + console.log(`Connected. Session Identifier: ${session.sessionId.toString()}`); + + // Insert work here + /// tag::log + expect(session.sessionId).not.toBeNull(); + expect(session.isConnected()).toBe(true); + /// end::log + + await session.closeSession(); + /// end::connection_establishment_connect_new_shared_worker[] +} diff --git a/ts/connection/connect.ts b/ts/connection/connect.ts new file mode 100644 index 00000000..c33345c8 --- /dev/null +++ b/ts/connection/connect.ts @@ -0,0 +1,38 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; + +export async function connectExample(): Promise { + /// tag::connection_establishment_connect_async[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + console.log(`Connected. Session Identifier: ${session.sessionId.toString()}`); + + // Insert work here + /// tag::log + expect(session.sessionId).not.toBeNull(); + expect(session.isConnected()).toBe(true); + /// end::log + + await session.closeSession(); + /// end::connection_establishment_connect_async[] +} diff --git a/ts/connection/resilience-reconnect.ts b/ts/connection/resilience-reconnect.ts new file mode 100644 index 00000000..10c4d55a --- /dev/null +++ b/ts/connection/resilience-reconnect.ts @@ -0,0 +1,61 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, Session } from 'diffusion'; + +export async function connectionReconnectExample(): Promise { + /// tag::connection_resilience_reconnection_strategy[] + let session: Session; + let attempts = 0; + + try { + // Connect to the server. + session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password', + reconnect: { + // Set the maximum amount of time the client will try and reconnect for to 10 minutes + timeout: 1000 * 60 * 10, + // The reconnection strategy is a function that is called when the session is + // disconnected unexpectedly + strategy: (reconnect: () => void, abort: () => void) => { + if (attempts > 10) { + // abort after 10 attempts + abort(); + } else { + // retry after 3 seconds + setTimeout(reconnect, 3000); + } + } + } + }); + } catch (err) { + console.error('Connection could not be established.', err); + throw err; + } + + console.log(`Connected. Session Identifier: ${session.sessionId.toString()}`); + + // Insert work here + /// tag::log + expect(session.sessionId).not.toBeNull(); + expect(session.isConnected()).toBe(true); + /// end::log + + await session.closeSession(); + /// end::connection_resilience_reconnection_strategy[] +} diff --git a/ts/connection/resilience-retry.ts b/ts/connection/resilience-retry.ts new file mode 100644 index 00000000..818fd6d0 --- /dev/null +++ b/ts/connection/resilience-retry.ts @@ -0,0 +1,48 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, Session } from 'diffusion'; + +export async function initialConnectRetryExample(): Promise { + /// tag::connection_resilience_session_establishment_retry_mechanism[] + let session: Session; + try { + // Connect to the server. + session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password', + retry: { + attempts: 10, + interval: 250 + } + }); + } catch (err) { + console.error('Connection could not be established.', err); + throw err; + } + + console.log(`Connected. Session Identifier: ${session.sessionId.toString()}`); + + // Insert work here + /// tag::log + expect(session.sessionId).not.toBeNull(); + expect(session.isConnected()).toBe(true); + /// end::log + + await session.closeSession(); + /// end::connection_resilience_session_establishment_retry_mechanism[] +} diff --git a/ts/connection/session-state-listener.ts b/ts/connection/session-state-listener.ts new file mode 100644 index 00000000..b7cb10e5 --- /dev/null +++ b/ts/connection/session-state-listener.ts @@ -0,0 +1,71 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { CloseReason, connect } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester } from '../../../test/util' +/// end::log + +export async function sessionStateListenerExample(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['close'] + ]); + /// end::log + /// tag::connection_session_state_listener[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + // Attach state listeners + session.on({ + disconnect : () => { + console.log('State changed to disconnected'); + /// tag::log + check.log('disconnect'); + /// end::log + }, + reconnect : () => { + console.log('State changed to reconnected'); + /// tag::log + check.log('reconnect'); + /// end::log + }, + error : (error: Error) => { + console.log('An error occured', error); + /// tag::log + check.log('error'); + /// end::log + }, + close : (reason: CloseReason) => { + console.log('State changed to closed', reason); + /// tag::log + check.log('close'); + /// end::log + } + }); + + // Insert work here + + await session.closeSession(); + /// end::connection_session_state_listener[] + /// tag::log + check.done(); + /// end::log +} diff --git a/ts/messaging/send-to-path.ts b/ts/messaging/send-to-path.ts new file mode 100644 index 00000000..68f85f32 --- /dev/null +++ b/ts/messaging/send-to-path.ts @@ -0,0 +1,83 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, RequestHandler } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester, promiseWithResolvers } from '../../../test/util'; +/// end::log + +export async function messagingSendToPath(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Received message: Hello'], + ['Received response: Goodbye'], + ['Message handler was closed.'], + ]); + + const closedPromise = promiseWithResolvers(); + /// end::log + /// tag::messaging_send_to_path[] + // Connect to the server. + const session1 = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const handler: RequestHandler = { + onRequest: (request, context, responder) => { + console.log(`Received message: ${request}`); + /// tag::log + check.log(`Received message: ${request}`); + /// end::log + responder.respond('Goodbye'); + }, + onError: (error) => { + console.error('An error occurred.', error); + }, + onClose: () => { + console.log('Message handler was closed.'); + /// tag::log + check.log('Message handler was closed.'); + closedPromise.resolve(); + /// end::log + } + }; + + await session1.messages.addRequestHandler('my/message/path', handler); + + // Connect to the server. + const session2 = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const response = await session2.messages.sendRequest('my/message/path', 'Hello'); + console.log(`Received response: ${response}`); + /// tag::log + check.log(`Received response: ${response}`); + /// end::log + + await session1.closeSession(); + await session2.closeSession(); + /// end::messaging_send_to_path[] + /// tag::log + await closedPromise.promise; + await check.done(); + /// end::log +} diff --git a/ts/messaging/send-to-session-filter.ts b/ts/messaging/send-to-session-filter.ts new file mode 100644 index 00000000..b7e8c177 --- /dev/null +++ b/ts/messaging/send-to-session-filter.ts @@ -0,0 +1,119 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, RequestStream } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester, promiseWithResolvers } from '../../../test/util'; +/// end::log + +export async function messagingSendToSessionFilter(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Received message: Hello'], + ['Received response: Goodbye'], + ]); + + const responsePromise = promiseWithResolvers(); + /// end::log + /// tag::messaging_send_to_session_filter[] + // Connect to the server. + const session1 = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const stream1: RequestStream = { + onRequest: (path, request, responder) => { + console.log(`Received message: ${request}`); + /// tag::log + check.log(`Received message: ${request}`); + /// end::log + responder.respond('Goodbye'); + }, + onError: (error) => { + console.error('An error occurred.', error); + }, + onClose: () => { + console.log('Message handler was closed.'); + } + }; + + session1.messages.setRequestStream('my/message/path', stream1); + + // Connect to the server. + const session2 = await connect({ + host: 'localhost', + port: 8080, + principal: 'control', + credentials: 'password' + }); + + const stream2: RequestStream = { + onRequest: (path, request, responder) => { + console.log(`Received message: ${request}`); + responder.respond('I\'m not supposed to receive a message.'); + /// tag::log + check.log('I\'m not supposed to receive a message.'); + /// end::log + }, + onError: (error) => { + console.error('An error occurred.', error); + }, + onClose: () => { + console.log('Message handler was closed.'); + } + }; + + session2.messages.setRequestStream('my/message/path', stream2); + + // Connect to the server. + const session3 = await connect({ + host: 'localhost', + port: 8080, + principal: 'control', + credentials: 'password' + }); + + await session3.messages.sendRequestToFilter( + '$Principal EQ "admin"', + 'my/message/path', + 'Hello', + { + onResponse: (sessionId, response)=> { + console.log(`Received response: ${response}`); + /// tag::log + check.log(`Received response: ${response}`); + responsePromise.resolve(); + /// end::log + }, + onResponseError: (sessionId, error) => { + console.error('Received an error response', error); + } + } + ); + /// tag::log + await responsePromise.promise; + /// end::log + + await session1.closeSession(); + await session2.closeSession(); + await session3.closeSession(); + /// end::messaging_send_to_session_filter[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/messaging/send-to-session-id.ts b/ts/messaging/send-to-session-id.ts new file mode 100644 index 00000000..995b7812 --- /dev/null +++ b/ts/messaging/send-to-session-id.ts @@ -0,0 +1,106 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, RequestStream } from 'diffusion'; +/// tag::log +const { PartiallyOrderedCheckpointTester } = require('../../../test/util'); +/// end::log + +export async function messagingSendToSessionId(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Received message: Hello'], + ['Received response: Goodbye'], + ]); + /// end::log + /// tag::messaging_send_to_session_id[] + // Connect to the server. + const session1 = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const stream1: RequestStream = { + onRequest: (path, request, responder) => { + console.log(`Received message: ${request}`); + /// tag::log + check.log(`Received message: ${request}`); + /// end::log + responder.respond('Goodbye'); + }, + onError: (error) => { + console.error('An error occurred.', error); + }, + onClose: () => { + console.log('Message handler was closed.'); + } + }; + + session1.messages.setRequestStream('my/message/path', stream1); + + // Connect to the server. + const session2 = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const stream2: RequestStream = { + onRequest: (path, request, responder) => { + console.log(`Received message: ${request}`); + responder.respond('I\'m not supposed to receive a message.'); + /// tag::log + check.log('I\'m not supposed to receive a message.'); + /// end::log + }, + onError: (error) => { + console.error('An error occurred.', error); + }, + onClose: () => { + console.log('Message handler was closed.'); + } + }; + + session2.messages.setRequestStream('my/message/path', stream2); + + // Connect to the server. + const session3 = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + console.log(`Session 3 connected ${session3.sessionId}`); + + const response = await session3.messages.sendRequest( + 'my/message/path', + 'Hello', + session1.sessionId); + console.log(`Received response: ${response}`); + /// tag::log + check.log(`Received response: ${response}`); + /// end::log + + await session1.closeSession(); + await session2.closeSession(); + await session3.closeSession(); + /// end::messaging_send_to_session_id[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/monitoring/missing-topic-notifications.ts b/ts/monitoring/missing-topic-notifications.ts new file mode 100644 index 00000000..1e27bb60 --- /dev/null +++ b/ts/monitoring/missing-topic-notifications.ts @@ -0,0 +1,90 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, MissingTopicHandler, topics } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester, promiseWithResolvers } from '../../../test/util'; +/// end::log + +export async function monitoringMissingTopicNotifications(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ 'missing topic notification my/topic/path/does/not/exist/yet' ], + [ 'Subscribed to my/topic/path/does/not/exist/yet' ], + ]); + const promise = promiseWithResolvers(); + /// end::log + /// tag::monitoring_missing_topic_notifications[] + // Connect to the server. + const session1 = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const missingTopicHandler: MissingTopicHandler = { + onMissingTopic: async (notification) => { + /// tag::log + check.log(`missing topic notification ${notification.path}`); + /// end::log + const specification = new topics.TopicSpecification(topics.TopicType.STRING); + await session1.topics.add(notification.path, specification); + }, + onRegister: (path, deregister) => {}, + onClose: (path) => {}, + onError: (path, error) => {} + }; + await session1.topics.addMissingTopicHandler('my/topic/path', missingTopicHandler); + + // Connect to the server. + const session2 = await connect({ + host: 'localhost', + port: 8080, + principal: 'client', + credentials: 'password' + }); + + const valueStream = session2.addStream('?my/topic/path//', datatypes.string()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + promise.resolve(); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${oldValue.get()} to ${newValue.get()}`); + } + }); + + await session2.select('my/topic/path/does/not/exist/yet'); + + // wait until topic has been created + /// tag::log + await promise.promise; + /// end::log + + await session1.closeSession(); + await session2.closeSession(); + /// end::monitoring_missing_topic_notifications[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/monitoring/session-event-listener.ts b/ts/monitoring/session-event-listener.ts new file mode 100644 index 00000000..99cabe38 --- /dev/null +++ b/ts/monitoring/session-event-listener.ts @@ -0,0 +1,86 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { + ClientCloseReason, + clients, + connect, + SessionEvent, + SessionEventStream, +} from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester, promiseWithResolvers } from '../../../test/util'; +/// end::log + +export async function monitoringSessionEventListener(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ 'Session open' ]]); + const sessionOpenPromise = promiseWithResolvers(); + /// end::log + /// tag::monitoring_session_event_listener[] + // Connect to the server. + const session1 = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const session2 = await connect({ + host: 'localhost', + port: 8080, + principal: 'client', + credentials: 'password' + }); + + const sessionEventStream: SessionEventStream = { + onSessionEvent: (event: SessionEvent) => { + if (event.isOpenEvent()) { + console.log(`New session: id=${event.sessionId}`); + /// tag::log + check.log(`Session open`); + sessionOpenPromise.resolve(); + /// end::log + } else if (event.type === clients.SessionEventStreamEventType.STATE) { + console.log(`Session state changed: id=${event.sessionId}, state=${event.state}`); + } else { + console.log( + `Session properties changed: id=${event.sessionId}, properties=${JSON.stringify(event.changedProperties)}` + ); + } + }, + onClose: () => { + console.log('Stream closed'); + }, + onError: (err) => { + console.error(`An error occured: ${err}`); + } + }; + + await session1.clients.addSessionEventListener(sessionEventStream, { + properties: new Set(clients.PropertyKeys.ALL_FIXED_PROPERTIES), + filter: `$Principal NE 'admin'` + }); + + /// tag::log + await sessionOpenPromise.promise; + /// end::log + await session2.closeSession(); + await session1.closeSession(); + /// end::monitoring_session_event_listener[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/monitoring/topic-notifications.ts b/ts/monitoring/topic-notifications.ts new file mode 100644 index 00000000..0bef8878 --- /dev/null +++ b/ts/monitoring/topic-notifications.ts @@ -0,0 +1,111 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, TopicNotificationListener, TopicNotificationType, topics } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester } from '../../../test/util'; +/// end::log + +export async function monitoringTopicNotifications(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Topic my/topic/path has been added.', + 'Descendant Topic my/topic/path/descendant has been added.' + ]]); + /// end::log + /// tag::monitoring_topic_notifications[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const topicNotificationListener: TopicNotificationListener = { + onTopicNotification: (path, specification, type) => { + switch (type) { + case TopicNotificationType.ADDED: + console.log(`Topic ${path} has been added.`); + /// tag::log + check.log(`Topic ${path} has been added.`); + /// end::log + break; + case TopicNotificationType.SELECTED: + console.log(`Topic ${path} has been selected.`); + break; + case TopicNotificationType.DESELECTED: + console.log(`Topic ${path} has been deselected.`); + break; + case TopicNotificationType.REMOVED: + console.log(`Topic ${path} has been removed.`); + break; + } + }, + onDescendantNotification: (path, type) => { + switch (type) { + case TopicNotificationType.ADDED: + console.log(`Descendant Topic ${path} has been added.`); + /// tag::log + check.log(`Descendant Topic ${path} has been added.`); + /// end::log + break; + case TopicNotificationType.SELECTED: + console.log(`Descendant Topic ${path} has been selected.`); + break; + case TopicNotificationType.DESELECTED: + console.log(`Descendant Topic ${path} has been deselected.`); + break; + case TopicNotificationType.REMOVED: + console.log(`Descendant Topic ${path} has been removed.`); + break; + } + }, + onClose: () => {}, + onError: (error) => {} + }; + const registration = await session.notifications.addListener(topicNotificationListener); + await registration.select('>my/topic/path'); + + const specification = new topics.TopicSpecification(topics.TopicType.STRING); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.string(), + 'Good morning', + { specification: specification } + ); + await session.topicUpdate.set( + 'my/topic/path/descendant', + datatypes.string(), + 'Good afternoon', + { specification: specification } + ); + await session.topicUpdate.set( + 'other/path/of/the/topic/tree', + datatypes.string(), + 'This will not generate a notification', + { specification: specification } + ); + + await session.topics.remove('my/topic/path'); + + await session.unsubscribe('?my/topic/path//'); + + await session.closeSession(); + /// end::monitoring_topic_notifications[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/package.json b/ts/package.json deleted file mode 100644 index 251f7801..00000000 --- a/ts/package.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "diffusion-examples", - "version": "6.9.8", - "description": "Examples for using the Diffusion JavaScript client", - "main": "index.js", - "directories": { - "example": "examples" - }, - "scripts": { - "start": "npm run check && npm run compile", - "check": "eslint src/**/*.ts", - "compile": "tsc" - }, - "license": "Apache-2.0", - "dependencies": { - "@types/long": "4.0.1", - "@types/node": "16.7.10", - "@typescript-eslint/eslint-plugin": "4.31.1", - "@typescript-eslint/parser": "4.31.1", - "eslint": "7.32.0", - "eslint-plugin-deprecation": "1.2.1", - "long": "4.0.0", - "typescript": "4.4.3" - } -} diff --git a/ts/ping/ping-server.ts b/ts/ping/ping-server.ts new file mode 100644 index 00000000..0c034d1a --- /dev/null +++ b/ts/ping/ping-server.ts @@ -0,0 +1,33 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; + +export async function pingExample(): Promise { + /// tag::ping_server[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + await session.pingServer(); + console.log('Received Ping response.'); + + await session.closeSession(); + /// end::ping_server[] +} diff --git a/ts/pubsub/constraint/add-topic-and-set-and-operator.ts b/ts/pubsub/constraint/add-topic-and-set-and-operator.ts new file mode 100644 index 00000000..784e93ed --- /dev/null +++ b/ts/pubsub/constraint/add-topic-and-set-and-operator.ts @@ -0,0 +1,77 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics, topicUpdate, updateConstraints } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue } from '../../../../test/util'; +/// end::log + +export async function addTopicAndSetAndConstraintExample(): Promise { + /// tag::pub_sub_publish_with_constraint_add_and_set_topic_and[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + try { + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + const jsonData = datatypes.json().from({ diffusion: 'data' }); + + const topicCreationResult = await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { specification: specification } + ); + + if (topicCreationResult === topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult).toBe(topicUpdate.TopicCreationResult.CREATED); + /// end::log + + const updateConstraintA = updateConstraints() + .jsonValue() + .without('/bar'); + const updateConstraintB = updateConstraints() + .jsonValue() + .with('/diffusion', 'data', topicUpdate.UpdateConstraintOperator.IS); + + const updateConstraint = updateConstraintA.and(updateConstraintB); + const newJsonData = datatypes.json().from({ diffusion: 'baz' }); + + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + newJsonData, + { constraint: updateConstraint } + ); + } catch (err) { + console.error('Topic value could not be set.', err); + throw err; + } + + await session.closeSession(); + /// end::pub_sub_publish_with_constraint_add_and_set_topic_and[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path', { diffusion: 'baz' }); + /// end::log +} diff --git a/ts/pubsub/constraint/add-topic-and-set-json-value-with.ts b/ts/pubsub/constraint/add-topic-and-set-json-value-with.ts new file mode 100644 index 00000000..91118272 --- /dev/null +++ b/ts/pubsub/constraint/add-topic-and-set-json-value-with.ts @@ -0,0 +1,79 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { + connect, + datatypes, + topics, + topicUpdate, + updateConstraints +} from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue } from '../../../../test/util'; +/// end::log + +export async function addTopicAndSetJsonValueWithConstraintExample(): Promise { + /// tag::pub_sub_publish_with_constraint_add_and_set_topic_json_value_with[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + try { + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + + const jsonData = datatypes.json().from({ diffusion: 'bar' }); + const topicCreationResult = await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { specification: specification } + ); + + if (topicCreationResult === topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + throw new Error('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult).toBe(topicUpdate.TopicCreationResult.CREATED); + /// end::log + + const updateConstraint = updateConstraints() + .jsonValue().with('/diffusion', 'bar', topicUpdate.UpdateConstraintOperator.IS); + + const jsonData2 = datatypes.json().from({ diffusion: 'baz' }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData2, + { constraint: updateConstraint } + ); + + console.log('Topic value has been set.'); + } catch (err) { + console.error('Topic value could not be set.', err); + throw err; + } + + await session.closeSession(); + /// end::pub_sub_publish_with_constraint_add_and_set_topic_json_value_with[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path', { diffusion: 'baz' }); + /// end::log +} diff --git a/ts/pubsub/constraint/add-topic-and-set-json-value-without.ts b/ts/pubsub/constraint/add-topic-and-set-json-value-without.ts new file mode 100644 index 00000000..2a7d12fd --- /dev/null +++ b/ts/pubsub/constraint/add-topic-and-set-json-value-without.ts @@ -0,0 +1,79 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { + connect, + datatypes, + topics, + topicUpdate, + updateConstraints +} from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue } from '../../../../test/util'; +/// end::log + +export async function addTopicAndSetJsonValueWithoutConstraintExample(): Promise { + /// tag::pub_sub_publish_with_constraint_add_and_set_topic_json_value_without[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + try { + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + + const jsonData = datatypes.json().from({ diffusion: 'data' }); + const topicCreationResult = await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { specification: specification } + ); + + if (topicCreationResult === topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + throw new Error('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult).toBe(topicUpdate.TopicCreationResult.CREATED); + /// end::log + + const updateConstraint = updateConstraints() + .jsonValue().without('/bar'); + + const jsonData2 = datatypes.json().from({ diffusion: 'baz' }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData2, + { constraint: updateConstraint } + ); + + console.log('Topic value has been set.'); + } catch (err) { + console.error('Topic value could not be set.', err); + throw err; + } + + await session.closeSession(); + /// end::pub_sub_publish_with_constraint_add_and_set_topic_json_value_without[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path', { diffusion: 'baz' }); + /// end::log +} diff --git a/ts/pubsub/constraint/add-topic-and-set-no-topic.ts b/ts/pubsub/constraint/add-topic-and-set-no-topic.ts new file mode 100644 index 00000000..4da3e7e0 --- /dev/null +++ b/ts/pubsub/constraint/add-topic-and-set-no-topic.ts @@ -0,0 +1,62 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics, topicUpdate, updateConstraints } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue } from '../../../../test/util'; +/// end::log + +export async function addTopicAndSetNoTopicConstraintExample(): Promise { + /// tag::pub_sub_publish_with_constraint_add_and_set_topic_no_topic[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + try { + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + const updateConstraint = updateConstraints().noTopic(); + + const jsonData = datatypes.json().from({ diffusion: 'data' }); + const topicCreationResult = await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { specification: specification, constraint: updateConstraint } + ); + + if (topicCreationResult === topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult).toBe(topicUpdate.TopicCreationResult.CREATED); + /// end::log + console.log('Topic value has been set.'); + } catch (err) { + console.error('Topic value could not be set.', err); + throw err; + } + + await session.closeSession(); + /// end::pub_sub_publish_with_constraint_add_and_set_topic_no_topic[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path', { diffusion: 'data' }); + /// end::log +} diff --git a/ts/pubsub/constraint/add-topic-and-set-session-lock.ts b/ts/pubsub/constraint/add-topic-and-set-session-lock.ts new file mode 100644 index 00000000..23735ec2 --- /dev/null +++ b/ts/pubsub/constraint/add-topic-and-set-session-lock.ts @@ -0,0 +1,64 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics, topicUpdate, updateConstraints } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue } from '../../../../test/util'; +/// end::log + +export async function addTopicAndSetSessionLockConstraintExample(): Promise { + /// tag::pub_sub_publish_with_constraint_add_and_set_topic_session_lock[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + try { + const lock = await session.lock('My Session Lock'); + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + const updateConstraint = updateConstraints().locked(lock); + + const jsonData = datatypes.json().from({ diffusion: 'data' }); + const topicCreationResult = await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { specification: specification, constraint: updateConstraint } + ); + + if (topicCreationResult === topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult).toBe(topicUpdate.TopicCreationResult.CREATED); + /// end::log + + console.log('Topic value has been set.'); + } catch (err) { + console.error('Topic value could not be set.', err); + throw err; + } + + await session.closeSession(); + /// end::pub_sub_publish_with_constraint_add_and_set_topic_session_lock[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path', { diffusion: 'data' }); + /// end::log +} diff --git a/ts/pubsub/constraint/add-topic-and-set-value.ts b/ts/pubsub/constraint/add-topic-and-set-value.ts new file mode 100644 index 00000000..4defc290 --- /dev/null +++ b/ts/pubsub/constraint/add-topic-and-set-value.ts @@ -0,0 +1,71 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics, topicUpdate, updateConstraints } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue } from '../../../../test/util'; +/// end::log + +export async function addTopicAndSetValueConstraintExample(): Promise { + /// tag::pub_sub_publish_with_constraint_add_and_set_topic_value[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + try { + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + + const jsonData = datatypes.json().from({ diffusion: 'data' }); + const topicCreationResult = await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { specification: specification } + ); + + if (topicCreationResult === topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + throw new Error('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult).toBe(topicUpdate.TopicCreationResult.CREATED); + /// end::log + + const updateConstraint = updateConstraints().value(jsonData); + const jsonData2 = datatypes.json().from({ diffusion: 'data2' }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData2, + { constraint: updateConstraint } + ); + + console.log('Topic value has been set.'); + } catch (err) { + console.error('Topic value could not be set.', err); + throw err; + } + + await session.closeSession(); + /// end::pub_sub_publish_with_constraint_add_and_set_topic_value[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path', { diffusion: 'data2' }); + /// end::log +} diff --git a/ts/pubsub/constraint/set-topic-json-value-with.ts b/ts/pubsub/constraint/set-topic-json-value-with.ts new file mode 100644 index 00000000..dee73aeb --- /dev/null +++ b/ts/pubsub/constraint/set-topic-json-value-with.ts @@ -0,0 +1,65 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { + connect, + datatypes, + topicUpdate, + updateConstraints +} from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue } from '../../../../test/util'; +/// end::log + +export async function setTopicJsonValueWithConstraintExample(): Promise { + /// tag::pub_sub_publish_with_constraint_set_topic_json_value_with[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + try { + const jsonData = datatypes.json().from({ diffusion: 'bar' }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData + ); + + const updateConstraint = updateConstraints() + .jsonValue().with('/diffusion', 'bar', topicUpdate.UpdateConstraintOperator.IS); + + const jsonData2 = datatypes.json().from({ diffusion: 'baz' }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData2, + { constraint: updateConstraint } + ); + console.log('Topic value has been set.'); + } catch (err) { + console.error('Topic value could not be set.', err); + throw err; + } + + await session.closeSession(); + /// end::pub_sub_publish_with_constraint_set_topic_json_value_with[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path', { diffusion: 'baz' }); + /// end::log +} diff --git a/ts/pubsub/constraint/set-topic-json-value-without.ts b/ts/pubsub/constraint/set-topic-json-value-without.ts new file mode 100644 index 00000000..a254dec3 --- /dev/null +++ b/ts/pubsub/constraint/set-topic-json-value-without.ts @@ -0,0 +1,64 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { + connect, + datatypes, + updateConstraints +} from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue } from '../../../../test/util'; +/// end::log + +export async function setTopicJsonValueWithoutConstraintExample(): Promise { + /// tag::pub_sub_publish_with_constraint_set_topic_json_value_without[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + try { + const jsonData = datatypes.json().from({ diffusion: null }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData + ); + + const updateConstraint = updateConstraints() + .jsonValue().without('/bar'); + + const jsonData2 = datatypes.json().from({ diffusion: 'baz' }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData2, + { constraint: updateConstraint } + ); + console.log('Topic value has been set.'); + } catch (err) { + console.error('Topic value could not be set.', err); + throw err; + } + + await session.closeSession(); + /// end::pub_sub_publish_with_constraint_set_topic_json_value_without[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path', { diffusion: 'baz' }); + /// end::log +} diff --git a/ts/pubsub/constraint/set-topic-no-value.ts b/ts/pubsub/constraint/set-topic-no-value.ts new file mode 100644 index 00000000..fa4bfb7f --- /dev/null +++ b/ts/pubsub/constraint/set-topic-no-value.ts @@ -0,0 +1,58 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics, updateConstraints } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue } from '../../../../test/util'; +/// end::log + +export async function setTopicNoValueConstraintExample(): Promise { + /// tag::pub_sub_publish_with_constraint_set_topic_no_value[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + try { + await session.topics.add('my/topic/path', topics.TopicType.JSON); + + const jsonData = datatypes.json().from({ + diffusion: ['data', 'more data'] + }); + + const updateConstraint = updateConstraints().noValue(); + + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { constraint: updateConstraint } + ); + + console.log('Topic value has been set.'); + } catch (err) { + console.error('Topic value could not be set.', err); + throw err; + } + + await session.closeSession(); + /// end::pub_sub_publish_with_constraint_set_topic_no_value[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path', { diffusion: ['data', 'more data'] }); + /// end::log +} diff --git a/ts/pubsub/constraint/set-topic-session-lock.ts b/ts/pubsub/constraint/set-topic-session-lock.ts new file mode 100644 index 00000000..17e250e4 --- /dev/null +++ b/ts/pubsub/constraint/set-topic-session-lock.ts @@ -0,0 +1,54 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, updateConstraints } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue } from '../../../../test/util'; +/// end::log + +export async function setTopicSessionLockConstraintExample(): Promise { + /// tag::pub_sub_publish_with_constraint_set_topic_session_lock[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + try { + const lock = await session.lock('My Session Lock'); + const updateConstraint = updateConstraints().locked(lock); + + const jsonData = datatypes.json().from({ diffusion: ['data', 'more data'] }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { constraint: updateConstraint } + ); + + console.log('Topic value has been set.'); + } catch (err) { + console.error('Topic value could not be set.', err); + throw err; + } + + await session.closeSession(); + /// end::pub_sub_publish_with_constraint_set_topic_session_lock[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path', { diffusion: ['data', 'more data'] }); + /// end::log +} diff --git a/ts/pubsub/constraint/set-topic-value.ts b/ts/pubsub/constraint/set-topic-value.ts new file mode 100644 index 00000000..e94cd24d --- /dev/null +++ b/ts/pubsub/constraint/set-topic-value.ts @@ -0,0 +1,58 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, updateConstraints } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue } from '../../../../test/util'; +/// end::log +export async function setTopicValueConstraintExample(): Promise { + /// tag::pub_sub_publish_with_constraint_set_topic_value[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + try { + const jsonData = datatypes.json().from({ diffusion: ['data', 'more data'] }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData + ); + + const updateConstraint = updateConstraints().value(jsonData); + + const jsonData2 = datatypes.json().from({ diffusion: ['data', 'more data', 'yet more data'] }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData2, + { constraint: updateConstraint } + ); + console.log('Topic value has been set.'); + } catch (err) { + console.error('Topic value could not be set.', err); + throw err; + } + + await session.closeSession(); + /// end::pub_sub_publish_with_constraint_set_topic_value[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path', { diffusion: ['data', 'more data', 'yet more data'] }); + /// end::log +} diff --git a/ts/pubsub/fetch/fetch-topics-properties.ts b/ts/pubsub/fetch/fetch-topics-properties.ts new file mode 100644 index 00000000..cdbabbeb --- /dev/null +++ b/ts/pubsub/fetch/fetch-topics-properties.ts @@ -0,0 +1,116 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, Session, topics } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester } from '../../../../test/util'; +/// end::log + +export async function pubSubFetchTopicProperties(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ + 'my/topic/path/with/properties/0 DONT_RETAIN_VALUE: true', + 'my/topic/path/with/properties/0 PERSISTENT: false', + 'my/topic/path/with/properties/0 PUBLISH_VALUES_ONLY: true', + 'my/topic/path/with/properties/1 DONT_RETAIN_VALUE: true', + 'my/topic/path/with/properties/1 PERSISTENT: false', + 'my/topic/path/with/properties/1 PUBLISH_VALUES_ONLY: true', + 'my/topic/path/with/properties/2 DONT_RETAIN_VALUE: true', + 'my/topic/path/with/properties/2 PERSISTENT: false', + 'my/topic/path/with/properties/2 PUBLISH_VALUES_ONLY: true', + 'my/topic/path/with/properties/3 DONT_RETAIN_VALUE: true', + 'my/topic/path/with/properties/3 PERSISTENT: false', + 'my/topic/path/with/properties/3 PUBLISH_VALUES_ONLY: true', + 'my/topic/path/with/properties/4 DONT_RETAIN_VALUE: true', + 'my/topic/path/with/properties/4 PERSISTENT: false', + 'my/topic/path/with/properties/4 PUBLISH_VALUES_ONLY: true' + ] + ]); + /// end::log + /// tag::pub_sub_fetch_topic_properties[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification1 = new topics.TopicSpecification(topics.TopicType.JSON, { + 'DONT_RETAIN_VALUE': 'true', + 'PERSISTENT': 'false', + 'PUBLISH_VALUES_ONLY': 'true' + }); + for (let count = 0; count < 5; count++) { + const jsonData = datatypes.json().from({ diffusion: `data #${count}` }); + await session.topicUpdate.set( + `my/topic/path/with/properties/${count}`, + datatypes.json(), + jsonData, + { specification: specification1 } + ); + } + + const specification2 = new topics.TopicSpecification(topics.TopicType.STRING); + for (let count = 0; count < 5; count++) { + await session.topicUpdate.set( + `my/topic/path/with/default/properties/${count}`, + datatypes.string(), + `diffusion data #${count}`, + { specification: specification2 } + ); + } + + const fetchResult1 = await session.fetchRequest() + .withProperties() + .topicTypes([ topics.TopicType.JSON ]) + .fetch('?my/topic/path//'); + for (const result of fetchResult1.results()) { + console.log(`${result.path()} properties:`); + const properties = result.specification().properties; + for (const property of Object.keys(properties)) { + console.log(` ${property}: ${properties[property]}`); + /// tag::log + if (['DONT_RETAIN_VALUE', 'PERSISTENT', 'PUBLISH_VALUES_ONLY'].includes(property)) { + check.log(`${result.path()} ${property}: ${properties[property]}`); + } + /// end::log + } + } + + const fetchResult2 = await session.fetchRequest() + .withProperties() + .topicTypes([ topics.TopicType.STRING ]) + .fetch('?my/topic/path//'); + for (const result of fetchResult2.results()) { + console.log(`${result.path()} properties:`); + const properties = result.specification().properties; + for (const property of Object.keys(properties)) { + console.log(` ${property}: ${properties[property]}`); + /// tag::log + if (['DONT_RETAIN_VALUE', 'PERSISTENT', 'PUBLISH_VALUES_ONLY'].includes(property)) { + check.log(`${result.path()} ${property}: ${properties[property]}`); + } + /// end::log + } + } + + await session.closeSession(); + /// end::pub_sub_fetch_topic_properties[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/pubsub/fetch/fetch-topics-via-paging.ts b/ts/pubsub/fetch/fetch-topics-via-paging.ts new file mode 100644 index 00000000..1e79f2f4 --- /dev/null +++ b/ts/pubsub/fetch/fetch-topics-via-paging.ts @@ -0,0 +1,84 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, FetchResult, topics } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester } from '../../../../test/util'; +/// end::log + +export async function pubSubFetchTopicViaPaging(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + Array.from({length: 25}). map((v, i) => `my/topic/path/${i}: diffusion data #${i}`) + ]); + /// end::log + /// tag::pub_sub_fetch_topic_via_paging[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.STRING); + + for (let count = 0; count < 25; count++) { + await session.topicUpdate.set( + `my/topic/path/${count}`, + datatypes.string(), + `diffusion data #${count}`, + { specification: specification } + ); + } + + let fetchResult: FetchResult; + let lastTopicPath: string | undefined = undefined; + do { + let fetchRequest = session.fetchRequest() + .withValues(datatypes.string()) + .first(10); + if (lastTopicPath !== undefined) { + fetchRequest = fetchRequest.after(lastTopicPath); + } + fetchResult = await fetchRequest.fetch('?my/topic/path//'); + const topicResults = fetchResult.results(); + + for (const result of topicResults) { + console.log(`${result.path()}: ${result.value()}`); + /// tag::log + check.log(`${result.path()}: ${result.value()}`); + /// end::log + } + if (fetchResult.hasMore()) { + /// tag::log + expect(topicResults.length).toBe(10); + /// end::log + console.log('loading next page'); + lastTopicPath = topicResults[topicResults.length - 1].path(); + } else { + /// tag::log + expect(topicResults.length).toBe(5); + /// end::log + console.log('done'); + } + } while (fetchResult.hasMore()); + + await session.closeSession(); + /// end::pub_sub_fetch_topic_via_paging[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/pubsub/json-patch/json-patch-add.ts b/ts/pubsub/json-patch/json-patch-add.ts new file mode 100644 index 00000000..d4eb9a35 --- /dev/null +++ b/ts/pubsub/json-patch/json-patch-add.ts @@ -0,0 +1,104 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester, promiseWithResolvers } from '../../../../test/util' +/// end::log + +export async function jsonPatchAddExample(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Subscribed to my/topic/path'], + ['my/topic/path changed'], + ['old value Fred: Flintstone', 'old value Barney: Rubble'], + ['new value Fred: Flintstone', 'new value Barney: Rubble', 'new value George: Jetson'], + ['Closed'], + ]); + const valuePromise = promiseWithResolvers(); + /// end::log + /// tag::pub_sub_json_patch_add[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + const jsonData = datatypes.json().from({ + Fred: 'Flintstone', + Barney: 'Rubble' + }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addStream('my/topic/path', datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + /// tag::log + close : () => { + check.log(`Closed`); + }, + /// end::log + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${JSON.stringify(oldValue.get())} to ${JSON.stringify(newValue.get())}`); + /// tag::log + check.log(`${topic} changed`); + const oldJson = oldValue.get(); + const newJson = newValue.get(); + for (const key of Object.keys(oldJson)) { + check.log(`old value ${key}: ${oldJson[key]}`); + } + for (const key of Object.keys(newJson)) { + check.log(`new value ${key}: ${newJson[key]}`); + } + valuePromise.resolve(); + /// end::log + } + }); + + await session.select('my/topic/path'); + + await session.topicUpdate.applyJsonPatch( + 'my/topic/path', [{ + op: 'add', + path: '/George', + value: 'Jetson' + }] + ); + + /// tag::log + await valuePromise.promise; + /// end::log + await session.closeSession(); + /// end::pub_sub_json_patch_add[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/pubsub/json-patch/json-patch-copy.ts b/ts/pubsub/json-patch/json-patch-copy.ts new file mode 100644 index 00000000..a419c90c --- /dev/null +++ b/ts/pubsub/json-patch/json-patch-copy.ts @@ -0,0 +1,122 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester, promiseWithResolvers } from '../../../../test/util' +/// end::log + +export async function jsonPatchCopyExample(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Subscribed to my/topic/path'], + ['my/topic/path changed'], + [ + 'old value Meet the Flintstones/Fred: Flintstone', + 'old value Meet the Flintstones/Barney: Rubble', + 'old value The Jetsons/George: Jetson' + ], + [ + 'new value Meet the Flintstones/Fred: Flintstone', + 'new value Meet the Flintstones/Barney: Rubble', + 'new value The Jetsons/George: Jetson', + 'new value The Jetsons/Fred: Flintstone' + ], + ['Closed'], + ]); + const valuePromise = promiseWithResolvers(); + /// end::log + /// tag::pub_sub_json_patch_copy[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + const jsonData = datatypes.json().from({ + 'Meet the Flintstones': { + 'Fred': 'Flintstone', + 'Barney': 'Rubble' + }, + 'The Jetsons': { + 'George': 'Jetson' + } + }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addStream('my/topic/path', datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + /// tag::log + close : () => { + check.log(`Closed`); + }, + /// end::log + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${JSON.stringify(oldValue.get())} to ${JSON.stringify(newValue.get())}`); + /// tag::log + check.log(`${topic} changed`); + const oldJson = oldValue.get(); + const newJson = newValue.get(); + for (const key of Object.keys(oldJson)) { + for (const name of Object.keys(oldJson[key])) { + check.log(`old value ${key}/${name}: ${oldJson[key][name]}`); + } + } + for (const key of Object.keys(newJson)) { + for (const name of Object.keys(newJson[key])) { + check.log(`new value ${key}/${name}: ${newJson[key][name]}`); + } + } + valuePromise.resolve(); + /// end::log + } + }); + + await session.select('my/topic/path'); + + await session.topicUpdate.applyJsonPatch( + 'my/topic/path', [{ + 'op': 'copy', + 'from': '/Meet the Flintstones/Fred', + 'path': '/The Jetsons/Fred' + }] + ); + + /// tag::log + await valuePromise.promise; + /// end::log + await session.closeSession(); + /// end::pub_sub_json_patch_copy[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/pubsub/json-patch/json-patch-move.ts b/ts/pubsub/json-patch/json-patch-move.ts new file mode 100644 index 00000000..f10885bd --- /dev/null +++ b/ts/pubsub/json-patch/json-patch-move.ts @@ -0,0 +1,105 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester, promiseWithResolvers } from '../../../../test/util' +/// end::log + +export async function jsonPatchMoveExample(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Subscribed to my/topic/path'], + ['my/topic/path changed'], + ['old value Fred: Flintstone', 'old value Barney: Rubble', 'old value George: Jetson'], + ['new value Meet The Flintstones/Fred: Flintstone', 'new value Barney: Rubble', 'new value George: Jetson'], + ['Closed'], + ]); + const valuePromise = promiseWithResolvers(); + /// end::log + /// tag::pub_sub_json_patch_move[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + const jsonData = datatypes.json().from({ + Fred: 'Flintstone', + Barney: 'Rubble', + George: 'Jetson' + }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addStream('my/topic/path', datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + /// tag::log + close : () => { + check.log(`Closed`); + }, + /// end::log + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${JSON.stringify(oldValue.get())} to ${JSON.stringify(newValue.get())}`); + /// tag::log + check.log(`${topic} changed`); + const oldJson = oldValue.get(); + const newJson = newValue.get(); + for (const key of Object.keys(oldJson)) { + check.log(`old value ${key}: ${oldJson[key]}`); + } + for (const key of Object.keys(newJson)) { + check.log(`new value ${key}: ${newJson[key]}`); + } + valuePromise.resolve(); + /// end::log + } + }); + + await session.select('my/topic/path'); + + await session.topicUpdate.applyJsonPatch( + 'my/topic/path', [{ + 'op': 'move', + 'from': '/Fred', + 'path': '/Meet The Flintstones~1Fred' + }] + ); + + /// tag::log + await valuePromise.promise; + /// end::log + await session.closeSession(); + /// end::pub_sub_json_patch_move[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/pubsub/json-patch/json-patch-remove.ts b/ts/pubsub/json-patch/json-patch-remove.ts new file mode 100644 index 00000000..9a46dd96 --- /dev/null +++ b/ts/pubsub/json-patch/json-patch-remove.ts @@ -0,0 +1,104 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester, promiseWithResolvers } from '../../../../test/util' +/// end::log + +export async function jsonPatchRemoveExample(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Subscribed to my/topic/path'], + ['my/topic/path changed'], + ['old value Fred: Flintstone', 'old value Barney: Rubble', 'old value George: Jetson'], + ['new value Fred: Flintstone', 'new value Barney: Rubble'], + ['Closed'], + ]); + const valuePromise = promiseWithResolvers(); + /// end::log + /// tag::pub_sub_json_patch_remove[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + const jsonData = datatypes.json().from({ + Fred: 'Flintstone', + Barney: 'Rubble', + George: 'Jetson' + }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addStream('my/topic/path', datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + /// tag::log + close : () => { + check.log(`Closed`); + }, + /// end::log + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${JSON.stringify(oldValue.get())} to ${JSON.stringify(newValue.get())}`); + /// tag::log + check.log(`${topic} changed`); + const oldJson = oldValue.get(); + const newJson = newValue.get(); + for (const key of Object.keys(oldJson)) { + check.log(`old value ${key}: ${oldJson[key]}`); + } + for (const key of Object.keys(newJson)) { + check.log(`new value ${key}: ${newJson[key]}`); + } + valuePromise.resolve(); + /// end::log + } + }); + + await session.select('my/topic/path'); + + await session.topicUpdate.applyJsonPatch( + 'my/topic/path', [{ + op: 'remove', + path: '/George' + }] + ); + + /// tag::log + await valuePromise.promise; + /// end::log + await session.closeSession(); + /// end::pub_sub_json_patch_remove[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/pubsub/json-patch/json-patch-replace.ts b/ts/pubsub/json-patch/json-patch-replace.ts new file mode 100644 index 00000000..70283983 --- /dev/null +++ b/ts/pubsub/json-patch/json-patch-replace.ts @@ -0,0 +1,105 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester, promiseWithResolvers } from '../../../../test/util' +/// end::log + +export async function jsonPatchReplaceExample(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Subscribed to my/topic/path'], + ['my/topic/path changed'], + ['old value Fred: Flintstone', 'old value Barney: Rubble', 'old value George: Jetson'], + ['new value Fred: Flintstone', 'new value Barney: Rubble', 'new value George: Bedrock'], + ['Closed'], + ]); + const valuePromise = promiseWithResolvers(); + /// end::log + /// tag::pub_sub_json_patch_replace[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + const jsonData = datatypes.json().from({ + Fred: 'Flintstone', + Barney: 'Rubble', + George: 'Jetson' + }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addStream('my/topic/path', datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + /// tag::log + close : () => { + check.log(`Closed`); + }, + /// end::log + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${JSON.stringify(oldValue.get())} to ${JSON.stringify(newValue.get())}`); + /// tag::log + check.log(`${topic} changed`); + const oldJson = oldValue.get(); + const newJson = newValue.get(); + for (const key of Object.keys(oldJson)) { + check.log(`old value ${key}: ${oldJson[key]}`); + } + for (const key of Object.keys(newJson)) { + check.log(`new value ${key}: ${newJson[key]}`); + } + valuePromise.resolve(); + /// end::log + } + }); + + await session.select('my/topic/path'); + + await session.topicUpdate.applyJsonPatch( + 'my/topic/path', [{ + op: 'replace', + path: '/George', + value: 'Bedrock' + }] + ); + + /// tag::log + await valuePromise.promise; + /// end::log + await session.closeSession(); + /// end::pub_sub_json_patch_replace[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/pubsub/json-patch/json-patch-test.ts b/ts/pubsub/json-patch/json-patch-test.ts new file mode 100644 index 00000000..63371de8 --- /dev/null +++ b/ts/pubsub/json-patch/json-patch-test.ts @@ -0,0 +1,97 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester } from '../../../../test/util' +/// end::log + +export async function jsonPatchTestExample(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Subscribed to my/topic/path'], + ['Closed'], + ]); + /// end::log + /// tag::pub_sub_json_patch_test[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + const jsonData = datatypes.json().from({ + Fred: 'Flintstone', + Barney: 'Rubble', + George: 'Jetson' + }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addStream('my/topic/path', datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + /// tag::log + close : () => { + check.log(`Closed`); + }, + /// end::log + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${JSON.stringify(oldValue.get())} to ${JSON.stringify(newValue.get())}`); + /// tag::log + check.log(`${topic} changed`); + const oldJson = oldValue.get(); + const newJson = newValue.get(); + for (const key of Object.keys(oldJson)) { + check.log(`old value ${key}: ${oldJson[key]}`); + } + for (const key of Object.keys(newJson)) { + check.log(`new value ${key}: ${newJson[key]}`); + } + /// end::log + } + }); + + await session.select('my/topic/path'); + + await session.topicUpdate.applyJsonPatch( + 'my/topic/path', [{ + op: 'test', + path: '/Fred', + value: 'Flintstone' + }] + ); + + await session.closeSession(); + /// end::pub_sub_json_patch_test[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/pubsub/publishing/add-topic-and-set.ts b/ts/pubsub/publishing/add-topic-and-set.ts new file mode 100644 index 00000000..78b86e42 --- /dev/null +++ b/ts/pubsub/publishing/add-topic-and-set.ts @@ -0,0 +1,46 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue } from '../../../../test/util'; +/// end::log + +export async function addTopicAndSetExample(): Promise { + /// tag::pub_sub_publish_add_and_set_topic[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + const jsonData = datatypes.json().from({ diffusion: 'data' }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { specification: specification } + ); + console.log('Topic value has been set.'); + + await session.closeSession(); + /// end::pub_sub_publish_add_and_set_topic[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path', { diffusion: 'data' }); + /// end::log +} diff --git a/ts/pubsub/publishing/add-topic-with-properties.ts b/ts/pubsub/publishing/add-topic-with-properties.ts new file mode 100644 index 00000000..87c8594a --- /dev/null +++ b/ts/pubsub/publishing/add-topic-with-properties.ts @@ -0,0 +1,51 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, topics } from 'diffusion'; +/// tag::log +import { expectTopicExists } from '../../../../test/util'; +/// end::log + +export async function addTopicWithPropertiesExample(): Promise { + /// tag::pub_sub_publish_add_topic_custom_properties[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON, { + 'DONT_RETAIN_VALUE': 'true', + 'PERSISTENT': 'false', + 'PUBLISH_VALUES_ONLY': 'true' + }); + const topicAddResult = await session.topics.add('my/topic/path', specification); + if (topicAddResult.added) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicAddResult.added).toBe(true); + /// end::log + + await session.closeSession(); + /// end::pub_sub_publish_add_topic_custom_properties[] + /// tag::log + await expectTopicExists('my/topic/path'); + /// end::log +} diff --git a/ts/pubsub/publishing/add-topic.ts b/ts/pubsub/publishing/add-topic.ts new file mode 100644 index 00000000..b8dae846 --- /dev/null +++ b/ts/pubsub/publishing/add-topic.ts @@ -0,0 +1,47 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, topics } from 'diffusion'; +/// tag::log +import { expectTopicExists } from '../../../../test/util'; +/// end::log + +export async function addTopicExample(): Promise { + /// tag::pub_sub_publish_add_topic[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + const topicAddResult = await session.topics.add('my/topic/path', specification); + if (topicAddResult.added) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicAddResult.added).toBe(true); + /// end::log + + await session.closeSession(); + /// end::pub_sub_publish_add_topic[] + /// tag::log + await expectTopicExists('my/topic/path'); + /// end::log +} diff --git a/ts/pubsub/publishing/set-topic.ts b/ts/pubsub/publishing/set-topic.ts new file mode 100644 index 00000000..355596a4 --- /dev/null +++ b/ts/pubsub/publishing/set-topic.ts @@ -0,0 +1,44 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue } from '../../../../test/util'; +/// end::log + +export async function setTopicExample(): Promise { + /// tag::pub_sub_publish_set_topic[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const jsonData = datatypes.json().from({ diffusion: 'data' }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData + ); + console.log('Topic value has been set.'); + + await session.closeSession(); + /// end::pub_sub_publish_set_topic[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path', { diffusion: 'data' }); + /// end::log +} diff --git a/ts/pubsub/publishing/update-stream-add-and-set.ts b/ts/pubsub/publishing/update-stream-add-and-set.ts new file mode 100644 index 00000000..d714fea0 --- /dev/null +++ b/ts/pubsub/publishing/update-stream-add-and-set.ts @@ -0,0 +1,51 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topicUpdate, topics } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue } from '../../../../test/util'; +/// end::log + +export async function updateSreamAddAndSetExample(): Promise { + /// tag::pub_sub_publish_add_and_set_topic_via_update_stream[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + const jsonData = datatypes.json().from({ diffusion: 'data' }); + const updateStream = session.topicUpdate.newUpdateStreamBuilder() + .specification(specification) + .build('my/topic/path/with/update/stream', datatypes.json()); + const topicCreationResult = await updateStream.set(jsonData); + if (topicCreationResult === topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult).toBe(topicUpdate.TopicCreationResult.CREATED); + /// end::log + + await session.closeSession(); + /// end::pub_sub_publish_add_and_set_topic_via_update_stream[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path/with/update/stream', { diffusion: 'data' }); + /// end::log +} diff --git a/ts/pubsub/publishing/update-stream-set.ts b/ts/pubsub/publishing/update-stream-set.ts new file mode 100644 index 00000000..5f43ce39 --- /dev/null +++ b/ts/pubsub/publishing/update-stream-set.ts @@ -0,0 +1,45 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue } from '../../../../test/util'; +/// end::log + +export async function updateSreamSetExample(): Promise { + /// tag::pub_sub_publish_set_topic_via_update_stream[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + await session.topics.add('my/topic/path/with/update/stream', specification); + + const jsonData = datatypes.json().from({ diffusion: ['data', 'more data'] }); + const updateStream = session.topicUpdate.newUpdateStreamBuilder() + .build('my/topic/path/with/update/stream', datatypes.json()); + await updateStream.set(jsonData); + console.log('Topic value has been set.'); + + await session.closeSession(); + /// end::pub_sub_publish_set_topic_via_update_stream[] + /// tag::log + await expectJsonTopicToHaveValue('my/topic/path/with/update/stream', { diffusion: ['data', 'more data'] }); + /// end::log +} diff --git a/ts/pubsub/removal/automatic-topic-removal.ts b/ts/pubsub/removal/automatic-topic-removal.ts new file mode 100644 index 00000000..9d8a21c5 --- /dev/null +++ b/ts/pubsub/removal/automatic-topic-removal.ts @@ -0,0 +1,149 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics, topicUpdate } from 'diffusion'; +/// tag::log +import { expectTopicCounts } from '../../../../test/util'; +/// end::log + +export async function pubSubAutomaticTopicRemoval(): Promise { + /// tag::pub_sub_remove_automatic_topic_removal[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification1 = new topics.TopicSpecification(topics.TopicType.JSON, { + REMOVAL: 'when time after "Tue, 4 May 2077 11:05:30 GMT"' + }); + const topicCreationResult1 = await session.topics.add('my/topic/path/to/be/removed/time/after', specification1); + if (topicCreationResult1.added) { + console.log(`Topic "${topicCreationResult1.topic}" has been created.`); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult1.added).toBeTrue(); + /// end::log + + const specification2 = new topics.TopicSpecification(topics.TopicType.JSON, { + REMOVAL: 'when subscriptions < 1 for 10m' + }); + const topicCreationResult2 = await session.topics.add('my/topic/path/to/be/removed/subscriptions', specification2); + if (topicCreationResult2.added) { + console.log(`Topic "${topicCreationResult2.topic}" has been created.`); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult2.added).toBeTrue(); + /// end::log + + const specification3 = new topics.TopicSpecification(topics.TopicType.JSON, { + REMOVAL: 'when local subscriptions < 1 for 10m' + }); + const topicCreationResult3 = await session.topics.add('my/topic/path/to/be/removed/local/subscriptions', specification3); + if (topicCreationResult3.added) { + console.log(`Topic "${topicCreationResult3.topic}" has been created.`); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult3.added).toBeTrue(); + /// end::log + + const specification4 = new topics.TopicSpecification(topics.TopicType.JSON, { + REMOVAL: 'when no updates for 10m' + }); + const topicCreationResult4 = await session.topics.add('my/topic/path/to/be/removed/no/updates', specification4); + if (topicCreationResult4.added) { + console.log(`Topic "${topicCreationResult4.topic}" has been created.`); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult4.added).toBeTrue(); + /// end::log + + const specification5 = new topics.TopicSpecification(topics.TopicType.JSON, { + REMOVAL: 'when no session has \'$Principal is "client"\' for 1h' + }); + const topicCreationResult5 = await session.topics.add('my/topic/path/to/be/removed/no/session', specification5); + if (topicCreationResult5.added) { + console.log(`Topic "${topicCreationResult5.topic}" has been created.`); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult5.added).toBeTrue(); + /// end::log + + const specification6 = new topics.TopicSpecification(topics.TopicType.JSON, { + REMOVAL: 'when no local session has \'Department is "Accounts"\' for 1h after 1d' + }); + const topicCreationResult6 = await session.topics.add('my/topic/path/to/be/removed/no/local/session', specification6); + if (topicCreationResult6.added) { + console.log(`Topic "${topicCreationResult6.topic}" has been created.`); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult6.added).toBeTrue(); + /// end::log + + const specification7 = new topics.TopicSpecification(topics.TopicType.JSON, { + REMOVAL: 'when subscriptions < 1 for 10m or no updates for 20m' + }); + const topicCreationResult7 = await session.topics.add('my/topic/path/to/be/removed/subcriptions/or/updates', specification7); + if (topicCreationResult7.added) { + console.log(`Topic "${topicCreationResult7.topic}" has been created.`); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult7.added).toBeTrue(); + /// end::log + + const specification8 = new topics.TopicSpecification(topics.TopicType.JSON, { + REMOVAL: 'when subscriptions < 1 for 10m and no updates for 20m' + }); + const topicCreationResult8 = await session.topics.add('my/topic/path/to/be/removed/subcriptions/and/updates', specification8); + if (topicCreationResult8.added) { + console.log(`Topic "${topicCreationResult8.topic}" has been created.`); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult8.added).toBeTrue(); + /// end::log + + await session.closeSession(); + /// end::pub_sub_remove_automatic_topic_removal[] + /// tag::log + await expectTopicCounts({ + 'my/topic/path/to/be/removed/time/after': 1, + 'my/topic/path/to/be/removed/subscriptions': 1, + 'my/topic/path/to/be/removed/local/subscriptions': 1, + 'my/topic/path/to/be/removed/no/updates': 1, + 'my/topic/path/to/be/removed/no/session': 1, + 'my/topic/path/to/be/removed/no/local/session': 1, + 'my/topic/path/to/be/removed/subcriptions/or/updates': 1, + 'my/topic/path/to/be/removed/subcriptions/and/updates': 1 + }); + /// end::log +} diff --git a/ts/pubsub/removal/remove-multiple-topics.ts b/ts/pubsub/removal/remove-multiple-topics.ts new file mode 100644 index 00000000..6eee891e --- /dev/null +++ b/ts/pubsub/removal/remove-multiple-topics.ts @@ -0,0 +1,112 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics, topicUpdate } from 'diffusion'; +/// tag::log +import { expectTopicCounts } from '../../../../test/util'; +/// end::log + +export async function pubSubRemoveMultipleTopicsViaSelector(): Promise { + /// tag::pub_sub_remove_multiple_topics_via_selector[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + const jsonData1 = datatypes.json().from({ diffusion: [ 'data', 'more data' ] }); + const topicCreationResult1 = await session.topicUpdate.set( + 'my/topic/path/to/be/removed', + datatypes.json(), + jsonData1, + { specification: specification } + ); + if (topicCreationResult1 === topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult1).toBe(topicUpdate.TopicCreationResult.CREATED); + /// end::log + + const jsonData2 = datatypes.json().from({ diffusion: [ 'data', 'also more data' ] }); + const topicCreationResult2 = await session.topicUpdate.set( + 'my/topic/path/to/be/also/removed', + datatypes.json(), + jsonData2, + { specification: specification } + ); + if (topicCreationResult2 === topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult2).toBe(topicUpdate.TopicCreationResult.CREATED); + /// end::log + + const jsonData3 = datatypes.json().from({ diffusion: [ 'no data' ] }); + + const topicCreationResult3 = await session.topicUpdate.set( + 'my/topic/path/will/not/be/removed', + datatypes.json(), + jsonData3, + { specification: specification } + ); + if (topicCreationResult3 === topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult3).toBe(topicUpdate.TopicCreationResult.CREATED); + /// end::log + + const jsonData4 = datatypes.json().from({ diffusion: [ 'no data either' ] }); + + const topicCreationResult4 = await session.topicUpdate.set( + 'my/topic/path/will/not/be/removed/either', + datatypes.json(), + jsonData4, + { specification: specification } + ); + if (topicCreationResult4 === topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult4).toBe(topicUpdate.TopicCreationResult.CREATED); + /// end::log + + + const removalResult = await session.topics.remove('?my/topic/path/to/be//'); + console.log(`${removalResult.removedCount} topics have been removed.`); + + await session.closeSession(); + /// end::pub_sub_remove_multiple_topics_via_selector[] + /// tag::log + await expectTopicCounts({ + 'my/topic/path/to/be/removed': 0, + 'my/topic/path/to/be/also/removed': 0, + 'my/topic/path/will/not/be/removed': 1, + 'my/topic/path/will/not/be/removed/either': 1 + }); + /// end::log +} diff --git a/ts/pubsub/removal/remove-single-topic.ts b/ts/pubsub/removal/remove-single-topic.ts new file mode 100644 index 00000000..3fc1167c --- /dev/null +++ b/ts/pubsub/removal/remove-single-topic.ts @@ -0,0 +1,93 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics, topicUpdate } from 'diffusion'; +/// tag::log +import { expectTopicCounts } from '../../../../test/util'; +/// end::log + +export async function pubSubRemoveSingleTopicViaPath(): Promise { + /// tag::pub_sub_remove_single_topic_via_path[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + const jsonData1 = datatypes.json().from({ diffusion: [ 'data', 'more data' ] }); + const topicCreationResult1 = await session.topicUpdate.set( + 'my/topic/path/to/be/removed', + datatypes.json(), + jsonData1, + { specification: specification } + ); + if (topicCreationResult1 === topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult1).toBe(topicUpdate.TopicCreationResult.CREATED); + /// end::log + + const jsonData2 = datatypes.json().from({ diffusion: [ 'no data' ] }); + const topicCreationResult2 = await session.topicUpdate.set( + 'my/topic/path/will/not/be/removed', + datatypes.json(), + jsonData2, + { specification: specification } + ); + if (topicCreationResult2 === topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult2).toBe(topicUpdate.TopicCreationResult.CREATED); + /// end::log + + const jsonData3 = datatypes.json().from({ diffusion: [ 'no data either' ] }); + + const topicCreationResult3 = await session.topicUpdate.set( + 'my/topic/path/will/not/be/removed/either', + datatypes.json(), + jsonData3, + { specification: specification } + ); + if (topicCreationResult3 === topicUpdate.TopicCreationResult.CREATED) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(topicCreationResult3).toBe(topicUpdate.TopicCreationResult.CREATED); + /// end::log + + await session.topics.remove('my/topic/path/to/be/removed'); + console.log('Topic has been removed.'); + + await session.closeSession(); + /// end::pub_sub_remove_single_topic_via_path[] + /// tag::log + await expectTopicCounts({ + 'my/topic/path/to/be/removed': 0, + 'my/topic/path/will/not/be/removed': 1, + 'my/topic/path/will/not/be/removed/either': 1 + }); + /// end::log +} diff --git a/ts/pubsub/subscribing/subscribe-cross-compatible.ts b/ts/pubsub/subscribing/subscribe-cross-compatible.ts new file mode 100644 index 00000000..1aabfa73 --- /dev/null +++ b/ts/pubsub/subscribing/subscribe-cross-compatible.ts @@ -0,0 +1,118 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, Session, topics } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester, promiseWithResolvers } from '../../../../test/util' +/// end::log + +export async function pubSubSubscribeCrossCompatible(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ + 'JSON stream subscribed to my/int/topic/path', + 'String stream subscribed to my/int/topic/path' + ], + [ + 'JSON stream closed', + 'String stream closed' + ], + ]); + + const { promise: promiseJSON, resolve: resolveJSON } = promiseWithResolvers(); + const { promise: promiseString, resolve: resolveString } = promiseWithResolvers(); + /// end::log + /// tag::pub_sub_subscribe_cross_compatible[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.INT64); + await session.topics.add('my/int/topic/path', specification); + + const jsonValueStream = session.addStream('my/int/topic/path', datatypes.json()); + jsonValueStream.on({ + subscribe : (topic, specification) => { + console.log(`JSON stream subscribed to ${topic}`); + /// tag::log + check.log(`JSON stream subscribed to ${topic}`); + resolveJSON(); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`JSON stream unsubscribed from ${topic}: ${reason}`, Date.now(), JSON.stringify(reason)); + /// tag::log + check.log(`JSON stream unsubscribed from ${topic}: ${reason}`); + /// end::log + }, + /// tag::log + close : () => { + check.log(`JSON stream closed`); + }, + /// end::log + value : (topic, spec, newValue, oldValue) => { + console.log(`JSON stream ${topic} changed from ${oldValue.get()} to ${newValue.get()}`); + /// tag::log + check.log(`JSON stream ${topic} changed from ${oldValue.get()} to ${newValue.get()}`); + /// end::log + } + }); + + const stringValueStream = session.addStream('my/int/topic/path', datatypes.string()); + stringValueStream.on({ + subscribe : (topic, specification) => { + console.log(`String stream subscribed to ${topic}`); + /// tag::log + check.log(`String stream subscribed to ${topic}`); + resolveString(); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`String stream unsubscribed from ${topic}: ${reason}`); + /// tag::log + check.log(`String stream unsubscribed from ${topic}: ${reason}`); + /// end::log + }, + /// tag::log + close : () => { + check.log(`String stream closed`); + }, + /// end::log + value : (topic, spec, newValue, oldValue) => { + console.log(`String stream ${topic} changed from ${oldValue} to ${newValue}`); + /// tag::log + check.log(`String stream ${topic} changed from ${oldValue} to ${newValue}`); + /// end::log + } + }); + + console.log('Selecting my/int/topic/path', Date.now()); + await session.select('my/int/topic/path'); + /// tag::log + console.log('Waiting for both streams to subscribe', Date.now()); + await Promise.all([promiseJSON, promiseString]); + /// end::log + + console.log('Closing session', Date.now()); + await session.closeSession(); + /// end::pub_sub_subscribe_cross_compatible[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/pubsub/subscribing/subscribe-fallback-streams.ts b/ts/pubsub/subscribing/subscribe-fallback-streams.ts new file mode 100644 index 00000000..b10f7fde --- /dev/null +++ b/ts/pubsub/subscribing/subscribe-fallback-streams.ts @@ -0,0 +1,84 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester } from '../../../../test/util' +/// end::log + +export async function pubSubSubscribeFallbackStream(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ + 'Subscribed to my/topic/path', + 'Subscribed to my/other/topic/path', + 'Subscribed to my/additional/topic/path' + ], + ['Closed'], + ]); + /// end::log + /// tag::pub_sub_subscribe_fallback_stream[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + await session.topics.add('my/topic/path', specification); + await session.topics.add('my/other/topic/path', specification); + + const valueStream = session.addFallbackStream(datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + /// tag::log + check.log(`Unsubscribed from ${topic}: ${reason}`); + /// end::log + }, + /// tag::log + close : () => { + check.log(`Closed`); + }, + /// end::log + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${oldValue.get()} to ${newValue.get()}`); + /// tag::log + check.log(`${topic} changed from ${oldValue.get()} to ${newValue.get()}`); + /// end::log + } + }); + + await session.select('?my//'); + + console.log('Creating my/additional/topic/path'); + await session.topics.add('my/additional/topic/path', specification); + console.log('Creating this/topic/path/will/not/be/picked/up'); + await session.topics.add('this/topic/path/will/not/be/picked/up', specification); + + await session.closeSession(); + /// end::pub_sub_subscribe_fallback_stream[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/pubsub/subscribing/subscribe-multiple-topics.ts b/ts/pubsub/subscribing/subscribe-multiple-topics.ts new file mode 100644 index 00000000..c81c281b --- /dev/null +++ b/ts/pubsub/subscribing/subscribe-multiple-topics.ts @@ -0,0 +1,82 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester } from '../../../../test/util' +/// end::log + +export async function subscribeMultipleTopicExample(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ + 'Subscribed to my/topic/path', + 'Subscribed to my/other/topic/path', + 'Subscribed to my/additional/topic/path' + ], + ['Closed'], + ]); + /// end::log + /// tag::pub_sub_subscribe_multiple_topics_via_selector[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + await session.topics.add('my/topic/path', specification); + await session.topics.add('my/other/topic/path', specification); + + const valueStream = session.addStream('?my//', datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + /// tag::log + check.log(`Unsubscribed from ${topic}: ${reason}`); + /// end::log + }, + /// tag::log + close : () => { + check.log(`Closed`); + }, + /// end::log + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${oldValue.get()} to ${newValue.get()}`); + /// tag::log + check.log(`${topic} changed from ${oldValue.get()} to ${newValue.get()}`); + /// end::log + } + }); + + await session.select('?my//'); + + console.log('Creating my/additional/topic/path'); + await session.topics.add('my/additional/topic/path', specification); + + await session.closeSession(); + /// end::pub_sub_subscribe_multiple_topics_via_selector[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/pubsub/subscribing/subscribe-single-topic.ts b/ts/pubsub/subscribing/subscribe-single-topic.ts new file mode 100644 index 00000000..5c3aef6a --- /dev/null +++ b/ts/pubsub/subscribing/subscribe-single-topic.ts @@ -0,0 +1,92 @@ +/******************************************************************************* + * Copyright (C) 2024 - 2025 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester } from '../../../../test/util' +/// end::log + +export async function subscribeSingleTopicExample(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Subscribed to my/topic/path'], + ['my/topic/path changed from undefined to {"diffusion":"data"}'], + ['my/topic/path changed from {"diffusion":"data"} to {"diffusion":"more data"}'], + ['Closed'], + ]); + /// end::log + /// tag::pub_sub_subscribe_single_topic_via_path[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + await session.topics.add('my/topic/path', specification); + + const valueStream = session.addStream('my/topic/path', datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + /// tag::log + check.log(`Unsubscribed from ${topic}: ${reason}`); + /// end::log + }, + /// tag::log + close : () => { + check.log(`Closed`); + }, + /// end::log + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${JSON.stringify(oldValue?.get())} to ${JSON.stringify(newValue?.get())}`); + /// tag::log + check.log(`${topic} changed from ${JSON.stringify(oldValue?.get())} to ${JSON.stringify(newValue?.get())}`); + /// end::log + } + }); + + await session.select('my/topic/path'); + + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + datatypes.json().from({ "diffusion": "data" }) + ); + + await new Promise(resolve => setTimeout(resolve, 2000)); + + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + datatypes.json().from({ "diffusion": "more data" }) + ); + + await new Promise(resolve => setTimeout(resolve, 2000)); + + await session.closeSession(); + /// end::pub_sub_subscribe_single_topic_via_path[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/pubsub/subscribing/subscribe-topic-selection-scopes.ts b/ts/pubsub/subscribing/subscribe-topic-selection-scopes.ts new file mode 100644 index 00000000..baeafce6 --- /dev/null +++ b/ts/pubsub/subscribing/subscribe-topic-selection-scopes.ts @@ -0,0 +1,128 @@ +/******************************************************************************* + * Copyright (C) 2025 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester } from '../../../../test/util' +/// end::log + +export async function subscribeTopicSelectionScopesExample(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ + 'componentA: Subscribed to my/topic/path', + 'componentB: Subscribed to my/topic/path' + ], + ['componentB: Subscribed to my/other/path'], + [ + 'componentA: Unsubscribed from my/topic/path', + 'componentB: Unsubscribed from my/topic/path', + 'componentB: Unsubscribed from my/other/path' + ] + ]); + /// end::log + /// tag::pub_sub_subscribe_selection_scopes[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + // Create topics 'my/topic/path' and 'my/other/path' + const specification = new topics.TopicSpecification(topics.TopicType.STRING); + await session.topics.add('my/topic/path', specification); + await session.topics.add('my/other/path', specification); + + // each component registers a stream for the topics they are interested in + // and subscribe to the topics with their own scope + + const componentAStream = session.addStream('my/topic/path', datatypes.string()); + const componentBStream = session.addStream('?my//', datatypes.string()); + + componentAStream.on({ + subscribe : (topic, specification) => { + console.log(`componentA: Subscribed to ${topic}`); + /// tag::log + check.log(`componentA: Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`componentA: Unsubscribed from ${topic}`); + /// tag::log + check.log(`componentA: Unsubscribed from ${topic}`); + /// end::log + }, + close : () => { + console.log(`componentA: stream closed`); + }, + value : (topic, spec, newValue, oldValue) => { + console.log(`componentA: ${topic} changed from ${oldValue?.get()} to ${newValue?.get()}`); + } + }); + + componentBStream.on({ + subscribe : (topic, specification) => { + console.log(`componentB: Subscribed to ${topic}`); + /// tag::log + check.log(`componentB: Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`componentB: Unsubscribed from ${topic}`); + /// tag::log + check.log(`componentB: Unsubscribed from ${topic}`); + /// end::log + }, + close : () => { + console.log(`componentB: stream closed`); + }, + value : (topic, spec, newValue, oldValue) => { + console.log(`componentB: ${topic} changed from ${oldValue?.get()} to ${newValue?.get()}`); + } + }); + + await session.selectWithScope('my/topic/path', 'scopeA'); + await session.selectWithScope('my/topic/path', 'scopeB'); + await session.selectWithScope('my/other/path', 'scopeB'); + + const selectionsA = await session.clients.getTopicSelections(session.sessionId); + for (const selection of Object.keys(selectionsA)) { + console.log(`Scope ${selection}: ${selectionsA[selection].map(topic => topic.selector).join(', ')}`); + } + + // componentB unsubscribes from 'my/topic/path', scopeA is unaffected + await session.unsubscribeWithScope('my/topic/path', 'scopeB'); + + const selectionsB = await session.clients.getTopicSelections(session.sessionId); + for (const selection of Object.keys(selectionsB)) { + console.log(`Scope ${selection}: ${selectionsB[selection].map(topic => topic.selector).join(', ')}`); + } + + // componentA unsubscribes from all topics, scopeB is unaffected + // 'my/topic/path' is no longer in any scopes and is unsubscribed for the session + await session.unsubscribeWithScope("?.*//", "scopeA"); + + // a control client unsubscribes all remaining scopes for 'my/other/path' which + // is now unsubscribed for the session + await session.clients.unsubscribeAllScopes(session.sessionId, 'my/other/path'); + + await session.closeSession(); + /// end::pub_sub_subscribe_selection_scopes[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/security/change-principal.ts b/ts/security/change-principal.ts new file mode 100644 index 00000000..9c4cde3a --- /dev/null +++ b/ts/security/change-principal.ts @@ -0,0 +1,33 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; + +export async function changePrincipalExample(): Promise { + /// tag::security_change_principal[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + await session.security.changePrincipal('control', 'password'); + console.log('Principal has been changed to control'); + + await session.closeSession(); + /// end::security_change_principal[] +} diff --git a/ts/security/get-global-permissions.ts b/ts/security/get-global-permissions.ts new file mode 100644 index 00000000..b6f48d84 --- /dev/null +++ b/ts/security/get-global-permissions.ts @@ -0,0 +1,59 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester } from '../../../test/util' +/// end::log + +export async function getGlobalPermissionsExample(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ + 'VIEW_SESSION', + 'MODIFY_SESSION', + 'REGISTER_HANDLER', + 'VIEW_SERVER', + 'CONTROL_SERVER', + 'VIEW_SECURITY', + 'MODIFY_SECURITY', + 'READ_TOPIC_VIEWS', + 'MODIFY_TOPIC_VIEWS' + ] + ]); + /// end::log + /// tag::security_get_global_permissions[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const globalPermissions = await session.security.getGlobalPermissions(); + for (const permission of globalPermissions) { + console.log(permission); + /// tag::log + check.log(permission); + /// end::log + } + + await session.closeSession(); + /// end::security_get_global_permissions[] + /// tag::log + check.done(); + /// end::log +} diff --git a/ts/security/get-path-permissions.ts b/ts/security/get-path-permissions.ts new file mode 100644 index 00000000..220ddd65 --- /dev/null +++ b/ts/security/get-path-permissions.ts @@ -0,0 +1,60 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester } from '../../../test/util' +/// end::log + +export async function getPathPermissionsExample(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ + 'SELECT_TOPIC', + 'READ_TOPIC', + 'UPDATE_TOPIC', + 'MODIFY_TOPIC', + 'SEND_TO_MESSAGE_HANDLER', + 'SEND_TO_SESSION', + 'EDIT_TIME_SERIES_EVENTS', + 'ACQUIRE_LOCK', + 'EXPOSE_BRANCH' + + ] + ]); + /// end::log + /// tag::security_get_path_permissions[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const pathPermissions = await session.security.getPathPermissions('.*//'); + for (const permission of pathPermissions) { + console.log(permission); + /// tag::log + check.log(permission); + /// end::log + } + + await session.closeSession(); + /// end::security_get_path_permissions[] + /// tag::log + check.done(); + /// end::log +} diff --git a/ts/server-configuration/metrics/get-metrics/metrics-console.ts b/ts/server-configuration/metrics/get-metrics/metrics-console.ts new file mode 100644 index 00000000..51655ee1 --- /dev/null +++ b/ts/server-configuration/metrics/get-metrics/metrics-console.ts @@ -0,0 +1,95 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, MetricType } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester } from '../../../../../test/util'; +/// end::log + +export async function metricsRequestMetricsConsole(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ + 'diffusion_license: diffusion_license (INFO)', + 'diffusion_multiplexer_manager_number_of_multiplexers: diffusion_multiplexer_manager_number_of_multiplexers (GAUGE)', + 'diffusion_release: diffusion_release (INFO)', + 'diffusion_server_free_memory_bytes: diffusion_server_free_memory_bytes bytes (GAUGE)', + 'diffusion_server_license_expiry_date: diffusion_server_license_expiry_date (INFO)', + 'diffusion_server_max_memory_bytes: diffusion_server_max_memory_bytes bytes (GAUGE)', + 'diffusion_server_number_of_topics: diffusion_server_number_of_topics (GAUGE)', + 'diffusion_server_session_locks: diffusion_server_session_locks (INFO)', + 'diffusion_server_start_date: diffusion_server_start_date (INFO)', + 'diffusion_server_start_date_millis: diffusion_server_start_date_millis millis (GAUGE)', + 'diffusion_server_time_zone: diffusion_server_time_zone (INFO)', + 'diffusion_server_total_memory_bytes: diffusion_server_total_memory_bytes bytes (GAUGE)', + 'diffusion_server_uptime: diffusion_server_uptime (INFO)', + 'diffusion_server_uptime_millis: diffusion_server_uptime_millis millis (GAUGE)', + 'diffusion_server_used_physical_memory_size_bytes: diffusion_server_used_physical_memory_size_bytes bytes (GAUGE)', + 'diffusion_server_used_swap_space_size_bytes: diffusion_server_used_swap_space_size_bytes bytes (GAUGE)', + 'diffusion_server_user_directory: diffusion_server_user_directory (INFO)', + 'diffusion_server_user_name: diffusion_server_user_name (INFO)' + ], + ]); + /// end::log + /// tag::metrics_get_metrics_console[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const metricsResult = await session.metrics.metricsRequest() + .filter([ + 'diffusion_server_time_zone', + 'diffusion_server_user_directory', + 'diffusion_server_license_expiry_date', + 'diffusion_server_uptime_millis', + 'diffusion_license', + 'diffusion_server_free_memory_bytes', + 'diffusion_server_max_memory_bytes', + 'diffusion_server_total_memory_bytes', + 'diffusion_release', + 'diffusion_server_start_date', + 'diffusion_server_start_date_millis', + 'diffusion_server_used_swap_space_size_bytes', + 'diffusion_server_used_physical_memory_size_bytes', + 'diffusion_server_number_of_topics', + 'diffusion_server_session_locks', + 'diffusion_server_user_name', + 'diffusion_server_uptime', + 'diffusion_multiplexer_manager_number_of_multiplexers' + ]) + .currentServer() + .fetch(); + + const servers = metricsResult.getServerNames(); + /// tag::log + expect(servers.size).toBe(1); + /// end::log + const collections = metricsResult.getMetrics([...servers.values()][0]); + for (const collection of collections) { + for (const sample of collection.samples) { + console.log(`${collection.name}: ${sample.value} ${collection.unit} (${MetricType[collection.type]})`); + /// tag::log + check.log(`${collection.name}: ${sample.name} ${collection.unit} (${MetricType[collection.type]})`); + /// end::log + } + } + + await session.closeSession(); + /// end::metrics_get_metrics_console[] +} diff --git a/ts/server-configuration/metrics/get-metrics/outbound-bytes.ts b/ts/server-configuration/metrics/get-metrics/outbound-bytes.ts new file mode 100644 index 00000000..ec570418 --- /dev/null +++ b/ts/server-configuration/metrics/get-metrics/outbound-bytes.ts @@ -0,0 +1,46 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; + +export async function metricsGetOutboundBytes(): Promise { + /// tag::metrics_get_metrics_outbound_bytes[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const metricsResult = await session.metrics.metricsRequest() + .filter('diffusion_network_outbound_bytes') + .currentServer() + .fetch(); + + const servers = metricsResult.getServerNames(); + /// tag::log + expect(servers.size).toBe(1); + /// end::log + const collections = metricsResult.getMetrics([...servers.values()][0]); + /// tag::log + expect(collections[0].samples.length).toBe(1); + /// end::log + const sample = collections[0].samples[0]; + console.log(`${collections[0].name}: ${sample.value} ${collections[0].unit} (${collections[0].type})`); + + await session.closeSession(); + /// end::metrics_get_metrics_outbound_bytes[] +} diff --git a/ts/server-configuration/metrics/session-metric-collector/list-session-metric-collectors.ts b/ts/server-configuration/metrics/session-metric-collector/list-session-metric-collectors.ts new file mode 100644 index 00000000..60c430c6 --- /dev/null +++ b/ts/server-configuration/metrics/session-metric-collector/list-session-metric-collectors.ts @@ -0,0 +1,60 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, newSessionMetricCollectorBuilder } from 'diffusion'; + +export async function metricsListSessionMetricCollectors(): Promise { + /// tag::metrics_session_metric_collector_list[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const sessionMetricCollector1 = newSessionMetricCollectorBuilder() + .exportToPrometheus(false) + .maximumGroups(10) + .removeMetricsWithNoMatches(true) + .groupByProperty('$Location') + .create('Session Metric Collector 1', '$Principal is "control"'); + const sessionMetricCollector2 = newSessionMetricCollectorBuilder() + .exportToPrometheus(true) + .maximumGroups(250) + .removeMetricsWithNoMatches(true) + .groupByProperty('$Location') + .create('Session Metric Collector 2', '$Principal is "control"'); + await Promise.all([ + session.metrics.putSessionMetricCollector(sessionMetricCollector1), + session.metrics.putSessionMetricCollector(sessionMetricCollector2) + ]); + + const sessionMetricCollectors = await session.metrics.listSessionMetricCollectors(); + for (const collector of sessionMetricCollectors.collectors) { + console.log(`${collector.name}: ${collector.sessionFilter} (${collector.maximumGroups}, ` + + `${collector.exportToPrometheus}, ${collector.removeMetricsWithNoMatches}, ` + + `[${collector.groupByProperties.join(', ')}])`); + } + /// tag::log + expect(sessionMetricCollectors.collectors.length).toBe(2); + expect(sessionMetricCollectors.collectors.map((c) => c.name)).toEqual(jasmine.arrayContaining( + ['Session Metric Collector 1', 'Session Metric Collector 2'] + )); + /// end::log + + await session.closeSession(); + /// end::metrics_session_metric_collector_list[] +} diff --git a/ts/server-configuration/metrics/session-metric-collector/put-session-metric-collector.ts b/ts/server-configuration/metrics/session-metric-collector/put-session-metric-collector.ts new file mode 100644 index 00000000..9b40191f --- /dev/null +++ b/ts/server-configuration/metrics/session-metric-collector/put-session-metric-collector.ts @@ -0,0 +1,43 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, newSessionMetricCollectorBuilder } from 'diffusion'; + +export async function metricsPutSessionMetricCollector(): Promise { + /// tag::metrics_session_metric_collector_put[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const sessionMetricCollector = newSessionMetricCollectorBuilder() + .exportToPrometheus(false) + .maximumGroups(10) + .removeMetricsWithNoMatches(true) + .groupByProperty('$Location') + .create('Session Metric Collector 1', '$Principal is "control"'); + await session.metrics.putSessionMetricCollector(sessionMetricCollector); + /// tag::log + const sessionMetricCollectors = await session.metrics.listSessionMetricCollectors(); + expect(sessionMetricCollectors.collectors.length).toBe(1); + expect(sessionMetricCollectors.collectors[0].name).toBe('Session Metric Collector 1'); + /// end::log + + await session.closeSession(); + /// end::metrics_session_metric_collector_put[] +} diff --git a/ts/server-configuration/metrics/session-metric-collector/remove-session-metric-collector.ts b/ts/server-configuration/metrics/session-metric-collector/remove-session-metric-collector.ts new file mode 100644 index 00000000..e9b37c58 --- /dev/null +++ b/ts/server-configuration/metrics/session-metric-collector/remove-session-metric-collector.ts @@ -0,0 +1,49 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, newSessionMetricCollectorBuilder } from 'diffusion'; + +export async function metricsRemoveSessionMetricCollector(): Promise { + /// tag::metrics_session_metric_collector_remove[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const sessionMetricCollector = newSessionMetricCollectorBuilder() + .exportToPrometheus(false) + .maximumGroups(10) + .removeMetricsWithNoMatches(true) + .groupByProperty('$Location') + .create('Session Metric Collector 1', '$Principal is "control"'); + await session.metrics.putSessionMetricCollector(sessionMetricCollector); + /// tag::log + const sessionMetricCollectors1 = await session.metrics.listSessionMetricCollectors(); + expect(sessionMetricCollectors1.collectors.length).toBe(1); + expect(sessionMetricCollectors1.collectors[0].name).toBe('Session Metric Collector 1'); + /// end::log + + await session.metrics.removeSessionMetricCollector('Session Metric Collector 1'); + /// tag::log + const sessionMetricCollectors2 = await session.metrics.listSessionMetricCollectors(); + expect(sessionMetricCollectors2.collectors.length).toBe(0); + /// end::log + + await session.closeSession(); + /// end::metrics_session_metric_collector_remove[] +} diff --git a/ts/server-configuration/metrics/topic-metric-collector/list-topic-metric-collectors.ts b/ts/server-configuration/metrics/topic-metric-collector/list-topic-metric-collectors.ts new file mode 100644 index 00000000..bd3c28e4 --- /dev/null +++ b/ts/server-configuration/metrics/topic-metric-collector/list-topic-metric-collectors.ts @@ -0,0 +1,61 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, newTopicMetricCollectorBuilder } from 'diffusion'; + +export async function metricsListTopicMetricCollectors(): Promise { + /// tag::metrics_topic_metric_collector_list[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const topicMetricCollector1 = newTopicMetricCollectorBuilder() + .exportToPrometheus(false) + .maximumGroups(10) + .groupByTopicType(true) + .groupByTopicView(true) + .groupByPathPrefixParts(15) + .create('Topic Metric Collector 1', '?my/topic//'); + const topicMetricCollector2 = newTopicMetricCollectorBuilder() + .exportToPrometheus(false) + .maximumGroups(10) + .groupByTopicType(true) + .groupByTopicView(true) + .groupByPathPrefixParts(15) + .create('Topic Metric Collector 2', '?my/topic//'); + await Promise.all([ + session.metrics.putTopicMetricCollector(topicMetricCollector1), + session.metrics.putTopicMetricCollector(topicMetricCollector2) + ]); + + const topicMetricCollectors = await session.metrics.listTopicMetricCollectors(); + for (const collector of topicMetricCollectors.collectors) { + console.log(`${collector.name}: ${collector.topicSelector} (${collector.maximumGroups}, ` + + `${collector.exportToPrometheus}, ${collector.groupByTopicType}, ${collector.groupByTopicView}, ${collector.groupByPathPrefixParts})`); + } + /// tag::log + expect(topicMetricCollectors.collectors.length).toBe(2); + expect(topicMetricCollectors.collectors.map((c) => c.name)).toEqual(jasmine.arrayContaining( + ['Topic Metric Collector 1', 'Topic Metric Collector 2'] + )); + /// end::log + + await session.closeSession(); + /// end::metrics_topic_metric_collector_list[] +} diff --git a/ts/server-configuration/metrics/topic-metric-collector/put-topic-metric-collector.ts b/ts/server-configuration/metrics/topic-metric-collector/put-topic-metric-collector.ts new file mode 100644 index 00000000..aea86be3 --- /dev/null +++ b/ts/server-configuration/metrics/topic-metric-collector/put-topic-metric-collector.ts @@ -0,0 +1,44 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, newTopicMetricCollectorBuilder } from 'diffusion'; + +export async function metricsPutTopicMetricCollector(): Promise { + /// tag::metrics_topic_metric_collector_put[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const topicMetricCollector = newTopicMetricCollectorBuilder() + .exportToPrometheus(false) + .maximumGroups(10) + .groupByTopicType(true) + .groupByTopicView(true) + .groupByPathPrefixParts(15) + .create('Topic Metric Collector 1', '?my/topic//'); + await session.metrics.putTopicMetricCollector(topicMetricCollector); + /// tag::log + const topicMetricCollectors = await session.metrics.listTopicMetricCollectors(); + expect(topicMetricCollectors.collectors.length).toBe(1); + expect(topicMetricCollectors.collectors[0].name).toBe('Topic Metric Collector 1'); + /// end::log + + await session.closeSession(); + /// end::metrics_topic_metric_collector_put[] +} diff --git a/ts/server-configuration/metrics/topic-metric-collector/remove-topic-metric-collector.ts b/ts/server-configuration/metrics/topic-metric-collector/remove-topic-metric-collector.ts new file mode 100644 index 00000000..424fa989 --- /dev/null +++ b/ts/server-configuration/metrics/topic-metric-collector/remove-topic-metric-collector.ts @@ -0,0 +1,50 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, newTopicMetricCollectorBuilder } from 'diffusion'; + +export async function metricsRemoveTopicMetricCollector(): Promise { + /// tag::metrics_topic_metric_collector_remove[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const topicMetricCollector = newTopicMetricCollectorBuilder() + .exportToPrometheus(false) + .maximumGroups(10) + .groupByTopicType(true) + .groupByTopicView(true) + .groupByPathPrefixParts(15) + .create('Topic Metric Collector 1', '?my/topic//'); + await session.metrics.putTopicMetricCollector(topicMetricCollector); + /// tag::log + const topicMetricCollectors1 = await session.metrics.listTopicMetricCollectors(); + expect(topicMetricCollectors1.collectors.length).toBe(1); + expect(topicMetricCollectors1.collectors[0].name).toBe('Topic Metric Collector 1'); + /// end::log + + await session.metrics.removeTopicMetricCollector('Topic Metric Collector 1'); + /// tag::log + const topicMetricCollectors2 = await session.metrics.listTopicMetricCollectors(); + expect(topicMetricCollectors2.collectors.length).toBe(0); + /// end::log + + await session.closeSession(); + /// end::metrics_topic_metric_collector_remove[] +} diff --git a/ts/server-configuration/remote-servers/check-remote-server.ts b/ts/server-configuration/remote-servers/check-remote-server.ts new file mode 100644 index 00000000..eac2ed4f --- /dev/null +++ b/ts/server-configuration/remote-servers/check-remote-server.ts @@ -0,0 +1,103 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { + connect, + ConnectionOption, + ConnectionState, + newRemoteServerBuilder, + RemoteServerType, + SecondaryInitiatorDefinition, +} from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester } from '../../../../test/util'; +/// end::log + +export async function remoteServersCheck(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Remote Server 1 (ws://new.server.url.com): connection failed (Feature \'REMOTE_CONNECTIONS\' is not licensed.)', + 'Remote Server 2 (ws://another.server.url.com): connection failed (Feature \'REMOTE_CONNECTIONS\' is not licensed.)' + ]]); + /// end::log + /// tag::remote_servers_check[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const builder = newRemoteServerBuilder(RemoteServerType.SECONDARY_INITIATOR) + .principal('admin') + .credentials('password') + .connectionOptions({ + [ConnectionOption.RECONNECTION_TIMEOUT] : '120000', + [ConnectionOption.MAXIMUM_QUEUE_SIZE]: '1000', + [ConnectionOption.CONNECTION_TIMEOUT]: '15000' + }) + .missingTopicNotificationFilter('?abc'); + await session.remoteServers.createRemoteServer( + builder.build('Remote Server 1', 'ws://new.server.url.com') + ); + builder.reset() + .principal('control') + .credentials('password') + .connectionOptions({ + [ConnectionOption.RECONNECTION_TIMEOUT] : '60000', + [ConnectionOption.MAXIMUM_QUEUE_SIZE]: '10000', + [ConnectionOption.CONNECTION_TIMEOUT]: '5000' + }); + await session.remoteServers.createRemoteServer( + builder.build('Remote Server 2', 'ws://another.server.url.com') + ); + + const remoteServers = await session.remoteServers.listRemoteServers(); + for (const remoteServer of remoteServers as SecondaryInitiatorDefinition[]) { + const status = await session.remoteServers.checkRemoteServer(remoteServer.name); + let statusMessage = ''; + switch (status.connectionState) { + case ConnectionState.INACTIVE: + statusMessage = 'inactive'; + break; + case ConnectionState.CONNECTED: + statusMessage = 'connected'; + break; + case ConnectionState.MISSING: + statusMessage = 'missing'; + break; + case ConnectionState.FAILED: + statusMessage = `connection failed (${status.failureMessage})`; + break; + case ConnectionState.RETRYING: + statusMessage = `retrying (${status.failureMessage})`; + break; + } + console.log(`${remoteServer.name} (${remoteServer.url}): ${statusMessage}`); + /// tag::log + check.log(`${remoteServer.name} (${remoteServer.url}): ${statusMessage}`); + /// end::log + } + + // Clean up + await session.remoteServers.removeRemoteServer('Remote Server 1'); + await session.remoteServers.removeRemoteServer('Remote Server 2'); + await session.closeSession(); + /// end::remote_servers_check[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/server-configuration/remote-servers/create-primary-initiator.ts b/ts/server-configuration/remote-servers/create-primary-initiator.ts new file mode 100644 index 00000000..dc078e52 --- /dev/null +++ b/ts/server-configuration/remote-servers/create-primary-initiator.ts @@ -0,0 +1,51 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { + connect, + newRemoteServerBuilder, + RemoteServerType, + PrimaryInitiatorDefinition +} from 'diffusion'; + +export async function remoteServersCreatePrimaryInitiator(): Promise { + /// tag::remote_servers_create_primary_initiator[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const definition = newRemoteServerBuilder(RemoteServerType.PRIMARY_INITIATOR) + .retryDelay(2500) + .build( + 'Remote Server 1', + ['ws://new.server.url.com:8080', 'ws://new.server.url.com:8081', 'ws://new.server.url.com:8082'], + 'High Volume Connector' + ); + await session.remoteServers.createRemoteServer(definition); + /// tag::log + const remoteServers = await session.remoteServers.listRemoteServers(); + expect(remoteServers.length).toBe(1); + expect(remoteServers[0].name).toBe('Remote Server 1'); + /// end::log + + // Clean up + await session.remoteServers.removeRemoteServer('Remote Server 1'); + await session.closeSession(); + /// end::remote_servers_create_primary_initiator[] +} diff --git a/ts/server-configuration/remote-servers/create-secondary-acceptor.ts b/ts/server-configuration/remote-servers/create-secondary-acceptor.ts new file mode 100644 index 00000000..f3ea643b --- /dev/null +++ b/ts/server-configuration/remote-servers/create-secondary-acceptor.ts @@ -0,0 +1,54 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { + connect, + ConnectionOption, + newRemoteServerBuilder, + RemoteServerType, +} from 'diffusion'; + +export async function remoteServersCreateSecondaryAcceptor(): Promise { + /// tag::remote_servers_create_secondary_acceptor[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const definition = newRemoteServerBuilder(RemoteServerType.SECONDARY_ACCEPTOR) + .principal('') + .credentials(null) + .connectionOptions({ + [ConnectionOption.WRITE_TIMEOUT] : '2000', + [ConnectionOption.MAXIMUM_QUEUE_SIZE]: '1000', + [ConnectionOption.CONNECTION_TIMEOUT]: '15000' + }) + .missingTopicNotificationFilter('?abc') + .build('Remote Server 1', 'ws://new.server.url.com'); + await session.remoteServers.createRemoteServer(definition); + /// tag::log + const remoteServers = await session.remoteServers.listRemoteServers(); + expect(remoteServers.length).toBe(1); + expect(remoteServers[0].name).toBe('Remote Server 1'); + /// end::log + + // Clean up + await session.remoteServers.removeRemoteServer('Remote Server 1'); + await session.closeSession(); + /// end::remote_servers_create_secondary_acceptor[] +} diff --git a/ts/server-configuration/remote-servers/create-secondary-initiator.ts b/ts/server-configuration/remote-servers/create-secondary-initiator.ts new file mode 100644 index 00000000..08c371a6 --- /dev/null +++ b/ts/server-configuration/remote-servers/create-secondary-initiator.ts @@ -0,0 +1,54 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { + connect, + ConnectionOption, + newRemoteServerBuilder, + RemoteServerType, +} from 'diffusion'; + +export async function remoteServersCreateSecondaryInitiator(): Promise { + /// tag::remote_servers_create_secondary_initiator[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const definition = newRemoteServerBuilder(RemoteServerType.SECONDARY_INITIATOR) + .principal('admin') + .credentials('password') + .connectionOptions({ + [ConnectionOption.RECONNECTION_TIMEOUT] : '120000', + [ConnectionOption.MAXIMUM_QUEUE_SIZE]: '1000', + [ConnectionOption.CONNECTION_TIMEOUT]: '15000' + }) + .missingTopicNotificationFilter('?abc') + .build('Remote Server 1', 'ws://new.server.url.com'); + await session.remoteServers.createRemoteServer(definition); + /// tag::log + const remoteServers = await session.remoteServers.listRemoteServers(); + expect(remoteServers.length).toBe(1); + expect(remoteServers[0].name).toBe('Remote Server 1'); + /// end::log + + // Clean up + await session.remoteServers.removeRemoteServer('Remote Server 1'); + await session.closeSession(); + /// end::remote_servers_create_secondary_initiator[] +} diff --git a/ts/server-configuration/remote-servers/list-remote-servers.ts b/ts/server-configuration/remote-servers/list-remote-servers.ts new file mode 100644 index 00000000..cfe3ce87 --- /dev/null +++ b/ts/server-configuration/remote-servers/list-remote-servers.ts @@ -0,0 +1,83 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { + connect, + ConnectionOption, + newRemoteServerBuilder, + RemoteServerType, + SecondaryInitiatorDefinition, +} from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester } from '../../../../test/util'; +/// end::log + +export async function remoteServersList(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Remote Server 1 (ws://new.server.url.com)', + 'Remote Server 2 (ws://another.server.url.com)' + ]]); + /// end::log + /// tag::remote_servers_list[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const builder = newRemoteServerBuilder(RemoteServerType.SECONDARY_INITIATOR) + .principal('admin') + .credentials('password') + .connectionOptions({ + [ConnectionOption.RECONNECTION_TIMEOUT] : '120000', + [ConnectionOption.MAXIMUM_QUEUE_SIZE]: '1000', + [ConnectionOption.CONNECTION_TIMEOUT]: '15000' + }) + .missingTopicNotificationFilter('?abc'); + await session.remoteServers.createRemoteServer( + builder.build('Remote Server 1', 'ws://new.server.url.com') + ); + builder.reset() + .principal('control') + .credentials('password') + .connectionOptions({ + [ConnectionOption.RECONNECTION_TIMEOUT] : '6000', + [ConnectionOption.MAXIMUM_QUEUE_SIZE]: '10000', + [ConnectionOption.CONNECTION_TIMEOUT]: '5000' + }); + await session.remoteServers.createRemoteServer( + builder.build('Remote Server 2', 'ws://another.server.url.com') + ); + + const remoteServers = await session.remoteServers.listRemoteServers(); + for (const remoteServer of remoteServers as SecondaryInitiatorDefinition[]) { + console.log(`${remoteServer.name} (${remoteServer.url})`); + /// tag::log + check.log(`${remoteServer.name} (${remoteServer.url})`); + /// end::log + } + + // Clean up + await session.remoteServers.removeRemoteServer('Remote Server 1'); + await session.remoteServers.removeRemoteServer('Remote Server 2'); + await session.closeSession(); + /// end::remote_servers_list[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/server-configuration/remote-servers/remove-remote-server.ts b/ts/server-configuration/remote-servers/remove-remote-server.ts new file mode 100644 index 00000000..0e0a2ca1 --- /dev/null +++ b/ts/server-configuration/remote-servers/remove-remote-server.ts @@ -0,0 +1,58 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { + connect, + ConnectionOption, + newRemoteServerBuilder, + RemoteServerType, +} from 'diffusion'; + +export async function remoteServersRemove(): Promise { + /// tag::remote_servers_remove[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const definition = newRemoteServerBuilder(RemoteServerType.SECONDARY_INITIATOR) + .principal('admin') + .credentials('password') + .connectionOptions({ + [ConnectionOption.RECONNECTION_TIMEOUT] : '120000', + [ConnectionOption.MAXIMUM_QUEUE_SIZE]: '1000', + [ConnectionOption.CONNECTION_TIMEOUT]: '15000' + }) + .missingTopicNotificationFilter('?abc') + .build('Remote Server 1', 'ws://new.server.url.com'); + await session.remoteServers.createRemoteServer(definition); + /// tag::log + const remoteServers1 = await session.remoteServers.listRemoteServers(); + expect(remoteServers1.length).toBe(1); + expect(remoteServers1[0].name).toBe('Remote Server 1'); + /// end::log + + await session.remoteServers.removeRemoteServer('Remote Server 1'); + /// tag::log + const remoteServers2 = await session.remoteServers.listRemoteServers(); + expect(remoteServers2.length).toBe(0); + /// end::log + + await session.closeSession(); + /// end::remote_servers_remove[] +} diff --git a/ts/server-configuration/security-control/define-roles-hierarchy.ts b/ts/server-configuration/security-control/define-roles-hierarchy.ts new file mode 100644 index 00000000..8d16bfe2 --- /dev/null +++ b/ts/server-configuration/security-control/define-roles-hierarchy.ts @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; + +export async function securityControlDefineRolesHierarchy(): Promise { + /// tag::security_control_define_roles_hierarchy[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const securityScript = session.security.securityScriptBuilder() + .setRoleIncludes('OPERATOR', [ 'CLIENT', 'CLIENT_CONTROL' ]) + .build(); + console.log('OPERATOR now includes CLIENT and CLIENT_CONTROL roles.'); + console.log(securityScript); + await session.security.updateSecurityStore(securityScript); + + // Clean up + const securityScriptCleanup = session.security.securityScriptBuilder() + .setRoleIncludes('OPERATOR', [ 'CLIENT' ]) + .build(); + await session.security.updateSecurityStore(securityScriptCleanup); + await session.closeSession(); + /// end::security_control_define_roles_hierarchy[] +} diff --git a/ts/server-configuration/security-control/deisolate-path.ts b/ts/server-configuration/security-control/deisolate-path.ts new file mode 100644 index 00000000..f7ccfc4d --- /dev/null +++ b/ts/server-configuration/security-control/deisolate-path.ts @@ -0,0 +1,44 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; + +export async function securityControlDeisolatePath(): Promise { + /// tag::security_control_deisolate_path[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const securityScript1 = session.security.securityScriptBuilder() + .isolatePath('my/topic/path') + .build(); + console.log('Isolating my/topic/path permissions from parent and default path permissions.'); + console.log(securityScript1); + await session.security.updateSecurityStore(securityScript1); + + const securityScript2 = session.security.securityScriptBuilder() + .deisolatePath('my/topic/path') + .build(); + console.log('Removing my/topic/path permission isolation.'); + console.log(securityScript2); + await session.security.updateSecurityStore(securityScript2); + + await session.closeSession(); + /// end::security_control_deisolate_path[] +} diff --git a/ts/server-configuration/security-control/isolate-path.ts b/ts/server-configuration/security-control/isolate-path.ts new file mode 100644 index 00000000..6624378f --- /dev/null +++ b/ts/server-configuration/security-control/isolate-path.ts @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; + +export async function securityControlIsolatePath(): Promise { + /// tag::security_control_isolate_path[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const securityScript = session.security.securityScriptBuilder() + .isolatePath('my/topic/path') + .build(); + console.log('Isolating my/topic/path permissions from parent and default path permissions.'); + console.log(securityScript); + await session.security.updateSecurityStore(securityScript); + + // Clean up + const securityScriptCleanup = session.security.securityScriptBuilder() + .deisolatePath('my/topic/path') + .build(); + await session.security.updateSecurityStore(securityScriptCleanup); + await session.closeSession(); + /// end::security_control_isolate_path[] +} diff --git a/ts/server-configuration/security-control/remove-path-permissions.ts b/ts/server-configuration/security-control/remove-path-permissions.ts new file mode 100644 index 00000000..4321e958 --- /dev/null +++ b/ts/server-configuration/security-control/remove-path-permissions.ts @@ -0,0 +1,44 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; + +export async function securityControlRemovePathPermissions(): Promise { + /// tag::security_control_remove_path_permissions[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const securityScript1 = session.security.securityScriptBuilder() + .setPathPermissions('CLIENT','my/topic/path', [ 'UPDATE_TOPIC', 'MODIFY_TOPIC' ]) + .build(); + console.log('Allowing Role CLIENT to update and modify my/topic/path.'); + console.log(securityScript1); + await session.security.updateSecurityStore(securityScript1); + + const securityScript2 = session.security.securityScriptBuilder() + .removePathPermissions('CLIENT','my/topic/path') + .build(); + console.log('Removing path permissions for Role CLIENT at my/topic/path.'); + console.log(securityScript2); + await session.security.updateSecurityStore(securityScript2); + + await session.closeSession(); + /// end::security_control_remove_path_permissions[] +} diff --git a/ts/server-configuration/security-control/restrict-role.ts b/ts/server-configuration/security-control/restrict-role.ts new file mode 100644 index 00000000..7bbec5e6 --- /dev/null +++ b/ts/server-configuration/security-control/restrict-role.ts @@ -0,0 +1,43 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; + +export async function securityControlRestrictRole(): Promise { + /// tag::security_control_restrict_role_edit_permissions[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const securityScript = session.security.securityScriptBuilder() + .setRoleLockedByPrincipal('EXAMPLE', 'admin') + .build(); + console.log('EXAMPLE role has been locked by admin principal.'); + console.log(securityScript); + await session.security.updateSecurityStore(securityScript); + + // Clean up + const securityScriptCleanup = session.security.authenticationScriptBuilder() + .removePrincipal('admin') + .addPrincipal('admin', 'password', ['ADMINISTRATOR']) + .build(); + await session.security.updateAuthenticationStore(securityScriptCleanup); + await session.closeSession(); + /// end::security_control_restrict_role_edit_permissions[] +} diff --git a/ts/server-configuration/security-control/set-default-path-permissions.ts b/ts/server-configuration/security-control/set-default-path-permissions.ts new file mode 100644 index 00000000..7529db30 --- /dev/null +++ b/ts/server-configuration/security-control/set-default-path-permissions.ts @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; + +export async function securityControlSetDefaultPathPermissions(): Promise { + /// tag::security_control_set_default_path_permissions[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const securityScript = session.security.securityScriptBuilder() + .setDefaultPathPermissions('CLIENT', [ 'UPDATE_TOPIC', 'MODIFY_TOPIC' ]) + .build(); + console.log('Adding the following permissions to the default path permisions of Role CLIENT: MODIFY_TOPIC and UPDATE_TOPIC'); + console.log(securityScript); + await session.security.updateSecurityStore(securityScript); + + // Clean up + const securityScriptCleanup = session.security.securityScriptBuilder() + .setDefaultPathPermissions('CLIENT', [ 'SELECT_TOPIC', 'READ_TOPIC', 'SEND_TO_MESSAGE_HANDLER' ]) + .build(); + await session.security.updateSecurityStore(securityScriptCleanup); + await session.closeSession(); + /// end::security_control_set_default_path_permissions[] +} diff --git a/ts/server-configuration/security-control/set-default-roles-for-anonymous-sessions.ts b/ts/server-configuration/security-control/set-default-roles-for-anonymous-sessions.ts new file mode 100644 index 00000000..24a8e197 --- /dev/null +++ b/ts/server-configuration/security-control/set-default-roles-for-anonymous-sessions.ts @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; + +export async function securityControlSetDefaultRolesForAnonymousSessions(): Promise { + /// tag::security_control_set_default_roles_for_anonymous_sessions[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const securityScript = session.security.securityScriptBuilder() + .setRolesForAnonymousSessions([ 'AUTHENTICATION_HANDLER' ]) + .build(); + console.log('All anonymous sessions now have AUTHENTICATION_HANDLER priviledges.'); + console.log(securityScript); + await session.security.updateSecurityStore(securityScript); + + // Clean up + const securityScriptCleanup = session.security.securityScriptBuilder() + .setRolesForAnonymousSessions([ 'CLIENT' ]) + .build(); + await session.security.updateSecurityStore(securityScriptCleanup); + await session.closeSession(); + /// end::security_control_set_default_roles_for_anonymous_sessions[] +} diff --git a/ts/server-configuration/security-control/set-default-roles-for-named-sessions.ts b/ts/server-configuration/security-control/set-default-roles-for-named-sessions.ts new file mode 100644 index 00000000..f2a0049a --- /dev/null +++ b/ts/server-configuration/security-control/set-default-roles-for-named-sessions.ts @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; + +export async function securityControlSetDefaultRolesForNamedSessions(): Promise { + /// tag::security_control_set_default_roles_for_named_sessions[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const securityScript = session.security.securityScriptBuilder() + .setRolesForNamedSessions([ 'ADMINISTRATOR' ]) + .build(); + console.log('All named sessions now have ADMINISTRATOR priviledges.'); + console.log(securityScript); + await session.security.updateSecurityStore(securityScript); + + // Clean up + const securityScriptCleanup = session.security.securityScriptBuilder() + .setRolesForNamedSessions([ 'CLIENT' ]) + .build(); + await session.security.updateSecurityStore(securityScriptCleanup); + await session.closeSession(); + /// end::security_control_set_default_roles_for_named_sessions[] +} diff --git a/ts/server-configuration/security-control/set-global-permissions.ts b/ts/server-configuration/security-control/set-global-permissions.ts new file mode 100644 index 00000000..e9a8534d --- /dev/null +++ b/ts/server-configuration/security-control/set-global-permissions.ts @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; + +export async function securityControlSetGlobalPermissions(): Promise { + /// tag::security_control_set_global_permissions[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const securityScript = session.security.securityScriptBuilder() + .setGlobalPermissions('CLIENT', [ 'VIEW_SERVER', 'VIEW_SESSION' ]) + .build(); + console.log('Adding the following permissions to the global permissions of Role CLIENT: VIEW_SERVER and VIEW_SESSION'); + console.log(securityScript); + await session.security.updateSecurityStore(securityScript); + + // Clean up + const securityScriptCleanup = session.security.securityScriptBuilder() + .setGlobalPermissions('CLIENT', []) + .build(); + await session.security.updateSecurityStore(securityScriptCleanup); + await session.closeSession(); + /// end::security_control_set_global_permissions[] +} diff --git a/ts/server-configuration/security-control/set-path-permissions.ts b/ts/server-configuration/security-control/set-path-permissions.ts new file mode 100644 index 00000000..6fce5c0d --- /dev/null +++ b/ts/server-configuration/security-control/set-path-permissions.ts @@ -0,0 +1,46 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { + connect, + SecurityScriptBuilder, + Session, +} from 'diffusion'; + +export async function securityControlSetPathPermissions(): Promise { + /// tag::security_control_set_path_permissions[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const securityScript = session.security.securityScriptBuilder() + .setPathPermissions('CLIENT','my/topic/path', [ 'UPDATE_TOPIC', 'MODIFY_TOPIC' ]) + .build(); + console.log('Allowing Role CLIENT to update and modify my/topic/path.'); + console.log(securityScript); + await session.security.updateSecurityStore(securityScript); + + // Clean up + const securityScriptCleanup = session.security.securityScriptBuilder() + .removePathPermissions('CLIENT', 'my/topic/path') + .build(); + await session.security.updateSecurityStore(securityScriptCleanup); + await session.closeSession(); + /// end::security_control_set_path_permissions[] +} diff --git a/ts/server-configuration/system-authentication-control/abstain-anonymous-connections.ts b/ts/server-configuration/system-authentication-control/abstain-anonymous-connections.ts new file mode 100644 index 00000000..97456925 --- /dev/null +++ b/ts/server-configuration/system-authentication-control/abstain-anonymous-connections.ts @@ -0,0 +1,89 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { + Authenticator, + AuthenticatorCallback, + connect, + Credentials, + Session, + SessionProperties +} from 'diffusion'; + +export async function abstainAnonymousConnections(): Promise { + /// tag::system_authentication_control_abstain_anonymous_connections[] + // Connect to the server. + const session1 = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const authenticationScript = session1.security.authenticationScriptBuilder() + .abstainAnonymousConnections() + .build(); + await session1.security.updateAuthenticationStore(authenticationScript); + + const session2 = await connect({ + host: 'localhost', + port: 8080, + principal: 'control', + credentials: 'password' + }); + const authenticator: Authenticator = { + authenticate: ( + principal: string, + credentials: Credentials, + sessionProperties: SessionProperties, + proposedPorperties: SessionProperties, + callback: AuthenticatorCallback + ) => { + if (credentials === null) { + callback.deny(); + } else { + callback.allow(); + } + }, + onClose: () => {}, + onError: () => {} + }; + + await session2.security.setAuthenticator('after-system-handler', authenticator); + + try { + await connect({ + host: 'localhost', + port: 8080 + }); + /// tag::log + fail('Anonymous connection should be denied'); + /// end::log + } + catch (err) { + // expected to fail + console.error('Could not connect', err.message); + } + + /// tag::log + const restoreScript = session1.security.authenticationScriptBuilder() + .allowAnonymousConnections(['CLIENT']) + .build(); + await session1.security.updateAuthenticationStore(restoreScript); + /// end::log + await session1.closeSession(); + await session2.closeSession(); + /// end::system_authentication_control_abstain_anonymous_connections[] +} diff --git a/ts/server-configuration/system-authentication-control/add-locked-principal.ts b/ts/server-configuration/system-authentication-control/add-locked-principal.ts new file mode 100644 index 00000000..d683b32e --- /dev/null +++ b/ts/server-configuration/system-authentication-control/add-locked-principal.ts @@ -0,0 +1,41 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; + +export async function addLockedPrincipal(): Promise { + /// tag::system_authentication_control_add_locked_principal[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const authenticationScript = session.security.authenticationScriptBuilder() + .addPrincipal('super_user', 'password12345', [ 'ADMINISTRATOR' ], 'admin') + .build(); + await session.security.updateAuthenticationStore(authenticationScript); + + /// tag::log + const restoreScript = session.security.authenticationScriptBuilder() + .removePrincipal('super_user') + .build(); + await session.security.updateAuthenticationStore(restoreScript); + /// end::log + await session.closeSession(); + /// end::system_authentication_control_add_locked_principal[] +} diff --git a/ts/server-configuration/system-authentication-control/add-principal.ts b/ts/server-configuration/system-authentication-control/add-principal.ts new file mode 100644 index 00000000..6938b286 --- /dev/null +++ b/ts/server-configuration/system-authentication-control/add-principal.ts @@ -0,0 +1,41 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; + +export async function addPrincipal(): Promise { + /// tag::system_authentication_control_add_principal[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const authenticationScript = session.security.authenticationScriptBuilder() + .addPrincipal('super_user', 'password12345', [ 'ADMINISTRATOR' ]) + .build(); + await session.security.updateAuthenticationStore(authenticationScript); + + /// tag::log + const restoreScript = session.security.authenticationScriptBuilder() + .removePrincipal('super_user') + .build(); + await session.security.updateAuthenticationStore(restoreScript); + /// end::log + await session.closeSession(); + /// end::system_authentication_control_add_principal[] +} diff --git a/ts/server-configuration/system-authentication-control/allow-anonymous-connections.ts b/ts/server-configuration/system-authentication-control/allow-anonymous-connections.ts new file mode 100644 index 00000000..dd2a4be8 --- /dev/null +++ b/ts/server-configuration/system-authentication-control/allow-anonymous-connections.ts @@ -0,0 +1,49 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; + +export async function allowAnonymousConnections(): Promise { + /// tag::system_authentication_control_allow_anonymous_connections[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const authenticationScript = session.security.authenticationScriptBuilder() + .allowAnonymousConnections() + .build(); + await session.security.updateAuthenticationStore(authenticationScript); + + const anonymous = await connect({ + host: 'localhost', + port: 8080 + }); + console.log(`Anonymous session has been established: ${anonymous.sessionId}`); + + /// tag::log + const restoreScript = session.security.authenticationScriptBuilder() + .denyAnonymousConnections() + .allowAnonymousConnections(['CLIENT']) + .build(); + await session.security.updateAuthenticationStore(restoreScript); + /// end::log + await anonymous.closeSession(); + await session.closeSession(); + /// end::system_authentication_control_allow_anonymous_connections[] +} diff --git a/ts/server-configuration/system-authentication-control/assign-roles.ts b/ts/server-configuration/system-authentication-control/assign-roles.ts new file mode 100644 index 00000000..a1e4441a --- /dev/null +++ b/ts/server-configuration/system-authentication-control/assign-roles.ts @@ -0,0 +1,46 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; + +export async function assignRoles(): Promise { + /// tag::system_authentication_control_assign_roles[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const authenticationScript1 = session.security.authenticationScriptBuilder() + .addPrincipal('super_user', 'password12345', [ 'CLIENT' ]) + .build(); + await session.security.updateAuthenticationStore(authenticationScript1); + + const authenticationScript2 = session.security.authenticationScriptBuilder() + .assignRoles('super_user', [ 'ADMINISTRATOR' ]) + .build(); + await session.security.updateAuthenticationStore(authenticationScript2); + + /// tag::log + const restoreScript = session.security.authenticationScriptBuilder() + .removePrincipal('super_user') + .build(); + await session.security.updateAuthenticationStore(restoreScript); + /// end::log + await session.closeSession(); + /// end::system_authentication_control_assign_roles[] +} diff --git a/ts/server-configuration/system-authentication-control/change-password.ts b/ts/server-configuration/system-authentication-control/change-password.ts new file mode 100644 index 00000000..f390f119 --- /dev/null +++ b/ts/server-configuration/system-authentication-control/change-password.ts @@ -0,0 +1,46 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; + +export async function changePassword(): Promise { + /// tag::system_authentication_control_change_password[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const authenticationScript1 = session.security.authenticationScriptBuilder() + .addPrincipal('super_user', 'password12345', [ 'CLIENT' ]) + .build(); + await session.security.updateAuthenticationStore(authenticationScript1); + + const authenticationScript2 = session.security.authenticationScriptBuilder() + .setPassword('super_user', 'hunter2') + .build(); + await session.security.updateAuthenticationStore(authenticationScript2); + + /// tag::log + const restoreScript = session.security.authenticationScriptBuilder() + .removePrincipal('super_user') + .build(); + await session.security.updateAuthenticationStore(restoreScript); + /// end::log + await session.closeSession(); + /// end::system_authentication_control_change_password[] +} diff --git a/ts/server-configuration/system-authentication-control/deny-anonymous-connections.ts b/ts/server-configuration/system-authentication-control/deny-anonymous-connections.ts new file mode 100644 index 00000000..64866975 --- /dev/null +++ b/ts/server-configuration/system-authentication-control/deny-anonymous-connections.ts @@ -0,0 +1,55 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; + +export async function denyAnonymousConnections(): Promise { + /// tag::system_authentication_control_deny_anonymous_connections[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const authenticationScript = session.security.authenticationScriptBuilder() + .denyAnonymousConnections() + .build(); + await session.security.updateAuthenticationStore(authenticationScript); + + try { + await connect({ + host: 'localhost', + port: 8080 + }); + /// tag::log + fail('Anonymous connection should be denied'); + /// end::log + } + catch (err) { + // expected to fail + console.error('Could not connect', err.message); + } + + /// tag::log + const restoreScript = session.security.authenticationScriptBuilder() + .allowAnonymousConnections(['CLIENT']) + .build(); + await session.security.updateAuthenticationStore(restoreScript); + /// end::log + await session.closeSession(); + /// end::system_authentication_control_deny_anonymous_connections[] +} diff --git a/ts/server-configuration/system-authentication-control/ignore-client-proposed-property.ts b/ts/server-configuration/system-authentication-control/ignore-client-proposed-property.ts new file mode 100644 index 00000000..b2407341 --- /dev/null +++ b/ts/server-configuration/system-authentication-control/ignore-client-proposed-property.ts @@ -0,0 +1,90 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { clients, connect } from 'diffusion'; + +export async function ignoreClientProposedProperty(): Promise { + /// tag::system_authentication_control_ignore_client_proposed_property[] + // Connect to the server. + const session1 = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const authenticationScript1 = session1.security.authenticationScriptBuilder() + .ignoreClientProposedProperty('Rubble') + .trustClientProposedPropertyMatches('Flintstone', '.*_Flintstone') + .build(); + await session1.security.updateAuthenticationStore(authenticationScript1); + + const session2 = await connect({ + host: 'localhost', + port: 8080, + principal: 'control', + credentials: 'password', + properties: { + 'Rubble': 'Barney_Rubble' + } + }); + + const properties2 = await session1.clients.getSessionProperties( + session2.sessionId, + clients.PropertyKeys.ALL_PROPERTIES + ); + console.log('Received the following session properties:'); + for (const key of Object.keys(properties2)) { + console.log(` ${key}: ${properties2[key]}`); + } + /// tag::log + expect(properties2['Rubble']).toBeUndefined(); + /// end::log + + await session2.closeSession(); + + const session3 = await connect({ + host: 'localhost', + port: 8080, + principal: 'control', + credentials: 'password', + properties: { + 'Flintstone': 'Fred_Flintstone' + } + }); + + const properties3 = await session1.clients.getSessionProperties( + session3.sessionId, + clients.PropertyKeys.ALL_PROPERTIES + ); + console.log('Received the following session properties:'); + for (const key of Object.keys(properties3)) { + console.log(` ${key}: ${properties3[key]}`); + } + /// tag::log + expect(properties3['Flintstone']).toBe('Fred_Flintstone'); + /// end::log + + await session3.closeSession(); + + /// tag::log + const restoreScript = session1.security.authenticationScriptBuilder() + .ignoreClientProposedProperty('Flintstone') + .build(); + await session1.security.updateAuthenticationStore(restoreScript); + /// end::log + await session1.closeSession(); + /// end::system_authentication_control_ignore_client_proposed_property[] +} diff --git a/ts/server-configuration/system-authentication-control/remove-principal.ts b/ts/server-configuration/system-authentication-control/remove-principal.ts new file mode 100644 index 00000000..af4410dd --- /dev/null +++ b/ts/server-configuration/system-authentication-control/remove-principal.ts @@ -0,0 +1,40 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; + +export async function removePrincipal(): Promise { + /// tag::system_authentication_control_remove_principal[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const authenticationScript1 = session.security.authenticationScriptBuilder() + .addPrincipal('super_user', 'password12345', [ 'ADMINISTRATOR' ]) + .build(); + await session.security.updateAuthenticationStore(authenticationScript1); + + const authenticationScript2 = session.security.authenticationScriptBuilder() + .removePrincipal('super_user') + .build(); + await session.security.updateAuthenticationStore(authenticationScript2); + + await session.closeSession(); + /// end::system_authentication_control_remove_principal[] +} diff --git a/ts/server-configuration/system-authentication-control/trust-client-proposed-property-in.ts b/ts/server-configuration/system-authentication-control/trust-client-proposed-property-in.ts new file mode 100644 index 00000000..04b07039 --- /dev/null +++ b/ts/server-configuration/system-authentication-control/trust-client-proposed-property-in.ts @@ -0,0 +1,89 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { clients, connect } from 'diffusion'; + +export async function trustClientProposedPropertyIn(): Promise { + /// tag::system_authentication_control_trust_client_proposed_property_in[] + // Connect to the server. + const session1 = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const authenticationScript1 = session1.security.authenticationScriptBuilder() + .trustClientProposedPropertyIn('Flintstone', [ 'Fred', 'Wilma', 'Pebbles' ]) + .build(); + await session1.security.updateAuthenticationStore(authenticationScript1); + + const session2 = await connect({ + host: 'localhost', + port: 8080, + principal: 'control', + credentials: 'password', + properties: { + 'Flintstone': 'Barney' + } + }); + + const properties2 = await session1.clients.getSessionProperties( + session2.sessionId, + clients.PropertyKeys.ALL_PROPERTIES + ); + console.log('Received the following session properties:'); + for (const key of Object.keys(properties2)) { + console.log(` ${key}: ${properties2[key]}`); + } + /// tag::log + expect(properties2['Flintstone']).toBeUndefined(); + /// end::log + + await session2.closeSession(); + + const session3 = await connect({ + host: 'localhost', + port: 8080, + principal: 'control', + credentials: 'password', + properties: { + 'Flintstone': 'Fred' + } + }); + + const properties3 = await session1.clients.getSessionProperties( + session3.sessionId, + clients.PropertyKeys.ALL_PROPERTIES + ); + console.log('Received the following session properties:'); + for (const key of Object.keys(properties3)) { + console.log(` ${key}: ${properties3[key]}`); + } + /// tag::log + expect(properties3['Flintstone']).toBe('Fred'); + /// end::log + + await session3.closeSession(); + + /// tag::log + const restoreScript = session1.security.authenticationScriptBuilder() + .ignoreClientProposedProperty('Flintstone') + .build(); + await session1.security.updateAuthenticationStore(restoreScript); + /// end::log + await session1.closeSession(); + /// end::system_authentication_control_trust_client_proposed_property_in[] +} diff --git a/ts/server-configuration/system-authentication-control/trust-client-proposed-property-matches.ts b/ts/server-configuration/system-authentication-control/trust-client-proposed-property-matches.ts new file mode 100644 index 00000000..45a20a29 --- /dev/null +++ b/ts/server-configuration/system-authentication-control/trust-client-proposed-property-matches.ts @@ -0,0 +1,89 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { clients, connect } from 'diffusion'; + +export async function trustClientProposedPropertyMatches(): Promise { + /// tag::system_authentication_control_trust_client_proposed_property_matches[] + // Connect to the server. + const session1 = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const authenticationScript1 = session1.security.authenticationScriptBuilder() + .trustClientProposedPropertyMatches('Flintstone', '.*_Flintstone') + .build(); + await session1.security.updateAuthenticationStore(authenticationScript1); + + const session2 = await connect({ + host: 'localhost', + port: 8080, + principal: 'control', + credentials: 'password', + properties: { + 'Flintstone': 'Barney_Rubble' + } + }); + + const properties2 = await session1.clients.getSessionProperties( + session2.sessionId, + clients.PropertyKeys.ALL_PROPERTIES + ); + console.log('Received the following session properties:'); + for (const key of Object.keys(properties2)) { + console.log(` ${key}: ${properties2[key]}`); + } + /// tag::log + expect(properties2['Flintstone']).toBeUndefined(); + /// end::log + + await session2.closeSession(); + + const session3 = await connect({ + host: 'localhost', + port: 8080, + principal: 'control', + credentials: 'password', + properties: { + 'Flintstone': 'Fred_Flintstone' + } + }); + + const properties3 = await session1.clients.getSessionProperties( + session3.sessionId, + clients.PropertyKeys.ALL_PROPERTIES + ); + console.log('Received the following session properties:'); + for (const key of Object.keys(properties3)) { + console.log(` ${key}: ${properties3[key]}`); + } + /// tag::log + expect(properties3['Flintstone']).toBe('Fred_Flintstone'); + /// end::log + + await session3.closeSession(); + + /// tag::log + const restoreScript = session1.security.authenticationScriptBuilder() + .ignoreClientProposedProperty('Flintstone') + .build(); + await session1.security.updateAuthenticationStore(restoreScript); + /// end::log + await session1.closeSession(); + /// end::system_authentication_control_trust_client_proposed_property_matches[] +} diff --git a/ts/server-configuration/system-authentication-control/verify-password.ts b/ts/server-configuration/system-authentication-control/verify-password.ts new file mode 100644 index 00000000..4faba724 --- /dev/null +++ b/ts/server-configuration/system-authentication-control/verify-password.ts @@ -0,0 +1,78 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; + +export async function verifyPassword(): Promise { + /// tag::system_authentication_control_verify_password[] + // Connect to the server. + const session1 = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const authenticationScript1 = session1.security.authenticationScriptBuilder() + .verifyPassword('control', 'password') + .setPassword('control', '12345') + .build(); + await session1.security.updateAuthenticationStore(authenticationScript1); + + const session2 = await connect({ + host: 'localhost', + port: 8080, + principal: 'control', + credentials: '12345' + }); + console.log(`Control session has been established: ${session2.sessionId}`); + await session2.closeSession(); + + const authenticationScript2 = session1.security.authenticationScriptBuilder() + .verifyPassword('control', 'this_is_not_the_right_password') + .setPassword('control', 'new_password') + .build(); + try { + await session1.security.updateAuthenticationStore(authenticationScript2); + } catch (err) { + // expected to fail + console.log('Password verification failed'); + } + + try { + await connect({ + host: 'localhost', + port: 8080, + principal: 'control', + credentials: 'new_password' + }); + /// tag::log + fail('Connection should be denied'); + /// end::log + } + catch (err) { + // expected to fail + console.error('Could not connect', err.message); + } + + /// tag::log + const restoreScript = session1.security.authenticationScriptBuilder() + .setPassword('control', 'password') + .build(); + await session1.security.updateAuthenticationStore(restoreScript); + /// end::log + await session1.closeSession(); + /// end::system_authentication_control_change_password[] +} diff --git a/ts/session-management/authentication-control.ts b/ts/session-management/authentication-control.ts new file mode 100644 index 00000000..2c29cbfd --- /dev/null +++ b/ts/session-management/authentication-control.ts @@ -0,0 +1,130 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { + Authenticator, + AuthenticatorCallback, + connect, + Credentials, + Session, + SessionProperties +} from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester } from '../../../test/util'; +/// end::log + +export async function sessionManagementAuthenticationControl(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Rejecting anonymous connection attempt.'], + ['Anonymous connection failed.'], + ['Rejecting connection attempt from principal not statring with diffusion_.'], + ['control connection failed.'], + ['Accepting connection attempt from principal starting with diffusion_.'], + ['diffusion_control connection established.'] + ]); + /// end::log + /// tag::session_management_authentication_control[] + // Connect to the server. + const session1 = await connect({ + host: 'localhost', + port: 8080, + principal: 'control', + credentials: 'password' + }); + + const authenticator: Authenticator = { + authenticate: ( + principal: string, + credentials: Credentials, + sessionProperties: SessionProperties, + proposedPorperties: SessionProperties, + callback: AuthenticatorCallback + ) => { + if (principal === '') { + console.log('Anonymous connection attempt detected. Session establishment rejected.'); + /// tag::log + check.log('Rejecting anonymous connection attempt.'); + /// end::log + callback.deny(); + } else if (principal.startsWith('diffusion_')) { + console.log('Principal begins with diffusion_ prefix. Session establishment accepted.'); + /// tag::log + check.log('Accepting connection attempt from principal starting with diffusion_.'); + /// end::log + callback.allow(); + } else { + console.log('Principal does not begin with diffusion_ prefix. Session establishment rejected.'); + /// tag::log + check.log('Rejecting connection attempt from principal not statring with diffusion_.'); + /// end::log + callback.deny(); + } + }, + onClose: () => {}, + onError: () => {} + }; + await session1.security.setAuthenticator('before-system-handler', authenticator); + + let session2: Session | undefined = undefined; + try { + // Connect to the server. + session2 = await connect({ + host: 'localhost', + port: 8080 + }); + } catch (err) { + console.error('Connection could not be established. (Expected)', err); + /// tag::log + check.log('Anonymous connection failed.'); + /// end::log + } + + let session3: Session | undefined = undefined; + try { + // Connect to the server. + session3 = await connect({ + host: 'localhost', + port: 8080, + principal: 'control', + credentials: 'password' + }); + } catch (err) { + console.error('Connection could not be established. (Expected)', err); + /// tag::log + check.log('control connection failed.'); + /// end::log + } + + // Connect to the server. + const session4 = await connect({ + host: 'localhost', + port: 8080, + principal: 'diffusion_control', + credentials: 'password' + }); + /// tag::log + check.log('diffusion_control connection established.'); + /// end::log + + await session1.closeSession(); + await session2?.closeSession(); + await session3?.closeSession(); + await session4.closeSession(); + /// end::session_management_authentication_control[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/session-management/client-control/change-roles-via-session-filter.ts b/ts/session-management/client-control/change-roles-via-session-filter.ts new file mode 100644 index 00000000..63c7f723 --- /dev/null +++ b/ts/session-management/client-control/change-roles-via-session-filter.ts @@ -0,0 +1,59 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; + +export async function clientControlChangeRolesViaSessionFilter(): Promise { + /// tag::client_control_change_roles_via_session_filter[] + // Connect to the server. + const session1 = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + // Connect to the server. + const session2 = await connect({ + host: 'localhost', + port: 8080, + principal: 'client', + credentials: 'password' + }); + + const properties1 = await session1.clients.getSessionProperties( + session2.sessionId, + ['$Roles'] + ); + console.log(`Original session roles: ${properties1['$Roles']}`); + /// tag::log + expect(properties1['$Roles']).toBe('"CLIENT"'); + /// end::log + + await session1.clients.changeRoles('$Principal is "client"', [], ['TOPIC_CONTROL']); + + const properties2 = await session1.clients.getSessionProperties( + session2.sessionId, + ['$Roles'] + ); + console.log(`Changed session roles: ${properties2['$Roles']}`); + /// tag::log + expect(properties2['$Roles']).toBe('"CLIENT","TOPIC_CONTROL"'); + /// end::log + + await session1.closeSession(); + await session2.closeSession(); + /// end::client_control_change_roles_via_session_filter[] +} diff --git a/ts/session-management/client-control/change-roles-via-session-id.ts b/ts/session-management/client-control/change-roles-via-session-id.ts new file mode 100644 index 00000000..5d80944d --- /dev/null +++ b/ts/session-management/client-control/change-roles-via-session-id.ts @@ -0,0 +1,59 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; + +export async function clientControlChangeRolesViaSessionId(): Promise { + /// tag::client_control_change_roles_via_session_id[] + // Connect to the server. + const session1 = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + // Connect to the server. + const session2 = await connect({ + host: 'localhost', + port: 8080, + principal: 'client', + credentials: 'password' + }); + + const properties1 = await session1.clients.getSessionProperties( + session2.sessionId, + ['$Roles'] + ); + console.log(`Original session roles: ${properties1['$Roles']}`); + /// tag::log + expect(properties1['$Roles']).toBe('"CLIENT"'); + /// end::log + + await session1.clients.changeRoles(session2.sessionId, [], ['TOPIC_CONTROL']); + + const properties2 = await session1.clients.getSessionProperties( + session2.sessionId, + ['$Roles'] + ); + console.log(`Changed session roles: ${properties2['$Roles']}`); + /// tag::log + expect(properties2['$Roles']).toBe('"CLIENT","TOPIC_CONTROL"'); + /// end::log + + await session1.closeSession(); + await session2.closeSession(); + /// end::client_control_change_roles_via_session_id[] +} diff --git a/ts/session-management/client-control/close-client-via-session-filter.ts b/ts/session-management/client-control/close-client-via-session-filter.ts new file mode 100644 index 00000000..7eb8b95a --- /dev/null +++ b/ts/session-management/client-control/close-client-via-session-filter.ts @@ -0,0 +1,57 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; +/// tag::log +import { promiseWithResolvers } from '../../../../test/util'; +/// end::log + +export async function clientControlCloseClientViaSessionFilter(): Promise { + /// tag::log + const { promise, resolve } = promiseWithResolvers(); + /// end::log + /// tag::client_control_close_client_via_session_filter[] + // Connect to the server. + const session1 = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + // Connect to the server. + const session2 = await connect({ + host: 'localhost', + port: 8080, + principal: 'client', + credentials: 'password' + }); + + session2.on('close', () => { + console.log('Session closed'); + /// tag::log + resolve(); + /// end::log + }); + + await session1.clients.close('$Principal is "client"'); + + await session1.closeSession(); + /// tag::log + await promise; + expect(session2.isClosed()).toBe(true); + /// end::log + /// end::client_control_close_client_via_session_filter[] +} diff --git a/ts/session-management/client-control/close-client-via-session-id.ts b/ts/session-management/client-control/close-client-via-session-id.ts new file mode 100644 index 00000000..42dd156b --- /dev/null +++ b/ts/session-management/client-control/close-client-via-session-id.ts @@ -0,0 +1,57 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; +/// tag::log +import { promiseWithResolvers } from '../../../../test/util'; +/// end::log + +export async function clientControlCloseClientViaSessionId(): Promise { + /// tag::log + const { promise, resolve } = promiseWithResolvers(); + /// end::log + /// tag::client_control_close_client_via_session_id[] + // Connect to the server. + const session1 = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + // Connect to the server. + const session2 = await connect({ + host: 'localhost', + port: 8080, + principal: 'client', + credentials: 'password' + }); + + session2.on('close', () => { + console.log('Session closed'); + /// tag::log + resolve(); + /// end::log + }); + + await session1.clients.close(session2.sessionId); + + await session1.closeSession(); + /// tag::log + await promise; + expect(session2.isClosed()).toBe(true); + /// end::log + /// end::client_control_close_client_via_session_id[] +} diff --git a/ts/session-management/client-control/get-session-properties-via-session-id.ts b/ts/session-management/client-control/get-session-properties-via-session-id.ts new file mode 100644 index 00000000..ae723ad9 --- /dev/null +++ b/ts/session-management/client-control/get-session-properties-via-session-id.ts @@ -0,0 +1,75 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { clients, connect } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester } from '../../../../test/util'; +/// end::log + +export async function clientControlGetSessionPropertiesViaSessionId(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + '$Country', + '$ClientIP', + '$Environment', + '$SessionId', + '$Transport', + '$Principal', + '$ServerName', + '$StartTime', + '$Language', + '$Latitude', + '$Connector', + '$Longitude', + '$ClientType', + '$Roles', + ]]); + /// end::log + /// tag::client_control_get_session_properties_via_session_id[] + // Connect to the server. + const session1 = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + // Connect to the server. + const session2 = await connect({ + host: 'localhost', + port: 8080, + principal: 'client', + credentials: 'password' + }); + + const properties = await session1.clients.getSessionProperties( + session2.sessionId, + clients.PropertyKeys.ALL_FIXED_PROPERTIES + ); + console.log('Received the following session properties:'); + for (const key of Object.keys(properties)) { + console.log(` ${key}: ${properties[key]}`); + /// tag::log + check.log(`${key}`); + /// end::log + } + + await session1.closeSession(); + await session2.closeSession(); + /// end::client_control_get_session_properties_via_session_id[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/session-management/client-control/queue-conflation-via-session-filter.ts b/ts/session-management/client-control/queue-conflation-via-session-filter.ts new file mode 100644 index 00000000..112567ca --- /dev/null +++ b/ts/session-management/client-control/queue-conflation-via-session-filter.ts @@ -0,0 +1,50 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester } from '../../../../test/util'; +/// end::log + +export async function clientControlQueueConflationViaSessionFilter(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([]); + /// end::log + /// tag::client_control_queue_conflation_via_session_filter[] + // Connect to the server. + const session1 = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + // Connect to the server. + const session2 = await connect({ + host: 'localhost', + port: 8080, + principal: 'client', + credentials: 'password' + }); + + await session1.clients.setConflated('$Principal is "client"', false); + + await session1.closeSession(); + await session2.closeSession(); + /// end::client_control_queue_conflation_via_session_filter[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/session-management/client-control/queue-conflation-via-session-id.ts b/ts/session-management/client-control/queue-conflation-via-session-id.ts new file mode 100644 index 00000000..2b8f8348 --- /dev/null +++ b/ts/session-management/client-control/queue-conflation-via-session-id.ts @@ -0,0 +1,50 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester } from '../../../../test/util'; +/// end::log + +export async function clientControlQueueConflationViaSessionId(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([]); + /// end::log + /// tag::client_control_queue_conflation_via_session_id[] + // Connect to the server. + const session1 = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + // Connect to the server. + const session2 = await connect({ + host: 'localhost', + port: 8080, + principal: 'client', + credentials: 'password' + }); + + await session1.clients.setConflated(session2.sessionId, false); + + await session1.closeSession(); + await session2.closeSession(); + /// end::client_control_queue_conflation_via_session_id[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/session-management/client-control/set-session-properties-via-filter.ts b/ts/session-management/client-control/set-session-properties-via-filter.ts new file mode 100644 index 00000000..54228b2e --- /dev/null +++ b/ts/session-management/client-control/set-session-properties-via-filter.ts @@ -0,0 +1,65 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { clients, connect } from 'diffusion'; + +export async function clientControlSetSessionPropertiesViaSessionFilter(): Promise { + /// tag::client_control_set_session_properties_via_session_filter[] + // Connect to the server. + const session1 = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + // Connect to the server. + const session2 = await connect({ + host: 'localhost', + port: 8080, + principal: 'client', + credentials: 'password' + }); + + const properties1 = await session1.clients.getSessionProperties( + session2.sessionId, + clients.PropertyKeys.ALL_FIXED_PROPERTIES + ); + console.log('Original session properties:'); + for (const key of Object.keys(properties1)) { + console.log(` ${key}: ${properties1[key]}`); + } + + await session1.clients.setSessionPropertiesByFilter( + '$Principal is "client"', + { '$Language': 'en-gb' } + ); + + const properties2 = await session1.clients.getSessionProperties( + session2.sessionId, + clients.PropertyKeys.ALL_FIXED_PROPERTIES + ); + console.log('Changed session properties:'); + for (const key of Object.keys(properties2)) { + console.log(` ${key}: ${properties2[key]}`); + } + /// tag::log + expect(properties2['$Language']).toBe('en-gb'); + /// end::log + + await session1.closeSession(); + await session2.closeSession(); + /// end::client_control_set_session_properties_via_session_filter[] +} diff --git a/ts/session-management/client-control/set-session-properties-via-session-id.ts b/ts/session-management/client-control/set-session-properties-via-session-id.ts new file mode 100644 index 00000000..64d36b69 --- /dev/null +++ b/ts/session-management/client-control/set-session-properties-via-session-id.ts @@ -0,0 +1,65 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { clients, connect } from 'diffusion'; + +export async function clientControlSetSessionPropertiesViaSessionId(): Promise { + /// tag::client_control_set_session_properties_via_session_id[] + // Connect to the server. + const session1 = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + // Connect to the server. + const session2 = await connect({ + host: 'localhost', + port: 8080, + principal: 'client', + credentials: 'password' + }); + + const properties1 = await session1.clients.getSessionProperties( + session2.sessionId, + clients.PropertyKeys.ALL_FIXED_PROPERTIES + ); + console.log('Original session properties:'); + for (const key of Object.keys(properties1)) { + console.log(` ${key}: ${properties1[key]}`); + } + + await session1.clients.setSessionProperties( + session2.sessionId, + { '$Language': 'en-gb' } + ); + + const properties2 = await session1.clients.getSessionProperties( + session2.sessionId, + clients.PropertyKeys.ALL_FIXED_PROPERTIES + ); + console.log('Changed session properties:'); + for (const key of Object.keys(properties2)) { + console.log(` ${key}: ${properties2[key]}`); + } + /// tag::log + expect(properties2['$Language']).toBe('en-gb'); + /// end::log + + await session1.closeSession(); + await session2.closeSession(); + /// end::client_control_set_session_properties_via_session_id[] +} diff --git a/ts/session-management/subscription-control.ts b/ts/session-management/subscription-control.ts new file mode 100644 index 00000000..7c44d6c6 --- /dev/null +++ b/ts/session-management/subscription-control.ts @@ -0,0 +1,133 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { + connect, + datatypes, + SessionEvent, + SessionEventStream, + topics, + clients +} from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester, promiseWithResolvers } from '../../../test/util'; +/// end::log + +export async function sessionManagementSubscriptionControl(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['subscribed client'], + ['Subscribed to my/topic/path/hello'], + ['unsubscribed client', 'Unsubscribed from my/topic/path/hello'] + ]); + const subscribedPromise = promiseWithResolvers(); + const unsubscribeTopicPromise = promiseWithResolvers(); + /// end::log + /// tag::session_management_subscription_control[] + // Connect to the server. + const session1 = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.STRING); + await session1.topicUpdate.set( + 'my/topic/path/hello', + datatypes.string(), + 'Hello World!', + { specification: specification } + ); + console.log('Topic value has been set.'); + + let deferredUnsubscribeResolve: () => void; + const unsubscribePromise = new Promise((resolve) => { + deferredUnsubscribeResolve = resolve; + }); + + const sessionEventStream: SessionEventStream = { + onSessionEvent: (event: SessionEvent) => { + console.log(`Session ${event.sessionId.toString()} has been updated:`); + console.log(` Type: ${clients.SessionEventStreamEventType[event.type]}`); + console.log(` State: ${clients.SessionState[event.state]}`); + + if ( + event.type === clients.SessionEventStreamEventType.STATE + && event.state === clients.SessionState.ACTIVE + && event.sessionId.toString() !== session1.sessionId.toString() + ) { + session1.clients.subscribe(event.sessionId, '?my/topic/path//'); + /// tag::log + check.log('subscribed client'); + /// end::log + setTimeout(async () => { + /// tag::log + await subscribedPromise.promise; + /// end::log + await session1.clients.unsubscribe(event.sessionId, '?my/topic/path//'); + /// tag::log + check.log('unsubscribed client'); + /// end::log + deferredUnsubscribeResolve(); + }, 5000); + } + }, + onClose: () => {}, + onError: () => {} + }; + await session1.clients.addSessionEventListener(sessionEventStream, {}); + + // Connect to the server. + const session2 = await connect({ + host: 'localhost', + port: 8080, + principal: 'client', + credentials: 'password' + }); + + const valueStream = session2.addFallbackStream(datatypes.string()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + subscribedPromise.resolve(); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + /// tag::log + check.log(`Unsubscribed from ${topic}`); + unsubscribeTopicPromise.resolve(); + /// end::log + }, + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${oldValue.get()} to ${newValue.get()}`); + } + }); + + await unsubscribePromise; + /// tag::log + await unsubscribeTopicPromise.promise; + /// end::log + + await session1.closeSession(); + await session2.closeSession(); + /// end::session_management_subscription_control[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/src/addTopics.ts b/ts/src/addTopics.ts deleted file mode 100644 index 02a3dc7d..00000000 --- a/ts/src/addTopics.ts +++ /dev/null @@ -1,80 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -import { connect, topics, Session, TopicAddResult, TopicSpecification } from 'diffusion'; - -// example showcasing how to add a topic using session.topics.add -export async function addTopicExample(): Promise { - // Connect to the server. Change these options to suit your own environment. - // Node.js does not accept self-signed certificates by default. If you have - // one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 - // before running this example. - const session: Session = await connect({ - host: 'diffusion.example.com', - port: 443, - secure: true, - principal: 'control', - credentials: 'password' - }); - - // 1. Topics can be created with a topic path and a TopicType or TopicSpecification. The '/' delimiter allows topics - // to be created in a hierarchy. - - const TopicType = topics.TopicType; - - // Create a topic from a topic type - session.topics.add('topic/string', new TopicSpecification(TopicType.STRING)); - - // Create a topic from a topic specification, with optional properties - session.topics.add('topic/integer', new TopicSpecification(TopicType.INT64, { - VALIDATES_VALUES: "true" - })); - - try { - // 2. Adding a topic returns a promise, which allows us to handle when the operation has either completed - // successfully or encountered an error. - const result: TopicAddResult = await session.topics.add('topic/result', new TopicSpecification(TopicType.JSON)); - - // result.added will be true - console.log('Added topic: ' + result.topic, result.added); - } catch (error) { - console.log('Failed to add topic: ', error); - } - - try { - // Adding a topic that already exists will succeed, so long as it has the same value type - const result: TopicAddResult = await session.topics.add('topic/result', new TopicSpecification(TopicType.JSON)); - - // result.added will be false, as the topic already existed - console.log('Added topic: ' + result.topic, result.added); - } catch (error) { - console.log('Failed to add topic: ', error); - } - - try { - // 3. Because the result returned from adding a topic is a promise, we can run multiple operations and wait for all - // of them to finish - const promise1: Promise = session.topics.add('chain/foo', new TopicSpecification(TopicType.STRING)); - const promise2: Promise = session.topics.add('chain/bar', new TopicSpecification(TopicType.STRING)); - const promise3: Promise = session.topics.add('chain/baz', new TopicSpecification(TopicType.STRING)); - const promise4: Promise = session.topics.add('chain/qux', new TopicSpecification(TopicType.STRING)); - - await Promise.all([promise1, promise2, promise3, promise4]); - - console.log('Added all topics'); - } catch (error) { - console.log('Failed to add topic: ', error); - } -} diff --git a/ts/src/clientControl.ts b/ts/src/clientControl.ts deleted file mode 100644 index 9068c7e4..00000000 --- a/ts/src/clientControl.ts +++ /dev/null @@ -1,85 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -import { connect, clients, Session, SessionProperties, SessionId, SessionEventType } from 'diffusion'; - -// example showcasing how a control session can receive updates on another session's properties -export async function clientControlExample(): Promise { - - // Connect to the server. Change these options to suit your own environment. - // Node.js does not accept self-signed certificates by default. If you have - // one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 - // before running this example. - const session: Session = await connect({ - host: 'localhost', - port: 8080, - secure: false, - principal: 'control', - credentials: 'password' - }); - - try { - // Get our own fixed properties - const props: SessionProperties = await session.clients.getSessionProperties(session.sessionId, clients.PropertyKeys.ALL_FIXED_PROPERTIES); - console.log('getSessionProperties returns properties:', props); - } catch (error) { - console.log('An error has occurred:', error); - } - - try { - // Register a listener for session properties - await session.clients.setSessionPropertiesListener(clients.PropertyKeys.ALL_FIXED_PROPERTIES, { - onActive: (deregister) => { - console.log("Session properties listener opened"); - - // `deregister` is a callback passed to the listener when it becomes active. - // A call to deregister() will close this listener. - }, - onClose: () => { - console.log("Session properties listener closed"); - }, - onSessionOpen: (sessionId: SessionId, properties: SessionProperties) =>{ - // Notification that a session has been opened - console.log("Session opened: " + session, JSON.stringify(properties)); - }, - onSessionEvent: (sessionId: SessionId, event: SessionEventType, properties: SessionProperties) => { - // Notification that a session's properties have changed - switch (event) { - case session.clients.SessionEventType.UPDATED: - console.log("Session updated: " + sessionId, JSON.stringify(properties)); - break; - case session.clients.SessionEventType.DISCONNECTED: - console.log("Session disconnected: " + sessionId, JSON.stringify(properties)); - break; - case session.clients.SessionEventType.RECONNECTED: - console.log("Session reconnected: " + sessionId, JSON.stringify(properties)); - break; - case session.clients.SessionEventType.FAILED_OVER: - console.log("Session failed over: " + sessionId, JSON.stringify(properties)); - } - }, - onSessionClose: (sessionId: SessionId, properties: SessionProperties, reason) => { - console.log("Session closed: " + session + " reason: " + reason, JSON.stringify(properties)); - }, - onError: (error) => { - console.log('An error has occurred:', error); - } - }); - - console.log("Session listener successfully registered"); - } catch (error) { - console.log('An error occurred registering a session listener:', error); - } -} diff --git a/ts/src/connectRetry.ts b/ts/src/connectRetry.ts deleted file mode 100644 index 0249826e..00000000 --- a/ts/src/connectRetry.ts +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -import { connect, Session } from 'diffusion'; - -// example showcasing how to set an initial connection retry -export async function connectionRetryExample(): Promise { - - // When establishing a session, it is possible to specify whether the initial - // connection attempt should be retried when a failure occurs - - // Connect to the server. - const session: Session = await connect({ - host: 'diffusion.example.com', - port: 443, - secure: true, - principal: 'control', - credentials: 'password', - retry: { - // perform 5 initial connection attempts before giving up - attempts: 5, - // set 300 ms between connection attempts - interval: 300 - } - }); - - console.log(`Connection established ${session.sessionId}`); -} diff --git a/ts/src/datatypes.ts b/ts/src/datatypes.ts deleted file mode 100644 index eb095376..00000000 --- a/ts/src/datatypes.ts +++ /dev/null @@ -1,81 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -import { connect, datatypes, topics, Session } from 'diffusion'; - -// example showcasing the diffusion data types -export async function datatypesExample(): Promise { - - // Connect to the server. Change these options to suit your own environment. - // Node.js does not accept self-signed certificates by default. If you have - // one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 - // before running this example. - const session: Session = await connect({ - host: 'diffusion.example.com', - port: 443, - secure: true, - principal: 'control', - credentials: 'password' - }); - - // 1. Data Types are exposed from the top level Diffusion namespace. It is often easier - // to assign these directly to a local variable. - const stringDataType = datatypes.string(); - const jsonDataType = datatypes.json(); - const TopicSpecification = topics.TopicSpecification; - const TopicType = topics.TopicType; - - // 2. Data Types are currently provided for JSON, Binary, String, Double, Int64 and RecordV2 topic types. - await Promise.all([ - session.topics.add('topic/string', new TopicSpecification(TopicType.STRING)), - session.topics.add('topic/json', new TopicSpecification(TopicType.JSON)) - ]); - - // 3. Values can be created directly from the data type. - const jsonValue = jsonDataType.from({ - "foo" : "bar" - }); - - await Promise.all([ - // Topics are updated using the standard update mechanisms - session.topicUpdate.set('topic/json', jsonDataType, jsonValue), - // For String, Double and Int64 topics, values can be passed directly - session.topicUpdate.set('topic/string', stringDataType, "This is a new string value") - ]); - - // 4. Add a value streams for receiving JSON values. - session.addStream('topic/json', jsonDataType).on('value', function(topic, spec, newValue, oldValue) { - // When a JSON or Binary topic is updated, any value handlers on a subscription will be called with both the - // new value, and the old value. - - // The oldValue parameter will be undefined if this is the first value received for a topic. - - // For JSON topics, value#get returns a JavaScript object. - // For Binary topics, value#get returns a Buffer instance. - console.log("Update for " + topic, newValue.get()); - }); - - session.addStream('topic/string', stringDataType).on('value', function(topic, spec, newValue, oldValue) { - // Unlike JSON or Binary, String, Double and Int64 datatypes provide values as primitive types. - // This means you don't need to call #get to receive the actual data. - console.log("Update for string topic: " + newValue); - }); - - session.select('?topic//'); - - // 5. Raw values of an appropriate type can also be used for JSON and Binary topics. - // For example, plain JSON objects can be used to update JSON topics. - session.topicUpdate.set('topic/json', jsonDataType, {"foo" : "baz", "numbers" : [1, 2, 3] }); -} diff --git a/ts/src/fallbackStream.ts b/ts/src/fallbackStream.ts deleted file mode 100644 index 1458aafb..00000000 --- a/ts/src/fallbackStream.ts +++ /dev/null @@ -1,81 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -import { connect, datatypes, topics, Session } from 'diffusion'; - -// example showcasing how to add a fallback stream that receives updates for topics that -// don't have a value stream -export async function fallbackStreamExample(): Promise { - - // Data Types are exposed from the top level Diffusion namespace. It is often easier - // to assign these directly to a local variable. - const stringDataType = datatypes.string(); - const TopicSpecification = topics.TopicSpecification; - const TopicType = topics.TopicType; - - // Connect to the server. Change these options to suit your own environment. - // Node.js does not accept self-signed certificates by default. If you have - // one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 - // before running this example. - const session: Session = await connect({ - host: 'diffusion.example.com', - port: 443, - secure: true, - principal: 'control', - credentials: 'password' - }); - - try { - // 1. Create a String topic type - await session.topics.add('topic/foo', new TopicSpecification(TopicType.STRING)); - // Once the topic is added successfully then update it with a new value - await session.topicUpdate.set('topic/foo', stringDataType, "foo-string"); - } catch (error) { - console.log("Fail to update topic 'foo': ", error); - } - - try { - // Create another String topic type - await session.topics.add('topic/bar', new TopicSpecification(TopicType.STRING)); - await session.topicUpdate.set('topic/bar', stringDataType, 'bar-string'); - } catch (error) { - console.log("Fail to update topic 'bar': ", error); - } - - try { - // And another String topic type - await session.topics.add('topic/baz', new TopicSpecification(TopicType.STRING)); - await session.topicUpdate.set('topic/baz', stringDataType, "baz-string"); - } catch (error) { - console.log("Fail to update topic 'baz': ", error); - } - - // 2. Register a value stream for receiving String value update - session.addStream('topic/foo', stringDataType) - .on('value', function(topic, specification, newValue, oldValue) { - console.log("Received update ", newValue); - }); - - - // 3. Register a fallback value stream to receive update for any topics that don't have a stream register - // In this example, the falback stream will receive updates from 'topic/bar' and 'topic/baz' - session.addFallbackStream(stringDataType) - .on('value', function(topic, specification, newValue, oldValue) { - console.log("Received update ", newValue); - }); - - // 4. Subscribe - session.select('?topic//'); -} diff --git a/ts/src/fetchRequest.ts b/ts/src/fetchRequest.ts deleted file mode 100644 index 01577f3e..00000000 --- a/ts/src/fetchRequest.ts +++ /dev/null @@ -1,105 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -import { connect, datatypes, topics, Session, FetchResult, TopicResult, JSON } from 'diffusion'; - -// example showcasing how to fetch topics and their values using session.fetchRequest -export async function fetchRequestExample(): Promise { - - const jsonDataType = datatypes.json(); - const TopicType = topics.TopicType; - - - // Connect to the server. Change these options to suit your own environment. - // Node.js does not accept self-signed certificates by default. If you have - // one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 - // before running this example. - const session: Session = await connect({ - host: 'diffusion.example.com', - port: 443, - secure: true, - principal: 'client', - credentials: 'password' - }); - - const fetchResult: FetchResult - = await session - .fetchRequest() // obtain a FetchRequest - .from("SomeTopic/B") // limit to topics after and including SomeTopic/B - .to("SomeTopic/X") // limit to topics before and including SomeTopic/X - .first(10) // only fetch the first 10 topics - .topicTypes([TopicType.STRING, TopicType.INT64]) // limit to string and integer topic types - .withValues(jsonDataType) // fetch values return them as JSON objects - .withProperties() // get the topic properties - .fetch("*SomeTopic//"); // perform the fetch request using a topic selector - const results: TopicResult[] = fetchResult.results(); - console.log("Fetch Request returned "+results.length+" topics"); - - results.forEach((topicResult: TopicResult) => { - console.log("Path: ", topicResult.path()); - console.log("Type: ", topicResult.type()); - console.log("Value: ", topicResult.value().get()); - }); - - if (fetchResult.hasMore()) { - console.log("There are more topics remaining"); - } - -} - -// example showcasing how to limit the branch depth when fetching topics -export async function fetchRequestLimitBranchDepthExample(): Promise { - - const jsonDataType = datatypes.json(); - const TopicType = topics.TopicType; - - - // Connect to the server. Change these options to suit your own environment. - // Node.js does not accept self-signed certificates by default. If you have - // one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 - // before running this example. - const session: Session = await connect({ - host: 'diffusion.example.com', - port: 443, - secure: true, - principal: 'client', - credentials: 'password' - }); - - const fetchResult: FetchResult - = await session - .fetchRequest() // obtain a FetchRequest - .limitDeepBranches(3, 3) - // A deep branch has a root path that has a - // number of parts equal to the deep_branch_depth parameter. - // The deep_branch_limit specifies the maximum number of results for each deep branch. - .withProperties() // get the topic properties - .topicTypes([TopicType.STRING, TopicType.INT64]) // limit to string and integer topic types - .withValues(jsonDataType) // fetch values return them as JSON objects - .fetch("?.//") // perform the fetch using a topic selector - const results: TopicResult[] = fetchResult.results(); - console.log("Fetch Request returned "+results.length+" topics"); - - results.forEach((topicResult: TopicResult) => { - console.log("Path: ", topicResult.path()); - console.log("Type: ", topicResult.type()); - console.log("Value: ", topicResult.value().get()); - }); - - if (fetchResult.hasMore()) { - console.log("There are more topics remaining"); - } - -} diff --git a/ts/src/jsonSubscription.ts b/ts/src/jsonSubscription.ts deleted file mode 100644 index ee430dac..00000000 --- a/ts/src/jsonSubscription.ts +++ /dev/null @@ -1,55 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -import { connect, datatypes, topics, Session } from 'diffusion'; - -// example showcasing how to receive updates for JSON topics -export async function jsonSubscriptionExample(): Promise { - - // Connect to the server. Change these options to suit your own environment. - // Node.js will not accept self-signed certificates by default. If you have - // one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 - // before running this example. - const session: Session = await connect({ - host: 'diffusion.example.com', - port: 443, - secure: true - }); - - // 1. ValueStreams are the best way to receive values from JSON and Binary topics. - - // Streams for notifications can be registered separately from subscribing to a topic. Registering a stream is a - // local operation and does not change the data the client receives. - - // Like subscribing, streams are registered using a topic selection. Each stream will only receive notifications - // from topics that match the topic selector it is registered with. - - // A ValueStream will only receive notifications from topics that match the topic selector it is registered - // with and that match its DataType. - - // A ValueStream emits a 'value' notification, listeners for 'value' events will be passed the topic path, - // topic specification, the new value of the topic and the previous value. - - // A ValueStream also emits 'open', 'close', 'subscribe' and 'unsubscribe' events. - - session - .addStream('foo', datatypes.json()) - .on('value', function(path, specification, newValue, oldValue) { - console.log('Got JSON update for topic: ' + path, newValue.get()); - }); - - // 2. Subscribe to the "foo" topic. The value stream registered earlier will now start to receive notifications. - session.select('foo'); -} diff --git a/ts/src/messages-filter.ts b/ts/src/messages-filter.ts deleted file mode 100644 index ecd18d92..00000000 --- a/ts/src/messages-filter.ts +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -import { connect, datatypes, topics, Session, SessionId, RequestStream, Responder, FilteredResponseHandler } from 'diffusion'; - -// example showcasing how to send messages to multiple sessions using a filter -export async function messagesFilterExample(): Promise { - - // Connect to the server. Change these options to suit your own environment. - // Node.js will not accept self-signed certificates by default. If you have - // one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 - // before running this example. - const session: Session = await connect({ - host: 'diffusion.example.com', - port: 443, - secure: true, - principal: 'control', - credentials: 'password' - }); - - // Create a request handler that handles strings - const requestSream: RequestStream = { - onRequest: function(path: string, request, responder: Responder) { - console.log('Received request: ' + request); // Log the request - responder.respond('confirmation of request ' + request); - }, - onError: function() { - console.log('An error occurred'); - }, - onClose: function() { - console.log('Handler closed'); - } - }; - - // Register the stream - session.messages.setRequestStream('foo/bar', requestSream); - - // Send a message to another session listening on 'foo' by way of - // session properties. - const responseHandler: FilteredResponseHandler = { - onResponse: function(sessionID: SessionId, response) { - console.log("Received response " + response); - }, - onResponseError: function() { - console.log("There was an error when receiving the response"); - }, - }; - - session.messages.sendRequestToFilter('$Principal is "control"', 'foo/bar', 'Hello world', responseHandler); -} diff --git a/ts/src/messages.ts b/ts/src/messages.ts deleted file mode 100644 index 45b5d5dd..00000000 --- a/ts/src/messages.ts +++ /dev/null @@ -1,82 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -import { connect, datatypes, topics, Session, RequestHandler, Responder, RequestContext } from 'diffusion'; - -// example showcasing how to send messages to a single session -export async function messagesExample(): Promise { - - // Connect to the server. Change these options to suit your own environment. - // Node.js will not accept self-signed certificates by default. If you have - // one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 - // before running this example. - const session: Session = await connect({ - host: 'diffusion.example.com', - port: 443, - secure: true, - principal: 'control', - credentials: 'password' - }); - - // 1. Messages can be sent & received between sessions. - // Create a request handler that handles strings - const handler: RequestHandler = { - onRequest: function(request, context: RequestContext, responder: Responder) { - console.log('Received request: ' + request); // Log the request - responder.respond('confirmation of request ' + request); - }, - onError: function() { - console.log('An error occurred'); - }, - onClose: function() { - console.log('Handler closed'); - } - }; - - try { - - // Register the handler - await session.messages.addRequestHandler('foo/bar', handler); - console.log("Request handler has been added"); - } catch (error) { - console.log('Failed to register request handler: ', error); - } - - // 2. Messages can be sent & received between sessions. - - // Send a message to another session. It is the application's responsibility - // to find the SessionID of the intended recipient. - const responseFoo = await session.messages.sendRequest('foo/bar', 'Hello World', 'another-session-id', datatypes.string(), datatypes.string()); - console.log("Received response " + responseFoo); - - // 3. Messages can also be sent without a recipient, in which case they will be dispatched to any Message Handlers - // that have been registered for the same path. If multiple handlers are registered to the same path, any given - // message will only be dispatched to one handler. - - // Send a message at a lower path, without an explicit recipient - this will be received by the Handler. - const responseBar = await session.messages.sendRequest('foo/bar', 'Hello World', datatypes.string(), datatypes.string()); - console.log("Received response " + responseBar); - - // 4. The datatype of the message and the response can be specified using topic types or omitted altogether. - // In the latter case, the datatype is inferred from the value passed to sendRequest() - - // Send a message using topic types to specify the datatype - const responseBaz = await session.messages.sendRequest('foo/bar', 'Hello World', topics.TopicType.STRING, topics.TopicType.STRING); - console.log("Received response " + responseBaz); - - // Send a message leaving out the datatype - const responseQux = await session.messages.sendRequest('foo/bar', 'Hello World') - console.log("Received response " + responseQux); -} diff --git a/ts/src/missingTopicNotification.ts b/ts/src/missingTopicNotification.ts deleted file mode 100644 index 2f68d3ef..00000000 --- a/ts/src/missingTopicNotification.ts +++ /dev/null @@ -1,76 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -import { connect, datatypes, topics, Session, MissingTopicHandler } from 'diffusion'; - -// example showcasing how to receive notifications when a session subscribes to a topic that -// doesn't exist -export async function missingTopicNotificationExample(): Promise { - - const stringDataType = datatypes.string(); - const TopicType = topics.TopicType; - const TopicSpecification = topics.TopicSpecification; - - // Connect to the server. Change these options to suit your own environment. - // Node.js will not accept self-signed certificates by default. If you have - // one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 - // before running this example. - const session: Session = await connect({ - host: 'diffusion.example.com', - port: 443, - secure: true - }); - - const handler: MissingTopicHandler = { - // Called when a handler is successfully registered - onRegister: function(path, close) { - console.log(`Registered missing topic handler on path: ${path}`); - - // Once we've registered the handler, we subscribe with the selector '?example/topic/.*' - session.select('?example/topic/.*'); - - // Register a stream to listen for a subscription event - session.addStream('?example/topic/.*', stringDataType).on('subscribe', function(topic, specification) { - console.log(`Subscribed to topic: ${topic}`); - }); - }, - // Called when the handler is closed - onClose: function(path) { - console.log(`Missing topic handler on path '${path}' has been closed`); - }, - // Called if there is an error on the handler - onError: function(path, error) { - console.log('Error on missing topic handler'); - }, - // Called when we've received a missing topic notification on our registered handler path - onMissingTopic: function(notification) { - console.log(`Received missing topic notification with selector: ${notification.selector}`); - - // Once we've received the missing topic notification initiated from subscribing to '?example/topic/.*', - // we add a topic that will match the selector - const path = 'example/topic/foo'; - - session.topics.add(path, new TopicSpecification(TopicType.STRING)).then(function(result) { - console.log(`Topic add success: ${path}`); - }, function(reason) { - console.log(`Topic add failed: ${reason}`); - }); - } - }; - - // Register a missing topic handler on the 'example' root topic - // Any subscriptions to missing topics along this path will invoke this handler - session.topics.addMissingTopicHandler('example', handler); -} diff --git a/ts/src/reconnect.ts b/ts/src/reconnect.ts deleted file mode 100644 index 9b04c7ff..00000000 --- a/ts/src/reconnect.ts +++ /dev/null @@ -1,82 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -import { connect, Session } from 'diffusion'; - -// example showcasing how to create a custom reconnection strategy -export async function reconnectExample(): Promise { - - // When establishing a session, it is possible to specify whether reconnection - // should be attempted in the event of an unexpected disconnection. This allows - // the session to recover its previous state. - - // Set the maximum amount of time we'll try and reconnect for to 10 minutes - const maximumTimeoutDuration = 1000 * 60 * 10; - - // Set the maximum interval between reconnect attempts to 60 seconds - const maximumAttemptInterval = 1000 * 60; - - // Set an upper limit to the number of times we'll try to reconnect for - const maximumAttempts = 25; - - // Count the number of reconnection attempts we've made - let attempts = 0; - - // Create a reconnection strategy that applies an exponential back-off - // The strategy will be called with two arguments, start & abort. Both - // of these are functions, which allow the strategy to either start a - // reconnection attempt, or to abort reconnection (which will close the session) - const reconnectionStrategy = (start: () => void, abort: () => void) => { - if (attempts > maximumAttempts) { - abort(); - } else { - const wait = Math.min(Math.pow(2, attempts++) * 100, maximumAttemptInterval); - - // Wait the specified time period, and then start the reconnection attempt - setTimeout(start, wait); - } - }; - - // Connect to the server. - const session: Session = await connect({ - host: 'diffusion.example.com', - port: 443, - secure: true, - principal: 'control', - credentials: 'password', - reconnect: { - timeout: maximumTimeoutDuration, - strategy: reconnectionStrategy - } - }); - - session.on('disconnect', function(reason) { - // This will be called when we lose connection. Because we've specified the - // reconnection strategy, it will be called automatically when this event - // is dispatched - }); - - session.on('reconnect', function() { - // If the session is able to reconnect within the reconnect timeout, this - // event will be dispatched to notify that normal operations may resume - attempts = 0; - }); - - session.on('close', function() { - // If the session is closed normally, or the session is unable to reconnect, - // this event will be dispatched to notify that the session is no longer - // operational. - }); -} diff --git a/ts/src/removeTopicWhenNoSessionIdExist.ts b/ts/src/removeTopicWhenNoSessionIdExist.ts deleted file mode 100644 index 75a793c6..00000000 --- a/ts/src/removeTopicWhenNoSessionIdExist.ts +++ /dev/null @@ -1,64 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -import { connect, datatypes, topics, Session, TopicSpecification } from 'diffusion'; - -// example showcasing how to automatically remove a topic using a topic removal specification -export async function removeTopicExample(): Promise { - - // Connect to the server. Change these options to suit your own environment. - // Node.js does not accept self-signed certificates by default. If you have - // one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 - // before running this example. - const session: Session = await connect({ - host: 'diffusion.example.com', - port: 443, - secure: true, - principal: 'control', - credentials: 'password' - }); - - // Subscribe to topic 'foo' - await session.select("foo"); - - // Register a JSON value stream and listen for subscription/unsubscription events - const stream = session.addStream("foo", datatypes.json()); - stream.on({ - 'subscribe': function (topic, spec) { - console.log("Subscribed to topic: ", topic); - }, - 'unsubscribe': function (topic, spec, reason) { - console.log("Unsubscribed from topic: ", topic); - console.log("Reason: ", reason); - - // Finally close the session - session.close(); - } - }); - - // Remove a topic 2 seconds when no clients with principal 'unknown' - const expression = `when no session has '$Principal is "unknown"' for 2s`; - - // Add a JSON topic type with the REMOVAL topic specification property - const jsonSpec = new topics.TopicSpecification(topics.TopicType.JSON) - .withProperty(topics.TopicSpecification.REMOVAL, expression); - - try { - await session.topics.add("foo", jsonSpec); - console.log("Topic added"); - } catch (error) { - console.log("Failed ", error); - } -} diff --git a/ts/src/removeTopics.ts b/ts/src/removeTopics.ts deleted file mode 100644 index f64dcf52..00000000 --- a/ts/src/removeTopics.ts +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -import { connect, topics, datatypes, Session, TopicSpecification, } from 'diffusion'; - -// example showcasing how to remove topics using session.topics.remove -export async function removeTopicExample(): Promise { - - // Connect to the server. Change these options to suit your own environment. - // Node.js will not accept self-signed certificates by default. If you have - // one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 - // before running this example. - const session: Session = await connect({ - host: 'diffusion.example.com', - port: 443, - secure: true, - principal: 'control', - credentials: 'password' - }); - - const TopicType = topics.TopicType; - - try { - // 1. Like session.topics.add(), remove returns a promise, so we can chain together calls. - await session.topics.add('foo', new TopicSpecification(TopicType.STRING)); - console.log('Added topic foo'); - await session.topics.remove('foo'); - console.log('Removed topic foo'); - } catch (error) { - console.log('Failed to remove topic foo: ', error); - } - - // 2. Removing a topic will not remove any topics underneath it. - - // Add a hierarchy of topics. - await session.topics.add('a', new TopicSpecification(TopicType.STRING)); - await session.topics.add('a/b', new TopicSpecification(TopicType.STRING)); - await session.topics.add('a/b/c', new TopicSpecification(TopicType.STRING)); - await session.topics.add('a/b/c/d', new TopicSpecification(TopicType.STRING)); - - // Wait until we've removed the root topics - await session.topics.remove('a'); - - // Child topic still exists - await session.topicUpdate.set('a/b', datatypes.string(), 'hello'); - - // Removing all topics using a topic selector expression - await session.topics.remove('?a//'); -} diff --git a/ts/src/security.ts b/ts/src/security.ts deleted file mode 100644 index e22e7c0f..00000000 --- a/ts/src/security.ts +++ /dev/null @@ -1,92 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -import { connect, topics, Session, SecurityConfiguration, SystemAuthenticationConfiguration } from 'diffusion'; - - -// example showcasing how to update the security and authentication stores -export async function securityExample(): Promise { - - // Session security allows you to change the principal that a session is authenticated as. It also allows users to - // query and update server-side security and authentication stores, which control users, roles and permissions. - // This enables you to manage the capabilities that any logged in user will have access to. - - // Connect to Diffusion with control client credentials - const session: Session = await connect({ - host: 'diffusion.example.com', - port: 443, - secure: true, - principal: 'control', - credentials: 'password' - }); - - // 1. A session change their principal by re-authenticating - await session.security.changePrincipal('admin', 'password'); - console.log('Authenticated as admin'); - - try { - // 2. The security configuration provides details about roles and their assigned permissions - const config: SecurityConfiguration = await session.security.getSecurityConfiguration(); - console.log('Roles for anonymous sessions: ', config.anonymous); - console.log('Roles for named sessions: ', config.named); - console.log('Available roles: ', config.roles); - } catch(error) { - console.log('Unable to fetch security configuration', error); - } - - // 3. Changes to the security configuration are done with a SecurityScriptBuilder - const securityScriptBuilder = session.security.securityScriptBuilder(); - - // Set the permissions for a particular role - global and topic-scoped - // Each method on a script builder returns a new builder - const setPermissionScript = securityScriptBuilder - .setGlobalPermissions('SUPERUSER', ['REGISTER_HANDLER']) - .setPathPermissions('SUPERUSER', '/foo', ['UPDATE_TOPIC']) - .build(); - - try { - // Update the server-side store with the generated script - await session.security.updateSecurityStore(setPermissionScript); - console.log('Security configuration updated successfully'); - } catch(error) { - console.log('Failed to update security configuration: ', error); - } - - try { - // 4. The system authentication configuration lists all users & roles - const config: SystemAuthenticationConfiguration = await session.security.getSystemAuthenticationConfiguration(); - console.log('System principals: ', config.principals); - console.log('Anonymous sessions: ', config.anonymous); - } catch(error) { - console.log('Unable to fetch system authentication configuration', error); - } - - // 5. Changes to the system authentication config are done with a SystemAuthenticationScriptBuilder - const authenticationScriptBuilder = session.security.authenticationScriptBuilder(); - - // Add a new user and set password & roles. - const addUserScript = authenticationScriptBuilder - .addPrincipal('Superman', 'correcthorsebatterystapler') - .assignRoles('Superman', ['SUPERUSER']) - .build(); - - try { - // Update the system authentication store - await session.security.updateAuthenticationStore(addUserScript); - console.log('Updated system authentication config'); - } catch(error) { - console.log('Failed to update system authentication: ', error); - } -} diff --git a/ts/src/sessionLocks.ts b/ts/src/sessionLocks.ts deleted file mode 100644 index 75b948d1..00000000 --- a/ts/src/sessionLocks.ts +++ /dev/null @@ -1,79 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -import { connect, datatypes, locks, Session, SessionLock } from 'diffusion'; - - -// example showcasing how to acquire and release session locks -export async function sessionLockExample(): Promise { - - const stringDataType = datatypes.string(); - const SessionLockScope = locks.SessionLockScope; - - const LOCK_NAME = "lockA"; - - // Connect to the server. Change these options to suit your own environment. - // Node.js does not accept self-signed certificates by default. If you have - // one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 - // before running this example. - const session1: Session = await connect({ - host: 'diffusion.example.com', - port: 443, - secure: true, - principal: 'control', - credentials: 'password' - }); - - const session2: Session = await connect({ - host: 'diffusion.example.com', - port: 443, - secure: true, - principal: 'control', - credentials: 'password' - }); - - let session1Lock: SessionLock; - let session2Lock: SessionLock; - - async function acquireLockSession1() { - console.log(`Requesting lock ${LOCK_NAME} by session 1`); - session1Lock = await session1.lock(LOCK_NAME, SessionLockScope.UNLOCK_ON_CONNECTION_LOSS); - - console.log(`Acquired lock ${LOCK_NAME} by session 1`); - - // Note: no await - // Not waiting for session 2 to acquire the lock - acquireLockSession2(); - setTimeout(releaseLock1, 1000); - } - - async function acquireLockSession2() { - console.log(`Requesting lock ${LOCK_NAME} by session 2`); - - // this will block until the lock has been released by session 1 in releaseLock1 - session2Lock = await session2.lock(LOCK_NAME, SessionLockScope.UNLOCK_ON_CONNECTION_LOSS); - - console.log(`Acquired lock ${LOCK_NAME} by session 2`); - } - - async function releaseLock1() { - console.log(`Requesting lock ${LOCK_NAME} release by session 1`); - await session1Lock.unlock(); - - console.log(`Released lock ${LOCK_NAME} from session 1`); - } - - acquireLockSession1(); -} diff --git a/ts/src/sessionTrees.ts b/ts/src/sessionTrees.ts deleted file mode 100644 index 1cfa0164..00000000 --- a/ts/src/sessionTrees.ts +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2021 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -import { - connect, - Session, - BranchMappingTable , - newBranchMappingTableBuilder, -} from 'diffusion'; - -// example showcasing how create and query session tree branch mappings -export async function sessionTreesExample(): Promise { - - // Connect to the server. Change these options to suit your own environment. - // Node.js does not accept self-signed certificates by default. If you have - // one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 - // before running this example. - const session: Session = await connect({ - host: 'diffusion.example.com', - port: 443, - secure: true, - principal: 'control', - credentials: 'password' - }); - - const table: BranchMappingTable = newBranchMappingTableBuilder() - .addBranchMapping("$Principal is 'control'", "target/1") - .addBranchMapping("all", "target/2") - .create("topic/path"); - - await session.sessionTrees.putBranchMappingTable(table); - - console.log(`Branch mapping table for session tree branch ${table.getSessionTreeBranch()} has been added`); - - const listSessionTreeBranches: string[] = await session.sessionTrees.getSessionTreeBranchesWithMappings(); - - console.log(`Session tree branches with mappings obtained: ${listSessionTreeBranches.join(', ')}`); - - for (const sessionTreeBranch of listSessionTreeBranches) - { - const branchMappingTable: BranchMappingTable = await session.sessionTrees.getBranchMappingTable(sessionTreeBranch); - - for (const branchMapping of branchMappingTable.getBranchMappings()) - { - console.log(`Session tree branch: '${sessionTreeBranch}', Session filter: '${branchMapping.sessionFilter}', Topic tree branch: '${branchMapping.topicTreeBranch}'`); - } - } -} diff --git a/ts/src/subscription.ts b/ts/src/subscription.ts deleted file mode 100644 index bfdfcf79..00000000 --- a/ts/src/subscription.ts +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -import { connect, datatypes, Session, ValueStream } from 'diffusion'; - -// example showcasing how to subscribe to a topic with a value stream -export async function subscriptionExample(): Promise { - - // Connect to the server. Change these options to suit your own environment. - // Node.js will not accept self-signed certificates by default. If you have - // one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 - // before running this example. - const session: Session = await connect({ - host: 'diffusion.example.com', - port: 443, - secure: true - }); - - // 1. Subscriptions are how sessions receive streams of data from the server. - - // When subscribing, a topic selector is used to select which topics to subscribe to. Topics do not need to exist - // at the time of subscription - the server dynamically resolves subscriptions as topics are added or removed. - - // Subscribe to the "foo" topic - await session.select('foo'); - - // 2. Sessions may unsubscribe from any topic to stop receiving data - - // Unsubscribe from the "foo" topic. Sessions do not need to have previously been subscribed to the topics they are - // unsubscribing from. - await session.unsubscribe('foo'); - - // 3. Subscriptions / Unsubscriptions can select multiple topics using Topic Selectors - - // Topic Selectors provide regex-like capabilities for subscribing to topics. These are resolved dynamically, much - // like subscribing to a single topic. - session.select('?foo/.*/[a-z]'); - - // 4. Register a value stream - const valueStream: ValueStream = session.addStream('baz', datatypes.json()); - - // Receive update values - valueStream.on('value', function(topic, spec, newValue, oldValue) { - console.log('JSON update for topic: ' + topic, newValue.get()); - }); - - // Subscribe to a JSON topic - session.select('baz'); -} diff --git a/ts/src/timeseries.ts b/ts/src/timeseries.ts deleted file mode 100644 index ceb699a4..00000000 --- a/ts/src/timeseries.ts +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -import { connect, datatypes, topics, Session, TopicSpecification, QueryResult } from 'diffusion'; - -// example showcasing how to manage time series topics -export async function timeseriesExample(): Promise { - - const TopicSpecification = topics.TopicSpecification; - const TopicType = topics.TopicType; - const dataType = datatypes.double(); - - // Connect to the server. Change these options to suit your own environment. - // Node.js does not accept self-signed certificates by default. If you have - // one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 - // before running this example. - const session: Session = await connect({ - host: 'diffusion.example.com', - port: 443, - secure: true, - principal: 'control', - credentials: 'password' - }); - - // 1. Create a time series topic specification with events - // of type double - const specification: TopicSpecification = new TopicSpecification(TopicType.TIME_SERIES, { - TIME_SERIES_EVENT_VALUE_TYPE: "double" - }); - - // 2. Create a time series topic - await session.topics.add('topic/timeseries', specification); - - // 3. Register a value stream - session.addStream('topic/timeseries', dataType).on('value', function(topic, specification, newValue, oldValue) { - const value = newValue.toString(); - - console.log(`New value ${newValue.isEditEvent?"edited on":"appended to"} topic: ${value}`); - }); - - // 4. Subscribe - session.select('topic/timeseries'); - - for (let i = 0; i < 10; i++) { - // 4. Append values 0 - 9 to the topic - session.timeseries.append("topic/timeseries", i, dataType); - } - - for (let i = 10; i < 20; i++) { - // 5. Append values 10 - 19 to the topic using a value constructor to specify the datatype - session.timeseries.append("topic/timeseries", i, Number); - } - - // 5. Retrieve the last time series event and edit it - const result: QueryResult = await session.timeseries.rangeQuery().as(dataType).fromLast(1).selectFrom("topic/timeseries"); - session.timeseries.edit("topic/timeseries", result.events[0].sequence, 999, dataType); -} diff --git a/ts/src/topicNotifications.ts b/ts/src/topicNotifications.ts deleted file mode 100644 index 79217f3a..00000000 --- a/ts/src/topicNotifications.ts +++ /dev/null @@ -1,95 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -import { - connect, - Session, - TopicNotificationListener, - TopicSpecification, - TopicNotificationType, - TopicNotificationRegistration -} from 'diffusion'; - -// example showcasing how to fetch topics and their values using session.fetchRequest -export async function fetchRequestExample(): Promise { - - // Connect to the server. Change these options to suit your own environment. - // Node.js does not accept self-signed certificates by default. If you have - // one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 - // before running this example. - const session: Session = await connect({ - host: 'diffusion.example.com', - port: 443, - secure: true, - principal: 'client', - credentials: 'password' - }); - - const TopicNotificationType = session.notifications.TopicNotificationType; - - // A topic notification listener can be used to listen to topic notifications - const topicNotificationListener: TopicNotificationListener = { - // Called when the session receives a notification for a selected topic - onTopicNotification: (path: string, specification: TopicSpecification, type: TopicNotificationType) => { - switch (type) { - case TopicNotificationType.ADDED: - console.log(`Topic ${path} has been added`); - break; - case TopicNotificationType.REMOVED: - console.log(`Topic ${path} has been removed`); - break; - case TopicNotificationType.SELECTED: - console.log(`Topic ${path} existed at the time of the selector registration.`); - break; - case TopicNotificationType.DESELECTED: - console.log(`Topic ${path} has been deselected`); - break; - } - }, - // Called when the session receives a notification for an immediate - // descendant of a selected topic - onDescendantNotification: (path: string, type: TopicNotificationType) => { - switch (type) { - case TopicNotificationType.ADDED: - console.log(`Topic ${path} has been added as a descendant of a selected topic`); - break; - case TopicNotificationType.REMOVED: - console.log(`Topic ${path} has been removed as a descendant of a selected topic`); - break; - case TopicNotificationType.SELECTED: - console.log(`Topic ${path} existed as a descendant of a selected topic at the time of the selector registration.`); - break; - case TopicNotificationType.DESELECTED: - console.log(`Topic ${path} has been deselected as a descendant of a selected topic`); - break; - } - }, - // Called when the listener is closed - onClose: () => { - console.log('Topic notification listener has been closed'); - }, - // Called when an error has occurred - onError(error) { - console.log('An error has occurred'); - } - } - - // register the listener - session.notifications.addListener(topicNotificationListener).then((registration: TopicNotificationRegistration) => { - // select topics - // topic notifications will be emitted on all selected topics - registration.select('?foo/bar//'); - }); -} diff --git a/ts/src/topicUpdate.ts b/ts/src/topicUpdate.ts deleted file mode 100644 index f4871947..00000000 --- a/ts/src/topicUpdate.ts +++ /dev/null @@ -1,145 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -import { connect, datatypes, topics, topicUpdate, updateConstraints, Session, SessionLock } from 'diffusion'; - -// example showcasing how to update topics using session.topicUpdate.set or topic update streams -export async function topicUpdateExample(): Promise { - - const stringDataType = datatypes.string(); - const jsonDataType = datatypes.json(); - const TopicType = topics.TopicType; - - - // Connect to the server. Change these options to suit your own environment. - // Node.js does not accept self-signed certificates by default. If you have - // one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 - // before running this example. - const session: Session = await connect({ - host: 'diffusion.example.com', - port: 443, - secure: true, - principal: 'control', - credentials: 'password' - }); - - - async function basicSetOperation() { - await session.topicUpdate.set('foo_topic', stringDataType, 'hello'); - await session.topicUpdate.set('bar_topic', jsonDataType, {foo: 'foo', qux: 'qux'}) - } - - async function setOperationWithValueConstraint() { - const constraint = updateConstraints().value('hello', stringDataType); - await session.topicUpdate.set('foo_topic', stringDataType, 'world', {constraint}); - } - - async function setOperationWithSessionLockConstraint() { - const sessionLock: SessionLock = await session.lock("lock"); - const constraint = updateConstraints().locked(sessionLock); - - await session.topicUpdate.set('foo_topic', stringDataType, 'lorem ipsum', {constraint}); - } - - async function setOperationWithPartialJSONConstraint() { - const sessionLock: SessionLock = await session.lock("lock"); - const constraint = updateConstraints().jsonValue() - .with('/foo', 'foo', stringDataType) - .without('/bar'); - await session.topicUpdate.set('bar_topic', jsonDataType, {foo:'baz', bar:'bar'}, {constraint}); - } - - async function basicAddAndSetOperation() { - const topicSpec = new topics.TopicSpecification(TopicType.STRING); - await session.topicUpdate.set('baz_topic', stringDataType, 'hello', {specification: topicSpec}); - } - - async function addAndSetOperationWithNoTopicConstraint() { - const topicSpec = new topics.TopicSpecification(TopicType.STRING); - const constraint = updateConstraints().noTopic(); - await session.topicUpdate.set('qux_topic', stringDataType, 'hello', {specification: topicSpec, constraint}); - } - - async function createUpdateStream() { - const stream = session.topicUpdate.newUpdateStreamBuilder() - .build('foo_topic', stringDataType); - await stream.validate(); - await stream.set('hello'); - const cachedValue = stream.get(); - await stream.set('world'); - } - - async function createUpdateStreamWithValueConstraint() { - const constraint = updateConstraints().value('world', stringDataType); - const stream = session.topicUpdate.newUpdateStreamBuilder() - .constraint(constraint) - .build('foo_topic', stringDataType); - await stream.validate(); - await stream.set('hello'); - const cachedValue = stream.get(); - return stream.set('world'); - } - - - async function createUpdateStreamThatAddsTopic() { - const topicSpec = new topics.TopicSpecification(TopicType.STRING); - const stream = session.topicUpdate.newUpdateStreamBuilder() - .specification(topicSpec) - .build('quux_topic', stringDataType); - // the first call to validate() or set() resolves in a TopicCreationResult - const result = await stream.validate(); - if (result === topicUpdate.TopicCreationResult.CREATED) { - console.log('A new topic has been created!'); - } else { - console.log('The topic already existed.'); - } - await stream.set('hello'); - const cachedValue = stream.get(); - await stream.set('world'); - } - - async function createUpdateStreamThatAddsTopicWithNoTopicConstraint() { - const topicSpec = new topics.TopicSpecification(TopicType.STRING); - const constraint = updateConstraints().noTopic(); - const stream = session.topicUpdate.newUpdateStreamBuilder() - .specification(topicSpec) - .constraint(constraint) - .build('quuz_topic', stringDataType); - // the first call to validate() or set() resolves in a TopicCreationResult - const result = await stream.validate(); - if (result === topicUpdate.TopicCreationResult.CREATED) { - console.log('A new topic has been created!'); - } else { - console.log('The topic already existed.'); - } - await stream.set('hello'); - const cachedValue = stream.get(); - await stream.set('world'); - } - - await session.topics.add('foo_topic', TopicType.STRING); - await session.topics.add('bar_topic', TopicType.JSON); - - await basicSetOperation; - await setOperationWithValueConstraint; - await setOperationWithSessionLockConstraint; - await setOperationWithPartialJSONConstraint; - await basicAddAndSetOperation; - await addAndSetOperationWithNoTopicConstraint; - await createUpdateStream; - await createUpdateStreamWithValueConstraint; - await createUpdateStreamThatAddsTopic; - await createUpdateStreamThatAddsTopicWithNoTopicConstraint; -} diff --git a/ts/src/topicViews.ts b/ts/src/topicViews.ts deleted file mode 100644 index 2c9a9423..00000000 --- a/ts/src/topicViews.ts +++ /dev/null @@ -1,68 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2020 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the 'License'); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an 'AS IS' BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -import { connect, topics, Session, TopicView } from 'diffusion'; -let session: Session; - -async function createTopicView(): Promise { - // First create a topic called 'some/topic'. - await session.topics.add('some/topic', topics.TopicType.STRING); - - // Now add a topic view. - // This will create a topic 'other/topic' that mirrors the value of 'some/topic' - await session.topicViews.createTopicView('example-view', 'map ?some/ to other/'); -} - -async function listTopicViews() { - // list all topic views - const views = await session.topicViews.listTopicViews(); - - // show the name and specification of each topic view - console.log('All Topic Views:') - views.forEach((topicView) => { - console.log(`${topicView.name}: ${topicView.specification}`); - }); -} - -async function getTopicView() { - // get a topic view - const topicView: TopicView = await session.topicViews.getTopicView('example-view') as TopicView; - - // show the name and specification of the topic view - console.log('Topic View:'); - console.log(`${topicView.name}: ${topicView.specification}`); -} - -async function removeTopicViews() { - // remove a named topic view - await session.topicViews.removeTopicView('example-view'); -} - -// Connect to the server. Change these options to suit your own environment. -// Node.js does not accept self-signed certificates by default. If you have -// one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 -// before running this example. -connect({ - host : 'diffusion.example.com', - port : 443, - secure : true, - principal : 'control', - credentials : 'password' -}).then(function(sess) { - session = sess; -}).then(createTopicView) - .then(listTopicViews) - .then(getTopicView) - .then(removeTopicViews); diff --git a/ts/src/updateJson.ts b/ts/src/updateJson.ts deleted file mode 100644 index 1f7edaff..00000000 --- a/ts/src/updateJson.ts +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -import { connect, datatypes, topics, Session } from 'diffusion'; - -// example showcasing how to update a JSON topic -export async function updateJsonExample(): Promise { - - // Connect to the server. Change these options to suit your own environment. - // Node.js will not accept self-signed certificates by default. If you have - // one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 - // before running this example. - const session: Session = await connect({ - host: 'diffusion.example.com', - port: 443, - secure: true, - principal: 'control', - credentials: 'password' - }); - - const jsonDataType = datatypes.json(); - const TopicSpecification = topics.TopicSpecification; - const TopicType = topics.TopicType; - - // A session may update any existing topic. Update values must be of the same type as the topic being updated. - - // Add a topic first with topic specification - await session.topics.add('foo', new TopicSpecification(TopicType.JSON)); - - // Update the topic with JSON content - await session.topicUpdate.set('foo', jsonDataType, jsonDataType.from({ "hello": "bar", "foo": "world" })); - - // Update the topic again with JSON converted from a JSON string - await session.topicUpdate.set('foo', jsonDataType, jsonDataType.fromJsonString("{ \"hello\": \"foo\", \"foo\": \"hello\" }")); - - // Update the topic again with a standard JavaScript JSON object - await session.topicUpdate.set('foo', jsonDataType, { hello: "world", foo: "bar" }); -} diff --git a/ts/src/updateRecordContent.ts b/ts/src/updateRecordContent.ts deleted file mode 100644 index 9f94698a..00000000 --- a/ts/src/updateRecordContent.ts +++ /dev/null @@ -1,91 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2019 - 2022 Push Technology Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *******************************************************************************/ - -import { connect, datatypes, topics, Session } from 'diffusion'; - -// example showcasing how to update a RecordV2 topic -export async function updateRecordContentExample(): Promise { - // Connect to the server. Change these options to suit your own environment. - // Node.js will not accept self-signed certificates by default. If you have - // one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 - // before running this example. - const session: Session = await connect({ - host: 'diffusion.example.com', - port: 443, - secure: true, - principal: 'control', - credentials: 'password' - }); - - // Record values allow topics to contain data that conforms to a particular schema. Producing a schema allows new - // values to be easily constructed. - - const TopicSpecification = topics.TopicSpecification; - const TopicType = topics.TopicType; - - const RecordV2DataType = datatypes.recordv2(); - - // 1. Create a new schema using the SchemaBuilder API - const schema = RecordV2DataType.schemaBuilder() - .record("Row1").decimal("Field1", 3).integer("Field2") - .record("Row2").string("Field3") - .build(); - - // 2. To create a RecordV2 topic, use a TopicSpecification with the defined schema - const specification = new TopicSpecification(TopicType.RECORD_V2, { - SCHEMA: schema.asJSON() - }); - - await session.topics.add('topic/record', specification); - - // 3. Produce RecordV2 values from the schema by creating a mutable model - const model = schema.createMutableModel(); - - model.set("Row1.Field1", "123.456"); - model.set("Row1.Field2", "789"); - model.set("Row2.Field3", "Hello world"); - - session.topicUpdate.set('topic/record', RecordV2DataType, model.asValue()); - - // 4. Subsequent updates can be produced from the same model - - model.set("Row2.Field3", "Hello everybody"); - - session.topicUpdate.set('topic/record', RecordV2DataType, model.asValue()); - - - // RecordV2 values can be easily consumed, too - session - .addStream('topic/record', RecordV2DataType) - .on('value', (topic, specification, newValue, oldValue) => { - // 5. The schema can be used to produce a model that allows key-based lookup of records and fields - const model = newValue.asModel(schema); - - const f1 = model.get("Row1.Field1"); - const f2 = model.get("Row1.Field2"); - const f3 = model.get("Row2.Field3"); - - console.log(`Field1: ${f1} Field2: ${f2} Field3: ${f3}`); - - // 6. If the schema is not known, it is possible to iterate across the received records and fields - for (const record of newValue.asRecords()) { - for (const field of record) { - console.log("Field value: " + field); - } - } - }); - - session.select('topic/record'); -} diff --git a/ts/timeseries/append-timeseries-topic-with-timestamp.ts b/ts/timeseries/append-timeseries-topic-with-timestamp.ts new file mode 100644 index 00000000..79c0f942 --- /dev/null +++ b/ts/timeseries/append-timeseries-topic-with-timestamp.ts @@ -0,0 +1,67 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { expectTimeseriesDoubleTopicToHaveValues } from '../../../test/util'; +/// end::log + +export async function timeSeriesAppendUserSuppliedTimestamp(): Promise { + /// tag::log + const values: number[] = []; + /// end::log + /// tag::time_series_append_user_supplied_timestamp[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.TIME_SERIES, { + 'TIME_SERIES_EVENT_VALUE_TYPE': 'double', + 'TIME_SERIES_RETAINED_RANGE': 'limit 15 last 10s', + 'TIME_SERIES_SUBSCRIPTION_RANGE': 'limit 3' + }); + + await session.topics.add('my/time/series/topic/path/user/supplied', specification); + + let timestamp = 1000001; + for (let count = 0; count < 25; count++) { + const value = Math.random(); + await session.timeseries.append( + 'my/time/series/topic/path/user/supplied', + value, + datatypes.double(), + timestamp + ); + /// tag::log + values.push(value); + /// end::log + timestamp++; + } + + await session.closeSession(); + /// end::time_series_append_user_supplied_timestamp[] + /// tag::log + const timestamps = values.map((_, i) => 1000001 + i); + await expectTimeseriesDoubleTopicToHaveValues( + 'my/time/series/topic/path/user/supplied', + values.slice(-15), + timestamps.slice(-15) + ); + /// end::log +} diff --git a/ts/timeseries/append-timeseries-topic.ts b/ts/timeseries/append-timeseries-topic.ts new file mode 100644 index 00000000..0ef47a57 --- /dev/null +++ b/ts/timeseries/append-timeseries-topic.ts @@ -0,0 +1,66 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { expectTimeseriesDoubleTopicToHaveValues } from '../../../test/util'; +/// end::log + +export async function timeSeriesAppendValue(): Promise { + /// tag::log + const values: number[] = []; + /// end::log + /// tag::time_series_append_value[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.TIME_SERIES, { + 'TIME_SERIES_EVENT_VALUE_TYPE': 'double', + 'TIME_SERIES_RETAINED_RANGE': 'limit 15 last 10s', + 'TIME_SERIES_SUBSCRIPTION_RANGE': 'limit 3' + }); + + const addResult = await session.topics.add('my/time/series/topic/path', specification); + if (addResult.added) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(addResult.added).toBeTrue(); + /// end::log + + for (let count = 0; count < 25; count++) { + const value = Math.random(); + await session.timeseries.append('my/time/series/topic/path', value, datatypes.double()); + /// tag::log + values.push(value); + /// end::log + } + + await session.closeSession(); + /// end::time_series_append_value[] + /// tag::log + await expectTimeseriesDoubleTopicToHaveValues( + 'my/time/series/topic/path', + values.slice(-15) + ); + /// end::log +} diff --git a/ts/timeseries/append-timeseries-update-stream.ts b/ts/timeseries/append-timeseries-update-stream.ts new file mode 100644 index 00000000..6777aeb7 --- /dev/null +++ b/ts/timeseries/append-timeseries-update-stream.ts @@ -0,0 +1,58 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { expectTimeseriesDoubleTopicToHaveValues } from '../../../test/util'; +/// end::log + +export async function timeSeriesAppendValueViaUpdateStream(): Promise { + const values: number[] = []; + /// tag::time_series_append_value_via_update_stream[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.TIME_SERIES, { + 'TIME_SERIES_EVENT_VALUE_TYPE': 'double', + 'TIME_SERIES_RETAINED_RANGE': 'limit 15 last 10s', + 'TIME_SERIES_SUBSCRIPTION_RANGE': 'limit 3' + }); + + await session.topics.add('my/time/series/topic/path', specification); + + const updateStream = session.topicUpdate.newUpdateStreamBuilder() + .build('my/time/series/topic/path', datatypes.double()); + for (let count = 0; count < 25; count++) { + const value = Math.random(); + await updateStream.set(value); + /// tag::log + values.push(value); + /// end::log + } + + await session.closeSession(); + /// end::time_series_append_value_via_update_stream[] + /// tag::log + await expectTimeseriesDoubleTopicToHaveValues( + 'my/time/series/topic/path', + values.slice(-15) + ); + /// end::log +} diff --git a/ts/timeseries/create-timeseries-topic.ts b/ts/timeseries/create-timeseries-topic.ts new file mode 100644 index 00000000..b404d515 --- /dev/null +++ b/ts/timeseries/create-timeseries-topic.ts @@ -0,0 +1,52 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, topics } from 'diffusion'; +/// tag::log +import { expectTopicExists } from '../../../test/util'; +/// end::log + +export async function timeSeriesCreateTopic(): Promise { + /// tag::time_series_create_topic[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.TIME_SERIES, { + 'TIME_SERIES_EVENT_VALUE_TYPE': 'double', + 'TIME_SERIES_RETAINED_RANGE': 'limit 15 last 10s', + 'TIME_SERIES_SUBSCRIPTION_RANGE': 'limit 3' + }); + + const addResult = await session.topics.add('my/time/series/topic/path', specification); + if (addResult.added) { + console.log('Topic has been created.'); + } else { + console.log('Topic already exists.'); + } + /// tag::log + expect(addResult.added).toBeTrue(); + /// end::log + + await session.closeSession(); + /// end::time_series_create_topic[] + /// tag::log + await expectTopicExists('my/time/series/topic/path'); + /// end::log +} diff --git a/ts/timeseries/edit-timeseries-topic.ts b/ts/timeseries/edit-timeseries-topic.ts new file mode 100644 index 00000000..69ef6a7e --- /dev/null +++ b/ts/timeseries/edit-timeseries-topic.ts @@ -0,0 +1,73 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, EventMetadata, topics } from 'diffusion'; +/// tag::log +import { expectTimeseriesDoubleTopicToHaveValues } from '../../../test/util'; +/// end::log + +export async function timeSeriesEditValue(): Promise { + /// tag::log + const values: number[] = []; + /// end::log + /// tag::time_series_edit_value[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.TIME_SERIES, { + 'TIME_SERIES_EVENT_VALUE_TYPE': 'double', + 'TIME_SERIES_RETAINED_RANGE': 'limit 15 last 10s', + 'TIME_SERIES_SUBSCRIPTION_RANGE': 'limit 3' + }); + + await session.topics.add('my/time/series/topic/path', specification); + + const metaData: EventMetadata[] = []; + for (let count = 0; count < 25; count++) { + const value = Math.random(); + const result = await session.timeseries.append( + 'my/time/series/topic/path', + value, + datatypes.double() + ); + metaData.push(result); + /// tag::log + values.push(value); + /// end::log + } + + const eventToEdit = metaData[20]; + await session.timeseries.edit( + 'my/time/series/topic/path', + eventToEdit.sequence, + 3.14, + datatypes.double() + ); + + await session.closeSession(); + /// end::time_series_edit_value[] + /// tag::log + values[20] = 3.14; + await expectTimeseriesDoubleTopicToHaveValues( + 'my/time/series/topic/path', + values.slice(-14) + ); + /// end::log +} diff --git a/ts/timeseries/range-query-timeseries-topic.ts b/ts/timeseries/range-query-timeseries-topic.ts new file mode 100644 index 00000000..8ba2bd4d --- /dev/null +++ b/ts/timeseries/range-query-timeseries-topic.ts @@ -0,0 +1,87 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, EventMetadata, topics } from 'diffusion'; + +export async function timeSeriesRangeQuery(): Promise { + /// tag::log + const values = []; + /// end::log + /// tag::time_series_range_query[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.TIME_SERIES, { + 'TIME_SERIES_EVENT_VALUE_TYPE': 'double', + 'TIME_SERIES_RETAINED_RANGE': 'limit 50 last 120s', + 'TIME_SERIES_SUBSCRIPTION_RANGE': 'limit 3' + }); + + await session.topics.add('my/time/series/topic/path', specification); + + const metaData: EventMetadata[] = []; + for (let count = 0; count < 25; count++) { + const value = Math.random(); + const result = await session.timeseries.append( + 'my/time/series/topic/path', + value, + datatypes.double() + ); + metaData.push(result); + /// tag::log + values.push(value); + /// end::log + } + + const eventToEdit = metaData[10]; + await session.timeseries.edit( + 'my/time/series/topic/path', + eventToEdit.sequence, + 3.14, + datatypes.double() + ); + + const queryResult = await session.timeseries.rangeQuery() + .from(metaData[5].sequence) + .to(metaData[15].sequence) + .selectFrom('my/time/series/topic/path'); + /// tag::log + let count = 0; + expect(queryResult.events.length).toBe(11); + /// end::log + for (const event of queryResult.events) { + const value = datatypes.double().readValue(event.value); + console.log(`${event.sequence} (${event.timestamp}): ${value}`); + /// tag::log + if (count === 5) { + expect(value).toBe(3.14); + expect(event.sequence).toBe(25); + } else { + expect(value).toBe(values[5 + count]); + expect(event.sequence).toBe(metaData[5 + count].sequence); + expect(event.timestamp).toBe(metaData[5 + count].timestamp); + } + count++; + /// end::log + } + + await session.closeSession(); + /// end::time_series_range_query[] +} diff --git a/ts/timeseries/subscribe-timeseries-topic-cross-compatible.ts b/ts/timeseries/subscribe-timeseries-topic-cross-compatible.ts new file mode 100644 index 00000000..20777275 --- /dev/null +++ b/ts/timeseries/subscribe-timeseries-topic-cross-compatible.ts @@ -0,0 +1,94 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester, promiseWithResolvers } from '../../../test/util' +/// end::log + +export async function timeSeriesSubscribeCrossCompatible(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Subscribed to my/time/series/topic/path'] + ]); + + const valuePromise = promiseWithResolvers(); + let valueCount = 0; + let oldValue = 'undefined'; + /// end::log + /// tag::time_series_subscribe_cross_compatible[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.TIME_SERIES, { + 'TIME_SERIES_EVENT_VALUE_TYPE': 'double', + 'TIME_SERIES_RETAINED_RANGE': 'limit 15 last 10s', + 'TIME_SERIES_SUBSCRIPTION_RANGE': 'limit 3' + }); + + await session.topics.add('my/time/series/topic/path', specification); + + const jsonValueStream = session.addStream('my/time/series/topic/path', datatypes.json()); + jsonValueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + /// tag::log + close : () => { + check.log(`Closed`); + }, + /// end::log + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${oldValue?.get()} to ${newValue.get()}`); + /// tag::log + if (++valueCount >= 25) { + valuePromise.resolve(); + } + check.log(`${topic} changed from ${oldValue?.get()} to ${newValue.get()}`); + /// end::log + } + }); + + await session.select('?my/time/series//'); + + for (let count = 0; count < 25; count++) { + const value = Math.random(); + /// tag::log + check.appendExpected([`my/time/series/topic/path changed from ${oldValue} to ${value}`]); + oldValue = `${value}`; + /// end::log + await session.timeseries.append('my/time/series/topic/path', value, datatypes.double()); + } + /// tag::log + check.appendExpected([`Closed`]); + await valuePromise.promise; + /// end::log + await session.closeSession(); + /// end::time_series_subscribe_cross_compatible[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/timeseries/subscribe-timeseries-topic.ts b/ts/timeseries/subscribe-timeseries-topic.ts new file mode 100644 index 00000000..a98e7adc --- /dev/null +++ b/ts/timeseries/subscribe-timeseries-topic.ts @@ -0,0 +1,98 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester, promiseWithResolvers } from '../../../test/util'; +/// end::log + +export async function timeSeriesSubscribe(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Subscribed to my/time/series/topic/path'], + ]); + + const valuePromise = promiseWithResolvers(); + let valueCount = 0; + let oldValue = 'undefined'; + /// end::log + /// tag::time_series_subscribe[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.TIME_SERIES, { + 'TIME_SERIES_EVENT_VALUE_TYPE': 'double', + 'TIME_SERIES_RETAINED_RANGE': 'limit 15 last 10s', + 'TIME_SERIES_SUBSCRIPTION_RANGE': 'limit 3' + }); + + await session.topics.add('my/time/series/topic/path', specification); + + const valueStream = session.addStream( + 'my/time/series/topic/path', + datatypes.timeseries(datatypes.double()) + ); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + /// tag::log + close : () => { + check.log(`Closed`); + }, + /// end::log + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${oldValue?.value} to ${newValue.value}`); + /// tag::log + if (++valueCount >= 25) { + valuePromise.resolve(); + } + check.log(`${topic} changed from ${oldValue?.value} to ${newValue.value}`); + /// end::log + } + }); + + await session.select('?my/time/series//'); + + for (let count = 0; count < 25; count++) { + const value = Math.random(); + /// tag::log + check.appendExpected([`my/time/series/topic/path changed from ${oldValue} to ${value}`]); + oldValue = `${value}`; + /// end::log + await session.timeseries.append('my/time/series/topic/path', value, datatypes.double()); + } + + /// tag::log + check.appendExpected([`Closed`]); + await valuePromise.promise; + /// end::log + await session.closeSession(); + /// end::time_series_subscribe[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/tsconfig.json b/ts/tsconfig.json deleted file mode 100644 index 2ef3f3e3..00000000 --- a/ts/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions" : { - "target" : "es5", - "module" : "commonjs", - "outDir" : "./target/build/js", - "baseUrl" : ".", - "sourceMap" : false, - "noImplicitAny" : false, - "allowJs" : false, - "declaration" : false, - "strictNullChecks": true, - "downlevelIteration": true, - "lib": [ - "es6", - "es2017.object" - ], - "traceResolution": false - }, - "include": [ - "./src/**/*.ts", - ], - "exclude" : [] -} diff --git a/ts/wrangling/session-trees/get-branch-mapping-table.ts b/ts/wrangling/session-trees/get-branch-mapping-table.ts new file mode 100644 index 00000000..a0775ea4 --- /dev/null +++ b/ts/wrangling/session-trees/get-branch-mapping-table.ts @@ -0,0 +1,77 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, newBranchMappingTableBuilder, Session } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester } from '../../../../test/util'; +/// end::log + +export async function sessionTreesGetBranchMappingTable(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'my/personal/path', + '$Principal is "admin": my/topic/path/for/admin', + '$Principal is "control": my/topic/path/for/control', + '$Principal is "": my/topic/path/for/anonymous', + 'my/alternate/path', + '$Transport is "WEBSOCKET": my/alternate/path/for/websocket', + '$Transport is "HTTP_LONG_POLL": my/alternate/path/for/http', + '$Transport is "TCP": my/alternate/path/for/tcp' + ]]); + /// end::log + /// tag::session_trees_get_branch_mapping_table[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const branchMappingTable1 = newBranchMappingTableBuilder() + .addBranchMapping('$Principal is "admin"', 'my/topic/path/for/admin') + .addBranchMapping('$Principal is "control"', 'my/topic/path/for/control') + .addBranchMapping('$Principal is ""', 'my/topic/path/for/anonymous') + .create('my/personal/path'); + await session.sessionTrees.putBranchMappingTable(branchMappingTable1); + + const branchMappingTable2 = newBranchMappingTableBuilder() + .addBranchMapping('$Transport is "WEBSOCKET"', 'my/alternate/path/for/websocket') + .addBranchMapping('$Transport is "HTTP_LONG_POLL"', 'my/alternate/path/for/http') + .addBranchMapping('$Transport is "TCP"', 'my/alternate/path/for/tcp') + .create('my/alternate/path'); + await session.sessionTrees.putBranchMappingTable(branchMappingTable2); + + const sessionTrees = await session.sessionTrees.getSessionTreeBranchesWithMappings(); + for (const sessionTreeBranch of sessionTrees) { + console.log(`${sessionTreeBranch}:`); + /// tag::log + check.log(sessionTreeBranch); + /// end::log + const mappingTable = await session.sessionTrees.getBranchMappingTable(sessionTreeBranch); + for (const branchMapping of mappingTable.getBranchMappings()) { + console.log(` ${branchMapping.sessionFilter}: ${branchMapping.topicTreeBranch}`); + /// tag::log + check.log(`${branchMapping.sessionFilter}: ${branchMapping.topicTreeBranch}`); + /// end::log + } + } + + await session.closeSession(); + /// end::session_trees_get_branch_mapping_table[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/wrangling/session-trees/list-session-tree-branches-with-mappings.ts b/ts/wrangling/session-trees/list-session-tree-branches-with-mappings.ts new file mode 100644 index 00000000..352007db --- /dev/null +++ b/ts/wrangling/session-trees/list-session-tree-branches-with-mappings.ts @@ -0,0 +1,64 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, newBranchMappingTableBuilder, Session } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester } from '../../../../test/util'; +/// end::log + +export async function sessionTreesListSessionTreeBranchesWithMappings(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'my/personal/path', + 'my/alternate/path', + ]]); + /// end::log + /// tag::session_trees_list_session_tree_branches_with_mappings[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const branchMappingTable1 = newBranchMappingTableBuilder() + .addBranchMapping('$Principal is "admin"', 'my/topic/path/for/admin') + .addBranchMapping('$Principal is "control"', 'my/topic/path/for/control') + .addBranchMapping('$Principal is ""', 'my/topic/path/for/anonymous') + .create('my/personal/path'); + await session.sessionTrees.putBranchMappingTable(branchMappingTable1); + + const branchMappingTable2 = newBranchMappingTableBuilder() + .addBranchMapping('$Transport is "WEBSOCKET"', 'my/alternate/path/for/websocket') + .addBranchMapping('$Transport is "HTTP_LONG_POLL"', 'my/alternate/path/for/http') + .addBranchMapping('$Transport is "TCP"', 'my/alternate/path/for/tcp') + .create('my/alternate/path'); + await session.sessionTrees.putBranchMappingTable(branchMappingTable2); + + const sessionTrees = await session.sessionTrees.getSessionTreeBranchesWithMappings(); + for (const sessionTree of sessionTrees) { + console.log(sessionTree); + /// tag::log + check.log(sessionTree); + /// end::log + } + + await session.closeSession(); + /// end::session_trees_list_session_tree_branches_with_mappings[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/wrangling/session-trees/put-branch-mapping-table.ts b/ts/wrangling/session-trees/put-branch-mapping-table.ts new file mode 100644 index 00000000..d28afba2 --- /dev/null +++ b/ts/wrangling/session-trees/put-branch-mapping-table.ts @@ -0,0 +1,56 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, newBranchMappingTableBuilder } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester } from '../../../../test/util'; +/// end::log + +export async function sessionTreesPutBranchMappingTable(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + '$Principal is "admin": my/topic/path/for/admin', + '$Principal is "control": my/topic/path/for/control', + '$Principal is "": my/topic/path/for/anonymous' + ]]); + /// end::log + /// tag::session_trees_put_branch_mapping_table[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const branchMappingTable = newBranchMappingTableBuilder() + .addBranchMapping('$Principal is "admin"', 'my/topic/path/for/admin') + .addBranchMapping('$Principal is "control"', 'my/topic/path/for/control') + .addBranchMapping('$Principal is ""', 'my/topic/path/for/anonymous') + .create('my/personal/path'); + await session.sessionTrees.putBranchMappingTable(branchMappingTable); + /// tag::log + const mappingTable = await session.sessionTrees.getBranchMappingTable('my/personal/path'); + for (const branchMapping of mappingTable.getBranchMappings()) { + check.log(`${branchMapping.sessionFilter}: ${branchMapping.topicTreeBranch}`); + } + /// end::log + + await session.closeSession(); + /// end::session_trees_put_branch_mapping_table[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/wrangling/session-trees/put-remove-branch-mapping-table.ts b/ts/wrangling/session-trees/put-remove-branch-mapping-table.ts new file mode 100644 index 00000000..29f7c561 --- /dev/null +++ b/ts/wrangling/session-trees/put-remove-branch-mapping-table.ts @@ -0,0 +1,64 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, newBranchMappingTableBuilder } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester } from '../../../../test/util'; +/// end::log + +export async function sessionTreesPutAndRemoveBranchMappingTable(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + '$Principal is "admin": my/topic/path/for/admin', + '$Principal is "control": my/topic/path/for/control', + '$Principal is "": my/topic/path/for/anonymous' + ]]); + /// end::log + /// tag::session_trees_put_and_remove_branch_mapping_table[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const branchMappingTable = newBranchMappingTableBuilder() + .addBranchMapping('$Principal is "admin"', 'my/topic/path/for/admin') + .addBranchMapping('$Principal is "control"', 'my/topic/path/for/control') + .addBranchMapping('$Principal is ""', 'my/topic/path/for/anonymous') + .create('my/personal/path'); + await session.sessionTrees.putBranchMappingTable(branchMappingTable); + /// tag::log + const mappingTable = await session.sessionTrees.getBranchMappingTable('my/personal/path'); + for (const branchMapping of mappingTable.getBranchMappings()) { + check.log(`${branchMapping.sessionFilter}: ${branchMapping.topicTreeBranch}`); + } + /// end::log + + const emptyBranchMappingTable = newBranchMappingTableBuilder() + .create('my/personal/path'); + await session.sessionTrees.putBranchMappingTable(emptyBranchMappingTable); + /// tag::log + const mappingTable2 = await session.sessionTrees.getBranchMappingTable('my/personal/path'); + expect(mappingTable2.getBranchMappings().length).toBe(0); + /// end::log + + await session.closeSession(); + /// end::session_trees_put_and_remove_branch_mapping_table[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/wrangling/session-trees/use-case.ts b/ts/wrangling/session-trees/use-case.ts new file mode 100644 index 00000000..4293baa2 --- /dev/null +++ b/ts/wrangling/session-trees/use-case.ts @@ -0,0 +1,164 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, newBranchMappingTableBuilder, Session, topics } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester, promiseWithResolvers } from '../../../../test/util'; +/// end::log + +export async function sessionTreesUseCase(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Session1 subscribed to my/personal/path', + 'Session2 subscribed to my/personal/path', + 'Session1 value changed to Good morning Administrator', + 'Session2 value changed to Good night Anonymous', + ]]); + const promiseValue1 = promiseWithResolvers(); + const promiseValue2 = promiseWithResolvers(); + /// end::log + /// tag::session_trees_use_case[] + let session: Session; + try { + // Connect to the server. + session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + } catch (err) { + console.error('Connection could not be established.', err); + throw err; + } + + const specification = new topics.TopicSpecification(topics.TopicType.STRING); + try { + await session.topicUpdate.set( + 'my/topic/path/for/admin', + datatypes.string(), + 'Good morning Administrator', + { specification: specification } + ); + + await session.topicUpdate.set( + 'my/topic/path/for/control', + datatypes.string(), + 'Good afternoon Control Client', + { specification: specification } + ); + + await session.topicUpdate.set( + 'my/topic/path/for/anonymous', + datatypes.string(), + 'Good night Anonymous', + { specification: specification } + ); + } catch (err) { + console.error('Topic values could not be set.', err); + throw err; + } + + try { + const branchMappingTable = newBranchMappingTableBuilder() + .addBranchMapping('$Principal is "admin"', 'my/topic/path/for/admin') + .addBranchMapping('$Principal is "control"', 'my/topic/path/for/control') + .addBranchMapping('$Principal is ""', 'my/topic/path/for/anonymous') + .create('my/personal/path'); + await session.sessionTrees.putBranchMappingTable(branchMappingTable); + } catch (err) { + console.error('Could not put branch mapping table', err); + } + + const valueStream = session.addStream('my/personal/path', datatypes.string()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Session1 subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${oldValue} to ${newValue}`); + /// tag::log + check.log(`Session1 value changed to ${newValue}`); + promiseValue1.resolve(); + /// end::log + } + }); + + try { + await session.select('my/personal/path'); + } catch (err) { + console.error('Could not select topic.', err); + throw err; + } + + let session2: Session; + try { + // Connect to the server. + session2 = await connect({ + host: 'localhost', + port: 8080 + }); + } catch (err) { + console.error('Connection could not be established.', err); + throw err; + } + + const valueStream2 = session2.addStream('my/personal/path', datatypes.string()); + valueStream2.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Session2 subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${oldValue} to ${newValue}`); + /// tag::log + check.log(`Session2 value changed to ${newValue}`); + promiseValue2.resolve(); + /// end::log + } + }); + + try { + await session2.select('my/personal/path'); + } catch (err) { + console.error('Could not select topic.', err); + throw err; + } + + /// tag::log + await Promise.all([promiseValue1.promise, promiseValue2.promise]); + /// end::log + try { + await session.closeSession(); + await session2.closeSession(); + } catch (err) { + console.error('An error occurred when closing session.', err); + } + /// end::session_trees_use_case[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/wrangling/topic-views/api/add-topic-view.ts b/ts/wrangling/topic-views/api/add-topic-view.ts new file mode 100644 index 00000000..689dd469 --- /dev/null +++ b/ts/wrangling/topic-views/api/add-topic-view.ts @@ -0,0 +1,56 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue, expectTopicCounts } from '../../../../../test/util'; +/// end::log + +export async function topicViewsApiAdd(): Promise { + /// tag::topic_views_api_add[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + const jsonData = datatypes.json().from({ diffusion: 'data' }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { specification: specification } + ); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + 'map my/topic/path to views/' + ); + console.log(`Topic View ${topicView.name} has been created.`); + /// tag::log + await expectJsonTopicToHaveValue('views/my/topic/path', { diffusion: 'data' }); + /// end::log + + await session.topicViews.removeTopicView('topic_view_1'); + + await session.closeSession(); + /// end::topic_views_api_add[] + /// tag::log + await expectTopicCounts({ 'views/my/topic/path': 0 }); + /// end::log +} diff --git a/ts/wrangling/topic-views/api/list-topic-views.ts b/ts/wrangling/topic-views/api/list-topic-views.ts new file mode 100644 index 00000000..8b4bb546 --- /dev/null +++ b/ts/wrangling/topic-views/api/list-topic-views.ts @@ -0,0 +1,86 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { expectTopicCounts, PartiallyOrderedCheckpointTester } from '../../../../../test/util'; +/// end::log + +export async function topicViewsApiList(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ + 'Topic View topic_view_1: map my/topic/path to views/ (ADMINISTRATOR)', + 'Topic View topic_view_2: map my/topic/path/array to views/ (ADMINISTRATOR)' + ] + ]); + /// end::log + /// tag::topic_views_api_list[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + const jsonData = datatypes.json().from({ diffusion: 'data' }); + + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { specification: specification } + ); + + const topicView1 = await session.topicViews.createTopicView( + 'topic_view_1', + 'map my/topic/path to views/' + ); + console.log(`Topic View ${topicView1.name} has been created.`); + + await session.topicUpdate.set( + 'my/topic/path/array', + datatypes.json(), + jsonData, + { specification: specification } + ); + + const topicView2 = await session.topicViews.createTopicView( + 'topic_view_2', + 'map my/topic/path/array to views/' + ); + console.log(`Topic View ${topicView2.name} has been created.`); + + const topicViews = await session.topicViews.listTopicViews(); + for (const topicView of topicViews) { + console.log(`Topic View ${topicView.name}: ${topicView.specification} (${[...topicView.roles]})`); + /// tag::log + check.log(`Topic View ${topicView.name}: ${topicView.specification} (${[...topicView.roles]})`); + /// end::log + } + + await session.closeSession(); + /// end::topic_views_api_list[] + /// tag::log + await expectTopicCounts({ + 'views/my/topic/path': 1, + 'views/my/topic/path/array': 1, + + }); + await check.done(); + /// end::log +} diff --git a/ts/wrangling/topic-views/api/remove-topic-views.ts b/ts/wrangling/topic-views/api/remove-topic-views.ts new file mode 100644 index 00000000..4b464b27 --- /dev/null +++ b/ts/wrangling/topic-views/api/remove-topic-views.ts @@ -0,0 +1,100 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } from '../../../../../test/util'; +/// end::log + +export async function topicViewsApiRemove(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ + 'Topic View topic_view_1: map my/topic/path to views/ (ADMINISTRATOR)', + 'Topic View topic_view_2: map my/topic/path/array to views/ (ADMINISTRATOR)' + ], + [ + 'Topic View topic_view_2: map my/topic/path/array to views/ (ADMINISTRATOR)' + ] + ]); + /// end::log + /// tag::topic_views_api_remove[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + const jsonData = datatypes.json().from({ diffusion: 'data' }); + + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { specification: specification } + ); + + const topicView1 = await session.topicViews.createTopicView( + 'topic_view_1', + 'map my/topic/path to views/' + ); + console.log(`Topic View ${topicView1.name} has been created.`); + /// tag::log + await expectJsonTopicToHaveValue('views/my/topic/path', { diffusion: 'data' }); + /// end::log + + await session.topicUpdate.set( + 'my/topic/path/array', + datatypes.json(), + jsonData, + { specification: specification } + ); + + const topicView2 = await session.topicViews.createTopicView( + 'topic_view_2', + 'map my/topic/path/array to views/' + ); + console.log(`Topic View ${topicView2.name} has been created.`); + /// tag::log + await expectJsonTopicToHaveValue('views/my/topic/path/array', { diffusion: 'data' }); + /// end::log + + const topicViews1 = await session.topicViews.listTopicViews(); + for (const topicView of topicViews1) { + console.log(`Topic View ${topicView.name}: ${topicView.specification} (${[...topicView.roles]})`); + /// tag::log + check.log(`Topic View ${topicView.name}: ${topicView.specification} (${[...topicView.roles]})`); + /// end::log + } + + await session.topicViews.removeTopicView('topic_view_1'); + + const topicViews2 = await session.topicViews.listTopicViews(); + for (const topicView of topicViews2) { + console.log(`Topic View ${topicView.name}: ${topicView.specification} (${[...topicView.roles]})`); + /// tag::log + check.log(`Topic View ${topicView.name}: ${topicView.specification} (${[...topicView.roles]})`); + /// end::log + } + + await session.closeSession(); + /// end::topic_views_api_remove[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/wrangling/topic-views/dsl/expand-value.ts b/ts/wrangling/topic-views/dsl/expand-value.ts new file mode 100644 index 00000000..d02973f1 --- /dev/null +++ b/ts/wrangling/topic-views/dsl/expand-value.ts @@ -0,0 +1,80 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } from '../../../../../test/util'; +/// end::log + +export async function topicViewsDslExpandValue(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/currency0', + 'Subscribed to views/currency1', + 'Subscribed to views/currency2', + 'Subscribed to views/currency3' + ]]); + /// end::log + /// tag::topic_views_dsl_expand_value[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + const jsonData = datatypes.json().from({ + currencies: ['USD', 'GBP', 'EUR', 'CHF'] + }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + 'map my/topic/path to views/currency' + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_expand_value[] + /// tag::log + await expectJsonTopicToHaveValue('views/currency0', 'USD'); + await expectJsonTopicToHaveValue('views/currency1', 'GBP'); + await expectJsonTopicToHaveValue('views/currency2', 'EUR'); + await expectJsonTopicToHaveValue('views/currency3', 'CHF'); + + await check.done(); + /// end::log +} diff --git a/ts/wrangling/topic-views/dsl/insert-transformations.ts b/ts/wrangling/topic-views/dsl/insert-transformations.ts new file mode 100644 index 00000000..2ac129a0 --- /dev/null +++ b/ts/wrangling/topic-views/dsl/insert-transformations.ts @@ -0,0 +1,103 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, Session, topics } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } from '../../../../../test/util'; +/// end::log + +export async function topicViewsDslInsertTransformations(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/the_flintstones' + ]]); + /// end::log + /// tag::topic_views_dsl_insert_transformations[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + + const jsonData1 = datatypes.json().from([ + 'Fred Flintstone', + 'Wilma Flintstone', + 'Barney Rubble', + 'Betty Rubble' + ]); + await session.topicUpdate.set( + 'my/topic/path/original_cast', + datatypes.json(), + jsonData1, + { specification: specification } + ); + const jsonData2 = datatypes.json().from('Pebbles Flintstone'); + await session.topicUpdate.set( + 'my/topic/path/additional_cast/1', + datatypes.json(), + jsonData2, + { specification: specification } + ); + + const jsonData3 = datatypes.json().from('Bamm-Bamm Rubble'); + await session.topicUpdate.set( + 'my/topic/path/additional_cast/2', + datatypes.json(), + jsonData3, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + `map my/topic/path/original_cast + to views/the_flintstones + insert my/topic/path/additional_cast/1 at /- + insert my/topic/path/additional_cast/2 at /-` + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_insert_transformations[] + /// tag::log + await expectJsonTopicToHaveValue('views/the_flintstones', [ + 'Fred Flintstone', + 'Wilma Flintstone', + 'Barney Rubble', + 'Betty Rubble', + 'Pebbles Flintstone', + 'Bamm-Bamm Rubble' + ]); + + await check.done(); + /// end::log +} diff --git a/ts/wrangling/topic-views/dsl/options-delay.ts b/ts/wrangling/topic-views/dsl/options-delay.ts new file mode 100644 index 00000000..0b8e91ca --- /dev/null +++ b/ts/wrangling/topic-views/dsl/options-delay.ts @@ -0,0 +1,89 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester } from '../../../../../test/util'; +/// end::log + +export async function topicViewsDslOptionsDelay(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ 'Subscribed to my/topic/path' ] + ]); + /// end::log + /// tag::topic_views_dsl_options_delay[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.INT64); + + await session.topicUpdate.set( + 'my/topic/path', + datatypes.int64(), + 0, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(datatypes.int64()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${oldValue} to ${newValue}`); + /// tag::log + if (topic !== 'my/topic/path') { + check.log(`${topic} changed from ${oldValue}`); + } + /// end::log + } + }); + + await session.select('?.*//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + 'map my/topic/path to views/ delay by 5 seconds' + ); + console.log(`Topic View ${topicView.name} has been created.`); + + for (let i = 0; i < 15; i++) { + await session.topicUpdate.set( + 'my/topic/path', + datatypes.int64(), + Date.now(), + { specification: specification } + ); + await new Promise((resolve) => setTimeout(resolve, 1000)); + } + + await session.closeSession(); + /// end::topic_views_dsl_options_delay[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/wrangling/topic-views/dsl/options-preserve-topics.ts b/ts/wrangling/topic-views/dsl/options-preserve-topics.ts new file mode 100644 index 00000000..c3eeed77 --- /dev/null +++ b/ts/wrangling/topic-views/dsl/options-preserve-topics.ts @@ -0,0 +1,140 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue, expectTopicCounts, PartiallyOrderedCheckpointTester } from '../../../../../test/util'; +/// end::log + +export async function topicViewsDslOptionsPreserveTopics(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ + 'Subscribed to views/preserved/Fred Flintstone', + 'Subscribed to views/not_preserved/Fred Flintstone' + ], + [ + 'Subscribed to views/preserved/Wilma Flintstone', + 'Subscribed to views/not_preserved/Wilma Flintstone' + ], + [ + 'Subscribed to views/preserved/Pebbles Flintstone', + 'Subscribed to views/not_preserved/Pebbles Flintstone' + ] + ]); + /// end::log + /// tag::topic_views_dsl_options_preserve_topics[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + + const jsonData1 = datatypes.json().from({ + name: 'Fred Flintstone' + }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData1, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView1 = await session.topicViews.createTopicView( + 'topic_view_1', + 'map my/topic/path to views/preserved/ preserve topics' + ); + console.log(`Topic View ${topicView1.name} has been created.`); + const topicView2 = await session.topicViews.createTopicView( + 'topic_view_2', + 'map my/topic/path to views/not_preserved/' + ); + console.log(`Topic View ${topicView2.name} has been created.`); + + await new Promise(resolve => setTimeout(resolve, 2000)); + + const jsonData2 = datatypes.json().from({ + name: 'Wilma Flintstone' + }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData2, + ); + + await new Promise(resolve => setTimeout(resolve, 2000)); + + const jsonData3 = datatypes.json().from({ + name: 'Pebbles Flintstone' + }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData3, + ); + + await new Promise(resolve => setTimeout(resolve, 2000)); + + /// tag::log + await expectTopicCounts({ + 'my/topic/path': 1, + 'views/preserved/Fred Flintstone': 1, + 'views/preserved/Wilma Flintstone': 1, + 'views/preserved/Pebbles Flintstone': 1, + 'views/not_preserved/Fred Flintstone': 0, + 'views/not_preserved/Wilma Flintstone': 0, + 'views/not_preserved/Pebbles Flintstone': 1 + }); + + await expectJsonTopicToHaveValue('views/preserved/Fred Flintstone', { + name: 'Fred Flintstone' + }); + await expectJsonTopicToHaveValue('views/preserved/Wilma Flintstone', { + name: 'Wilma Flintstone' + }); + await expectJsonTopicToHaveValue('views/preserved/Pebbles Flintstone', { + name: 'Pebbles Flintstone' + }); + await expectJsonTopicToHaveValue('views/not_preserved/Pebbles Flintstone', { + name: 'Pebbles Flintstone' + }); + /// end::log + + await session.topics.remove('my/topic/path'); + + await session.closeSession(); + /// end::topic_views_dsl_options_preserve_topics[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/wrangling/topic-views/dsl/options-separator.ts b/ts/wrangling/topic-views/dsl/options-separator.ts new file mode 100644 index 00000000..c978625b --- /dev/null +++ b/ts/wrangling/topic-views/dsl/options-separator.ts @@ -0,0 +1,105 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } from '../../../../../test/util'; +/// end::log + +export async function topicViewsDslOptionsSeparator(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/Fred_Flintstone', + 'Subscribed to views/Wilma_Flintstone', + 'Subscribed to views/Pebbles_Flintstone', + ]]); + /// end::log + /// tag::topic_views_dsl_options_separator[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + + const jsonData1 = datatypes.json().from({ + name: 'Fred/Flintstone' + }); + await session.topicUpdate.set( + 'my/topic/path/1', + datatypes.json(), + jsonData1, + { specification: specification } + ); + + const jsonData2 = datatypes.json().from({ + name: 'Wilma/Flintstone' + }); + await session.topicUpdate.set( + 'my/topic/path/2', + datatypes.json(), + jsonData2, + { specification: specification } + ); + + const jsonData3 = datatypes.json().from({ + name: 'Pebbles/Flintstone' + }); + await session.topicUpdate.set( + 'my/topic/path/3', + datatypes.json(), + jsonData3, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + `map ?my/topic/path// to views/ separator '_'` + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_options_separator[] + /// tag::log + await expectJsonTopicToHaveValue('views/Fred_Flintstone', { + name: 'Fred/Flintstone' + }); + await expectJsonTopicToHaveValue('views/Wilma_Flintstone', { + name: 'Wilma/Flintstone' + }); + await expectJsonTopicToHaveValue('views/Pebbles_Flintstone', { + name: 'Pebbles/Flintstone' + }); + + await check.done(); + /// end::log +} diff --git a/ts/wrangling/topic-views/dsl/options-throttle.ts b/ts/wrangling/topic-views/dsl/options-throttle.ts new file mode 100644 index 00000000..057112bd --- /dev/null +++ b/ts/wrangling/topic-views/dsl/options-throttle.ts @@ -0,0 +1,93 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { PartiallyOrderedCheckpointTester } from '../../../../../test/util'; +/// end::log + +export async function topicViewsDslOptionsThrottle(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + [ 'Subscribed to views/my/topic/path', 'Subscribed to my/topic/path' ], + [ + 'views/my/topic/path changed from undefined', + 'views/my/topic/path changed from 0' + ], + ]); + /// end::log + /// tag::topic_views_dsl_options_throttle[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.INT64); + + await session.topicUpdate.set( + 'my/topic/path', + datatypes.int64(), + 0, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(datatypes.int64()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${oldValue} to ${newValue}`); + /// tag::log + if (topic !== 'my/topic/path') { + check.log(`${topic} changed from ${oldValue}`); + } + /// end::log + } + }); + + await session.select('?.*//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + 'map my/topic/path to views/ throttle to 1 update every 3 seconds' + ); + console.log(`Topic View ${topicView.name} has been created.`); + + for (let i = 0; i < 15; i++) { + await session.topicUpdate.set( + 'my/topic/path', + datatypes.int64(), + Date.now(), + { specification: specification } + ); + await new Promise((resolve) => setTimeout(resolve, 1000)); + } + + await session.closeSession(); + /// end::topic_views_dsl_options_throttle[] + /// tag::log + await check.done(); + /// end::log +} diff --git a/ts/wrangling/topic-views/dsl/options-topic-property-mapping.ts b/ts/wrangling/topic-views/dsl/options-topic-property-mapping.ts new file mode 100644 index 00000000..2d88eea8 --- /dev/null +++ b/ts/wrangling/topic-views/dsl/options-topic-property-mapping.ts @@ -0,0 +1,85 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { expectTopicToHaveProperties, PartiallyOrderedCheckpointTester } from '../../../../../test/util'; +/// end::log + +export async function topicViewsDslOptionsTopicPropertyMapping(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/my/topic/path' + ]]); + /// end::log + /// tag::topic_views_dsl_options_topic_property_mapping[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + + const jsonData = datatypes.json().from([ + 'Fred Flintstone', + 'Wilma Flintstone', + 'Barney Rubble', + 'Betty Rubble' + ]); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + `map ?my/topic/path// to views/ + with properties 'CONFLATION':'off', 'COMPRESSION':'false', 'DONT_RETAIN_VALUE':'true'` + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_options_topic_property_mapping[] + /// tag::log + await expectTopicToHaveProperties('views/my/topic/path', { + CONFLATION: 'off', + COMPRESSION: 'false', + DONT_RETAIN_VALUE: 'true', + PERSISTENT: 'false', + _VIEW: 'topic_view_1' + }); + + await check.done(); + /// end::log +} diff --git a/ts/wrangling/topic-views/dsl/options-topic-type.ts b/ts/wrangling/topic-views/dsl/options-topic-type.ts new file mode 100644 index 00000000..1eacf0cd --- /dev/null +++ b/ts/wrangling/topic-views/dsl/options-topic-type.ts @@ -0,0 +1,68 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; + +export async function topicViewsDslOptionsTopicType(): Promise { + /// tag::topic_views_dsl_options_topic_type[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.INT64); + + await session.topicUpdate.set( + 'my/topic/path', + datatypes.int64(), + 0, + { specification: specification } + ); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + 'map my/topic/path to views/archive/ type TIME_SERIES' + ); + console.log(`Topic View ${topicView.name} has been created.`); + + for (let i = 0; i < 15; i++) { + await session.topicUpdate.set( + 'my/topic/path', + datatypes.int64(), + Date.now(), + { specification: specification } + ); + await new Promise((resolve) => setTimeout(resolve, 1000)); + } + /// tag::log + await new Promise((resolve) => setTimeout(resolve, 2000)); + /// end::log + + const queryResult = await session.timeseries.rangeQuery() + .fromStart() + .selectFrom('views/archive/my/topic/path'); + for (const event of queryResult.events) { + console.log(`${event.sequence} (${event.timestamp}): ${event.value}`); + } + /// tag::log + expect(queryResult.events.length).toBe(10); + /// end::log + + await session.closeSession(); + /// end::topic_views_dsl_options_topic_type[] +} diff --git a/ts/wrangling/topic-views/dsl/options-topic-value.ts b/ts/wrangling/topic-views/dsl/options-topic-value.ts new file mode 100644 index 00000000..f82a5744 --- /dev/null +++ b/ts/wrangling/topic-views/dsl/options-topic-value.ts @@ -0,0 +1,86 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } from '../../../../../test/util'; +/// end::log + +export async function topicViewsDslOptionsTopicValue(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/1234' + ]]); + /// end::log + /// tag::topic_views_dsl_options_topic_value[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + + const jsonData = datatypes.json().from({ + account: '1234', + balance: { + amount: 12.57, + currency: 'USD' + } + }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => { + console.log(`Unsubscribed from ${topic}: ${reason}`); + }, + value : (topic, spec, newValue, oldValue) => { + console.log(`${topic} changed from ${oldValue.get()} to ${newValue.get()}`); + } + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + 'map my/topic/path to views/ as ' + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_options_topic_value[] + /// tag::log + await expectJsonTopicToHaveValue('views/1234', { + amount: 12.57, + currency: 'USD' + }); + + await check.done(); + /// end::log +} diff --git a/ts/wrangling/topic-views/dsl/patch-transformations-add.ts b/ts/wrangling/topic-views/dsl/patch-transformations-add.ts new file mode 100644 index 00000000..06198fc3 --- /dev/null +++ b/ts/wrangling/topic-views/dsl/patch-transformations-add.ts @@ -0,0 +1,87 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } from '../../../../../test/util'; +/// end::log + + +export async function topicViewsDslPatchTransformationsAdd(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/my/topic/path' + ]]); + /// end::log + /// tag::topic_views_dsl_patch_transformations_add[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + + const jsonData = datatypes.json().from({ + Fred: 'Flintstone', + Barney: 'Rubble' + }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + `map ?my/topic/path// to views/ patch '[ + { + "op": "add", + "path": "/George", + "value": "Jetson" + } + ]'` + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_patch_transformations_add[] + /// tag::log + await expectJsonTopicToHaveValue('views/my/topic/path', { + Fred: 'Flintstone', + Barney: 'Rubble', + George: 'Jetson' + }); + + await check.done(); + /// end:log +} diff --git a/ts/wrangling/topic-views/dsl/patch-transformations-copy.ts b/ts/wrangling/topic-views/dsl/patch-transformations-copy.ts new file mode 100644 index 00000000..c597d2aa --- /dev/null +++ b/ts/wrangling/topic-views/dsl/patch-transformations-copy.ts @@ -0,0 +1,96 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } from '../../../../../test/util'; +/// end::log + +export async function topicViewsDslPatchTransformationsCopy(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/my/topic/path' + ]]); + /// end::log + /// tag::topic_views_dsl_patch_transformations_copy[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + + const jsonData = datatypes.json().from({ + 'Meet the Flintstones': { + Fred: 'Flintstone', + Barne: 'Rubble' + }, + 'The Jetsons': { + George: 'Jetson' + } + }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + `map ?my/topic/path// to views/ patch '[ + { + "op": "copy", + "from": "/Meet the Flintstones/Fred", + "path": "/The Jetsons/Fred" + } + ]'` + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_patch_transformations_copy[] + /// tag::log + await expectJsonTopicToHaveValue('views/my/topic/path', { + 'Meet the Flintstones': { + Fred: 'Flintstone', + Barne: 'Rubble' + }, + 'The Jetsons': { + Fred: 'Flintstone', + George: 'Jetson' + } + }); + + await check.done(); + /// end::log +} diff --git a/ts/wrangling/topic-views/dsl/patch-transformations-move.ts b/ts/wrangling/topic-views/dsl/patch-transformations-move.ts new file mode 100644 index 00000000..943d8643 --- /dev/null +++ b/ts/wrangling/topic-views/dsl/patch-transformations-move.ts @@ -0,0 +1,97 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } from '../../../../../test/util'; +/// end::log + +export async function topicViewsDslPatchTransformationsMove(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/my/topic/path' + ]]); + /// end::log + /// tag::topic_views_dsl_patch_transformations_move[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + + const jsonData = datatypes.json().from({ + Fred: 'Flintstone', + Barney: 'Rubble', + George: 'Jetson' + }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + `map ?my/topic/path// to views/ patch '[ + { + "op": "move", + "from": "/Fred", + "path": "/Meet The Flintstones~1Fred" + }, + { + "op": "move", + "from": "/Barney", + "path": "/Meet The Flintstones~1Barney" + }, + { + "op": "move", + "from": "/George", + "path": "/The Jetsons~1George" + } + ]'` + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_patch_transformations_move[] + /// tag::log + await expectJsonTopicToHaveValue('views/my/topic/path', { + "Meet The Flintstones/Fred": 'Flintstone', + "Meet The Flintstones/Barney": 'Rubble', + "The Jetsons/George": 'Jetson' + }); + + await check.done(); + /// end::log +} diff --git a/ts/wrangling/topic-views/dsl/patch-transformations-remove.ts b/ts/wrangling/topic-views/dsl/patch-transformations-remove.ts new file mode 100644 index 00000000..4bac950a --- /dev/null +++ b/ts/wrangling/topic-views/dsl/patch-transformations-remove.ts @@ -0,0 +1,85 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } from '../../../../../test/util'; +/// end::log + +export async function topicViewsDslPatchTransformationsRemove(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/my/topic/path' + ]]); + /// end::log + /// tag::topic_views_dsl_patch_transformations_remove[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + + const jsonData = datatypes.json().from({ + Fred: 'Flintstone', + Barney: 'Rubble', + George: 'Jetson' + }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + `map ?my/topic/path// to views/ patch '[ + { + "op": "remove", + "path": "/George" + } + ]'` + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_patch_transformations_remove[] + /// tag::log + await expectJsonTopicToHaveValue('views/my/topic/path', { + Fred: 'Flintstone', + Barney: 'Rubble' + }); + + await check.done(); + /// end::log +} diff --git a/ts/wrangling/topic-views/dsl/patch-transformations-replace.ts b/ts/wrangling/topic-views/dsl/patch-transformations-replace.ts new file mode 100644 index 00000000..5a975bd4 --- /dev/null +++ b/ts/wrangling/topic-views/dsl/patch-transformations-replace.ts @@ -0,0 +1,87 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } from '../../../../../test/util'; +/// end::log + +export async function topicViewsDslPatchTransformationsReplace(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/my/topic/path' + ]]); + /// end::log + /// tag::topic_views_dsl_patch_transformations_replace[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + + const jsonData = datatypes.json().from({ + Fred: 'Flintstone', + Barney: 'Rubble', + George: 'Jetson' + }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + `map ?my/topic/path// to views/ patch '[ + { + "op": "replace", + "path": "/George", + "value": "Bedrock" + } + ]'` + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_patch_transformations_replace[] + /// tag::log + await expectJsonTopicToHaveValue('views/my/topic/path', { + Fred: 'Flintstone', + Barney: 'Rubble', + George: 'Bedrock' + }); + + await check.done(); + /// end::log +} diff --git a/ts/wrangling/topic-views/dsl/patch-transformations-test.ts b/ts/wrangling/topic-views/dsl/patch-transformations-test.ts new file mode 100644 index 00000000..58aac49f --- /dev/null +++ b/ts/wrangling/topic-views/dsl/patch-transformations-test.ts @@ -0,0 +1,87 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } from '../../../../../test/util'; +/// end::log + +export async function topicViewsDslPatchTransformationsTest(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/my/topic/path' + ]]); + /// end::log + /// tag::topic_views_dsl_patch_transformations_test[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + + const jsonData = datatypes.json().from({ + Fred: 'Flintstone', + Barney: 'Rubble', + George: 'Jetson' + }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + `map ?my/topic/path// to views/ patch '[ + { + "op": "test", + "path": "/Fred", + "value": "Flintstone" + } + ]'` + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_patch_transformations_test[] + /// tag::log + await expectJsonTopicToHaveValue('views/my/topic/path', { + Fred: 'Flintstone', + Barney: 'Rubble', + George: 'Jetson' + }); + + await check.done(); + /// end::log +} diff --git a/ts/wrangling/topic-views/dsl/process-transformations-set-continue.ts b/ts/wrangling/topic-views/dsl/process-transformations-set-continue.ts new file mode 100644 index 00000000..1f823e38 --- /dev/null +++ b/ts/wrangling/topic-views/dsl/process-transformations-set-continue.ts @@ -0,0 +1,99 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue, expectTopicCounts, PartiallyOrderedCheckpointTester } from '../../../../../test/util'; +/// end::log + +export async function topicViewsDslProcessTransformationsContinue(): Promise { + /// tag::log + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/2' + ]]); + /// end::log + /// tag::topic_views_dsl_process_transformations_continue[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + + const jsonData1 = datatypes.json().from({ + name: 'APPL', + quantity: 100, + price_per_share: 12.34 + }); + await session.topicUpdate.set( + 'my/topic/path/1', + datatypes.json(), + jsonData1, + { specification: specification } + ); + const jsonData2 = datatypes.json().from({ + name: 'AMZN', + quantity: 256, + price_per_share: 87.65 + }); + await session.topicUpdate.set( + 'my/topic/path/2', + datatypes.json(), + jsonData2, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + `map ?my/topic/path// to views/ + process + { + if '/price_per_share > 20' continue + }` + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_process_transformations_continue[] + /// tag::log + await expectJsonTopicToHaveValue('views/2', { + name: 'AMZN', + quantity: 256, + price_per_share: 87.65 + }); + + await expectTopicCounts({ 'views/1': 0 }); + + await check.done(); + /// end::log +} diff --git a/ts/wrangling/topic-views/dsl/process-transformations-set-remove.ts b/ts/wrangling/topic-views/dsl/process-transformations-set-remove.ts new file mode 100644 index 00000000..d7cb5285 --- /dev/null +++ b/ts/wrangling/topic-views/dsl/process-transformations-set-remove.ts @@ -0,0 +1,102 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } from '../../../../../test/util'; +/// end::log + +export async function topicViewsDslProcessTransformationsRemove(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/1', + 'Subscribed to views/2' + ]]); + /// end::log + /// tag::topic_views_dsl_process_transformations_remove[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + + const jsonData1 = datatypes.json().from({ + name: 'APPL', + quantity: 100, + price_per_share: 12.34 + }); + await session.topicUpdate.set( + 'my/topic/path/1', + datatypes.json(), + jsonData1, + { specification: specification } + ); + const jsonData2 = datatypes.json().from({ + name: 'AMZN', + quantity: 256, + price_per_share: 87.65 + }); + await session.topicUpdate.set( + 'my/topic/path/2', + datatypes.json(), + jsonData2, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + `map ?my/topic/path// to views/ + process + { + set(/total, calc '/quantity * /price_per_share'); + remove(/quantity); + remove(/price_per_share) + }` + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_process_transformations_remove[] + /// tag::log + await expectJsonTopicToHaveValue('views/1', { + name: 'APPL', + total: 1234 + }); + await expectJsonTopicToHaveValue('views/2', { + name: 'AMZN', + total: 256*87.65 + }); + + await check.done(); + /// end::log +} diff --git a/ts/wrangling/topic-views/dsl/process-transformations-set.ts b/ts/wrangling/topic-views/dsl/process-transformations-set.ts new file mode 100644 index 00000000..7fe1961a --- /dev/null +++ b/ts/wrangling/topic-views/dsl/process-transformations-set.ts @@ -0,0 +1,120 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } from '../../../../../test/util'; +/// end::log + +export async function topicViewsDslProcessTransformationsSet(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([[ + 'Subscribed to views/1', + 'Subscribed to views/2' + ]]); + /// end::log + /// tag::topic_views_dsl_process_transformations_set[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + + const jsonData1 = datatypes.json().from({ + account: '1234', + balance: { + amount: 12.57, + currency: 'USD' + } + }); + await session.topicUpdate.set( + 'my/topic/path/1', + datatypes.json(), + jsonData1, + { specification: specification } + ); + + const jsonData2 = datatypes.json().from({ + account: '5678', + balance: { + amount: 98.76, + currency: 'USD' + } + }); + await session.topicUpdate.set( + 'my/topic/path/2', + datatypes.json(), + jsonData2, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + `map ?my/topic/path// to views/ + process { + if '/balance/amount > 20' + set(/tier, 1) + else + set(/tier, 2) + } + process { + set(/balance/amount_in_cents, calc '/balance/amount * 100') + }` + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_process_transformations_set[] + /// tag::log + await expectJsonTopicToHaveValue('views/1', { + account: '1234', + balance: { + amount: 12.57, + amount_in_cents: 1257, + currency: 'USD' + }, + tier: 2 + }); + await expectJsonTopicToHaveValue('views/2', { + account: '5678', + balance: { + amount: 98.76, + amount_in_cents: 9876, + currency: 'USD' + }, + tier: 1 + }); + + await check.done(); + /// end::log +} diff --git a/ts/wrangling/topic-views/dsl/remote-topic-view.ts b/ts/wrangling/topic-views/dsl/remote-topic-view.ts new file mode 100644 index 00000000..c5ac4968 --- /dev/null +++ b/ts/wrangling/topic-views/dsl/remote-topic-view.ts @@ -0,0 +1,48 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, ConnectionOption, newRemoteServerBuilder } from 'diffusion'; + +export async function topicViewsDslRemoteTopicView(): Promise { + /// tag::topic_views_dsl_remote_topic_view[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const definition = newRemoteServerBuilder() + .principal('admin') + .credentials('password') + .connectionOptions({ + [ConnectionOption.RECONNECTION_TIMEOUT]: '120000', + [ConnectionOption.MAXIMUM_QUEUE_SIZE]: '1000', + [ConnectionOption.CONNECTION_TIMEOUT]: '15000' + }) + .create('Remote Server 1', 'ws://new.server.url.com'); + await session.remoteServers.createRemoteServer(definition); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + 'map my/topic/path from \'Remote Server 1\' to views/remote/' + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.remoteServers.removeRemoteServer('Remote Server 1'); + await session.closeSession(); + /// end::topic_views_dsl_remote_topic_view[] +} diff --git a/ts/wrangling/topic-views/dsl/scalar-directive.ts b/ts/wrangling/topic-views/dsl/scalar-directive.ts new file mode 100644 index 00000000..d627a6ad --- /dev/null +++ b/ts/wrangling/topic-views/dsl/scalar-directive.ts @@ -0,0 +1,85 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue, PartiallyOrderedCheckpointTester } from '../../../../../test/util'; +/// end::log + +export async function topicViewsDslScalarDirective(): Promise { + /// tag::log + const check = new PartiallyOrderedCheckpointTester([ + ['Subscribed to views/currency/USD/account/1234'] + ]); + /// end::log + /// tag::topic_views_dsl_scalar_directive[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + const jsonData = datatypes.json().from({ + account: '1234', + balance: { + amount: 12.57, + currency: 'USD' + } + }); + await session.topicUpdate.set( + 'my/topic/path', + datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + /// tag::log + check.log(`Subscribed to ${topic}`); + /// end::log + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView = await session.topicViews.createTopicView( + 'topic_view_1', + 'map my/topic/path to views/currency//account/' + ); + console.log(`Topic View ${topicView.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_scalar_directive[] + /// tag::log + const expectedValue = { + account: '1234', + balance: { + amount: 12.57, + currency: 'USD' + } + }; + await expectJsonTopicToHaveValue('views/currency/USD/account/1234', expectedValue); + + await check.done(); + /// end::log +} diff --git a/ts/wrangling/topic-views/dsl/source-path-directive.ts b/ts/wrangling/topic-views/dsl/source-path-directive.ts new file mode 100644 index 00000000..356ba558 --- /dev/null +++ b/ts/wrangling/topic-views/dsl/source-path-directive.ts @@ -0,0 +1,87 @@ +/******************************************************************************* + * Copyright (C) 2024 Diffusion Data Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +import { connect, datatypes, topics } from 'diffusion'; +/// tag::log +import { expectJsonTopicToHaveValue } from '../../../../../test/util'; +/// end::log + +export async function topicViewsDslSourcePathDirective(): Promise { + /// tag::topic_views_dsl_source_path_directive[] + // Connect to the server. + const session = await connect({ + host: 'localhost', + port: 8080, + principal: 'admin', + credentials: 'password' + }); + + const specification = new topics.TopicSpecification(topics.TopicType.JSON); + const jsonData = datatypes.json().from({ + account: '1234', + balance: { + amount: 12.57, + currency: 'USD' + } + }); + await session.topicUpdate.set( + 'a/b/c/d/e/f/g', + datatypes.json(), + jsonData, + { specification: specification } + ); + + const valueStream = session.addFallbackStream(datatypes.json()); + valueStream.on({ + subscribe : (topic, specification) => { + console.log(`Subscribed to ${topic}`); + }, + unsubscribe : (topic, specification, reason) => {}, + value : (topic, spec, newValue, oldValue) => {} + }); + + await session.select('?views//'); + + const topicView1 = await session.topicViews.createTopicView( + 'topic_view_1', + 'map a/b/c/d/e/f/g to views/' + ); + console.log(`Topic View ${topicView1.name} has been created.`); + const topicView2 = await session.topicViews.createTopicView( + 'topic_view_2', + 'map a/b/c/d/e/f/g to views/' + ); + console.log(`Topic View ${topicView2.name} has been created.`); + const topicView3 = await session.topicViews.createTopicView( + 'topic_view_3', + 'map a/b/c/d/e/f/g to views/' + ); + console.log(`Topic View ${topicView3.name} has been created.`); + + await session.closeSession(); + /// end::topic_views_dsl_source_path_directive[] + /// tag::log + const expectedValue = { + account: '1234', + balance: { + amount: 12.57, + currency: 'USD' + } + }; + await expectJsonTopicToHaveValue('views/a/b/c/d/e/f/g', expectedValue); + await expectJsonTopicToHaveValue('views/c/d/e/f/g', expectedValue); + await expectJsonTopicToHaveValue('views/d/e/f/g', expectedValue); + /// end::log +}